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
b781e6ada01dddf2d8caaf18d027dc69eddf868f
Ruby
enowmbi/algorithms
/byte_by_byte/median_of_two_sorted_arrays.rb
UTF-8
927
4.28125
4
[]
no_license
#Question 1 -- find the median of two sorted arrays arr1 = [1,3,5] and arr2 = [2,4,6] median = 3.5 # merge the two arrays, take the middle numbers and divide by 2 if resulting array is even else get the middle element if not even def median(arr1,arr2) result = [] return result if arr1 == nil && arr2 == nil pointer_1 = 0 pointer_2 = 0 while(pointer_1 < arr1.size && pointer_2 < arr2.size) if arr1[pointer_1] < arr2[pointer_2] result << arr1[pointer_1] pointer_1 += 1 else result << arr2[pointer_2] pointer_2 += 1 end end while(pointer_1 < arr1.size) result << arr1[pointer_1] pointer_1 += 1 end while(pointer_2 < arr2.size) result << arr2[pointer_2] pointer_2 += 1 end mid_point = result.size / 2 if result.size.odd? return result[mid_point] else return (result[mid_point - 1] + result[mid_point]) / 2.to_f end end
true
0462cb770182e0be749f54626fb191cc738492df
Ruby
baweaver/advent_of_code_2020
/05_binary_boarding.rb
UTF-8
904
3.890625
4
[]
no_license
# I like naming things to make them clearer FRONT = 'F'.freeze BACK = 'B'.freeze LEFT = 'L'.freeze RIGHT = 'R'.freeze # This is a fun little trick. The problem spec hinted at it pretty hard # with "binary boarding", meaning each character is a bit switch. First half # for off, last half for on, convert and `to_i(2)` to get that lovely binary. # # Right, gsub with a hash, that's fun. We're substituting every character and # a Hash can be coerced into a proc or in the case of gsub it looks for a value # to substitute in the place of a key def find_position(pass) = pass.gsub(/./, { FRONT => 0, LEFT => 0, BACK => 1, RIGHT => 1 }).to_i(2) # Then we transform all our passes into their positions def positions(passes) = passes.map { find_position(_1) } # ...and find the largest position def max_position(...) = positions(...).max File.readlines(ARGV[0]).then { puts max_position(_1) }
true
02d99630cc338f7874db92ea40fc97668f771c8f
Ruby
smthom05/enigma
/lib/offset.rb
UTF-8
469
3.140625
3
[]
no_license
require 'date' class Offset attr_reader :offset_hash def initialize @offset_hash = {} end def generate_offset offset = Date.today.strftime("%d%m%y") end def generate_offset_hash(date = generate_offset) date_squared = date.to_i ** 2 offset_values = date_squared.to_s[-4,4] @offset_hash = { a: offset_values[0].to_i, b: offset_values[1].to_i, c: offset_values[2].to_i, d: offset_values[3].to_i } end end
true
a28b567c69154d42cfae7822a432aa456f0c404f
Ruby
cloudfoundry-attic/git_pipeline
/app/models/git_commit_collection_lazy.rb
UTF-8
651
2.890625
3
[]
no_license
class GitCommitCollectionLazy class NotAvailableError < StandardError; end include Enumerable # wtf enumerable? alias_method :size, :count def initialize(git_commit_fetcher) @git_commit_fetcher = git_commit_fetcher @commits = nil @available = false end def available? fetch_commits @available end def each(*args, &blk) raise NotAvailableError, "commits are not available" unless available? @commits.each(*args, &blk) end private def fetch_commits @commits ||= @git_commit_fetcher.fetch @available = true rescue @git_commit_fetcher.class::FetchError @available = false end end
true
5a688e913aa7a51120d7154416f3530dfe783211
Ruby
WhatOSS/Twiki
/couch_db.rb
UTF-8
4,319
2.53125
3
[]
no_license
require 'v8' require 'json' require 'securerandom' class Couch def self.load_config configs = YAML.load(File.read("#{Rails.root}/config/database.yml")) config = configs[Rails.env] @@host = config['host'] @@port = config['port'] || '5984' @@username = config['username'] @@password = config['password'] Couch::Db.set_db(config['database']) end def self.base_url "http://#{@@host}:#{@@port}/" end def self.connection conn = Faraday.new(:url => self.base_url) do |faraday| faraday.request :url_encoded # form-encode POST params faraday.adapter Faraday.default_adapter # make requests with Net::HTTP end if @@username.empty? && @@password.empty? conn.basic_auth(@@username, @@password) end conn end def self.delete url response = connection.delete(url) JSON.parse response.body end def self.get url response = connection.get(url) json = JSON.parse response.body raise Couch::Exception.new(json) if json['error'].present? return json end def self.put url, body="" response = connection.put do |req| req.url url req.headers['Content-Type'] = 'application/json' req.body = body.to_json end JSON.parse response.body end def self.design_documents Dir.glob(File.join(Rails.root, 'app', 'design_documents', '*.js')) end def self.load_design_documents @docs ||= design_documents @docs.each do |doc_path| doc_id = File.basename(doc_path, '.js') doc_json = self.read_design_document doc_path begin existing_document = self::Db.get("_design/#{doc_id}") _rev = existing_document.delete('_rev') if existing_document != doc_json doc_json['_rev'] = _rev end rescue Couch::Exception ensure Couch::Db.put("_design/#{doc_id}", doc_json) end end end def self.read_design_document file_path doc_js = File.read(file_path) cxt = V8::Context.new doc_json = cxt.eval(" convertFunctionsToStrings = function(document) { var action, fn, functions, viewName, _ref, _results; _ref = document.views; _results = []; for (viewName in _ref) { functions = _ref[viewName]; _results.push((function() { var _results1; _results1 = []; for (action in functions) { fn = functions[action]; _results1.push(document.views[viewName][action] = fn.toString()); } return _results1; })()); } return _results; }; doc = #{doc_js} convertFunctionsToStrings(doc); JSON.stringify(doc); ") JSON.parse(doc_json) end class Exception < StandardError end class Db def self.set_db db_name @@db_name = db_name end def self.create_database Couch.put "/#{@@db_name}/" end def self.delete_database Couch.delete "/#{@@db_name}/" end def self.get id Couch.get "#{@@db_name}/#{id}" end def self.put id, body Couch.put "#{@@db_name}/#{id}", body end def self.post body="" response = Couch.connection.post do |req| req.url "/#{@@db_name}" req.headers['Content-Type'] = 'application/json' req.body = body.to_json end JSON.parse response.body end end class Model attr_accessor :attributes UpdateBlacklist = ["_id", "type"] def initialize attributes = {} @attributes = attributes @attributes['_id'] ||= SecureRandom.uuid end def id @attributes['_id'] end def self.find id attributes = Couch::Db.get(id) return new(attributes) end def self.view view_name pluralised_class_name = self.to_s.underscore.pluralize url_encoded_class_name = URI.encode(pluralised_class_name, /\//) results = Couch::Db.get("_design/#{url_encoded_class_name}/_view/#{view_name}") results['rows'] end def save response = Couch::Db.put("/#{id}", @attributes) @attributes['_rev'] = response['rev'] end def update new_attributes @attributes = @attributes.merge(new_attributes.except(*Model::UpdateBlacklist)) self.save end end end
true
ced6b0175bda6192d8850c015715133d939deb61
Ruby
benfloydsmith/basic_repo
/coding_dojo/Ruby/Rails/NinjaGoldGame/app/controllers/rpgs_controller.rb
UTF-8
1,091
2.546875
3
[]
no_license
class RpgsController < ApplicationController def index if !session[:gold] then session[:gold] = 0 end if !session[:activity] then session[:activity] = [] end end def farm farm = rand(10..20) session[:gold] += farm session[:activity] << "Earned #{farm} gold from the farm! " + Time.now.strftime("%Y/%m/%d %I:%M %P") redirect_to '/rpg' end def cave cave = rand(5..10) session[:gold] += cave session[:activity] << "Earned #{cave} gold from the cave! " + Time.now.strftime("%Y/%m/%d %I:%M %P") redirect_to '/rpg' end def house house = rand(2..5) session[:gold] += house session[:activity] << "Earned #{house} gold from the House! " + Time.now.strftime("%Y/%m/%d %I:%M %P") redirect_to '/rpg' end def casino casino = rand(-50..50) session[:gold] += casino if casino < 0 then session[:activity] << "lost #{casino} gold from the Casino! " + Time.now.strftime("%Y/%m/%d %I:%M %P") else session[:activity] << "Earned #{casino} golds from the Casino! " + Time.now.strftime("%Y/%m/%d %I:%M %P") end redirect_to '/rpg' end end
true
416b1c1dbf2de8a6dd98a64232980ebff553c5d4
Ruby
andrebnf/kmeans-slink-rb
/slink_v1.rb
UTF-8
1,601
2.84375
3
[]
no_license
require_relative 'lib/point' require_relative 'lib/file_reader' require_relative 'lib/plotter' require_relative 'slink_cluster_v1' def insert_sorted arr, new_i for i in 0..arr.size-1 if new_i < arr[i] arr.insert(i, new_i) return false end end arr.push new_i return false end if ARGV.size < 2 p "usage: ruby slink.rb <file_name> <k> [<k_interval>]" abort end # points = FileReader.read ARGV[0] points, names = FileReader.read "data/" + ARGV[0], true # points = FileReader.read "data/c2ds1-2sp.txt" n = points.size k = ARGV[1].to_i k2 = ARGV[2].to_i k2 = k if k2 == 0 clusters = [] clusters = SLinkCluster.init points # every point is a cluster at beginning c1, c2 = -1, -1 while clusters.size != k min_dist = -1 for i in 0..clusters.size-1 for j in i+1..clusters.size-1 dist = SLinkCluster.get_min_distance clusters[i], clusters[j] if dist < min_dist || min_dist == -1 min_dist = dist c1 = i c2 = j end end end clusters = SLinkCluster.merge clusters, c1, c2 p clusters.size if clusters.size <= k2 && clusters.size >= k x = [] y = [] c = [] points.each do |p| x << p.x y << p.y c << p.cluster_id end Plotter.plot x, y, c out = "" for i in 0..points.size-1 out += names[i] + "\t" + points[i].cluster_id.to_s + "\n" end out_fn = ARGV[0].split(".") out_fn = out_fn[0..out_fn.size-2].join(".") File.open("./data_out_slink/#{out_fn}K_#{clusters.size}.out", 'w') { |file| file.write(out) } end end
true
debbe3795b83386f8baef9a1d1dfb679c236169e
Ruby
briankung/understanding-computation
/test/support/node_exec.rb
UTF-8
474
2.734375
3
[]
no_license
require 'json' require 'open3' class NodeError < StandardError def initialize(msg="Invalid JavaScript generated!") super end end def node_exec code, env={} result, error = nil, nil input = "console.log((#{code}).call(null, #{env.to_json}))" Open3.popen3('node') do |stdin, stdout, stderr, thread| stdin.write(input) stdin.close result = stdout.read.chomp error = stderr.read end raise NodeError, error unless error.empty? result end
true
adf5a4609ed077f5f0cf9eab67ad9e9282627e7b
Ruby
rutgerjmckenna/sql-crowdfunding-lab-nyc-web-080519
/lib/sql_queries.rb
UTF-8
1,965
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your sql queries in this file in the appropriate method like the example below: # # def select_category_from_projects # "SELECT category FROM projects;" # end # Make sure each ruby method returns a string containing a valid SQL statement. def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title "SELECT projects.title, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title ;" end def selects_the_user_name_age_and_pledge_amount_for_all_pledges_alphabetized_by_name "SELECT users.name, users.age, SUM(pledges.amount) FROM users JOIN pledges ON users.id = pledges.user_id GROUP BY users.name" end def selects_the_titles_and_amount_over_goal_of_all_projects_that_have_met_their_funding_goal "SELECT projects.title, (SUM(pledges.amount) - projects.funding_goal) AS amount_left FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title HAVING amount_left >= 0;" end def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_summed_amount "SELECT users.name, SUM(pledges.amount) FROM users JOIN pledges ON users.id = pledges.user_id GROUP BY users.name ORDER BY SUM(pledges.amount);" end def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category "SELECT projects.category, pledges.amount FROM projects JOIN pledges ON projects.id = pledges.project_id WHERE projects.category = 'music';" end def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category "SELECT projects.category, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id WHERE projects.category = 'books' GROUP BY projects.category;" end
true
ce0c5b78ca5c2b4e6a731d4f6121a40e4028749a
Ruby
hlbtyne/badges-and-schedules-london-web-career-040119
/conference_badges.rb
UTF-8
678
3.671875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def badge_maker(name) "Hello, my name is #{name}." end def batch_badge_creator(attendees) badges = [] attendees.each do |name| badges.push(badge_maker(name)) end return badges end def assign_rooms(attendees) room_assignments = [] room_number = 1 attendees.each do |attendee| room_assignments.push("Hello, #{attendee}! You'll be assigned to room #{room_number}!") room_number += 1 end return room_assignments end # COME BACK TO THIS # def printer(attendees) # batch_badge_creator(attendees).each do |badge_message| # return badge_message # end # assign_rooms(attendees).each do |room_message| # return room_message # end # end
true
514d9b8f9ff89b4f2de32b02971da3496dc0b0ff
Ruby
Liboul/martyr
/lib/martyr/runtime/query/metric_dependency_resolver.rb
UTF-8
5,960
2.5625
3
[ "MIT" ]
permissive
module Martyr module Runtime class MetricDependencyResolver attr_reader :cube # @param cube [BaseCube] either virtual or regular cube def initialize(cube) @cube = cube @metrics_by_cube = {} @inferred_fact_grain_by_cube = {} end def to_hash Hash[@metrics_by_cube.map{ |cube_name, arr| [cube_name, arr.keys] }] end def inspect to_hash.inspect end # @option all [Boolean] send true if all metrics, including dependents, should be retrieved. Otherwise, only # explicitly asked-for metrics will be included in the result set # @return [Array<BaseMetric>] def metrics(all: false) metric_entries = @metrics_by_cube.flat_map { |_cube_name, metric_ids_hash| metric_ids_hash.values } metric_entries.select! { |entry| entry[:explicit] } unless all metric_entries.map { |entry| entry[:metric] } end # @return [Array<String>] metric IDs def metric_ids(all: false) metrics(all: all).map(&:id) end # @param cube_name [String] # @option all [Boolean] send true if all metrics, including dependents, should be retrieved. Otherwise, only # explicitly asked-for metrics will be included in the result set # @return [Array<BaseMetric>] def metrics_for(cube_name, all: false) relevant_entries_for(cube_name, all: all).map do |_metric_id, metric_entry| metric_entry[:metric] end end # @see metrics_for # @return [Array<String>] metric IDs def metric_ids_for(cube_name, all: false) relevant_entries_for(cube_name, all: all).map(&:first) end # @return [Array<String>] of all fact grains combined acrross cubes def inferred_fact_grain @inferred_fact_grain_by_cube.flat_map{ |_cube_name, levels_lookup_hash| levels_lookup_hash.keys }.uniq end # @return [Array<String>] array of level IDs that need to be part of the fact grain in order for the metrics to # compute, including any dependent metrics. This does not include the default_fact_grain def inferred_fact_grain_for(cube_name) @inferred_fact_grain_by_cube[cube_name].try(:keys) || [] end # @return [Array<String>] array of sub facts that need to be joined in order to support the required metrics, # as provided under the `sub_queries` key of the metric definition. def sub_facts_for(cube_name) metrics_for(cube_name, all: true).flat_map {|metric| metric.sub_queries if metric.respond_to?(:sub_queries) }.compact end # Recursively add the metric and its dependencies # @param metric_id [String] fully qualified metric ID (with cube name) # @option explicit [Boolean] indicates whether the metric was asked to be included as part of a query. # send false for metrics that were added due to dependency. def add_metric(metric_id, explicit: true) metric = cube.find_metric_id(metric_id) add_count_distinct_fact_grain_dependency(metric, explicit) return unless register_metric(metric, explicit) add_fact_grain_dependency(metric) add_dependent_metrics(metric) end def data_dup dup.instance_eval do @metrics_by_cube = @metrics_by_cube.deep_dup @inferred_fact_grain_by_cube = @inferred_fact_grain_by_cube.deep_dup self end end private # @param metric [BaseMetric] # @param explicit [Boolean] see #add_metric # @return [Boolean] # true if the metric was added for the first time. # false if the metric was already added before # # @note this method makes sure to set the explicit flag to true if explicit param is true. The flag will not be # changed if explicit param is false. # # This makes sure that if the user specifies select('a', 'b') and 'a' depends on 'b', then 'b' will be marked # as explicit, despite the fact it was added as explicit=false when 'a' was added. # def register_metric(metric, explicit) @metrics_by_cube[metric.cube_name] ||= {} if @metrics_by_cube[metric.cube_name].has_key?(metric.id) @metrics_by_cube[metric.cube_name][metric.id][:explicit] = true if explicit return false end @metrics_by_cube[metric.cube_name][metric.id] = { metric: metric, explicit: explicit } true end # The level which count-distinct metric A depends on is added only if another metric depends on metric A, # and only if the user did not specify a custom fact_grain for metric A. def add_count_distinct_fact_grain_dependency(metric, explicit) return unless !explicit and metric.is_a?(Schema::CountDistinctMetric) and metric.fact_grain.blank? store_inferred_fact_grain(metric.cube_name, metric.level_id) end def add_fact_grain_dependency(metric) return unless metric.respond_to?(:fact_grain) and metric.fact_grain.present? metric.fact_grain.each do |level_id| store_inferred_fact_grain(metric.cube_name, level_id) end end # @param metric [BaseMetric] def add_dependent_metrics(metric) return unless metric.respond_to?(:depends_on) and metric.depends_on.present? metric.depends_on.each do |dependent_metric_id| add_metric(dependent_metric_id, explicit: false) end end # @see metrics_for def relevant_entries_for(cube_name, all:) candidates = @metrics_by_cube[cube_name] || [] candidates.select!{ |_metric_id, metric_entry| metric_entry[:explicit] } unless all candidates end def store_inferred_fact_grain(cube_name, level_id) @inferred_fact_grain_by_cube[cube_name] ||= {} @inferred_fact_grain_by_cube[cube_name][level_id] = true end end end end
true
0847dfe1137401e7c47c7d8bb5b280b464126b26
Ruby
jamiepaterson6715/HW-music_collection
/db/console.rb
UTF-8
344
2.671875
3
[]
no_license
require("pry") require_relative("../models/artists") require_relative("../models/albums") # Albums.delete_all # Artists.delete_all() artist1 = Artist.new({"name" => "AC/DC"}) artist1.save() album1 = Albums.new({ "name" => "Who Made Who", "genre" => "Hard Rock", "artist_id" => artist1.id }) album1.save() binding.pry nil
true
5cefd998e67923852f96a527196d558164fff143
Ruby
stevecass/simple-ruby-crud
/app.rb
UTF-8
3,595
3.71875
4
[]
no_license
require_relative 'parser' require_relative 'person' require 'colorize' class App def initialize @people = {} PeoplePersister.load_people.each { |person| @people[person.id] = person } puts "Loaded #{@people.length} people" until @quit_requested do main_loop end end def save_people PeoplePersister.save_people @people.values show_status "People collection saved. There are #{@people.count} people." end def cls print "\e[2J" print "\e[H" end def show_status s puts s.colorize(:green) sleep 1 end def warn s puts s.colorize(:orange) sleep 1 end def show_error s puts s.colorize(:red) sleep 1 end def show_menu cls puts "What do you want to do?" puts "C - create a new person" puts "R - retrieve a person / some people" puts "U - update a record " puts "D - delete a person" puts "Q - quit" puts "We are managing #{@people.count} people." input = gets.chomp case input.upcase when 'C' prompt_for_person when 'R' find_people when 'U' do_update when 'D' do_deletion when 'Q' @quit_requested = true end end def main_loop show_menu end def do_deletion print "Enter id of a person to delete: " id = gets.chomp.to_i print "Are you sure? " reply = gets.chomp remove_person(id) if reply.upcase == "Y" end def remove_person id @people.delete(id) save_people end def text_entered s = gets.chomp s == '_' ? nil : s end def do_update print "Enter id of a person to update: " id = gets.chomp.to_i p = @people[id] if !p puts "Sorry couldn't find a person with that id" else puts "Enter the updated data below. To leave an item unchanged, enter underscore" print "Enter first name: (or _ for #{p.first_name}) " p.first_name = text_entered if text_entered print "Enter last name: (or _ for #{p.last_name}) " p.last_name = text_entered if text_entered print "Enter email: (or _ for #{p.email}) " p.email = text_entered if text_entered print "Enter phone: (or _ for #{p.phone}) " p.phone = text_entered if text_entered save_people end end def prompt_for_person p = Person.new print "Enter first name: " p.first_name = gets.chomp print "Enter last name: " p.last_name = gets.chomp print "Enter email: " p.email = gets.chomp print "Enter phone: " p.phone = gets.chomp p.created_at = Time.now max_person = @people.values.max_by { |ele| ele.id } p.id = 1 + max_person.id @people[p.id] = p save_people end def find_by(by, val) return [] if val == nil || by == nil results = [] results << @people.values.select do |p| res = p.send(by) res && val.to_s == res.to_s end results.flatten end def find_people print "What do you want to find by? " field = gets.chomp print "What should it match? " val = gets.chomp results = find_by(field, val) results.flatten! results.each do |person| puts person.to_display end show_status "Found #{results.size} " puts "Press enter to continue" gets end end class PeoplePersister FILE_NAME = 'people.csv' def self.load_people result = [] arr = CSVParser.import FILE_NAME arr.each {|h| result << Person.new(h) } result end def self.save_people arr arr = arr.map { |p| p.to_hash } CSVParser.export FILE_NAME, arr end end app = App.new
true
49505e5b1629cddb98fa2dd2e6cdcc63633f838d
Ruby
deCadeh/wallarm-source-leak
/pkgs/wallarm_logger/wallarm_logger/logger_hub.rb
UTF-8
1,933
3
3
[]
no_license
require_relative './json_logger' require_relative './local_logger' require_relative './standart_logger' # Singletone container of all LoggerHub instances # Use it to reopen all logs by signal class ActiveLoggerHubs @@hubs = [] class << self def hubs @@hubs end def clear @@hubs = [] end def add(hub) @@hubs << hub end def reopen @@hubs.each(&:reopen) end def trap(signal) Signal.trap(signal) do ActiveLoggerHubs.reopen end end end end # LoggerHub contains other loggers # Use LoggerHub to log messages into different loggers simultaneously class LoggerHub attr_reader :loggers attr_reader :old_loggers def initialize @mutex = Mutex.new @reopen = false @loggers = [] @old_loggers = [] ActiveLoggerHubs.add(self) end # Use for loggers that can be reopened def add_logger(logger) @loggers << logger end # Use for loggers that cannot be reopened def add_old_logger(logger) @old_loggers << logger end # Logs will be reopened later def reopen @reopen = true end def get_reopen @reopen end def pop_last_logger @loggers = @loggers[0...-1] end LOG_METHODS = [ :debug, :info, :warn, :warning, :error, :fatal, :unknown ].freeze def exception(ex) @mutex.synchronize { reopen_logs if @reopen } (@loggers + @old_loggers).each do |logger| logger.exception(ex) end end LOG_METHODS.each do |method| define_method(method) do |*args, &block| @mutex.synchronize do reopen_logs if @reopen (@loggers + @old_loggers).each do |logger| if block logger.method(method).call(block.call) else logger.method(method).call(*args) end end end end end private def reopen_logs @loggers.map!(&:reopen) @reopen = false end end
true
24cb3377cb4768f017f9ba45ebd120cc001e59e1
Ruby
omitter/mobility
/lib/mobility/plugins/cache/translation_cacher.rb
UTF-8
1,181
2.65625
3
[ "MIT" ]
permissive
module Mobility module Plugins module Cache =begin Creates a module to cache a given translation fetch method. The cacher defines private methods +cache+ and +clear_cache+ to access and clear, respectively, a translations hash. This cacher is used to cache translation values in {Mobility::Plugins::Cache}, and also to cache translation *records* in {Mobility::Backends::Table} and {Mobility::Backends::KeyValue}. =end class TranslationCacher < Module # @param [Symbol] fetch_method Name of translation fetch method to cache def initialize(fetch_method) class_eval <<-EOM, __FILE__, __LINE__ + 1 def #{fetch_method} locale, **options return super(locale, options) if options.delete(:cache) == false if cache.has_key?(locale) cache[locale] else cache[locale] = super(locale, options) end end EOM include CacheMethods end module CacheMethods private def cache; @cache ||= {}; end def clear_cache; @cache = {}; end end end end end end
true
dbded6bb696a091c7fe0c3f776d30e75641d0f56
Ruby
kromoser/oxford-comma-v-000
/lib/oxford_comma.rb
UTF-8
177
3.578125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def oxford_comma(array) x = array.count if x <= 2 array.join(" and ") else new_string = array[0..x-2].join(", ") new_string << ", and #{array[x-1]}" end end
true
04e3a3d812a92ba0ca4c9ee393a343b02918723f
Ruby
kamui/kanpachi
/examples/twitter.rb
UTF-8
5,030
2.828125
3
[ "MIT" ]
permissive
require 'roar/representer/json' require 'roar/representer/feature/hypermedia' module UserRepresenter include Roar::Representer::JSON include Roar::Representer::Feature::Hypermedia property :first_name, type: String, required: true, doc: "it's the first name" property :last_name, type: String, required: true, doc: "it's the last name" end api 'Twitter' do title 'REST API v1.1 Resources' description 'This describes the resources that make up the official Twitter API v1.1' host 'api.twitter.com' error :malformed_params do description 'Sending invalid JSON will result in a 400 Bad Request response.' response do status 400 header 'Content-Type', 'application/json' representation do property :message, type: String end end end section 'Timelines' do description 'Timelines are collections of Tweets, ordered with the most recent first.' resource :get, '/statuses/mentions_timeline' do name 'Mentions timeline' description <<-TEXT Returns the 20 most recent mentions (tweets containing a users's @screen_name) for the authenticating user. The timeline returned is the equivalent of the one seen when you view your mentions on twitter.com. This method can only return up to 800 tweets. See __Working with Timelines__ for instructions on traversing timelines. TEXT versions '1.1' ssl true formats :json params do optional do integer :count, doc: 'Specifies the number of tweets to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed after the count has been applied. We include retweets in the count, even if `include_rts` is not supplied. It is recommended you always send `include_rts=1` when using this API method.' integer :since_id, doc: 'Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available. __Example Values__: 12345' integer :max_id, doc: 'Returns results with an ID less than (that is, older than) or equal to the specified ID. __Example Values__: 54321' boolean :trim_user, doc: 'When set to either true, t or 1, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object. __Example Values__: true' boolean :contributor_details, doc: 'This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included. __Example Values__: true' boolean :include_entities, doc: 'The `entities` node will be disincluded when set to false. __Example Values__: false' end end response do status 200 header 'Content-Type', 'application/json' representation do property :id, type: Integer, doc: "it's the id" property :title, type: String, doc: "it's the title" collection :users, extend: UserRepresenter, doc: "it's the users" end end end resource :get, '/statuses/user_timeline' do name 'User timeline' description <<-TEXT Returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters. User timelines belonging to protected users may only be requested when the authenticated user either "owns" the timeline or is an approved follower of the owner. The timeline returned is the equivalent of the one seen when you view a user's profile on twitter.com. This method can only return up to 3,200 of a user's most recent Tweets. Native retweets of other statuses by the user is included in this total, regardless of whether include_rts is set to false when requesting this resource. See Working with Timelines for instructions on traversing timelines. See Embeddable Timelines, Embeddable Tweets, and GET statuses/oembed for tools to render Tweets according to Display Requirements. TEXT versions '1.1' ssl true formats :json params do optional do integer :user_id string :screen_name integer :since_id integer :count integer :max_id boolean :trim_user boolean :exclude_replies boolean :contributor_details boolean :include_rts end end response do status 200 header 'Content-Type', 'application/json' representation do property :id, type: Integer, doc: "it's the id" property :title, type: String, doc: "it's the title" collection :users, extend: UserRepresenter, doc: "it's the users" end end end end end
true
f8068d3aec2278d70093816f541b13cd79928d55
Ruby
Samellenrider/learn-to-program
/chapter08/esmethodvar.rb
UTF-8
126
2.734375
3
[]
no_license
def excitedsurfer excitementlevel puts 'Hey mate, let\'s go surf !!!!! ' * excitementlevel end puts excitedsurfer 100
true
5d5b15ae22d49a17bf32ee1aa8e92a528cc52706
Ruby
krivospitsky/SimpleShop
/app/models/delivery_method.rb
UTF-8
398
2.53125
3
[]
no_license
class DeliveryMethod < ActiveRecord::Base default_scope -> {order(sort_order: :asc)} scope :enabled, -> { where(enabled: 't') } has_and_belongs_to_many :payment_methods def text if price && price > 0 "#{name} (+#{price} руб.)" else name end end def applicable?(price) (min_price.to_i==0 || min_price<price) && (max_price.to_i==0 || max_price>price) end end
true
e5a47db9b49c8c3ad5c34dfd2c2c63dde3471b76
Ruby
cdemyanovich/demyano_bst
/lib/demyano_bst/node.rb
UTF-8
1,630
3.28125
3
[]
no_license
module DemyanoBst class Node attr_accessor :value, :parent, :left_child, :right_child def initialize(value, parent = nil) @value = value @parent = parent end def disown(child) self.left_child = nil if self.left_child && self.left_child.value == child.value self.right_child = nil if self.right_child && self.right_child.value == child.value end def root? self.parent.nil? end def leaf? self.left_child.nil? && self.right_child.nil? end def only_child return nil if leaf? return nil if self.left_child && self.right_child return self.left_child if self.left_child return self.right_child if self.right_child end # right-most child of left child def in_order_predecessor return nil if leaf? node = self.left_child while node.right_child node = node.right_child end node end def replace_in_parent(new_child) if self.parent if self.parent.left_child == self self.parent.left_child = new_child else self.parent.right_child = new_child end end new_child.parent = self.parent end # check the left child, since we're using in-order predecessor when # handling a delete of a node with 2 children def adopt_children_of(other_parent) if other_parent.left_child != self self.left_child = other_parent.left_child self.left_child.parent = self end self.right_child = other_parent.right_child self.right_child.parent = self end end end
true
49988e5980dacea6cff1bae82341341553f1e6d9
Ruby
yuihyama/mre
/module/module_prepend.rb
UTF-8
291
3.15625
3
[]
no_license
#!/usr/bin/env ruby module MyModule def hello_world 'hello, world' end end class MyClass1 prepend MyModule end obj1 = MyClass1.new p obj1.hello_world puts obj1.hello_world puts class MyClass2 prepend MyModule end obj2 = MyClass2.new p obj2.hello_world puts obj2.hello_world
true
99a9f0d2321f632fbb08411343eb1154329ce365
Ruby
lesniakania/twitter_analyser
/lib/sequences/prefix_span.rb
UTF-8
2,972
2.96875
3
[]
no_license
require 'lib/models/sequence_part' require 'lib/models/sequence_freq' require 'lib/models/user' require 'lib/models/twitt' MinSequenceFreq = 10 class PrefixSpan def initialize(twitts) # 'log' puts "Init started..." SequencePart.delete SequenceFreq.delete vector_number = 0 twitts.each do |twitt| part_sequences = [] while parent_twitt = twitt.parent part_sequences << SequencePart.new( :start_edge => parent_twitt.user, :end_edge => twitt.user, :vector_number => vector_number ) twitt = parent_twitt end size = part_sequences.size part_sequences.each_with_index do |part_sequence,i| part_sequence.position = size-i part_sequence.save end vector_number += 1 end # 'log' puts "init finished" end def prefix_span(map, pos, min_sequence_freq) map2 = Hash.new(0) sequences = [] map.each do |key, value| sequences = SequencePart.filter( :position => pos-1, :start_edge_id => key[pos*2-4], :end_edge_id => key[pos*2-3] ).all sequences.each do |seq| tmp = pos-1 check = 1 while tmp > 0 and check == 1 do unless SequencePart.filter( { :position => tmp-1, :vector_number => seq.vector_number }, ~{ :start_edge_id => key[tmp*2-4], :end_edge_id => key[tmp*2-3] } ).empty? check = 0 end tmp -= 1 end if check == 1 SequencePart.filter( :vector_number => seq.vector_number, :position => pos ).each do |sequence| if sequence != seq val = Array.new(key) map2[val.concat([sequence.start_edge.id, sequence.end_edge.id])] += 1 end end end end end map2.delete_if {|key, value| value < min_sequence_freq } # 'log' map2.each { |k,v| puts "%s %d" % [k,v] } map.update(map2) unless sequences.empty? map.update(prefix_span(map2, pos + 1, min_sequence_freq)) end return map2 end def find_frequent(min_sequence_freq=MinSequenceFreq) map = Hash.new(0) #pierwszy krok algorytmu; wyszukanie najkrotszych sekwencji SequencePart.filter(:position => 1).each do |seq| new_seq = [seq.start_edge.id, seq.end_edge.id] map[new_seq] += 1 end map.delete_if {|key, value| value < min_sequence_freq } prefix_span(map, 2, min_sequence_freq) map.each do |sequence, frequency| key = sequence.join("-") unless existing_sequence = SequenceFreq.filter(:key => key).first SequenceFreq.create(:key => key, :frequency => frequency, :length => sequence.size) else existing_sequence.frequency += frequency existing_sequence.save end end end end
true
76ab244963a283fb78295cc21ae2d99bcbcea84f
Ruby
Middlebrooks314/sinatra-dynamic-routes-lab-chicago-web-062419
/app.rb
UTF-8
230
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative 'config/environment' class App < Sinatra::Base # Write your code here! get '/reversename/:name' params[:name].reverse end get '/square/:number' num = params[:number] num.to_i **2 end end
true
3bd574c74fd58cc066715af97529138c3abbecdc
Ruby
rubythings/rubyd3
/node.rb
UTF-8
1,093
3
3
[]
no_license
class Node attr_accessor :force_coulomb attr_accessor :force_harmonic attr_accessor :velocity attr_accessor :id attr_accessor :cc_number, :coordinate_x, :coordinate_y, :neighbour_ids, :movable, :name, :transition def initialize(node_id, name, transition) @name = name @transition = transition @id = node_id # id (as an integer for example) @neighbour_ids = [] # list of the ids of the neighbours @degree = 0 # number of neighbours @coordinate_x = 0 @coordinate_y = 0 @force_coulomb = [0,0] @force_harmonic = [0,0] @cc_number = 0 # the number of the connected component (0 if not assigned yet) @cc_centers = [] @velocity = [0, 0] # instead of replacing the nodes, change its velocity to produce inertia @movable = 1 end def getNeighbours return @neighbour_ids end def getDegree return @degree end def getId return @id end def setNeighbour(node_id) @neighbour_ids << node_id @degree += 1 end def deleteNeighbour(node_id) @neighbour_ids.delete_if{|x| x == node_id} @degree -= 1 end end
true
a9402cb1eb61e6c6eebdd8f207d9e414de8e9397
Ruby
mikeyduece/vend
/spec/features/user_see_snack_info_spec.rb
UTF-8
1,708
2.765625
3
[]
no_license
require 'rails_helper' # When I visit a specific snack page # I see the name of that snack # I see the price for that snack # I see a list of locations with vending machines that carry that snack # I see the average price for snacks in those vending machines # And I see a count of the different kinds of items in that vending machine. # ``` feature "User" do context "visits snack page" do scenario "sees snack name and price" do owner = Owner.create!(name: 'Mike', id: 1) machine = Machine.create!(id: 1, location: 'turing', owner_id: 1) machine_2 = Machine.create!(id: 2, location: 'union station', owner_id: 1) snack = Snack.create!(name: 'Cheetos', price: 1.0) snack_2 = Snack.create!(name: 'Doritos', price: 4.0) machine.snacks << snack machine_2.snacks = [snack, snack_2] visit snack_path(snack) expect(page).to have_content(snack.name) expect(page).to have_content(snack.price) end scenario "sees locations with machines that carry that snack" do owner = Owner.create!(name: 'Mike', id: 1) machine = Machine.create!(id: 1, location: 'turing', owner_id: 1) machine_2 = Machine.create!(id: 2, location: 'union station', owner_id: 1) snack = Snack.create!(name: 'Cheetos', price: 1.0) snack_2 = Snack.create!(name: 'Doritos', price: 4.0) machine.snacks << snack machine_2.snacks = [snack, snack_2] visit snack_path(snack) save_and_open_page expect(page).to have_content(machine.location) expect(page).to have_content(machine.average_price) end # # xscenario "sees count of snacks in other machines" do # # end end end
true
c28b0e57983bd3f5d5207dd492f1513c5428fc11
Ruby
gglin/project-euler
/ruby_all/124.rb
UTF-8
753
3.78125
4
[]
no_license
# Problem 124: Ordered radicals # http://projecteuler.net/problem=124 # # The radical of n, rad(n), is the product of distinct prime factors of n. For example, 504 = 2^3× 3^2× 7, so rad(504) = 2 × 3 × 7 = 42. # If we calculate rad(n) for 1 ≤n ≤ 10, then sort them on rad(n), and sorting on n if the radical values are equal, we get: # Unsorted #   # Sorted # (tile)n # (tile)rad(n) # (tile) # (tile)n # (tile)rad(n) # (tile)k # 11 #   # 111 # 22 #   # 222 # 33 #   # 423 # 42 #   # 824 # 55 #   # 335 # 66 #   # 936 # 77 #   # 557 # 82 #   # 668 # 93 #   # 779 # 1010 #   # 101010 # Let E(k) be the kth element in the sorted n column; for example, E(4) = 8 and E(6) = 9. # If rad(n) is sorted for 1 ≤n ≤ 100000, find E(10000).
true
0ed94579eba47c230604b6a34b9cd256e1cf39cb
Ruby
Baconthorpe/looping-loop-000
/looping.rb
UTF-8
93
2.890625
3
[]
no_license
def looping #your code here while (1 == 1) end end #call your method here looping()
true
fc973bf6961a83b99b403a6cbff00aa6652fa96b
Ruby
mnutt/intranet
/vendor/rails/activerecord/lib/active_record/connection_adapters/abstract/quoting.rb
UTF-8
2,226
2.734375
3
[ "MIT" ]
permissive
module ActiveRecord module ConnectionAdapters # :nodoc: module Quoting # Quotes the column value to help prevent # {SQL injection attacks}[http://en.wikipedia.org/wiki/SQL_injection]. def quote(value, column = nil) # records are quoted as their primary key return value.quoted_id if value.respond_to?(:quoted_id) case value when String, ActiveSupport::Multibyte::Chars value = value.to_s if column && column.type == :binary && column.class.respond_to?(:string_to_binary) "#{quoted_string_prefix}'#{quote_string(column.class.string_to_binary(value))}'" # ' (for ruby-mode) elsif column && [:integer, :float].include?(column.type) value = column.type == :integer ? value.to_i : value.to_f value.to_s else "#{quoted_string_prefix}'#{quote_string(value)}'" # ' (for ruby-mode) end when NilClass then "NULL" when TrueClass then (column && column.type == :integer ? '1' : quoted_true) when FalseClass then (column && column.type == :integer ? '0' : quoted_false) when Float, Fixnum, Bignum then value.to_s # BigDecimals need to be output in a non-normalized form and quoted. when BigDecimal then value.to_s('F') else if value.acts_like?(:date) || value.acts_like?(:time) "'#{quoted_date(value)}'" else "#{quoted_string_prefix}'#{quote_string(value.to_yaml)}'" end end end # Quotes a string, escaping any ' (single quote) and \ (backslash) # characters. def quote_string(s) s.gsub(/\\/, '\&\&').gsub(/'/, "''") # ' (for ruby-mode) end # Returns a quoted form of the column name. This is highly adapter # specific. def quote_column_name(name) name end def quoted_true "'t'" end def quoted_false "'f'" end def quoted_date(value) value.to_s(:db) end def quoted_string_prefix '' end end end end
true
e4292a780a1ff03f57409d982b543f270c0365fa
Ruby
badr96/git-thp
/Vendredi/exo_13.rb
UTF-8
173
3.5
4
[]
no_license
puts"hello buddy what was ur birt year: " birth_year = gets.to_i puts"\nyear that past: " while birth_year != 2018+1 puts"#{birth_year}" birth_year = birth_year + 1 end
true
85d664c036404212d718655f4e77ab8fba81548d
Ruby
mv/ynab-csv-scripts
/bin/sofisa-pdf.rb
UTF-8
2,245
2.84375
3
[]
no_license
#!/usr/bin/env ruby require 'pp' ### ### file name ### def usage() puts <<-"USAGE" Usage: #{$0} path-to-sofisa-pdf USAGE exit 1 end usage if ARGV.empty? pdf_name = ARGV[0] file_name = pdf_name base_name = File.basename(pdf_name, '.*') dir_name = File.dirname( File.absolute_path( pdf_name ) ) csv_name = base_name + '.csv' txt_name = base_name + '.txt' if ENV['YNAB_DEBUG'] puts "Processing: [#{pdf_name}]" puts "base: #{base_name}" puts "dir: #{dir_name}" puts "csv: #{csv_name}" puts "txt: #{txt_name}" end ### ### definitions ### def trim( string ) return '' unless string string.gsub(/^\s+|\s+$/,'') end def noblanks( string ) return '' unless string string.gsub(/\s{2,}/,' ') end csv = [] ### ### pre-process ### # simplify: pdf -> txt system("pdftotext #{pdf_name} -layout #{txt_name}") # parse txt File.open( txt_name, :encoding => 'utf-8').each do |line| line.chomp! puts "line: [#{line}]" if ENV['YNAB_DEBUG'] case line when /Saldo em/ next when /^\d\d[\/]\d\d[\/]\d\d\d\d/ line.encode(Encoding::ISO_8859_1) day, mes, year, payee, val = line.match( /^(\d\d)[\/](\d\d)[\/](\d\d\d\d) \s+ (\w+ .*) \s+ ([-]?\d?[.]?\d+[,]\d+)/ixu ).captures dt = "#{year}/#{mes}/#{day}" payee = trim(payee) payee = noblanks(payee) memo = payee val.gsub!( ".", "" ) val.gsub!( ",", ".") # date,payee,category,memo,outflow,inflow res = "#{dt},#{payee},,#{memo},,#{val}" puts "res: [#{res}]" if ENV['YNAB_DEBUG'] csv << res end # case line end # file ### ### Results ### # sort order for some same date entries csv = csv.sort.join("\n") if ENV['YNAB_STDOUT'] puts "Date,Payee,Category,Memo,Outflow,Inflow" puts csv else base_name = File.basename(file_name, '.*') dir_name = File.dirname( File.absolute_path( file_name ) ) csv_name = base_name + '.ynab.csv' if ENV['YNAB_DEBUG'] puts "Processing: [#{file_name}]" puts "base: #{base_name}" puts "dir: #{dir_name}" puts "csv: #{csv_name}" end file = File.open(csv_name, 'w') file.write("Date,Payee,Category,Memo,Outflow,Inflow\n") file.write(csv) file.write("\n") file.close puts "Created: [#{csv_name}]" end
true
b3a2fbef2ac913f6fe59b0fb1ae2befedac4e977
Ruby
rahul26goyal/eventmachine-ruby
/1. sample.rb
UTF-8
846
2.921875
3
[ "MIT" ]
permissive
$eventmachine_library = :pure_ruby require 'eventmachine' def register() puts "register...." i = 0 while i < 2 puts "i: #{i}" i = i + 1 #sleep 1 end end def register2() puts "register2...." i = 0 while i < 2 puts "i: #{i}" i = i + 1 sleep 1 end end def start() #Process.daemon puts "starting EM Run in processs...#{Process.pid}" EM.run { puts "starting reactor...." #handle graceful shutdown. Signal.trap("INT") { puts "quitting..." EM.stop() } #kick start functions in reactor loop. #there are not events but synchronoue execution code in reactor. register() #register2() puts "all the function in reactor are executed...waiting infinite..." } puts "EM is stopped...." end start() puts "we will never reach here unless someones quits.."
true
cdde7e8634d303cc4630c637119fe94063ac073f
Ruby
plasticine/simulacrum
/lib/simulacrum/cli/parser.rb
UTF-8
2,421
2.734375
3
[]
no_license
# encoding: UTF-8 require 'optparse' require 'ostruct' require 'simulacrum' module Simulacrum module CLI # Option parser for handling options passed into the Simulacrum CLI # # This class is mostly borrowed from Cane's Parser class. Thanks Xav! <3 class Parser attr_reader :stdout # Exception to indicate that no further processing is required and the # program can exit. This is used to handle --help and --version flags. class OptionsHandled < RuntimeError; end def self.parse(args) new.parse(args) end def initialize(stdout = $stdout) @stdout = stdout add_banner add_format_options add_separator add_version add_help end def parse(args, _return = true) parser.parse!(args) options['files'] = args if args.size > 0 OpenStruct.new(default_options.merge(options)) rescue OptionParser::InvalidOption, OptionParser::AmbiguousOption args = %w(--help) _return = false retry rescue OptionsHandled _return end private def default_options {} end def add_banner parser.banner = 'Usage: simulacrum [options] [files or directories]' add_separator end def add_separator parser.separator '' end def add_version parser.on_tail('--version', 'Show version') do stdout.puts Simulacrum::VERSION fail OptionsHandled end end def add_help parser.on_tail('-h', '--help', 'You\'re looking at it!') do stdout.puts parser fail OptionsHandled end end def add_format_options parser.on('-c', '--[no-]color', '--[no-]colour', 'Enable color in the output.') do |value| options['color'] = value end parser.on('-v', '--verbose', 'Be more shouty.') do |value| options['verbose'] = value end end def options @options ||= begin options = {} options['files'] = ['spec/ui'] options['color'] = false options['verbose'] = false options end end def parser @parser ||= OptionParser.new end end end end
true
c5da4db32cf57b0213172c612f6a0e6180c3e233
Ruby
varyform/wufoo
/lib/wufoo/query.rb
UTF-8
1,097
2.515625
3
[ "MIT" ]
permissive
module Wufoo class Query attr_accessor :client, :form, :params def initialize(client, form, params={}) @client = client @form = form @params = {}.merge(params || {}) end def add_params(new_params) @params.merge!(new_params) self end def process Response.new(@client.post('/api/query/', params.merge({:w_form => form, :w_format => 'json'}))) end class Response attr_accessor :data def initialize(data) @data = data populate end def success? return false if data.nil? || data == {} data['success'] == 'true' end def fail? return true if data.nil? || data == {} error.size > 0 end def error @error || '' end def total_records @total_records end def records @records || [] end private def populate @records = data["query_records"] @total_records = data["total_records"] @error = data['error'] end end end end
true
1d1575c83b7c31a91d874f9bbc90b37ff69b9a64
Ruby
Clinton-dev/substrings
/.github/workflows/sub.rb
UTF-8
520
3.046875
3
[]
no_license
dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"] puts "enter word(s)" words = gets.chomp def subString(word,arrOfSubs) wordsArr = word.downcase.split(' ') subStringFreq = Hash.new(0) wordsArr.select do |word| arrOfSubs.each do |char| if (word.include? char) subStringFreq[word] += 1 end end end subStringFreq.each do |word,frequency| puts word + ' ' + frequency.to_s end end subString(words,dictionary)
true
4ef13655152825fa45062cc80a7cab1c18238648
Ruby
NareshPS/ludak.me
/fbclient/Album.rb
UTF-8
315
3
3
[]
no_license
class Album < Array attr_reader :id, :name, :description def initialize(id, name, description) @id = id @name = name @description = description super() end def photos() Array.new(self) end def to_s() return "|Id: #{@id} Name: #{@name} Description: #{@description}" end end
true
1d16920a280ab62eac969f66c78a84c34fbbfd01
Ruby
rdsoze/ignitte
/app/models/tweet.rb
UTF-8
780
2.671875
3
[]
no_license
class Tweet < ActiveRecord::Base belongs_to :user attr_accessible :id, :tweet_date, :html class << self def check_for_new @tweets = Tweet.get_tweets 10 @tweets.each do |tweet| break unless Tweet.where(id:tweet.attrs['id']).empty? user = User.get_user tweet Tweet.add_tweet(user,tweet) end end def add_tweet(user, tweet) user.tweets << Tweet.new(id: tweet.attrs['id'], html: Twitter::oembed(tweet.attrs['id'], { lang: 'en' })['html'], tweet_date: tweet.attrs['created_at']) user.increment!(:count) p "**Tweet Added** #{tweet.attrs['text']} by #{user['name']}" end def get_tweets number @tweets = Twitter.search('#ignitte', rpp: number, result_type: 'recent') end end end
true
ff7c4c8186b1c360208c6aaf55577818c1f94972
Ruby
gitKrystan/ruby-dealership
/spec/vehicle_spec.rb
UTF-8
1,737
3.203125
3
[ "MIT" ]
permissive
require('rspec') require('vehicle') describe(Vehicle) do before() do Vehicle.clear() end describe('#make') do it('returns the make of the vehicle') do expect(toyota_prius_2000().make()).to(eq("Toyota")) end end describe('#model') do it('returns the model of the vehicle') do expect(toyota_prius_2000().model()).to(eq("Prius")) end end describe('#year') do it('returns the year of the vehicle') do expect(toyota_prius_2000().year()).to(eq(2000)) end end describe('#dealership_id') do it('returns the id of the vehicle dealership') do expect(toyota_prius_2000().dealership_id()).to(eq(1)) end end describe('.all') do it('is empty at first') do expect(Vehicle.all()).to(eq([])) end end describe('#save') do it('will save a vehicle to the array') do test_vehicle = toyota_prius_2000() test_vehicle.save() expect(Vehicle.all()).to(eq([test_vehicle])) end end describe('#clear') do it('will clear the array') do toyota_prius_2000().save() Vehicle.clear() expect(Vehicle.all()).to(eq([])) end end describe('#id') do it('will create a unique id for each vehicle') do test_vehicle = toyota_prius_2000 test_vehicle.save() expect(test_vehicle.id()).to(eq(1)) end end describe('.find') do it('will return a vehicle by its id number') do test_vehicle = toyota_prius_2000 test_vehicle.save() test_vehicle2 = Vehicle.new("Toyota", "Yaris", 2013, 1) test_vehicle2.save() expect(Vehicle.find(test_vehicle.id())).to(eq(test_vehicle)) end end end def toyota_prius_2000 Vehicle.new("Toyota", "Prius", 2000, 1) end
true
5589a33d005c14935691e7bbc0af7e814cfcc482
Ruby
auslaendernola/tts-ruby
/activity_today.rb
UTF-8
1,037
3.984375
4
[]
no_license
#decide an appropriate activity def choose_activity #Get temperature puts "What is today's temperature in F" temp = gets.chomp.to_i if temp > 110 || temp < 20 puts "#{temp} isn't even a real temperature for N.O., that's just silly." choose_activity elsif temp >= 80 puts "It's #{temp}F degrees is perfect for swimming." elsif temp > 50 puts "It's #{temp}F degrees. I'm going hiking!" else puts "It's #{temp}F degrees. It's too cold for hiking." end puts "The Answer to Life" if temp == 42 puts temp > 50 ? "It's so nice out!" : "Brrrr, it's just cold!" # if temp < 0 # "It's #{temp}F degrees. Get off Mars and go home!" # end # # if temp > 1000 # "It's #{temp}F degrees. You are reentering the atmosphere with a faulty shield..." # end # # if temp < 60 || temp > 100 # puts "It's #{temp}F degrees. Keep yo black ass inside" # end # # if temp == 85 # puts "It's #{temp}F degrees. Welcome to Heaven, you can do anything you want!" # end end choose_activity
true
f5183e0b98b32b77c31055d7e9885a80659b3898
Ruby
ngoctoandhv/Ruby_Basic
/16. Ruby - Metaprogramming/02.Metaprogramming basic .rb
UTF-8
1,834
3.8125
4
[]
no_license
#Metaprogramming basic #“Metaprogramming is a programming technique in which computer programs have the ability to treat programs as their data” https://en.wikipedia.org/wiki/Metaprogramming # Example code without metaprogramming #send( ) is an instance method of the Object class class Rubyist def welcome(*args) "Welcome " + args.join(" ") end end obj = Rubyist.new puts(obj.send(:welcome, "famous", "Rubyists")) # => Welcome famous Rubyists #======================================================================================= class Rubyist end rubyist = Rubyist.new if rubyist.respond_to?(:also_railist) puts rubyist.send(:also_railist) else puts "No such information available" end #============================================================================================ class Rubyist private def say_hello name "#{name} rocks!!" end end obj = Rubyist.new puts obj.send(:say_hello, "Matz") #============================================================================================= #The Module#define_method( ) is a private instance method of the class Module class A define_method(:wilma) {puts "Touch me!!!"} end class B < A define_method(:barney) {puts "Call me!!!"} end b = B.new b.barney => "Call me!!!" b.wilma => "Touch me!!!" #================================================================================================ #Kernel#method_missing( ) responds by raising a NoMethodError class Caller def method_missing(m, *args, &block) puts "Called #{m} with #{args.inspect} and #{block}" end end Caller.new.anything # => Called anything with [ ] and Caller.new.anything(3, 4) {something} # => Called anything with [3, 4] and #<Proc:0x02efd664@tmp2.rb:7>
true
171cfcc391f81c63c1e5e539efb35a6a952a8f2b
Ruby
lynneq/bootcamp
/shapes/cube.rb
UTF-8
171
2.765625
3
[]
no_license
$LOAD_PATH << File.dirname(__FILE__) require 'square' class Cube def initialize(square) @square = square end def area 6 * @square.area end end
true
97bfcfa3fb9f47e8ef90eb559599b8423554568a
Ruby
hoangdzung/OOP
/app/views/api/v1/customers/schedules/index.json.jbuilder
UTF-8
273
2.546875
3
[]
no_license
json.code 1 json.message "Thành công" json.data @schedules.each do |schedule| json.merge! schedule.attributes json.time_begin schedule.time_begin.strftime("%d/%m/%Y %H:%M") rescue nil json.time_end schedule.time_end.strftime("%d/%m/%Y %H:%M") rescue nil end
true
dcb33355ec9c79c9c872a8850001fceab03e4ff7
Ruby
r7kamura/qchan-worker
/lib/qchan_worker/builder/executor.rb
UTF-8
1,446
2.625
3
[]
no_license
require "mem" require "open3" require "qchan_worker/builder/publisher" require "tempfile" module QchanWorker class Builder class Executor include Mem def self.execute(*args) new(*args).execute end def initialize(command) @command = command end def execute invoke { exit_status: @exit_status, output: lines.join("\n") } end private def invoke Open3.popen2e(script) do |input, output, thread| while line = output.gets on_printed(line) end on_finished(thread) end end def script str = "/bin/bash -e #{tempfile.path}" str = "docker run -v #{tempdir}:#{workspace} -w #{workspace} #{image} #{str}" if has_docker? str end def on_printed(line) lines << line Publisher.publish(line: line) end def on_finished(thread) @exit_status = thread.value.exitstatus end def tempfile file = Tempfile.new("script") file << @command file.close file end memoize :tempfile def tempdir File.dirname(tempfile) end def lines [] end memoize :lines def has_docker? !`which docker`.empty? end def image "worker" end def workspace "/workspace" end end end end
true
0011ffee82d02bdc1ab40667ebd3c0df0c7871ab
Ruby
Gamua/Flox-Ruby
/test/test_flox.rb
UTF-8
4,884
2.8125
3
[ "BSD-2-Clause", "BSD-2-Clause-Views" ]
permissive
## Author: Daniel Sperl ## Copyright: Copyright 2014 Gamua ## License: Simplified BSD require 'flox' require 'test/unit' require 'mocha/setup' class FloxTest < Test::Unit::TestCase GAME_ID = "game_id" GAME_KEY = "game_key" BASE_URL = "http://url.com" attr_reader :flox def setup @flox = Flox.new(GAME_ID, GAME_KEY, BASE_URL) end def test_init assert_equal(GAME_ID, flox.game_id) assert_equal(GAME_KEY, flox.game_key) assert_equal(BASE_URL, flox.base_url) assert_kind_of(Flox::Player, flox.current_player) assert_equal(:guest, flox.current_player.auth_type) end def test_post_score flox.service.expects(:post).once flox.post_score('leaderboard_id', 123, 'player_name') end def test_load_scores leaderboard_id = "dummy" path = "leaderboards/#{leaderboard_id}" raw_score = { :value => 20, :playerName => 'hugo', :playerId => '123', :country => 'at', :createdAt => '2014-02-24T20:15:00.123Z' } # using time scope (t) flox.service.expects(:get).once.with(path, has_key(:t)).returns([]) scores = flox.load_scores(leaderboard_id, :today) assert_kind_of(Array, scores) assert_equal(0, scores.length) # using player scope (p) flox.service.expects(:get).once.with(path, has_key(:p)).returns([raw_score]) scores = flox.load_scores(leaderboard_id, %w(1, 2, 3)) assert_kind_of(Array, scores) assert_equal(1, scores.length) highscore = scores.first assert_kind_of(Flox::Score, highscore) assert_equal(raw_score[:value], highscore.value) assert_equal(raw_score[:playerName], highscore.player_name) assert_equal(raw_score[:playerId], highscore.player_id) assert_equal(raw_score[:country], highscore.country) assert_equal(raw_score[:createdAt], highscore.created_at.to_xs_datetime) end def test_login_with_key key = "key" result = { :id => '123', :entity => { :authType => 'key' } } flox.service.expects(:login).with(:key, key, nil).once.returns(result) player = flox.login_with_key(key) assert_not_nil(player) assert_equal(:key, player.auth_type) assert_equal(player, flox.current_player) end def test_login_guest player = flox.login_guest assert_not_nil(player) assert_equal(:guest, player.auth_type) assert_equal(player, flox.current_player) assert_not_nil(player.id) end def test_load_entity type = "type" id = "id" path = "entities/#{type}/#{id}" data = { :name => "Jean-Luc" } flox.service.expects(:get).with(path).once.returns(data) entity = flox.load_entity(type, id) assert_kind_of(Flox::Entity, entity) assert_equal(id, entity.id) assert_equal(type, entity.type) assert_equal(path, entity.path) assert_equal(data[:name], entity[:name]) end def test_load_player id = "id" data = { :name => "Jean-Luc" } flox.service.expects(:get).once.returns(data) player = flox.load_player(id) assert_kind_of(Flox::Player, player) assert_equal(data[:name], player[:name]) assert_equal(id, player.id) assert_equal('.player', player.type) end def test_save_entity data = { :name => "Jean-Luc" } entity = Flox::Entity.new("type", "id", data) path = "entities/#{entity.type}/#{entity.id}" result = { :createdAt => "2014-01-01T12:00:00.000Z", :updatedAt => "2014-02-01T12:00:00.000Z" } flox.service.expects(:put).with(path, entity).once.returns(result) flox.save_entity(entity) assert_equal(result[:createdAt], entity.created_at.to_xs_datetime) assert_equal(result[:updatedAt], entity.updated_at.to_xs_datetime) end def test_delete_entity entity = Flox::Entity.new("type", "id") path = "entities/#{entity.type}/#{entity.id}" flox.service.expects(:delete).with(path) flox.delete_entity(entity) end def test_find_logs log_ids = %w{ 0 1 2 } result = { :ids => log_ids, :cursor => nil } flox.service.expects(:get).times(4).returns(result).then.returns({}) logs = flox.find_logs('severity:warning', 50) assert_kind_of(Array, logs) assert_equal(log_ids.length, logs.length) logs.each { |log| assert_kind_of(Hash, log) } end def test_find_log_ids log_ids = %w{ 0 1 2 3 4 5 6 7 8 9 } log_ids_a = log_ids.slice 0, 5 log_ids_b = log_ids.slice 5, 5 result_a = { :ids => log_ids_a, :cursor => 'a' } result_b = { :ids => log_ids_b, :cursor => nil } # without limit flox.service.expects(:get).twice.returns(result_a, result_b) out_log_ids = flox.find_log_ids assert_equal(log_ids.length, out_log_ids.length) # with limit limit = 7 result_b[:ids] = %w{ 5 6 } flox.service.expects(:get).twice.returns(result_a, result_b) out_log_ids = flox.find_log_ids(nil, limit) assert_equal(limit, out_log_ids.length) end end
true
c2c85cf31c0910a011a801065da8c0864f92c94f
Ruby
developwithpassion/fakes
/spec/specs/class_swaps_spec.rb
UTF-8
3,301
2.8125
3
[ "MIT" ]
permissive
require 'spec_helper' module SomeModule module NestedModule class AClassInANestedModule end end class ClassInAModule end end module Fakes class SomeClass def self.calculate 42 end end describe ClassSwaps do class MySwap attr_accessor :inititated, :was_reset def initiate @inititated = true end def reset @was_reset = true end end context 'when a class swap is registered ' do context 'and it does not already exist' do let(:the_sym) { MyClass.to_s.to_sym } let(:replacement) { Object.new } let(:the_swap) { MySwap.new } let(:sut) { ClassSwaps.instance } before(:each) do ClassSwap.stub(:new).with(MyClass, replacement).and_return(the_swap) end after(:each) do sut.swaps.clear end before(:each) do sut.add_fake_for(MyClass, replacement) end it 'should add a new class swap to the set of class swaps' do expect(ClassSwaps.instance.swaps[the_sym]).to eql(the_swap) end it 'should initiate the swap' do expect(the_swap.inititated).to be true end end context 'and it already exist' do let(:the_sym) { MyClass.to_s.to_sym } let(:sut) { ClassSwaps.instance } before(:each) do sut.swaps[the_sym] = 2 end after(:each) do sut.swaps.clear end before(:each) do @exception = catch_exception { sut.add_fake_for(MyClass, Object.new) } end it 'should throw an error indicating that the swap is already present' do expect(@exception.message).to contain(MyClass.to_s) end end end context 'when reset' do let(:first_swap) { MySwap.new } let(:second_swap) { MySwap.new } let(:sut) { ClassSwaps.instance } before(:each) do sut.swaps[:first] = first_swap sut.swaps[:second] = second_swap end before(:each) do sut.reset end it 'should reset each of the swaps' do expect(first_swap.was_reset).to be true expect(second_swap.was_reset).to be_truthy end it 'should clear the swaps' do expect(sut.swaps.count).to eql(0) end end context 'Integration Test' do let(:replacement) { Object.new } it 'should be able to swap class values' do ClassSwaps.instance.add_fake_for(Dir, replacement) expect(Dir).to eql(replacement) ClassSwaps.instance.reset expect(Dir).to_not eql(replacement) end it 'should be able to swap class values in another module' do ClassSwaps.instance.add_fake_for(SomeModule::ClassInAModule, replacement) expect(SomeModule::ClassInAModule).to eql(replacement) ClassSwaps.instance.reset expect(SomeModule::ClassInAModule).to_not eql(replacement) ClassSwaps.instance.add_fake_for(SomeModule::NestedModule::AClassInANestedModule, replacement) expect(SomeModule::NestedModule::AClassInANestedModule).to eql(replacement) ClassSwaps.instance.reset expect(SomeModule::NestedModule::AClassInANestedModule).to_not eql(replacement) end end end end
true
e5765c6624780a4bf24b5be03c5e0d1fbfe25606
Ruby
RavenB/playfulbent
/test/unit/gender_test.rb
UTF-8
1,781
2.734375
3
[]
no_license
# == Schema Information # # Table name: genders # # id :integer(4) not null, primary key # name :string(255) # require File.dirname(__FILE__) + '/../unit_test_helper' class UserTest < Test::Unit::TestCase def test_is_male @gender = Gender.new assert_equal false, @gender.is_male? @gender.name = 'mAle' assert_equal true, @gender.is_male? end def test_is_female @gender = Gender.new assert_equal false, @gender.is_female? @gender.name = 'femaLE' assert_equal true, @gender.is_female? end def test_third_person_passive_pronoun @gender = Gender.new assert_equal 'them', @gender.third_person_passive_pronoun @gender.name = 'male' assert_equal 'him', @gender.third_person_passive_pronoun @gender.name = 'female' assert_equal 'her', @gender.third_person_passive_pronoun end def test_third_person_active_pronoun @gender = Gender.new assert_equal 'they', @gender.third_person_active_pronoun @gender.name = 'male' assert_equal 'he', @gender.third_person_active_pronoun @gender.name = 'female' assert_equal 'she', @gender.third_person_active_pronoun end def test_third_person_possessive @gender = Gender.new assert_equal 'their', @gender.third_person_possessive @gender.name = 'male' assert_equal 'his', @gender.third_person_possessive @gender.name = 'female' assert_equal 'her', @gender.third_person_possessive end def test_third_person_self_pronoun @gender = Gender.new assert_equal 'themself', @gender.third_person_self_pronoun @gender.name = 'male' assert_equal 'himself', @gender.third_person_self_pronoun @gender.name = 'female' assert_equal 'herself', @gender.third_person_self_pronoun end end
true
cbab5e81c4c2f155b59784981d13946df6cb7c22
Ruby
MRSTkz/greping
/lib/str.rb
UTF-8
211
3.5625
4
[]
no_license
class String def colorize(color_code) "\e[#{color_code}m#{self}\e[0m" end def green colorize(32) end def yellow colorize(33) end def blue colorize(36) end end
true
021870729c394cbbb06209b362f580c87324c66e
Ruby
time4kids/time4kids-api
/spec/support/url_matcher.rb
UTF-8
416
2.703125
3
[]
no_license
# Passes if result is a valid url, returns error "expected result to be url" if not. # Matcher to see if a string is a URL or not. # RSpec::Matchers.define :be_url do |expected| # # The match method, returns true if valie, false if not. # match do |actual| # # Use the URI library to parse the string, returning false if this fails. # !!(actual =~ /\A#{URI::regexp(['http', 'https'])}\z/) # end # end
true
2079c4e710a3bc44d2e08a3431b871f22e9cd857
Ruby
Rasit1/Exercices-Ruby
/exo_14.rb
UTF-8
119
3.3125
3
[]
no_license
puts "Entrez un nombre" print "-->" nombre = gets.chomp i=0 while i <= nombre.to_i do puts nombre.to_i-i i +=1 end
true
6186a1c13be31c197b37757c0804a2ac1e3eefc9
Ruby
to93m/a_filter
/convo.rb
UTF-8
2,061
2.875
3
[]
no_license
#ruby convo.rb input_file_name 畳み込むもの #ruby convo.rb SpeechData.raw 16 impulse_response_file.raw mode output_file_name require './plot' base_wave ||= [] impulse_response ||= [] x_axis ||= [] def read_wave(file_name, mode) wave ||= [] File.open("./data/"+ file_name) {|file| if mode == "s" binary = file.read wave = binary.unpack('s*') elsif mode == "d" #64bitの収録音源は8バイトで読み込まないといけない binary = file.read wave = binary.unpack('d*') #d* は符号付きの浮動小数点を指定 elsif mode == "text" file.each{|line| wave << line.chomp.to_f } end } return wave end base_wave = read_wave(ARGV[0], ARGV[1]) impulse_response = read_wave(ARGV[2], ARGV[3]) impulse_response.length.times{|n| base_wave << 0 } #max = impulse_response.max #impulse_response.collect!{|n| n /= max} #最大を1にする #max = base_wave.max #base_wave.collect!{|n| n /= max} #最大を1にする out_wave ||= [] base_wave.length.times{|i| out_wave[i] = 0 impulse_response.length.times{|j| if i - j >= 0 out_wave[i] += base_wave[i - j] * impulse_response[j] end } } x_axis = (0..base_wave.length).to_a x_axis.collect!{|n| n /= 16000.0} x_impulse = (0..7200).to_a x_impulse.collect!{|n| n /= 16000.0} x_base = (0..base_wave.length).to_a x_base.collect!{|n| n /= 16000.0} File.open("./data/"+ ARGV[4] +".raw", 'w') {|file| #rawファイルで書き出し file.write(out_wave.pack("s*")) } =begin File.open("./data/"+ ARGV[4] +".txt", 'w') {|file| #textファイルで書き出し out_wave.length.times{|i| file.write "#{out_wave[i]}\n" } } =end plot(x_base, out_wave) #o_plot(x_base, base_wave, "time[s]", "Amplitude", "SpeechData_graph") #o_plot(x_impulse, impulse_response, "time[s]", "Amplitude", "ImpulseResponse_graph") #o_plot(x_axis, out_wave, "time[s]", "Amplitude", "Convolution_out") #impulse_response.collect!{|n| n *= 30000} #File.open("./LMS/impulse.raw", 'w') {|file| # file.write(impulse_response.pack("s*")) #}
true
2db16f4b1f83541d362e8a6d432aa58a22c61f66
Ruby
nerab/pwl
/lib/pwl/commands/base.rb
UTF-8
4,052
2.59375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module Pwl module Commands EXIT_CODES = { :success => Message.new('Success.'), :aborted => Message.new('Aborted by user.', 1), :passwords_dont_match => ErrorMessage.new('Passwords do not match.', 2), :no_value_found => Message.new('No value found for <%= name %>.', 3, :name => 'NAME'), :file_exists => ErrorMessage.new('There already exists a locker at <%= file %>. Use --force to overwrite it or --file to specify a different locker.', 4, :file => 'FILE'), :file_not_found => ErrorMessage.new('Locker file <%= file %> could not be found.', 5, :file => 'FILE'), :name_blank => ErrorMessage.new('Name may not be blank.', 6), :value_blank => ErrorMessage.new('Value may not be blank.', 7), :list_empty => Message.new('List is empty.', 8), :list_empty_filter => Message.new('No names found that match filter <%= filter %>.', 9, :filter => 'FILTER'), :validation_new_failed => ErrorMessage.new('<%= message %>.', 10, :message => 'Validation of new master password failed'), :unknown_format => ErrorMessage.new('<%= format %> is not a known format.', 11, :format => 'FORMAT'), :inaccessible_field => ErrorMessage.new("Field '<%= field %>' is not accessible.", 12, :field => 'FIELD'), :is_dir => ErrorMessage.new('File expected, but <%= file %> is a directory. Specify a regular file for the locker.', 13, :file => 'FILE'), } class InacessibleFieldError < StandardError def initialize(field) super("The field #{field} is not accessible") end end class Base class << self def exit_codes_help EXIT_CODES.values.sort{|l,r| l.exit_code <=> r.exit_code}.collect{|m| " #{m.exit_code.to_s.rjust(EXIT_CODES.size.to_s.size)}: #{m.to_s}"}.join("\n") end def default_locker_file File.expand_path("~/.#{program(:name)}.pstore") end end protected def locker_file(options, init = false) result = options.file || self.class.default_locker_file if File.exists?(result) || init result else exit_with(:file_not_found, options.verbose, :file => result) end end def open_locker(options, master_password = nil) # TODO Use DRb at options.url if not nil locker_file = locker_file(options) msg "Attempting to open locker at #{locker_file}" if options.verbose Locker.open(locker_file, master_password || get_password("Enter the master password for #{program(:name)}:", options.gui)) end def new_locker(options, master_password) # Remote init not allowed. Or maybe it should be? Locker.new(locker_file(options, true), master_password, {:force => options.force}) end def msg(str) STDERR.puts("#{program(:name)}: #{str}") end def exit_with(error_code, verbose, msg_args = {}) msg = EXIT_CODES[error_code] raise "No message defined for error #{error_code}" if !msg if msg.error? || verbose # always print errors; messages only when verbose msg msg.to_s(msg_args) end exit(msg.exit_code) end def get_password(prompt, gui = false) (gui ? Pwl::Dialog::Password.new(program(:name), prompt) : Pwl::Dialog::ConsolePasswordDialog.new(prompt)).get_input end def get_text(prompt, gui = false) (gui ? Pwl::Dialog::Text.new(program(:name), prompt) : Pwl::Dialog::ConsoleTextDialog.new(prompt)).get_input end def validate!(pwd) Pwl::Locker.password_policy.validate!(pwd) end # # Returns the value of the passed attribute name if it is allowed to be retrieved from a locker entry # def attr!(entry, field) raise InacessibleFieldError.new(field) unless entry.instance_variable_defined?("@#{field}".to_sym) entry.send(field) end end end end
true
24580598436a15faeb1467f86b7aae28b11920d3
Ruby
TravisExline/collections_practice-online-web-ft-051319
/collections_practice.rb
UTF-8
845
3.90625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(integer_array) integer_array.sort do |a, b| if a == b 0 elsif a < b -1 elsif a > b 1 end end end def sort_array_desc(array) array.sort do |a, b| if a == b 0 elsif a < b 1 elsif a > b -1 end end end def sort_array_char_count(array) array.sort do |a, b| a.length <=> b.length end end def swap_elements(array) array[1], array[2] = array[2], array[1] array end def reverse_array(array) array.reverse end def kesha_maker(array) new_array = [] i = 0 array.each do |name| name[2] = "$" end end def find_a(array) array.select do |name| name[0] == "a" end end def sum_array(array) array.sum end def add_s(array) array.collect do |element| if array[1] != element element << "s" end end array end
true
529b4abac35cf286aa6959355df55bfef00a3021
Ruby
pyrmont/taipo
/lib/taipo/type_element/constraints.rb
UTF-8
843
2.71875
3
[ "Unlicense", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
module Taipo class TypeElement # A set of {Taipo::TypeElement::Constraint} objects # # @since 1.4.0 # @api private class Constraints < Array # Initialize a new set of {Taipo::TypeElement::Constraint} # # @param constraints [Array<Taipo::TypeElement::Constraint>] the # constraints # # @since 1.4.0 # @api private def initialize(constraints = nil) constraints&.each { |c| self.push c } end # Return the String representation of this object # # @return [String] the representation as a String # # @since 1.4.0 # @api private def to_s inner = self.reduce('') do |memo,c| (memo == '') ? c.to_s : memo + ',' + c.to_s end '(' + inner + ')' end end end end
true
b1747d0e755285b37806e75574e62f6630c39114
Ruby
calo81/ruby-recommender
/spec/recommendations/similarity/neighborhood/nearest_n_user_neighborhood_spec.rb
UTF-8
1,020
2.65625
3
[]
no_license
require_relative '../../../../spec/spec_helper' require_relative '../../../../lib/recommendations' describe Recommendations::Similarity::Neighborhood::NearestNUserNeighborhood do it "should return the top N users similar to passed user" do data_model = mock(:data_model) similarity = mock(:similarity) user = 1 neighborhood = Recommendations::Similarity::Neighborhood::NearestNUserNeighborhood.new(data_model,similarity,2,0.75) data_model.should_receive(:users).and_return([1,2,3,4,5]) similarity.should_receive(:user_similarity).with(1,2).and_return(0.68) similarity.should_receive(:user_similarity).with(1,3).and_return(0.78) similarity.should_receive(:user_similarity).with(1,4).and_return(0.77) similarity.should_receive(:user_similarity).with(1,5).and_return(0.79) neighbors = neighborhood.user_neighborhood(user) neighbors.size.should == 2 neighbors[0].should == 5 neighbors[1].should == 3 end end
true
29256f6d8a1f38fa1b91d2e6cee30a5ad6049aaf
Ruby
GBSEcom/Ruby
/lib/openapi_client/models/additional_response_data.rb
UTF-8
12,956
2.609375
3
[]
no_license
=begin #Payment Gateway API Specification. #The documentation here is designed to provide all of the technical guidance required to consume and integrate with our APIs for payment processing. To learn more about our APIs please visit https://docs.firstdata.com/org/gateway. The version of the OpenAPI document: 21.5.0.20211029.001 Generated by: https://openapi-generator.tech OpenAPI Generator version: 4.1.1 =end require 'date' module OpenapiClient # Additional Response Data. class AdditionalResponseData # Issuing Bank Name. attr_accessor :issuing_bank_name # Country of Issuance. attr_accessor :country_of_issuance # Card Product ID. attr_accessor :card_product_id # Detailed Product ID. attr_accessor :detailed_product_id # Association Response Code. attr_accessor :association_response_code_adtl # Card Brand. attr_accessor :card_brand # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'issuing_bank_name' => :'issuingBankName', :'country_of_issuance' => :'countryOfIssuance', :'card_product_id' => :'cardProductID', :'detailed_product_id' => :'detailedProductID', :'association_response_code_adtl' => :'associationResponseCodeAdtl', :'card_brand' => :'cardBrand' } end # Attribute type mapping. def self.openapi_types { :'issuing_bank_name' => :'String', :'country_of_issuance' => :'String', :'card_product_id' => :'String', :'detailed_product_id' => :'String', :'association_response_code_adtl' => :'String', :'card_brand' => :'String' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::AdditionalResponseData` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::AdditionalResponseData`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'issuing_bank_name') self.issuing_bank_name = attributes[:'issuing_bank_name'] end if attributes.key?(:'country_of_issuance') self.country_of_issuance = attributes[:'country_of_issuance'] end if attributes.key?(:'card_product_id') self.card_product_id = attributes[:'card_product_id'] end if attributes.key?(:'detailed_product_id') self.detailed_product_id = attributes[:'detailed_product_id'] end if attributes.key?(:'association_response_code_adtl') self.association_response_code_adtl = attributes[:'association_response_code_adtl'] end if attributes.key?(:'card_brand') self.card_brand = attributes[:'card_brand'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if !@issuing_bank_name.nil? && @issuing_bank_name.to_s.length > 18 invalid_properties.push('invalid value for "issuing_bank_name", the character length must be smaller than or equal to 18.') end if !@country_of_issuance.nil? && @country_of_issuance.to_s.length > 3 invalid_properties.push('invalid value for "country_of_issuance", the character length must be smaller than or equal to 3.') end if !@card_product_id.nil? && @card_product_id.to_s.length > 1 invalid_properties.push('invalid value for "card_product_id", the character length must be smaller than or equal to 1.') end if !@detailed_product_id.nil? && @detailed_product_id.to_s.length > 3 invalid_properties.push('invalid value for "detailed_product_id", the character length must be smaller than or equal to 3.') end if !@association_response_code_adtl.nil? && @association_response_code_adtl.to_s.length > 3 invalid_properties.push('invalid value for "association_response_code_adtl", the character length must be smaller than or equal to 3.') end if !@card_brand.nil? && @card_brand.to_s.length > 1 invalid_properties.push('invalid value for "card_brand", the character length must be smaller than or equal to 1.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if !@issuing_bank_name.nil? && @issuing_bank_name.to_s.length > 18 return false if !@country_of_issuance.nil? && @country_of_issuance.to_s.length > 3 return false if !@card_product_id.nil? && @card_product_id.to_s.length > 1 return false if !@detailed_product_id.nil? && @detailed_product_id.to_s.length > 3 return false if !@association_response_code_adtl.nil? && @association_response_code_adtl.to_s.length > 3 return false if !@card_brand.nil? && @card_brand.to_s.length > 1 true end # Custom attribute writer method with validation # @param [Object] issuing_bank_name Value to be assigned def issuing_bank_name=(issuing_bank_name) if !issuing_bank_name.nil? && issuing_bank_name.to_s.length > 18 fail ArgumentError, 'invalid value for "issuing_bank_name", the character length must be smaller than or equal to 18.' end @issuing_bank_name = issuing_bank_name end # Custom attribute writer method with validation # @param [Object] country_of_issuance Value to be assigned def country_of_issuance=(country_of_issuance) if !country_of_issuance.nil? && country_of_issuance.to_s.length > 3 fail ArgumentError, 'invalid value for "country_of_issuance", the character length must be smaller than or equal to 3.' end @country_of_issuance = country_of_issuance end # Custom attribute writer method with validation # @param [Object] card_product_id Value to be assigned def card_product_id=(card_product_id) if !card_product_id.nil? && card_product_id.to_s.length > 1 fail ArgumentError, 'invalid value for "card_product_id", the character length must be smaller than or equal to 1.' end @card_product_id = card_product_id end # Custom attribute writer method with validation # @param [Object] detailed_product_id Value to be assigned def detailed_product_id=(detailed_product_id) if !detailed_product_id.nil? && detailed_product_id.to_s.length > 3 fail ArgumentError, 'invalid value for "detailed_product_id", the character length must be smaller than or equal to 3.' end @detailed_product_id = detailed_product_id end # Custom attribute writer method with validation # @param [Object] association_response_code_adtl Value to be assigned def association_response_code_adtl=(association_response_code_adtl) if !association_response_code_adtl.nil? && association_response_code_adtl.to_s.length > 3 fail ArgumentError, 'invalid value for "association_response_code_adtl", the character length must be smaller than or equal to 3.' end @association_response_code_adtl = association_response_code_adtl end # Custom attribute writer method with validation # @param [Object] card_brand Value to be assigned def card_brand=(card_brand) if !card_brand.nil? && card_brand.to_s.length > 1 fail ArgumentError, 'invalid value for "card_brand", the character length must be smaller than or equal to 1.' end @card_brand = card_brand end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && issuing_bank_name == o.issuing_bank_name && country_of_issuance == o.country_of_issuance && card_product_id == o.card_product_id && detailed_product_id == o.detailed_product_id && association_response_code_adtl == o.association_response_code_adtl && card_brand == o.card_brand end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [issuing_bank_name, country_of_issuance, card_product_id, detailed_product_id, association_response_code_adtl, card_brand].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes, attribute_map = self.class.attribute_map, openapi_types = self.class.openapi_types) return nil unless attributes.is_a?(Hash) openapi_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model klass = OpenapiClient.const_get(type) if klass.respond_to?(:openapi_discriminator_name) klass = OpenapiClient.const_get(value[klass.attribute_map[klass.openapi_discriminator_name]]) end klass.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash(attribute_map = self.class.attribute_map, openapi_nullable = Set.new([])) hash = {} attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
true
1d6d4c1e7a91bb5b60fffefb6b97036a4c2f3915
Ruby
eudai/copycat
/copycat.rb
UTF-8
4,668
3.546875
4
[]
no_license
require 'rumouse' class CopyCat def initialize puts 'welcome to copycat.' puts 'copycat will record your mouse locations, and play them back.' help terminal puts 'goodbye.' end def record events = [] input "press 'enter' to begin." loop do start_time = Time.now command = input "press 'enter' to save the mouse location, or type 'done'." break if command =~ /done/ end_time = Time.now events << { event: 'wait', t: end_time - start_time } events << { event: 'click', x: mouse.position[:x], y: mouse.position[:y] } puts "#{(end_time - start_time).to_s} second wait recorded." puts "click at #{mouse.position[:x]}, #{mouse.position[:y]} recorded." end puts 'recording complete.' summarize events @recording = events end def play if @recording puts 'staring playback...' @recording.each do |e| wait e[:t] if e[:event] == 'wait' click e[:x], e[:y] if e[:event] == 'click' end puts 'playback complete.' else puts 'no loaded recordings to play.' end end def repeat if @recording count = input('how many times would you like to repeat your recording?').to_i delay = input('how many seconds would you like to wait between playbacks?').to_i puts "recording will be played back #{count} times with a #{delay} second delay." count.times do |index| play wait delay unless index == count - 1 end puts 'done repeating recording.' else puts 'no loaded recordings to repeat.' end end def save if @recording filename = input 'name your recording.' unless filename File.open("recordings/#{filename}.txt", 'w') do |f| f.puts @recording.to_s end puts "recording saved as #{filename}." else puts 'no loaded recordings to save.' end end def load filename = input "what recording would you like to load?" unless filename if File.exists? "recordings/#{filename}.txt" recording = eval File.open("recordings/#{filename}.txt", 'r').read puts 'recording loaded.' summarize recording @recording = recording else puts "failed to load: #{filename}" show_recordings end end def delete filename = input 'what recording would you like to delete?' if File.exists? "recordings/#{filename}.txt" if input("are you sure you want to delete #{filename}? (y/n)") == 'y' File.delete "recordings/#{filename}.txt" puts "#{filename} deleted." end else puts "failed to delete: #{filename}" show_recordings end end def summarize(events) puts 'this recording will do the following:' events.each do |e| puts " wait for #{e[:t]} seconds" if e[:event] == 'wait' puts " click at #{e[:x]}, #{e[:y]}" if e[:event] == 'click' end end def show_recordings puts "here is a list of available recordings:" Dir.glob('recordings/*').each do |f| puts ' ' + f.gsub('recordings/', '').gsub('.txt','') end end def help puts 'here are some things you can do:' puts ' record' puts ' play' puts ' repeat' puts ' save' puts ' load' puts ' delete' puts ' help' puts ' quit' end def terminal loop do allowed_commands = ['record', 'play', 'repeat', 'save', 'load', 'delete', 'quit', 'help'] command = input('waiting on your command...').downcase if allowed_commands.include? command return if command == 'quit' eval command else puts command + ' is not a recognized command.' help end end end def input(message) puts message gets.chomp end def mouse @mouse ||= RuMouse.new @mouse end def click(x,y) puts " clicking at #{x.to_s}, #{y.to_s}..." mouse.click x, y end def wait(seconds) puts " waiting #{seconds.to_s} seconds..." sleep seconds end end
true
987a87cca7bf15b32beb9268a221d4152670aafc
Ruby
edem228/backend
/backend/octoly_email_finder.rb
UTF-8
1,148
3.046875
3
[]
no_license
require "json" class Octoly_email_finder def initialize(file) @file = file @number_for_email = number_for_email end def read_file File.read(@file) end def parsed_file JSON.parse(read_file) end def counts_videos_by_id most_viewed_topics = [] parsed_file.each do |video| video["topic_ids"].each do |id| if most_viewed_topics.any? {|topic| topic.include?(id)} index = most_viewed_topics.index {|topic| topic[id]} most_viewed_topics[index][id] += video["views_count"] most_viewed_topics[index]["like"] += video["likes_count"] most_viewed_topics[index]["dislike"] += video["dislikes_count"] else most_viewed_topics << {id => video["views_count"], "like" => video["likes_count"], "dislike" => video["dislikes_count"]} end end end most_viewed_topics end def max_by_value counts_videos_by_id.max_by{|key,value| value} end def number_for_email max_by_value.values.inject(:*) end end def octoly_email Octoly_email_finder.new("videos.json").number_for_email.to_s + "@octoly.com" end puts octoly_email
true
791ad4ab9d6e196c321197d6ab27127f95797559
Ruby
ksummerill/ttt-game-status-online-web-sp-000
/lib/game_status.rb
UTF-8
1,427
4.09375
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require "pry" # Helper Method def position_taken?(board, index) !(board[index].nil? || board[index] == " ") end # Define your WIN_COMBINATIONS constant WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] def won?(board) winner = [] empty_board = board.all? { |empty| empty == " " || empty == nil} WIN_COMBINATIONS.each do |win_combo| # binding.pry if win_combo.all? { |value| board[value] == "X"} || win_combo.all? { |value| board[value] == "O"} winner = win_combo return winner end end return false end # check to see if the board is full def full?(board) board.all? { |full| full == "X" || full == "O"} end # returns true if the board has not been won but is full, # false if the board is not won and the board is not full, # and false if the board is won def draw?(board) # binding.pry full?(board) && !won?(board) # if !won?(board) && full?(board) # return true # elsif !won?(board) && !full?(board) # return false # else won?(board) # return false # end end # returns true if the board has been won, is a draw, or is full. def over?(board) if won?(board) || draw?(board) || full?(board) return true else return false end end # return the token, "X" or "O" that has won the game given a winning board def winner(board) if won?(board) return board[won?(board)[0]] end end
true
1976032ad459c5640c6cb645db3082d3b5de5cce
Ruby
zkbell91/zbell-linkedlist1
/linked_list_1.rb
UTF-8
1,256
4
4
[]
no_license
class LinkedListNode attr_accessor :value, :next_node def initialize(value, next_node=nil) @value = value @next_node = next_node end end class Stack attr_reader :data def initialize @data = nil end def push(value) @data = LinkedListNode.new(value, @data) end def pop if @data first_out = @data.value @data = @data.next_node return first_out else nil end end def empty? @data.nil? end end node1 = LinkedListNode.new(37) node2 = LinkedListNode.new(99, node1) node3 = LinkedListNode.new(12, node2) def print_values(list_node) if list_node puts "#{list_node.value} --> " print_values(list_node.next_node) else print "nil\n" return end end def reverse_list(list) temp_stack = Stack.new while list temp_stack.push(list.value) list = list.next_node end reversed_node = head = LinkedListNode.new(temp_stack.pop) return nil if reversed_node.nil? until temp_stack.empty? current_node = LinkedListNode.new(temp_stack.pop) reversed_node.next_node = current_node reversed_node = current_node end head end print_values(node3) puts "-------" revlist = reverse_list(node3) print_values(revlist)
true
4490e31fce45ae7ac84c36f0dacd6676e29e03e8
Ruby
pmatsinopoulos/hackerrank
/spec/find_median_spec.rb
UTF-8
392
2.84375
3
[]
no_license
require 'spec_helper' require_relative '../lib/find_median' describe 'Find Median' do [ [[0, 1, 2, 4, 6, 5, 3], 3], [[], nil], [[1], 1], [[1, 2], 1], [[1, 5, 8], 5], [[8, 5, 1], 5], [[1, 1, 1], 1] ].each do |input, expected| it "finds the median for array #{input} to be #{expected}" do expect(find_median(input)).to eq(expected) end end end
true
cec071af4ed2fab70155e78f4ac08be760fee8e9
Ruby
jtlai0921/PG20249_example
/PG20249_sample/Ruby268-SampleProgram-UTF8/Ch2/sample033-03.rb
UTF-8
116
2.859375
3
[]
no_license
str = "3.14159265357919" char_stat(str).each{|char, count| puts "#{char.inspect}: #{count * 100 / str.length}%" }
true
83f21a5f367822857f66267338e80c7715dc7451
Ruby
kazuhirodk/mutation-test-introduction
/lib/tax_calculator.rb
UTF-8
130
2.84375
3
[ "MIT" ]
permissive
class TaxCalculator def calculate(product) if product.price > 500 return product.price * 0.1 end 0 end end
true
7711162b704d0371cbb6090f8244c0fbc2ff7cd5
Ruby
Ortuna/bana_new
/lib/bana/builder.rb
UTF-8
828
2.53125
3
[]
no_license
module Bana class Builder attr_reader :path, :manifest_file def initialize(options = {}) configure_builder default_options.merge(options) load_manifest end def create_pdf(output_path) Bana::Converters::Md.new(manifest_files, output_path) end private def load_manifest file_path = File.expand_path(path + '/' + manifest_file) @manifest = Bana::Manifest.new(file_path) end def default_options { manifest_file: 'manifest.yml' } end def manifest_files @manifest.files end ## # sets key/value pairs for each option # on the instance def configure_builder(options) options.each do |key, value| self.instance_variable_set "@#{key}", value if self.respond_to? key end end end #class end #module
true
8e9069e3771ac2e3582a717c2f9dbfb445cabba7
Ruby
RJ-Ponder/RB101
/exercises/easy_5/05clean.rb
UTF-8
1,590
4.46875
4
[]
no_license
# Problem # Given a string that consists of some words (all lowercased) and an # assortment of non-alphabetic characters, write a method that returns that # string with all of the non-alphabetic characters replaced by spaces. If one or # more non-alphabetic characters occur in a row, you should only have one space # in the result (the result should never have consecutive spaces). # Examples / Test Cases # cleanup("---what's my +*& line?") == ' what s my line ' # Data Structures # Input: string, with non-alphanumeric characters # Output: modified string (mutated) # Algorithm # Can identify alphanumeric characters (a..z) (A..Z) (0..9) def cleanup(string) string.gsub!(/[^a-z]/i, ' ').squeeze(' ') # incorrectly included numbers in the regexp at first, fixed and now i shows case insensitve end # I also thought the problem wanted the same string, modified p cleanup("---what's my +*& line?") == ' what s my line ' # old attempt before I found squeeze from docs: # counter = 0 # loop do # break if string[counter] == nil # if string[counter] == ' ' && string[counter + 1] == ' ' # string[counter] = '' # end # counter += 1 # end # string # TRY WRITING THIS WITHOUT REGEXP (don't look at book solution again yet) def cleanup2(string) letters = ('a'..'z').to_a + ('A'..'Z').to_a cleaned = [] string.each_char do |char| if letters.include?(char) cleaned << char else cleaned << ' ' unless cleaned.last == ' ' end end cleaned.join end p cleanup2("---what's my +*& line?") == ' what s my line '
true
ac57e2e60c2ac573e2adeb213769bac621ed9420
Ruby
MAshrafM/The_Odin_Project
/08_Serialization/Hangman/example/example_game.rb
UTF-8
148
2.9375
3
[ "MIT" ]
permissive
require_relative '../lib/Hangman.rb' puts "Your name: " name = gets.chomp player = Hangman::Player.new({name: name}) Hangman::Game.new(player).play
true
6a839127e3f4852feab621d75941e3ac0b5a547f
Ruby
Ootm/FIT4AF
/Ruby/Code/Block.rb
UTF-8
254
3.4375
3
[]
no_license
# Block 3.times do |number| puts number.to_s end 3.times { |n| puts n.to_s } numbers = (1..10).to_a var = numbers.select do |n| n.even? end evens, odds = numbers.partition do |n| n.even? end puts evens puts "------------------------" puts odds
true
afe2a8a98ee40e0ca4f442fff5f0ecda5a61f3c2
Ruby
wasamasa/aoc
/2015/18.rb
UTF-8
5,432
3.90625
4
[ "Unlicense" ]
permissive
require_relative 'util' # --- Day 18: Like a GIF For Your Yard --- # After the million lights incident, the fire code has gotten # stricter: now, at most ten thousand lights are allowed. You arrange # them in a 100x100 grid. # Never one to let you down, Santa again mails you instructions on the # ideal lighting configuration. With so few lights, he says, you'll # have to resort to animation. # Start by setting your lights to the included initial configuration # (your puzzle input). A # means "on", and a . means "off". # Then, animate your grid in steps, where each step decides the next # configuration based on the current one. Each light's next state # (either on or off) depends on its current state and the current # states of the eight lights adjacent to it (including # diagonals). Lights on the edge of the grid might have fewer than # eight neighbors; the missing ones always count as "off". # For example, in a simplified 6x6 grid, the light marked A has the # neighbors numbered 1 through 8, and the light marked B, which is on # an edge, only has the neighbors marked 1 through 5: # 1B5... # 234... # ...... # ..123. # ..8A4. # ..765. # The state a light should have next is based on its current state (on # or off) plus the number of neighbors that are on: # - A light which is on stays on when 2 or 3 neighbors are on, and # turns off otherwise. # - A light which is off turns on if exactly 3 neighbors are on, and # stays off otherwise. # All of the lights update simultaneously; they all consider the same # current state before moving to the next. # Here's a few steps from an example configuration of another 6x6 # grid: # Initial state: # .#.#.# # ...##. # #....# # ..#... # #.#..# # ####.. # # After 1 step: # ..##.. # ..##.# # ...##. # ...... # #..... # #.##.. # # After 2 steps: # ..###. # ...... # ..###. # ...... # .#.... # .#.... # # After 3 steps: # ...#.. # ...... # ...#.. # ..##.. # ...... # ...... # # After 4 steps: # ...... # ...... # ..##.. # ..##.. # ...... # ...... # After 4 steps, this example has four lights on. # In your grid of 100x100 lights, given your initial configuration, # how many lights are on after 100 steps? input = File.open('18.txt') { |f| f.readlines.map { |l| l.chomp.chars } } test_input = ".#.#.#\n...##.\n#....#\n..#...\n#.#..#\n####..".split("\n") .map(&:chars) class Grid def initialize(input) @grid = input @size = input[0].length end def at(x, y) return nil if x < 0 || y < 0 row = @grid[y] return nil unless row row[x] end def neighbors(x, y) count = 0 offsets = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]] offsets.each do |xo, yo| count += 1 if at(x + xo, y + yo) == '#' end count end def evolve result = Array.new(@size) { Array.new(@size) } (0...@size).each do |y| (0...@size).each do |x| is_on = at(x, y) == '#' neighbors = neighbors(x, y) if is_on result[y][x] = [2, 3].include?(neighbors) ? '#' : '.' else result[y][x] = (neighbors == 3 ? '#' : '.') end end end @grid = result end def show @grid.each do |row| puts row.join end puts end def count sum = 0 @grid.each do |row| sum += row.count('#') end sum end end def easy(input, steps) grid = Grid.new(input) steps.times { grid.evolve } grid.count end assert(easy(test_input, 4) == 4) puts "easy(input, 100): #{easy(input, 100)}" # --- Part Two --- # You flip the instructions over; Santa goes on to point out that this # is all just an implementation of Conway's Game of Life. At least, it # was, until you notice that something's wrong with the grid of lights # you bought: four lights, one in each corner, are stuck on and can't # be turned off. The example above will actually run like this: # Initial state: # ##.#.# # ...##. # #....# # ..#... # #.#..# # ####.# # # After 1 step: # #.##.# # ####.# # ...##. # ...... # #...#. # #.#### # # After 2 steps: # #..#.# # #....# # .#.##. # ...##. # .#..## # ##.### # # After 3 steps: # #...## # ####.# # ..##.# # ...... # ##.... # ####.# # # After 4 steps: # #.#### # #....# # ...#.. # .##... # #..... # #.#..# # # After 5 steps: # ##.### # .##..# # .##... # .##... # #.#... # ##...# # After 5 steps, this example now has 17 lights on. # In your grid of 100x100 lights, given your initial configuration, # but with the four corners always in the on state, how many lights # are on after 100 steps? class StuckGrid < Grid def simulate_stuck_lights @grid[0][0] = '#' @grid[@size - 1][0] = '#' @grid[0][@size - 1] = '#' @grid[@size - 1][@size - 1] = '#' end def initialize(input) super simulate_stuck_lights end def evolve super simulate_stuck_lights end end def hard(input, steps) grid = StuckGrid.new(input) steps.times { grid.evolve } grid.count end assert(hard(test_input, 5) == 17) puts "hard(input, 100): #{hard(input, 100)}"
true
e218825de919f0acf6ed158026f98c9c89959168
Ruby
hoshito/AtCoder
/M-SOLUTIONS プロコンオープン/main_c.rb
UTF-8
202
2.953125
3
[]
no_license
q=gets.chomp.to_i arr = [] q.times do |i| arr << gets.chomp.split(" ").map(&:to_i) end arr.each do |(x, d, n)| a = 1 n.times do |i| a *= (x + i * d) % 1000003 end puts a % 1000003 end
true
37a6296eb50dfa8889a6b23cb8abb3a95e97f19f
Ruby
jonatanklosko/wca_statistics
/core/statistic.rb
UTF-8
952
2.78125
3
[ "MIT" ]
permissive
require "time" require_relative "database" class Statistic attr_reader :title def query raise "Must implement #query" end def query_results Database.client.query(query) end def transform(query_results) query_results.each(as: :array) end def data @data ||= transform(query_results) end def top timestamp = Time.parse(Database.metadata["export_timestamp"]) markdown = "## #{@title}\n\n" markdown += "*Note: #{@note}*\n" if @note markdown + timestamp.strftime("*Updated on %e %B %Y*\n\n") end def markdown top + markdown_table(@table_header, data) end def markdown_table(header, data) table = "| #{header.keys.join(' | ')} |\n" alignments = { left: ":---", center: ":--:", right: "---:" } table += "| #{header.values.map { |alignment| alignments[alignment] }.join(' | ')} |\n" data.each do |row| table += "| #{row.join(' | ')} |\n" end table end end
true
a57d74347eb08f85902e350a93b8c92f308d348d
Ruby
andycamp/orasaurus
/lib/orasaurus/cli.rb
UTF-8
2,783
2.78125
3
[]
no_license
require 'highline' require 'thor' require 'orasaurus/version' require 'orasaurus/application' module Orasaurus class CLI < Thor include Thor::Actions map "-v" => :version map "-h" => :help map "-g" => :generate desc "generate [SCRIPT_TYPE]", "Generate scripts. SCRIPT_TYPE is optional. Valid values are build_scripts, teardown_scripts and all." method_option :base_dir, :type => :string, :default => ".", :desc => "Base Directory for your code. Defaults to your current location.", :optional => true method_option :sort_method, :type => :string, :default => :none, :desc => "The method used for ordering the scripts. The only available option other than the default is SQL, which will order the scripts by dependency in the database (assuming the file name is a database object name.", :optional => true method_option :db_name, :type => :string, :desc => "Only needed if order_method is sql.", :optional => true method_option :db_username, :type => :string, :desc => "Only needed if order_method is sql.", :optional => true method_option :db_password, :type => :string, :desc => "Only needed if order_method is sql.", :optional => true def generate(script_type=:all) puts "generate " + script_type.to_s + " #{options.to_s}" a = Orasaurus::Application.new("cli",options.base_dir) if options.sort_method.upcase == "SQL" then puts "connecting for sql sorting." db_connect_options = process_db_connect_options(options.db_username, options.db_password, options.db_name) a.connect(db_connect_options[:db_username], db_connect_options[:db_password],db_connect_options[:db_name]) sort_options = { :method => :SQL, :db_connection => a.connection } else sort_options = {} end if [:build_scripts,:all].include? script_type.to_sym then puts "generating build scrtipts" a.generate(:build_scripts, sort_options) end if [:teardown_scripts,:all].include? script_type.to_sym then puts "generating teardown scripts" a.generate(:teardown_scripts, sort_options) end end desc "version", "Currently running version of Orasaurus." def version puts "Orasarus v"+Orasaurus::VERSION end def process_db_connect_options(db_username=nil, db_password=nil, db_name=nil) params = Hash.new params[:db_name] = db_name||ask("Database Name? ") { |q| q.echo = true } params[:db_username] = db_username||ask("Database User? ") { |q| q.echo = true } params[:db_password] = db_password||ask("Database Password? ") { |q| q.echo = "*" } return params end end end
true
0cfadabb38597fefb2fbee9201339e5cb9ef2122
Ruby
fishforward/read
/app/models/site.rb
UTF-8
2,647
2.75
3
[]
no_license
# encoding: utf-8 require 'rss/2.0' require 'nokogiri' require 'open-uri' class Site < ActiveRecord::Base attr_accessible :auto_read, :content_tag, :name, :name_tag, :read_type, :status, :url, :read_url, :last_pub_date, :author def self.read_site sites = Site.find_all_by_auto_read("Y") sites.each do |site| Site.read_one_site(site) end end def self.read_one_site(site) begin puts "=====" + site.name + "=====" + site.read_url feed = Site.read_rss(site.read_url) if feed == nil puts "rss is nil" return end last_pub_date = nil feed.items.reverse_each do |item| # 当前文章的发表时间 pubDate = item.pubDate.strftime("%Y%m%d%H%M%S") if site.last_pub_date && pubDate <= site.last_pub_date #puts "continue"; next end retMap = {} ## 根据读取类型 进行适配 if site.read_type == 'RSS_summary' retMap = Site.read_html(site, item.link) elsif site.read_type == 'RSS_content' end source = Source.create_wait_audit_source(site, item, retMap["content"]) puts source.title + "--" + source.post_url if source && (last_pub_date == nil || pubDate > last_pub_date) last_pub_date = pubDate end end rescue StandardError => e puts "===== EXCEPTION ====="+e.inspect end if last_pub_date && !last_pub_date.blank? site.last_pub_date = last_pub_date site.save end end def self.read_one_link(site_id, link) site = Site.find(site_id) if site == nil puts "site is nil" return end retMap = Site.read_html(site, link) #### ?????????????有问题 source = Source.create_wait_audit_source(site, item, retMap["content"]) end # 直接根据link读取html -> 根据定义的tag读取正文和作者名 def self.read_html(site, link) doc = Nokogiri::HTML(open(link)) # title name = doc.at_css(site.name_tag).text content = doc.at_css(site.content_tag).to_s return {"name" =>name, "content" => content } end def self.read_rss(rss_url) feed = RSS::Parser.parse(open(rss_url).read, false) return feed end ################################# # test ################################# def self.test_read_rss(rss_url) feed = Site.read_rss(rss_url) puts feed.inspect end def self.test_read_html(site_id, link) site = Site.find(site_id) retMap = read_html(site, link) puts retMap["name"] puts retMap["content"] end end
true
2e48026347d2c775e293d2ae86801334e4205be6
Ruby
joshvarney/tic-tac-toe
/ttt.rb
UTF-8
10,176
3.5625
4
[]
no_license
class Board def initialize(move) if move.class == Array @board = move[0..8] elsif @board = Array.new(9) counter = 0 @board.each do |cell| @board[counter] = counter counter += 1 end end @board_array = @board @board = game_board end def game_board grid = "" @board.each_with_index do |cell, index| grid << " #{@board[index]} " case index % 3 when 0, 1 then grid << "|" when 2 then grid << "\n-----------\n" unless index == 8 end end @board = grid end attr_reader :board_array attr_reader :board end class Winning def initialize(game_array) game_array = game_array @check_win = winning_combos(game_array) @check_win end def winning_combos(check_win) @check_win = check_win if @check_win[0..2].uniq.length == 1 @check_win[9] = "Winner Top Row" elsif @check_win[3..5].uniq.length == 1 @check_win[9] = "Winner Middle Row" elsif @check_win[6..8].uniq.length == 1 @check_win[9] = "Winner Bottom Row" elsif @check_win[0] == @check_win[3] && @check_win[0] == @check_win[6] @check_win[9] = "Winner Left Column" elsif @check_win[1] == @check_win[4] && @check_win[1] == @check_win[7] @check_win[9] = "Winner Middle Column" elsif @check_win[2] == @check_win[5] && @check_win[2] == @check_win[8] @check_win[9] = "Winner Right Column" elsif @check_win[0] == @check_win[4] && @check_win[0] == @check_win[8] @check_win[9] = "Winner Diagonal Left to Right" elsif @check_win[2] == @check_win[4] && @check_win[2] == @check_win[6] @check_win[9] = "Winner Diagonal Right to Left" end @check_win end @check_win attr_reader :check_win end class Two_player def initialize start_board = nil stuff = Board.new(start_board) game_board = stuff.board @game_array = stuff.board_array update_board end def update_board p1 = "X" p2 = "O" tie = "Its a Tie" wrong_space = " " count = 0 until count == 10 counter = 0 if count.even? == true player = "Player 1" else player = "Player 2" end new_board = Board.new(@game_array) puts " " puts "Varney's TTT" puts " " puts new_board.board puts "#{wrong_space}" case @game_array.count when 9 then if count == 9 break else puts "#{player} enter the number of the space you want to take:" puts " " moves = gets.chomp unless ("0".."8").include?(moves) moves = 9 end moves = moves.to_i system "cls" end when 10 then if player == "Player 1" player = "Player 2" else player = "Player 1" end puts "#{player} is the #{@game_array[9]}" puts " " tie = " " break end if @game_array.include?(moves) == true wrong_space = " " @game_array.each do |cell| if cell == moves if count.even? == true @game_array[counter] = p1 @game_array = Winning.new(@game_array).check_win count += 1 else @game_array[counter] = p2 @game_array = Winning.new(@game_array).check_win count += 1 end end counter += 1 end else wrong_space = "Try Again" end end unless tie == " " puts "#{tie}" puts " " end end end class One_player def initialize(skill) @skill = skill start_board = nil stuff = Board.new(start_board) game_board = stuff.board @game_array = stuff.board_array @marker = pick_marker one_board end def pick_marker puts " " puts "Varney's TTT" puts " " puts "Select X or O (X Goes First):" puts " " @marker = gets.chomp.upcase system "cls" unless ["X", "O"].include?(@marker) One_player.new(@skill) end @marker end def one_board @marker p1 = "X" p2 = "O" tie = "Its a Tie" wrong_space = " " count = 0 until count == 10 new_board = Board.new(@game_array) puts " " puts "Varney's TTT" puts " " puts new_board.board puts "#{wrong_space}" case @game_array.count when 9 then if count == 9 break else if @marker == "X" && count.even? puts "Your turn enter number of the space to place your #{@marker}:" puts " " moves = gets.chomp elsif @marker == "O" && count.odd? puts "Your turn enter number of the space to place your #{@marker}:" puts " " moves = gets.chomp elsif @marker == "X" && count.odd? puts "Wait for CPU to make move:" puts " " puts " " case @skill when 1 then moves = Easy_cpu.new(@game_array).move when 2 then moves = Medium_cpu.new(@game_array).move when 3 then moves = Hard_cpu.new(@game_array, @marker).move end sleep(2) elsif @marker == "O" && count.even? puts "Wait for CPU to make move:" puts " " puts " " case @skill when 1 then moves = Easy_cpu.new(@game_array).move when 2 then moves = Medium_cpu.new(@game_array).move when 3 then moves = Hard_cpu.new(@game_array, @marker).move end sleep(2) end unless ("0".."8").include?(moves) moves = 9 end moves = moves.to_i system "cls" end when 10 then if @marker == "O" && count.even? winner = "You are" elsif @marker == "O" && count.odd? winner = "The computer is" elsif @marker == "X" && count.even? winner = "The computer is" elsif @marker == "X" && count.odd? winner = "You are" end puts "#{winner} the #{@game_array[9]}" puts " " tie = " " break end if @game_array.include?(moves) == true wrong_space = " " counter = 0 @game_array.each do |cell| if cell == moves if count.even? == true @game_array[counter] = p1 @game_array = Winning.new(@game_array).check_win count += 1 else @game_array[counter] = p2 @game_array = Winning.new(@game_array).check_win count += 1 end end counter += 1 end else wrong_space = "Try Again" end end unless tie == " " puts "#{tie}" puts " " end end end class Easy_cpu def initialize(game_array) @game_array = game_array @move = cpu_move end def cpu_move @game_array.each do |cell| if cell.class == Integer return cell.to_s break end end end attr_reader :move end class Medium_cpu def initialize(game_array) @game_array = game_array @move = cpu_move end def cpu_move array = @game_array.shuffle array.each do |cell| if cell.class == Integer return cell.to_s break end end end attr_reader :move end class Hard_cpu def initialize(game_array, marker) @game_array = game_array @corners = [0, 2, 6, 8] @side_middle = [1, 3, 5, 7] @open_sides = open_side @open_corners = open_corner @open_spaces = open_space if marker == "X" @cpu_marker = "O" else @cpu_marker = "X" end @move = cpu_move end def open_space @open_spaces = [] @game_array.each do |cell| if cell.class == Integer @open_spaces << cell end end @open_spaces end def open_corner @open_corners = [] @game_array.each do |cell| if @corners.include?(cell) @open_corners << cell end end @open_corners end def open_side @open_sides = [] @game_array.each do |cell| if @side_middle.include?(cell) @open_sides << cell end end @open_sides end def terminal_board @stupid_move = [0, 4, 8], [6, 4, 2] @middle_corner = [[0, 4], [2, 4], [6, 4], [8, 4]] @terminal_combos = [[0, 1, 2], [1, 2, 0], [3, 4, 5], [4, 5, 3], [6, 7, 8], [7, 8, 6], [0, 3, 6], [3, 6, 0], [1, 4, 7], [4, 7, 1], [2, 5, 8], [5, 8, 2], [2, 4, 6], [4, 6, 2], [0, 4, 8], [4, 8, 0], [0, 2, 1], [0, 6, 3], [0, 8, 4], [1, 7, 4], [2, 8, 5], [2, 6, 4], [3, 5, 4], [6, 8, 7], [3, 1, 0], [1, 5, 2], [7, 5, 8], [3, 7, 6], [0, 7, 3], [0, 5, 1], [3, 2, 1], [2, 7, 5], [1, 6, 3], [5, 6, 7], [3, 8, 7], [1, 8, 5]] end def cpu_move terminal_board if @open_spaces.count == 9 return @open_corners.shuffle.last.to_s elsif @open_spaces.count == 7 @middle_corner.each do |combo| if @game_array.include?(combo[0]) == false && @game_array.include?(combo[1]) == false case combo[0] when 0 then return "8" when 2 then return "6" when 6 then return "2" when 8 then return "0" end end end elsif @open_spaces.count == 6 @stupid_move.each do |combo| if @game_array.include?(combo[0]) == false && @game_array.include?(combo[1]) == false && @game_array.include?(combo[2]) == false && combo[0] != combo[2] return @open_corners.shuffle.last.to_s end end elsif @open_spaces.count == 1 return @open_spaces[0].to_s end if @game_array.include?(4) return 4.to_s elsif @open_spaces.count == 8 return @open_corners.shuffle.last.to_s end @terminal_combos[0..23].each do |combo| if @game_array.include?(combo[0]) == false && @game_array.include?(combo[1]) == false && @game_array[combo[0]] == @cpu_marker && @game_array[combo[1]] == @cpu_marker && @game_array.include?(combo[2]) return combo[2].to_s end end @terminal_combos.each do |combo| if @game_array.include?(combo[0]) == false && @game_array.include?(combo[1]) == false && @game_array[combo[0]] == @game_array[combo[1]] && @game_array.include?(combo[2]) return combo[2].to_s end end if @open_corners.count > 0 return @open_sides.shuffle.last.to_s else return @open_spaces.shuffle.last.to_s end end attr_reader :move end class The_game def initialize system "cls" puts " " puts "Varney's TTT" puts " " puts "Select game type; 1 = PVP, 2 = Easy CPU, 3 = Medium CPU, 4 = Hard CPU" puts " " game_type = gets.chomp unless ("1".."4").include?(game_type) game_type = 0 end game_type = game_type.to_i if game_type < 1 The_game.new else system "cls" case game_type when 1 then Two_player.new when 2 then One_player.new(1) when 3 then One_player.new(2) when 4 then One_player.new(3) end end end end The_game.new
true
b9e9d906ea93e861030ca664dbe97c49ade4fa78
Ruby
Sh1pley/nightwriter
/lib/translator.rb
UTF-8
1,515
3.65625
4
[]
no_license
require_relative 'alphabet' class Translator attr_reader :alphabet def initialize @alphabet = Alphabet.new end def to_braille_line(string, index) line = "" numbers = false string.each_char do|character| if character == " " numbers = false end if numbers line << alphabet.given_alpha_number(character, index) else check_upcase(character, line, index) line << alphabet.given_alpha_letter(character, index) end if character == "#" numbers = true end end line end def check_upcase(character, line, index) if character.match(/^[[:alpha:]]$/) && character == character.upcase line << alphabet.given_alpha_letter("^", index) character.downcase! end end def to_braille(string) braille_array = [] braille_array << to_braille_line(string, 0) braille_array << to_braille_line(string, 1) braille_array << to_braille_line(string, 2) braille_array end def indexed_braille(string) string.scan(/../).each_slice(3).map { |e| e } end def to_alpha(string) final_string = "" indexed_braille(string).each do |item| final_string << alphabet.given_braille_letter(item) end to_upcase(final_string) end def to_upcase(string) string = string.scan(/./) string.each_with_index do |element, index| if element == "^" string[index +1].upcase! end end string.delete("^") string.join("") end end
true
c1d93a13c5f11e4a779d3d62d3fc00ab5cae2228
Ruby
melhemm/black-jack
/user.rb
UTF-8
488
3.140625
3
[]
no_license
require './bank' require './hand' class User < Hand include Bank attr_accessor :hand, :bank attr_reader :name def initialize(name) @name = name @hand = [] @bank = 100 end def user_hand(_flag = false) if name == 'Dealer' "#{name} #{hand.map { '*' }.join} points **" else "#{name} #{cards} points #{points}" end end HAND_LIMIT = 3 def hand_limit? hand.length == HAND_LIMIT end def clear_hand self.hand = [] end end
true
cb610dd8900dace8c75a5dd4d600aedb004f033e
Ruby
PhilHuangSW/Leetcode
/first_missing_positive.rb
UTF-8
1,124
4.34375
4
[]
no_license
#################### FIRST MISSING POSITIVE #################### # Given an unsorted integer array, find the smallest missing positive integer. # Example 1: # Input: [1,2,0] # Output: 3 # Example 2: # Input: [3,4,-1,1] # Output: 2 # Example 3: # Input: [7,8,9,11,12] # Output: 1 # Follow up: # Your algorithm should run in O(n) time and uses constant extra space. #################### SOLUTION #################### # @param {Integer[]} nums # @return {Integer} # TIME: O(n) -- SPACE: O(1) def first_missing_positive(nums) first_positive = 1 while nums.include?(first_positive) first_positive += 1 end first_positive end nums1 = [1,2,0] nums2 = [3,4,-1,1] nums3 = [7,8,9,11,12] nums4 = [-1,-2,-5,-10,10] nums5 = [1] nums6 = [] puts "Expected: 3 -- Actual: #{first_missing_positive(nums1)}" puts "Expected: 2 -- Actual: #{first_missing_positive(nums2)}" puts "Expected: 1 -- Actual: #{first_missing_positive(nums3)}" puts "Expected: 1 -- Actual: #{first_missing_positive(nums4)}" puts "Expected: 2 -- Actual: #{first_missing_positive(nums5)}" puts "Expected: 1 -- Actual: #{first_missing_positive(nums6)}"
true
a724b319bb08ba9ecddde151192c817581ffb995
Ruby
schoetlr/project_cli_connect_four_with_tests
/connect_four/spec/computer_spec.rb
UTF-8
570
3.015625
3
[]
no_license
require 'computer' describe Computer do let(:computer){Computer.new("Computron","O")} describe '#initialize' do it "should take 2 arguments" do expect{Computer.new("Computron")}.to raise_error(ArgumentError) end it "should create a name" do expect(computer.name).to eq("Computron") end it "should create a piece" do expect(computer.piece).to eq("O") end end describe '#get_input' do it "should return an input which is an Integer" do end it "should return an input in valid range" do end end end
true
7067672c8fdcbd48d6667f791b9de331a101d15c
Ruby
hokto/Judge
/Python/answer_sources/Products/increase.rb
UTF-8
2,279
3.546875
4
[]
no_license
#解法としては、現在の値段をciと表すと「もっとも値の小さいciを取り出してmから引くという操作を #何回することができるか」という風に解釈できる。よって、PriorityQueueというアルゴリズムを用いて #もっとも安い値段をqueueから取り出し、取り出した後にその値段にbiを加算し、またqueueに追加する #という操作をmが0になるまで繰り返せばよく、PriorityQueueの計算量は、要素の追加、取り出し共に #O(log N)なので、O(log N + M*log N)=O(M*log N)となり、間に合います。 def get_i() #空白区切の入力を数値(整数)の配列で返す return gets.chomp.split(" ").map(&:to_i) end def get_f() #空白区切の入力を数値(実数)の配列で返す return gets.chomp.split(" ").map(&:to_f) end def get() #空白区切の入力を文字列の配列で返す return gets.chomp.split(" ") end def get_nsp() #入力されたものを一文字ずつに区切った文字列の配列で返す return gets.chomp.split("") end def yn_judge(bool,y="Yes",n="No") #boolに真偽を投げることで、trueならy、falseならnの値を出力する return bool ? y : n end def array(size,n=1,init=nil) #nに配列の次元数、sizeに配列の大きさ、initに初期値を投げることでその配列を返す if n==1 return Array.new(size){init} else return Array.new(n).map{Array.new(size){init}} end end class PriorityQueue attr_accessor:queue,:n def initialize(n) @n=0 @queue=array(2,n,10**9) end def push_q(x) i=@n @n+=1 while i>0 p_=(i-1)/2 break if @queue[p_][0]<=x[0] @queue[i]=@queue[p_] i=p_ end @queue[i]=x end def pop_q() min=@queue[0] @n-=1 x=@queue[@n] i=0 while i*2+1<@n l=i*2+1 r=i*2+2 l=r if r<@n and @queue[r][0]<@queue[l][0] break if @queue[l][0]>=x[0] @queue[i]=@queue[l] i=l end @queue[i]=x return min end end n,m=get_i pq=PriorityQueue.new(n) a=get_i b=get_i n.times do|i| pq.push_q([a[i],b[i]]) end ans=0 while true c=pq.pop_q() if m-c[0]>=0 m-=c[0] c[0]+=c[1] pq.push_q(c) ans+=1 else break end end puts ans
true
b559f28d35d41e45fc6fee90504fab50e1ea87c0
Ruby
klaviyo/ruby-klaviyo
/lib/klaviyo/apis/campaigns.rb
UTF-8
1,605
2.546875
3
[]
no_license
module Klaviyo class Campaigns < Client CANCEL = 'cancel' CAMPAIGN = 'campaign' CAMPAIGNS = 'campaigns' SEND = 'send' # Retrieves all the campaigns from Klaviyo account # @kwarg :api_key [String] private API key for this request # @return [List] of JSON formatted campaing objects def self.get_campaigns(api_key: nil) v1_request(HTTP_GET, CAMPAIGNS, api_key: api_key) end # Retrieves the details of the list # @param campaign_id the if of campaign # @kwarg :api_key [String] private API key for this request # @return [JSON] a JSON object containing information about the campaign def self.get_campaign_details(campaign_id, api_key: nil) path = "#{CAMPAIGN}/#{campaign_id}" v1_request(HTTP_GET, path, api_key: api_key) end # Sends the campaign immediately # @param campaign_id [String] the id of campaign # @kwarg :api_key [String] private API key for this request # @return will return with HTTP ok in case of success def self.send_campaign(campaign_id, api_key: nil) path = "#{CAMPAIGN}/#{campaign_id}/#{SEND}" v1_request(HTTP_POST, path, api_key: api_key) end # Cancels the campaign with specified campaign_id # @param campaign_id [String] the id of campaign # @kwarg :api_key [String] private API key for this request # @return [JSON] a JSON object containing the campaign details def self.cancel_campaign(campaign_id, api_key: nil) path = "#{CAMPAIGN}/#{campaign_id}/#{CANCEL}" v1_request(HTTP_POST, path, api_key: api_key) end end end
true
b756ece986ccd482df099c225128abf19d3aa37e
Ruby
KelvinMutuma/nse_data
/app/models/forex.rb
UTF-8
1,870
2.546875
3
[]
no_license
# == Schema Information # # Table name: forexes # # id :integer not null, primary key # currency :string(255) # buy :float # sell :float # mean :float # created_at :datetime # updated_at :datetime # guid :string(255) # published_at :datetime # class Forex < ActiveRecord::Base feed_url = "https://spreadsheets.google.com/feeds/list/1KsgFX_MtJLqDcOs8fcV4HLZ_gAKlU0NMQviEAl5Ar4M/od6/public/values" def update_from_feed(feed_url) feed = Feedjira::Feed.fetch_and_parse(feed_url) # unless feed.is_a?(Fixnum) # add_entries(feed.entries) # else # puts feed.inspect # end end def self.update_from_feed_continuously(feed_url,delay_interval=2.minutes) feed = Feedjira::Feed.fetch_and_parse(feed_url) add_entries(feed.entries) loop do sleep delay_interval feed = Feedjira::Feed.update(feed_url) add_entries(feed.new_entries) if feed.updated? end end private def self.add_entries(entries) entries.each do | entry | c = entry.updated.to_s unless exists? guid: entry.id+c b = entry.content # anydate = b.scan(/\d{4}\/\d{2}\/\d{2}/) # if !anydate.empty? # anydate.each {|s| b = b.gsub(s,'0').gsub(",",".")} # else # b = b.gsub(",",".") # end content = b.scan(/(?<=[ *])-?\d[\d.]+/).map(&:to_f) #contents = entry.content.split(',').map {|n| n.split(" ").last } #parsed_contents = contents.map{ |x| x.scan(/[\d\.-]+/)[0] }.map(&:to_f) Forex.create!( currency: content[0], buy: content[1], sell: content[2], percentage_change: content[3], high: content[4], low: content[5], published_at: entry.updated, guid: entry.id+c ); end end end end
true
1cc86bf2dcc1080438fb5924fc9afc4c1d11bd6b
Ruby
asuc-octo/cao
/app/models/i18n_utils.rb
UTF-8
710
2.546875
3
[ "MIT" ]
permissive
# I18n utilities. module I18nUtils # Mapping of locales to UI friendly names. # Add more locales and names here as desired. LOCALE_NAMES = { en: 'English', hi: 'हिन्दी' } # Available locales for the main application. # # Note that these *do not* supersede available locales set via # `I18n.available_locales` in the config/application.rb file. Rather, they are # used to differentiate between locales available for the main and admin apps. # This is because one may not need the admin app to be internationalized. def self.avail_locales [:en, :hi] end # Available locales for the admin application. def self.admin_avail_locales [:en, :hi] end end
true
426a93209e172faaf4d09513232089262fd32127
Ruby
shveikus/json_api
/db/seeds.rb
UTF-8
1,645
2.671875
3
[]
no_license
require 'httparty' require 'oj' require 'faker' require 'progress_bar' require 'pry' HEADERS = { 'Content-type' => 'application/json' }.freeze threads = [] logins = [] 50.times do logins << Faker::Internet.user_name end bar_posts = ProgressBar.new 200_000 puts 'Start creating via http endpoint 200k posts' 20.times do threads << Thread.new do 10_000.times do bar_posts.increment! @result = HTTParty.post('http://localhost:9292/api/v1/post', body: { "body": Faker::Lorem.sentence, "title": Faker::Lorem.word, "login": logins.sample, "ip": "192.168.112.#{rand(50)}" }.to_json, headers: HEADERS) puts 'Error: #{@result.body}' unless @result.code == 200 end end end threads.each(&:join) threads_rates = [] bar_votes = ProgressBar.new 20_000 puts 'Starting creating via http endpoint 2k votes' 20.times do threads_rates << Thread.new do 1000.times do bar_votes.increment! @result = HTTParty.post('http://localhost:9292/api/v1/post/vote', body: { "user_rate": rand(1...5), "post_id": rand(1...200_000) # "user_rate": 1, # "post_id": 1 }.to_json, headers: HEADERS) puts 'Error' unless @result.code == 200 end end end threads_rates.each(&:join)
true
ff2db0a64ba1a3a6600c2d1212f6f302bc7426b9
Ruby
karanm645/fixer_upper_2108
/spec/house_spec.rb
UTF-8
1,996
3.375
3
[]
no_license
require './lib/room' require './lib/house' RSpec.describe House do it "exists" do house = House.new("$400000", "123 sugar lane") expect(house).to be_an_instance_of(House) end it "returns a price" do house = House.new("$400000", "123 sugar lane") expect(house.price).to eq(400000) end it "returns an address" do house = House.new("$400000", "123 sugar lane") expect(house.address).to eq("123 sugar lane") end it "returns an empty array" do house = House.new("$400000", "123 sugar lane") expect(house.rooms).to eq([]) end it "returns an array with rooms" do house = House.new("$400000", "123 sugar lane") room_1 = Room.new(:bedroom, 10, '13') room_2 = Room.new(:bedroom, 11, '15') house.add_room(room_1) house.add_room(room_2) expect(house.rooms).to eq([room_1, room_2]) end it "returns above_market_average?" do house = House.new("$400000", "123 sugar lane") expect(house.above_market_average?).to eq(false) end it "adds rooms" do house = House.new("$400000", "123 sugar lane") room_1 = Room.new(:bedroom, 10, '13') room_2 = Room.new(:bedroom, 11, '15') room_3 = Room.new(:living_room, 25, '15') room_4 = Room.new(:basement, 30, '41') house.add_room(room_1) house.add_room(room_2) house.add_room(room_3) house.add_room(room_4) expect(house.rooms_from_category(:bedroom)).to eq([room_1, room_2]) expect(house.rooms_from_category(:basement)).to eq([room_4]) expect(house.area).to eq(1900) end it "has details" do house = House.new("$400000", "123 sugar lane") room_1 = Room.new(:bedroom, 10, '13') room_2 = Room.new(:bedroom, 11, '15') room_3 = Room.new(:living_room, 25, '15') room_4 = Room.new(:basement, 30, '41') house.add_room(room_1) house.add_room(room_2) house.add_room(room_3) house.add_room(room_4) expect(house.details).to eq({"price" => 400000, "address" => "123 sugar lane"}) end end
true
5eaaf175fd94dc7d62a8bb7ff6647b9861f4be9f
Ruby
David-Roark/code_practice
/exercism/dominoes/dominoes.rb
UTF-8
974
3.78125
4
[]
no_license
# OOP class Dominoes attr_accessor :head, :tail def initialize(domi) @head, @tail = domi end def self.chain?(ds) return true if ds == [] return ds[0][0] == ds[0][1] if ds.size == 1 ds.permutation{ |d| return true if can_linked?(d) } false end # if all dominoes can link, # the last 'domi' will be [x, x] like [1,1], [2,2],... # else return false def self.can_linked?(dominoes) domi = new(dominoes[0]) dominoes[1..-1].each do |d| linked_domi = domi.link(d) if linked_domi domi = linked_domi else return false end end domi.head == domi.tail end # if two dominoes (can link) is [1,2], [3,2] => [1,3] # if two dominoes (can't link) is [1,2], [5,6] => false def link(domi) domi = Dominoes.new(domi) if self.tail == domi.head self.tail = domi.tail elsif self.tail == domi.tail self.tail = domi.head else return false end self end end
true
eeb40541f55d2e9b02adfdbe5aa79f72ebb37dc6
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/raindrops/7809d7e3090e42239223415747e7b312.rb
UTF-8
444
3.484375
3
[]
no_license
require 'prime' class Raindrops SOUNDS = { 3 => 'Pling', 5 => 'Plang', 7 => 'Plong' } def initialize(number) @number = number end def self.convert(number) new(number).convert end def convert sound.empty? ? @number.to_s : sound end private def sound @sound ||= prime_divisors.map { |prime| SOUNDS[prime] }.join end def prime_divisors SOUNDS.keys & Prime.prime_division(@number).flatten end end
true
c78d0b0498f3e5cc11a3c9a01963c096421bdb23
Ruby
angelodlfrtr/ruby-cic-embeded-payment
/lib/cic_embeded_payment/payment_response.rb
UTF-8
5,728
2.578125
3
[ "MIT" ]
permissive
require 'nokogiri' module CicEmbededPayment class PaymentResponse attr_reader :original_response, :parsed_response # Parse RestClient response to cic payment gateway # # @param response [Class] The RestClient response def initialize response @original_response, @parsed_response = response, Nokogiri::XML(response.body) end # Permit to know if request is a success # # @return [Boolean] true or false def success? @parsed_response.xpath('//cdr/text()').to_s.to_i > 0 end # Permit to know if request is an error # # @return [Boolean] true or false def error?; !success?; end def error code = @parsed_response.xpath('//cdr/text()') message_by_request_response_code(code) end private # Permit to get the message corresponding to the response code def message_by_request_response_code code { '2' => [ 'Résultat de l\'étape 1 pour une carte enrôlée 3DSecure', 'Le commerçant devra effectuer les étapes 2 et 3 pour l\'authentification du client' ], '1' => [ 'Mise en recouvrement effectuée', 'l’autorisation bancaire a été délivrée et la mise en recouvrement a été effectuée.' ], '0' => ['Paiement non effectué', 'L’autorisation bancaire n’a pas été délivrée' ], '-1' => [ 'Problème technique', 'Problème technique, il faut réitérer la demande' ], '-2' => [ 'Commerçant non identifié', 'Les paramètres servant à identifier le site commerçant ne sont pas corrects, vérifier les champs societe, lgue et TPE' ], '-3' => [ 'Commande non authentifiée', 'La signature MAC est invalide' ], '-4' => [ 'CB expirée', 'La date de validité de la carte bancaire n’est pas valide' ], '-5' => [ 'Numéro de CB erroné', 'Le numéro de la carte bancaire n’est pas valide' ], '-6' => [ 'Commande expirée', 'La date de la commande dépasse le délai autorisé (+/- 24h)' ], '-7' => [ 'Montant erroné', 'Le montant transmis est mal formaté ou est égal à zéro' ], '-8' => [ 'Date erronée', 'La date transmise est erronée' ], '-9' => [ 'CVX erroné', 'Le cryptogramme visuel transmis est erroné' ], '-10' => [ 'Paiement déjà autorisé', 'une autorisation a déjà été délivrée pour cette demande de paiement, il est toujours possible de mettre en recouvrement le paiement' ], '-11' => [ 'Paiement déjà accepté', 'Le paiement relatif à cette commande a déjà fait l’objet d’un recouvrement' ], '-12' => [ 'Paiement déjà annulé', 'la commande a été annulée et ne peut plus accepter de nouvelle demande d’autorisation' ], '-13' => [ 'Traitement en cours', 'La commande est en cours de traitement' ], '-14' => [ 'Commande grillée', 'Le nombre maximal de tentatives de fourniture de carte a été atteint (3 tentatives sont acceptées), la commande n’est plus acceptée par le serveur bancaire' ], '-15' => [ 'Erreur paramètres', 'Les paramètres transmis à l\'émulation TPE sont erronés' ], '-16' => [ 'Erreur résultat d\'authentification 3D-Secure', 'Le résultat d\'authentification 3D-Secure transmis à l\'émulation TPE est invalide' ], '-17' => [ 'Le montant des échéances est erroné', 'Le montant des échéances transmis est mal formaté. La somme des échéances n’est pas égale au montant de la commande.' ], '-18' => [ 'La date des échéances est erronée', 'L’une des dates transmise est mal formatée. La différence entre les dates n’est pas d’un mois.' ], '-19' => [ 'Le nombre d’échéance n’est pas correct', 'Le nombre d’échéance doit être compris entre 2 et 4' ], '-20' => [ 'La version envoyée n’est pas correcte', 'La version doit être égale à « 3.0 »' ], '-22' => [ 'CB séquestrée expirée', 'La date de la carte séquestrée utilisée est expirée' ], '-24' => [ 'CVV non présent', 'Le CVV n’a pas été fourni et est obligatoire' ], '-25' => [ 'TPE fermé', 'Le TPE utilisé est fermé' ], '-26' => [ 'AVS manquant', '« Address Verification System » : l’adresse n’a pas été fournie' ] }[code.to_s] end end end
true
32b6f2e63e8d359b488abd36f430b09f2db42ae4
Ruby
jianghaoyuan2007/pod-template-fastlane
/setup/TemplateConfigurator.rb
UTF-8
3,319
2.84375
3
[ "MIT" ]
permissive
require 'fileutils' require 'colored2' require 'find' module Pod class TemplateConfigurator attr_reader :pod_name, :homepage, :git_source, :github_username, :github_repo_name def initialize(pod_name) @pod_name = pod_name @message_bank = MessageBank.new(self) end def ask(question) answer = "" loop do puts "\n#{question}?" @message_bank.show_prompt answer = gets.chomp break if answer.length > 0 print "\nYou need to provide an answer." end answer end def run @homepage = self.ask("What is your homepage").to_s @git_source = self.ask("What is your git source").to_s @github_username = self.ask("What is the GitHub username").to_s @github_repo_name = self.ask("What is the GitHub repo name").to_s remove_podfile_lock replace_variables_in_files rename_template_files reinitialize_git_repo add_git_remote clean_template_files remove_configure_file run_pod_install end def remove_configure_file `rm -rf configure` end def remove_podfile_lock `rm -rf Podfile.lock` end def clean_template_files `rm -rf setup` end def add_git_remote `git remote add origin #{@git_source}` end def rename_template_files FileUtils.mv "POD_NAME.podspec", "#{@pod_name}.podspec" FileUtils.mv "Sources/POD_NAME.h", "Sources/#{@pod_name}.h" FileUtils.mv "POD_NAME.xcodeproj", "#{@pod_name}.xcodeproj" # FileUtils.mv "#{@pod_name}.xcodeproj/xcshareddata/xcschemes/POD_NAME.xcscheme", "#{@pod_name}.xcodeproj/xcshareddata/xcschemes/#{@pod_name}.xcscheme" # FileUtils.mv "#{@pod_name}.xcodeproj/xcshareddata/xcschemes/POD_NAMETests.xcscheme", "#{@pod_name}.xcodeproj/xcshareddata/xcschemes/#{@pod_name}Tests.xcscheme" FileUtils.mv "POD_NAMETests", "#{@pod_name}Tests" FileUtils.mv "#{@pod_name}Tests/POD_NAMETests.m", "#{@pod_name}Tests/#{@pod_name}Tests.m" end def replace_variables_in_files file_names = self.replace_variables_files file_names.each do |file_name| text = File.read(file_name) text.gsub!("${POD_NAME}", @pod_name) text.gsub!("${HOMEPAGE}", @homepage) text.gsub!("${GIT_SOURCE}", @git_source) text.gsub!("${GITHUB_USERNAME}", @github_username) text.gsub!("${GITHUB_REPO_NAME}", @github_repo_name) File.open(file_name, "w") { |file| file.puts text } end end def replace_variables_files file_names = ['POD_NAME.podspec', 'CHANGELOG.md', 'LICENSE', 'Podfile', 'README.md'] dirs = ['Example', 'POD_NAMETests', 'Sources', 'POD_NAME.xcodeproj', 'fastlane'] dirs.each do |dir| Find.find(dir) do |file_name| if File.file?(file_name) file_names << file_name end end end return file_names end def reinitialize_git_repo `rm -rf .git` `git init` `git add -A` end def run_pod_install puts "\nRunning " + "pod install".magenta + " on your new library." puts "" system "pod install" `git add -A` `git commit -m "Initial commit"` end end end
true
e6ec8127db5690768665a2781b8b093ba19f6643
Ruby
cpcsacggc/RubySchool.US
/arc/17/split_method5.rb
UTF-8
230
3.359375
3
[]
no_license
input = File.open("income.txt", "r") total = 0 x = 0 while x < 6 x+=1 line = input.gets arr = line.split(",") total += arr[1].to_i puts "#{arr[0]} - $#{arr[1]}" end input.close puts "" puts "6 month's Total: #{total}"
true
02b9cef267ec2e04b92d9b84cb727bc4f74b88f1
Ruby
dalalsunil1986/algorithms_ruby
/others/group_open_hours.rb
UTF-8
3,286
3.6875
4
[]
no_license
require 'RSpec' require 'date' def group_open_hours(open_hours) # if all are empty, return all days nil hash return [empty_day('Monday-Sunday')] if open_hours.empty? output = [] count = 0 input = {} # convert input array to hash with day as key open_hours.each do |hash| # change day key to days as in output we need days hash[:days] = hash.delete :day input[hash[:days]] = hash end # traverse from Monday to Sunday Date::DAYNAMES.rotate(1).each do |day| last = output[-1] current = input[day] || {} if output.any? && match?(current, last) output[-1][:days] = updated_days(output[-1][:days], day) elsif current != {} output << current else output << empty_day(day) end end output end def match?(day1, day2) day1[:open] == day2[:open] && day1[:close] == day2[:close] end def updated_days(str, day) days = str.split('-') days[1] = day days.join('-') end def empty_day(day) { days: day, open: nil, close: nil } end RSpec.describe 'group_open_hours' do it 'should work on the provided example' do open_hours = [ { day: 'Monday', open: '8:00 AM', close: '5:00 PM' }, { day: 'Tuesday', open: '8:00 AM', close: '5:00 PM' }, { day: 'Wednesday', open: '8:00 AM', close: '6:00 PM' }, { day: 'Thursday', open: '8:00 AM', close: '5:00 PM' }, { day: 'Friday', open: '8:00 AM', close: '5:00 PM' }, { day: 'Saturday', open: '8:00 AM', close: '4:00 PM' } ] expected = [ { days: 'Monday-Tuesday', open: '8:00 AM', close: '5:00 PM' }, { days: 'Wednesday', open: '8:00 AM', close: '6:00 PM' }, { days: 'Thursday-Friday', open: '8:00 AM', close: '5:00 PM' }, { days: 'Saturday', open: '8:00 AM', close: '4:00 PM' }, { days: 'Sunday', open: nil, close: nil } ] actual = group_open_hours(open_hours) expect(actual).to eq(expected) end it 'should handle ranges of closed days' do open_hours = [ { day: 'Monday', open: '9:00 AM', close: '4:00 PM' }, { day: 'Tuesday', open: '9:00 AM', close: '4:00 PM' }, { day: 'Wednesday', open: '9:00 AM', close: '4:00 PM' }, { day: 'Thursday', open: '9:00 AM', close: '4:00 PM' } ] expected = [ { days: 'Monday-Thursday', open: '9:00 AM', close: '4:00 PM' }, { days: 'Friday-Sunday', open: nil, close: nil } ] actual = group_open_hours(open_hours) expect(actual).to eq(expected) end end puts group_open_hours([{ day: 'Sunday', open: '9:00 AM', close: '4:00 PM' }, { day: 'Tuesday', open: '9:00 AM', close: '4:00 PM' }, { day: 'Wednesday', open: '9:00 AM', close: '4:00 PM' }, { day: 'Thursday', open: '9:00 AM', close: '4:00 PM' }])
true
f1f183521c41ab7adc6259233c70f3eaf2886aee
Ruby
matthewmpalen/ruby-auction-house
/models/item.rb
UTF-8
331
2.890625
3
[]
no_license
######### # Models ######### class Item # Model which represents the concrete item for sale in an auction attr_accessor :available attr_reader :name, :description, :created_at def initialize(name, description) @name = name @description = description @available = true @created_at = DateTime.new end end
true
8ade34a66dd72e005b1a24641a70d6e497621359
Ruby
meliew/collections_practice-online-web-pt-051319
/collections_practice.rb
UTF-8
860
3.8125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(integer_array) integer_array.sort do |a, b| a <=> b end end def sort_array_desc(integer_array) integer_array.sort do |a, b| b <=> a end end def sort_array_char_count(array) array.sort do |a, b| a.length <=> b.length end end def swap_elements(array) array[1], array[2] = array[2], array[1] array end def reverse_array(integers_array) integers_array.reverse end def kesha_maker(array) new_array = array.map do |word| word[2] = "$" word end new_array end def find_a(array) array.select do |word| if word.start_with?("a") word end end end def sum_array(numbers_array) sum = 0 numbers_array.each do |i| sum += i end sum end def add_s(array) array.each_with_index.collect do |element, index| if element == array[1] element else element +'s' end end end
true
c5683c7d7ae7429e70ddf72b441e3761d90f97a3
Ruby
lauranjansen/learn_ruby
/03_simon_says/simon_says.rb
UTF-8
582
3.84375
4
[]
no_license
def echo(input) input end def shout(input) input.upcase end def repeat(input, num = 2) output = input for i in 2..num output = output + " " + input end output end def start_of_word(input, num) input[0,num] end def first_word(input) input.split(" ")[0] end def titleize(input) words = input.split(" ") output = words[0].capitalize if words.count > 1 for i in 1..(words.count - 1) case words[i] when "and", "the", "over", "under", "at" output = output + " " + words[i] else output = output + " " + words[i].capitalize end end end output end
true
7178e91c8871ad7bc52be1eff2da0f0ddbdcdfc2
Ruby
ysk1180/refactoring-ruby-edition
/replace_abstract_superclass_with_module.rb
UTF-8
1,156
3.609375
4
[]
no_license
# class Item # def initialize(name, origin_country = nil) # @name = name # @origin_country = origin_country # end # # def description # puts "商品名:#{@name} / 補足:#{additional_description}" # end # end # # class DomesticItem < Item # def additional_description # '国内産です' # end # end # # class ImportedItem < Item # def additional_description # "#{@origin_country}で作られました" # end # end # # DomesticItem.new('イヤホン').description # ImportedItem.new('スマートフォン', 'アメリカ').description # ↓リファクタリング後↓ module Item def initialize(name, origin_country = nil) @name = name @origin_country = origin_country end def description puts "商品名:#{@name} / 補足:#{additional_description}" end end class DomesticItem include Item def additional_description '国内産です' end end class ImportedItem include Item def additional_description "#{@origin_country}で作られました" end end DomesticItem.new('イヤホン').description ImportedItem.new('スマートフォン', 'アメリカ').description
true
1109ea4792204e2182e1d2e7424d93c5013cdf2b
Ruby
pyjac/mastermind
/lib/game_colours.rb
UTF-8
580
3.28125
3
[]
no_license
class GameColours attr_accessor :beginner_colours, :intermediate_colours, :advanced_colours def self.beginner_colours {"R" => "Red" , "Y" => "Yellow" , "B" => "Blue", "G" => "Green"} end def self.intermediate_colour beginner_colours.merge( { "O" => "Orange"}) end def self.advanced_colours intermediate_colour.merge( {"W" => "White"}) end def self.get_game_colours(level) case level when Keys::BEGINNER return beginner_colours when Keys::INTERMEDIATE return intermediate_colour when Keys::ADVANCED return advanced_colours end end end
true
fa25f688c49f0a75128776cd0b36798462405bc3
Ruby
match-and-snatch/web
/lib/elasticpal/response.rb
UTF-8
1,211
2.6875
3
[]
no_license
module Elasticpal class Response def initialize(response, query = nil) @plain_response = response @query = query @scope = @query.try(:model) end def records(scope = {}) results = relation(scope).to_a ids.map do |id| results.find { |x| x.id == id } end.compact.sort do |r1, r2| order(r2) <=> order(r1) end end def relation(scope = {}) @scope.where(id: ids).where(scope) end def ids hits.map { |hit| hit['_id'] }.map(&:to_i) end def any? hits.any? end def hits @hits ||= hits_data['hits'] end def hits_data @hits_data ||= response['hits'] end def max_score hits_data['max_score'] end def total hits_data['total'] end def order(record) hit = hits.find { |hit| hit['_id'] == record.id.to_s } hit.has_key?('sort') ? hit['sort'] : hit['_score'] end def response @response ||= parse_plain_response(@plain_response) end private def parse_plain_response(response) if response.is_a?(String) JSON.parse(response) else raise ArgumentError end end end end
true
1bfcb6645d825917b5515f478de04b3543486c7e
Ruby
pcloeter/BenchBnB
/app/models/user.rb
UTF-8
867
2.640625
3
[]
no_license
class User < ApplicationRecord validates :username, presence: true validates :password, length: { minimum: 6, allow_nil: true } after_initialize :ensure_token attr_reader :password def self.generate_token SecureRandom.urlsafe_base64 end def self.find_by_credentials(credentials) user = User.find_by(username: credentials[:username]) if user return user if is_password?(credentials[:password]) else return nil end end def password=(password) self.password_digest = BCrypt::Password.create(password) end def is_password?(password) return BCrypt::Password.new(self.password_digest).is_password?(password) end def reset_token! self.session_token = User.generate_token self.save! self.session_token end def ensure_token return self.session_token ||= User.generate_token end end
true
c4b6676841b308b50c8103892b543407e8880fd7
Ruby
megamsys/megam_api
/lib/megam/core/organizations_collection.rb
UTF-8
3,133
3.109375
3
[ "MIT" ]
permissive
module Megam class OrganizationsCollection include Enumerable attr_reader :iterator def initialize @organizations = Array.new @organizations_by_name = Hash.new @insert_after_idx = nil end def all_organizations @organizations end def [](index) @organizations[index] end def []=(index, arg) is_megam_organizations(arg) @organizations[index] = arg @organizations_by_name[arg.name] = index end def <<(*args) args.flatten.each do |a| is_megam_organizations(a) @organizations << a @organizations_by_name[a.name] =@organizations.length - 1 end self end # 'push' is an alias method to << alias_method :push, :<< def insert(organizations) is_megam_organizations(organizations) if @insert_after_idx # in the middle of executing a run, so any predefs inserted now should # be placed after the most recent addition done by the currently executing # predefclouds @organizations.insert(@insert_after_idx + 1, organizations) # update name -> location mappings and register new predefclouds @organizations_by_name.each_key do |key| @organizations_by_name[key] += 1 if@organizations_by_name[key] > @insert_after_idx end @organizations_by_name[organizations.name] = @insert_after_idx + 1 @insert_after_idx += 1 else @organizations << organizations @organizations_by_name[organizations.name] =@organizations.length - 1 end end def each @organizations.each do |organizations| yield organizations end end def each_index @organizations.each_index do |i| yield i end end def empty? @organizations.empty? end def lookup(organizations) lookup_by = nil if organizations.kind_of?(Megam::Organizations) lookup_by = organizations.name elsif organizations.kind_of?(String) lookup_by = organizations else raise ArgumentError, "Must pass a Megam::PredefClouds or String to lookup" end res =@organizations_by_name[lookup_by] unless res raise ArgumentError, "Cannot find a predefclouds matching #{lookup_by} (did you define it first?)" end @organizations[res] end def to_s @organizations.join(", ") end def for_json to_a.map { |item| item.to_s } end def to_json(*a) Megam::JSONCompat.to_json(for_json, *a) end def self.json_create(o) collection = self.new() o["results"].each do |organizations_list| organizations_array = organizations_list.kind_of?(Array) ? organizations_list : [ organizations_list ] organizations_array.each do |organizations| collection.insert(organizations) end end collection end private def is_megam_organizations(arg) unless arg.kind_of?(Megam::Organizations) raise ArgumentError, "Members must be Megam::Organizations's" end true end end end
true
0a1289d3a88355023e4929ff7f941caed0202c44
Ruby
toddt67878/Building_a_Roll_Call_System_in_Ruby
/main.rb
UTF-8
3,583
3.328125
3
[ "MIT" ]
permissive
require 'rspec' require 'date' class RollCallBooleanError < StandardError def message 'Status needs to be either true or false' end end class RollCallPercentError < StandardError def message 'Grouping needs to be either present or absent' end end class RollCall attr_reader :roll def initialize @string_date = Date.today.to_s @roll = roll_builder @q = @roll[@string_date] end def roll_builder { @string_date => { :present => [], :absent => [] } } end def student_check(name:, status:) raise RollCallBooleanError unless (status == true || status == false) if status @q[:present].push(name) else @q[:absent].push(name) end end def save_to_file File.open('support/roll_log.md', 'a') do |f| f << formatted_roll end end def roll_percentage(grouping) total_students = @q.values.flatten.count present_percent = (@q[:present].count.to_f / total_students.to_f) * 100.0 if grouping == 'present' present_percent elsif grouping == 'absent' 100 - present_percent else raise RollCallPercentError end end def formatted_roll <<~ROLLDOC ## Roll call for #{@string_date} ### #{roll_percentage('present')}% Present #{@q[:present].join(', ')} ### #{roll_percentage('absent')}% Absent #{@q[:absent].join(', ')} #{'-' * 42} ROLLDOC end end describe RollCall do before do @rc = RollCall.new @rc.student_check(name: 'Ryan', status: true) @rc.student_check(name: 'Chase', status: true) @rc.student_check(name: 'KJ', status: true) @rc.student_check(name: 'Hunter', status: false) @rc.student_check(name: 'Devan', status: false) @rc.student_check(name: 'Zach', status: true) @rc.student_check(name: 'Ben', status: true) @rc.student_check(name: 'Stephanie', status: true) @rc.student_check(name: 'Ian', status: true) @rc.student_check(name: 'Alex', status: true) @rc.student_check(name: 'Cody', status: true) @rc.student_check(name: 'Preston', status: true) @rc.student_check(name: 'Andrew', status: true) @rc.student_check(name: 'Jason', status: true) @rc.student_check(name: 'Christian', status: false) end it 'can take roll for students and return a hash that lists the students that were present and absent' do expect(@rc.roll).to eq( { "2017-04-12"=> { :present=>[ "Ryan", "Chase", "KJ", "Zach", "Ben", "Stephanie", "Ian", "Alex", "Cody", "Preston", "Andrew", "Jason" ], :absent=>[ "Hunter", "Devan", "Christian" ] } }) end it 'can give a percent of absent and present' do expect(@rc.roll_percentage('present')).to eq(80.0) expect(@rc.roll_percentage('absent')).to eq(20.0) end it 'appends the daily roll call to a file' do # In order for this test you to pass, you will need to have a directory # named 'support' on the path that you call the RSpec test from @rc.save_to_file content = <<~CONTENT ## Roll call for 2017-04-12 ### 80.0% Present Ryan, Chase, KJ, Zach, Ben, Stephanie, Ian, Alex, Cody, Preston, Andrew, Jason ### 20.0% Absent Hunter, Devan, Christian ------------------------------------------ CONTENT expect(File.read('support/roll_log.md')).to match(content) end end
true
40bc442e2d85b520a0477621cde34441e658c3c0
Ruby
oscos/launch_school
/rb101/lesson3/hard1/x02.rb
UTF-8
503
3.3125
3
[]
no_license
=begin Launch School: RB101 Programming Foundations - Lesson 3 - Practice Problems ExerciseName: [Hard](https://launchschool.com/lessons/263069da/assignments/a3c602d1) FileName: x02.rb Answered On: 10/01/2020 =end # require "pry" # require "pp" # What do you expect to happen when the greeting variable is referenced in the # last line of the code below? greetings = { a: 'hi' } informal_greeting = greetings[:a] informal_greeting << ' there' puts informal_greeting # => "hi there" puts greetings
true
cb995f2492587cf02de368a0b5b081f59a0105b1
Ruby
Waynexiee/My_leetcode
/4Sum2.rb
UTF-8
437
3.40625
3
[]
no_license
def four_sum_count(a, b, c, d) size = a.size h = {} sum = 0 0.upto(size - 1) do |i| 0.upto(size - 1) do |j| h[a[i] + b[j]] = [] unless h[a[i] + b[j]] h[a[i] + b[j]] << [a[i],b[j]] end end 0.upto(size - 1) do |i| 0.upto(size - 1) do |j| sum += h[-(c[i] + d[j])].size if h[-(c[i] + d[j])] end end sum end A = [ 1, 2] B = [-2,-1] C = [-1, 2] D = [ 0, 2] puts four_sum_count(A, B, C, D)
true
f4c6c7e1b082a2ace32a99a06399d11f3a0aa90a
Ruby
teoucsb82/pokemongodb
/lib/pokemongodb/pokemon/seel.rb
UTF-8
1,402
2.78125
3
[]
no_license
class Pokemongodb class Pokemon class Seel < Pokemon def self.id 86 end def self.base_attack 104 end def self.base_defense 138 end def self.base_stamina 130 end def self.buddy_candy_distance 2 end def self.candy_to_evolve 50 end def self.capture_rate 0.4 end def self.cp_gain 16 end def self.description "Seel hunts for prey in the frigid sea underneath sheets of ice. When it needs to breathe, it punches a hole through the ice with the sharply protruding section of its head." end def self.egg_hatch_distance 5 end def self.evolves_into Pokemongodb::Pokemon::Dewgong end def self.flee_rate 0.09 end def self.height 1.1 end def self.max_cp 1107.03 end def self.moves [ Pokemongodb::Move::Lick, Pokemongodb::Move::IceShard, Pokemongodb::Move::AquaJet, Pokemongodb::Move::AquaTail, Pokemongodb::Move::IcyWind ] end def self.name "seel" end def self.types [ Pokemongodb::Type::Water ] end def self.weight 90.0 end end end end
true
89ee9ae0745f8a94bb6bc69bb868f4f55b560b2d
Ruby
everypolitician-scrapers/china-national-peoples-congress
/scraper.rb
UTF-8
1,262
2.53125
3
[]
no_license
#!/bin/env ruby # encoding: utf-8 # frozen_string_literal: true require 'pry' require 'scraped' require 'scraperwiki' def noko_for(url) Nokogiri::HTML(open(url).read) end def scrape_list(url) noko = noko_for(url) section = noko.css('h2').find { |h2| h2.text.include? '选举单位' } or raise "Can't find section" section.xpath('.//preceding::*').remove section_end = noko.css('h2').find { |h2| h2.text.include? '代表变动情况' } or raise "Can't find section end" section_end.xpath('.//following::*').remove noko.css('dl dt').each do |area| area.xpath('.//following::p').first.css('a').each do |person| data = { name: person.text, wikiname: person.attr('class') == 'new' ? '' : person.attr('title'), area: area.text.split('(').first.tidy, term: '12', } puts data.reject { |_, v| v.to_s.empty? }.sort_by { |k, _| k }.to_h if ENV['MORPH_DEBUG'] ScraperWiki.save_sqlite(%i(name wikiname area), data) end end end ScraperWiki.sqliteexecute('DELETE FROM data') rescue nil scrape_list('https://zh.wikipedia.org/wiki/%E7%AC%AC%E5%8D%81%E4%BA%8C%E5%B1%8A%E5%85%A8%E5%9B%BD%E4%BA%BA%E6%B0%91%E4%BB%A3%E8%A1%A8%E5%A4%A7%E4%BC%9A%E4%BB%A3%E8%A1%A8%E5%90%8D%E5%8D%95')
true