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
c305a979b572f811576120caee56a232751a9d3d
Ruby
snakerabbit/W2D1
/skeleton/chess/display.rb
UTF-8
832
3.5
4
[]
no_license
require 'colorize' require_relative 'board' require_relative 'cursor' class Display def initialize (board) @board = board @cursor = Cursor.new([0,0], board) end def build_grid @board.grid.each.map.with_index do |row, i| build_row(row, i) end end def build_row(row, i) row.map.with_index do |piece, j| color_options = colors_for(i, j) piece.to_s.colorize(color_options) end end def colors_for(i, j) if [i, j] == @cursor.cursor_pos && @cursor.selected bg = :light_green elsif [i, j] == @cursor.cursor_pos bg = :light_red elsif (i + j).odd? bg = :light_blue else bg = :light_yellow end {background: bg} end def render rendered_grid = build_grid rendered_grid.each do |row| puts row.join end end end
true
4809d1e399cc1871ef8d69219b180cf56091f458
Ruby
odelevingne/booking
/spec/seat_spec.rb
UTF-8
339
2.75
3
[]
no_license
require 'seat' describe 'Seat' do let(:seat) { Seat.new } let(:booked_seat) { Seat.new.book! } it 'is empty when created' do expect(seat).not_to be_booked end it 'can be booked' do expect(booked_seat).to be_booked end it 'can be unbooked' do booked_seat.unbook! expect(seat).not_to be_booked end end
true
ea7ca98e0685197f3106ebe8fa9a32dd3b05e1a8
Ruby
jj54321/playlister-sinatra-v-000
/.bundle/gems/httpclient-2.5.3.3/bin/jsonclient
UTF-8
2,834
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain", "Ruby" ]
permissive
#!/usr/bin/env ruby # httpclient shell command. # # Usage: 1) % httpclient get https://www.google.co.jp/ q=ruby # Usage: 2) % httpclient # # For 1) it issues a GET request to the given URI and shows the wiredump and # the parsed result. For 2) it invokes irb shell with the binding that has a # HTTPClient as 'self'. You can call HTTPClient instance methods like; # > get "https://www.google.co.jp/", :q => :ruby require 'httpclient' require 'json' module HTTP class Message # Returns JSON object of message body alias original_content content def content if JSONClient::CONTENT_TYPE_JSON_REGEX =~ content_type JSON.parse(original_content) else original_content end end end end # JSONClient provides JSON related methods in addition to HTTPClient. class JSONClient < HTTPClient CONTENT_TYPE_JSON_REGEX = /(application|text)\/(x-)?json/i attr_accessor :content_type_json class JSONRequestHeaderFilter attr_accessor :replace def initialize(client) @client = client @replace = false end def filter_request(req) req.header['content-type'] = @client.content_type_json if @replace end def filter_response(req, res) @replace = false end end def initialize(*args) super @header_filter = JSONRequestHeaderFilter.new(self) @request_filter << @header_filter @content_type_json = 'application/json; charset=utf-8' end def post(uri, *args, &block) @header_filter.replace = true request(:post, uri, jsonify(argument_to_hash(args, :body, :header, :follow_redirect)), &block) end def put(uri, *args, &block) @header_filter.replace = true request(:put, uri, jsonify(argument_to_hash(args, :body, :header)), &block) end private def jsonify(hash) if hash[:body] && hash[:body].is_a?(Hash) hash[:body] = JSON.generate(hash[:body]) end hash end end METHODS = ['head', 'get', 'post', 'put', 'delete', 'options', 'propfind', 'proppatch', 'trace'] if ARGV.size >= 2 && METHODS.include?(ARGV[0]) client = JSONClient.new client.debug_dev = STDERR $DEBUG = true require 'pp' pp client.send(*ARGV) exit end require 'irb' require 'irb/completion' class Runner def initialize @httpclient = HTTPClient.new end def method_missing(msg, *a, &b) debug, $DEBUG = $DEBUG, true begin @httpclient.send(msg, *a, &b) ensure $DEBUG = debug end end def run IRB.setup(nil) ws = IRB::WorkSpace.new(binding) irb = IRB::Irb.new(ws) IRB.conf[:MAIN_CONTEXT] = irb.context trap("SIGINT") do irb.signal_handle end begin catch(:IRB_EXIT) do irb.eval_input end ensure IRB.irb_at_exit end end def to_s 'HTTPClient' end end Runner.new.run
true
d6333686c7f62b2f26112843509ddf78020f52f6
Ruby
suhlig/wordclock
/exe/wordclock
UTF-8
810
2.5625
3
[]
no_license
#!/usr/bin/env ruby # frozen_string_literal: true $LOAD_PATH.unshift File.expand_path('../lib', __dir__) require 'word_clock/clock_24' require 'word_clock/xkcd_color_sampler' require 'word_clock/color_picker' require 'faderuby' if ARGV.size.zero? time = Time.now elsif ARGV.size == 1 time = Time.parse(ARGV.first) else warn "Unknown arguments #{ARGV}" exit 1 end clock = WordClock::Clock24.new(time) client = FadeRuby::Client.new( ENV.fetch('OPC_HOST', 'localhost'), ENV.fetch('OPC_PORT', '7890').to_i ) strip = FadeRuby::Strip.new(18 * 16) strip.set_all(r: 0, g: 0, b: 0) client.write(strip) color_picker = WordClock::ColorPicker.new(WordClock::XkcdColorSampler.new) clock.pixels.each do |i| color = color_picker.choose(time) strip.pixels[i].set(**color.to_h) end client.write(strip)
true
bb89b52f3a2aac110decb5eebb024e9a919be40c
Ruby
scel-hawaii/control-tower
/jobs/status_report/status_report.rb
UTF-8
2,239
2.859375
3
[]
no_license
# Status report of the current REIS services require 'pg' require 'active_support/all' require 'pp' class SensorReport def initialize() end def execute_database(command) conn = PGconn.open(:host=> 'localhost', :dbname => 'control_tower', :user=>'control_tower', :password=>'password') res = conn.exec(command) output = []; res.each do |row| output << row end conn.close() return output end def get_weatherbox_addr() q = 'SELECT DISTINCT address FROM outdoor_env' res = execute_database(q) output = [] res.each do |row| output << row["address"] end return output end def get_number_samples(address) q = "SELECT COUNT(*) FROM outdoor_env WHERE (uptime_ms IS NOT NULL AND address=#{address})" res = execute_database(q) return res[0]["count"] end def get_latest_sample(address) q = "SELECT * FROM outdoor_env WHERE address=#{address} ORDER BY db_time DESC LIMIT 1" res = execute_database(q) output = []; res.each do |row| output << row end return output end def get_latest_sample_time(address) sample = get_latest_sample(address) return Time.parse(sample[0]["db_time"]) end def check_boxes() box_addrs = get_weatherbox_addr puts "Box \t | Packets \t | Last Time Recv \t\t | Min Since\t | Status \t |" puts "--------------------------------------------------------------------------------------------\n" box_addrs.each do |box| num_packets = get_number_samples(box) current_time = Time.now() last_box_time = get_latest_sample_time(box) time_difference = current_time - last_box_time if(time_difference < 3*60) status = "GOOD" else status = "BAD" end puts "#{box} \t | #{num_packets} \t | #{last_box_time} \t | #{(time_difference/60).round(2)} \t | #{status} \t |" end end def print_splash() puts "====================================================" puts "SCEL Weatherbox Status Report Script" puts "Script run date: #{Time.now}" puts "====================================================" end end reporter = SensorReport.new reporter.print_splash reporter.check_boxes
true
eabd0daa38c14eb8b273582a5b01d71215c731c3
Ruby
patrickhidalgo/lrthw_exercises
/chapter_4/ex4.rb
UTF-8
1,182
3.75
4
[]
no_license
#!/usr/bin/env ruby # This defines the variable cars to equal 100. cars = 100 # This defines the variable space_in_a_car to equal 4.0. space_in_a_car = 4.0 # This defines the variable drivers to equal 30. drivers = 30 # This defines the variable passengers to equal 90. passengers = 90 # This defines the variable cars_not_driven to equal the variable cars less the # variable drivers. cars_not_driven = cars - drivers # This defines the variable cars_driven to equal the variable drivers. cars_driven = drivers # This defines the variable carpool_capacity to equal the variable cars_driven * # the variable space_in_a_car. carpool_capacity = cars_driven * space_in_a_car # This defines the variable average_passengers_per_car to equal the variable # passengers divided by the variable cars_driven. average_passengers_per_car = passengers / cars_driven puts "There are #{cars} cars available." puts "There are only #{drivers} drivers available." puts "There will be #{cars_not_driven} empty cars today." puts "We can transport #{carpool_capacity} people today." puts "We have #{passengers} to carpool today." puts "We need to put about #{average_passengers_per_car} in each car."
true
792ba0e7b917bbda6832583a77eba25bc4489d1c
Ruby
tatscru/ruby-puppy-online-web-pt-102218
/lib/dog.rb
UTF-8
792
3.984375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Dog # attr_reader :name @@all = [] # here we are gathering a list of dog names def initialize(name) @name= name @@all << self # self is referred to the name being passed through end # def bark # puts "woof" # # example that if you put dog.new the only method linked to the new instance is bark NOT self.all or self.clear_all # end def self.all @@all.each do |dog| # all names in the arrray are being iterated over and calling the variable dog puts dog.name # here you need to put the variable version of dog and .name since we are calling the argument/variable name end end def self.clear_all # here we are resetting our program to zero based on the existing array @@all.clear end end
true
8f83398d82787725e8ba35b8a48981526a24f5a4
Ruby
Enoch2k2/120919-ft-object-initialize-and-properties
/lib/character.rb
UTF-8
2,324
4.1875
4
[]
no_license
require 'pry' # In Ruby, the `self` keyword is a reference to the current context object # In Ruby, inside a method, the `self` keyword is a reference to the receiving object # In Ruby, inside a method, the `self` keyword is a reference to the object the method was called on # In Ruby, inside an INSTANCE method, the `self` keyword is a reference to the instance object the method was called on # In Ruby, inside an CLASS method, the `self` keyword is a reference to the class the method was called on class Character attr_accessor :name, :level, :klass, :score, :strength, :lives, :speed, :health @@all = [] def initialize(attributes) # attributes.each do |key, value| # self.send("#{key}=", value) # end self.name = attributes[:name] self.level = attributes[:level] self.klass = attributes[:klass] self.score = attributes[:score] self.strength = attributes[:strength] self.lives = attributes[:lives] self.speed = attributes[:speed] self.health = attributes[:health] end def say_description puts "My name is #{self.name}" puts "My level is #{self.level}" puts "My klass is #{self.klass}" puts "My score is #{self.score}" puts "My strength is #{self.strength}" puts "My lives is #{self.lives}" puts "My speed is #{self.speed}" puts "My health is #{self.health}" end # instantiate PLUS save def self.create(attributes) self.new(attributes).tap { |character| character.save } end # instance method that "persists" the object def save @@all << self # what is self? the new character instance that was just created end # this is a class method # this is a class-level reader method for the @@all class variable def self.all @@all end # attr_writer :name # attr_reader :name # def name=(name) # @name = name + "!" # end # def name # @name # end end # # details = { # name: "Biff", # level: 5, # klass: "Knight", # score: 2400, # strength: 17, # lives: 3, # speed: 6, # health: 100 # } # # # biff = Character.new("Biff", 5, "Knight", 2400, 17, 3, 6, 100) # biff = Character.create(details) # # biff.say_description # # What properties will our character have? # # =begin # name # level # klass # score # strength # lives # speed # health # =end
true
58a22bcef17e36588f76edfbff844b1b7ceaf0a7
Ruby
keithyow/code-katas
/day9.rb
UTF-8
217
3.40625
3
[]
no_license
def TimeConvert(num) # code goes here hours = num.to_i/60 mins = num.to_i%60 return hours.to_s + ":" + mins.to_s end # keep this function call here puts TimeConvert(STDIN.gets)
true
b7c51c9f9468562489c8dbaaef1c5d267fc205b2
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/anagram/74ffff50a7fe438580e92dbac67278b6.rb
UTF-8
546
3.4375
3
[]
no_license
class Anagram def initialize word @word = word.to_s.downcase end def match word_list filter_anagrams word_list end private def is_anagram? anagram @word != anagram && sorted_word == sort_string(anagram) end def sorted_word @sorted_word ||= sort_string(@word) end def downcase_list list list.each.map(&:to_s).map(&:downcase) end def filter_anagrams list downcase_list(list).select {|anagram| is_anagram? anagram } end def sort_string string string.split(//).sort end end
true
d3e367583c791895a025c5205fe4e379c57cd67f
Ruby
roger-sge/ruby_exercises
/hours_in_a_year.rb
UTF-8
252
4.03125
4
[]
no_license
# figuring out hours in a year def hours_in_a_year(leap=false) days_in_a_year = 365 if leap days_in_a_year = 366 puts "it's a leap year!" end hours_in_a_day = 24 return days_in_a_year * hours_in_a_day end puts "#{hours_in_a_year()}"
true
2ce5f2d1a592f96b48e16e09eac2bc0e5b986841
Ruby
kasumi8pon/atcoder_practice
/abc/102/b.rb
UTF-8
111
2.890625
3
[]
no_license
n = gets.to_i a = gets.split(" ").map(&:to_i) abs_a = a.map(&:abs) answer = abs_a.max - abs_a.min puts answer
true
9ff3140b8ff3c17a2e6ebe671827c884403806d6
Ruby
nctruong/ruby_advanced
/advanced/Logging.rb
UTF-8
1,241
3.234375
3
[]
no_license
require 'logger' class Logger @@instance = Logger.new("mylog.txt") def self.instance @@instance end module Severity # Redefine Constant by using self.class:: syntax self.class::DEBUG = 0 self.class::INFO = 1 self.class::WARN = 2 self.class::ERROR = 3 self.class::FATAL = 4 WILL = 5 self.class::UNKNOWN = 6 end def level=(severity) if severity.is_a?(Integer) @level = severity else _severity = severity.to_s.downcase case _severity when 'debug'.freeze @level = DEBUG when 'info'.freeze @level = INFO when 'warn'.freeze @level = WARN when 'error'.freeze @level = ERROR when 'fatal'.freeze @level = FATAL when 'will'.freeze @level = WILL when 'unknown'.freeze @level = UNKNOWN else raise ArgumentError, "invalid log level: #{severity}" end end end def will_log(progname = nil, &block) add(WILL, nil, progname, &block) end end Logger.instance.level = Logger::DEBUG Logger.instance.will_log "Will" Logger.instance.info "Info" Logger.instance.error "Error" Logger.instance.debug("ABC"){ "Rejected: ABX" }
true
438950cdd0bc2d99230c5e4e0d9b88e63a7a3865
Ruby
Thiago-Cardoso/devportifolio
/app/validators/date_interval_validator.rb
UTF-8
605
2.640625
3
[ "Apache-2.0" ]
permissive
class DateIntervalValidator < ActiveModel::Validator def validate(record) @record = record if @record.start_date.present? validate_future_start_date validate_start_date_after_end_date if @record.end_date.present? end end private def validate_future_start_date @record.errors.add(:start_date, "must be a past date") if @record.start_date >= Time.zone.now end def validate_start_date_after_end_date @record.errors.add(:end_date, "must be a date after start date") if @record.start_date >= @record.end_date end end
true
7dfe543b22c1a46688083a05cf8d9da4e4d9ff97
Ruby
agorf/adventofcode
/2015/02/2.rb
UTF-8
146
2.9375
3
[]
no_license
sum = $stdin.reduce(0) do |sum, line| l, w, h = line.chomp.split('x').map(&:to_i) sum + [2*(l+w), 2*(w+h), 2*(h+l)].min + l*w*h end puts sum
true
70847a30b3af30d5cb4a2dd83c6f7b88ad1c5273
Ruby
edev/cs510-analytics-in-data-science
/app/round_1.rb
UTF-8
10,617
2.953125
3
[]
no_license
require 'sinatra/base' class Round1 < Sinatra::Base get '/round_1/index.html' do erb :'round_1/index.html' end get '/round_1/all_meals.js' do meals = CouchDB::get(CouchDB::uri("_design/round_1/_view/all_meals")) meals = meals[:rows]&.map do |obj| # obj is a Hash with the following keys: # _id: the document ID # key: an array of date component strings, which should be [year, month, day] # value: number of meals served year = obj[:key][0] month = Integer(obj[:key][1], 10) - 1 # In JS, months range from 0 through 11. day = obj[:key][2] number_served = obj[:value] " [Date.UTC(#{year}, #{month}, #{day}, 17, 30, 0), #{number_served}]" end @data = if meals.nil? "" else meals.join(",\n") end erb :'round_1/all_meals.js', content_type: 'application/javascript' end get '/round_1/yearly_meals.js' do meals = CouchDB::get(CouchDB::uri("_design/round_1/_view/all_meals")) @years = Hash.new meals[:rows]&.each do |obj| # obj is a Hash with the following keys: # _id: the document ID # key: an array of date component strings, which should be [year, month, day] # value: number of meals served # Parse out all the bits for readability, clarity, and DRYness. year = obj[:key][0] month = Integer(obj[:key][1], 10) - 1 # In JS, months range from 0 through 11. day = obj[:key][2] number_served = obj[:value] # Render a line of text for the current entry. # Note: we hard-code a year so that Highcharts will render all lines over one another; Highcharts doesn't know # how to make a "yearly" chart, just a "datetime" chart. This follows the example "Time data with irregular # intervals": https://www.highcharts.com/demo/spline-irregular-time # # We MUST use a leap year to ensure that February 29 is a valid date. entry = " [Date.UTC(2020, #{month}, #{day}, 17, 30, 0), #{number_served}]" # Either instantiate or add to the year's array of values. if @years.has_key? year @years[year] << entry else @years[year] = [entry] end end # "Hashes enumerate their values in the order that the corresponding keys were inserted," which might require # us to sort the keys manually and iterate in that order, except that CouchDB stores its views in sorted order, # guaranteeing that we'll process our data sequentially. We can skip the sorting, but using SQLite3 in production # might require sorting, so future Dylan beware! :) # # Similarly, because of the sorting, we can easily pick out the final year from the keys. @latest_year = @years.keys.last.to_i # Use to_i, not Integer(), to fail relatively gracefully. Should never fail. erb :'round_1/yearly_meals.js', content_type: 'application/javascript' end get '/round_1/monthly_meals_in_last_year.js' do today = Date.today meals = CouchDB::get( CouchDB::uri( URI.escape( %{_design/round_1/_view/all_meals?start_key=["#{today.year-1}","#{"%02d" % today.month}"]} ))) @months = Hash.new @month_list = [] meals[:rows]&.each do |obj| # obj is a Hash with the following keys: # _id: the document ID # key: an array of date component strings, which should be [year, month, day] # value: number of meals served # Parse out all the bits for readability, clarity, and DRYness. year = obj[:key][0] month = Integer(obj[:key][1], 10) - 1 # In JS, months range from 0 through 11. day = obj[:key][2] number_served = obj[:value] # Render a line of text for the current entry. entry = " [#{day}, #{number_served}]" # Either instantiate or add to the year's array of values. key = "#{Date::MONTHNAMES[month+1]} #{year}" if @months.has_key? key @months[key] << entry else @months[key] = [entry] end @month_list << key unless @month_list.include? key end erb :'round_1/monthly_meals_in_last_year.js', content_type: 'application/javascript' end get '/round_1/monthly_meals_year_over_year/:month' do month = params[:month] @month_number = Date::MONTHNAMES.index(month) erb :'round_1/monthly_meals_year_over_year.html' end get '/round_1/monthly_meals_year_over_year/:month/chart' do month_number = params[:month].to_i if month_number < 1 || month_number > 12 redirect '/round_1/index.html' end @month_name = Date::MONTHNAMES[month_number] start_key = "%02d" % month_number end_key = "%02d" % (month_number+1) meals = CouchDB::get( CouchDB::uri( URI.escape( %{_design/round_1/_view/monthly_meals?start_key=["#{start_key}"]&end_key=["#{end_key}"]} ))) @months = Hash.new @month_list = [] meals[:rows]&.each do |obj| # obj is a Hash with the following keys: # _id: the document ID # key: [month (1-12), year] # value: [day of month, number of meals served] # Parse out all the bits for readability, clarity, and DRYness. month = Integer(obj[:key][0], 10) - 1 # In JS, months range from 0 through 11. year = obj[:key][1] day = obj[:value][0] number_served = obj[:value][1] # Render a line of text for the current entry. entry = "[#{day}, #{number_served}]" # Either instantiate or add to the year's array of values. if @months.has_key? year @months[year] << entry else @months[year] = [entry] end @month_list << year unless @month_list.include? year end erb :'round_1/monthly_meals_year_over_year.js', content_type: 'application/javascript' end get '/round_1/christmas_needs.js' do # First, compute the dates we'll need to reference. DAYS_BEFORE = 14 dinner_this_year = Date.parse(CouchDB::get(CouchDB::uri(CouchDB::token('christmas/2019')))[:dates][:dinner]) dinner_last_year = Date.parse(CouchDB::get(CouchDB::uri(CouchDB::token('christmas/2018')))[:dates][:dinner]) cutoff_this_year = dinner_this_year - DAYS_BEFORE cutoff_last_year = dinner_last_year - DAYS_BEFORE # Retrieve the raw data from the view. key_2018 = CouchDB::token('["2018"]') key_2019 = CouchDB::token('["2019"]') raw_data_this_year = CouchDB::get(CouchDB::uri("_design/round_1/_view/christmas_needs?start_key=#{key_2019}")) raw_data_last_year = CouchDB::get(CouchDB::uri("_design/round_1/_view/christmas_needs?start_key=#{key_2018}&end_key=#{key_2019}")) # Process this year's data for each need, collecting results into the needs Hash and building the category list. needs = Hash.new @categories = [] raw_data_this_year[:rows]&.each do |row| need_slug = row[:key][1].to_sym goal = row[:value][:goal] # Note: in CouchDB, adjustments should be an array of objects but is just a single object. adjustment = row[:value][:adjustment].to_i this_year_so_far = # Note: we only need to filter these for the demo; the live product will show live totals. row[:value][:sign_ups] .select { |hash| Date.parse(hash[:created_at]) < cutoff_this_year } # Filter by cutoff. .map { |hash| hash[:quantity] } # Keep only quantity. .reduce(0, :+) this_year_so_far += adjustment needs[need_slug] = { this_year: (this_year_so_far.to_f / goal * 100).to_i } # Note: we do NOT want to use the title of each need, because it might contain distracting information # like "on 12/14 and 12/17". Better to transform the need slug. @categories << need_slug.to_s.gsub('_', ' ').capitalize end # Process last year's data, collecting results into the needs Hash. raw_data_last_year[:rows]&.each do |row| need_slug = row[:key][1].to_sym goal = row[:value][:goal] # Note: in CouchDB, adjustments should be an array of objects but is just a single object. adjustment = row[:value][:adjustment].to_i last_year_so_far = # Note: we still still need to filter last year's result in production. row[:value][:sign_ups] .select { |hash| Date.parse(hash[:created_at]) < cutoff_last_year } # Filter by cutoff. .map { |hash| hash[:quantity] } # Keep only quantity. .reduce(0, :+) last_year_so_far += adjustment last_year_total = row[:value][:sign_ups] .reject { |hash| Date.parse(hash[:created_at]) < cutoff_last_year } # Keep only after cutoff. .map { |hash| hash[:quantity] } # Keep only quantity. .reduce(0, :+) last_year_total if needs.has_key? need_slug needs[need_slug][:last_year] = (last_year_so_far.to_f / goal * 100).to_i needs[need_slug][:last_year_total] = (last_year_total.to_f / goal * 100).to_i end # No else clause, because if it doesn't exist this year, then we don't even want to show it. end # At this point, needs has one key for each need_slug in this year's data set. Each value is a Hash. # Each value hash has a key :this_year holding this year's total of sign-ups so far. # Each value hash might or might not have two additional keys: # :last_year holds the total for last year by the same number of days before the event. # :last_year_total holds the total for last year overall. # # Now, we need to scan through these three keys, pulling the values into one of three matching arrays. # The reason we held these in a Hash is to guarantee that we will iterate over them in the same order, # even in the presence of missing or new need_slugs or other anomalies. # # Note: adding || 0 to the end of each map transforms nils (due to missing keys) into 0 values that JS will accept. @data_this_year = needs.map { |need_slug, hash| hash[:this_year] || 0 } @data_last_year = needs.map { |need_slug, hash| hash[:last_year] || 0 } @data_last_year_total = needs.map { |need_slug, hash| hash[:last_year_total] || 0 } erb :'/round_1/christmas_needs.js', content_type: 'application/javascript' end get '/round_1/christmas_needs.css' do key_2019 = CouchDB::token('["2019"]') raw_data_this_year = CouchDB::get(CouchDB::uri("_design/round_1/_view/christmas_needs?start_key=#{key_2019}")) @need_count = raw_data_this_year[:rows]&.length erb :'/round_1/christmas_needs.css', content_type: 'text/css' end end
true
6bf48e0b3aa7035d2557b11b7352769277246e1b
Ruby
hsyubon/demo
/int.rb
UTF-8
220
3.796875
4
[]
no_license
def call_block(&block) block.call(1) block.call(2) block.call(3) end proc_1 = Proc.new { |i| puts "#{i}: Blocks are cool!"} proc_2 = lambda { |i| puts "#{i}: lambda are cool!"} call_block(&proc_1) call_block(&proc_2)
true
ed87e9650449b66d85c8690499103b16c464280b
Ruby
mfilej/rubytapas-dl
/lib/rubytapas-dl/download_progress_notifier.rb
UTF-8
484
2.9375
3
[]
no_license
# encoding: utf-8 require "pathname" class DownloadProgressNotifier attr_reader :target, :output def initialize(target, output = $stderr) @target = Pathname(target) @output = output end def download_started output.puts end def progress(percent) report_progress percent end def download_finished report_progress 100 end private def report_progress(percent) output.print "\rDownloading #{target.basename} … #{percent}%" end end
true
22a6147a5143279dbac3d4556c9624b060010751
Ruby
andrewtrent/reverse-each-word-v-000
/reverse_each_word.rb
UTF-8
370
3.34375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#def reverse_each_word(string) # string_arr = string.split(" ") # string_arr_two = [] # string_arr.each do |x| # string_arr_two << x.reverse # end # string_arr_two.join(" ") #end def reverse_each_word(string) string_arr = string.split(" ") string_arr_two = [] string_arr.collect do |x| string_arr_two << x.reverse end string_arr_two.join(" ") end
true
7bb9197209c6d6fcb952e43f27a2fc9ece99c25c
Ruby
AaronC81/parlour
/lib/parlour/debugging.rb
UTF-8
4,641
3.140625
3
[ "MIT" ]
permissive
# typed: true require 'rainbow' module Parlour # Contains methods to enable debugging facilities for Parlour. module Debugging extend T::Sig @debug_mode = !ENV["PARLOUR_DEBUG"].nil? # Set whether debug messages should be printed. # @param [Boolean] value True if debug messages will be printed, false # otherwise. # @return [Boolean] The new value. sig { params(value: T::Boolean).returns(T::Boolean) } def self.debug_mode=(value) @debug_mode = value end # Whether debug messages sent by {.debug_puts} should be printed. # Defaults to true if the PARLOUR_DEBUG environment variable is set. # @return [Boolean] True if debug messages will be printed, false otherwise. sig { returns(T::Boolean) } def self.debug_mode? @debug_mode end # Prints a message with a debugging prefix to STDOUT if {.debug_mode?} is # true. # @param [Object] object The object which is printing this debug message. # Callers should pass +self+. # @param [String] message The message to print. It should not contain # newlines. # @return [void] sig { params(object: T.untyped, message: String).void } def self.debug_puts(object, message) return unless debug_mode? name = Rainbow("#{name_for_debug_caller(object)}: ").magenta.bright.bold prefix = Rainbow("Parlour debug: ").blue.bright.bold puts prefix + name + message end # Converts the given object into a human-readable prefix to a debug message. # For example, passing an instance of {ConflictResolver} returns # "conflict resolver". If the object type is unknown, this returns its class # name. # @param [Object] object The object to convert. # @return [String] A string describing the object for {.debug_puts}. sig { params(object: T.untyped).returns(String) } def self.name_for_debug_caller(object) case object when ConflictResolver "conflict resolver" when RbiGenerator "RBI generator" else if ((object < Plugin) rescue false) return "plugin #{object.name}" end object.class.name end end # A module for generating a globally-consistent, nicely-formatted tree of # output using Unicode block characters. class Tree extend T::Sig # The number of spaces to indent each layer of the tree by. Should be at # least 1. INDENT_SPACES = 2 # Whether to colour output or not. sig { returns(T::Boolean) } attr_reader :colour sig { params(colour: T::Boolean).void } def initialize(colour: false) @colour = colour @indent_level = 0 end # Returns a new heading, and then decents the tree one level into it. # (That is, future output will go under the new heading.) # @param [String] message The heading. # @return [String] The line of this tree which should be printed. sig { params(message: String).returns(String) } def begin(message) result = line_prefix + '├' + text_prefix + (colour ? Rainbow(message).green.bright.bold : message) indent!(1) result end # Prints a new tree element at the current level. # @param [String] message The element. # @return [String] The line of this tree which should be printed. sig { params(message: String).returns(String) } def here(message) line_prefix + '├' + text_prefix + message end # Prints the final tree element at the current level, then ascends one # level. # @param [String] message The element. # @return [String] The line of this tree which should be printed. sig { params(message: String).returns(String) } def end(message) result = line_prefix + '└' + text_prefix + message indent!(-1) result end # The prefix which should be printed before anything else on this line of # the tree, based on the current indent level. # @return [String] def line_prefix @indent_level.times.map { '│' + ' ' * INDENT_SPACES }.join end # The horizontal lines which should be printed between the beginning of # the current element and its text, based on the specified number of # spaces to use for indents. # @return [String] def text_prefix '─' * (INDENT_SPACES - 1) + " " end # Modifies the current indent level by the given offset. def indent!(offset) @indent_level = [0, @indent_level + offset].max end end end end
true
635b301546fec46801ae14a65626c4481f809598
Ruby
alextacho/foosball
/app/models/match.rb
UTF-8
950
2.703125
3
[ "MIT" ]
permissive
class PlayerNotInBothTeams < ActiveModel::Validator def validate(record) player_in_both_teams = (record.try(:home_team).try(:player_ids) & record.try(:away_team).try(:player_ids)) if player_in_both_teams.any? player_in_both_teams.each do |player_id| player = Player.find player_id record.errors[:players] << "Player #{player.name} can't play for both teams" end end end end class Match < ActiveRecord::Base belongs_to :home_team, class_name: 'Team' belongs_to :away_team, class_name: 'Team' scope :finished, -> { where.not(home_team_score: nil).where.not(away_team_score: nil) } scope :unfinished, -> { where(home_team_score: nil).where(away_team_score: nil) } validates :away_team_id, :home_team_id, presence: true validates_with PlayerNotInBothTeams def winner if self.home_team_score > self.away_team_score self.home_team else self.away_team end end end
true
35616e80915be630620cc2654c4390c6b4e542b6
Ruby
kota-shidara/atcoder-problems
/ABC/123/123-C.rb
UTF-8
106
3.125
3
[]
no_license
n = gets.to_i min_times = 5.times.map { gets.chomp.to_i }.min ans = 4 + (n / min_times.to_f).ceil puts ans
true
f07e254cf1026985826a4ee6f0011c720df08fcf
Ruby
paulfjacobs/knight-move-on-phone-keypad
/chess.rb
UTF-8
458
3.1875
3
[]
no_license
Move_map=[[4,6],[6,8],[7,9],[4,8],[3,9],[],[1,7],[2,6],[1,3],[2,4]] def compute(v,n) h = 1 prefix_queue = [ "#{v}" ] cur_level = [ v ] new_level = [] while h <= n cur_level.each do |k| prefix = prefix_queue.shift Move_map[ k ].each do |x| new_level.push x prefix_queue.push "#{prefix},#{x}" end end cur_level = new_level new_level = [] h += 1 end puts prefix_queue puts 'done' end compute( ARGV[0].to_i, ARGV[1].to_i)
true
f0e6dd0410e36d209e7ef8d4a7a9d7284106f196
Ruby
jeanfrancis/membr
/features/step_definitions/member_steps.rb
UTF-8
1,742
2.609375
3
[]
no_license
Given /^I chose to add a new member$/ do visit("/members/new") end Given /^I am on the members page$/ do visit("/") end Given /^a member exists with ic_number (\d+)$/ do |ic_number| @member = create(:member, ic_number: ic_number) @member.should_not be_nil end When /^I add a new member with details:$/ do |table| @data = table.rows_hash [ :name, :ic_number, :doj, :donation, :hand_phone, :home_phone, :family_members_attributes_0_name, :family_members_attributes_1_name, ].each do |attr| fill_in("member_#{attr}", :with => @data[attr.to_s]) end [ :line1, :line2, :postcode ].each do |attr| fill_in("address_#{attr}", :with => @data[attr.to_s]) end click_button('Save') end Then /^I see a confirmation of the member's details$/ do @data.values.each do |value| page.should have_content(value) end end When /^I search for member with ic_number (\w+)$/ do |arg1| visit("/search") fill_in("ic_number", :with => arg1) click_button("Find") end Then /^I see all the details of member with ic_number (\w+)$/ do |arg1| page.should have_content(@member.name) page.should have_content(@member.ic_number) page.should have_content(I18n.l(@member.doj)) page.should have_content(@member.donation) page.should have_content(@member.hand_phone) page.should have_content(@member.home_phone) page.should have_content(@member.address.line1) page.should have_content(@member.address.line2) page.should have_content(@member.address.postcode) page.should have_content(@member.remarks) #TODO replace this with a presenter page.should have_content(@member.family_members.map(&:name).join(", ")) end Then /^I see there are no results$/ do page.should have_content("No results") end
true
d750ac61ec4ee226fe562043e0ebd5ceea7fe06b
Ruby
peek/peek-mongo
/lib/peek/views/mongo.rb
UTF-8
2,739
2.75
3
[ "MIT" ]
permissive
require 'mongo' require 'concurrent' module Peek # Query times are logged by timing the Socket class of the Mongo Ruby Driver module MongoSocketInstrumented def read(*args, &block) start = Time.now super(*args, &block) ensure duration = (Time.now - start) ::Mongo::Socket.query_time.update { |value| value + duration } end def write(*args, &block) start = Time.now super(*args, &block) ensure duration = (Time.now - start) ::Mongo::Socket.query_time.update { |value| value + duration } end end # Query counts are logged to the Socket class by monitoring payload generation module MongoProtocolInstrumented def payload super ensure ::Mongo::Protocol::Message.query_count.update { |value| value + 1 } end end end # The Socket class will keep track of timing # The MongoSocketInstrumented class overrides the read and write methods, rerporting the total count as the attribute :query_count class Mongo::Socket prepend Peek::MongoSocketInstrumented class << self attr_accessor :query_time end self.query_time = Concurrent::AtomicFixnum.new(0) end # The Message class will keep track of count # Nothing is overridden here, only an attribute for counting is added class Mongo::Protocol::Message class << self attr_accessor :query_count end self.query_count = Concurrent::AtomicFixnum.new(0) end ## Following classes all override the various Mongo command classes in Protocol to add counting # The actual counting for each class is stored in Mongo::Protocol::Message class Mongo::Protocol::Query prepend Peek::MongoProtocolInstrumented end class Mongo::Protocol::Insert prepend Peek::MongoProtocolInstrumented end class Mongo::Protocol::Update prepend Peek::MongoProtocolInstrumented end class Mongo::Protocol::GetMore prepend Peek::MongoProtocolInstrumented end class Mongo::Protocol::Delete prepend Peek::MongoProtocolInstrumented end module Peek module Views class Mongo < View def duration ::Mongo::Socket.query_time.value end def formatted_duration ms = duration * 1000 if ms >= 1000 "%.2fms" % ms else "%.0fms" % ms end end def calls ::Mongo::Protocol::Message.query_count.value end def results { :duration => formatted_duration, :calls => calls } end private def setup_subscribers # Reset each counter when a new request starts subscribe 'start_processing.action_controller' do ::Mongo::Socket.query_time.value = 0 ::Mongo::Protocol::Message.query_count.value = 0 end end end end end
true
07a68525f74fcb0083eb2bef96b07560b6472f9a
Ruby
dpmontooth/pre_ruby_exercises
/hashes/exercise_3c.rb
UTF-8
197
4.1875
4
[]
no_license
# program to loop through hash and print keys and values hash_1 = {fluffy_dog: "Juno", skinny_dog: "Bailey", brother: "Mark", sister: "Kristie"} hash_1.each {|k,v| puts "My #{k} is named #{v}."}
true
ae8505afdc467be28a07901d4ef9554da5cbedf0
Ruby
gera-gas/iparser
/lib/iparser/state.rb
UTF-8
2,267
3.265625
3
[ "MIT" ]
permissive
module Iparser # Used for describe single state # of parser machine. class State attr_reader :statename attr_accessor :branches, :entry, :leave, :ientry, :ileave, :ignore # call-seq: # State.new( String ) def initialize ( sname ) unless sname.instance_of? String raise TypeError, 'Incorrectly types for <Parser-State> constructor.' end @statename = sname @init = nil # method called after entry (state constructor). @fini = nil # method called after leave (state destructor). @handler = nil # state machine for handler current state. @ignore = { :all => [], :handler => [] } @ientry = 0 # use to save compred index of this state. @ileave = 0 # use to save compred index of this state. @entry = [] # template chars for entry state. @leave = [] # template chars for leave state. @branches = [] # indexes of any states to branch. end # call-seq: # init( method(:some_init_method) ) # # Set initializer method for current state. def init ( method ) raise TypeError, error_message(method, __method__) unless method.instance_of? Method @init = method end # call-seq: # fini( method(:some_fini_method) ) # # Set finalizer method for current state. def fini ( method ) raise TypeError, error_message(method, __method__) unless method.instance_of? Method @fini = method end def run_init( *args ) # :nodoc: return @init.call( *args ) if @init != nil return nil end def run_fini( *args ) # :nodoc: return @fini.call( *args ) if @fini != nil return nil end # call-seq: # handler( method(:some_handler_method) ) # # Set handler method for current state. def handler ( method ) raise TypeError, error_message(method, __method__) unless method.instance_of? Method @handler = method end def run_handler( *args ) # :nodoc: return @handler.call( *args ) if @handler != nil return nil end private def error_message(object, method) "#{object.class}: Incorrectly types for <#{method}> method of <Parser-State>." end end # class State end
true
cb18783d974c1d6f31955c999de742d79c9c719e
Ruby
ElaErl/Intro-to-programming
/intro_to_prog/arrays_6/6_1.rb
UTF-8
87
3.34375
3
[]
no_license
arr = [1, 3, 5, 7, 9, 11] number = 3 if arr.include?(num) puts "num is in arr" end
true
a8cc78ed528128dcf7a98463ec26f9687cd4168d
Ruby
jhererxp/HotelSW
/confirm1.rb
UTF-8
140
3.078125
3
[]
no_license
class Confirm1 attr_reader :roomr attr_writer :roomr def initialize(room) @roomr = room end def say_room " #{roomr}" end end
true
7b73edd622223ebcfd4bb9fbd35557f1a2d53a9d
Ruby
galtet/posts_system
/lib/tyrion/models/post.rb
UTF-8
1,904
3.03125
3
[]
no_license
require 'date' module Tyrion module Models class Post < ActiveRecord::Base belongs_to :user has_many :votes after_create :update_hot_posts MAX_HOT_POSTS = 20 @@hot_posts = [] def self.hot_posts @@hot_posts ||= [] end def self.set_hot_posts(h_posts) @@hot_posts = h_posts end def upvote(user_id) self.votes.create(vote: '1', user_id: user_id) end def downvote(user_id) self.votes.create(vote: '0', user_id: user_id) end def update_hot_posts() return if self.class.hot_posts.any? { |p| p.id == self.id } if self.class.hot_posts.length < MAX_HOT_POSTS self.class.hot_posts << self else self.class.hot_posts << self res = self.class.hot_posts.sort_by do |p| p.hot_score end self.class.set_hot_posts(res.last(MAX_HOT_POSTS)) end end def hot_score hot(self.votes.where(vote: '1').count, self.votes.where(vote: '0').count, self.created_at.to_time) end private # Actually doesn't matter WHAT you choose as the epoch, it # won't change the algorithm. Just don't change it after you # have cached computed scores. Choose something before your first # post to avoid annoying negative numbers. Choose something close # to your first post to keep the numbers smaller. This is, I think, # reddit's own epoch. def epoch_seconds(t) epoch = Time.local(2017, 9, 10, 23, 46, 43).to_time (t.to_i - epoch.to_i).to_f end # date is a ruby Time def hot(ups, downs, date) s = ups - downs displacement = Math.log( [s.abs, 1].max, 10 ) sign = if s > 0 1 elsif s < 0 -1 else 0 end return (displacement * sign.to_f) + ( epoch_seconds(date) / 45000 ) end end end end
true
5a8d649f9abe7ee61c362aab161d75f764d4ac3b
Ruby
dlhede1509/classes-and-instances-lab-ruby-bootcamp-prep-000
/lib/dog.rb
UTF-8
155
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Dog attr_accessor :name end fido = Dog.new fido.name = 'fido' snoopy = Dog.new snoopy.name = 'snoopy' lassie = Dog.new lassie.name = 'lassie'
true
7deb1c6031ca9f69298c9fd4dae6e7135cb117cb
Ruby
PhilippePerret/Collecte
/lib/required_then/classe/Collecte/Collecte/instance/props.rb
UTF-8
570
2.546875
3
[]
no_license
# encoding: UTF-8 class Collecte # L'instance {Film} du film de la collecte def film ; @film ||= Film.new(self) end # {Array} Liste des erreurs rencontrées au cours de # l'opération. attr_reader :errors # Instance Collecte::Metadata des métadonnées def metadata ; @metadata ||= Metadata.new(self) end # Raccourcis vers les METADATA # ---------------------------- def auteurs ; @auteurs ||= metadata.data[:auteurs] end def debut ; @debut ||= metadata.data[:debut] end def fin ; @fin ||= metadata.data[:fin] end end
true
ae5382cf219db04e8c3c65691707edf6b2cbca4b
Ruby
vannida-lim/ruby-enumerables-hash-practice-emoticon-translator-lab-dumbo-web-100719
/lib/translator.rb
UTF-8
1,055
3.234375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# require modules here require "yaml" def load_library(filepath) # code goes here emoticons = YAML.load_file(filepath) result = {} result[:get_meaning] = {} result[:get_emoticon] = {} emoticons.each do |meaning, array_emojis| english_emojis = array_emojis[0] japanese_emojis = array_emojis[1] result[:get_meaning][japanese_emojis] = meaning result[:get_emoticon][english_emojis] = japanese_emojis end return result end def get_japanese_emoticon(filepath, english_emoticon_to_translate) # code goes here result = load_library(filepath) if result[:get_emoticon][english_emoticon_to_translate] return result[:get_emoticon][english_emoticon_to_translate] end return "Sorry, that emoticon was not found" end def get_english_meaning(filepath, japanese_emoticon_to_translate) # code goes here result = load_library(filepath) if result[:get_meaning][japanese_emoticon_to_translate] return result[:get_meaning][japanese_emoticon_to_translate] end return "Sorry, that emoticon was not found" end
true
8eb55c7f4d4d1c3c5a5cdce9fc33f2f8d5ec363e
Ruby
codeAligned/super_happy_interview_time
/rb/lib/leetcode/lc_49.rb
UTF-8
506
3.453125
3
[ "MIT" ]
permissive
# frozen_string_literal: true module LeetCode # 49. Group Anagrams module LC49 # Description: # Given an array of strings, group anagrams together. # # Examples: # Input: ["eat", "tea", "tan", "ate", "nat", "bat"] # Output: [ # ["ate", "eat", "tea"], # ["nat", "tan"], # ["bat"] # ] # # @param list {Array<String>} # @return {Array<Array<String>>} def group_anagrams(list) list.group_by { |s| s.chars.sort }.values end end end
true
9b34bf955decf414a2d929ed62e99d13b30b19df
Ruby
PhilippePerret/Piano
/public/page/article/admin/scores/Scores.rb
UTF-8
3,216
2.515625
3
[]
no_license
# encoding: UTF-8 =begin Class Stores ------------ Gestion des images créées à l'aide des scripts xextra sur Icare Extension administration seulement =end class Score app.require_module 'Score' class << self attr_reader :logs ## # # Retourne pour affichage les messages de l'opération # demandées si elle utilise le log # def display_logs if @logs.nil? || @logs.empty? "Aucun message n'a été généré." else @logs.collect { |m| m.in_div }.join("") end end def log str @logs ||= [] @logs << str end ## # # Demande d'édition d'une image # def edit_image img = Score::Image::new param(:img_id).to_i self.current = img img.data_in_param end ## # # Rappatrie le fichier ONLINE # def download_online_pstore fichier = Fichier::new Score::pstore fichier.download flash "Le pstore serveur a été ramené avec succès." end ## # # Méthode qui nettoie le pstore des scores en retirant les # images qui n'existe pas (se produit en cas d'erreur) # def check_scores ## ## On récupère toutes les images ## h = {} PPStore::new(pstore).each_root(except: :last_id) do |ps, root| next unless root.class == String h.merge! root => ps[root] end ## ## On regarde celles qui n'existent plus ## h.dup.each do |score_src, score_data| cmd = "curl #{score_src}" res = `#{cmd}` if res.index("404 Not Found") log "Image #{score_src} introuvable".in_span(class: 'warning') else log "Image #{score_data[:affixe]} OK" h.delete score_src end # debug "\n*** #{cmd}\nCURL: #{res}" end ## ## On détruit celles qui restent ## ## Note pour le moment, on ne fait rien, jusqu'à ce que ## ce soit bon ## PPStore::new(pstore).transaction do |ps| h.each do |score_src, score_data| log "Il FAUDRAIT détruire l'image ##{score_data[:id]} #{score_src}" log "(POUR LE MOMENT ÇA N'EST PAS ENCORE IMPLÉMENTÉ, IL FAUDRAIT POUVOIR CONFIRMER)" # ps.delete score_src # ps.delete score_data[:id] end end end # Traitée dans la vue def show_list; end end # << self Score # --------------------------------------------------------------------- # # Class Score::Image # # --------------------------------------------------------------------- class Image # --------------------------------------------------------------------- # # Méthode d'helper # # --------------------------------------------------------------------- ## # Retourne l'image pour un LI # # La méthode surclasse la méthode du module pour l'user # def as_li c = "" c << src.in_image c << affixe.in_span(class: 'affixe') c << "[edit]".in_a(href: "?a=admin/scores&operation=edit_image&img_id=#{id}") c.in_li(class: 'li_img', id: "li_img-#{id}") end end end
true
ef557b89428bfd884027eec9d077a5304bba1fa3
Ruby
kchien/KindleClippingExtractor
/lib/kindle_extractor/writes_anki_import_file.rb
UTF-8
700
2.953125
3
[]
no_license
module KindleExtractor class WritesAnkiImportFile ANKI_FIELD_SEPARATOR = "\t" def initialize(dir=ENV['PWD']) @output_dir = File.expand_path "#{dir}" end def write_out(highlight) FileUtils.mkdir_p(output_dir) unless Dir.exists?(output_dir) anki_text_file = File.join(output_dir, "#{highlight.book_title}.txt") File.open(anki_text_file, 'a') do |f| front = highlight.content back = "#{highlight.book_title}|#{highlight.author}|#{highlight.location}" f.puts "#{front}#{ANKI_FIELD_SEPARATOR}#{back}" end #book_title, author, type, location, content end private attr_reader :output_dir end end
true
4aaf0c0b0ca8d5675338d370f82f7346e930f480
Ruby
maayankaufman/todo-ruby-basics-001-prework-web
/lib/ruby_basics.rb
UTF-8
350
3.5
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def division(num1, num2) num1/num2 end def assign_variable(name) variable=name end def argue(phrase) phrase = "I'm right and you are wrong!" end def greeting (greeting, name) greeting = "Hi there, " name = "Bobby!" end def return_a_value "Nice" end def last_evaluated_value "expert" end def pizza_party (topping= "cheese") topping end
true
e9858edec1e777931256bf197f1a8a947f99e052
Ruby
BigTallJim/BorisBike
/spec/boris_bikes_spec.rb
UTF-8
1,802
2.921875
3
[]
no_license
require "boris_bikes" describe DockingStation do let(:bike) { double :bike } it "expect release of bike" do is_expected.to respond_to(:release_bike) end it "test bike is returned from release bike if bikes exist" do allow(bike).to receive(:is_working?).and_return(true) dock = DockingStation.new # bike = double(:bike) dock.dock_bike(bike) # bike = dock.release_bike expect(bike.is_working?).to eq (true) end it "expect to respond to docking of bike with 1 argument" do is_expected.to respond_to(:dock_bike).with(1).argument end it "expect fail if no bike to release from new Docking Station" do expect {DockingStation.new.release_bike}.to raise_error("No bikes available") end it "test if docked bike is correctly retuned" do allow(bike).to receive(:is_working?).and_return(true) dock = DockingStation.new bike1 = bike bike2 = bike dock.dock_bike(bike1) dock.dock_bike(bike2) expect(dock.release_bike).to eq (bike2) expect(dock.store).to eq ([bike1]) end it "test if exception thrown when docking station contains more than 20 bikes" do dock = DockingStation.new $DEFAULT_CAPACITY.times {dock.dock_bike(bike)} expect {dock.dock_bike(bike)}.to raise_error("Docking Station Full") end it "Test create docking station when user sets size value of 30" do dock = DockingStation.new(30) expect($DEFAULT_CAPACITY).to eq (30) end it "Test create docking station defaulting size to 20" do dock = DockingStation.new expect($DEFAULT_CAPACITY).to eq (20) end it "Don't release a bike if it's broken" do allow(bike).to receive(:is_working?).and_return(false) subject.dock_bike(bike) expect {subject.release_bike}.to raise_error("No working boris bikes") end end
true
e5f2a2241e320020f7457530146c6b4d5b057001
Ruby
IIIIIIIIll/RubyQuizess
/Quiz5/question21.rb
UTF-8
92
3.28125
3
[]
no_license
class Calculator def self.add(x, y) return(x + y) end end puts Calculator.add(3, 4)
true
43e2329d459edc2b1dade37ebedf9f58d06c8e74
Ruby
kacperwalanuselpassion/pasher
/app/models/storage/mongo/dish.rb
UTF-8
1,209
2.625
3
[]
no_license
module Storage::Mongo class Dish class << self def mapper Storage::Mongo::Dish::Mapper end def all collection.find().sort(_id: -1).map { |response| mapper.to_object(response) } end def find(id) response = collection.find_one(_id: BSON::ObjectId(id)) mapper.to_object(response) end def find_by(key, value) collection.find_one(key => value) end def find_all_by(key, value) collection.find(key => value).map { |response| mapper.to_object(response) } end def save(dish) collection.save(mapper.to_storage(dish)) end def update(id, dish) collection.update({_id: BSON::ObjectId(id)}, mapper.to_storage(dish)) end def remove(id) collection.remove(_id: BSON::ObjectId(id)) end def remove_by_order_uid(order_uid) collection.remove(order_uid: order_uid) end def users(users_ids) User.where(uid: users_ids) end def order(order_id) Order.new.storage.find(order_id) end private def collection Storage::Mongo::Driver.db['dishes'] end end end end
true
d953332066f6a9af673a66ed6d67897d8167e219
Ruby
prw001/mastermind
/GameTools.rb
UTF-8
237
3.015625
3
[]
no_license
module GameTools def numToColor(num) case num when 1 return 'r' when 2 return 'y' when 3 return 'b' when 4 return 'g' when 5 return 'c' else return 'p' end end end
true
2bd390c9f77cf8d2d1d619ff3d55392911a94279
Ruby
johnhowardroberts/launch-school
/101_109_small_problems/odd_numbers.rb
UTF-8
286
4.65625
5
[]
no_license
# Print all odd numbers from 1 to 99, inclusive. All numbers should be printed on separate lines. (1..99).each { |num| puts num if num.odd? } # Further Exploration # Integer#upto 1.upto(99) { |num| puts num if num.odd? } # Array#select puts (1..99).to_a.select { |num| num.odd? }
true
5123ce700b20065f51b86af02f0d48562b77b250
Ruby
bil-bas/bored_game_hotspot_editor
/test/TC_gridnode.rb
UTF-8
5,326
3.171875
3
[]
no_license
############################################################################### # # require 'test/unit' # require 'yaml' # For debugging only. require '../lib/pathfinding' include PathFinding ############################################################################### # class TC_GridNode < Test::Unit::TestCase # public def setup # 0 => Empty / no node. # 1..n => entry cost. # Transpose so it acts the way it looks. @grid = [ [1, 1, 1, 1, 1], [6, 0, 0, 0, 1], [1, 1, 1, 1, 1], [1, 0, 0, 0, 0], [1, 1, 1, 1, 1] ].transpose # Change numbers to nodes. @grid.size.times do |r| @grid.first.size.times do |c| if @grid[c][r] == 0 @grid[c][r] = nil else @grid[c][r] = GridNode.new((@grid[c][r]), c, r) end end end # Provide links. @grid.size.times do |r| @grid.first.size.times do |c| if @grid[c][r] @grid[c][r].exits.push @grid[c-1][r] if c > 0 && @grid[c-1][r] @grid[c][r].exits.push @grid[c+1][r] if c < (@grid.size-1) && @grid[c+1][r] @grid[c][r].exits.push @grid[c][r-1] if r > 0 && @grid[c][r-1] @grid[c][r].exits.push @grid[c][r+1] if r < (@grid.size-1) && @grid[c][r+1] end end end end # setup() # public def test_initialize() node = GridNode.new 5, 6, 7 assert_equal node.entryCost, 5 assert_equal node.x, 6 assert_equal node.y, 7 assert_equal node.exits.size, 0 end # test_initialize() # public def test_distanceTo() # Positive nodes. node1 = GridNode.new 5, 6, 7 node2 = GridNode.new 5, 10, 3 assert_equal 0, node1.distanceTo(node1) assert_equal 8, node1.distanceTo(node2) assert_equal 8, node2.distanceTo(node1) # Negative nodes. node3 = GridNode.new 5, -12, -8 node4 = GridNode.new 5, -4, -2 assert_equal 0, node3.distanceTo(node3) assert_equal 14, node3.distanceTo(node4) assert_equal 14, node4.distanceTo(node3) # Negative-positive. assert_equal 33, node3.distanceTo(node1) assert_equal 33, node1.distanceTo(node3) end # test_distanceTo() # public def test_shortestPath() # Long path to test for shortestPath(). longPathCoords = [ [0, 0], [0, 1], [0, 2], [0, 3], [0, 4], [1, 4], [2, 4], [3, 4], [4, 4] ] # Convert into GridNode array. longPath = longPathCoords.collect do |x, y| @grid[x][y] end longPathDistance = 13 # Unlimited path length. path = longPath.first.shortestPath longPath.last assert_paths_same(longPath, longPathDistance, path) # Test with max distance less than distance expected. (0...longPathDistance).each do |limit| path = longPath.first.shortestPath longPath.last, limit assert_nil path, "Path returned, in spite of limit being too low." end # Test with max greater than or equal to expected length. (longPathDistance..(longPathDistance + 5)).each do |limit| path = longPath.first.shortestPath longPath.last, limit assert_paths_same(longPath, longPathDistance, path) end end # test_shortestPath() # public def test_absolutePaths() # Absolute paths to test for. pathsCoords = [ [ [0, 0], [1, 0], [2, 0], [3, 0], [4, 0] , [4, 1], [4, 2], [3, 2], [2, 2] ], [ [0, 0], [0, 1], [0, 2], [0, 3] ], [ [0, 0], [0, 1], [0, 2], [1, 2] ] ] # Convert into GridNode arrays. expNodeLists = Array.new pathsCoords.each do |coordList| path = coordList.collect do |x, y| @grid[x][y] end expNodeLists.push path end expDistance = 8 paths = expNodeLists[0][0].absolutePaths expDistance # Check that array has correctly been returned. assert_kind_of Array, paths, "Paths expected to be in an array" assert_equal expNodeLists.size, paths.size, "Wrong # of paths returned." # Check each path in returned array. expNodeLists.each_with_index do |nodeList, i| assert_paths_same(nodeList, expDistance, paths[i]) end end # test_absolutePaths() # public def test_allPaths_limited() maxLen = 7 paths = @grid[0][0].allPaths maxLen # if paths # paths.each { |path| puts path.join("; ") + " = #{path.distance}" } # else # puts "Paths not found." # end end # test_allPaths_limited() # public def test_allPaths_unlimited() paths = @grid[0][0].allPaths # Check that all paths are considered. numPossPaths = @grid.flatten.nitems - 1 # Don't include start! assert_equal numPossPaths, paths.size, 'Wrong number of paths produced' # paths.each { |path| puts path.join("; ") + " = #{path.distance}" } # else # puts "Paths not found." # end end # test_allPaths_unlimited() # private def assert_paths_same(expectedNodes, expectedDist, path) # Check path is of correct type assert_kind_of(Path, path, "'path' is not a Path") # Check similarity. assert_equal(expectedNodes.size, path.size, "Path has wrong number of nodes.") assert_equal(expectedDist, path.distance, "Path of incorrect distance.") expectedNodes.each_with_index do |node, i| assert_equal(path[i], node, "Bad path node.") end end end # class TC_GridNode
true
6286dcc44a044fa3270313df47980af2dce95ddb
Ruby
gyg22/puzzle
/interview/elance/third/app.rb
UTF-8
1,087
2.609375
3
[]
no_license
#encoding: utf-8 require 'sinatra' require_relative 'config' require_relative 'user' class APP < Sinatra::Base get '/users' do users = User.all [200, {'Content-Type' => 'application/json'}, users.to_json] end post '/users' do user = User.new email: params[:email] if user.save [200, {'Content-Type' => 'application/json'}, user.to_json] else [400, {'Content-Type' => 'application/json'}, user.errors.to_json] end end put '/users/:id' do user = User.where(id: params[:id]).first if user user.email = params[:email] if user.save [200, {'Content-Type' => 'application/json'}, user.to_json] else [400, {'Content-Type' => 'application/json'}, user.errors.to_json] end else [404, {'Content-Type' => 'application/json'}, nil] end end delete '/users/:id' do user = User.where(id: params[:id]).first if user user.destroy [204, {'Content-Type' => 'application/json'}, nil] else [404, {'Content-Type' => 'application/json'}, nil] end end end
true
5face4852a136f07ff6a3814de46d37a11a75470
Ruby
nramadas/WebChess
/spec/libraries/bishop_spec.rb
UTF-8
1,391
2.984375
3
[]
no_license
require 'colorize' describe "Bishop".red do let(:board) { Chess::Board.new } subject(:piece) { Chess::Bishop.new(0, 4, :black, board) } its(:row) { should eq(0) } its(:col) { should eq(4) } its(:player) { should eq(:black) } describe "it has" do it "a bishop token" do piece.token == "\u265d" end end describe "it can move" do describe "diagonally" do it "left when unblocked" do piece.move(4,0) piece.row.should eq(4) piece.col.should eq(0) end it "right when unblocked" do piece.move(3,7) piece.row.should eq(3) piece.col.should eq(7) end end end describe "it cannot move" do describe "diagonally" do before(:each) do Chess::Pawn.new(2, 2, :white, piece.board) Chess::Pawn.new(2, 6, :white, piece.board) end it "left when blocked" do expect do piece.move(4,0) end.to raise_error(Chess::BadMove) end it "right when blocked" do expect do piece.move(3,7) end.to raise_error(Chess::BadMove) end end end describe "it captures" do before(:each) do Chess::Pawn.new(2, 2, :white, piece.board) Chess::Pawn.new(3, 7, :white, piece.board) end it "diagonally left" do piece.move(2,2) piece.row.should eq(2) piece.col.should eq(2) end it "diagonally right" do piece.move(3,7) piece.row.should eq(3) piece.col.should eq(7) end end end
true
054c10cb724aecd8dbb7f36d3f7e7ab893e7c81b
Ruby
riverswb/gryff_outdoor
/app/models/item.rb
UTF-8
508
2.5625
3
[]
no_license
class Item < ApplicationRecord validates :title,:description, :price, :image, presence: :true belongs_to :category has_many :order_items has_many :orders, through: :order_items enum status: [:active, :retired] def self.item_list(cart_items) cart_items.map do |item, quantity| [find(item), quantity] end end def self.find_quantity(item, order) order.items.where(id: item.id).count end def self.find_line_subtotal(quantity, item) item.price * quantity end end
true
4c5c872d74bec9a590d966d67638a2f51dd283bb
Ruby
noontage/scratches
/binary_gacp.rb
UTF-8
320
3.234375
3
[]
no_license
def solution(n) ary = [] t = 0 s = n.to_s(2) s.each_char do |c| if c == '1' unless t.zero? ary.push(t) t = 0 end else t+=1 end end return 0 if ary.empty? ary.max end p solution(0b11111111111111111)
true
dc2bc0dcd58fc53c082430c8fda17382c0632833
Ruby
docljn/advent2019
/lib/instruction.rb
UTF-8
729
3.734375
4
[ "MIT" ]
permissive
# frozen_string_literal: true class Instruction attr_reader :direction, :distance def initialize(data) @direction = data[0].upcase @distance = data.delete(direction).to_i end def ==(other) direction.equal?(other.direction) distance.equal?(other.distance) end def path_from(starting_point) x = starting_point[0] y = starting_point[1] path = [] case direction when 'R' distance.times do path << [x+=1, y] end when 'L' distance.times do path << [x-=1, y] end when 'U' distance.times do path << [x, y+=1] end when 'D' distance.times do path << [x, y-=1] end end path end end
true
84a1b03eef85d19cbd6756254557a0b96ee3350b
Ruby
baldesco/Ruby
/ejercicios/hipo.rb
UTF-8
197
3.484375
3
[]
no_license
puts "Digite el primer lado del triangulo" a=gets.chomp.to_i puts "Digite el segundo lado del triangulo" b=gets.chomp.to_i c=(a**2+b**2)**0.5 puts "La longitud de la hipotenusa es #{c}"
true
4cdc4c058e2987a87dd0586b3b294ef2b2b28f90
Ruby
mlongerich/plural_sight_exercises
/ruby_fundamentals/test/control_structs.rb
UTF-8
138
2.546875
3
[]
no_license
lander_count = 10 message = if lander_count > 10 "Launching probe" else "Waiting for probes to return" end puts message a = b = 10
true
c7e4141270d3f3fc33d350b38db03a4c9c21214a
Ruby
grzeswol/Euklides
/main.rb
UTF-8
169
2.5625
3
[]
no_license
require 'sinatra' def nwd(a,b) a, b = a.abs, b.abs while b > 0 a,b = b, a % b end a end get '/' do erb :index, :layout => false do erb :page_layout end end
true
15a4beb2dcc72a568b6b319304e780483d047c41
Ruby
Lindy-admin/lindy-admin
/rails-app/lib/tasks/lindy.rake
UTF-8
650
2.5625
3
[]
no_license
namespace :lindy do desc "Adds members and registers them to courses" task seed: :environment do Course.all.each do |course| print "seeding #{course.title}\n" 30.times do name = Faker::Name.name space = name.index(" ") firstname = name[0..space-1] lastname = name[space+1..-1] member = Member.create!({firstname: firstname, lastname: lastname, email: Faker::Internet.email, address: Faker::Address.street_address}) ticket = course.tickets.sample role = [true, false].sample course.register(member, {}, role, ticket) end end print "done\n" end end
true
6de80f370e56959cde6d711db687d8932e5331e0
Ruby
amandeep1420/RB101
/RB101/Small Problems/E5/4_letter.rb
UTF-8
1,365
4.9375
5
[]
no_license
# def swap(word) # word_array = word.split(' ') # word_array.each do |word| # first_letter = word[0] # last_letter = word[-1] # word[0] = last_letter # word[-1] = first_letter # end.join(' ') # end # puts swap('Oh what a wonderful day it is') == 'hO thaw a londerfuw yad ti si' # puts swap('Abcde') == 'ebcdA' # puts swap('a') == 'a' # our solution works - took a minute to write it out to explain why it works... # the original objects still existed; we pointed placeholder objects toward them; we used reassignment to change where the array values pointed to, # but used the placeholder variables as references to the original objects... # this sort of thing is summarized within multiple-assignment - the breakdown the book shows illustrates how it's like using placeholder variables. # 'ruby effectively creates a temporary array with the values from the right side, and then assigns array elements into the corresponding named variable. # learned multiple-assignment syntax to swap values ---> a, b = b, a def swap_first_last_characters(a, b) a, b = b, a end def swap(words) result = words.split.map do |word| swap_first_last_characters(word[0], word[-1]) end print result.join(' ') print "\n" end swap('Oh what a wonderful day it is') == 'hO thaw a londerfuw yad ti si' swap('Abcde') == 'ebcdA' swap('a') == 'a'
true
17ec98df81fdcd39e1e1444e859ee105c267cf23
Ruby
hackerway/Crime-Prediction
/code/crime_proc.rb
UTF-8
13,270
3.03125
3
[]
no_license
require 'sqlite3' require './crime_proc_funcs' require './offense_type' $db = SQLite3::Database.open "./crime.db" ########################### Define areas. # Probably better done with hardcoded boundaries. def areaTab() # Create area table. Tables with longitude/latitude information: # codeViol, pr_inc, neighborhood, pd911 tables = ["codeViol", "pr_inc", "neighborhood", "pd911"] lats = [] longs = [] puts "calculating latitude and longitude ranges. . ." tables.each do |t| lats += $db.execute("SELECT MAX(latitude), MIN(latitude) FROM #{t}")[0] longs += $db.execute("SELECT MAX(longitude), MIN(longitude) FROM #{t}")[0] end # queries are returned as strings, convert here to fixnum: lats = lats.map(&:to_f) longs = longs.map(&:to_f) max_lat = lats.max min_lat = lats.min max_long = longs.max #min_long = longs.min #This one is fucked up. min_long = -122.434761 puts "lat ranges from #{min_lat} to #{max_lat}.\n long ranges from #{min_long} to #{max_long}" puts "done.\n" puts "creating areas hash. . ." areas = create_areas(min_lat, min_long, max_lat, max_long, 0.17) puts "done." puts "Inserting values into areas" $db.execute("DROP TABLE IF EXISTS areas") $db.execute("CREATE TABLE areas (areaId, row, col, minLat, minLong, maxLat, maxLong)") sqlite_insert("areas",areas) puts "done.\n" end ########################### Process tables. # Convention: *_proc def neighTab() # Neighborhood puts "populating nh_proc table. . ." $db.execute("DROP TABLE IF EXISTS nh_proc") $db.execute("CREATE TABLE nh_proc (featID INTEGER, areaID TEXT, row INTEGER col INTEGER feat TEXT, lat REAL,long REAL)") nhs = $db.execute("SELECT city_feature, latitude, longitude FROM neighborhood") id = 1000 placeholder = "(?,?,?,?,?,?,?)" (0...nhs.length).each do |i| lat = nhs[i][1] long = nhs[i][2] feat = nhs[i][0] areaID = find_areaID(lat,long) row,col = areaID.split(/_/).map{|i| i.to_i} $db.execute("INSERT INTO nh_proc VALUES #{placeholder}", [id, areaID, row,col,feat, lat, long]) id += 1 end puts "done.\n" end # Codeviol def cvsTab() puts "populating cvs_proc table. . ." $db.execute("DROP TABLE IF EXISTS cv_proc") $db.execute("CREATE TABLE cv_proc ( cvID INTEGER, areaID TEXT, row INTEGER, col INTEGER, case_group TEXT, lat REAL, long REAL, mjd REAL)") cvs = $db.execute("SELECT case_group, latitude, longitude, date_case_created FROM codeViol WHERE case_group IS NOT NULL AND latitude IS NOT NULL AND longitude IS NOT NULL AND date_case_created IS NOT NULL") total = cvs.size id = 1000 placeholder = "(?,?,?,?,?,?,?,?)" (0...cvs.length).each do |i| lat = cvs[i][1] long = cvs[i][2] case_group = cvs[i][0] mjd = date_mjd(cvs[i][3]) areaID = find_areaID(lat,long) row, col = areaID.split(/_/).map{|i| i.to_i} #puts "#{[id, find_areaID(lat,long), case_group, lat, long, mjd].inspect} = #{cvs[i][-1]}" $db.execute("INSERT INTO cv_proc VALUES #{placeholder}", [id, areaID, row, col, case_group, lat, long, mjd]) id += 1 puts "\t#{(id-1000)*100/total} percent done. . ." if ((id-1000)*100.0/total)%1 == 0 end puts "done.\n" end # pr inc def prTab() puts "populating pr_proc table. . ." offense_type = offense_type() pr_incs = $db.execute("SELECT Latitude, Longitude, Hundred_Block_Location, Zone_Beat, Census_Tract_2000, Occurred_Date_or_Date_Range_Start, Occurred_Date_Range_End, Date_Reported, Summarized_Offense_Description, Offense_Type, RMS_CDW_ID FROM pr_inc WHERE Offense_Type IS NOT NULL AND Occurred_Date_or_Date_Range_Start IS NOT NULL AND Latitude IS NOT NULL AND Longitude IS NOT NULL AND Longitude != \"-127.390661925\"") pr_id = 1000 $db.execute("DROP TABLE IF EXISTS pr_proc") $db.execute("CREATE TABLE pr_proc ( prId INTEGER, areaID TEXT, row INTEGER, col INTEGER, latitude REAL, longitude REAL, hundred_block TEXT, zone TEXT, census TEXT, mjd REAL, reported_delay REAL, desc TEXT, off_type TEXT, proc_off_type TEXT)") total = pr_incs.size pr_incs.each do |pr| id = pr_id lat = pr[0]; raise "RMS #{pr[-1]} has invalid lat" if lat.nil? long = pr[1]; raise "RMS #{pr[-1]} has invalid long" if long.nil? areaID = find_areaID(lat,long) row,col = areaID.split(/_/).map{|i| i.to_i} hbl = pr[2] zone= pr[3] census = pr[4] occur = (pr[6].nil?) ? date_mjd(pr[5]) : (date_mjd(pr[5])+date_mjd(pr[6]))/2.0 delay = date_mjd(pr[7]) - occur desc = pr[8] off_type = pr[8] proc_off_type = offense_type[pr[9]] raise "pr[9] not found in dict" if proc_off_type.nil? placeholder = "("+"?,"*13+"?)" $db.execute("INSERT INTO pr_proc VALUES #{placeholder}", [id, areaID, row, col,lat, long, hbl, zone, census, occur, delay, desc, off_type, proc_off_type]) pr_id += 1 puts "\t #{id} of #{total} #{(pr_id-1000)*100/total} percent done. . ." if ((pr_id-1000)*100.0/total)%1== 0 end puts "done." end #pd911 table def pd911Tab() puts "Creating pd911_proc." # keep groupings as is, cap at <500. pd911 = $db.execute("SELECT Event_Clearance_Group, Latitude, Longitude, Census_Tract, Hundred_Block_Location, Zone_Beat, Event_Clearance_Date FROM pd911 WHERE Event_Clearance_Group IS NOT NULL AND Latitude IS NOT NULL AND Longitude IS NOT NULL AND Event_Clearance_Date IS NOT NULL AND Event_Clearance_Group IS NOT NULL AND Census_tract IS NOT NULL") pd911_id = 1000 $db.execute("DROP TABLE IF EXISTS pd911_proc") $db.execute("CREATE TABLE pd911_proc ( pd911Id INTEGER, desc TEXT, latitude REAL, longitude REAL, areaID INTEGER, row INTEGER, col INTEGER, zone TEXT, census TEXT, hundred_block TEXT, mjd REAL)") total = pd911.size pd911.each do |pd| id = pd911_id desc = pd[0] lat = pd[1] long = pd[2] areaID = find_areaID(lat,long) row,col = areaID.split(/_/).map{|i| i.to_i} zone = pd[5] census = pd[3] hbl = pd[4] dt = date_mjd(pd[6]) placeholder = "("+"?,"*10+"?)" $db.execute("INSERT INTO pd911_proc VALUES #{placeholder}", [id,desc,lat,long,areaID,row,col,zone,census,hbl,dt]) puts "\t #{id-1000} of #{total} done" if (id-1000)%10000 == 0 pd911_id+=1 end puts "done" end def timeGrid(tables, interval) min_mjd, max_mjd = getTimeRange(["cv_proc", "pr_proc", "pd911_proc"]) mjds = (min_mjd..max_mjd).step(interval).to_a id = 1000 $db.execute("DROP TABLE IF EXISTS mjds") $db.execute("CREATE TABLE mjds (mjd_id INTEGER, mjd_start INTEGER, mjd_end)") (0..mjds.length).each do |i| $db.execute("INSERT INTO mjds VALUES (?,?,?)", id,mjds[i], mjds[i+1]) id += 1 end end def addTimeGridCols(tbls) tbls.each do |tbl| $db.execute("ALTER TABLE #{tbl} ADD COLUMN mjd_id INTEGER") $db.execute("UPDATE #{tbl} SET mjd_id = (SELECT mjd_id FROM mjds WHERE mjds.mjd_start <= #{tbl}.mjd AND mjds.mjd_end > #{tbl}.mjd)") puts "#{tbl} updated to include time cell" end end def pruneAreas(in_tables) # Detects whether or not each areaID has within it a data object at any point. sql_cmd = "SELECT DISTINCT areaID FROM (" in_tables.each do |t| if t == in_tables[-1] sql_cmd += "SELECT areaID FROM #{t})" else sql_cmd += "SELECT areaID FROM #{t} UNION " end end $db.execute("DELETE FROM areas WHERE areaID NOT IN (#{sql_cmd})") end tbl_params = { 'pr' => { 'tbl' => 'pr_proc', 'src_col' => 'proc_off_type', 'a_range' => 2, 'time_range' => 4 }, 'cv' => { 'tbl' => 'cv_proc', 'src_col' => 'case_group', 'a_range' => 3, 'time_range' => 90 }, 'pd911' => { 'tbl' => 'pd911_proc', 'src_col' => 'desc', 'a_range' => 2, 'time_range' => 4 } } tbl_params.each do |t,v| v['src_cats'] = $db.prepare("SELECT DISTINCT #{v['src_col']} FROM #{v['tbl']}").map{|c| c[0]} v['tgt_cols'] = v['src_cats'].map{|c| noSpecial(c) + "_#{v['tbl']}"} end # 'src_cats' => $db.prepare("SELECT DISTINCT proc_off_type FROM pr_proc" tgt_params = { 'target_mjd_step' => 4, 'nsamp' => 5 # out of 1,000,000 } def main_table(tbl_params, tgt_params) puts "Creating main table. . ." $db.execute("DROP TABLE IF EXISTS main") $db.execute("CREATE TABLE main ( main_id INTEGER, areaID TEXT, row INTEGER, col INTEGER, mjd_start INTEGER )") # populate areaID and time range values. Add columns for values one at a time. areas = $db.execute("SELECT areaID from areas").map{|a| a[0]} mjd_starts = $db.execute("SELECT mjd_start FROM mjds").map{|m| m[0]} main_id = 1000 samp_freq = tgt_params['nsamp']*1000000/(areas.length*mjd_starts.length) expected = (areas.length*mjd_starts.length*samp_freq/1000000.0).floor puts "\tPopulating ids, expect #{expected} samples. . ." insert_string = "INSERT INTO main VALUES " areas.each do |a| mjd_starts.each do |m| if samp_freq >= rand(1000000) row,col = a.split(/_/).map{|i| i.to_i} insert_string += "(#{main_id}, '#{a}', #{row}, #{col},#{m})," main_id += 1 end end end $db.execute(insert_string[0...-1]) tbl_params.each do |k,v| (0...v['tgt_cols'].length).each do |i| puts "tgt_col = #{v['tgt_cols'][i]}" $db.execute("ALTER TABLE main ADD COLUMN #{v['tgt_cols'][i]} INTEGER") sql_cmd = "UPDATE main SET #{v['tgt_cols'][i]} = (SELECT COUNT(*) FROM #{v['tbl']} WHERE #{v['src_col']} == '#{v['src_cats'][i]}' AND #{v['tbl']}.mjd < main.mjd_start AND #{v['tbl']}.mjd > (main.mjd_start - #{v['time_range']}) AND #{v['tbl']}.row < main.row + #{v['a_range']} AND #{v['tbl']}.row >= main.row - #{v['a_range']} AND #{v['tbl']}.col < main.col + #{v['a_range']} AND #{v['tbl']}.col >= main.col - #{v['a_range']} )" puts "\t\t\t#{v["tgt_cols"][i]} added." #p $db.prepare("SELECT * FROM main").columns.inspect $db.execute(sql_cmd) end # UPDATE main SET NUISANCE_MISCHIEF__pd911_proc = (SELECT COUNT(*) FROM pd911_proc WHERE pd911_proc.mjd < main.mjd_start AND pd911_proc.areaID == main.areaID); end end #cvsTab() #pd911Tab() #neighTab() #prTab() #pruneAreas(['pr_proc', 'cv_proc', 'nh_proc', 'pd911_proc']) #timeGrid(['pr_proc', 'cv_proc', 'pd911_proc'],4) #addTimeGridCols(['cv_proc','pr_proc','pd911_proc']) #main_table(tbl_params, tgt_params) $db.execute( 'DELETE FROM pd911_proc_filt WHERE latitude < 47.54067 OR latitude > 47.69898 OR longitude < -122.3725 OR longitude > -122.2901 OR mjd < 55402.73 OR mjd > 56342.02') def pd911_main() # create a table by zone. cols_src = $db.execute("SELECT DISTINCT(desc) FROM pd911_proc_filt").map{|m| m[0]} cols_dest = cols_src.map{|c| noSpecial(c)} sql = "CREATE TABLE pd911_main (row INTEGER, col INTEGER, mjds_start REAL" cols_dest.each do |c| sql += "," + c end $db.execute("DROP TABLE IF EXISTS pd911_main") $db.execute(sql + ")") nonNullClause = ' WHERE col IS NOT NULL AND row IS NOT NULL AND mjd IS NOT NULL AND desc IS NOT NULL' min,max = $db.execute("SELECT MIN(mjd), MAX(mjd) FROM pd911_proc_filt" + nonNullClause)[0] rowsMin, rowsMax = $db.execute("SELECT MIN(row), MAX(row) FROM pd911_proc_filt" + nonNullClause)[0] colsMin, colsMax = $db.execute("SELECT MIN(col), MAX(col) FROM pd911_proc_filt" + nonNullClause)[0] timeStep = 45 areaStep = 3 # Time period: 60 interval starting with mjd numCols = $db.prepare("SELECT * FROM pd911_main").columns.length m = min zones = $db.execute("SELECT DISTINCT zone FROM pd911_proc_filt").map{|m| m[0]} start = Time.new() numbdone = 0 total = ((rowsMax-rowsMin) * (colsMax-colsMin)* (max-min)/(timeStep*areaStep**2)).round (min..max).step(timeStep) do |m| (rowsMin..rowsMax).step(areaStep) do |r| (colsMin..colsMax).step(areaStep) do |c| sql = "" (0...cols_src.length).each do |i| # form sql statement sql += " UNION ALL SELECT COUNT(*) FROM pd911_proc_filt WHERE row IS NOT NULL AND col IS NOT NULL AND mjd IS NOT NULL AND desc IS NOT NULL AND row >= #{r} AND row < #{r+areaStep} AND col >= #{c} AND col < #{c+areaStep} AND mjd >= #{m} AND mjd < #{m+60} AND desc = '#{cols_src[i]}'" end # remove leading 'union all' sql = sql[10..-1] # create insert: data = $db.execute(sql).map{|m| m[0]} sql = "INSERT INTO pd911_main VALUES(#{r}, #{c}, #{m}" data.each do |d| sql += ",#{d}" end sql += ")" puts sql $db.execute(sql) numbdone += 1 timeleft = (Time.new-start)*total / numbdone puts "#{numbdone} of #{total} done, #{(timeleft/60).round/60} hours, #{(timeleft/60).round%60} minutes remaining" end end end puts 'populating' end pd911_main() __END__ #SELECT COUNT(*) FROM pd911_proc WHERE zone IS NOT NULL AND mjd IS NOT NULL AND desc IS NOT NULL AND zone == 'N1' AND mjd >= 55053.92152777778 AND mjd < 55113.92152777778 AND desc = 'NARCOTICS COMPLAINTS' UNION ALL SELECT COUNT(*) FROM pd911_proc #puts '################ This might take a while. Have you turned off disk hibernation?' #areaTab() #neighTab() #cvsTab() #prTab() #pd911Tab() #pruneAreas(['pr_proc', 'cv_proc', 'nh_proc', 'pd911_proc']) #timeGrid(['pr_proc', 'cv_proc', 'pd911_proc'],4) #addTimeGridCols(['cv_proc'])
true
8e9d562438a000d39b0e89ca3014c0ff1cfd64fc
Ruby
HewlettPackard/oneview-chef
/libraries/resource_provider.rb
UTF-8
14,974
2.5625
3
[ "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
# (c) Copyright 2016 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. module OneviewCookbook # Base class for resource providers class ResourceProvider attr_accessor \ :context, # Ususally a Chef resource's context (self) :resource_name, # The Chef resource's type. e.g., oneview_ethernet_network :name, # Name of the Chef resource. e.g., EthNet1 :item, # The OneviewSDK resource instance :sdk_api_version, # Keep track of the API version used for the SDK resource class :sdk_variant, # Keep track of the variant used for the SDK resource class :sdk_resource_type, # Keep track of the SDK resource class name :sdk_base_module # Keep track of the internal base SDK module def initialize(context) @sdk_base_module = OneviewSDK @context = context @new_resource = context.new_resource @resource_name = context.new_resource.resource_name @name = context.new_resource.name klass = parse_namespace client_api_version = if context.property_is_set?(:client) if context.new_resource.client.is_a?(Hash) convert_keys(context.new_resource.client, :to_sym)[:api_version] elsif context.new_resource.client.is_a?(OneviewSDK::Client) # It works for both Image Streamer and OneView context.new_resource.client.api_version end end # If client.api_verion is not set, it sets appliance's max api version @new_resource.client.delete(:api_version) unless client_api_version c = if @sdk_base_module == OneviewSDK::ImageStreamer OneviewCookbook::Helper.build_image_streamer_client(@new_resource.client) else OneviewCookbook::Helper.build_client(@new_resource.client) end new_data = JSON.parse(@new_resource.data.to_json) rescue @new_resource.data @item = context.property_is_set?(:api_header_version) ? klass.new(c, new_data, @new_resource.api_header_version) : klass.new(c, new_data) Chef::Log.info("API Version #{@item.api_version}") @item['name'] ||= @new_resource.name end # rubocop:disable Metrics/MethodLength # Helper method that analyzes the namespace and defines the class variables and the resource class itself # @return [OneviewSDK::Resource] SDK resource class # @raise [NameError] If for some reason the method could not resolve the namespace to a OneviewSDK::Resource def parse_namespace klass_name = self.class.to_s Chef::Log.debug("Resource '#{@resource_name}' received with the '#{klass_name}' class name") name_arr = klass_name.split('::') @sdk_resource_type = name_arr.pop.gsub(/Provider$/i, '') # e.g., EthernetNetwork case name_arr.size when 1 Chef::Log.debug("Resource '#{klass_name}' has no variant or api version specified.") # This case should really only be used for testing # Uses the SDK's default api version and variant return OneviewSDK.resource_named(@sdk_resource_type) when 2 # No variant specified. e.g., OneviewCookbook::API200::EthernetNetworkProvider Chef::Log.debug("Resource '#{klass_name}' has no variant specified.") @sdk_api_version = name_arr.pop.gsub(/API/i, '').to_i # e.g., 200 @sdk_variant = nil # Not needed when 3 # Parses all the namespace when it is fully specified with API version, variant or base module case klass_name when /ImageStreamer/ Chef::Log.debug("Resource '#{klass_name}' is a Image Streamer resource.") @sdk_api_version = name_arr.pop.gsub(/API/i, '').to_i # e.g., 300 @sdk_base_module = OneviewSDK.const_get(name_arr.pop) # ImageStreamer @sdk_variant = nil # Not needed else # The variant is specified. e.g., OneviewCookbook::API200::C7000::EthernetNetworkProvider Chef::Log.debug("Resource '#{klass_name}' has variant and api version specified.") @sdk_variant = name_arr.pop # e.g., C7000 @sdk_api_version = name_arr.pop.gsub(/API/i, '').to_i # e.g., 200 end else # Something is wrong raise NameError, "Can't build a resource object from the class #{self.class}" end klass = @sdk_base_module.resource_named(@sdk_resource_type, @sdk_api_version, @sdk_variant) Chef::Log.debug("#{@resource_name} namespace parsed: > SDK Base Module: #{@sdk_base_module} <#{@sdk_base_module.class}> > SDK API Version: #{@sdk_api_version} <#{@sdk_api_version.class}> > SDK Variant: #{@sdk_variant} <#{@sdk_variant.class}> > SDK Resource Type: #{@sdk_resource_type} <#{@sdk_resource_type.class}> ") klass end # rubocop:enable Metrics/MethodLength # Creates the OneView resource or updates it if exists # @param [Symbol] method_1 Method used to create/add # @param [Symbol] method_2 Method used to update/edit # @return [TrueClass, FalseClass] Returns true if the resource was created, false if updated or unchanged def create_or_update(method_1 = :create, method_2 = :update) ret_val = false desired_state = Marshal.load(Marshal.dump(@item.data)) if @item.exists? @item.retrieve! if @item.like? desired_state Chef::Log.info("#{@resource_name} '#{@name}' is up to date") else diff = get_diff(@item, desired_state) Chef::Log.info "#{method_2.to_s.capitalize} #{@resource_name} '#{@name}'#{diff}" Chef::Log.debug "#{@resource_name} '#{@name}' Chef resource differs from OneView resource." Chef::Log.debug "Current state: #{JSON.pretty_generate(@item.data)}" Chef::Log.debug "Desired state: #{JSON.pretty_generate(desired_state)}" @context.converge_by "#{method_2.to_s.capitalize} #{@resource_name} '#{@name}'" do @item.update(desired_state) end end else create(method_1) ret_val = true end save_res_info ret_val end # Adds the resource to OneView or edits it if exists # @return [TrueClass, FalseClass] Returns true if the resource was added, false if edited or unchanged def add_or_edit create_or_update(:add, :edit) end # Creates the OneView resource only if it doesn't exist # @param [Symbol] method Create or add method # @return [TrueClass, FalseClass] Returns true if the resource was created/added def create_if_missing(method = :create) ret_val = false if @item.exists? Chef::Log.info("#{@resource_name} '#{@name}' exists. Skipping") @item.retrieve! if @new_resource.save_resource_info else create(method) ret_val = true end save_res_info ret_val end # Adds a resource to OneView only if it doesn't exist # @return [TrueClass, FalseClass] Returns true if the resource was added def add_if_missing create_if_missing(:add) end # Delete the OneView resource if it exists # @param [Symbol] method Delete or remove method # @return [TrueClass, FalseClass] Returns true if the resource was deleted/removed def delete(method = :delete) return false unless @item.retrieve! @context.converge_by "#{method.to_s.capitalize} #{@resource_name} '#{@name}'" do @item.send(method) end true end # Remove the OneView resource if it exists # @return [TrueClass, FalseClass] Returns true if the resource was removed def remove delete(:remove) end # Performs patch operation # It needs the context properties 'operation' and 'path'. # 'value' property is optional. # @return [TrueClass] true if the resource was patched def patch invalid_params = @new_resource.operation.nil? || @new_resource.path.nil? raise "InvalidParameters: Parameters 'operation' and 'path' must be set for patch" if invalid_params raise "ResourceNotFound: Patch failed to apply since #{@resource_name} '#{@name}' does not exist" unless @item.retrieve! @context.converge_by "Performing '#{@new_resource.operation}' at #{@new_resource.path} with #{@new_resource.value} in #{@resource_name} '#{@name}'" do @item.patch(@new_resource.operation, @new_resource.path, @new_resource.value) end true end # This method is shared between multiple actions and takes care of the creation of the resource. # Only call this method if the resource does not exist and needs to be created. # @param [Symbol] method Create method def create(method = :create) Chef::Log.info "#{method.to_s.capitalize} #{@resource_name} '#{@name}'" @context.converge_by "#{method.to_s.capitalize} #{@resource_name} '#{@name}'" do @item.send(method) end end # Adds scopes to the Oneview resource if scope is not already added def add_to_scopes apply_scopes_action(:add_to_scopes, :add_scope) { |scope| @item['scopeUris'].include?(scope['uri']) } end # Removes scopes from the Oneview resource if scope is already added def remove_from_scopes apply_scopes_action(:remove_from_scopes, :remove_scope) { |scope| !@item['scopeUris'].include?(scope['uri']) } end # Helper method to apply method related to add or remove scopes in Oneview resource def apply_scopes_action(action, resource_method, &ignore_scope_if) return Chef::Log.info("No scopes were specified to perform #{action}. Skipping") if @new_resource.scopes.nil? || @new_resource.scopes.empty? raise "ResourceNotFound: #{@resource_name} '#{@name}' does not exist" unless @item.retrieve! scopes = @new_resource.scopes.map { |scope_name| load_resource(:Scope, scope_name) } scopes.delete_if(&ignore_scope_if) return Chef::Log.info("'#{action}' with '#{@new_resource.scopes}' to #{@resource_name} '#{@name}' is not needed. Skipping") if scopes.empty? scope_names = scopes.map { |scope| scope['name'] }.sort @context.converge_by "Performing #{action} '#{scope_names}' in #{@resource_name} '#{@name}'" do scopes.each do |scope| @item.send(resource_method, scope) end end end # Replaces scopes to the Oneview resource def replace_scopes return Chef::Log.info('No scopes were specified to perform replace_scopes. Skipping') if @new_resource.scopes.nil? raise "ResourceNotFound: #{@resource_name} '#{@name}' does not exist" unless @item.retrieve! scopes = @new_resource.scopes.map { |scope_name| load_resource(:Scope, scope_name) } scope_uris = scopes.map { |scope| scope['uri'] } if @item['scopeUris'].sort == scope_uris.sort return Chef::Log.info("Scopes '#{@new_resource.scopes}' already are scopes of #{@resource_name} '#{@name}'. Skipping") end @context.converge_by "Replaced Scopes '#{@new_resource.scopes.sort}' for #{@resource_name} '#{@name}'" do @item.replace_scopes(scopes) end end # Gathers the OneviewSDK correct resource class # @param [Symbol, String] resource Resource name/type desired # @param [Integer] version Version of the SDK desired # @param [String] variant Variant of the SDK desired # @return [OneviewSDK::Resource] Returns the class of the resource in the loaded API version and variant def resource_named(resource, version = @sdk_api_version, variant = @sdk_variant) @sdk_base_module.resource_named(resource, version, variant) end # Save the data from a resource to a node attribute # @param [TrueClass, FalseClass, Array] attributes Attributes to save (or true/false) # @param [String, Symbol] name Resource name # @param [OneviewSDK::Resource] item to save data for # (@new_resource.save_resource_info, @name, @item) def save_res_info ov_url = @item.client.url.to_s case @new_resource.save_resource_info when Array # save subset @context.node.default['oneview'][ov_url][@name.to_s] = @item.data.select { |k, _v| @new_resource.save_resource_info.include?(k) } when TrueClass # save all @context.node.default['oneview'][ov_url][@name.to_s] = @item.data end rescue StandardError => e Chef::Log.error "Failed to save resource data for '#{@name}': #{e.message}" end # Utility method that converts Hash symbol to string keys # See the OneviewCookbook::Helper.convert_keys method for param details def convert_keys(info, conversion_method) OneviewCookbook::Helper.convert_keys(info, conversion_method) end # Get the diff of the current resource state and the desired state # See the OneviewCookbook::Helper.get_diff method for param details def get_diff(resource, desired_data) diff = OneviewCookbook::Helper.get_diff(resource, desired_data) return '. (no diff)' if diff.to_s.empty? ". Diff: #{diff}" end # Get the diff of the current resource state and the desired state # See the OneviewCookbook::Helper.recursive_diff method for param details def recursive_diff(data, desired_data, str = '', indent = '') OneviewCookbook::Helper.recursive_diff(data, desired_data, str, indent) end # Retrieve a resource by type and identifier (name or data) # See the OneviewCookbook::Helper.load_resource method for param details def load_resource(resource_class_type, resource_id, ret_attribute = nil) OneviewCookbook::Helper.load_resource( @item.client, type: resource_class_type, id: resource_id, ret_attribute: ret_attribute, api_ver: @sdk_api_version, variant: @sdk_variant, base_module: @sdk_base_module ) end # Validates the presence of resource properties # @param [Symbol] property An property name to be validating presence # @param [Symbol] ... More property names # @raise [RuntimeError] if some property is not set def validate_required_properties(*properties) properties.each { |property| raise("Unspecified property: '#{property}'. Please set it before attempting this action.") unless @new_resource.public_send(property) } end end end # Load all resource providers: Dir[File.dirname(__FILE__) + '/resource_providers/*.rb'].each { |file| require file }
true
878968860dbe199564b51e8f3ff9558802307301
Ruby
maikeru/vending_machine
/lib/vending_machine.rb
UTF-8
668
3.703125
4
[]
no_license
#require 'drink' class VendingMachine DENOMINATIONS = [10, 50, 100, 500, 1000] def initialize @total_inserted = 0 @drink = Drink.new "Coke", 120, 5 end def insert_money value if DENOMINATIONS.include? value @total_inserted += value else refund value end end def get_total_inserted @total_inserted end def refund value=get_total_inserted "Refund: #{value}" end def get_drinks "#{@drink.quantity}x #{@drink.name} at #{@drink.price} yen" end end class Drink attr_reader :name, :price, :quantity def initialize name, price, quantity @name, @price, @quantity = name, price, quantity end end
true
c790d562cff582083bbec5e290a4194f96c44153
Ruby
jesse-zonneveld/App-Academy-Open
/13 Chess/board.rb
UTF-8
2,981
3.625
4
[]
no_license
require_relative "pieces" require "byebug" class Board attr_reader :null_piece, :grid def initialize(dup_bool = false) @null_piece = NullPiece.instance setup_board(dup_bool) end def [](pos) x, y = pos @grid[x][y] end def []=(pos, piece) x, y = pos @grid[x][y] = piece end def move_piece(cur_color, start_pos, end_pos) raise "Sorry, there isn't a chess piece located at that position." if self[start_pos] == nil moving_piece = self[start_pos] if moving_piece.color != cur_color raise "Sorry, you can't move the other player's piece." elsif !moving_piece.moves.include?(end_pos) raise "Sorry, you can't move your piece to that location." elsif !moving_piece.valid_moves.include?(end_pos) raise "Sorry, you can't move into check." end move_piece!(start_pos, end_pos) end #moves piece regardless of if in check for the method moves_into_check def move_piece!(start_pos, end_pos) moving_piece = self[start_pos] self[start_pos] = @null_piece self[end_pos] = moving_piece moving_piece.pos = end_pos end def add_piece(piece, pos) raise "position not empty." unless self.empty?(pos) self[pos] = piece end def empty?(pos) self[pos] == @null_piece end def valid_pos?(pos) pos.all? { |coord| coord.between?(0,7) } end def in_check?(color) king_pos = find_king(color).pos pieces.any? { |piece| piece.color != color && piece.moves.include?(king_pos) } end def checkmate?(color) return false unless in_check?(color) pieces.select { |piece| piece.color == color }.all? do |piece| piece.valid_moves.empty? end end def pieces grid.flatten.reject { |piece| piece.empty? } end def dup new_board = Board.new(true) pieces.each do |piece| piece.class.new(piece.color, new_board, piece.pos) end new_board end private def setup_board(dup_bool) @grid = Array.new(8) { Array.new(8, @null_piece) } return if dup_bool [:white, :black].each do |color| set_back_row(color) set_pawn_row(color) end end def set_back_row(color) back_row_layout = [Rook, Knight, Bishop, Queen, King, Bishop, Knight, Rook] row = (color == :white ? 7 : 0) back_row_layout.each_with_index { |piece_class, y| piece_class.new(color, self, [row, y]) } end def set_pawn_row(color) back_row_layout = [] row = (color == :white ? 6 : 1) 8.times { |y| Pawn.new(color, self, [row, y]) } end def find_king(color) pieces.find { |piece| piece.color == color && piece.is_a?(King) } end end # if $PROGRAM_NAME == __FILE__ # b = Board.new # p b.pieces # end
true
2b04b504b73c15c4971528cfdb66cf69c44f65ae
Ruby
Inglorion-G/mythal
/lib/mythal/npc.rb
UTF-8
1,128
2.671875
3
[ "MIT" ]
permissive
module Mythal class Npc include Procto.call def initialize(challenge_rating: "1/4", user_overrides: {}) @challenge_rating = challenge_rating @user_overrides = user_overrides end def call self end def stats @stats ||= Mythal::Stats.new( challenge_rating: challenge_rating, options: (user_overrides || {}), ) end def character_description trait + " " + race + " " + dnd_class end def dnd_class config.dnd_classes.sample end def race config.races.sample end def trait config.traits.sample end def message <<~OUTPUT --- #{character_description} --- Armor Class: #{stats.armor_class} Hit Points: #{stats.hit_points} Attack: +#{stats.attack_bonus} Damage: #{stats.damage_per_round} slashing Speed: #{stats.speed}ft Challenge Rating: #{stats.challenge_rating} --- OUTPUT end private attr_reader :user_overrides, :challenge_rating def config Mythal::Config end end end
true
6c8ea5b3b6b9f31e03efc2a441d04aa1c5f61a92
Ruby
buithehoa/rspec-3-book
/book-code/06-integration-specs/09/expense_tracker/spec/integration/app/ledger_spec.rb
UTF-8
1,837
2.53125
3
[ "MIT" ]
permissive
require_relative '../../../app/ledger' module ExpenseTracker RSpec.describe Ledger, :aggregate_failures, :db do let(:ledger) { Ledger.new } let(:expense) do { 'payee' => 'Starbucks', 'amount' => 5.75, 'date' => '2017-06-10' } end describe '#record' do # ... contexts go here ... context 'with a valid expense' do it 'successfully saves the expense in the DB' do result = ledger.record(expense) expect(result).to be_success expect(DB[:expenses].all).to match [a_hash_including( id: result.expense_id, payee: 'Starbucks', amount: 5.75, date: Date.iso8601('2017-06-10') )] end end context 'when the expense lacks a payee' do it 'rejects the expense as invalid' do expense.delete('payee') result = ledger.record(expense) expect(result).not_to be_success expect(result.expense_id).to eq(nil) expect(result.error_message).to include('`payee` is required') expect(DB[:expenses].count).to eq(0) end end end describe '#expenses_on' do it 'returns all expenses for the provided date' do result_1 = ledger.record(expense.merge('date' => '2017-06-10')) result_2 = ledger.record(expense.merge('date' => '2017-06-10')) result_3 = ledger.record(expense.merge('date' => '2017-06-11')) expect(ledger.expenses_on('2017-06-10')).to contain_exactly( a_hash_including(id: result_1.expense_id), a_hash_including(id: result_2.expense_id) ) end it 'returns a blank array when there are no matching expenses' do expect(ledger.expenses_on('2017-06-10')).to eq([]) end end end end
true
0fdcb6ac201fbcf9bf33edc4db428d84d99bf83c
Ruby
marcosrafaellsousa/Curso-ruby-cucumber-capybara
/secao 5/xpath/mapeando_elementos.rb
UTF-8
1,621
3.921875
4
[]
no_license
# Referências: https://www.w3schools.com/xml/xpath_intro.asp # # Elemento HTML são composto por: # # Exemplo: <p class="important"> This is a paragraph </p> # # Abertura da tag: <p # Conjunto de atributos e valores: # Nome do atributo: class= # Valor do atributo: "important"> # Conteúdo do elemento: This is a paragraph # Fechamento da tag: </p> # # # Xpath (XML Path Language) é uma linguagem que facilita a busca de elementos em uma estrutura de árvore # # Exemplos da notação: # / Nó raiz # // Nós no documento a partir do nó atual # . Seleciona o nó atual # .. Seleciona o pai do nó atual # @ Seleciona atributos # # Predicados: Usados para buscar um nó específico # Exemplos de predicados: # /bookstore/book[1] Seleciona o primeiro elemento do nó livro # /bookstore/book[last ()] Último elemento do nó livro # /bookstore/book[last () - 1] Penúltimo elemento # /bookstore/book[position () < 3] Dois primeiros elementos # //title[@lang] Seleciona todos os elementos que possuem um atributo 'lang' # //title[@lang='EN'] Todos os elementos que possuem um atributo 'lang' com valor 'EN' # /bookstore/book[price < 35.00] Seleciona todos os elementos que possuem um outro elemento chamado 'preco' # com um valor menor que 35.00 # /bookstore/book[price < 35.00]/title Seleciona o título de todos os elementos que possuem um outro elemento # chamado 'preco' com um valor menor que 35.00
true
c1a5f9c460f16468c08bc2b3f208003d2aca1c46
Ruby
mlresearch/papersite
/ruby/old-mlresearch.rb
UTF-8
14,172
2.65625
3
[ "MIT" ]
permissive
require 'rubygems' require 'bibtex' require 'yaml' require 'facets' require 'latex/decode' require 'latex/decode/version' require 'latex/decode/compatibility' require 'latex/decode/base' require 'latex/decode/accents' require 'latex/decode/diacritics' require 'latex/decode/maths' require 'latex/decode/punctuation' require 'latex/decode/symbols' require 'latex/decode/greek' require "active_support/inflector" require 'fileutils' require 'pandoc-ruby' PandocRuby.pandoc_path = '/usr/local/bin/pandoc' class String def is_i? /\A[-+]?\d+\z/ === self end end module MLResearch def self.basedir # Get base of directory containing `papersite` repo by going three # steps up from where this file is located File.dirname(__FILE__).split('/')[0..-3].join('/') end def self.procdir self.basedir + '/' end def self.bibdir self.procdir + '/papersite/db/' end def self.url 'http://proceedings.mlr.press' end def self.tracking_id 'UA-92432422-1' end def self.github 'mlresearch' end def self.twitter 'MLResearchPress' end def self.markdown 'kramdown' end def self.publisher 'Proceedings of Machine Learning Research' end def self.email '' end def self.detex(string) # Returning up to second end character is to deal with new line return string unless string.respond_to?(:to_s) string = string.is_a?(String) ? string.dup : string.to_s LaTeX::Decode::Base.normalize(string) LaTeX::Decode::Accents.decode!(string) LaTeX::Decode::Diacritics.decode!(string) LaTeX::Decode::Punctuation.decode!(string) LaTeX::Decode::Symbols.decode!(string) LaTeX::Decode::Greek.decode!(string) #LaTeX::Decode::Base.strip_braces(string) LaTeX.normalize_C(string) # Need to deal with different encodings. Map to utf-8 end def self.detex_tex_title(string) # Returning up to second end character is to deal with new line return string unless string.respond_to?(:to_s) string = string.is_a?(String) ? string.dup : string.to_s LaTeX::Decode::Base.normalize(string) LaTeX::Decode::Accents.decode!(string) LaTeX::Decode::Diacritics.decode!(string) LaTeX::Decode::Punctuation.decode!(string) LaTeX::Decode::Symbols.decode!(string) LaTeX::Decode::Greek.decode!(string) LaTeX.normalize_C(string) # Need to deal with different encodings. Map to utf-8 end #def self.detex_abstract(text) # return PandocRuby.convert(text, {:from => :latex, :to => :markdown}, 'no-wrap')[0..-2] #end def self.bibtohash(obj) # Takes an bib file object and returns a cleaned up hash. # Params: # +obj+:: Object to clean up # +bib+:: +BibTeX+ object that contains strings etc # +errhandler+:: +Proc+ object that takes a pipe object as first and only param (may be nil) ha = obj.to_hash(:quotes=>'').rekey!(&:to_s) ha['layout'] = ha['bibtex_type'].to_s ha.tap { |hs| hs.delete('bibtex_type') } ha['series'] = "Proceedings of Machine Learning Research" ha['id'] = ha['bibtex_key'].to_s ha.tap { |hs| hs.delete('bibtex_key') } #ha['categories'] = Array.new(1) #ha['categories'][0] = ha['key'] ha['month'] = ha['month_numeric'].to_i ha.tap { |hs| hs.delete('month_numeric') } ha.delete_if {|key, value| key[0..2] == "opt" } if ha.has_key?('abstract') if ha['abstract'] == '' ha.tap { |hs| hs.delete('abstract') } else ha['abstract'] = detex(ha['abstract']) end end if ha.has_key?('title') ha['tex_title'] = detex_tex_title(ha['title']) ha['title'] = detex(ha['title']) end if ha.has_key?('pages') pages = ha['pages'].split('-') pages[0] = pages[0].strip pages[-1] = pages[-1].strip if pages[0].is_i? ha['firstpage'] = pages[0].to_i else ha['firstpage'] = pages[0] end if pages[-1].is_i? ha['lastpage'] = pages[-1].to_i else ha['lastpage'] = pages[-1] end ha['page'] = ha['firstpage'].to_s + '-' + ha['lastpage'].to_s ha.tap { |hs| hs.delete('pages') } end if ha.has_key?('firstpage') ha['order'] = ha['firstpage'].to_i end published = ha['published'] ha['cycles'] = false if ha.has_key?('sections') sections = ha['sections'].split('|') hasections = Array.new(sections.length) section_dates = ha['published'].split('|') sections.each.with_index do |section, index| name_title = section.split('=') if(section_dates.length==hasections.length) date = Date.parse section_dates[index] hasections[index] = {'name' => name_title[0], 'title' => name_title[-1], 'published' => date} ha['cycles']= true else hasections[index] = {'name' => name_title[0], 'title' => name_title[-1]} end end ha['sections'] = hasections end if ha.has_key?('editor') editor = splitauthors(ha, obj, type=:editor) ha.tap { |hs| hs.delete('editor') } ha['editor'] = editor end if ha.has_key?('author') author = splitauthors(ha, obj) ha.tap { |hs| hs.delete('author') } ha['author'] = author end if ha.has_key?('published') ha['published'] = Date.parse ha['published'] else #ha['date'] = Date.parse "0000-00-00 00:00:00" end if ha.has_key?('start') ha['start'] = Date.parse ha['start'] end if ha.has_key?('end') ha['end'] = Date.parse ha['end'] end return ha end def self.yamltohash(obj) end def self.mindigit(str, num=2) str.gsub(/-[0-9]+/, '') while str.length < num str = '0' + str end return str end def self.filename(date, title) puts title f = date.to_s + '-' + title.to_s + '.md' return f end def self.splitauthors(ha, obj, type=:author) a = Array.new(obj[type].length) #=> [nil, nil, nil] obj[type].each.with_index(0) do |name, index| first = detex(name.first) last = detex(name.last) a[index] = {'given' => first, 'family' => last} end return a end def self.extractpapers(bib_file, volume, volume_info) # Extract paper info from bib file and put it into yaml files in _posts file = File.open(bib_file, "rb") contents = file.read bib = BibTeX.parse(contents) # do work on files ending in .rb in the desired directory ids = [] bib['@inproceedings'].each do |obj| obj.replace(bib.q('@string')) obj.join ha = bibtohash(obj) ha['date'] = volume_info['published'] published = ha['date'] if ha.has_key?('section') if volume_info.has_key?('sections') volume_info['sections'].each_with_index do |item, index| if ha['section'] == item['name'] if item.has_key?('published') published = item['published'] ha['date'] = item['published'] ha['number'] = index + 1 end end end end end ha['address'] = volume_info['address'] ha['publisher'] = 'PMLR' ha['container-title'] = volume_info['booktitle'] ha['volume'] = volume.to_s ha['genre'] = 'inproceedings' ha['issued'] = {'date-parts' => [published.year, published.month, published.day]} letter = 97 # Fix up the filestubs filestub = (ha['author'][0]['family'].downcase + volume_info['published'].strftime('%y') + letter.chr).parameterize while ids.include? filestub letter += 1 filestub = (ha['author'][0]['family'].downcase + volume_info['published'].strftime('%y') + letter.chr).parameterize end ids.push(filestub) puts filestub #puts ha['author'][0]['family'] + published.year.to_s.slice(-2,-1) + 'a' #puts ha['id'] # True for volumes that didn't necessarily conform to original layout puts volume.to_i inc_layout = ([27..53] + [55..56] + [63..64]).include?(volume.to_i) puts inc_layout puts # Move all pdfs to correct directory with correct filename if inc_layout ha['pdf'] = 'http://proceedings.mlr.press' + '/v' + ha['volume'] + '/' + ha['id'] + '.pdf' else if File.file?(ha['id'] + '.pdf') Dir.mkdir(filestub) unless File.exists?(filestub) if not File.file?(filestub + '/' + filestub + '.pdf') FileUtils.mv(ha['id'] + '.pdf', filestub + '/' + filestub + '.pdf') end end if File.file?(filestub + '/' + filestub + '.pdf') ha['pdf'] = 'http://proceedings.mlr.press' + '/v' + ha['volume'] + '/' + filestub + '/' + filestub + '.pdf' else raise "PDF " + filestub + '/' + filestub + '.pdf' + " file not present" end end # Move all supplementary files to relevant directory Dir.glob(ha['id'] +'-supp.*') do |supp_file| newfilename = supp_file.gsub(ha['id'], filestub) Dir.mkdir(filestub) unless File.exists?(filestub) if not File.file?(filestub + '/' + newfilename) FileUtils.mv(supp_file, filestub + '/' + newfilename) end end if ha.has_key?('supplementary') supple = ha['supplementary'].split(':')[-1] else supple = filestub + '-supp.pdf' end # Link to all -supp files in directory if inc_layout ha['supplementary'] = 'http://proceedings.mlr.press' + '/v' + ha['volume'] + '/' + supple else ha['extras'] = [] Dir.glob(filestub + '/' + filestub +'-supp.*') do |supp_file| ha['extras'] += [{'label' => 'Supplementary ' + File.extname(supp_file)[1..-1].upcase, 'link' => 'http://proceedings.mlr.press' + '/v' + ha['volume'] + '/' + supp_file}] end end # If it's not in the bad layout then update key if not inc_layout ha['id'] = filestub end ya = ha.to_yaml(:ExplicitTypes => true) fname = filename(published, filestub) out = File.open('_posts/' + fname, 'w') out.puts ya out.puts "# Format based on citeproc: http://blog.martinfenner.org/2013/07/30/citeproc-yaml-for-bibliographies/" out.puts "---" end end def self.extractconfig(bibfile, volume) # Extract information about the volume from the bib file, place in _config.yml file = File.open(bibfile, "rb") contents = file.read reponame = 'v' + volume.to_s bib = BibTeX.parse(contents) obj = bib['@proceedings'][0] obj.replace(bib.q('@string')) obj.join ha = bibtohash(obj) puts ha ha['title'] = "Proceedings of Machine Learning Research" booktitle = ha['booktitle'] ha['description'] = booktitle if ha.has_key?('address') ha['description'] += "\n Held in " + ha['address'] end if ha.has_key?('start') and ha.has_key?('end') ha['description'] += " on " if (ha['start'].year == ha['end'].year) and (ha['start'].month == ha['end'].month) if (ha['start'].day == ha['end'].day) ha['description'] += "#{ha['end'].strftime('%d %B %Y')}" ha['date_str'] = "#{ha['end'].strftime('%d %b')}" else ha['description'] += "#{ha['start'].strftime('%d')}-#{ha['end'].strftime('%d %B %Y')}" ha['date_str'] = "#{ha['start'].strftime('%d')}--#{ha['end'].strftime('%d %b')}" end else ha['description'] += "#{ha['start'].strftime('%d %B')} to #{ha['end'].strftime('%d %B %Y')}" ha['date_str'] = "#{ha['start'].strftime('%d %b')}--#{ha['end'].strftime('%d %b')}" end end if(ha['cycles']) ha['description'] += "\n\nPublished in #{ha['sections'].length} Sections as Volume " + volume.to_s + " by the Proceedings of Machine Learning Research.\n" ha['sections'].each.with_index(0) do |section, index| ha['description'] += " #{section['title']} published on #{section['published'].strftime('%d %B %Y')}\n" end else ha['description'] += "\n\nPublished as Volume " + volume.to_s + " by the Proceedings of Machine Learning Research on #{ha['published'].strftime('%d %B %Y')}." + "\n" end if ha.has_key?('editor') ha['description'] += "\nVolume Edited by:\n" for name in ha['editor'] ha['description'] += " #{name['given']} #{name['family']}\n" end end ha['description'] += "\nSeries Editors:\n Neil D. Lawrence\n" if (volume.to_i>27) ha['description'] += " Mark Reid\n" end ha['url'] = url ha['baseurl'] = '/' + reponame ha['twitter_username'] = twitter ha['github_username'] = 'mlresearch' ha['markdown'] = 'kramdown' ha['permalink'] = '/:title.html' ha['github'] = {'edit' => true, 'repository' => reponame} if not ha.has_key?('name') ha['name'] = booktitle end ha['display'] = {'copy_button' => {'bibtex' => true, 'endnote' => true, 'apa' => true}} if ha.has_key?('comments') if ha['comments'].downcase == 'yes' or ha['comments'].downcase == 'true' ha['display']['comments'] = true else ha['display']['comments'] = false end else ha['display']['comments'] = false end #reponame = ha['shortname'].to_s.downcase + ha['year'].to_s #system "jekyll new " + self.procdir + reponame #File.delete(*Dir.glob(self.procdir + reponame + '/_posts/*.markdown')) # Add details to _config.yml file ha['volume'] = volume.to_i ha['email'] = email address = ha['address'] ha['conference'] = {'name' => ha['name'], 'url' => ha['conference_url'], 'location' => address, 'dates'=>ha['start'].upto(ha['end']).collect{ |i| i}} ha.tap { |hs| hs.delete('address') } ha.tap { |hs| hs.delete('conference_url') } ha.tap { |hs| hs.delete('name') } ha['analytics'] = {'google' => {'tracking_id' => self.tracking_id}} ya = ha.to_yaml(:ExplicitTypes => true) out = File.open('_config.yml', 'w') out.puts ya out.puts "# Site settings" out.puts "# Auto generated from " + bibfile return ha end end
true
9be87ca1fc9eda13b30bae903470d3e600bc145d
Ruby
b1nary/robobot
/lib/robobot/notification.rb
UTF-8
1,383
2.625
3
[ "MIT" ]
permissive
# Notifications help to show results and information to the user # It uses: libnotify # Author:: Roman Pramberger (mailto:[email protected]) # License:: MIT module Robobot module Notification # show a notification # you must define a title # # Parameter # title: required title # options: see below # # Options # :msg optional message # :icon icon path # :urgency low, normal or critical # :time time in milliseconds # def self.show title, options cmd = "notify-send \"#{title}\"" cmd += " \"#{options[:msg]}\"" if !options[:msg].nil? cmd += " -i #{options[:icon]}" if !options[:icon].nil? cmd += " -u #{options[:urgency]}" if !options[:urgency].nil? cmd += " -t #{options[:timeout]}" if !options[:timeout].nil? `#{cmd}` puts cmd if Robobot.debug end # beeping :) # in order to make it work you have to: # modprobe pcspkr # # Parameter # options: see below # # Options # :frequency # :length # :repeat # :delay # def self.beep options cmd = "beep" cmd += " -f #{options[:frequency]}" if !options[:frequency].nil? cmd += " -l #{options[:length]}" if !options[:length].nil? cmd += " -r #{options[:repeat]}" if !options[:repeat].nil? cmd += " -D #{options[:delay]}" if !options[:delay].nil? `beep` puts cmd if Robobot.debug end end end
true
acde5ed70393a471f52f7a2fbf5ef502c29695c9
Ruby
sheikhhamza012/ror_test
/config/schedule.rb
UTF-8
558
2.5625
3
[]
no_license
# Use this file to easily define all of your cron jobs. # # It's helpful, but not entirely necessary to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # Example: # # set :output, "/path/to/my/cron_log.log" # #job_type :mail, '/home/mehroz/railsTest/instagramclone/app/jobs/mail_to.rb :user' every :minute do puts "hello" runner 'UserMailer.crontest.deliver' command 'echo "heelllp"' puts "bye" end # # every 4.days do # runner "AnotherModel.prune_old_records" # end # Learn more: http://github.com/javan/whenever
true
1b0f62d9351cd115d6a6f13961be9567ec64b8bd
Ruby
srfraser/adventofcode
/2020/15/ruby/1.rb
UTF-8
1,908
3.5625
4
[]
no_license
def play_memory_game_naively(sequence, desired_number = 2020) (1..desired_number).each { |_| last_spoken = sequence[-1] if sequence[0..-2].include?(last_spoken) # puts "#{last_spoken} was in #{sequence[..-2]}" sequence.append(sequence.length - 1 - sequence[0..-2].rindex(last_spoken)) else # puts "#{last_spoken} was not in #{sequence[..-2]}" sequence.append(0) end } sequence[desired_number - 1] end def play_memory_game(sequence, desired_number = 2020) index_cache = sequence[0..-2].zip(0..).map { |s, index| [s, index] }.to_h next_to_speak = sequence[-1] # index_cache.delete!(last_spoken) (index_cache.length..desired_number).each { |current_position| new_index = 0 if index_cache.has_key?(next_to_speak) new_index = current_position - index_cache[next_to_speak] end # puts "Saying #{next_to_speak} at #{current_position}, next up is #{new_index}" index_cache[next_to_speak] = current_position next_to_speak = new_index } index_cache.select { |k, v| v == desired_number - 1 }.keys[0] end part1_tests = [ [[0, 3, 6], 436, 2020], [[1, 3, 2], 1, 2020], [[2, 1, 3], 10, 2020], [[1, 2, 3], 27, 2020], [[2, 3, 1], 78, 2020], [[3, 2, 1], 438, 2020], [[3, 1, 2], 1836, 2020], ] for input, expected, desired in part1_tests puts "Part 1 test #{play_memory_game(input, desired)} == #{expected}" end puts "Part 1 actual #{play_memory_game([11, 0, 1, 10, 5, 19])}" part2_tests = [ [[0, 3, 6], 175594, 30000000], [[1, 3, 2], 2578, 30000000], [[2, 1, 3], 3544142, 30000000], [[1, 2, 3], 261214, 30000000], [[2, 3, 1], 6895259, 30000000], [[3, 2, 1], 18, 30000000], [[3, 1, 2], 362, 30000000], ] for input, expected, desired in part2_tests puts "Part 2 test #{play_memory_game(input, desired)} == #{expected}" end puts "Part 2 actual #{play_memory_game([11, 0, 1, 10, 5, 19], 30000000)}"
true
1336eb81bc9427b8949fa1133ecddb017f38c1f2
Ruby
spree/spree
/core/app/models/spree/stock/estimator.rb
UTF-8
2,251
2.609375
3
[ "BSD-3-Clause" ]
permissive
module Spree module Stock class Estimator include VatPriceCalculation attr_reader :order, :currency def initialize(order) @order = order @currency = order.currency end def shipping_rates(package, shipping_method_filter = ShippingMethod::DISPLAY_ON_FRONT_END) rates = calculate_shipping_rates(package, shipping_method_filter) choose_default_shipping_rate(rates) sort_shipping_rates(rates) end private def choose_default_shipping_rate(shipping_rates) unless shipping_rates.empty? shipping_rates.min_by(&:cost).selected = true end end def sort_shipping_rates(shipping_rates) shipping_rates.sort_by!(&:cost) end def calculate_shipping_rates(package, ui_filter) shipping_methods(package, ui_filter).map do |shipping_method| cost = shipping_method.calculator.compute(package) next unless cost shipping_method.shipping_rates.new( cost: gross_amount(cost, taxation_options_for(shipping_method)), tax_rate: first_tax_rate_for(shipping_method.tax_category) ) end.compact end # Override this if you need the prices for shipping methods to be handled just like the # prices for products in terms of included tax manipulation. # def taxation_options_for(shipping_method) { tax_category: shipping_method.tax_category, tax_zone: @order.tax_zone } end def first_tax_rate_for(tax_category) return unless @order.tax_zone && tax_category Spree::TaxRate.for_tax_category(tax_category). potential_rates_for_zone(@order.tax_zone).first end def shipping_methods(package, display_filter) package.shipping_methods.select do |ship_method| calculator = ship_method.calculator ship_method.available_to_display?(display_filter) && ship_method.include?(order.ship_address) && calculator.available?(package) && (calculator.preferences[:currency].blank? || calculator.preferences[:currency] == currency) end end end end end
true
9f10d1bd00412484cd7c1130bdabb08d9645778d
Ruby
jordanbyron/advent-of-code
/2015/9-travel/part_one.rb
UTF-8
2,539
3.546875
4
[ "MIT" ]
permissive
require_relative '../advent' Visitor = ->(places, h = {}) { if places.one? return places.first else places.each do |place| h[place] = Visitor[places - [place]] end h end } module DistanceCalcualtor extend self def distance_for(origin, destination) distances[origin][destination] || distances[destination][origin] end def distances @distances ||= begin distances = {} File.read('input.txt').split("\n").each do |string| regex = /(?<start>\S+) to (?<finish>\S+) = (?<distance>\d+)/ if data = regex.match(string) distances[data[:start]] ||= {} distances[data[:start]][data[:finish]] = data[:distance].to_i else raise "Error parsing '#{string}'" end end distances["Straylight"] = {} distances end end end class Leg def initialize(origin, destination) @origin = origin @destination = destination end def distance DistanceCalcualtor.distance_for(origin, destination) end attr_reader :origin, :destination end class Route def self.all @all ||= [] end def self.add(origin) route = new(origin) all << route route end def self.shortest shortest_distance = all.map(&:distance).min all.find {|route| route.distance == shortest_distance } end def self.longest longest_distance = all.map(&:distance).max all.find {|route| route.distance == longest_distance } end def initialize(origin) @legs = [] @current_stop = origin end attr_reader :legs def add_stop(destination) legs << Leg.new(current_stop, destination) @current_stop = destination legs.last end def distance legs.inject(0) {|sum, leg| sum + leg.distance } end def to_s if legs.any? legs.map {|l| l.origin }.join(' -> ') + " -> #{legs.last.destination}" else "Trip to no where from #{current_stop}" end end def inspect "#<Route> #{to_s}" end private attr_reader :current_stop end routes = Visitor[DistanceCalcualtor.distances.keys] RoutesToArray = -> (hash, ancestors = [], results = []) { hash.each do |key, value| if value.is_a?(Hash) RoutesToArray[value, ancestors + [key], results] else results << (ancestors + [key, value]) end end results } route_array = RoutesToArray[routes] route_array.each do |trip| route = Route.add(trip.first) trip[1..-1].each do |destination| route.add_stop(destination) end end binding.pry
true
2e33288d6d70c79c68fb9910ae7a86343721e4b8
Ruby
rhys117/LaunchSchoolCurriculum
/Backend/101/exercises/easy4/short_long_short.rb
UTF-8
309
3.515625
4
[]
no_license
def short_long_short(str_one, str_two) if str_one.length > str_two.length str_two + str_one + str_two else str_one + str_two + str_one end end puts short_long_short('abc', 'defgh') == "abcdefghabc" puts short_long_short('abcde', 'fgh') == "fghabcdefgh" puts short_long_short('', 'xyz') == "xyz"
true
b500ff684f4dacae65946da884e8672f9486eba6
Ruby
ManageIQ/manageiq-performance
/lib/manageiq_performance/reporter.rb
UTF-8
5,292
2.671875
3
[]
no_license
require "yaml" require "bigdecimal" module ManageIQPerformance class Reporter attr_reader :io HEADERS = { "ms" => %w[ms], "queries" => %w[queries], "query (ms)" => %w[activerecord elapsed_time], "rows" => %w[rows] } def self.build(run_dir, io=STDOUT) new(run_dir, io).build end def initialize(run_dir, io=STDOUT) @run_dir = run_dir @report_data = {} @io = io end def build collect_data print_data end private # Collection def collect_data Dir["#{@run_dir}/*"].sort.each do |request_dir| request_id = File.basename request_dir @report_data[request_id] ||= {} @report_data[request_id]["avgs"] ||= {} gather_request_times request_dir, request_id gather_db_info request_dir, request_id end end def gather_request_times request_dir, request_id Dir["#{request_dir}/*.info"].sort.inject(@report_data[request_id]) do |data, info_file| info = YAML.load_file(info_file) || {} data["ms"] ||= [] data["activerecord"] ||= [] data["ms"] << info.fetch('time', {})['total'].to_i data["activerecord"] << info.fetch('time', {})['activerecord'].to_i data end @report_data[request_id]["avgs"]["ms"] = avg @report_data[request_id]["ms"] @report_data[request_id]["avgs"]["activerecord"] = avg @report_data[request_id]["activerecord"] end def gather_db_info request_dir, request_id Dir["#{request_dir}/*.queries"].sort.inject(@report_data[request_id]) do |data, info_file| queries = YAML.load_file(info_file) data["queries"] ||= [] data["rows"] ||= [] data["elapsed_time"] ||= [] data["queries"] << queries[:total_queries].to_i data["rows"] << queries[:total_rows].to_i data["elapsed_time"] << queries.fetch(:queries, []).map {|q| q[:elapsed_time] }.inject(BigDecimal("0.0"), :+).to_f data end @report_data[request_id]["avgs"]["queries"] = avg @report_data[request_id]["queries"] @report_data[request_id]["avgs"]["rows"] = avg @report_data[request_id]["rows"] @report_data[request_id]["avgs"]["elapsed_time"] = avg @report_data[request_id]["elapsed_time"] end # Printing # Prints the report data def print_data @report_data.keys.each do |request_id| @column_size_for = {} io.puts "/#{request_id.gsub("%", "/")}" print_headers request_id print_spacers request_id print_row_data request_id end end # Prints a single row, and defers to the caller to determine what is # printed (including determining proper spacing) for each column in the # row, passing it the current header for that row. # # Row columns are split using `|`, and a single space (at a minimum) will # always separate the content and the delimiters. def print_row row = "| " row += HEADERS.keys.map {|hdr| yield hdr }.join(" | ") row += " |" io.puts row end # Prints the headers. Just uses the `hdr` from the yield of `print_rows` def print_headers request_id print_row do |hdr| hdr.rjust(column_size_for hdr, request_id) end end # Prints spacers for each column def print_spacers request_id print_row do |hdr| "---:".rjust(column_size_for hdr, request_id) end end # Prints the data for each row, with each row data value rjust'd to the # size for the column, and formatted to 1 decimal point precision (if it is # a float) def print_row_data request_id # Find a header for a count do use in the next line count_header = HEADERS.values.flatten.detect do |hdr| @report_data[request_id][hdr] and hdr end (@report_data[request_id][count_header] || []).count.times do |i| print_row do |hdr| value = HEADERS[hdr].map { |header_column| @report_data[request_id].fetch(header_column, [])[i] || 0 }.max value = "%.1f" % value unless value.class.ancestors.include?(Integer) value.to_s.rjust(column_size_for hdr, request_id) end end end # Determines the largest string length character from the following: # # - The report data for that column # - The average for that report data # - The column header's length # - The spacer string (`---:`) # def column_size_for header, request_id @column_size_for[request_id] ||= {} @column_size_for[request_id][header] ||= (HEADERS[header].map { |header_column| @report_data[request_id][header_column].map {|i| value = i.to_s value = "%.1f" % i if i && !i.class.ancestors.include?(Integer) value.size }.max if @report_data[request_id][header_column] }.compact + [ header.to_s.length, @report_data[request_id]["avgs"][header].to_s.size, 4 # spacer size ]).max end def avg data return 0 if Array(data).empty? data.inject(0, :+) / data.size end end end
true
f9f9da8954e986396948d5c89991970be187e9bc
Ruby
JayTeeSF/TimeTracker
/lib/time_tracker.rb
UTF-8
2,927
3.21875
3
[]
no_license
class TimeTracker INSTANCES = {} def self.help puts <<-EOM irb -r ./app/lib/time_tracker.rb > TimeTracker.clear > t = TimeTracker.new("1") > t.start :one > TimeTracker.find("1") == t => true > TimeTracker.clear > TimeTracker.find("1") == t => false > TimeTracker.store("1", t) > TimeTracker.find("1") == t => true > t.finish(:one) > t.took(:one) => 56.28791809082031 > t.to_s => "[[:one, {:start=>1519870588.9845388, :finish=>1519870645.272457, :took=>56.28791809082031}]]" > t.section_keys => [:one] > t.started_last => [:one, 1519870588.9845388] # the start time > t.finished_first => [:one, 1519870645.272457] # the finish time EOM end def self.clear INSTANCES.clear end def self.find(name) INSTANCES[name] end def self.store(name, object) warn "overwriting tracker: #{name} -> #{object.sections.inspect}" if INSTANCES[name] INSTANCES[name] = object end START_KEY = :start FINISH_KEY = :finish TOOK_KEY = :took attr_reader :name, :sections def initialize(name) @name = name @sections = {} TimeTracker.store(@name, self) end def start(key, as_of=Time.now.to_f) fail("Attempt to (re-)start immutable section #{key.inspect}") if @sections.key?(key) @sections[key] = {} @sections[key][START_KEY] = as_of end def finish(key, as_of=Time.now.to_f) fail("Can't finish unknown section #{key.inspect}") unless @sections.key?(key) @sections[key] ||= {} fail("Attempt to (re-)finish immutable section #{key.inspect}") if @sections[key][FINISH_KEY] @sections[key][FINISH_KEY] = as_of @sections[key][TOOK_KEY] = as_of - @sections[key][START_KEY] end def took(key) if @sections.key?(key) && @sections[key].key?(TOOK_KEY) @sections[key][TOOK_KEY] else warn "Section #{key.inspect} has not finished, yet!" end end def to_s ordered_by_start.inspect end def section_keys @sections.keys end def finished_section_keys finished_sections.keys end def started_first key = ordered_by_start.first [key.first, key.last[START_KEY]] end def started_last key = ordered_by_start.last [key.first, key.last[START_KEY]] end def finished_first key = ordered_by_finish.first [key.first, key.last[FINISH_KEY]] end def finished_last key = ordered_by_finish.last [key.first, key.last[FINISH_KEY]] end private def finished_sections @sections.select { |s_key| @sections[s_key].key?(FINISH_KEY) } end def started_sections @sections.select { |s_key| @sections[s_key].key?(START_KEY) } end def ordered_by_finish finished_sections.sort { |l, r| l[1][FINISH_KEY] <=> r[1][FINISH_KEY] } end def ordered_by_start started_sections.sort { |l, r| l[1][START_KEY] <=> r[1][START_KEY] } end end
true
f952ac4ce590d5ba01b82f71302658cb82629c0e
Ruby
deepigarg/rubyx
/test/mains/source/32_adds__10.rb
UTF-8
287
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Integer < Data4 def <(right) X.comparison(:<) end def +(right) X.int_operator(:+) end def -(right) X.int_operator(:-) end end class Space def main(arg) a = 0 b = 20 while( a < b ) a = a + 1 b = b - 1 end return a end end
true
728072b2df612723d8645bc95c9d43f587a0806a
Ruby
jaleszek/reddit_wrapper
/1/lib/tdd.rb
UTF-8
2,208
3.109375
3
[]
no_license
require "addressable/uri" require 'curb' require 'json' module RedditAPI class Pinger attr_reader :resource, :action, :url, :http_method BASE_URL = 'http://www.reddit.com' FUNCTIONAL_ARGS = [:resource, :action] FORMAT = '.json' ROUTING = { "article/popular" => { url: "#{BASE_URL}/subreddits/popular#{FORMAT}", http_method: :get }, "article/new" => { url: "#{BASE_URL}/subreddits/new#{FORMAT}", http_method: :get }, "article/search" => { url: "#{BASE_URL}/subreddits/search#{FORMAT}", http_method: :get }, "link/search" => { url: "#{BASE_URL}/r/subreddit/search#{FORMAT}", http_method: :get } } def initialize(args= {}) FUNCTIONAL_ARGS.each do |arg| instance_variable_set("@#{arg}", args[arg]) end @additional_args = args.select{|k, _| !FUNCTIONAL_ARGS.include?(k)} compose_url end def execute Curl.send(ROUTING[resource_ident][:http_method], url) end private def compose_url uri = Addressable::URI.parse ROUTING[resource_ident][:url] uri.query_values = @additional_args @url = uri.to_s end def resource_ident "#{@resource}/#{@action}" end end module ResponseWrapper private def wrap_me(response) if response json = JSON.parse(response.body_str) return json['data']['children'].map do |article| new article['data'] end end [] end end class Resource attr_reader :input def initialize(json) @input = json json.each do |k,v| self.class.send(:define_method, "data_#{k}"){ v } end end def self.slug(method_name, additional_args) class_name = name.split('::').last.downcase additional_args.merge! resource: class_name , action: method_name end def attributes input.keys end extend ResponseWrapper end class Article < Resource def self.popular(args = {}) response = Pinger.new(slug(__method__, args)).execute wrap_me(response) end end class Link < Resource def self.search(args = {}) response = Pinger.new(slug(__method__, args)).execute wrap_me(response) end end end
true
0b18d0986687b8eeeee9e3ebbd0ff3e341e2a7d4
Ruby
spookybit/daily_projects
/w1d2/Sudoku/tile.rb
UTF-8
127
2.796875
3
[]
no_license
class Tile attr_accessor :value def initialize(value = 0, given = false) @given = given @value = value end end
true
c6421d4f180a15112c370e36e11d935db11205ae
Ruby
cielavenir/procon
/atcoder/abc/tyama_atcoderABC021C.rb
UTF-8
381
2.765625
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby n=gets.to_i s,g=gets.split.map(&:to_i) h=Hash.new{|h,k|h[k]=[]} gets.to_i.times{|i| a,b=gets.split.map(&:to_i) h[a]<<b h[b]<<a } q=[s] depth={s=>1} sum=Hash.new(0) sum[s]=1 while !q.empty? cur=q.shift h[cur].each{|e| if !depth.has_key?(e) depth[e]=depth[cur]+1 q<<e end if depth[e]==depth[cur]+1 sum[e]+=sum[cur] end } end p sum[g]%1000000007
true
d1109fd460eee4dcf195b75ae7eb9be0fddc6dff
Ruby
sisyphe0713/furima-30355
/app/models/order_address.rb
UTF-8
953
2.515625
3
[]
no_license
class OrderAddress include ActiveModel::Model attr_accessor :post_code, :prefecture_id, :city, :address_number, :building, :telephone, :user_id, :item_id, :token with_options presence: true do validates :post_code, format: { with: /\A\d{3}[-]\d{4}\z/, message: "is invalid. Inclue hyphen(-)" } validates :prefecture_id, numericality: { other_than: 1, message: "can't be blank" } validates :city validates :address_number validates :telephone, format: { with: /\A\d{,11}\z/, message: "must be less than 11 degit without hyphen(-)" } validates :user_id validates :item_id validates :token end def save user = User.find(user_id) item = Item.find(item_id) order = Order.create(user_id: user.id, item_id: item.id) Address.create(order_id: order.id, post_code: post_code, prefecture_id: prefecture_id, city: city, address_number: address_number, building: building, telephone: telephone) end end
true
1697a5b954ccac7035aa46f9cb0cec93ee384d66
Ruby
DanKnox/tmp_mail
/lib/tmp_mail/address.rb
UTF-8
480
2.609375
3
[]
no_license
module TmpMail class Address < ::Mail::Address def self.demongoize(object) Address.new(object) end def self.mongoize(object) case object when Address then object.mongoize when String then Address.new(object).mongoize else object end end def self.evolve(object) case object when Address then object.mongoize else object end end def mongoize to_s end end end
true
b5c8d14ff470479d4b6bfe6fb254d76c6d33a8e6
Ruby
tylerpalef/Thursday_July_26
/student.rb
UTF-8
778
3.328125
3
[]
no_license
require_relative "person" class Student < Person # This is how you make a class inherit another class Level = 0 # Constants are not supposed to change. So you put it in a constant variable. That way you can change the number if you have a big class # Value should always be there before initialize def initialize(f,l) super(f,l) # super is a function that will invoke the method in the parent class @knowledge_level = Level end def learn @knowledge_level = @knowledge_level + 5 if @knowledge_level > 20 bonus end def knowledge_level @knowledge_level end def slack @knowledge_level = @knowledge_level - 5 if @knowledge_level > 0 end # private # def bonus @knowledge_level = @knowledge_level + 100 end end end
true
19b3c0edc25a00ad6757749faf8cfde85b9a8f17
Ruby
siuying/gitdocs
/lib/gitdocs/markdown_converter.rb
UTF-8
1,250
2.59375
3
[ "MIT" ]
permissive
require 'redcarpet' require 'pygments' # Singleton markdown converter, configured with github favoured markdown # # adapted from (https://github.com/chitsaou/ruby-taiwan/blob/d342b58dcfff3089a9599714a6911ca9c1f1490f/config/initializers/markdown.rb) class MarkdownConverter include Singleton class HTMLwithSyntaxHighlight < Redcarpet::Render::HTML def block_code(code, language) language = 'text' if language.blank? begin Pygments.highlight(code, :lexer => language, :formatter => 'html', :options => {:encoding => 'utf-8'}) rescue Pygments.highlight(code, :lexer => 'text', :formatter => 'html', :options => {:encoding => 'utf-8'}) end end end def self.convert(text) self.instance.convert(text) end def convert(text) text = text.force_encoding('utf-8') if text.respond_to?(:force_encoding) @converter.render(text) end private def initialize html_renderer = HTMLwithSyntaxHighlight.new({ :filter_html => true # filter out html tags }) @converter = Redcarpet::Markdown.new(html_renderer, { :autolink => true, :fenced_code_blocks => true, :gh_blockcode => true, :hard_wrap => true, :no_intraemphasis => true }) end end
true
5e9500788b451cf25803c4d407f6d99b11a13787
Ruby
Muhidin123/programming-univbasics-4-simple-looping-lab-chi01-seng-ft-102620
/lib/simple_loops.rb
UTF-8
297
3.875
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Write your methods here def loop_message_five_times(message) 5.times do puts message end end def loop_message_n_times(message, n) n.times do puts message end end def output_array(message) message.map {|x| puts x } end def return_string_array(arr) arr.map(&:to_s) end
true
600a57080374d49d7184fcc751b2e9c1aecbc4da
Ruby
shuangliu12/NFL_data
/server.rb
UTF-8
1,943
3.5
4
[]
no_license
require 'sinatra' require 'csv' def import_csv(filename) data = [] CSV.foreach(filename, headers:true) do |row| data << row.to_hash end data end def count_results(league) wins = {} losses = {} #set all losses and wins to 0, initialize values league.each do |game| wins[game["home_team"]]=0 wins[game["away_team"]]=0 losses[game["home_team"]]=0 losses[game["away_team"]]=0 end #count losses and wins league.each do |game| if game["home_score"].to_i > game["away_score"].to_i wins[game["home_team"]] += 1 losses[game["away_team"]] += 1 else wins[game["away_team"]] += 1 losses[game["home_team"]] += 1 end end # wins = {"Patriots"=>3, "Broncos"=>1, "Colts"=>0, "Steelers"=>0} # losses = {"Patriots"=>0, "Broncos"=>1, "Colts"=>2, "Steelers"=>1} results=[] results << wins results << losses results end def sort(results) team = [] sort = [] wins = results[0] losses = results[1] wins.keys.each do |key| team = [key] sort << team #sort = [[Patriots],[Broncos],[Colts],[Steelers]] end #sort = [[Patriots, 3], [Bronocs, 1]..] sort.each do |array| array << wins[array[0]] end sort.each do |array| array << losses[array[0]] end #sort the result by wins, losses, the team names(if they have same w/l) result = sort.sort_by{|v1, v2, v3| [-v2, v3, v1]} end get '/leaderboard' do @all_games = import_csv('NFL.csv') @win_loss = count_results(@all_games) @results = sort(@win_loss) erb :index end get '/leaderboard/:team' do @team = params[:team] @all_games = import_csv('NFL.csv') #game info # win_loss=[{"Patriots"=>3, "Broncos"=>1, "Colts"=>0, "Steelers"=>0}, # {"Patriots"=>0, "Broncos"=>1, "Colts"=>2, "Steelers"=>1}] win_loss = count_results(@all_games) win = win_loss[0] @team_win = win[@team] loss = win_loss[1] @team_loss = loss[@team] erb :team end
true
d35a4fed5075c1958f4d3241887764ec3fb5e996
Ruby
alhd7892/git-push-origin-master
/db/seeds.rb
UTF-8
1,144
2.6875
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 rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts 'Cleaning database...' Restaurant.destroy_all puts 'Creating restaurants...' surpriz = { name: 'Surpriz', address: '110 Rue Oberkampf, 75011 Paris', category: 'french' } pny = { name: 'Paris New York Burger', address: '96 Rue Oberkampf, 75011 Paris', category: 'belgian' } pokawa = { name: 'Pokawa', address: '56 bis Rue Oberkampf, 75011 Paris', category: 'japanese' } camion_qui_fume = { name: 'Camion qui fume', address: '66 Rue Oberkampf, 75011 Paris', category: 'italian' } scoop_me_a_cookie = { name: 'Scoop me a cookie', address: '57 Rue Oberkampf, 75011 Paris', category: 'french' } [surpriz, pny, pokawa, camion_qui_fume, scoop_me_a_cookie].each do |attributes| restaurant = Restaurant.create!(attributes) puts "Created #{restaurant.name}" end puts 'Finished!'
true
6182f7d0f1ed7ad7f24d1fc745c1d16c48b4136b
Ruby
thenice/Poll-Everywhere-Ruby-API-Wrapper
/poll_everywhere.rb
UTF-8
5,956
2.671875
3
[ "MIT" ]
permissive
# @author Daniel Cohen # @release_date July, 23 2010 # @website http://thenice.tumblr.com # @email [email protected] # @license MIT license: http://www.opensource.org/licenses/mit-license.php require 'net/http' module PollEverywhere class Poll # Add any key of a poll to not have instantiated as a field in a Poll object DO_NOT_STORE_FIELD = %w(results options) CONFIG_FILE_URL = "#{RAILS_ROOT}/config/poll_everywhere.yml" def initialize self.create_ivar(:type) # create a field to store the type of poll end # Create cached access to the config file. # # @return [Array] Returns an array of a user's Polls def self.config @@config ||= YAML::load(File.open(CONFIG_FILE_URL)) end # Pulls down the most recent polls from the server, and store in class # variable @@polls and return the array. # # @return [Array] Returns an array of a user's Polls def self.refresh self.request end # Selects all multiple choice polls from a user's account # and utilizes the cached @@poll variable. # # @return [Array] Returns an array of a user's multiple choice Polls def self.multiple_choice self.all.select { |poll| poll.type == "MultipleChoicePoll" } end # Selects all free text polls from a user's account # and utilizes the cached @@poll variable. # # @return [Array] an array of a user's free text polls def self.free_text self.all.select { |poll| poll.type == "FreeTextPoll" } end # Searches through the cached @@poll array for a given poll # identified by the permalink # # @param permalink referred to as poll_id # @return [Array] an array of matching a user's free text polls def self.find(poll_id) self.all.select { |poll| poll.permalink.include?(poll_id) } end # Returns the entire cached @@poll array # or makes an initial request if one hasn't yet been made # # @return [Array] all of the user's polls def self.all @@poll_objects rescue self.request end # Searches through the cached @@poll array for a given poll # identified by the title field # # @param title the title of a poll # @return [Array] all of the user's polls def self.find_by_title(title) self.all.select { |poll| poll.title.include?(title) } end # Fetches detail json from server for specific multiple choice # poll. This method is depricated since the addition of the # detailed.json feed. # @depricated # # @param the permalink for the poll referred to as poll_id # @return [Hash] of the values for a given poll def self.request_multiple_choice(poll_id) poll_json = `curl #{config['urls']['detailed_multiple_choice']}/#{poll_id}.json` self.from_hash(JSON.parse(poll_json)) end # Pass in a keyword string, and this method will count the vote. # It will count repeat votes by default. Returns Nil no matter what # Does not provide feedback # @todo make this method return true for success and false for error # # @param keyword for a poll to vote (an sms keyword) # @return nil this should be fixed def self.vote(keyword) Net::HTTP.get_print(URI.parse("#{config['urls']['vote']}?response=#{keyword.gsub(' ', '+')}")) end # @instance_methods # @constructors # Instantiates a new Poll object from a hash of values. # # @param [Hash] A hash of poll values # @return [PollEverywhere::Poll] a new instanc of a Poll containing the Hash keys and values def self.from_hash(hash) new_poll = self.new hash.each_pair do |key, value| unless DO_NOT_STORE_FIELD.include?(key) new_poll.create_ivar(key) new_poll.send("#{key.to_s}=", value) end end return new_poll end # Given a poll, this method creates a new field, set's the value of field_nam_json # provides the appropriate accessors and mutators to store and access the json value # # @param new_poll the poll to operate on # @param field_name the name of the field to add # @value the value to set the new_field to in JSON format # @return nil def self.create_and_set_json_field_for(new_poll, field_name, value) new_poll.create_ivar("#{field_name}_json") new_poll.send("#{field_name}_json=", value) new_poll.class.class_eval do eval("def #{field_name}; JSON.parse(self.send('#{field_name}_json')) rescue []; end") end end # Get the number of results for a keyword in a Poll # # returns 0 if that keyword is not found in this Poll. Keywords are NOT # case sensitive # # @param keyword for the poll to lookup # @return an integer representing the number of responses, or 0 if the keyword didn't exist def result_count_for(keyword) options.select { |h| h["keyword"].downcase == keyword.downcase }[0]["results_count"] rescue 0 end # Get the percentage of results for a keyword in a Poll # # returns 0 if that keyword is not found in this Poll. Keywords are NOT # case sensitive # # @param keyword for the poll to lookup # @return a float representing the percentage of responses, or 0 if the keyword didn't exist def result_percentage_for(keyword) options.select { |h| h["keyword"].downcase == keyword.downcase }[0]["results_percentage"].to_f rescue 0.0 end # A utility method that should be private but requires public access. # This method does what it says... it creats an ivar for a given symbol # # # @param symbol ivar name def create_ivar(symbol) self.class.module_eval( "def #{symbol}() @#{symbol}; end" ) self.class.module_eval( "def #{symbol}=(val) @#{symbol} = val; end") end private # Makes the request to PollEverywhere to get the current detailed # Poll data. Sets two class viariabls, @polls and @poll_objects # # def self.request polls_json = `curl http://#{config['username']}:#{config['password']}@#{config['urls']['detailed_poll_list']}` @@polls = JSON.parse(polls_json) @@poll_objects = @@polls.collect { |poll_hash| self.from_hash(poll_hash.values.first) } end end end
true
8852f5f2d0c8feb58fdef1ae63b80305334b9b79
Ruby
Ermako27/compilers-course-work
/tests/sample3.rb
UTF-8
408
2.78125
3
[]
no_license
def foo (arg1, arg2, arg3) intVar = 42 dynVar = arg1 / 2 arrVar = [] fullArrVar = [9, 8] fullArrVar[0] = 5 strVar = 'hello' floatVar = 9.9 arrayOfVar = [intVar, floatVar] def barr(arg2) b = 99 dynVar = arg2 / 2 arrVar = [] return b end funcCallVar = barr(intVar) return floatVar end def bazz(arg2) b = 99 return b end
true
787d93e171237249168aae6e5b771d53f4e00cbf
Ruby
dpsk/book-club
/app/models/book.rb
UTF-8
936
2.578125
3
[]
no_license
class Book < ActiveRecord::Base attr_accessible :cover_url, :author, :genre, :name, :notes, :user_id, :featured belongs_to :user has_many :votes validates :name, presence: true, uniqueness: true validates :cover_url, :format => URI::regexp(%w(http https)) validates :author, presence: true validates :user_id, presence: true after_save :one_featured_book def self.book_of_the_month where(featured: true).first end def one_featured_book if featured featured_books = Book.where(featured: true).reject{|b| b == self} featured_books.each { |b| b.update_attribute(:featured, false) } end end def set_as_featured! assign_attributes(featured: true) self.save end def added_by user user_id == user.id if user end def voted_by user votes.map(&:user_id).include? user.id if user end def vote_by user votes.where(user_id: user.id).first if user end end
true
a1347e517bb64c92b2fd661cace64524c028b577
Ruby
atiaxi/kuiper
/lib/options.rb
UTF-8
9,966
2.921875
3
[]
no_license
require 'yaml' require 'overrides' # Holder class for every option in the game class Options attr_accessor :filename attr_accessor :screen_size attr_accessor :fullscreen attr_reader :controls def self.from_file(fullpath) result = YAML::load_file(fullpath) result.filename = fullpath return result end def initialize(fullpath=nil) @filename = fullpath @screen_size = [ 800, 600 ] @fullscreen = false @controls = default_controls end # Note that these controls only apply to flying around, and not to editing # or once landed on a planet. def default_controls result = [] result << KeyDownControl.new('Accelerate', :up) result << KeyDownControl.new('Slow', :down) result << KeyDownControl.new('Rotate Left', :left) result << KeyDownControl.new('Rotate Right', :right) result << KeyDownControl.new('Main Menu', :escape) result << KeyDownControl.new('Land', :l) result << KeyDownControl.new('Map', :m) result << KeyDownControl.new('Jump', :j) result << KeyDownControl.new('View Info', :i) result << KeyDownControl.new('Radar Zoom Out', :minus) result << KeyDownControl.new("Radar Zoom In", :equals ) result << KeyDownControl.new("Fire Primary Weapons", :space) result << KeyDownControl.new("Next Target", :tab) result << KeyDownControl.new("Next Secondary Weapon", :q) result << KeyDownControl.new("Fire Secondary Weapon", :f) result << KeyDownControl.new("Quicksave", :f5) result << KeyDownControl.new("Nearest Hostile Target", :r) result << KeyDownControl.new("Pause", :p) return result end def save if @filename File.open(@filename,"w") do |f| f.write(self.to_yaml) end end end end class Control include Rubygame::Events attr_accessor :name def self.from_event(event) case(event) when KeyDownEvent return KeyDownControl.new('',event.key) when JoystickAxisMoved return JoyAxisControl.new('',event.joystick_id, event.axis, event.value > 0) when JoystickBallMoved return JoyBallControl.new('',event.joystick_id, event.ball, *event.rel) when JoystickButtonPressed return JoyDownControl.new('',event.joystick_id, event.button ) when JoystickHatMoved return JoyHatControl.new('',event.joystick_id, event.hat, event.direction) when MousePressed return MouseDownControl.new('', event.button ) when MouseMoved return MouseMotionControl.new('', *event.rel) else return nil end end def initialize(name) @name = name end def ===(event) return false end # Each control is caused by an event (as determined by === ) and canceled by # one or more events. (i.e. KeyDowns are canceled by an equal KeyUp). This # tests for cancellations def canceled_by?(event) return false end def to_s return "Base Control class that should have been overridden" end def to_sym return @name.gsub(" ","_").downcase.to_sym end end # Control for the user pressing keys, probably # the most common class KeyDownControl < Control attr_accessor :sym def initialize(name, sym) super(name) @sym = sym end def ===(event) if event.class == KeyPressed return event.key == @sym end return false end def canceled_by?(event) return false unless event.class == KeyReleased return event.key == @sym end def to_s return "Key '#{@sym}' pressed" end end # A control which responds to joystick axis # movement. Right now it doesn't really # understand how throttles work, but there's # no way of differentiating them in SDL from # other axes. class JoyAxisControl < Control attr_accessor :stick, :axis, :positive # stick: The joystick number we're expecting # axis: The axis number we're expecting # pos: Whether the change we're looking for is positive def initialize(name, stick, axis, pos) super(name) @stick = stick @axis = axis @positive = pos end def ===(event) if event.class == JoystickAxisMoved return false unless @stick == event.joystick_id return false unless @axis == event.axis if @positive return event.value > 0 else return event.value < 0 end end return false end def canceled_by?(event) return false unless event.class == JoystickAxisMoved return false unless @stick == event.joystick_id return false unless @axis == event.axis return true if event.value == 0 if @positive return event.value < 0 else return event.value > 0 end end def to_s pos = @positive ? "up" : "down" return "Joystick \##{@stick} axis \##{@axis} #{pos}" end end module RelativeMotion attr_accessor :dx, :dy # Unfortunately, relative motion's canceler would be lack of motion, but we # don't get events about that! So we cancel if it's any other direction or # even the right direction but not strong enough, which should catch the # slowing down proceeding a stop. def canceled_by_motion( rel ) return !matches_motion(rel) end def direction_to_s xdir = '' ydir = '' if @dy > 0 ydir = 'up' elsif @dy < 0 ydir = 'down' end if @dx > 0 xdir = 'right' elsif @dx < 0 xdir = 'left' end return "#{ydir}#{xdir}" end def matches_motion( rel ) other_dx, other_dy = rel x_result = false y_result = false if other_dx.abs >= @dx.abs return false if (other_dx.positive? != @dx.positive?) x_result = true end if other_dy.abs >= @dy.abs return false if (other_dy.positive? != @dy.positive?) y_result = true end return false if @dx.zero? != other_dx.zero? return false if @dy.zero? != other_dy.zero? return x_result | y_result end end # I've never even seen a Joystick with a trackball. # Nontheless.... class JoyBallControl < Control attr_accessor :stick, :ball include RelativeMotion # stick: The joystick number # ball: The trackball number # dx: What movement in the X direction we're expecting. If the absolute # value of this is > 1, it's a threshold that the change must match or # exceed. # dy: Movement in Y direction to expect, same caveats as above def initialize(name, stick, ball, dx, dy) super(name) @stick = stick @ball = ball @dx = dx @dy = dy end def ===(event) if event.class == JoystickBallMoved return false unless @stick == event.joystick_id return false unless @ball == event.ball return matches_motion(event.rel) end return false end def canceled_by?(event) return false unless event.class == JoystickBallMoved return false unless @stick == event.joystick_id return false unless @ball == event.ball return canceled_by_motion(event.rel) end def to_s dir = direction_to_s return "Joystick \##{@stick} ball \##{@ball} #{dir}" end end # Depressing sounding name, but I'm naming it after the event itself. # Control for joystick buttons. class JoyDownControl < Control attr_accessor :stick, :button def initialize(name, stick, button) super(name) @stick = stick @button = button end def canceled_by?(event) return false unless event.class == JoystickButtonReleased return false unless event.joystick_id == @stick return event.button == @button end def to_s return "Joystick \##{@stick} button \##{@button} pressed" end def ===(event) if event.class == JoystickButtonPressed return false unless event.joystick_id == @stick return event.button == @button end return false end end # Control for joystick POV hats class JoyHatControl < Control attr_accessor :stick, :hat, :direction # stick: The joystick # hat: The hat # # direction: One of the constants from Rubygame::JoyHatEvent def initialize(name, stick, hat, direction) super(name) @stick = stick @hat = hat @direction = direction end # Returning to center is a cancelling event for all directions def canceled_by?(event) return false unless event.class == JoystickHatMoved return false unless @stick == event.joystick_id return false unless @hat == event.hat return event.center? end def ===(event) if event.class == JoystickHatMoved return false unless @stick == event.joystick_id return false unless @hat == event.hat return @direction == event.direction end return false end # Used to be a lot more work than this. def hat_direction_to_s return @direction.to_S end def to_s dir = hat_direction_to_s return "Joystick \##{@stick} POV \##{@hat} #{dir}" end end # Control for the user clicking buttons or using # the wheelmouse class MouseDownControl < Control attr_accessor :button # The only thing we care about mouse clicks is which button def initialize(name, button) super(name) @button = button end def ===(event) if event.class == MousePressed return event.button == @button end return false end def canceled_by?(event) return false unless event.class == MouseReleased return event.button == @button end def to_s return @button end end class MouseMotionControl < Control include RelativeMotion # All we care about is relative motion. See JoyBallControl def initialize(name, dx, dy) super(name) @dx = dx @dy = dy end def canceled_by?(event) return false unless event.class == MouseMoved return canceled_by_motion(event.rel) end def ===(event) if event.class == MouseMoved return matches_motion(event.rel) end return false end def to_s return "Mouse moves #{direction_to_s}" end end
true
12207a0d5d6a674b12157e3f8579aa2a2049b046
Ruby
hallbergandrew/Ruby-Dictionary
/lib/word.rb
UTF-8
259
2.6875
3
[]
no_license
require './lib/definition.rb' class Word attr_reader :word, :language attr_accessor :definition def initialize(word, language, definition) @word = word @language = language @definition = Definition.new(definition, language) end end
true
f8b846da6861935ab69464f8668037eb664d4815
Ruby
coryschires/katas
/bowling/spec/bowling_spec.rb
UTF-8
4,289
3.078125
3
[]
no_license
require 'bowling' describe Bowling do before { @bowling = Bowling.new } describe "#score" do it "should mark a double gutter" do @bowling.roll(0,0) @bowling.score.should == 0 end it "should mark seven pins" do @bowling.roll(5,2) @bowling.score.should == 7 end it "should mark sixteen pins" do @bowling.roll(5,5) @bowling.roll(2,2) @bowling.score.should == 16 end it "should mark 58 pins" do @bowling.roll(10) @bowling.roll(10) @bowling.roll(7,0) @bowling.roll(5,2) @bowling.score.should == 58 end it "should score the perfect game" do 9.times { @bowling.roll(10) } @bowling.roll(10,10,10) @bowling.score.should == 300 end it "should score the perfect game" do 9.times { @bowling.roll(10) } @bowling.roll(10,10,7) @bowling.score.should == 297 end it "should score the perfect game" do 9.times { @bowling.roll(10) } @bowling.roll(10,3,7) @bowling.score.should == 283 end end describe "#spared_last_frame?" do it "should mark a spare if the pins total 10" do @bowling.roll(5,5) @bowling.spared_last_frame?.should be_true end it "should not mark a spare if the pins are less than 10" do @bowling.roll(5,5) @bowling.roll(5,2) @bowling.spared_last_frame?.should be_false end it "should not mark spare if a strike is rolled" do @bowling.roll(10) @bowling.spared_last_frame?.should be_false end end describe "#striked_last_frame?" do it "should be true if the most recent frame was a strike" do @bowling.roll(10) @bowling.striked_last_frame?.should be_true end it "should be false if the most recent frame was a not strike" do @bowling.roll(4,2) @bowling.striked_last_frame?.should be_false end end describe "#has_striked_last_two_frames?" do it "should return true if the previous two frames were strikes" do @bowling.roll(10) @bowling.roll(10) @bowling.striked_last_two_frames?.should be_true end it "should return false if the previous two frames were not strikes" do @bowling.roll(5,0) @bowling.roll(10) @bowling.striked_last_two_frames?.should be_false end end describe "when previous frame was a spare" do it "should add the pins from the first ball to the spared frame" do @bowling.roll(5,5) @bowling.roll(4,4) @bowling.frames[-2][:pins].should == 14 end end describe "when the previous frame was a strike" do it "should add the pins from the next two rolls to the striked frame" do @bowling.roll(10) @bowling.roll(4,4) @bowling.frames[-2][:pins].should == 18 end end describe "when the previous two frames were both strikes" do it "should add the pins from the first ball to first strike" do @bowling.roll(10) @bowling.roll(10) @bowling.roll(5,5) @bowling.frames[-3][:pins].should == 25 end end describe "#previous_frame" do it "should return the data for the last frame" do @bowling.roll(4,4) @bowling.previous_frame.should == { ball1: 4, ball2: 4, ball3: 0, strike: false, spare: false, pins: 8 } end end describe "#frames" do it "should add a new frame after each set off rolls" do @bowling.roll(5,2) @bowling.frames.size.should == 1 end it "should record the first ball" do @bowling.roll(5,2) @bowling.previous_frame[:ball1].should == 5 end it "should record the second roll" do @bowling.roll(5,2) @bowling.previous_frame[:ball2].should == 2 end it "should record the third roll" do @bowling.roll(5,5,7) @bowling.previous_frame[:ball3].should == 7 end it "should record if the frame was a strike" do @bowling.roll(10) @bowling.previous_frame[:strike].should be_true end it "should record if the frame was a spare" do @bowling.roll(10) @bowling.previous_frame[:spare].should be_false end it "should record the number of pins for the frame" do @bowling.roll(7,2) @bowling.previous_frame[:pins].should == 9 end end end
true
d5e5354a18a673529b6e7b8e748376c42ff46d08
Ruby
samir-ayoub/aula_ruby
/orientacao_objeto/produtosEstoqueRefacao2/exec.rb
UTF-8
851
3.21875
3
[]
no_license
require "byebug" require "/Users/samir/projetos/aula_ruby/orientacao_objeto/produtosEstoqueRefacao2/cliente.rb" require "/Users/samir/projetos/aula_ruby/orientacao_objeto/produtosEstoqueRefacao2/produto.rb" def carga_de_produtos 20.times do |i| produto= Produto.new produto.codigo=i produto.nome="Nome#{i}" produto.quantidade=10 produto.salvar end end carga_de_produtos def checa_codigo while 1==1 puts "Digite o codigo do produto" codigo=gets.to_i produto=Produto.busca_por_codigo(codigo) if produto.nil? puts "burro, digita de novo outro codigo" else return produto end end end while 1==1 puts "Bem vindo nanana 1 para comprar 0 para sair" codigo=gets.to_i if codigo == 0 break else cliente=Cliente.new puts "Digite o nome do caba" cliente.nome=gets produto=checa_codigo end end byebug x=0
true
24935c10186f0ff1e462e0956c7992a4b1f9e0dd
Ruby
johnfelixespinosa/top_vinyls
/lib/top_vinyls/cli.rb
UTF-8
2,075
3.375
3
[ "MIT" ]
permissive
class TopVinyls::CLI require 'pry' def start puts "" puts "---------- Top 100 Must Own Vinyl Records ----------" puts "" puts "Which albums would you like to see?" puts " 1. [01-25] 2. [26-50] 3. [51-75] 4. [76-100]" puts "" puts "Choose 1-4" puts "" input = gets.chomp.to_i if !((1..4) === input) puts "Please try again" start else TopVinyls::Scraper.new.make_list(1) TopVinyls::Scraper.new.make_list(2) TopVinyls::Scraper.new.make_list(3) TopVinyls::Scraper.new.make_list(4) print_list(input) end end def print_list(input) puts "" puts "---------- Current List ----------" puts "" if input == 1 TopVinyls::Vinyls.all[0..24].each do |vinyls| puts "#{vinyls.position}. #{vinyls.name}" puts "" end elsif input == 2 TopVinyls::Vinyls.all[25..49].each do |vinyls| puts "#{vinyls.position}. #{vinyls.name}" puts "" end elsif input == 3 TopVinyls::Vinyls.all[50..74].each do |vinyls| puts "#{vinyls.position}. #{vinyls.name}" puts "" end elsif input == 4 TopVinyls::Vinyls.all[75..99].each do |vinyls| puts "#{vinyls.position}. #{vinyls.name}" puts "" end end which_album(input) end def which_album(input) range = () puts "" puts "Which album would you like more information about?" puts "Enter Album number : " if input == 1 range = (0..24) elsif input == 2 range = (25..49) elsif input == 3 range = (50..74) elsif input == 4 range = (75..99) end num = gets.chomp.to_i if !range.include?(num) puts "Please try again" which_album(input) else puts "ok" #Need to create Find method within vinyls.rb #Create method within scraper.rb to scrape info per individual album #HAVE -artist -year -position #NEED -blurb -vinylsize -tracklisting end end end
true
b84bfd047a9aa9e5df5e53376141488c18995085
Ruby
mikdiet/gretel
/lib/gretel/view_helpers.rb
UTF-8
4,195
2.609375
3
[ "MIT" ]
permissive
module Gretel module ViewHelpers # Sets the current breadcrumb to be rendered elsewhere. Put it somewhere in the view, preferably in the top, before you render any breadcrumbs HTML: # <% # breadcrumb :category, @category # %> def breadcrumb(*args) options = args.extract_options! if args.any? @_breadcrumb_key = args.shift @_breadcrumb_args = args else breadcrumbs(options) end end # Renders the breadcrumbs HTML, for example in your layout. See the readme for default options. # <%= breadcrumbs :pretext => "You are here: " %> # # If you supply a block, it will yield an array with the breadcrumb links so you can build the breadcrumbs HTML manually: # <% breadcrumbs do |links| %> # <% if links.any? %> # You are here: # <% links.each do |link| %> # <%= link_to link.text, link.url %> (<%= link.key %>) # <% end %> # <% end %> # <% end %> def breadcrumbs(options = {}) options = default_breadcrumb_options.merge(options) links = get_breadcrumb_links(options) if block_given? yield links else render_breadcrumbs(links, options) end end # Returns an array of links for the path of the breadcrumb set by +breadcrumb+. def get_breadcrumb_links(options = {}) return [] if @_breadcrumb_key.blank? # Get breadcrumb set by the `breadcrumb` method crumb = Gretel::Crumb.new(@_breadcrumb_key, *@_breadcrumb_args) # Links of first crumb links = crumb.links.dup # Build parents while crumb = crumb.parent links.unshift *crumb.links end # Handle autoroot if options[:autoroot] && links.map(&:key).exclude?(:root) links.unshift *Gretel::Crumb.new(:root).links end # Handle show root alone if links.count == 1 && links.first.key == :root && !options[:show_root_alone] links.shift end links end # Renders breadcrumbs HTML. def render_breadcrumbs(links, options) return "" if links.empty? # Array to hold the HTML fragments fragments = [] # Loop through all but the last (current) link and build HTML of the fragments links[0..-2].each do |link| fragments << render_breadcrumb_fragment(link.text, link.url, options[:semantic]) end # The current link is handled a little differently, and is only linked if specified in the options current_link = links.last fragments << render_breadcrumb_fragment(current_link.text, (options[:link_current] ? current_link.url : nil), options[:semantic], :class => options[:current_class]) # Build the final HTML html = (options[:pretext] + fragments.join(options[:separator]) + options[:posttext]).html_safe content_tag(:div, html, :id => options[:id], :class => options[:class]) end # Renders HTML for at breadcrumb fragment, i.e. a breadcrumb link. def render_breadcrumb_fragment(text, url, semantic, options = {}) if semantic if url.present? content_tag(:div, link_to(content_tag(:span, text, :itemprop => "title"), url, :class => options[:class], :itemprop => "url"), :itemscope => "", :itemtype => "http://data-vocabulary.org/Breadcrumb") else content_tag(:div, content_tag(:span, text, :class => options[:class], :itemprop => "title"), :itemscope => "", :itemtype => "http://data-vocabulary.org/Breadcrumb") end else if url.present? link_to(text, url, :class => options[:class]) elsif options[:class] content_tag(:span, text, :class => options[:class]) else text end end end # Default options for the breadcrumb rendering. def default_breadcrumb_options { :pretext => "", :posttext => "", :separator => " &gt; ", :autoroot => false, :show_root_alone => false, :link_current => false, :semantic => false, :class => "breadcrumbs", :current_class => "current", :id => nil } end end end
true
87aecb1d9951716f2f20b41e12ec3efa8d94c905
Ruby
Mustikrz/PR3
/PR3 Git/PR3_Smits_Lösungen/05_textanalysis/solution/wortliste.rb
UTF-8
1,321
3.453125
3
[]
no_license
class Wortliste def initialize @liste = {} @liste.default = nil end def <<(wort) key = wort.downcase frequency = @liste[key] || 0 frequency += 1 @liste[key] = frequency end def length @liste.length end def count_words @liste.values.reduce(:+) end def count_letters letters.length end def [](wort) @liste[wort.downcase] || 0 end def frequency(wort) Float(self[wort]) / count_words end def each_word count = count_words # for efficency array = @liste.to_a.sort { |a, b| -1 * (a[1] <=> b[1]) } array.each { |e| yield e[0], e[1], Float(e[1]) / count } end def letters array = @liste.to_a.map { |e| (e[0] * e[1]).chars } array.flatten! end def each_letter(&block) array = letters count = count_letters hash = array.reduce({}) do |hash, c| hash[c] ||= 1 hash[c] = hash[c] + 1 hash end pairs = hash.to_a.sort { |a, b| -1 * (a[1] <=> b[1]) } pairs.each { |e| block.call(e[0], e[1], Float(e[1]) / count) } end def to_s @liste.to_s end end
true
e63668c0077484a468e6812245458b5ee1d37265
Ruby
thiagomsilva/desafio-back-end
/app/models/store.rb
UTF-8
419
2.546875
3
[]
no_license
class Store < ApplicationRecord attribute :name, :valid_string attribute :owner, :valid_string validates_presence_of :name, :owner validates_uniqueness_of :name, scope: :owner has_many :financial_transactions, dependent: :destroy def total_amount Utils::NumberUtil.new( self.financial_transactions.map(&:real_ammount).reduce(:+) ).integer_to_money end end
true
63310933ff870a7853e51c5c479aab92052e6588
Ruby
ministryofjustice/laa-apply-for-legal-aid
/app/validators/date_validator.rb
UTF-8
1,718
2.71875
3
[ "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
class DateValidator < ActiveModel::EachValidator DEFAULT_FORMAT = "%Y-%m-%d".freeze DEFAULT_EARLIEST_DATE = "1900-01-01".freeze def validate_each(record, attribute, value) value = parse_date(value, options[:format]) if value.is_a?(String) return unless valid_date(record, attribute, value) validate_not_in_future(record, attribute, value) validate_not_too_early(record, attribute, value) end private def parse_date(date_str, format) format ||= DEFAULT_FORMAT Time.strptime(date_str, format).in_time_zone rescue StandardError nil end def valid_date(record, attribute, value) message = options[:message] || :date_not_valid unless value.is_a?(Date) record.errors.add(attribute, message) return false end true end def validate_not_in_future(record, attribute, value) required = options[:not_in_the_future] return if required.blank? message = required[:message] if required.is_a?(Hash) message ||= :date_is_in_the_future record.errors.add(attribute, message) if value > Date.current end def validate_not_too_early(record, attribute, value) required = options[:earliest_allowed_date] return if required.blank? formatted_date = earliest_allowed_date.strftime("%d %m %Y") message = required[:message] if required.is_a?(Hash) message ||= :earliest_allowed_date record.errors.add(attribute, message, date: formatted_date) if value < earliest_allowed_date end def earliest_allowed_date date_options = options[:earliest_allowed_date] date = date_options.is_a?(Hash) && date_options[:date] ? date_options[:date] : DEFAULT_EARLIEST_DATE parse_date(date, options[:format]) end end
true
9ce981ed1cf81f338d07e6c15f463328f5027d28
Ruby
abinofbrooklyn/Metis
/week1/music_problem.rb
UTF-8
755
3.59375
4
[]
no_license
require 'csv' class Music attr_accessor :db def initialize @db = {} end def sort CSV.foreach("music.csv") do |row| artist_name = row[3] song_title = row[0] if db.has_key?(artist_name) db[artist_name] << song_title else db[artist_name] = [song_title] end end end def prompt sort puts db.keys print "Select an artist:" query = gets.chomp if @db.has_key?(query) puts @db.fetch(query) else puts "Artist is not in the database" end repeat end def repeat puts "Do you want to select another artist? Yes or No?" answer = gets.chomp.downcase if answer == "yes".downcase prompt end end end db = Music.new db.prompt
true
cb677f71ade081601250b2ca00960edb1ef602a8
Ruby
BDCraven/learn-to-program
/chap02/ex1.rb
UTF-8
234
3.71875
4
[]
no_license
puts "Number of hours in a year = #{24 * 365}" puts "Number of minutes in a decade = #{60 * 24 * 365 * 10}" puts "Number of seconds in 20 years = #{60 * 60 * 24 * 365 * 20}" puts "Chris Pine's age = #{1160000000 / 60 / 60 / 24 / 365}"
true
e4e3111b09aaca43a5098be9e6f463c512ea675a
Ruby
Onionator/anagram_checker
/lib/anagram.rb
UTF-8
1,540
4.15625
4
[ "MIT" ]
permissive
class Anagram def initialize(input) @first_word = input end def anagram?(second_word) if self.is_word? @first_word.delete!("!@#${%^&*()}_+=[]|:;\"'<,>.?/ ") @first_word.downcase!() word_holder = @first_word.chomp second_word.delete!("!@#${%^&*()}_+=[]|:;\"'<,>.?/ ") second_word.downcase!() second_word.each_char { |chr| word_holder.sub!(second_word[chr], "") } if word_holder == "" && @first_word.length == second_word.length puts "These phrases are anigrams." return true elsif word_holder == @first_word puts "These phrases are antigrams." return false else word_holder.each_char { |chr| @first_word.sub!(word_holder[chr], "") } output = "" @first_word.each_char.with_index { |chr, i| if i == @first_word.length - 1 && output.length > 1 output += "and " end output += chr if i < @first_word.length - 1 output += ", " end } output += "." puts "These phrases aren't anagrams, but they both contain: #{output}" return false end end else puts "Use real words." end def is_word? /[aeiouy]/.match(@first_word) ? true : false end end puts "Enter the first word or phrase to test if it is anagram material." input = Anagram.new(gets.chomp) puts "Enter the second word or phrase you think might be an anagram." puts "return: #{input.anagram?(gets.chomp)}."
true
f39c5aa5c3c02ea410205aacf4b55ea7960ffac6
Ruby
gillisd/rebay
/lib/rebay/api.rb
UTF-8
1,852
2.546875
3
[ "MIT" ]
permissive
require 'net/http' require 'json' require 'uri' module Rebay class Api # default site is EBAY_US, for other available sites see eBay documentation: # http://developer.ebay.com/DevZone/merchandising/docs/Concepts/SiteIDToGlobalID.html class << self attr_accessor :app_id, :default_site_id, :sandbox def base_url [base_url_prefix, sandbox ? "sandbox" : nil, base_url_suffix].compact.join('.') end def base_url_prefix "https://svcs" end def base_url_suffix "ebay.com" end def sandbox @sandbox ||= false end def default_site_id @default_site_id ||= "EBAY-US" end def configure yield self if block_given? end end attr_accessor :proxy_url, :proxy_port, :proxy_username, :proxy_password, :user_agent def initialize(proxy_url: nil, proxy_port: nil, proxy_username: nil, proxy_password: nil, user_agent: 'eBayiPhone/6.24.0') @proxy_url = proxy_url @proxy_port = proxy_port @proxy_username = proxy_username @proxy_password = proxy_password @user_agent = user_agent end protected def get_json_response(url, headers: {}) uri = URI.parse(url) response = nil Net::HTTP.start(uri.host, 443, proxy_url, proxy_port, proxy_username, proxy_password, use_ssl: true) do |http| request = Net::HTTP::Get.new(uri, { 'User-Agent' => user_agent }.merge(headers)) response = http.request request # Net::HTTPResponse object end Rebay::Response.new(JSON.parse(response.body)) end def build_rest_payload(params) payload = '' unless params.nil? params.keys.each do |key| payload += URI.escape "&#{key}=#{params[key]}" end end return payload end end end
true
4c83d1150b5fd9329a2d58d3e1ba801b50b60e93
Ruby
luc34fenos/ruby
/exo_07_a.rb
UTF-8
122
3.0625
3
[]
no_license
puts "Bonjour, c'est quoi ton blase ?" user_name = gets.chomp #attend d'un donnees entrer par l'utilisateur puts user_name
true
57d7520a5541d2f10864b80fa232313f4a8d7957
Ruby
AndryMac/first
/Lesson_1/part_2.rb
UTF-8
251
3.0625
3
[]
no_license
puts "Укажите основание треугольника" base = gets.chomp.to_i puts "Укажите высоту треугольника" height = gets.chomp.to_i area = 0.5*base*height puts "Площадь треугольника #{area}"
true
daa7fdfe780f7cb046bc7c0dc6ccec96d4ea4456
Ruby
rich-ma/aA-homeworks
/w2d5/LRU_cache.rb
UTF-8
882
3.3125
3
[]
no_license
class LRUCache attr_reader :arr, :max_size def initialize(size) @arr = Array.new(size) @max_size = size end def count arr.length# returns number of elements currently in cache end def add(el) arr.delete(el) if arr.include?(el) arr.shift if arr.length == @max_size arr.push(el) end def show p arr.dup end private attr_writer :arr end if $PROGRAM_NAME == __FILE__ johnny_cache = LRUCache.new(4) johnny_cache.add("I walk the line") johnny_cache.add(5) johnny_cache.count johnny_cache.add([1,2,3]) johnny_cache.add(5) johnny_cache.add(-5) johnny_cache.add({a: 1, b: 2, c: 3}) johnny_cache.add([1,2,3,4]) johnny_cache.add("I walk the line") johnny_cache.add(:ring_of_fire) johnny_cache.add("I walk the line") johnny_cache.add({a: 1, b: 2, c: 3}) johnny_cache.show end
true
32b31c1b9d41c4a9b148a1008366432ff6a5b137
Ruby
Dan2D/learn_ruby
/05_book_titles/book.rb
UTF-8
946
3.953125
4
[]
no_license
#arg = gets.chomp =begin class Book # write your code here def title(arg) no_cap = ["the","a","an","and","in","of"] @books = arg.split(' ') #puts @book.inspect @books.map!{|x| if @books.index(x)==0 or !no_cap.include?(x) x=x.capitalize else x end} @books = @books.join(' ') #puts @book @books end #Cant put the puts here because it's outside the method def end #books = Book.new #books.title(arg) =end class Book attr_reader :title def title (arg) @arg = arg.split(' ') no_cap = ["the","a","an","and","in","of"] @arg.map!{|x| if @arg.index(x)==0 or !no_cap.include?(x) x=x.capitalize else x end} @arg = @arg.join(' ') end end #@books = Book.new #@books.title = "this is a test" #@books.title
true