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
1cc2d1f3bc8805f35de8de3b3e0934a5a507e6af
Ruby
skyraseal/cp-learn-to-program
/ch7/leapyears.rb
UTF-8
738
4.0625
4
[]
no_license
### Receive input ### while true puts "Welcome to the leap year calculator. Please input the starting year:" first_year = gets.chomp.to_i puts "Please input the ending year:" last_year = gets.chomp.to_i if last_year >= first_year break else puts "Invalid entries: Your ending year must be later than your starting year. Please re-try." puts "-------" end end leap_array = [] ### Identify start year ### if first_year%4 == 0 start_year = first_year else start_year = first_year + (4 - first_year%4) end until start_year > last_year if start_year % 100 == 0 else leap_array.push start_year end start_year += 4 end puts "" puts "Here are the leap years you requested!" print leap_array puts ""
true
6d02666b2bdffa0eefe063b77204614fecf41bab
Ruby
matbat99/medium_scraper_reader
/post.rb
UTF-8
262
2.828125
3
[]
no_license
class Post attr_reader :path, :author, :title, :text_body, :read attr_writer :read def initialize(path, author, title, text_body, read = false) @path = path @author = author @title = title @text_body = text_body @read = read end end
true
3b501ea245403a6d9639a3a5965eefe704dcc960
Ruby
alphagov/content-publisher
/app/services/withdraw_document_service.rb
UTF-8
1,745
2.578125
3
[ "MIT", "LicenseRef-scancode-proprietary-license" ]
permissive
class WithdrawDocumentService include Callable def initialize(edition, user, public_explanation:) @edition = edition @public_explanation = public_explanation @user = user end def call edition.document.lock! check_withdrawable withdrawal = build_withdrawal update_edition(withdrawal) unpublish_edition end private attr_reader :edition, :public_explanation, :user def unpublish_edition GdsApi.publishing_api.unpublish( edition.content_id, type: "withdrawal", explanation: format_govspeak(public_explanation, edition), locale: edition.locale, unpublished_at: edition.status.details.withdrawn_at, ) end def update_edition(withdrawal) AssignEditionStatusService.call(edition, user:, state: :withdrawn, status_details: withdrawal) edition.save! end def check_withdrawable document = edition.document if edition != document.live_edition raise "attempted to withdraw an edition other than the live edition" end if document.current_edition != document.live_edition raise "Publishing API does not support unpublishing while there is a draft" end end def build_withdrawal if edition.withdrawn? withdrawal = edition.status.details.dup withdrawal.tap do |w| w.assign_attributes(public_explanation:) end else Withdrawal.new(public_explanation:, published_status: edition.status, withdrawn_at: Time.zone.now) end end def format_govspeak(text, edition) GovspeakDocument.new(text, edition).payload_html end end
true
1452c7cab641dce80c912c0d5b07195df605071d
Ruby
zhchsf/jd_pay
/lib/jd_pay/util/des3.rb
UTF-8
1,703
2.921875
3
[ "MIT" ]
permissive
module JdPay module Util # 京东支付 des3 加解密,掺杂了京东自定义的一些位转移逻辑 class Des3 def self.encrypt(source, base64_key) key = Base64.decode64(base64_key) transformed_source = transform_source(source.bytes) des = OpenSSL::Cipher::Cipher.new('des-ede3') des.encrypt des.key = key des.padding = 0 res = des.update(transformed_source) + des.final res.unpack("H*").first end def self.decrypt(source, base64_key) key = Base64.decode64(base64_key) b2 = source.chars.each_slice(2).map{|x| x.join().to_i(16) }.map(&:chr).join des = OpenSSL::Cipher::Cipher.new('des-ede3') des.decrypt des.key = key des.padding = 0 res = des.update(b2) + des.final decrypt_bytes = res.bytes bytes_length = bytes_to_int(decrypt_bytes[0, 4]) decrypt_bytes[4, bytes_length].map(&:chr).join end # 对要加密的字符串按照京东的规则处理 def self.transform_source(source_bytes) source_len = source_bytes.length x = (source_len + 4) % 8 y = x == 0 ? 0 : 8 - x result_bytes = [] 0.upto(3).each do |index| result_bytes << ((source_len >> (3 - index) * 8) & 0xFF) end result_bytes += source_bytes y.times { result_bytes << 0 } result_bytes.map(&:chr).join end # 解密 def self.bytes_to_int(bytes) total = 0 bytes.each_with_index do |value, index| shift = (3 - index) * 8 total += (value & 0xFF) << shift end total end end end end
true
7e34abe67940190d31931e49931b862cc9d6e516
Ruby
codystair/ruby_small_problems
/Easy_8/03.rb
UTF-8
845
4.34375
4
[]
no_license
=begin input: string output: array rules: - will return array of all substrings in array - substrings will always begin with first character of string - subs should be in order from shortest to longest examples: substrings_at_start('abc') == ['a', 'ab', 'abc'] substrings_at_start('a') == ['a'] substrings_at_start('xyzzy') == ['x', 'xy', 'xyz', 'xyzz', 'xyzzy'] algorithm: - set subs to empty array - set i to 0 - while i < size of string: - slice string from index zero to current i - push sliced string to subs - increment i by 1 - return subs =end def substrings_at_start(str) subs = [] i = 0 while i < str.size subs << str.slice(0..i) i += 1 end subs end p substrings_at_start('abc') == ['a', 'ab', 'abc'] p substrings_at_start('a') == ['a'] p substrings_at_start('xyzzy') == ['x', 'xy', 'xyz', 'xyzz', 'xyzzy']
true
2c2ba8c3f4a57d38ae0ee324c070911ac5e274d2
Ruby
ftt9282/chess
/lib/chess/queen.rb
UTF-8
552
3.625
4
[]
no_license
module Chess class Queen < Piece attr_reader :color, :symbol attr_accessor :position # grab the attributes from Piece class and assign symbol def initialize(color, position) super @color == "white" ? @symbol = "♕" : @symbol = "♛" end # lists all moves and then returns the ones that won't go off the board def possible_moves bishop = Bishop.new(@color, @position) rook = Rook.new(@color, @position) queen = bishop.possible_moves + rook.possible_moves queen end end end
true
fd07e784ddbc176a412f675449ff0e5fcef16f91
Ruby
bmitchellblurb/flux-hue
/lib/flux_hue/discovery/ssdp.rb
UTF-8
1,459
2.515625
3
[ "MIT" ]
permissive
module FluxHue module Discovery # Helpers for SSDP discovery of bridges. module SSDP def ssdp_scan! setup_ssdp_lib! Playful::SSDP .search("IpBridge") .select { |resp| ssdp_response?(resp) } .map { |resp| ssdp_extract(resp) } end # Loads the Playful library for SSDP late to avoid slowing down the CLI # needlessly when SSDP isn't needed. def setup_ssdp_lib! require "playful/ssdp" unless defined?(Playful) Playful.log = false # Playful is super verbose end # Ensure we're *only* getting responses from a Philips Hue bridge. The # Hue Bridge tends to be obnoxious and announce itself on *any* SSDP # SSDP request, so we assume that we may encounter other obnoxious gear # as well... def ssdp_response?(resp) (resp[:server] || "") .split(/[,\s]+/) .find { |token| token =~ %r{\AIpBridge/\d+(\.\d+)*\z} } end def ssdp_extract(resp) { "id" => ssdp_usn_to_id(resp[:usn]), "name" => resp[:st], "ipaddress" => URI.parse(resp[:location]).host, } end # TODO: With all the hassle around ID and the fact that I'm essentially # TODO: coercing it down to just MAC address.... Just use the damned IP # TODO: or MAC! def ssdp_usn_to_id(usn); usn.split(/:/, 3)[1].split(/-/).last; end end end end
true
730f65e7a373dd8fd4d09d5623118065a2f2a7d1
Ruby
mkrahu/launchschool
/exercises/small_problems/vers3/easy_2/sum_prod_consec_integers.rb
UTF-8
674
4.40625
4
[]
no_license
# sum_prod_consec_integers.rb # Launch School 101-109 Small Problems Exercises (3rd time through) print 'Please enter an integer greater than 0: ' num = $stdin.gets.chomp.to_i loop do print "Enter 's' to compute the sum, 'p' to compute the product: " operation = $stdin.gets.chomp if operation.downcase == 's' sum = 1.upto(num).inject(0) { |sum, num| sum + num } puts "The sum of integers between 1 and #{num} is #{sum}" break elsif operation.downcase == 'p' product = 1.upto(num).inject(1) { |product, num| product * num } puts "The product of integers between 1 and #{num} is #{product}" break end puts "Please enter 's' or 'p'" end
true
7bed3666621233d6c78263b9bbbd3fb51d9a610b
Ruby
JacobNinja/codeminer
/test/matchers/colon3_assign_matcher.rb
UTF-8
391
2.78125
3
[]
no_license
class Colon3AssignMatcher < Matcher def initialize(colon3_matcher, body_matcher, src) @colon3_matcher = colon3_matcher @body_matcher = body_matcher @src = src end def type :colon3_assign end def assert(exp) assert_equal type, exp.type @colon3_matcher.assert(exp.receiver) @body_matcher.assert(exp.body) assert_equal @src.chomp, exp.src end end
true
70266621e08816e3dcc06b2cdf3bb8e86cf6e63a
Ruby
aarias89/phase-0-tracks
/ruby/puppy_methods.rb
UTF-8
1,444
4.125
4
[]
no_license
class Puppy def fetch(toy) puts "I brought back the #{toy}!" toy end def speak(n) n.times {print "Woof!"} end def roll_over print "*rolls over*" end def dog_years(i) age=9*i p age end def mail_man puts "*chases mailman around the block*" end def initialize puts "Initializing new puppy instance ..." end end marley= Puppy.new marley.fetch("ball") marley.speak(6) marley.roll_over marley.dog_years(9) marley.mail_man class Car def initialize puts "Initializing new car" end def drive(i) puts "You just drive #{i} miles." end def no_gas print "Car is dead, you forgot to check the gas." end end subaru=Car.new subaru.drive(300) subaru.no_gas cars=[] 50.times{cars << Car.new} cars.each{|car| car.drive(200) car.no_gas} # release 0 # Add driver code at the bottom that initializes an instance of Puppy, and verify that your instance can now fetch a ball. Run the file from the command line to check your work. # Add a speak method that takes an integer, and then prints "Woof!" that many times. # Add a roll_over method that just prints "*rolls over*". # Add a dog_years method that takes an integer (of human years) and converts that number to dog years, returning a new integer. # Add one more trick -- whichever one you'd like. # If you haven't already, update your driver code to demonstrate that all of these methods work as expected.
true
56602890f4548e101639bb420a27a193dd4d5d55
Ruby
jan-czekawski/introduction-to-programming-exercises
/regex/quantifiers/ex_4.rb
UTF-8
1,042
3.671875
4
[]
no_license
# Write a regex that matches any line of text that contains nothing but a # URL. For the purposes of this exercise, a URL begins with http:// or https://, # and continues until a whitespace character or end of line is detected. # Test your regex with these strings: # http://launchschool.com/ # https://mail.google.com/mail/u/0/#inbox # htpps://example.com # Go to http://launchschool.com/ # https://user.example.com/test.cgi?a=p&c=0&t=0&g=0 hello # http://launchschool.com/ # There should be 2 matches. # regex = /(cat|cats)$/ # strings = ["wildcat", "catastrophy", "bobcats"] # regex = /^https+\:\/\/.*/ regex = /^https?:\/\/\S*$/ strings = ["http://launchschool.com/", 'https://mail.google.com/mail/u/0/#inbox', "htpps://example.com", "Go to http://launchschool.com/", "https://user.example.com/test.cgi?a=p&c=0&t=0&g=0 hello", " http://launchschool.com/"] strings.each do |word| if word.match(regex) puts "#{word} matches #{regex}" else puts "#{word} does not match #{regex}" end end
true
cb96e2719c5478551aeebe8dcace38bd6febd561
Ruby
Dflexcee/Bubble_sort
/bubble_sort.rb
UTF-8
542
3.453125
3
[]
no_license
def bubble_sort(arr) idx = 0 while idx < arr.length arr.each do |x| a = arr.index(x) y = arr.index(x) + 1 next unless y < arr.length && x > arr[y] arr[a], arr[y] = arr[y], arr[a] end idx += 1 end arr end def bubble_sort_by(arr) loop do flag = false arr.each_with_index do |_val, i| next if i == arr.length - 1 if yield(arr[i], arr[i + 1]).positive? arr[i], arr[i + 1] = arr[i + 1], arr[i] flag = true end end break unless flag end arr end
true
b84aa4c520604380fe3c21c51ae5f6fdd5d25b32
Ruby
bmquinn/riiif
/app/services/riiif/image_magick_info_extractor.rb
UTF-8
366
2.953125
3
[ "Apache-2.0" ]
permissive
module Riiif # Get height and width information using imagemagick to interrogate the file class ImageMagickInfoExtractor def initialize(path) @path = path end def extract height, width = Riiif::CommandRunner.execute("identify -format %hx%w #{@path}").split('x') { height: Integer(height), width: Integer(width) } end end end
true
69fc07fa80708bb7df49ece910a1be7d46c0f281
Ruby
dgarwood/exercism_solutions
/ruby/hamming/hamming.rb
UTF-8
241
2.671875
3
[]
no_license
module Hamming def self.compute(source, diff) raise ArgumentError, "strands not same length" unless source.length == diff.length (0...source.length).count{ |i| source[i] != diff[i] } end end module BookKeeping VERSION = 3 end
true
dc00154a7b425ec1eb5d616ae47e7d6f5a9b3cfc
Ruby
alexappelt/rubybasico
/for.rb
UTF-8
85
3.140625
3
[]
no_license
fruits = ['Maça' , 'Morango' , 'Banana'] for fruit in fruits puts fruit end
true
fb39352b424a5d53b9b8ce17d0cd9ed81ecb545e
Ruby
3scale/apisonator
/lib/3scale/backend/storage_async/client.rb
UTF-8
5,982
2.671875
3
[ "Apache-2.0", "Python-2.0", "Artistic-2.0", "LGPL-2.0-or-later", "MIT", "BSD-3-Clause", "GPL-2.0-or-later", "Ruby", "BSD-2-Clause" ]
permissive
require 'async/io' require 'async/redis/client' module ThreeScale module Backend module StorageAsync # This is a wrapper for the Async-Redis client # (https://github.com/socketry/async-redis). # This class overrides some methods to provide the same interface that # the redis-rb client provides. # This is done to avoid modifying all the model classes which assume that # the Storage instance behaves likes the redis-rb client. class Client include Configurable DEFAULT_HOST = 'localhost'.freeze private_constant :DEFAULT_HOST DEFAULT_PORT = 22121 private_constant :DEFAULT_PORT HOST_PORT_REGEX = /redis:\/\/(.*):(\d+)/ private_constant :HOST_PORT_REGEX class << self attr_writer :instance def instance(reset = false) if reset || @instance.nil? @instance = new( Storage::Helpers.config_with( configuration.redis, options: { default_url: "#{DEFAULT_HOST}:#{DEFAULT_PORT}" } ) ) else @instance end end end def initialize(opts) host, port = opts[:url].match(HOST_PORT_REGEX).captures if opts[:url] host ||= DEFAULT_HOST port ||= DEFAULT_PORT endpoint = Async::IO::Endpoint.tcp(host, port) @redis_async = Async::Redis::Client.new( endpoint, limit: opts[:max_connections] ) @building_pipeline = false end # Now we are going to define the methods to run redis commands # following the interface of the redis-rb lib. # # These are the different cases: # 1) Methods that can be called directly. For example SET: # @redis_async.call('SET', some_key) # 2) Methods that need to be "boolified". These are methods for which # redis-rb returns a boolean, but redis just returns an integer. # For example, Redis returns 0 or 1 for the EXISTS command, but # redis-rb transforms that into a boolean. # 3) There are a few methods that need to be treated differently and # do not fit in any of the previous categories. For example, SSCAN # which accepts a hash of options in redis-rb. # # All of this might be simplified a bit in the future using the # "methods" in async-redis # https://github.com/socketry/async-redis/tree/master/lib/async/redis/methods # but there are some commands missing, so for now, that's not an option. METHODS_TO_BE_CALLED_DIRECTLY = [ :del, :expire, :expireat, :flushdb, :get, :hset, :hmget, :incr, :incrby, :keys, :llen, :lpop, :lpush, :lrange, :ltrim, :mget, :ping, :rpush, :scard, :setex, :smembers, :sunion, :ttl, :zcard, :zrangebyscore, :zremrangebyscore, :zrevrange ].freeze private_constant :METHODS_TO_BE_CALLED_DIRECTLY METHODS_TO_BE_CALLED_DIRECTLY.each do |method| define_method(method) do |*args| @redis_async.call(method, *args.flatten) end end METHODS_TO_BOOLIFY = [ :exists, :sismember, :sadd, :srem, :zadd ].freeze private_constant :METHODS_TO_BOOLIFY METHODS_TO_BOOLIFY.each do |method| define_method(method) do |*args| @redis_async.call(method, *args.flatten) > 0 end end def blpop(*args) call_args = ['BLPOP'] + args # redis-rb accepts a Hash as last arg that can contain :timeout. if call_args.last.is_a? Hash timeout = call_args.pop[:timeout] call_args << timeout end @redis_async.call(*call_args.flatten) end def set(key, val, opts = {}) args = ['SET', key, val] args += ['EX', opts[:ex]] if opts[:ex] args << 'NX' if opts[:nx] @redis_async.call(*args) end def sscan(key, cursor, opts = {}) args = ['SSCAN', key, cursor] args += ['MATCH', opts[:match]] if opts[:match] args += ['COUNT', opts[:count]] if opts[:count] @redis_async.call(*args) end def scan(cursor, opts = {}) args = ['SCAN', cursor] args += ['MATCH', opts[:match]] if opts[:match] args += ['COUNT', opts[:count]] if opts[:count] @redis_async.call(*args) end # This method allows us to send pipelines like this: # storage.pipelined do # storage.get('a') # storage.get('b') # end def pipelined(&block) # This replaces the client with a Pipeline that accumulates the Redis # commands run in a block and sends all of them in a single request. # # There's an important limitation: this assumes that the fiber will # not yield in the block. # When running a nested pipeline, we just need to continue # accumulating commands. if @building_pipeline block.call return end @building_pipeline = true original = @redis_async pipeline = Pipeline.new @redis_async = pipeline begin block.call ensure @redis_async = original @building_pipeline = false end pipeline.run(original) end def close @redis_async.close end end end end end
true
bf03de93951c1d72673ae3d39f9b109fea1ba45a
Ruby
JeremyFSD/Ruby_Programming_Book
/4_flow_control/5_flow_control.rb
UTF-8
320
3.859375
4
[]
no_license
puts "Type a number between 0 and 100" number = gets.chomp.to_i number = case when number > 101 puts "Type a number BETWEEN 100 and 0" when number < -1 puts "Type a number greater than 0" when number < 50 puts "that number is between 0 and 50" else number > 50 puts "that number is bewteen 51 and 100" end
true
294b4c41de2111bd1ebab0639b5db28462599e3c
Ruby
chet-k/AppAcademy-Open-Work
/0-Foundations/07-Class-Monkey-Patching/monkey_patching_project/chet_monkey_patching_project/lib/array.rb
UTF-8
1,410
3.53125
4
[]
no_license
# Monkey-Patch Ruby's existing Array class to add your own custom methods class Array def span return nil if self.length == 0 self.max - self.min end def average return nil if self.length == 0 1.0 * self.sum / self.length end def median sorted_temp = self.sort n = self.length if n == 0 return nil elsif n.even? return 1.0 * (sorted_temp[n/2 - 1] + sorted_temp[n/2]) / 2 else return sorted_temp[n/2] end end def counts hash = Hash.new(0) self.each {|ele| hash[ele] += 1} hash end def my_count(val) val_count = 0 self.each{|ele| val_count += 1 if ele == val} val_count end def my_index(val) self.each_with_index{|ele, i| return i if ele == val} nil end def my_uniq # uniques = [] # ele_counts = self.counts # ele_counts.each {|key, val| uniques << key} # wait a minute... # uniques self.counts.keys # works because Ruby hashes preserve input order end def my_transpose new_arr = Array.new(self.length) { Array.new(self[0].length) } self.each_with_index do |row, m| row.each_with_index do |ele, n| new_arr[n][m] = ele end end new_arr end end
true
266e7d13f636445ff20bc2e4c3fbee29ad9128f7
Ruby
se3000/bter-ruby
/examples/trade.rb
UTF-8
500
2.984375
3
[ "MIT" ]
permissive
require 'bter' bt = Bter::Trade.new #supply your key and secret bt.key = "my key" bt.secret = "my secret" #enable logging , off by default bt.logging :on #your funds puts bt.get_info #your orders puts bt.active_orders #supply an order id and get its status puts bt.order_status(123456) #cancel and order with its id puts bt.cancel_order(123456) #supply the buy and sell methods with a coin pair and an amount puts bt.buy("btc_cny", 50) puts bt.sell("btc_cny", 50) #all methods return a hash
true
15d1f7d2094d18ee9b173aa0d6f9ed6649cf6361
Ruby
jedbr/towers_of_hanoi
/hanoi.rb
UTF-8
2,018
3.484375
3
[]
no_license
require_relative 'hanoi/peg.rb' # Class solving instance of Towers of Hanoi problem for 3 and 4 pegs. class Hanoi include Math attr_reader :pegs, :moves Disk = Struct.new(:size) def initialize(number_of_disks, number_of_pegs) @pegs = [] @number_of_disks = number_of_disks @moves = 0 number_of_pegs.times { |i| @pegs << Peg.new(i + 1) } number_of_disks.times do |i| disk = Disk.new(number_of_disks - i) @pegs.first << disk end end def print_start return unless @verbose puts '----------------------------' puts 'Start' print_current_state end def print_report(move) return unless @verbose puts '----------------------------' puts "Move: #{@moves}" puts "Disk #{move[:item]} moved from peg #{move[:from]} to peg #{move[:to]}" print_current_state end def print_current_state @pegs.each do |p| print "Peg #{p.id} | " disks = p.disks.map(&:size).reverse puts "Disks: #{disks}" end end # Optimal Frame-Stewart recursive algorithm for 4 pegs def solve(verbose = true) @verbose = verbose print_start hanoi4(@number_of_disks, @pegs[0], [@pegs[1], @pegs[2]], @pegs[3]) end def hanoi4(number_of_disks, from, additional_pegs, to) k = number_of_disks - sqrt(2 * number_of_disks + 1).round + 1 hanoi4(k, from, [additional_pegs.first, to], additional_pegs.last) if k > 0 hanoi3(number_of_disks - k, from, additional_pegs.first, to) hanoi4(k, additional_pegs.last, [from, additional_pegs.first], to) if k > 0 end # Classic recursive algorithm for 3 pegs def solve3(verbose = true) @verbose = verbose print_start k = @number_of_disks hanoi3(k, @pegs[0], @pegs[1], @pegs[2]) end def hanoi3(k, from, additional_peg, to) return unless k > 0 hanoi3(k - 1, from, to, additional_peg) to << from.shift @moves += 1 print_report(from: from.id, to: to.id, item: to.first.size) hanoi3(k - 1, additional_peg, from, to) end end
true
4f3352a45ceaf688a7dc322a110b86f2c3ca35e5
Ruby
RobertoM80/Introduction_to_ruby_and_wb
/lesson_1/calculator_v2.rb
UTF-8
1,075
3.9375
4
[]
no_license
#1. ask user for input number one and store it #2. ask user for input number two and store it #3. ask user for input operator and store it #4. if inputs are not number, has spaces ask again for an apropriate input # => else continue #5. calculate results and display # # def ask words puts words end def re_ask words puts words end loop do ask "This is a calculator, chose the first number for you calculation: " number_1 = gets.chomp ask "Chose now your second number:" number_2 = gets.chomp ask "Chose now your operator ( + , - , * , / ) :" operator = gets.chomp puts "#{number_1} + #{number_2} = #{number_1.to_i + number_2.to_i}" if operator == "+" puts "#{number_1} - #{number_2} = #{number_1.to_i - number_2.to_i}" if operator == "-" puts "#{number_1} * #{number_2} = #{number_1.to_i * number_2.to_i}" if operator == "*" puts "#{number_1} / #{number_2} = #{number_1.to_f / number_2.to_f}" if operator == "/" puts "Do you want to perform another calculation? (Y/N)" replay = gets.chomp break if replay.downcase == "n" end
true
23a51441d7dd1cf140ed752261d33b47284b865c
Ruby
ashtrail/tsp
/LK_agent.rb
UTF-8
769
3.046875
3
[]
no_license
#!/usr/bin/env ruby require_relative 'src/parser' require_relative 'src/greedy_solver' require_relative 'src/LKOptimizer' require_relative 'src/timer' # init total_time = 30 safety_time = 2 time = Timer.new time.start() solver = GreedySolver.new lk = LKOptimizer.new solution = [] # parse file begin graph = Parser.new.parse_file(ARGV[0]) output = File.new(ARGV[1], "w") rescue puts "Usage : ./optimizer_agent.rb input_file output_file." exit end # greedy solve solution = solver.solve(graph) # optimization deadline = total_time - safety_time solution.pop solution = lk.run(solution, solver.cost, graph, time, deadline) # prints the solution in the output file output.print "#{Utility.solution_to_s(solution)}" output.close puts "#{(time.ellapsed)}"
true
7ecc4e59a7c947d5d158987bd0946c12eeb492f3
Ruby
frc-862/attendance
/scripts/attendance_log.rb
UTF-8
1,008
2.78125
3
[ "MIT" ]
permissive
class AttendanceLog def initialize(fname = File.absolute_path(File.dirname(__FILE__) + "/../attendance.log")) @fname = fname end def append(op, ip, *value) File.open(@fname, "a") do |out| out.puts("#{Time.now} #{op.to_s.ljust(5)} #{ip.to_s.ljust(15)} #{value.join("\t")}") end end def process_line(line) if line.match(/^(.{25})\s+(\S+)\s+(\S+)\s+(.*)$/) time, cmd, ip, body = $~.captures time = Time.parse(time).localtime date = time.to_date yield date, time, cmd, ip, body end end def foreach(&block) File.open(@fname).each_line do |line| process_line(line, &block) end end def tail(follow = true, &block) if follow File.open(@fname) do |log| log.extend(File::Tail) log.interval # 10 log.tail do |line| process_line(line, &block) end end else File.open(@fname).each_line do |line| process_line(line, &block) end end end end
true
4cfb6248853779f9ae425cfcf21e64ddbaf095e4
Ruby
SettRaziel/ruby_visualization
/lib/output/data_output/dataset_output.rb
UTF-8
1,097
2.90625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module DataOutput # Parent class for data output and delta output class DatasetOutput < BaseOutput private # @return [VisMetaData] the meta data for this output attr :meta_data # prints the meta information consisting of dataset name and informations # of the different dimensions def print_meta_information print_meta_head print_domain_information(@meta_data.domain_x, "\nX") print_domain_information(@meta_data.domain_y, "Y") print_meta_tail nil end # abstract method to print additional information before the x and y # domain informations # @abstract subclasses need to implement this method # @raise [NotImplementedError] if the subclass does not have this method def print_meta_head fail NotImplementedError, " Error: the subclass #{self.class} needs " \ "to implement the method: print_meta_tail from its base class".red end # method to print additional information after the x and y # domain informations def print_meta_tail nil # do nothing end end end
true
b053f5f40a433508a65aa3fee6ec8168f3620297
Ruby
Lunairi/42-Atlantis-Chatterbot-Auditing
/src/userinfo.rb
UTF-8
1,928
2.90625
3
[]
no_license
require 'slack-ruby-client' require 'rubygems' require 'write_xlsx' # Class that helps to search user and create and update doc class UserInfo def initialize_vars @row = 0 @col = -1 puts 'Userinfo search called' end def upload_file(client) client.files_upload( channels: '#general', as_user: true, file: Faraday::UploadIO.new('./userinfo.xlsx', 'userinfo.xlsx'), title: 'User Info', filename: 'userinfo.xlsx', initial_comment: 'User Info in Excel' ) end def display_error(client, search) client.chat_postMessage(channel: '#general', text: "Sorry, UID [#{search}] is invalid!", as_user: true) end def display_intro(client) client.chat_postMessage(channel: '#general', text: 'User Information', as_user: true) end def write_info(worksheet, key, value) worksheet.write(@row, @col += 1, key) worksheet.write(@row, @col += 1, value) @row += 1 @col = -1 end def search_user(client, worksheet, search) userinfo = client.users_info(user: search) userinfo['user'].each do |key, value| if value.class != Slack::Messages::Message write_info(worksheet, key, value) else userinfo['user'][key].each do |key2, value2| write_info(worksheet, key2, value2) end end end end def search_and_handle(client, worksheet, search, workbook) search_user(client, worksheet, search) workbook.close upload_file(client) rescue StandardError display_error(client, search) workbook.close end def get_user_info(client, search) puts "Search userinfo called for #{search}" initialize_vars display_intro(client) workbook = WriteXLSX.new('userinfo.xlsx') worksheet = workbook.add_worksheet search_and_handle(client, worksheet, search, workbook) end end
true
b76d3984d5a3649b9237885b638f318517f7cc6d
Ruby
cldwalker/lightning
/lib/lightning/util.rb
UTF-8
2,098
2.75
3
[ "MIT" ]
permissive
module Lightning module Util extend self if RUBY_VERSION < '1.9.1' # From Ruby 1.9's Shellwords#shellescape def shellescape(str) # An empty argument will be skipped, so return empty quotes. return "''" if str.empty? str = str.dup # Process as a single byte sequence because not all shell # implementations are multibyte aware. str.gsub!(/([^A-Za-z0-9_\-.,:\/@\n])/n, "\\\\\\1") # A LF cannot be escaped with a backslash because a backslash + LF # combo is regarded as line continuation and simply ignored. str.gsub!(/\n/, "'\n'") return str end else require 'shellwords' def shellescape(str) Shellwords.shellescape(str) end end # @return [String] Cross-platform way to determine a user's home. From Rubygems. def find_home ['HOME', 'USERPROFILE'].each {|e| return ENV[e] if ENV[e] } return "#{ENV['HOMEDRIVE']}#{ENV['HOMEPATH']}" if ENV['HOMEDRIVE'] && ENV['HOMEPATH'] File.expand_path("~") rescue File::ALT_SEPARATOR ? "C:/" : "/" end # @return [Boolean] Determines if a shell command exists by searching for it in ENV['PATH']. def shell_command_exists?(command) (@path ||= ENV['PATH'].split(File::PATH_SEPARATOR)). any? {|d| File.exists? File.join(d, command) } end # @return [Hash] Symbolizes keys of given hash def symbolize_keys(hash) hash.inject({}) do |h, (key, value)| h[key.to_sym] = value; h end end # Loads *.rb plugins in given directory and sub directory under it def load_plugins(base_dir, sub_dir) if File.exists?(dir = File.join(base_dir, sub_dir)) plugin_type = sub_dir.sub(/s$/, '') Dir[dir + '/*.rb'].each {|file| load_plugin(file, plugin_type) } end end protected def load_plugin(file, plugin_type) require file rescue Exception => e puts "Error: #{plugin_type.capitalize} plugin '#{File.basename(file)}'"+ " failed to load:", e.message end end end
true
78769ac2000995bf1dc56beffc24eabf8343a8dd
Ruby
billyacademy/class_prac
/deck.rb
UTF-8
348
3.5
4
[]
no_license
class Deck SUITS = ["Spades", "Clubs", "Hearts", "Diamonds"] VALUES = [2, 3, 4, 5, 6, 7, 8, 9, 10, 'J', 'Q', 'K', 'A'] attr_reader :deck def initialize @deck = [] SUITS.each do |suit| VALUES.each do |value| @deck << Card.new(suit, value) end end @deck.shuffle! end def draw @deck.pop end end
true
385843d4a2dc6fddde3f05c98327b536a172abee
Ruby
saidmaadan/masma_game
/lib/masma_game/next_game.rb
UTF-8
520
2.84375
3
[ "LicenseRef-scancode-other-permissive" ]
permissive
require_relative 'die' require_relative 'player' require_relative 'hoard_store' require_relative 'loaded_die' module MasmaGame module NextGame def self.next_player(p) die = Die.new case die.roll when 1..2 p.blam when 3..4 puts "#{p.name} was skipped." else p.w00t end hoard = HoardStore.random p.found_hoard(hoard) end end end if __FILE__ == $0 p = MasmaGame::Player.new("bimbo", 125) MasmaGame::NextGame.next_player(p) end
true
a1a466a0a84e66065b17201dcd26dc1fe89940fe
Ruby
ngeballe/ls120-lesson3
/review/variable_scope/5_class_variables.rb
UTF-8
515
3.84375
4
[]
no_license
class Person @@total_people = 0 # initialized at the class level def self.total_people @@total_people # accessible from class method end def initialize @@total_people += 1 # mutable from instance method end def total_people @@total_people # accessible from instance method end end p Person.total_people # 0 Person.new Person.new p Person.total_people # 2 bob = Person.new p bob.total_people # 3 joe = Person.new p joe.total_people # 4 p Person.total_people # 4
true
87ea66aed34812cfc8f793919849b9d36085ba62
Ruby
reteshbajaj/learn_to_program
/challenge9.rb
UTF-8
544
3.3125
3
[]
no_license
#challenge9.rb def ask question while true puts question reply = gets.chomp.downcase until (reply == "yes" || reply == "no") puts "please answer yes or no ma'am!!" puts question reply = gets.chomp.downcase end if (reply == "yes" || reply == "no") if reply == "yes" puts "yes entered" condition = true else reply == "no" puts "ok...no" condition2 = true end end break end end sba = ask "Do you luuuuuv SBAs?" family = ask "But you love your family??" ##This runs the method ask
true
e9cc58ad3948c35a1f78bab4ae12579528450427
Ruby
creinken/ruby-collaborating-objects-lab-onl01-seng-ft-032320
/lib/song.rb
UTF-8
594
3.25
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song #### Attributes #### attr_accessor :name, :artist @@all = [] #### Instance methods #### def initialize(name) @name = name @@all << self end def artist_name=(name) if self.artist == nil self.artist = Artist.find_or_create_by_name(name) else self.artist = Artist.all.select {|artist| artist.name == name} end end #### Class methods #### def self.all @@all end def self.new_by_filename(filename) song = self.new(filename.split(" - ")[1]) song.artist_name = filename.split(" - ")[0] song end end
true
590dbc577bf4be23d5150c79f10c63ee5e3294bb
Ruby
KirilKostov/task_2
/song.rb
UTF-8
156
3.03125
3
[]
no_license
class Song attr_reader :name, :artist, :album def initialize(name, artist, album) @name = name @artist = artist @album = album end end
true
c2ec34265995a8d0c586a6a4fc3e3234f54a50ce
Ruby
andrewkjankowski/debug-me-001
/runner.rb
UTF-8
772
3.859375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative './jukebox.rb' def run puts "Welcome to Ruby Console Jukebox!" prompt command = get_command while command.downcase != "exit" do run_command(command.downcase) unless command.downcase == "exit" prompt command = get_command end end def prompt puts "Enter a command to continue. Type 'help' for a list of commands." end def get_command gets.strip end def run_command(command) case command when "help" show_help else jukebox(command) end end def show_help puts "Never worked a jukebox, eh? Pretty standard. Available commands are:\n" puts "'help' - shows this menu\n" puts "'list' - lists the whole song library\n" puts "or you can enter an artist's name to show that artist's songs\n" puts "" end run
true
21ccd5774f1e5e3809d7c346b145232d9b0e4154
Ruby
kad3nce/env_vars_validator
/lib/env_vars_validator.rb
UTF-8
843
2.671875
3
[ "MIT" ]
permissive
class EnvVarsValidator @@last_error = nil def self.last_error @@last_error end def self.source_from_ruby_files(starting_dir) Dir.glob(File.join(starting_dir, '**', '*.rb')). reject { |file_path| file_path.include?('vendor') }. map { |file_path| File.read(file_path) }. join("\n") end def self.used_env_vars(starting_dir) source_from_ruby_files(starting_dir). scan(/ENV\[(?:'|")([^\]]+)(?:'|")\]/). flatten. uniq. sort end def self.validate(starting_dir) declared_env_vars = ENV.keys missing_env_vars = used_env_vars(starting_dir) - declared_env_vars unless missing_env_vars.empty? @@last_error = "The following env vars are required and have not been defined:\n #{missing_env_vars.sort.join("\n ")}" return false end true end end
true
fc4e8cbe507a8ee847b1d2febaa75e106e18a079
Ruby
VKuzmich/ruby-exercice-files
/cases.rb
UTF-8
796
3.609375
4
[]
no_license
puts "Dates of week" puts "Write the number from 1 to 7 " ch=gets.to_i case ch when 1 puts "Monday" when 2 puts "Tuesday" when 3 puts "Wednesday" when 4 puts "Thursday" when 5 puts "Friday" when 6 puts "Saturday" when 7 puts "Sunday" else puts "you wrote wrong number" end puts "What is the type of your car?" car=gets.chomp manufacturer = case car when "Focus" then "Ford" when "Navigator" then "Lincoln" when "Camry" then "Toyota" when "Patriot" then "Jeep" when "Ceyene" then "Porshe" when "Forester" then "Subaru" when "520i" then "BMW" when "Juke" then "Nissan" else "Unknown" end puts "The " + car + " is " + manufacturer
true
bb848652d381b56622e1a3ffe8fd9b323af08a6e
Ruby
mekimball/craft_2108
/spec/person_spec.rb
UTF-8
1,128
3.046875
3
[]
no_license
require './lib/person' require './lib/craft' RSpec.describe Person do before(:each) do @person = Person.new({ name: 'Hector', interests: %w[sewing millinery drawing] }) end it 'exists' do expect(@person).to be_a(Person) end it 'has attributes' do expect(@person.name).to eq('Hector') expect(@person.interests).to eq(%w[sewing millinery drawing]) expect(@person.supplies).to eq({}) end it 'can add supplies' do @person.add_supply('fabric', 4) @person.add_supply('scissors', 1) expect(@person.supplies).to eq({ 'fabric' => 4, 'scissors' => 1 }) end it 'can determine if can be built' do sewing = Craft.new('sewing', { fabric: 5, scissors: 1, thread: 1, sewing_needles: 1 }) expect(@person.can_build?(sewing)).to eq(false) @person.add_supply('fabric', 7) @person.add_supply('thread', 1) expect(@person.can_build?(sewing)).to eq(false) @person.add_supply('scissors', 1) @person.add_supply('sewing_needles', 1) expect(@person.can_build?(sewing)).to eq(true) end end
true
91ef48ce4868fb5acbc8d091dc1057d218c1d046
Ruby
Rmole57/intro-to-programming-ruby-exercises
/flow_control/ex5.rb
UTF-8
1,530
4.75
5
[]
no_license
# Exercise 5 (Exercise 3 program, refactored using a case statement wrapped in a method) =begin NOTE: I decided to use a case statement with an argument. Using a case statement without an argument would mean I would have to provide each 'when' clause with a condition that evaluates to a boolean. Then the case statement would be evaluating the truthiness of the object in each 'when' clause. However, by providing the case statement with an argument, each 'when' clause is given an object to compare to the argument I provided the case statement with. This was mainly a way of me solving this exercsie in a more uncomfortable way as using boolean expressions in 'when' clauses is much like using if/else statements. I thought it would be both beneficial and inmportant for me to practice it this way and explain out the respective processes and functionality of each solution. =end # Defines 'range' method to carry out range evaluation from Exercise 3 program. def range(number) case number when 0..50 puts "Your number, #{number}, is between 0 and 50." when 51..100 puts "Your number, #{number}, is between 51 and 100." else if number < 0 puts "Oops! You've entered a negative number!" else puts "Too high! Your number, #{number}, is over 100!" end end end # Prompts user for number and stores input in 'num' variable. puts "Choose a number between 0 and 100:" num = gets.chomp.to_i # Calls the 'range' method, which prints out appropriate message for each range. range(num)
true
6f7dc7d5c5f0dda70ae832c9459307db33c45700
Ruby
Teshager21/online-sales-data-scrapper
/lib/page_parser.rb
UTF-8
549
2.875
3
[]
no_license
require 'httparty' require 'nokogiri' class PageParser attr_reader :parsed_page, :unparsed_page def parse_page @parsed_page = Nokogiri::HTML(@unparsed_page.body) end def filter_by_class(css_class, parsed_page = @parsed_page) parsed_page.css(css_class) end def initialize(url) try = 3 @parsed_page = nil begin @unparsed_page = HTTParty.get(url) rescue StandardError retry unless (try -= 1).zero? if try.zero? puts 'Failed to connect to server' exit end end end end
true
f30929c96382ad435d1d476d7c6b8a8ffe0c5089
Ruby
Argonus/algorithms
/coursera_algorithms/course_1/week_3/quick_sort.rb
UTF-8
2,574
3.515625
4
[]
no_license
module Course1 module Week3 class QuickSort attr_reader :comparasions def initialize(array, manner = :random) @array = array @a_length = array.size @comparasions = 0 @manner = manner end def sort! return @array if @a_length <= 1 quicksort(@array, 0, @a_length) end private def quicksort(array, left, right) return array if left >= right current = partition(array, left, right) quicksort(array, left, current) quicksort(array, current+1, right) array end def partition(array, left, right) pivot, i = select_pivot_and_i(array, left, right) increment_number_of_comparisons(left, right) (i...right).each do |j| i = swap_and_increment(array, i, j) if array[j] < pivot end swap_arrays(array, i-1, left) i-1 end def increment_number_of_comparisons(left, right) @comparasions += right-left-1 end def swap_and_increment(array, i, j) swap_arrays(array, i, j) i + 1 end def swap_arrays(array, i, j) array[j], array[i] = array[i], array[j] end def select_pivot_and_i(array, left, right) case @manner when :first pivot, i = array[left], calculate_i(left) return pivot, i when :last right_index = right-1 pivot, i = array[right_index], calculate_i(left) swap_arrays(array, right_index, left) return pivot, i when :middle left_elemnt, right_element, length = array[left], array[right-1], (right-left) middle = select_middel_element(array, left, length) pivot, i = median(left_elemnt, right_element, middle), calculate_i(left) pivot_index = array.index(pivot) swap_arrays(array, pivot_index, left) return pivot, i when :random pivot_index = rand(left...right) pivot, i = array[pivot_index], calculate_i(left) swap_arrays(array, pivot_index, left) return pivot, i else raise NotImplementedError end end def calculate_i(left) left+1 end def select_middel_element(array, left, length) length % 2 == 0 ? middle = array[left + length/2 - 1] : middle = array[left + length/2] middle end def median(a, b, c) [a, b, c].sort[1] end end end end
true
0064081612cee96f190ab29631e4693f1061c7f4
Ruby
ismk/phase_0_unit_2
/week_5/4_boggle_board/my_solution.rb
UTF-8
1,347
4.53125
5
[]
no_license
# U2.W5: A Nested Array to Model a Boggle Board # I worked on this challenge [by myself]. boggle_board = [["b", "r", "a", "e"], ["i", "o", "d", "t"], ["e", "c", "l", "r"], ["t", "a", "k", "e"]] # Part 1: Access multiple elements of a nested array # Pseudocode # Initial Solution def get_row(board,row) board[row] end # Refactored Solution # DRIVER TESTS GO BELOW THIS LINE puts boggle_board[0] == get_row(boggle_board, 0) puts boggle_board[1] == get_row(boggle_board, 1) puts boggle_board[2] == get_row(boggle_board, 2) # Reflection #------------------------------------------------------------------------------- # Part 2: Write a method that takes a row number and returns all the elements in the row. # Pseudocode # Initial Solution def get_col(board,col) board.map{ |x| x[col]} end # Refactored Solution # DRIVER TESTS GO BELOW THIS LINE puts %W{b i e t} == get_col(boggle_board, 0) puts %W{r o c a} == get_col(boggle_board, 1) puts %W{e t r e} == get_col(boggle_board, 3) # Reflection # Simple nested arrays, very useful in board games where you want to lay down rows and columns, # the board is most constructed by the use of 2 for loops, one creating the row and the other column # Example # for (int i=;i<=10;i++){ # for(int j=0;j<=10;j++){ # print "x" # } #}
true
8f55324ad99fc954c8bca765714e191ea9790bc1
Ruby
Laner12/random_res
/app/services/current_location_service.rb
UTF-8
402
2.640625
3
[]
no_license
class CurrentLocationService def initialize @_connection = Faraday.post("https://www.googleapis.com/geolocation/v1/geolocate?key=#{ENV['GOOGLE_API_KEY']}") end def get_location response = connection parse(response.body) end private def parse(response) JSON.parse(response, symbolize_names: true)[:location] end def connection @_connection end end
true
05f6109753342619583c713147496d7203158f6a
Ruby
aurora-a-k-a-lightning/gaku_admin
/lib/tasks/admin_user.rake
UTF-8
2,783
2.5625
3
[]
no_license
require 'highline/import' namespace :gaku do desc "Create admin username and password" task generate_admin: :environment do if Gaku::User.admin.empty? create_admin_user else puts 'Admin user has already been previously created.' if agree('Would you like to create a new admin user? (yes/no)') create_admin_user else puts 'No admin user created.' end end end end def prompt_for_admin_password if ENV['ADMIN_PASSWORD'] password = ENV['ADMIN_PASSWORD'].dup say "Admin Password #{password}" else password = ask('Password [123456]: ') do |q| q.echo = false q.validate = /^(|.{5,40})$/ q.responses[:not_valid] = 'Invalid password. Must be at least 5 characters long.' q.whitespace = :strip end password = '123456' if password.blank? end password end def prompt_for_admin_email if ENV['ADMIN_EMAIL'] email = ENV['ADMIN_EMAIL'].dup say "Admin User #{email}" else email = ask('Email [admin@gakuengine.com]: ') do |q| q.echo = true q.whitespace = :strip end email = 'admin@gakuengine.com' if email.blank? end email end def prompt_for_admin_username if ENV['ADMIN_USERNAME'] username = ENV['ADMIN_USERNAME'].dup say "Admin User #{username}" else username = ask('Username [admin]: ') do |q| q.echo = true q.whitespace = :strip end username = 'admin' if username.blank? end username end def create_admin_user if ENV['AUTO_ACCEPT'] password = '123456' email = 'admin@gakuengine.com' else puts 'Create the admin user (press enter for defaults).' username = prompt_for_admin_username email = prompt_for_admin_email password = prompt_for_admin_password end attributes = { password: password, password_confirmation: password, email: email, username: username } if Gaku::User.find_by_email(email) say "\nWARNING: There is already a user with the email: #{email}, so no account changes were made. If you wish to create an additional admin user, please run rake gaku:generate_admin again with a different email.\n\n" elsif Gaku::User.find_by_username(username) say "\nWARNING: There is already a user with the username: #{username}, so no account changes were made. If you wish to create an additional admin user, please run rake gaku:generate_admin again with a different username.\n\n" else say "Creating user..." creator = Gaku::UserCreator.new(attributes) creator.save admin = creator.get_user # create an admin role and and assign the admin user to that role role = Gaku::Role.where(name: 'Admin').first_or_initialize admin.roles << role if admin.save say "User Created" else say "User NOT Created" end end end
true
6fb9e94bf4d3e526a519df75a0a886c9047eec25
Ruby
Ghrind/roguelike
/lib/roguelike/field_of_view.rb
UTF-8
2,409
3.21875
3
[ "MIT" ]
permissive
# Taken from http://www.roguebasin.com/index.php?title=Ruby_shadowcasting_implementation module ShadowcastingFieldOfView # Multipliers for transforming coordinates into other octants @@mult = [ [1, 0, 0, -1, -1, 0, 0, 1], [0, 1, -1, 0, 0, -1, 1, 0], [0, 1, 1, 0, 0, -1, -1, 0], [1, 0, 0, 1, -1, 0, 0, -1], ] # Determines which co-ordinates on a 2D grid are visible # from a particular co-ordinate. # start_x, start_y: center of view # radius: how far field of view extends def do_fov(creature) creature.fov = [] light creature, creature.x, creature.y 8.times do |oct| cast_light creature, 1, 1.0, 0.0, @@mult[0][oct],@@mult[1][oct], @@mult[2][oct], @@mult[3][oct], 0 end end private # Recursive light-casting function def cast_light(creature, row, light_start, light_end, xx, xy, yx, yy, id) radius = creature.light_radius cx = creature.x cy = creature.y return if light_start < light_end radius_sq = radius * radius (row..radius).each do |j| # .. is inclusive dx, dy = -j - 1, -j blocked = false while dx <= 0 dx += 1 # Translate the dx, dy co-ordinates into map co-ordinates mx, my = cx + dx * xx + dy * xy, cy + dx * yx + dy * yy # l_slope and r_slope store the slopes of the left and right # extremities of the square we're considering: l_slope, r_slope = (dx-0.5)/(dy+0.5), (dx+0.5)/(dy-0.5) if light_start < r_slope next elsif light_end > l_slope break else # Our light beam is touching this square; light it light(creature, mx, my) if (dx*dx + dy*dy) < radius_sq if blocked # We've scanning a row of blocked squares if blocked?(mx, my) new_start = r_slope next else blocked = false light_start = new_start end else if blocked?(mx, my) and j < radius # This is a blocking square, start a child scan blocked = true cast_light(creature, j+1, light_start, l_slope, xx, xy, yx, yy, id+1) new_start = r_slope end end end end # while dx <= 0 break if blocked end # (row..radius+1).each end end
true
9a0ddc0e59aff0b738b77b74acdb7f752c29c5db
Ruby
kraila/blackjack
/blackjack.rb
UTF-8
518
3.296875
3
[]
no_license
#!/usr/bin/env ruby Dir[File.join('lib', '**', '*.rb')].each do |file| require_relative file end def play_new blackjack = Game.new blackjack.begin_blackjack! blackjack.display_player_hand blackjack.prompt_hit_or_stand blackjack.compare_scores play_again? end def play_again? print "Play again? (Y/N): " answer = gets.chomp.downcase if answer == "y" play_new elsif answer == "n" puts "Ok, goodbye!" else puts "Invalid input. \n" play_again? end end play_new
true
e54653f20c97870fcdb17f2b3be747268a2cae76
Ruby
MrJaba/IPRUG-Sept-HigherOrderRuby
/currying.rb
UTF-8
707
4.0625
4
[]
no_license
#Ruby 1.8 def scale_number(x, factor) x * factor end def scale_factory(factor) lambda{|x| x * factor} end scale_3 = scale_factory(3) 1.upto(10) do |x| puts scale_number(x, 3) end 1.upto(10) do |x| puts scale_3.call(x) end #Ruby 1.9 # scale = lambda{|factor, x| x * factor } # scale_3 = scale.curry[3] # # 1.upto(10) do |x| # puts scale_3.call(x) # end #Curried Map function - bit pointless in ruby! #before p (1..10).to_a.map {|x| x * 2} #cant pass this around and use anywhere else #after def cmap(&block) lambda{|array| return array.map(&block) } end #this can be reused elsewhere to double any stream of numbers map_double = cmap {|x| x * 2 } p map_double.call((1..10).to_a)
true
6d2276319bf012e82048f5d2f361b2f85424004a
Ruby
buchheimt/golf-links
/spec/features/course_features_spec.rb
UTF-8
6,953
2.515625
3
[ "MIT" ]
permissive
require_relative "../rails_helper.rb" describe "Course Features", type: :feature do describe "Course#index", type: :feature do before :each do Course.create( name: "Augusta National GC", description: "Home of the Masters", location: "Augusta, GA" ) end let(:course) { Course.first } it "displays with name and location" do visit courses_path expect(page).to have_content(course.name) expect(page).to have_content(course.location) end it "has links to course show pages" do visit courses_path click_link "Augusta National GC" expect(current_path).to eq(course_path(course)) end it "has a link to Course#new" do visit_signin user_login visit courses_path click_link "Add New Course" expect(current_path).to eq(new_course_path) end end describe "Course#show", type: :feature do before :each do User.create( username: "tylerB", email: "tyler@gmail.com", password: "123456", password_confirmation: "123456" ) end before :each do Course.create( name: "Augusta National GC", description: "Home of the Masters", location: "Augusta, GA" ) end let(:user) { User.first } let(:course) { Course.first } # context "as admin" do # it "has a link to Course#edit" do # visit_signin # admin_login # visit course_path(course) # expect(page).to have_content("Edit Course") # click_link "Edit Course" # expect(current_path).to eq(edit_course_path(course)) # end # end context "when logged in" do it "links to Course/TeeTime#new" do visit_signin user_login visit course_path(course) click_link("Create New Tee Time") expect(current_path).to eq(new_course_tee_time_path(course)) end it "does not link to Course#edit if not an admin" do visit_signin user_login visit course_path(course) expect(page).to_not have_content("Edit Course") end end context "when logged out" do it "doesn't link to User/TeeTime#new" do visit course_path(course) expect(page).to_not have_content("Create New Tee Time") end end it "displays a course name" do visit course_path(course) expect(page).to have_content("Augusta National GC") end it "displays a course description" do visit course_path(course) expect(page).to have_content("Home of the Masters") end it "displays a course location" do visit course_path(course) expect(page).to have_content("Augusta, GA") end it "displays tee times scheduled for the course" do tee_time = course.tee_times.build(time: "Dec 1 2099") tee_time.add_user(user) visit course_path(course) expect(page).to have_content("Dec 1, 2099") end it "displays associated tee times as links to nested tee time show page" do tee_time = course.tee_times.build(time: "Dec 1 2099") tee_time.add_user(user) visit course_path(course) click_link(tee_time.time.year) expect(current_path).to eq(course_tee_time_path(course, tee_time)) end it "defaults to displaying associated tee times in chronological order" do tee_time1 = course.tee_times.build(time: "Dec 1 2099") tee_time2 = course.tee_times.build(time: "Dec 1 2097") tee_time3 = course.tee_times.build(time: "Dec 1 2098") tee_time1.user_tee_times.build(user_id: user.id) tee_time2.user_tee_times.build(user_id: user.id) tee_time3.user_tee_times.build(user_id: user.id) course.save visit course_path(course) expect(page.body.index(tee_time2.time.year.to_s)).to be < page.body.index(tee_time1.time.year.to_s) end it "does not display tee times that have already taken place" do tee_time1 = course.tee_times.build(time: "Dec 1 2000") tee_time1.add_user(user) visit course_path(course) expect(page).to_not have_content("2000") end end describe "Course#edit", type: :feature do before :each do Course.create( name: "Augusta National GC", description: "Home of the Masters", location: "Augusta, GA" ) end let(:course) { Course.first } context "as admin" do it "allows for the course to be updated" do visit_signin admin_login visit edit_course_path(course) fill_in("course[description]", with: "Madagascar") click_button "Update Course" expect(current_path).to eq(course_path(course)) expect(page).to have_content("Madagascar") end it "has a link to destroy the course" do visit_signin admin_login visit edit_course_path(course) expect(page).to have_content("Delete Course") end end context "when not admin" do it "redirects to welcome page" do visit_signin user_login visit edit_course_path(course) expect(current_path).to eq(user_path(current_user)) end end end # describe "Course#destroy", type: :feature do # # before :each do # User.create( # username: "tylerB", # email: "tyler@gmail.com", # password: "123456", # password_confirmation: "123456" # ) # end # # before :each do # Course.create( # name: "Augusta National GC", # description: "Home of the Masters", # location: "Augusta, GA" # ) # end # # let(:user) { # User.first # } # # let(:course) { # Course.first # } # # it "destroys course" do # course_id = course.id # visit_signin # admin_login # visit edit_course_path(course) # click_button "Delete Course" # expect(current_path).to eq(courses_path) # expect(Course.find_by_id(course_id)).to be_nil # end # # it "destroys all course tee times" do # tee_time = course.tee_times.build(time: "Dec 1 2098") # tee_time_id = tee_time.id # visit_signin # admin_login # visit edit_course_path(course) # click_link "Delete Course" # expect(current_path).to eq(courses_path) # expect(TeeTime.find_by_id(tee_time_id)).to be_nil # end # # it "destroys all user tee times associated with course" do # tee_time = course.tee_times.build(time: "Dec 1 2098") # tee_time.add_user(user) # user_tee_time_id = tee_time.user_tee_times.first.id # visit_signin # admin_login # visit edit_course_path(course) # click_link "Delete Course" # expect(current_path).to eq(courses_path) # expect(UserTeeTime.find_by_id(user_tee_time_id)).to be_nil # end # end end
true
0d35beaefd404ebc6f76ea9d3a259f77f8c2bde7
Ruby
ScottDuane/chess
/game.rb
UTF-8
1,596
3.5625
4
[]
no_license
require_relative 'player.rb' require_relative 'Display.rb' require_relative 'Board.rb' require_relative 'humanplayer.rb' require_relative 'computerplayer.rb' class Game attr_reader :display, :board, :current_player def initialize(board) @board = board @display = Display.new(board, self) @current_player = HumanPlayer.new(:white, self) @other_player = ComputerPlayer.new(:black, self) end def play until self.game_over? @display.render move = @current_player.get_move puts "Move is: #{move}" # debugger successful_move = @board.make_move(move[0], move[1], @current_player.color) if successful_move switch_players else puts "Invalid move. Try again." sleep(2) end @display.selected = nil @display.cursor_pos = [0,0] @display.render #try_to_save end puts "GAME OVER. #{@other_player.color} player WON!!" end def switch_players @current_player, @other_player = @other_player, @current_player end def game_over? #puts "In game over method" @board.checkmate?(:white) || @board.checkmate?(:black) end def try_to_save puts "Name your file:" file_name = gets.chomp File.write("./#{file_name}.yaml", self.to_yaml) Kernel.abort end end if(__FILE__ == $PROGRAM_NAME) if ARGV.empty? #Welcome message game_board = Board.new() game = Game.new(game_board) #dis = Display.new(game_board, game) game.play else load_file_name = ARGV.shift YAML.load_file(load_file_name).play end end
true
638675594b34bd91d517d740232d5a7d25c15989
Ruby
calvinsettachatgul/thai_trainer
/vowels_test.rb
UTF-8
404
3.203125
3
[]
no_license
require 'io/console' # input = STDIN.getch @first_consonants = "กขฃคฅฆงจฉชซ" @second_consonants = "ฌญฎฏฐฑฒณดตถ" @third_consonants = "ทธนบปผฝพฟภม" @fourth_consonants = "ยรลวศษสหฬอฮ" @first_vowels = "ะาเแ ิ ี ุ ู" @tones = " ่ ้ ๊ ๋ ็ ํ ์" p @first_vowels.split(" ") p @tones.split(" ")
true
d8030fc6d38509372742db880aead435d5e03802
Ruby
stallpool/lazac
/samples/test.rb
UTF-8
1,040
3.1875
3
[ "MIT" ]
permissive
a = "" b = 1 puts a.\ \ class puts a + if b == 1 then "x" else "y" end =begin hello world end =begin =end =end def a(x) puts x # this is comment ? =begin =end end =begin again =end 1 def b? puts "wojofiewf" y = 1 z = if y == 1 then y+1 else y+2 end z = z + ( if y == 1 then 3 else 9 end ) + 2 \ if y == 1 end # warning []] character class has ']' without escape a = /te[]] st/ puts a b=4 i=3 test=4 puts b/test/i.to_f puts %-a\-)- puts %q["mane"] puts %Q["mane"] puts %["mane"] puts %q{"ma[ne"} puts %q("(m\((a(n)e)")?) puts %q<man|e\>> puts %r"man#e[]][]"ix puts %i(#{"a"} int) puts %q-mane- puts %q\mane\ puts <<EOF echo 1 #{$x} EOF puts <<-EOS jeeepwofjeowpf ab sdfwefwef EOS puts "b" puts <<"TEST" what a bug TEST a_b_c_d = 1 puts b, a_b_c_d puts %{ hello } puts DATA i = 1 i++ if i > 0 then 0 else 1 end {} if i > 0 if i == 0 then puts 1 else puts 2 \ end module Txq end a=[Txq] class A0 class << self end end class a[0]::A < \ A0 end puts `ls` __END__ Hello World
true
3e7dee9879a32a3c5f01f641bb02bb6614ae4c41
Ruby
alejoFinocchi/back-up
/Ruby/Ruby/Ruby/p4/ej5/manejoDeArgumentos.rb
UTF-8
662
2.8125
3
[]
no_license
require 'sinatra' get '/' do lista todos los endpoints disponibles (sirve a modo de documentación) end get '/mcm/:a/:b' do calcula y presenta el mínimo común múltiplo de los valores numéricos end get 'mcd/:a/:b' do calcula y presenta el máximo común divisor de los valores numéricos end get '/sum/*' do calcula la sumatoria de todos los valores numéricos recibidos como parámetro en el splat end get '/even/*' do presenta la cantidad de números pares que hay entre los valores numéricos recibidos como parámetro en el splat end post '/random' do rand(1..1000) end post '/random/:lower/:upper' do rand(params[':lower']..params[':upper']) end
true
79d9c0113cd55d8bca018622bc7da030b1610571
Ruby
vmwhoami/travod
/app/controllers/concerns/scraping_module.rb
UTF-8
1,600
2.578125
3
[]
no_license
module ScrapingModule extend ActiveSupport::Concern def format_target_languages(target_languages) target_languages.join(' / ') end def check_url(url) return true if url.include? 'https://www.proz.com/' false end def scrapp_page(url) unparsed = HTTParty.get(url) doc = Nokogiri::HTML(unparsed) first_name = name(doc)[0] last_name = name(doc)[1] country = country(doc) native_language = language(doc) target_language = target_language(doc) - [native_language] source = url hash = {} hash['first_name'] = first_name hash['last_name'] = last_name hash['country'] = country hash['native_language'] = native_language hash['target_language'] = target_language hash['source'] = source hash end def name(doc) arr = doc.search('strong')[1] return if arr.nil? text = arr.children.text.strip.split first_name = text.shift family_name = text.join(' ') [first_name, family_name] end def language(doc) lang = doc.search('.pd_bot').children.text.split[-1] return 'No language defined' if lang[0...-1] == 'languages' lang[0...-1] end def target_language(doc) arr = [] doc.search('#lang_full').children.each do |span| arr << span.text.split(' to ') end arr.reject(&:empty?).flatten.uniq.reject { |c| c.strip.downcase == 'less' } end def country(doc) br = doc.xpath('//span[@id="tagline"]') return if br.empty? br = br.first.next_element nextbr = br.next_element nextbr.next_element.children[0].text.split(',')[-1] end end
true
b00ef22840d5e8b88fc62589f88892a76d7813a0
Ruby
Maghamrohith/ruby-programs
/greeting.rb
UTF-8
323
3.359375
3
[]
no_license
class Person attr_accessor :first_name,:last_name def initialize(details) @first_name = details[:first_name] @last_name = details[:last_name] end def details puts "hello,#{first_name}#{last_name}" end end p1=Person.new({:first_name=> "rohith",:last_name=> "kumar"}) p1.details
true
a33c7a6245f17c469889757b8935b303d9471b16
Ruby
Jauny/connect_four
/lib/connect_four/twitter_player.rb
UTF-8
2,782
3.09375
3
[]
no_license
require 'tweetstream' class TwitterPlayer attr_reader :name, :twitter, :piece, :random_tag, :id def initialize(options={}, tag) @name = options[:name] @twitter = options[:twitter] @piece = options[:piece] @id = options[:id] @random_tag = tag end def self.from_twitter @random_tag = (('a'..'z').to_a + ('A'..'Z').to_a + (1..9).to_a).shuffle[0..2].join @file_path = File.expand_path(File.join(File.dirname(__FILE__) , 'oauth'))#, '..', '..', 'db', name)) consumer_key_path = File.join(@file_path, "consumer_key.txt") consumer_secret_path = File.join(@file_path, "consumer_secret.txt") oauth_token_path = File.join(@file_path, "access_token.txt") oauth_token_secret_path = File.join(@file_path, "access_token_secret.txt") Twitter.configure do |config| config.consumer_key = File.read(consumer_key_path) config.consumer_secret = File.read(consumer_secret_path) config.oauth_token = File.read(oauth_token_path) config.oauth_token_secret = File.read(oauth_token_secret_path) end TweetStream.configure do |config| config.consumer_key = File.read(consumer_key_path) config.consumer_secret = File.read(consumer_secret_path) config.oauth_token = File.read(oauth_token_path) config.oauth_token_secret = File.read(oauth_token_secret_path) config.auth_method = :oauth end puts "...waiting for player" TweetStream::Client.new.track('#dbc_c4') do |status, client| #puts "id = #{status.user[:id]}, text = #{status.text}" text = status.text.gsub(/#.*/, "").strip if text == "Who wants to get demolished?" client.stop puts "@#{status.user[:screen_name]} Game on! #dbc_c4 #{@random_tag}" Twitter.update("@#{status.user[:screen_name]} Game on! #dbc_c4 #{@random_tag}") return TwitterPlayer.new({name: status.user[:name], twitter: status.user[:screen_name], piece: 'O', id: status.user[:id]}, @random_tag) end end end def move board = to_a(board_as_string) column = parsed_board(board) return column end def board_as_string TweetStream::Client.new.follow("#{@id}") do |status, client| raw_board = status.text.gsub!(/#.*/, "") board = raw_board.match(/[^@\w*](.*)/).to_s.strip client.stop return board end end def parsed_board(board_as_array) result = nil board_as_array board_as_array.each_with_index do |cell, index| if cell != UI.game.board.cells[index] result = (index % 7) + 1 end end return result end def to_a(move_string) board_info = move_string.gsub(/\|/, "").split("") board_info.each { |field| field.gsub!(/\./, "") } board_info end end
true
6854d29249fb961800ef25dd7c3aae39766c29f0
Ruby
flipsasser/maintain
/spec/integer_spec.rb
UTF-8
809
2.890625
3
[ "MIT" ]
permissive
# Tests on integer-specific functionality require 'spec_helper' require 'maintain' describe Maintain do before :each do class ::MaintainTest extend Maintain end end describe "integer" do before :each do MaintainTest.maintain :kind, integer: true do state :man, 1 state :woman, 2, default: true state :none, 3 end @maintainer = MaintainTest.new end it "should handle numbery strings" do @maintainer.kind = "3" @maintainer.none?.should be_true end it "should handle defaults just fine" do @maintainer.woman?.should be_true end it "should return valid names, too" do @maintainer.kind = :woman @maintainer.kind.should == 2 @maintainer.kind.name.should == "woman" end end end
true
9ab953a10251c404389ea4b497a4ee0c5c9680cb
Ruby
magoosh/browser-timezone
/lib/browser-timezone/instance_methods.rb
UTF-8
589
2.546875
3
[]
no_license
module BrowserTimezone module InstanceMethods protected # Internal: Sets the Time class's default zone to the value returned by browser_timezone # This method should be called as a before_action def set_timezone_from_browser_cookie Time.zone = browser_timezone || 'UTC' end # Internal: Gets the timezone that corresponds to the value in the tzoffset cookie # # Returns: Returns a string or nil def browser_timezone return nil if cookies[:tzoffset].blank? ActiveSupport::TimeZone[-cookies[:tzoffset].to_i.minutes] end end end
true
fb47bca663c9fd699ca5cf03e2597fc27fa3fb16
Ruby
tungtung233/math_game
/main.rb
UTF-8
608
3.296875
3
[]
no_license
require './player' require './active_player' require './math_question' def start Math_logic.new_question if (P1.lives != 0 && P2.lives != 0) puts "----- NEW TURN -----" Current_player.change_active_player Math_logic.change_numbers start else string = "wins with a score of" if (P1.lives == 0) puts "Player 2 #{string} #{P2.lives}/3" else puts "Player 1 #{string} #{P1.lives}/3" end puts "----- GAME OVER -----" puts "Good bye!" end end P1 = Player.new P2 = Player.new Current_player = Active_player.new Math_logic = Math_question.new start
true
b2b7a368b34fcba73b959b564edccf6c16a90bfe
Ruby
vconcepcion/level_up_exercises
/art/app/models/show_recommender.rb
UTF-8
662
2.671875
3
[ "MIT" ]
permissive
class ShowRecommender def initialize(user = nil) @user = user end def recommendations return [] unless Review.beloved.by(@user).exists? cool_people(beloved_shows(@user)).inject([]) do |recommendations, user| recommendations += beloved_shows(user) (recommendations - beloved_shows(@user)).uniq end end private def beloved_shows(user) Show.find(Review.beloved.by(user) .includes(:performance) .pluck(:show_id) ) end def cool_people(beloved_shows) Review.includes(:performance) .where(rating: 5, performances: {show_id: beloved_shows}) .pluck(:user_id) end end
true
54d3e4ce3ace38112d8730d1637105adbb9cf060
Ruby
flipstone/codiphi
/engine/examples/functional/transform_spec.rb
UTF-8
9,116
2.515625
3
[]
no_license
require_relative '../spec_helper.rb' module Codiphi describe Transform do describe "matching_named_type" do it "yields proper hash reference to passed block" do indata = { "fum" => [{ Tokens::Name => "baz", Tokens::Type => "fum" }] } yielded = nil Transform.matching_named_type(indata, "baz", "fum") do |node| yielded = node end yielded.should == indata["fum"].first end it "yields to multiple matches" do indata = { "foo" => { "fum" => [{ Tokens::Name => "baz", "attr" => "aaa", Tokens::Type => "fum" }, { Tokens::Name => "baz", "attr" => "bbb", Tokens::Type => "fum" }] } } yielded = [] Transform.matching_named_type(indata, "baz", "fum") do |node| yielded << node end yielded.should have(2).nodes yielded.should include(indata["foo"]["fum"].first) yielded.should include(indata["foo"]["fum"].last) end it "matches list node parent declaration" do matches = 0 indata = { "list" => { "model" => [{ "type" => "baz", Tokens::Type => "model" }], "attr1" => "attr1val", Tokens::Type => "list" } } yielded = nil Transform.matching_named_type(indata, "list", "list") do |node| yielded = node end yielded.should == indata["list"] end it "finds a single case" do matches = 0 indata = { "fum" => [{ Tokens::Name => "baz", Tokens::Type => "fum" }] } Transform.matching_named_type(indata, "baz", "fum") do |n| matches += 1 n end matches.should == 1 end it "ignores non-immediate matches" do matches = 0 indata = { "fum" => [{ Tokens::Name => "baz", Tokens::Type => "fum" }, { "fum" => [{ "fum" => [{ "fie" => [{ Tokens::Name => "baz", Tokens::Type => "fie" }] }] }] }] } Transform.matching_named_type(indata, "baz", "fum") do |n| matches += 1 n end matches.should == 1 end it "finds buried cases twice" do matches = 0 indata = { "fum" => [{ Tokens::Name => "baz", Tokens::Type => "fum" }, { "fie" => [{ "big" => [{ "fum" => [{ Tokens::Name => "baz", Tokens::Type => "fum" }] }] }] }] } Transform.matching_named_type(indata, "baz", "fum") do |n| matches += 1 n end matches.should == 2 end it "doesn't yield when no matches" do matches = 0 indata = { "list" => [{ Tokens::Name => "baz", Tokens::Type => "list" }] } Transform.matching_named_type(indata, "baz", "foo") do |n| matches += 1 n end matches.should == 0 end it "finds multiple matches" do matches = 0 indata = { "fum" => [{ Tokens::Name => "baz", Tokens::Type => "fum" }, { Tokens::Name => "baz", Tokens::Type => "fum" }] } Transform.matching_named_type(indata, "baz", "fum") do |n| matches += 1 n end matches.should == 2 end it "puts returned data into the output tree" do indata = { "fum" => [{ Tokens::Name => "baz", Tokens::Type => "fum" }] } outdata = Transform.matching_named_type(indata, "baz", "fum") do |node| node.merge("erkle" => 999) end outdata["fum"].first["erkle"].should == 999 end end describe "remove_canonical_keys" do it "works" do input = { "a" => "b", "c" => [ { Tokens::Name => "foo", Tokens::Type => "c" }, { Tokens::Name => "bar", Tokens::Type => "c" }] } output = Transform.remove_canonical_keys(input) output["c"].each do |e| e.keys.should_not be_include(Tokens::Type) end end it "doesn't modify input" do input = { "a" => "b", "c" => [ { Tokens::Name => "foo", Tokens::Type => "c" }, { Tokens::Name => "bar", Tokens::Type => "c" }] } original_input = Marshal.load(Marshal.dump(input)) Transform.remove_canonical_keys(input) input.should == original_input end end describe "expand_to_canonical" do it "expands single named types to Hash" do namespace = Namespace.new.add_named_type("foo", "unit") input = { "unit" => "foo" } output = Transform.expand_to_canonical(input, namespace) output["unit"].class.should == Hash output["unit"][Tokens::Name].should == "foo" output["unit"][Tokens::Type].should == "unit" end it "doesn't expand existing Hashes" do namespace = Namespace.new.add_named_type("foo", "unit") input = { "c" => { Tokens::Name => "foo", Tokens::Type => "c" } } output = Transform.expand_to_canonical(input, namespace) output.should == input end it "applies Tokens::Type to Hash" do input = { "a" => "b", "c" => { Tokens::Name => "foo" } } output = Transform.expand_to_canonical(input, Namespace.new) output["a"].should == "b" output["c"].keys.should include(Tokens::Type) output["c"][Tokens::Type].should == "c" end it "applies Tokens::Type to Array of Hash" do input = { "a" => "b", "c" => [ { Tokens::Name => "foo" }, { Tokens::Name => "bar" }] } output = Transform.expand_to_canonical(input,Namespace.new) output["a"].should == "b" output["c"].each do |e| e.keys.should include(Tokens::Type) e[Tokens::Type].should == "c" end end it "applies Tokens::Type to nested Hash" do input = { "a" => [ { Tokens::Name => "foo", "weapon" => { Tokens::Name => "weapon_type", "ammunition" => { Tokens::Name => "hellfire_rounds" } } }] } output = Transform.expand_to_canonical(input,Namespace.new) output["a"][0][Tokens::Type].should == "a" weapon = output["a"][0]["weapon"] weapon[Tokens::Type].should == "weapon" ammo = weapon["ammunition"] ammo[Tokens::Type].should == "ammunition" end it "doesn't modify the input hash" do namespace = Namespace.new.add_named_type("foo", "unit") input = { "unit" => "foo" } output = Transform.expand_to_canonical(input, namespace) input.should == {"unit" => "foo"} end end describe "fold_type" do it "matches in Arrays" do indata = { "fee" => { Tokens::Name => "bim", Tokens::Type => "foo" }, "foo" => [{ Tokens::Name => "bar", Tokens::Type => "foo", "foo" => [{ Tokens::Name => "baz", Tokens::Type => "foo" }] }] } Transform.fold_type(indata, "foo", 0) do |match, memo| memo + 1 end.should == 3 end end describe "fold_selected" do it "folds on the items matching predicate" do indata = { "fee" => { Tokens::Name => "bim", Tokens::Type => "foo" }, "foo" => [{ Tokens::Name => "bar", Tokens::Type => "foo", "foo" => [{ Tokens::Name => "baz", Tokens::Type => "foo" }] }] } Transform.fold_selected( indata, 0, -> x { x[Tokens::Type] == "foo" }, -> x, memo { memo + 1 } ).should == 3 end end end end
true
f484ee7f5a083a4be5125db971bcbe7e92235cd1
Ruby
mbalbera/OO-mini-project-nyc-web-080519
/app/models/User.rb
UTF-8
859
3.25
3
[]
no_license
class User attr_accessor :recipe_cards @@all = [] def initialize(recipe_cards, allergies) @recipe_cards = recipe_cards @allergies = allergies @@all << self end def self.all @@all end def recipes recipe_cards.select { |r_c| r_c.recipe } end def add_recipe_card(attributes) #date, recipe, rating recipe_cards << RecipeCard.new(user: self, recipe: attributes[recipe],date: attributes[date],rating: attributes[rating]) end def declare_allergy(ingredient) Allergy.new(self, ingredient) end def allergens self.allergies end def top_three_recipies h = Hash.new(0) self.recipe_cards.each {|r_c| h[r_c] += 1} h.sort_by{|k,v| v}[0..2] end def most_recent_recipe self.recipe_cards[-1] end end
true
a310c3cb061f91f1c911e4a413c0248762f7d85a
Ruby
ebertolazzi/pins-mruby-pure-regexp
/test/regexp.rb
UTF-8
3,274
2.6875
3
[ "MIT" ]
permissive
assert('PureRegexp.compile') do assert_false PureRegexp.compile("((a)?(z)?x)") === "ZX" assert_true PureRegexp.compile("((a)?(z)?x)", PureRegexp::IGNORECASE) === "ZX" assert_false PureRegexp.compile("z.z", PureRegexp::IGNORECASE) === "z\nz" end assert('PureRegexp#match') do assert_nil PureRegexp.compile("z.z").match("zzz", 1) PureRegexp.compile("z.z").match("zzz") do |m| assert_equal "zzz", m[0] end end assert('PureRegexp#eql?') do assert_true PureRegexp.compile("z.z") == /z.z/ assert_true PureRegexp.compile("z.z").eql? /z.z/ assert_false PureRegexp.compile("z.z") == /z.z/mi end assert('PureRegexp#=~') do assert_nil PureRegexp.compile("z.z") =~ "azz" assert_nil PureRegexp.compile("z.z") =~ nil assert_equal 1, PureRegexp.compile("z.z") =~ "azzz" assert_equal 0, PureRegexp.compile("z.z") =~ "zzz" assert_equal 0, PureRegexp.compile("y?") =~ "zzz" end assert('PureRegexp#casefold?') do assert_true PureRegexp.compile("z.z", PureRegexp::IGNORECASE).casefold? end assert('PureRegexp#options') do assert_equal PureRegexp::IGNORECASE, PureRegexp.compile("z.z", PureRegexp::IGNORECASE).options end assert('PureRegexp#source') do assert_equal "((a)?(z)?x)", PureRegexp.compile("((a)?(z)?x)").source end assert('PureRegexp#===') do assert_true /^$/ === "" assert_true /((a)?(z)?x)/ === "zx" assert_false /((a)?(z)?x)/ === "z" assert_true /c?/ === "" end assert('PureMatchData#==') do m = /((a)?(z)?x)?/.match("zx") m2 = /((a)?(z)?x)?/.match("zx") assert_true m == m2 end assert('PureMatchData#[]') do m = /((a)?(z)?x)?/.match("zx") assert_equal "zx", m[0] assert_equal "zx", m[1] assert_equal nil, m[2] assert_equal "z", m[3] assert_equal ["zx", nil], m[1..2] end assert('PureMatchData#begin') do m = /((a)?(z)?x)?/.match("zx") assert_equal 0, m.begin(0) assert_equal 0, m.begin(1) assert_equal nil, m.begin(2) assert_equal 0, m.begin(3) end assert('PureMatchData#end') do m = /((a)?(z)?x)?/.match("zx") assert_equal 1, m.end(0) assert_equal 1, m.end(1) assert_equal nil, m.end(2) assert_equal 0, m.end(3) end assert('PureMatchData#post_match') do m = /c../.match("abcdefg") assert_equal "fg", m.post_match assert_equal "", /c?/.match("").post_match end assert('PureMatchData#pre_match') do m = /c../.match("abcdefg") assert_equal "ab", m.pre_match assert_equal "", /c?/.match("").pre_match end assert('PureMatchData#captures') do m = /((a)?(z)?x)?/.match("zx") assert_equal ["zx", nil, "z"], m.captures end assert('PureMatchData#to_a') do m = /((a)?(z)?x)?/.match("zx") assert_equal ["zx", "zx", nil, "z"], m.to_a assert_equal [""], /c?/.match("").to_a end assert('PureMatchData#length') do m = /((a)?(z)?x)?/.match("zx") assert_equal 4, m.length assert_equal 4, m.size end assert('PureMatchData#offset') do m = /((a)?(z)?x)?/.match("zx") assert_equal [0, 1], m.offset(0) assert_equal [0, 1], m.offset(1) assert_equal [nil, nil], m.offset(2) assert_equal [0, 0], m.offset(3) end assert('PureMatchData#to_s') do m = /((a)?(z)?x)?/.match("zx") assert_equal "zx", m.to_s end assert('PureMatchData#values_at') do m = /((a)?(z)?x)?/.match("zx") assert_equal ["zx", nil, "z"], m.values_at(0, 2, 3) end
true
3eb7cf91ab0282ba806e82b6e51e31ea78c0a87b
Ruby
denistsuman/csv-ping
/app/checker/remote.rb
UTF-8
1,907
2.875
3
[]
no_license
require 'json' # A class to check http availability using requests from a remote service (check-host.net currently). class Checker::Remote < Checker REQUEST_BASE = 'https://check-host.net/check-http?host={URL}' RESULT_BASE = 'https://check-host.net/check-result/{ID}' KYIV_HOST = 'ua2.node.check-host.net' ATTEMPT_COUNT = 10 private ## # Returns an availability of the url. # # (String) => Boolean def url_accessibility(url) resp = response(url) resp && resp.dig(0, 0) == 1 # check the response body end ## # check-host.net returns a result with 2 steps: # 1st: to request the host availabilities, which returns the request id # 2nd: to get the request result with the received id # # JSON Response body: # { # ... # "ua2.node.check-host.net": [ # [ # 1, # 0.141490936279297, # "Found", # "200", # "18.157.219.111" # ] # ] # } # # (String) => Hash def response(url) request_id = request_availabilities(url)['request_id'] result_url = RESULT_BASE.gsub('{ID}', request_id) # We need the loop because the 2nd step is becoming available on the server not immediately, # but with some delay. ATTEMPT_COUNT.times do |i| resp = open_json(result_url)[KYIV_HOST] break resp if resp end end ## JSON response body: # { # "nodes": [...] # "ok": 1, # "permanent_link": "https://check-host.net/check-report/e1da4d6k56f", # "request_id": "e1da4d6k56f" # } # # (String) => Hash def request_availabilities(url) request_url = REQUEST_BASE.gsub('{URL}', formatted_url(url)) open_json(request_url) end # (String) => Hash def open_json(url) JSON.parse open(url, 'Accept' => 'application/json').read end end
true
2af0864f1d04fadaa66b860272f3a894245c0c46
Ruby
ddollar/sinatra-cli
/lib/sinatra/cli/command.rb
UTF-8
3,214
2.828125
3
[]
no_license
require "sinatra/cli" class Sinatra::CLI::Command attr_reader :group, :banner, :description, :name def initialize(group, banner, description, &block) @group = group @banner = banner @description = description @name = banner.split(" ").first instance_eval &block end ## accessors ################################################################# class Helped attr_reader :command, :name, :description, :options def initialize(command, name, description, options={}) @command = command @name = name @description = description @options = options end def padding names = command.arguments.keys.concat(command.options.keys) names.map(&:length).max + 2 end end class Argument < Helped def help " %-#{padding}s %s" % [name.upcase, description] end end class Option < Helped def help "%-#{padding+2}s %s" % ["--#{name}", description] end end def arguments @arguments ||= {} end def options @options ||= {} end ## dsl ####################################################################### def argument(name, help=nil, opts={}) arguments[name.to_s] = Argument.new(self, name, help, opts) if help arguments[name.to_s] end def option(name, help=nil, opts={}) options[name.to_s] = Option.new(self, name, help, opts) if help options[name.to_s] end def action(&block) @action = block if block_given? @action end ## help ###################################################################### def full_name [ group.options[:prefix], name ].compact.join(":") end def full_path [ group.options[:prefix], name ].compact.join("/") end def help "%-30s # %s" % [full_name, description] end def padding group.commands.keys.map(&:length).max + 2 end ## execution ################################################################# class Context def run(&block) catch(:abort) { instance_eval &block } end def actions @@actions ||= [] end def display(message) actions << ["display", message] end def warning(message) actions << ["warning", message] end def error(message) actions << ["error", message] throw :abort end def execute(command) actions << ["execute", command] end end class CommandContext < Context attr_reader :args, :options, :request def initialize(args, options, request) @args = args || [] @options = options || {} @request = request end def confirm(message, &block) if options["confirm"] if options["confirm"].downcase[0..0] == "y" block.call else throw :abort end else actions << ["confirm", message] end end end class ErrorContext < Context attr_reader :exception, :response def initialize(exception, response) @exception = exception @response = response end end def execute(args, options, request) context = CommandContext.new(args, options, request) context.run(&action) { "commands" => context.actions }.to_json end end
true
51480365d062494cf343b45508afb07cbfcc1e9c
Ruby
jinx/core
/lib/jinx/helpers/set.rb
UTF-8
380
3.15625
3
[ "MIT" ]
permissive
require 'set' class Set # The standard Set {#merge} is an anomaly among Ruby collections, since merge modifies the called Set in-place rather # than return a new Set containing the merged contents. Preserve this unfortunate behavior, but partially address # the anomaly by adding the merge! alias to make it clear that this is an in-place merge. alias :merge! :merge end
true
a1ae180c774763c73565c169a486083a4cc84c89
Ruby
deepak-webonise/Ruby
/meta_programming/metaprogram.rb
UTF-8
936
3.265625
3
[]
no_license
#/usr/bin/ruby -w require "csv.rb" #CSV file path file_path = "states.csv" #csv file parsing options csv_options = {:headers => true,:col_sep => ",",:header_converters => :symbol,:converters => :all} #CSV file reading and storing in csv_content csv_content = CSV.read(file_path, csv_options) #Extracting class name from file class_name = File.basename(file_path,"s.csv").capitalize #setting class name as constant Object.const_set(class_name,Class.new) class_csv= Object.const_get(class_name) class_csv.class_eval{ define_method :convert_csv_values do csv_content.each do |row| obj_csv = class_csv.new row.each do |instance_var, instance_val| class_csv.class_eval{attr_accessor instance_var} obj_csv.instance_variable_set("@#{instance_var}",instance_val) end puts obj_csv.inspect end end } #object of state class obj_state = class_csv.new obj_state.send(:convert_csv_values)
true
b8631f0ab94b0b6abd1e9883e4a7ad4a87f91fdd
Ruby
pcylo/xkomer
/apps/web/services/fetch_current_offer.rb
UTF-8
2,293
2.671875
3
[]
no_license
class FetchCurrentOffer def initialize @page = load_page @repository = OfferRepository.new @current_name = get_by_selector(ENV['NAME_SELECTOR']) @current_old_price = get_by_selector(ENV['OLD_PRICE_SELECTOR']) @current_new_price = get_by_selector(ENV['NEW_PRICE_SELECTOR']) @current_discount = get_by_selector(ENV['DISCOUNT_SELECTOR']) @current_image_url = get_attr_by_selector(ENV['IMAGE_URL_SELECTOR'], 'src').to_s. gsub('-small', '').gsub('?filters=grayscale', '') @current_quantity = get_int_attr_by_selector(ENV['QUANTITY_SELECTOR'], 'aria-valuemax', 0). to_s.to_i @current_code = get_attr_by_selector(ENV['CODE_SELECTOR'], 'data-product-id'). to_s.to_i @current_left_count = get_int_attr_by_selector(ENV['SOLD_COUNT_SELECTOR'], 'aria-valuenow', 0). to_s.to_i end def call offer_exists? ? update_existing_offer : create_new_offer end private attr_reader :page, :repository, :current_name, :current_old_price, :current_new_price, :current_discount, :current_image_url, :current_quantity, :current_code, :existing_id, :current_left_count def offer_exists? !!(@existing_id = OfferRepository.new.find_recent(current_code)) end def update_existing_offer repository.update(existing_id, left_count: current_left_count) end def create_new_offer new_offer = repository.create( name: current_name, old_price: current_old_price, new_price: current_new_price, discount: current_discount, image_url: current_image_url, quantity: current_quantity, product_code: current_code, left_count: current_left_count ) Mailers::Notification.deliver(offer: new_offer) # TODO move to service end def load_page Mechanize.new.get(ENV['BASE_PARSING_URL']) end def get_by_selector(selector) page.at(selector)&.text&.strip end def get_attr_by_selector(selector, attribute) page.at(selector)&.attributes[attribute] end def get_int_attr_by_selector(selector, attribute, default) page.at(selector) ? page.at(selector).attributes[attribute] : default end end
true
dd7920ddea9b507ecd39dd3b68d6ed236c730d2a
Ruby
bosskey59/tweet-shortener-houston-web-071618
/tweet_shortener.rb
UTF-8
1,082
3.65625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. def dictionary(word) dictionary={ "hello": "hi", "to":"2", "two": "2", "too": "2", "for": "4", "four": "4", "be": "b", "you": "u", "at": "@", "and": "&" } dictionary.each do |key, value| if word == key.to_s || word == key.to_s.capitalize return value end end word end def word_substituter(tweet) array_of_tweet= tweet.split new_tweet =[]; array_of_tweet.each do |tweet_word| new_word = dictionary(tweet_word) new_tweet.push(new_word) end new_tweet.join(" ") end def bulk_tweet_shortener(statemant) statemant.each do |one_tweet| puts word_substituter(one_tweet) end end def selective_tweet_shortener(tweet) if tweet.length >140 return word_substituter(tweet) end tweet end def shortened_tweet_truncator(tweet) if tweet.length >140 shortened_tweet = word_substituter(tweet) if shortened_tweet.length>140 return shortened_tweet[0..136].concat("...") else return shortened_tweet end end tweet end
true
19be2ce496d8e5856247c8871c8d698b8e5f964b
Ruby
jaysoko/my-select-online-web-prework
/lib/my_select.rb
UTF-8
67
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_select(collection) collection.select { |i| yield(i) } end
true
56b627be85c0e473f67b9d1282db52ce88c52de2
Ruby
Madh93/advent-of-code-2017
/lib/aoc2017/day06/memory_reallocation.rb
UTF-8
1,765
3.0625
3
[ "MIT" ]
permissive
module Aoc2017 module Day06 class << self def memory_reallocation(filename) # Get absolute pathname file = File.join(File.dirname(__FILE__), filename) # Store memory banks in an array banks = File.read(file).split.map(&:to_i) states = [] cycles = 0 # Repeat until exists repeated state until states.include?(banks) # Add current banks copy to states array states << banks.dup # Get max block and index max_blocks, index = banks.each.with_index.max_by(&:first) # Reallocate blocks banks[index] = 0 1.upto(max_blocks) { |i| banks[(index + i) % banks.size] += 1 } cycles += 1 end # Return redistribution cycles cycles end def memory_reallocation_two(filename) # Get absolute pathname file = File.join(File.dirname(__FILE__), filename) # Store memory banks in an array banks = File.read(file).split.map(&:to_i) states = [] seen_state = nil cycles = 0 # Repeat until exists repeated state until banks == seen_state # Store the already seen state seen_state = banks.dup if states.include?(banks) && seen_state.nil? # Add current banks copy to states array states << banks.dup # Get max block and index max_blocks, index = banks.each.with_index.max_by(&:first) # Reallocate blocks banks[index] = 0 1.upto(max_blocks) { |i| banks[(index + i) % banks.size] += 1 } cycles += 1 unless seen_state.nil? end # Return redistribution cycles cycles end end end end
true
2e1381af369b6f298cb989165b326f8a990766e8
Ruby
Xavier-J-Ortiz/blocitoff
/db/seeds.rb
UTF-8
719
2.5625
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) require 'random_data' 5.times do User.create!( email: RandomData.random_email, password: RandomData.random_sentence ) end users = User.all 150.times do Item.create!( name: RandomData.random_sentence, user_id: rand(1 .. users.length) ) end # Create Posts puts "Seed finished" puts "#{User.count} users created" puts "#{Item.count} items created"
true
540e709f9ef287b75bb110fa921683d88a12fe6f
Ruby
globewalldesk/practice
/montyhall2.rb
UTF-8
1,196
3.984375
4
[]
no_license
#!/usr/bin/env ruby -w class Array def choice self.shuffle.first end end class MontyHall def initialize @doors = ['car', 'goat', 'goat'].shuffle end def pick_door return rand(3) end def reveal_door(pick) available_doors = [0, 1, 2] available_doors.delete(pick) available_doors.delete(@doors.index('car')) return available_doors.choice #makes a random choice of array elements end def staying_wins?(pick) won?(pick) end def switching_wins?(pick, open_door) switched_pick = ([0, 1, 2] - [open_door, pick]).first won?(switched_pick) end def won?(pick) @doors[pick] == 'car' end end staying_rate = 0 switching_rate = 0 if __FILE__ == $0 ITERATIONS = (ARGV.shift || 1_000_000).to_i staying = 0 switching = 0 ITERATIONS.times do mh = MontyHall.new picked = mh.pick_door revealed = mh.reveal_door(picked) staying += 1 if mh.staying_wins?(picked) switching += 1 if mh.switching_wins?(picked,revealed) staying_rate = (staying.to_f / ITERATIONS) * 100 switching_rate = (switching.to_f / ITERATIONS) * 100 end end puts "Staying: #{staying_rate}%." puts "Switching: #{switching_rate}%."
true
ed73ee1a33f81f9c7417a0f755b056aac5b6a313
Ruby
draftcode/git-panini
/lib/git/panini/real_repository.rb
UTF-8
4,569
2.5625
3
[ "MIT" ]
permissive
require 'rugged' module Git module Panini class RealRepository attr_reader :path def initialize(path) @path = path.expand_path end def panini_name "panini:#{path.basename('.git')}" end def ==(other) path == other.path end alias :eql? :== def hash path.hash end private def repo @repo ||= Rugged::Repository.new(path.to_s) end def flag_to_str(flags) index = worktree = ' ' flags.each do |flag| case flag when :index_new index = 'A' when :index_modified index = 'M' when :index_deleted index = 'D' when :worktree_new index = worktree = '?' when :worktree_modified worktree = 'M' when :worktree_deleted worktree = 'D' end end index + worktree end end module SharedRepositoryFactory def self.discover(path) repos = [] path.entries.each do |subpath| if subpath.extname == '.git' repos << SharedRepository.new(path + subpath) end end repos end end class LocalRepository < RealRepository def status lines = [] repo.status do |path, flags| unless flags.empty? lines << flag_to_str(flags) + " " + path end end lines end def branch_status local_branches = [] remote_branches = Hash.new { |h,k| h[k] = Hash.new } repo.branches.each do |branch| case branch.canonical_name when %r{\Arefs/heads/(.*)} local_branches << branch when %r{\Arefs/remotes/([^/]*)/(.*)} remote_branches[$1][$2] = branch else raise "Unknown branch: " + branch.canonical_name end end lines = [] local_branches.each do |branch| line = branch.name repo.remotes.each do |remote| remote_branch = remote_branches[remote.name][branch.name] if remote_branch line += " [#{remote.name} #{show_distance(repo.lookup(branch.target), repo.lookup(remote_branch.target))}]" else line += " [#{remote.name} NO BRANCH]" end end lines << line end lines end def fetch repo.remotes.each do |remote| begin remote.connect(:fetch) do |r| r.download end puts "Success: #{remote.url}" rescue Rugged::NetworkError puts "NetworkError: #{remote.url}" rescue Rugged::OSError puts "OSError: #{remote.url}" end end end def remotes h = Hash.new repo.remotes.each do |remote| h[remote.name] = Remote.new( remote.name, remote.url, remote.push_url, remote.fetch_refspecs, remote.push_refspecs, ) end h end def add_remote(remote) Rugged::Remote.add(repo, remote.name, remote.url) nil end private def show_distance(from_commit, to_commit) return '+0 -0' if from_commit == to_commit from_visited = {from_commit.oid => 0} to_visited = {to_commit.oid => 0} queue = [[from_commit, :from], [to_commit, :to]] until queue.empty? commit, tag = queue.shift if tag == :from if to_visited[commit.oid] return "+#{to_visited[commit.oid]} -#{from_visited[commit.oid]}" else distance = from_visited[commit.oid] commit.parents.each do |parent| from_visited[parent.oid] = distance + 1 queue.push([parent, tag]) end end elsif tag == :to if from_visited[commit.oid] return "+#{to_visited[commit.oid]} -#{from_visited[commit.oid]}" else distance = to_visited[commit.oid] commit.parents.each do |parent| to_visited[parent.oid] = distance + 1 queue.push([parent, tag]) end end end end end end class SharedRepository < RealRepository def to_remote Remote.new_from_url('panini', path.to_s) end end end end
true
e4ff6f1300de5e709473dce17c65fca978b2c2a1
Ruby
hashtegner/my-exercism-io
/ruby/binary/binary.rb
UTF-8
313
3.171875
3
[]
no_license
module BookKeeping VERSION = 2 end class Binary attr_reader :string def initialize(string) raise ArgumentError if string.match(/\D|[2-9]/) @string = string end def to_decimal string.chars.reverse.map.with_index do |char, index| char.to_i * (2 ** index) end.reduce(:+) end end
true
b8fc51443442117346df07dff2718aec087af256
Ruby
gbs4ever/sql-library-lab-online-web-ft-011419
/lib/querying.rb
UTF-8
1,235
2.65625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def select_books_titles_and_years_in_first_series_order_by_year "SELECT books.title, books.year FROM Books WHERE series_id = 1 ORDER BY year;" end def select_name_and_motto_of_char_with_longest_motto "SELECT Characters.name , Characters.motto FROM Characters ORDER BY length(motto) DESC LIMIT 1;" end def select_value_and_count_of_most_prolific_species "SELECT species ,COUNT(species) FROM Characters GROUP BY species ORDER BY COUNT(species) DESC LIMIT 1;" end def select_name_and_series_subgenres_of_authors "SELECT Authors.name ,Subgenres.name FROM Authors JOIN series ON Authors.id = series.author_id JOIN Subgenres ON Subgenres.id = series.subgenre_id ;" end def select_series_title_with_most_human_characters "SELECT series.title FROM Series JOIN Characters ON series.id = characters.series_id WHERE characters.species = 'human' GROUP BY characters.species,title ORDER BY COUNT(*) DESC LIMIT 1 ;" end def select_character_names_and_number_of_books_they_are_in "SELECT Characters.name, COUNT(books.id) FROM Characters JOIN Character_Books ON Characters.id = Character_Books.Character_id JOIN books ON books.id = Character_Books.book_id GROUP BY Characters.name ORDER BY COUNT(books.id) DESC ; " end
true
e0b95737c4dc46a6c11ff9a4155f7acbd4fc00fa
Ruby
linuxsable/rread
/app/models/activity.rb
UTF-8
1,963
2.609375
3
[]
no_license
class Activity < ActiveRecord::Base attr_accessor :user_name, :user_avatar, :target_name belongs_to :user belongs_to :target, :polymorphic => true # Activity Types ARTICLE_LIKED = 1 ARTICLE_READ = 2 SUBSCRIPTION_ADDED = 3 FRIENDSHIP_ADDED = 4 BLOG_LIKED = 5 def self.batch_add(users, activity_type, target) return false if users.blank? or activity_type.blank? or target.blank? inserts = [] users.each {|user| inserts.push "('#{user.id}', '#{activity_type}', '#{target.id}', '#{target.class}', UTC_TIMESTAMP())" } sql = "INSERT INTO activities (`user_id`, `activity_type`, `target_id`, `target_type`, `created_at`) VALUES #{inserts.join(", ")}" ActiveRecord::Base.connection.execute sql end def self.add(user, activity_type, target) return false if user.blank? or activity_type.blank? or target.blank? create!(:user => user, :activity_type => activity_type, :target => target) end # This appends the user_name to the result set. This field # is not actually stored in the DB. def self.feed(ids, count=20) result = self.where(:user_id => ids) .where("activity_type != ?", ARTICLE_READ) .order('created_at DESC') .limit(count) return result if result.empty? result.each do |item| # Append the user_name user = User.find(item.user_id) item.user_name = user.name item.user_avatar = user.avatar # Append the target name based on the target # if item.activity_type == ARTICLE_READ # item.target_name = Article.title_by_id(item.target_id) if item.activity_type == SUBSCRIPTION_ADDED blog_id = Subscription.blog_id_by_id(item.target_id) item.target_name = Blog.get_name_by_id(blog_id) elsif item.activity_type == FRIENDSHIP_ADDED friend_id = Friendship.friend_id_by_id(item.target_id) item.target_name = User.name_by_id(friend_id) end end end end
true
102294239406f4df82792552110e6da988933f1a
Ruby
hugobast/dentsubos-pool
/spec/temperature_store_spec.rb
UTF-8
858
2.90625
3
[]
no_license
require 'json' require_relative '../lib/temperature_store' class TestClock < DateTime def now self end end describe TemperatureStore do after do Redis.new.del(:test) end it "saves temperatures and conditions" do clock = TestClock.new(2012, 8, 17, 11, 34) temperatures = {pool: 79, outside: 24, condition: :cloudy} TemperatureStore.save(temperatures, :test, clock).should be true end context "reads in temperatures from the store" do it "gets only the latest temperatures" do [{m:34, t:80},{m:39, t:81},{m:44, t:82}].each do |value| clock = TestClock.new(2012, 8, 17, 11, value[:m]) temperature = {pool: value[:t], outside: 24, condition: 'cloudy'} TemperatureStore.save(temperature, :test, clock) end TemperatureStore.latest(:test)[:pool].should == 82 end end end
true
0533f1e8b7ddc6ad17cef5cfe5dfdf74d08dec34
Ruby
Wendyv510/square_array-onl01-seng-pt-100619
/square_array.rb
UTF-8
155
3.328125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array=[9,10,16,25] square_array.each do |numbers| puts "#{number} **" end def square_array=[1,2,3] square_array.collect{|x| (x**)} end
true
9d93fbf900f1c4927a2d8bcc8469bb91b3c699c9
Ruby
sato-s/EnhancedPrompt
/lib/enhanced_prompt/token/token.rb
UTF-8
2,421
2.640625
3
[ "MIT" ]
permissive
require_relative './emoji_writable' class EnhancedPrompt::Prompt # Responsible for delegating instructions to proper instance. # And convert into proper string after receiving Integer, AddrInfo or something else class Token include EmojiWritable # Delegating to Network resource def ipv4 _network.ipv4 ? _network.ipv4.inspect_sockaddr : '' end def ipv6 _network.ipv6 ? _network.ipv6.inspect_sockaddr : '' end def global_ipv4 _network.global_ipv4 ? _network.global_ipv4.inspect_sockaddr : '' end def global_ipv6 _network.global_ipv6 ? _network.global_ipv6.inspect_sockaddr : '' end def hostname_full _network.hostname_full || '' end def hostname _network.hostname || '' end # Delegating to User resource def username _user.username || '' end def groupname _user.groupname || '' end def usernames _user.usernames.join(',') end def other_user_names _user.other_usernames.join(',') end def other_user_names_if_exists _user.other_users_count == 0 ? '' : _user.other_usernames.join(',') end def users_count _user.users_count.to_s end # TODO : should be method missing to ***_scale def users_count_scale1 vertical_bar_scale(_user.users_count) end def other_users_count _user.other_users_count.to_s end def login_count _user.login_count.to_s end def my_login_count _user.my_login_count.to_s end def other_login_count _user.other_login_count.to_s end def uid _user.uid.to_s || "No #{__method__}" end def gid _user.gid.to_s || "No #{__method__}" end # Delegating to Dir resources def dir_abbreviated1(limit=40) _dir.dir_abbreviated1(limit).to_s || "" end def dir_full _dir.dir_full.to_s end def git _git.git end # Delegating to Time resources def time1 _time.time1.to_s end private def _git @_git ||= Git.new(_dir.dir_full) end def _network @_network ||= Network.new end def _user @_user ||= User.new end def _dir @_dir ||= Dir.new end def _time @_time ||= Time.new end def method_missing(name,*args) puts "No such token. " raise super end end end
true
c34255214c7ebd63ea7263aa96e2c8e12dd0eb82
Ruby
veliancreate-zz/Ruby-School
/new ruby/hmmm.rb
UTF-8
1,469
2.859375
3
[]
no_license
single_num = ones_method(thousands_mod, places) tens_num = tens_method(thousands_mod, places) hundreds_num = hundreds_method(thousands_mod, places) if thousands_mod == 0 if thousands_div >= 100 return_string = hundreds_thou + " thousand" elsif thousands_div < 100 && thousands_div >= 10 return_string = tens_thou + " thousand" elsif thousands_div < 10 return_string = single_thou + " thousand" end elsif thousands_mod < 10 && thousands_mod > 0 if thousands_div >= 100 return_string = hundreds_thou + " thousand and " + single_num elsif thousands_div < 100 && thousands_div >= 10 return_string = tens_thou + " thousand and " + single_num elsif thousands_div < 10 return_string = single_thou + " thousand and " + single_num end elsif thousands_mod > 10 && thousands_mod < 100 if thousands_div >= 100 return_string = hundreds_thou + " thousand and " + tens_num elsif thousands_div < 100 && thousands_div >= 10 return_string = tens_thou + " thousand and " + tens_num elsif thousands_div < 10 return_string = single_thou + " thousand and " + tens_num end elsif thousands_mod >= 100 if thousands_div >= 100 return_string = hundreds_thou + " thousand and " + hundreds_num elsif thousands_div < 100 && thousands_div >= 10 return_string = tens_thou + " thousand and " + hundreds_num elsif thousands_div < 10 return_string = single_thou + " thousand, " + hundreds_num end end return_string
true
ebc30863f458105e5e9cd626404449ffc5ce6f36
Ruby
kentgray/Portfolio-KentGray
/Ruby/Practice Apps/numofmoos.rb
UTF-8
113
3.171875
3
[]
no_license
def sayMoo numberOfMoos puts 'mooooooo...'*numberOfMoos 'yellow submarine' end x = sayMoo 2 puts x
true
303a2f06c5b554bdf56664c440429f8d153c7379
Ruby
marcelomst/ethereum_voting_example
/app/services/vote_service.rb
UTF-8
425
2.640625
3
[]
no_license
class VoteService def initialize(key, meals, address = nil) @key = key @address = address || Voting.last.contract_address @meals = meals end def call vote end private def vote voting_contract = Contract::GetService.new(@address).call signed_voting_contract = Contract::SignService.new(voting_contract, @key).call signed_voting_contract.transact.vote_for_meal_type(@meals) end end
true
eff59720907d6fa7a62c64e3a531b71660bee0c4
Ruby
Tempate/Advent-of-Code-2020
/day7/main.rb
UTF-8
1,256
3.625
4
[]
no_license
file = File.open("input.txt") $lines = file.readlines.map(&:chomp) def parse_input() bags = {} entry_pattern = Regexp.compile('^(.+) bags contain (.+)\.$') items_pattern = Regexp.compile('^(\d+) (.+) (bag|bags)$') $lines.each do |line| name, items = entry_pattern.match(line)[1..2] bags[name] = [] if items == "no other bags" next end items.split(", ").each do |item| info = items_pattern.match(item) bags[name].push({ "amount" => info[1].to_i, "type" => info[2] }) end end return bags end def bag_contains_package(bag, package) $bags[bag].any? { |sub_bag| sub_bag["type"] == package || bag_contains_package(sub_bag["type"], package) } end def count_bags_that_contain_package(package) $bags.keys().select { |bag| bag_contains_package(bag, package) }.length() end def count_packages_for_bag(bag) $bags[bag].sum { |bag_info| bag_info["amount"] * (count_packages_for_bag(bag_info["type"]) + 1) } end $bags = parse_input() puts "Part 1: " + count_bags_that_contain_package("shiny gold").to_s puts "Part 2: " + count_packages_for_bag("shiny gold").to_s
true
5184e23654e1c131c8b99f15f23c6d9b617b297f
Ruby
superhighfives/fox-server
/lib/gif_cache.rb
UTF-8
329
3.09375
3
[ "CC-BY-4.0", "CC-BY-3.0" ]
permissive
class GifCache def initialize(memcached_client) @client = memcached_client end def get(lyric) @client.get cache_key(lyric) end def set(lyric, gif) @client.set cache_key(lyric), gif end def delete(lyric) @client.delete cache_key(lyric) end def cache_key(lyric) lyric.id.to_s end end
true
69481716e41dbbcdffeddd17bdf634b927b5f47a
Ruby
SupernovaTitanium/Ruby-example
/ex39_test.rb
UTF-8
1,153
3.921875
4
[]
no_license
require './dict.rb' #create a mapping of state to abbreviation states=Dict.new() Dict.set(states,'Oregon','OR') Dict.set(states, 'Florida', 'FL') Dict.set(states, 'California', 'CA') Dict.set(states, 'New York', 'NY') Dict.set(states, 'Michigan', 'MI') # create a basic set of states and some cities in them cities = Dict.new() Dict.set(cities, 'CA', 'San Francisco') Dict.set(cities, 'MI', 'Detroit') Dict.set(cities, 'FL', 'Jacksonville') Dict.set(cities,'NY','New York') Dict.set(cities,'OR','Portland') puts '_'*10 puts "NY State has: #{Dict.get(cities, 'NY')}" puts "OR State has: #{Dict.get(cities, 'OR')}" puts '_'*10 puts "Michigan's abbreviation is: #{Dict.get(states, 'Michigan')}" puts "Florida's abbreviation is: #{Dict.get(states, 'Florida')}" puts '_'*10 puts "Michigan has: #{Dict.get(cities,Dict.get(states,'Michigan'))}" puts "Florida has: #{Dict.get(cities, Dict.get(states, 'Florida'))}" puts '_' *10 Dict.list(states) puts '-' * 10 Dict.list(cities) puts '_' *10 state=Dict.get(states, 'Texas') if !state puts "Sorry, no Texas." end city=Dict.get(cities,'TX','Does Not Exist') puts "The city for the state 'TX' is: #{city}"
true
c06a327d550e4eeb6c80cf5d04c64d26217b7881
Ruby
solyarisoftware/blomming_api
/blomming_api/lib/blomming_api/oauth_endpoint.rb
UTF-8
2,581
2.59375
3
[ "MIT" ]
permissive
# encoding: utf-8 require 'multi_json' require 'rest_client' module BlommingApi module OauthEndpoint # # authentication request # # => to get initial OAuth access token: # # authenticate :initialize # # => to get refresh token in case of OAuth access token expired # # authenticate :refresh # def authenticate(type=:initialize) url = api_url('/oauth/token') services = @services.downcase.to_sym # client_id and client_secret are required for any kind of request auth_params = { client_id: @client_id, client_secret: @client_secret } # authentication type must be :initalize or :refresh if type == :initialize # authentication for services :buy or :sell if services == :buy @grant_type = "client_credentials" auth_params.merge! grant_type: @grant_type elsif services == :sell @grant_type = "password" auth_params.merge! \ grant_type: @grant_type, username: @username, password: @password else raise"FATAL: config value for: services (#@services): invalid" end elsif type == :refresh @grant_type = "refresh_token" auth_params.merge! \ grant_type: @grant_type, refresh_token: @refresh_token else raise "FATAL: incorrect authentication type (#{type})" end data = feed_or_retry do RestClient.post url, auth_params end #puts_response_header(__method__, data) if @verbose_access_token #puts_access_token(access_token) if @verbose # assign all token info to instance variables @token_type = data["token_type"] @expires_in = data["expires_in"] @refresh_token = data["refresh_token"] @access_token = data["access_token"] end private :authenticate def authentication_details "\n" + " config file: #@config_file\n" + " services: #{@services}\n" + " grant_type: #{@grant_type}\n" + " username: #{@username}\n" + " password: #{@password}\n" + " client_id: #{@client_id}\n" + "client_secret: #{@client_secret}\n" + "\n" + " token_type: #{@token_type}\n" + " access_token: #{@access_token}\n" + " expires_in: #{@expires_in}\n" + "refresh_token: #{@refresh_token}\n" + "\n" end public :authentication_details end end
true
35852f97dc2de0f91e162e91e3e7f301ec5b0df9
Ruby
ethanjurman/GWACI
/Grid.rb
UTF-8
1,167
4.0625
4
[]
no_license
#Class: Grid, class that represents a board of a givin size class Grid def initialize(name, sizeX=8, sizeY=8) #name: name of the board #sizeX: size of the X axis (a..z); defaults to 8 #sizeY: size of the Y axis (1..26); defaults to 8 @name = name @sizeX = sizeX @sizeY = sizeY @grid = {} #populate array for i in (0..sizeX-1) key = (i+97).chr() @grid.merge!(key=>{}) for j in (0..sizeY-1) @grid[key].merge!(j.to_s() => nil) end end end def move(pos1, pos2) #method to move a piece from one position to the other #pos1: string in AN notation, first position (contains piece) #pos2: string in AN notation, second position (must be empty) @grid[pos2[0]][pos2[1]] = @grid[pos1[0]][pos1[1]] @grid[pos1[0]][pos1[1]] = nil end def addPiece(piece, pos) #method to place a piece onto the board #piece: piece object #pos: string in AN notation, position piece will be placed on (must be empty) @grid[pos[0]][pos[1]] = piece end end
true
29c012ad336afd16d816e23a8a20fce3d2e003d0
Ruby
chintas1/badges-and-schedules-001-prework-web
/conference_badges.rb
UTF-8
469
3.84375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. def badge_maker(name) "Hello, my name is #{name}." end def batch_badge_creator(attendees) (1..(attendees.size)).collect{|i| badge_maker(attendees[i-1])} end def assign_rooms(speakers) (1..(speakers.size)).collect{|i| "Hello, #{speakers[i-1]}! You'll be assigned to room #{i}!"} end def printer(names) batch_badge_creator(names).each do |badge| puts badge end assign_rooms(names).each do |greeting| puts greeting end end
true
bd6741b1d1d37d2009a93ba0f055de152aefa02f
Ruby
thomaspouncy/Fred
/lib/fred/body_types/nxt_body.rb
UTF-8
914
2.578125
3
[]
no_license
require 'ruby_nxt' class NXTBody < Body DEFAULT_TOUCH_PORT = 1 DEFAULT_COLOR_PORT = 3 DEFAULT_ULTRASONIC_PORT = 4 attr_reader :nxt # Tell ruby-nxt to give us bluetooth details $DEBUG = true def initialize(touch_port = DEFAULT_TOUCH_PORT,color_port = DEFAULT_COLOR_PORT,ultrasonic_port = DEFAULT_ULTRASONIC_PORT) @nxt = NXTComm.new("/dev/tty.NXT-DevB") sensory_channels = { :touch => SensoryChannel.new("touch",Commands::TouchSensor.new(nxt,touch_port),:raw_value), :color => SensoryChannel.new("color",Commands::ColorSensor.new(nxt,color_port),:current_color), :ultrasonic => SensoryChannel.new("ultrasonic",Commands::UltrasonicSensor.new(nxt,ultrasonic_port),:distance) } super(sensory_channels) end def die unless sensory_channels[:color].nil? sensory_channels[:color].sensor.light_sensor end nxt.close super end end
true
dfe9f8860f958f21c15529900c966b6e38aa8c49
Ruby
yohei-ota/furima-36556
/spec/models/user_spec.rb
UTF-8
6,007
2.609375
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do before do @user = FactoryBot.build(:user) end describe "ユーザー新規登録" do context "新規登録できるとき" do it "全ての項目が存在すれば登録できる" do expect(@user).to be_valid end it "passwordとpassword_confirmationが6文字以上で英数字混合なら登録できる" do @user.password = "123abc" @user.password_confirmation = "123abc" expect(@user).to be_valid end it "first_nameに漢字かひらがなかカタカナが存在すれば登録できる" do @user.first_name = "やまだ" expect(@user).to be_valid end it "last_nameに漢字かひらがなかカタカナが存在すれば登録できる" do @user.last_name = "りくたろう" expect(@user).to be_valid end it "first_name_kanaがカタカナであれば登録できる" do @user.first_name_kana = "ヤマダ" expect(@user).to be_valid end it "last_name_kanaがカタカナであれば登録できる" do @user.last_name_kana = "リクタロウ" expect(@user).to be_valid end end context "新規登録できないとき" do it "nicknameが空では登録できない" do @user.nickname = "" @user.valid? expect(@user.errors.full_messages).to include("Nickname can't be blank") end it "emailが空では登録できない" do @user.email = "" @user.valid? expect(@user.errors.full_messages).to include("Email can't be blank") end it "emailに@が含まれていなければ登録できない" do @user.email = "abc" @user.valid? expect(@user.errors.full_messages).to include("Email is invalid") end it "passwordが空では登録できない" do @user.password = "" @user.valid? expect(@user.errors.full_messages).to include("Password can't be blank") end it "passwordとpassword_confirmationが不一致では登録できない" do @user.password = "123abc" @user.password_confirmation = "456def" @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password") end it "first_nameが空では登録できない" do @user.first_name = "" @user.valid? expect(@user.errors.full_messages).to include("First name can't be blank") end it "last_nameが空では登録できない" do @user.last_name = "" @user.valid? expect(@user.errors.full_messages).to include("Last name can't be blank") end it "first_name_kanaが空では登録できない" do @user.first_name_kana = "" @user.valid? expect(@user.errors.full_messages).to include("First name kana can't be blank") end it "last_name_kanaが空では登録できない" do @user.last_name_kana = "" @user.valid? expect(@user.errors.full_messages).to include("Last name kana can't be blank") end it "birthdayが空では登録できない" do @user.birthday = "" @user.valid? expect(@user.errors.full_messages).to include("Birthday can't be blank") end it "重複したemailが存在すれば登録できない" do @user.save another = FactoryBot.build(:user) another.email = @user.email another.valid? expect(another.errors.full_messages).to include("Email has already been taken") end it "passwordが5文字以下では登録できない" do @user.password = "123ab" @user.password_confirmation = "123ab" @user.valid? expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)") end it "passwordが数字のみでは登録できない" do @user.password = "123456" @user.password_confirmation = "123456" @user.valid? expect(@user.errors.full_messages).to include("Password には半角英数字で入力してください") end it "passwordが英字のみでは登録できない" do @user.password = "abcdef" @user.password_confirmation = "abcdef" @user.valid? expect(@user.errors.full_messages).to include("Password には半角英数字で入力してください") end it "passwordが全角だと登録できない" do @user.password = "123abc" @user.password_confirmation = "123abc" @user.valid? expect(@user.errors.full_messages).to include("Password には半角英数字で入力してください") end it "first_nameに漢字かひらがなかカタカナが存在しないと登録できない" do @user.first_name = "yamada" @user.valid? expect(@user.errors.full_messages).to include("First name には漢字・ひらがな・カタカナを入力してください") end it "last_nameに漢字かひらがなかカタカナが存在しないと登録できない" do @user.last_name = "rikutarou" @user.valid? expect(@user.errors.full_messages).to include("Last name には漢字・ひらがな・カタカナを入力してください") end it "first_name_kanaがカタカナ以外だと登録できない" do @user.first_name_kana = "山田" @user.valid? expect(@user.errors.full_messages).to include("First name kana にはカタカナを入力してください") end it "last_name_kanaがカタカナ以外だと登録できない" do @user.last_name_kana = "陸太郎" @user.valid? expect(@user.errors.full_messages).to include("Last name kana にはカタカナを入力してください") end end end end
true
3d41b0a9bc1618518ef851a0377590bd96772d73
Ruby
koenhandekyn/adventofcode
/2019/d04/secure_container.rb
UTF-8
795
3.375
3
[]
no_license
def assert_eq(v1, v2) raise "expected #{v2}, but got #{v1}" unless v1 == v2 end lower = 206938 upper = 679128 candidates = (0..9).map do |d1| (d1..9).map do |d2| (d2..9).map do |d3| (d3..9).map do |d4| (d4..9).map do |d5| (d5..9).map do |d6| [d1,d2,d3,d4,d5,d6].join("") end end end end end end .flatten .select { |c| (0..4).map { |i| c[i] == c[i+1] }.any? } .select { |c| i = c.to_i; i >= lower && i <= upper } puts "initial candidates: #{candidates.size}" def c3(c) (0..4).map { |i| c[i-1] != c[i] && c[i] == c[i+1] && c[i+1] != c[i+2] }.any? end assert_eq c3("112233"), true assert_eq c3("123444"), false assert_eq c3("111122"), true candidates = candidates.select { |c| c3(c) } puts "remaining candidates: #{candidates.size}"
true
f9e7aef924d9a36c5f3b684ee33e4600a5c39cdf
Ruby
leafy-metrics/leafy
/spec/meter_spec.rb
UTF-8
878
2.640625
3
[ "Apache-2.0" ]
permissive
require 'leafy/core/meter' RSpec.describe Leafy::Core::Meter do let(:clock) do clock = Leafy::Core::Clock.new def clock.tick @ticks ||= [0, 0] + [10000000000] * 10 @ticks.shift end clock end let(:meter) { Leafy::Core::Meter.new(clock) } it 'starts out with no rates or count' do expect(meter.count).to eq 0 expect(meter.mean_rate).to eq 0 expect(meter.one_minute_rate).to eq 0 expect(meter.five_minute_rate).to eq 0 expect(meter.fifteen_minute_rate).to eq 0 end it 'marksEventsAndUpdatesRatesAndCount' do meter.mark meter.mark(2) expect(meter.mean_rate).to eq 0.3 expect(Number[meter.one_minute_rate]).to eql Number[0.1840, 0.1] expect(Number[meter.five_minute_rate]).to eql Number[0.1966, 0.1] expect(Number[meter.fifteen_minute_rate]).to eql Number[0.1988, 0.1] end end
true
5f7826b77a579a325a83ad90ec3411094a62728b
Ruby
kevinfalank-devbootcamp/web_flashcards
/app/controllers/user.rb
UTF-8
1,328
2.546875
3
[]
no_license
post '/login' do #Validates username/password. Redirects to /decks if successful. # params[:login].inspect user_id = User.login(params[:login]) if user_id > 0 session[:user_id] = user_id redirect to '/decks' else redirect "/" end end post '/users/create' do #Generates user from form input. #Sets user as logged in. #Redirects to 'select deck' /decks new_user = params[:new_user] user = User.create(user_name: new_user[:user_name], password: new_user[:password], email: new_user[:email], name: new_user[:name]) session[:user_id] = user.id redirect to '/decks' end get '/users/create' do #Generates user form for new user. erb :create_user end get '/users/logout' do #Logs user out. #Redirects to 'login' / # session.delete(:user_id) redirect to '/' end get '/users/:user_id' do #This is the 'profile' page. Displays history of rounds played. @profile_data = User.get_rounds_by_user(current_user.id) erb :profile end get '/login/error' do #Where you are redirected when POST /login route has problem with your info. #Takes your info as query string so we can display it + error end get '/signup/error' do #Where you are redirected when POST /users/create route has problem with your info. #Takes your info as query string so we can display it + error end
true
de8837db04c3f46c7ee3c364886bca6d2e78807a
Ruby
zklamm/ruby-small-problems
/exercises/second_pass/easy_01/04.rb
UTF-8
779
4.5625
5
[]
no_license
# Write a method that counts the number of occurrences of each element in a given array. # input: array # output: print the count of each element # assume: # examples: given # logic: iterate thru array and create a hash containing elements as keys and instances # as a count def count_occurrences(ary) count = {} ary.each do |elem| if count[elem] count[elem] += 1 else count[elem] = 1 end end count.each do |key, value| puts "#{key} => #{value}" end end vehicles = ['car', 'car', 'truck', 'car', 'SUV', 'truck', 'motorcycle', 'motorcycle', 'car', 'truck'] count_occurrences(vehicles) # Once counted, print each element alongside the number of occurrences. # Expected output: # car => 4 # truck => 3 # SUV => 1 # motorcycle => 2
true
8072dc36c9265b27b86176bd0ece368229d19f2d
Ruby
pjfitzgibbons/config-reader
/spec/config_reader_spec.rb
UTF-8
2,895
2.921875
3
[ "MIT" ]
permissive
require 'spec_helper' require 'config_reader' describe ConfigReader do let(:sample) { ' # This is what a comment looks like, ignore it # All these config lines are valid host = test.com server_id=55331 server_load_alarm=2.5 user= user # comment can appear here as well verbose =true test_mode = on debug_mode = off log_file_path = /tmp/logfile.log send_notifications = yes ' } subject { ConfigReader.new(sample) } it 'should read the lines' do expect(subject.raw_lines.count).to eq(14) end it 'should read the lines without comments' do expect(subject.lines.count).to eq(9) end it 'should parse keys' do expect(subject.keys).to eq( %w/host server_id server_load_alarm user verbose test_mode debug_mode log_file_path send_notifications / ) end it 'should parse all values' do expect(subject.config).to include({ 'host' => 'test.com', 'server_id' => 55331, 'server_load_alarm' => 2.5, 'user' => 'user', 'verbose' => true, 'test_mode' => true, 'debug_mode' => false, 'log_file_path' => '/tmp/logfile.log', 'send_notifications' => true }) end describe "comment rx" do it 'should filter lines starting hash' do expect(["# comment"].grep(ConfigReader::RX_COMMENT)).to eq(["# comment"]) end it 'should filter empty lines' do lines = ['data-line', '', 'data-line', ' '] expect(lines.grep(ConfigReader::RX_COMMENT)).to eq(['', ' ']) end end describe "parse line" do it 'should split =' do expect(subject.parse(["key=value"])).to eq({ 'key' => 'value' }) end end describe "value parsing" do it 'should parse values into bool' do %w/true yes on/.each { |v| expect(subject.value_parse(v)).to eq true } %w/false no off/.each { |v| expect(subject.value_parse(v)).to eq false } end it 'should parse integers, floats' do expect(subject.value_parse('55331')).to eq 55331 expect(subject.value_parse('0')).to eq 0 expect(subject.value_parse('-55331')).to eq -55331 expect(subject.value_parse('0.0')).to eq 0.0 expect(subject.value_parse('2.5')).to eq 2.5 expect(subject.value_parse('0.1')).to eq 0.1 expect(subject.value_parse('-2.2')).to eq -2.2 end it 'should parse string values' do expect(subject.value_parse("some-string")).to eq "some-string" expect(subject.value_parse("domain.tld")).to eq "domain.tld" end end end
true
58e787d20add47cf8c32051627221b03b0c178c8
Ruby
waterfield/testables
/lib/scope_machine.rb
UTF-8
807
3.109375
3
[ "MIT" ]
permissive
# The +state_machine+ gem is really cool, but I kind of wish # each of the defined states would make a scope. So if you # had for instance :queued and :finished as states, you would # be able to do # # Model.queued # => Model.where(state: 'queued') # # This module makes that happen by putting an after filter # on the +state_machine+ class method that adds all the scopes. module ScopeMachine def self.included(base) class << base def state_machine_with_scopes *args, &block state_machine_without_scopes(*args, &block).tap do |machine| machine.states.map(&:value).each do |state| next if respond_to? state scope state, where(state: state) end end end alias_method_chain :state_machine, :scopes end end end
true
5259c41ab797dd9ac7ed472b6f0feab1a70cdf6b
Ruby
juanger/typing_trainer
/lib/typing_trainer/level_generator.rb
UTF-8
1,395
3.484375
3
[ "MIT" ]
permissive
require 'contemporary_words' require "typing_trainer/level" require "typing_trainer/keyboard_layout" class TypingTrainer::LevelGenerator SENCENCES_PER_LEVEL = 3 WORDS_PER_SENTENCE = 8 def self.generate(level: nil, letters: nil, layout: nil) throw "You need to specify a layout" unless layout throw "No level or letters were provided to generate a Game level :(" unless level || letters layouts = TypingTrainer::KeyboardLayout::LAYOUTS layout_letters = layouts[layout]::LETTER_PROGRESSION if letters letters = letters.join('').downcase end letters ||= layout_letters.slice(0, level) sentences = self.new(letters).generate_sentences(SENCENCES_PER_LEVEL) TypingTrainer::Level.new(number: level, letters: letters, sentences: sentences, layout: layout) end def initialize(letters) @letters = letters.split(//) @level_pattern = /^[#{letters}]+$/ @words = initialize_words end def initialize_words words = ContemporaryWords.all.filter { |word| @level_pattern.match?(word) } while words.size < WORDS_PER_SENTENCE words << self.generate_word end words end def generate_sentences(count) sentences = [] count.times { sentences << @words.sample(WORDS_PER_SENTENCE).join(' ') + ' ' } sentences end def generate_word (@letters * 10).sample(rand(5) + 1).join('') end end
true
c4a61585a56c07f30550938c474c91b036822a19
Ruby
aljurgens/ruby_exercises
/euler.rb
UTF-8
153
3.5625
4
[]
no_license
puts 'Sum of all multiples of 3 or 5 below 1000:' sum = 0 i = 0 while i < 1000 if i % 3 == 0 || i % 5 == 0 sum += i end i += 1 end puts sum
true
5849c5f4d98e139af1ee2692736a2c850519253d
Ruby
evelinawest/learn_to_program_book
/Chapter6/rand.rb
UTF-8
109
2.671875
3
[]
no_license
puts rand puts rand puts rand (10) puts rand (100) puts rand (1) puts rand (1) puts rand (1) puts rand (1.0)
true
369c3ba626c7e7f475c6de6af66938153ea25938
Ruby
walterio212/aydoo2017ruby-TpFinal
/Calendario/spec/validador_calendario_spec.rb
UTF-8
976
2.578125
3
[]
no_license
require 'rspec' require_relative '../model/calendario' require_relative '../model/validador_calendario' require_relative '../model/calendario_nombre_existente_error' require_relative '../model/calendario_sin_nombre_error' describe 'ValidadorCalendario' do it 'crearCalendario nombre existente error' do persistorDouble = double('Persistor', :existe_calendario? => true) calendario = Calendario.new("calendario 1") validador = ValidadorCalendario.new(persistorDouble) expect{ validador.validar_crear_calendario(calendario) }. to raise_error(CalendarioNombreExistenteError) end end describe 'ValidadorCalendario' do it 'crearCalendario nombre vacio error' do persistorDouble = double('Persistor', :existe_calendario? => false) calendario = Calendario.new("") validador = ValidadorCalendario.new(persistorDouble) expect{ validador.validar_crear_calendario(calendario) }. to raise_error(CalendarioSinNombreError) end end
true
5aa765e4ba5580121fdf590c21d567f01519258f
Ruby
ejf89/the-bachelor-todo-web-040317
/lib/bachelor.rb
UTF-8
734
3.078125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def get_first_name_of_season_winner(data, season) winner = "" data[season].each do |stats, value| if stats["status"] == "Winner" winner = stats["name"].split(" ")[0] end end winner end def get_contestant_name(data, occupation) name = "" data.each do |season, person| person.each do |stats, value| if stats["occupation"] == occupation name = stats["name"] end end end name end def count_contestants_by_hometown(data, hometown)exit # code here end def get_occupation(data, hometown) # code here end def get_average_age_for_season(data, season) # code here end
true
c07d0a2f01221f4cdfaee0552b39a4120cc09bc6
Ruby
wlffann/black_thursday
/test/items_price_analyst_test.rb
UTF-8
1,326
2.84375
3
[]
no_license
require_relative 'test_helper' require_relative '../lib/items_price_analyst' class ItemsPriceAnalystTest < Minitest::Test attr_reader :engine, :analyst def setup @engine = SalesEngine.from_csv({:items => './test/assets/test_items.csv', :merchants => './test/assets/test_merchants.csv', :invoices => "./test/assets/test_invoices.csv", :invoice_items => "./test/assets/test_invoice_items.csv", :transactions => "./test/assets/test_transactions.csv", :customers => "./test/assets/test_customers.csv"}) @analyst = ItemsPriceAnalyst.new(engine) end def test_it_finds_average_price_of_one_merchant_in_analyst_class assert_equal 115.66, analyst.average_item_price_for_merchant(55).to_f end def test_analyst_finds_average_average_price_per_merchant_in_analyst_class assert_equal 100.42, analyst.average_average_price_per_merchant.to_f end def test_it_finds_golden_items_of_all_items_in_analyst_class golden_array = ["Solid Cherry Trestle Table : 5500.0"] found_items = analyst.golden_items.map { |item| "#{item.name} : #{item.unit_price_as_dollars}"} assert_equal golden_array, found_items end end
true