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
896346463075f2de11c5bb0eaa4af0ef7997f3ca
Ruby
krastina/date_night
/lib/date_night.rb
UTF-8
1,829
3.875
4
[]
no_license
require_relative "binary_search_tree" tree = BinarySearchTree.new puts "Welcome to date night!" puts "Type 'commands' to see available tree methods." puts "Type 'quit' to leave date night." input = nil until input == "quit" input = gets.chomp case input when "commands" then puts "You can: insert, include?, depth_of, max, min, sort, load, health, leaves, or height" when "depth_of" puts "Please enter movie score: " score = gets.chomp.to_i puts "The depth of #{score} is #{tree.depth_of(score)}" when "health" puts "Please indicate depth: " depth = gets.chomp.to_i puts "Reporting health at depth #{depth}: #{tree.health(depth)}" when "height" puts "Tree height is: #{height}" when "insert" puts "Please enter movie title: " title = gets.chomp puts "Please enter movie score: " score = gets.chomp.to_i puts "#{title} was inserted at depth #{tree.insert(score, title)}" when "leaves" puts "Total tree leaves: #{tree.leaves}" when "load" puts "Please provide file to be loaded: " file = gets.chomp.to_s puts "Total titles loaded: #{tree.load(file)}" when "max" puts "Maximum tree value is: #{tree.max}" when "min" puts "Minimum tree value is: #{tree.min}" when "sort" puts "Sorted tree: #{tree.sort}" when "include?" puts "What score are you interested in?" score = gets.chomp.to_i puts tree.include?(score) ? "Score found!" : "Score not found!" else puts "Could not understand command! Try again." unless input == "quit" end end
true
0a94ee9c1d399479523122a6d4705a9ceebdd78b
Ruby
yuhanlyu/coding-challenge
/codeeval/email_validation.rb
UTF-8
154
2.6875
3
[]
no_license
File.open(ARGV[0]).each_line do |line| puts line.strip.match(/(?:^[^ @"<>]+|".*")@(?:[A-Z0-9]+?(?:-*[A-Z0-9]+)*\.)+[A-Z]+$/i) ? "true" : "false" end
true
e5bf303aab48c79e5507980d20d5695dac51d842
Ruby
sabtain93/rb_101_small_problems
/easy_1/03.rb
UTF-8
1,124
4.96875
5
[]
no_license
# Write a method that takes one argument, a positive int # and returns a list of the digits in that number # input = positive integer # output = list of integers (array) # Given a positive integer of any length # Split it up into an array # Each element in the array is a single digit in the integer # Put array into correct order def digit_list(integer) integer.digits.reverse end puts digit_list(12345) == [1, 2, 3, 4, 5] # => true puts digit_list(7) == [7] # => true puts digit_list(375290) == [3, 7, 5, 2, 9, 0] # => true puts digit_list(444) == [4, 4, 4] # => true # Option 2: # Convert the integer into a string # Convert the string into an array of chars # Iterate over the array # Convert each element back to an integer # Return the array of integers def digit_list2(num) digits = num.to_s.chars digits.map { |digit| digit.to_i } end puts digit_list2(12345) == [1, 2, 3, 4, 5] # => true puts digit_list2(7) == [7] # => true puts digit_list2(375290) == [3, 7, 5, 2, 9, 0] # => true puts digit_list2(444) == [4, 4, 4] # => true
true
c29654968c9f1e13dd8d3aa69aac5e7a0ddb12f1
Ruby
jcigale/classwork_review
/week1/rspec_exercise_5/lib/exercise.rb
UTF-8
459
3.515625
4
[]
no_license
def zip(*arrays) length = arrays.first.length zipped = [] (0...length).each do |i| zipped << arrays.map {|arr| arr[i]} end zipped end def prizz_proc(arr, prc1, prc2) arr.select do |ele| (prc1.call(ele) == true && prc2.call(ele) == false) || (prc1.call(ele) == false && prc2.call(ele) == true) end end def zany_zip(*arrays) arrays.sort_by {|arr| arr.length} max_len = arrays.last.length p max_len end
true
7c17298b3bb27a01c2bc9aa98928a0d245bf58e3
Ruby
jhund/rails-data-explorer
/lib/rails_data_explorer/statistics/rng_category.rb
UTF-8
1,571
3.109375
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- class RailsDataExplorer module Statistics # Responsibilities: # * Provide random categorical data. Useful for testing and demo data. # class RngCategory # @param categories [Array<Object>] the pool of available categories. # @param category_probabilities [Array, optional] probability of each category. # @param rng [Proc, optional] lambda to generate random numbers which will # be mapped to categories. def initialize(categories, category_probabilities = nil, rng = lambda { Kernel.rand }) @categories, @category_probabilities, @rng = categories, category_probabilities, rng @category_probabilities ||= @categories.map { |e| @rng.call } @category_probabilities = normalize_category_probabilities @category_order = compute_category_order end # Returns a random category def rand r_v = @rng.call rnd = @category_order.detect { |e| e[:threshold] >= r_v } rnd[:category] end protected def normalize_category_probabilities total = @category_probabilities.inject(0) { |m,e| m += e } @category_probabilities.map { |e| e / total.to_f } end def compute_category_order category_order = [] running_sum = 0 @categories.each_with_index { |e, idx| running_sum += @category_probabilities[idx] category_order << { category: e, threshold: running_sum } } category_order end end end end
true
f04ad92d154c60f7c1091d9b307feba40f759770
Ruby
Tambi-Mat/oystercard
/spec/station_spec.rb
UTF-8
301
2.515625
3
[]
no_license
require 'station' describe Station do subject(:station) { described_class.new("Paddington",1)} it 'has a name attribute on initialization' do expect(station.station_name).to eq "Paddington" end it 'has a zone attribute on initialization' do expect(station.zone).to eq 1 end end
true
c17ecf10614e4df0feefa153d54787b0e5754081
Ruby
tarun-pacifica/wdi6
/angela_mikulasev/mta1/mta_multi.rb
UTF-8
1,115
3.59375
4
[]
no_license
# given that I am on Line N # and I am at station 28th # When I change to station 6th on line L # I should have stopped at 3 stations lines = { 'n' => ['Times Square', '34th', '28th', '23rd', 'Union Square', '8th'], 'l' => ['8th', '6th', 'Union Square', '3rd', '1st'], '6' => ['Grand Central', '33rd', '28th', 'Union Square', 'Astor Place'] } puts "Enter the departure line (#{lines.keys.join(', ')}): " departure_line = gets.chomp departure_stations = lines[departure_line] puts "Enter the departure station (#{departure_stations.join(', ')}): " departure_station = gets.chomp puts "Enter the destination line (#{lines.keys.join(', ')}): " destination_line = gets.chomp destination_stations = lines[destination_line] puts "Enter the destination station (#{destination_stations.join(', ')}): " destination_station = gets.chomp number_of_stations = ((departure_stations.index('Union Square') - departure_stations.index(departure_station)).abs) + ((destination_stations.index('Union Square') - destination_stations.index(destination_station)).abs) puts "total number of stations: #{number_of_stations}"
true
32f6cba67c9ada274b9d4b71e2733a3d2abbb7ef
Ruby
scotdalton/ceely
/lib/ceely/scales/ptolemaic.rb
UTF-8
1,265
2.84375
3
[ "MIT" ]
permissive
module Ceely module Scales module Ptolemaic # A Ptolemaic::Note is a Pythagorean Note # but tweaked class Note < Ceely::Scales::Pythagorean::Note def octave_adjusted_factor @octave_adjusted_factor ||= case index when -5, -4, -3 syntonic_comma * super when 3, 4, 5 (1/syntonic_comma) * super when 6 diminished_fifth_factor else super end end def diminished_fifth_factor return @diminished_fifth_factor if defined? @diminished_fifth_factor pythagorean_f = pythagorean.note_by_name("F") harmonic_b = harmonic.note_by_name("B") @diminished_fifth_factor = harmonic_b.interval(pythagorean_f ) * 2 end end # A Ptolemaic::Scale is a Pythagorean::Scale # adjusted by Ptolemy for consonance. class Scale < Ceely::Scales::Pythagorean::Scale NOTE_NAMES = %w{ C Db D Eb E F F# G Ab A Bb B } NOTE_TYPES = %w{ 1 m2 2 m3 M3 4 b5 5 m6 M6 m7 M7 } def initialize(fundamental_frequency=528.0, *args) super(fundamental_frequency, 12, -5, NOTE_NAMES, NOTE_TYPES) end end end end end
true
ec413261e9d34baa06a3dd157d0fef4ee8f64bfc
Ruby
VidgarVii/Thinknetica
/Base Ruby/lesson_3_OOP/lib/cargo_wagon.rb
UTF-8
479
3.328125
3
[]
no_license
class CargoWagon < Wagon attr_reader :free_volume, :occupied_volume alias free free_volume alias occupied occupied_volume def initialize(volume = 86.4) super('cargo') @free_volume = volume @occupied_volume = 0 end def take_volume(volume) check_free_volume!(volume) @free_volume -= volume @occupied_volume += volume end private def check_free_volume!(volume) raise 'Мест нет' if (@free_volume - volume).negative? end end
true
af3667f613f10a55a6e4d5b4b4adbca27130a06d
Ruby
failure-driven/remote-button
/lib/tasks/quote_fake.rake
UTF-8
1,446
3.046875
3
[]
no_license
# rails fetch_quotes[https://source.of.quotes.url] desc "fetch quotes" task :fetch_quotes, %i[quote_url] => :environment do |_, args| quote_url = args[:quote_url] doc = Nokogiri::HTML(URI.parse(quote_url).open.read) quotes = doc.search("ol").map do |ol| ol.search("li span") .map(&:text) .map(&:strip) end quotes .flatten .filter { |quote| quote[0] == "“" } .each do |quote| # puts quote.gsub("“", "").gsub(/”.*$/, "") # rubocop:disable Style/AsciiComments puts quote end # next find the subject (noun) # next replace subject with text "button" # maybe using python TextBlob # # pip3 install TextBlob # python3 # >>> from textblob import TextBlob # >>> txt = """Natural language processing (NLP) is a field of computer # science, artificial intelligence, and computational linguistics concerned # with the inter actions between computers and human (natural) # languages.""" # >>> blob = TextBlob(txt) # >>> print(blob.noun_phrases) # # OR # # pip3 install nltk # python3 # import nltk # lines = 'lines is some string of words' # # function to test if something is a noun # is_noun = lambda pos: pos[:2] == 'NN' # # do the nlp stuff # tokenized = nltk.word_tokenize(lines) # nouns = [word for (word, pos) in nltk.pos_tag(tokenized) if is_noun(pos)] # print nouns # ['lines', 'string', 'words'] end
true
867fe5d1a1213c619997eea428f3ee29bc135cfe
Ruby
Far-Traveller/THP_projects
/w04_d1_gossip_project_sinatra/lib/gossip.rb
UTF-8
1,486
3.3125
3
[]
no_license
require 'csv' class Gossip attr_accessor :author, :content def initialize(author, content) @author = author @content = content end def save #append mode (ab) : permet d'ajouter CSV.open("./db/gossip.csv", "ab") do |csv| csv << [@author,@content] end end def self.all all_gossips = [] # lis le csv ligne par ligne et les implémente dans l'array all_gossips CSV.read("./db/gossip.csv").each do |csv_line| all_gossips << Gossip.new(csv_line[0], csv_line[1]) end return all_gossips end def self.find(id) gossips_id = [] CSV.read("./db/gossip.csv").each_with_index do |row, index| #va vérifier si l'index de chaque gossip est égal à l'id demandé, si oui il le mets dans l'array if (id == index+1) gossips_id << Gossip.new(row[0], row[1]) break end end return gossips_id end def self.update(id, author, content) edit_gossip = [] #il faut recréer un array et un csv avec les nouvelles données CSV.read("./db/gossip.csv").each_with_index do |row, index| if id.to_i == (index + 1) edit_gossip << [author, content] else #je ne comprends pas cette ligne là, mais sans ça ne fonctionne pas et personne n'a réussi à me l'expliquer.. edit_gossip << [row[0], row[1]] end end # le w c'est pour write CSV.open("./db/gossip.csv", "w") do |csv| edit_gossip.each do |row| csv << row end end end end
true
1973bb013a8f939ac3cf3270c1d66e88e6bb9b49
Ruby
Vishal0203/really-simple-history-api
/parse-wikipedia.rb
UTF-8
3,663
2.53125
3
[]
no_license
#!/usr/bin/env ruby require "rubygems" require "bundler/setup" require 'rest_client' require 'media_wiki' require 'json' mw = MediaWiki::Gateway.new('http://en.wikipedia.org/w/api.php') span = Date.new(2000, 1, 1)..Date.new(2000, 12, 31) span.each { |x| actual_date = x.strftime("%m-%d") wiki_date = x.strftime("%B %e").gsub(/ +/, ' ') puts wiki_date cat = "" data = {} wikitext = mw.get(wiki_date) File.open("data/#{actual_date}.wiki", 'w') {|f| f.write(wikitext) } cats_to_ignore = ["", "Holidays and observances", "External links", "References"] wikitext.each_line { |line| line.chomp! tmp = line.match /\=\=([^\=]+)\=\=/ if tmp != nil cat = tmp[1].rstrip.lstrip data[cat] = [] unless cats_to_ignore.include?(cat) elsif line[0,1] == "*" and !cats_to_ignore.include?(cat) url = nil url_match = line[1..-1].match /\[\[([^\|\]]+)\|([^\]]+)\]\]/ url = "http://wikipedia.org/wiki/#{$2.gsub(/ /, '_')}" unless url_match.nil? or ! url.nil? tmp = line[1..-1].gsub(/\[\[([^\|\]]+)\|([^\]]+)\]\]/) { |link| $2 }. gsub(/''/, "'"). gsub(/\]\]/, ""). gsub(/\[\[/, ""). gsub(/\&ndash;/, "-"). gsub(/ +/, ' '). lstrip.rstrip.gsub(/\{\{([^\}]+)\}\}/) { |special| stuff = $1.split("|") type = stuff.first result = case when type == "by" stuff.last when ["cite", "cite news"].include?(type) "" when type == "city-state" stuff.join(", ") when type.downcase == "convert" "#{stuff[1]} #{stuff[2]}" when type == "frac" "#{stuff[1]}/#{stuff[2]}" when type == "lang-de" stuff.last when type == "mdash" "--" when type == "NYT" when type == "okina" "okina" when type == "RailGauge" "4ft 8.5in" when type == "Sclass" "#{stuff[1]}-class #{stuff[2]}" when type.downcase == "ship" stuff[1,2].join(" ").rstrip.lstrip when type == "SMU" stuff[1] when type == "US$" stuff.join(" ") when ["HMAS", "HMS", "MS", "MV", "USS", "USCGC", "SS", "MS", "RMS"].include?(type) stuff = stuff.reject { |i| i == "" } if stuff.size <= 2 stuff.join(" ") # elsif stuff.size == 3 # "#{stuff[0, 2].join(" ")}" # (#{stuff[2]})" else stuff[0,2].join(" ") end end if result.nil? #puts "#{wiki_date} |#{cat}| #{type} #{special}" stuff.join(" ") else #puts "!! #{wiki_date} #{type} -> #{result}" result end } # tmp = line[1..-1].gsub(/\&ndash;/, "-").gsub(/ +/, ' ').lstrip.rstrip #puts tmp event_year, event_data = tmp.split(" - ") output = {:year => event_year, :text => event_data } # skipping URL output for now # output[:url] = url unless url.nil? data[cat] << output else # puts "!! #{cat} #{line}" end } results = { :date => wiki_date, :url => "http://wikipedia.org/wiki/#{wiki_date.gsub(/ /, '_')}", :data => data } File.open("data/#{actual_date}.json", 'w') {|f| f.write(results.to_json) } } # span.each
true
871aa5b371ccad702ac5829b018c1f90fa7126f1
Ruby
nanoaguayo/IIC3103-2017-G4
/IIC3103-G4-API/app/controllers/concerns/banco.rb
UTF-8
2,663
2.640625
3
[]
no_license
require 'rails/all' require 'openssl' require "base64" require 'httparty' module Banco BANK_URI = Rails.env.development? && "http://integracion-2017-dev.herokuapp.com/banco/" || Rails.env.production? && "https://integracion-2017-prod.herokuapp.com/banco/" CUENTA_URI = Rails.env.development? && "https://integracion-2017-dev.herokuapp.com/bodega/fabrica/getCuenta" || Rails.env.production? &&"https://integracion-2017-prod.herokuapp.com/bodega/fabrica/getCuenta" ID = Rails.env.development? && "590baa00d6b4ec000490246e" || Rails.env.production? && "5910c0910e42840004f6e68c" #cuenta nuestra def self.transferFab(monto) path = BANK_URI + "trx" cuenta = obtenerCuenta() header = {"Content-Type" => "application/json"} params = { "monto": monto, "origen": ID, "destino": cuenta } @result = HTTParty.put(path, :body => params, :header => header) case @result.code when 200 @trans = JSON.parse(@result.response.body) @transaction = Transaction.new(@trans) if @transaction.save then puts "Guardada con éxito" end end return @result end def self.transfer (monto, cuenta) path = BANK_URI + "trx" header = {"Content-Type" => "application/json"} params = { "monto": monto, "origen": ID, "destino": cuenta } @result = HTTParty.put(path, :body => params, :header => header) case @result.code when 200 @trans = JSON.parse(@result.response.body) @transaction = Transaction.new(@trans) if @transaction.save then puts "Guardada con éxito" end end return @result end def self.obtenerCuentaGrupo(id) path = BANK_URI + "cuenta/"+id header = {"Content-Type" => "application/json"} @result = HTTParty.get(path, :query => {}, :header => header) case @result.code when 200 @trans = JSON.parse(@result.response.body) end return @result end #Obtener cuenta de la fabrica (interno) def self.obtenerCuenta auth = Crypt.generarauth("GET") puts auth headers = {'Content-type' => 'application/json', 'Authorization' => auth} params = {} @result = HTTParty.get(CUENTA_URI, :headers => headers) cuenta = JSON.parse(@result.response.body) puts cuenta["cuentaId"] return cuenta["cuentaId"] end def self.obtenerTransferencia(id) path = BANK_URI + "trx/"+id header = {"Content-Type" => "application/json"} @result = HTTParty.get(path, :query => {}, :header => header) case @result.code when 200 @trans = JSON.parse(@result.response.body) end return @trans end end
true
711336b4c2277bd067177e108cd842dedc5e1449
Ruby
state-machines/state_machines
/test/unit/branch/branch_with_multiple_implicit_requirements_test.rb
UTF-8
1,826
2.53125
3
[ "MIT" ]
permissive
require 'test_helper' class BranchWithMultipleImplicitRequirementsTest < StateMachinesTest def setup @object = Object.new @branch = StateMachines::Branch.new(parked: :idling, idling: :first_gear, on: :ignite) end def test_should_create_multiple_state_requirements assert_equal 2, @branch.state_requirements.length end def test_should_not_match_event_as_state_requirement refute @branch.matches?(@object, from: :on, to: :ignite) end def test_should_match_if_from_included_in_any assert @branch.matches?(@object, from: :parked) assert @branch.matches?(@object, from: :idling) end def test_should_not_match_if_from_not_included_in_any refute @branch.matches?(@object, from: :first_gear) end def test_should_match_if_to_included_in_any assert @branch.matches?(@object, to: :idling) assert @branch.matches?(@object, to: :first_gear) end def test_should_not_match_if_to_not_included_in_any refute @branch.matches?(@object, to: :parked) end def test_should_match_if_all_options_match assert @branch.matches?(@object, from: :parked, to: :idling, on: :ignite) assert @branch.matches?(@object, from: :idling, to: :first_gear, on: :ignite) end def test_should_not_match_if_any_options_do_not_match refute @branch.matches?(@object, from: :parked, to: :idling, on: :park) refute @branch.matches?(@object, from: :parked, to: :first_gear, on: :park) end def test_should_include_all_known_states assert_equal [:first_gear, :idling, :parked], @branch.known_states.sort_by { |state| state.to_s } end def test_should_not_duplicate_known_statse branch = StateMachines::Branch.new(parked: :idling, first_gear: :idling) assert_equal [:first_gear, :idling, :parked], branch.known_states.sort_by { |state| state.to_s } end end
true
9e5c215a36dc28afe3fb598b78f119af0f92d2e1
Ruby
ThomasRoest/ruby-practice
/ruby-basics/loops_iteration/iteration2.rb
UTF-8
420
4.09375
4
[]
no_license
puts 23 array = %w(dog cat giraf bob) array.each do |a| rev = a.reverse if rev == a puts a + " is a palindrome!" else puts a + " is not" end # puts "this is the word #{a} in reverse\n" # puts a.reverse # if end def fizz_buzz(num) num.times do |n| if n % 2 == 0 puts n puts " this Fizz" else puts n puts " this is Buzz" end end end fizz_buzz(100)
true
913babfda842138866c6b995dfc784722b850d0e
Ruby
nixworks/big-o
/lib/big-o/exceptions.rb
UTF-8
1,055
3.171875
3
[ "MIT" ]
permissive
module BigO # The function could not be run more than X times (where X is a configurable value). # # This exception happens if the function is too slow to run, or if the timeout is too short. class SmallResultSetError < StandardError # Sets default message. # # @param [Integer] resultset_size number of values the result set contains. # @return [SmallResultSetError] def initialize(resultset_size) super "Less than #{resultset_size} values could be retrieved." + " Try using longer timeout or a different range. (function complexity may be too high)" end end # The function runs too fast and can't be quantified by our measurement tool. # # To fix this error, it is possible to augment the number of times the function should run. class InstantaneousExecutionError < StandardError # Sets default message. # # @return [InstantaneousExecutionError] def initialize super "Function execution time can't be quantified. (execution speed close to instantaneous)" end end end
true
4f11939d6ad07c5810f8ec868210b6214dbe6221
Ruby
cmarion-mq/S03-J1
/tests-ruby-master/lib/02_calculator.rb
UTF-8
346
3.40625
3
[]
no_license
def add(x,y) return x.to_f + y.to_f end def subtract(x,y) return x.to_f - y.to_f end def sum(array) sum=0 return array.sum end def multiply(x,y) return x.to_f * y.to_f end def power(x,y) return x.to_f ** y.to_f end def factorial(n) if n == 0 return 1 else return (1..n).inject(:*) end end
true
3672792d10ee964774c5a9edbe364f0a7750c326
Ruby
molenzwiebel/lambda
/lib/λ/ast.rb
UTF-8
2,147
3
3
[]
no_license
module Lambda class Visitor def visit_any(node) nil end end class ASTNode attr_accessor :filename, :line def self.attrs(*fields) attr_accessor *fields define_method "==" do |other| return false unless other.class == self.class eq = true fields.each do |field| eq &&= self.send(field) == other.send(field) end return eq end class_eval %Q( def initialize(#{fields.map(&:to_s).join ", "}) #{fields.map(&:to_s).map{|x| x.include?("body") ? "@#{x} = Body.from #{x}" : "@#{x} = #{x}"}.join("\n")} end ) end def self.inherited(klass) name = klass.name.split('::').last.gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').gsub(/([a-z\d])([A-Z])/,'\1_\2').tr("-", "_").downcase klass.class_eval %Q( def accept(visitor) visitor.visit_any(self) || visitor.visit_#{name}(self) end ) Visitor.class_eval %Q( def visit_#{name}(node) nil end ) end def raise(msg) Kernel::raise "#{filename}##{line}: #{msg}" end end class Body < ASTNode include Enumerable attrs :contents def self.from(other) return Body.new [] if other.nil? return other if other.is_a? Body return Body.new other if other.is_a? ::Array Body.new [other] end def each(&block) contents.each &block end end class Ident < ASTNode attrs :name end class Num < ASTNode attrs :value end class Binary < ASTNode attrs :left, :op, :right end class LambdaDef < ASTNode attrs :name, :args, :body end class Call < ASTNode attrs :target, :args end class If < ASTNode attrs :cond, :if_body, :else_body end end
true
c0cb0c672c197301d31262d8d16ef53bb673e2cd
Ruby
lvivdev/lesson2
/app3.rb
UTF-8
188
3.921875
4
[]
no_license
print "Enter your name: " myname = gets.chomp puts "Hello " + myname print "Enter your age: " age = gets.chomp puts "Your age is " + age print "Hello #{myname} your age is #{age} "
true
a83c998775fc712e8fc5b2b0924cd61d269d5f2a
Ruby
RavensKrag/rubyOF
/bin/projects/livecode2/lib/UI_model.rb
UTF-8
893
2.625
3
[]
no_license
class UI_Model def initialize super() @step_delay = 10 @step_i = 0 end state_machine :update_mode, :initial => :manual_stepping do state :manual_stepping do end state :auto_stepping do end state :running do end # ---------- event :shift_manual do transition any => :manual_stepping end event :shift_auto do transition any => :auto_stepping end event :shift_run do transition any => :running end end def auto_step? if update_mode_name == :auto_stepping out = if @step_i == 0 true else false end # periodic counter @step_i += 1; @step_i = @step_i % @step_delay return out else return false end end end
true
87c79592aaf486357a36ea4cbb11969c3fad70e8
Ruby
SuelyBarreto/slack-cli
/lib/workspace.rb
UTF-8
1,240
3.203125
3
[]
no_license
require_relative 'user' require_relative 'channel' class Workspace # Generator attr_reader :users, :channels, :selected # Constructor def initialize @users = User.list_all @channels = Channel.list_all @selected = nil end # Method to select a channel def select_channel(param) raise ArgumentError, "Channel name or id must be a string" unless param.is_a?(String) @selected = @channels.find { |channel| channel.id == param || channel.name == param } raise ArgumentError, "Channel not found" if @selected == nil end # Method to select a user def select_user(param) raise ArgumentError, "User name or id must be a string" unless param.is_a?(String) @selected = @users.find { |user| user.id == param || user.name == param } raise ArgumentError, "User not found" if @selected == nil end # Method to show details of the selected user or channel def show_details raise ArgumentError, "Nothing is selected" if @selected == nil return @selected.details end # Method to send a message to the selected user or channel def send_message(msg) raise ArgumentError, "Nothing is selected" if @selected == nil return @selected.send_message(msg) end end # Class
true
e07f85336f5a426b68acb5118456e62f3b162f25
Ruby
schacon/retrospectiva
/vendor/plugins/wiki_engine/lib/wiki_engine/engines.rb
UTF-8
5,799
2.796875
3
[ "MIT", "MIT-0" ]
permissive
module WikiEngine class AbstractEngine def markup_examples examples = ActiveSupport::OrderedHash.new examples[_('Paragraphs')] = [] examples[_('Headers')] = [] examples[_('Formats')] = [] examples[_('Blocks')] = [] examples[_('Lists')] = [] examples[_('Links')] = [] examples[_('References')] = [] examples[_('Tables')] = [] examples end def markup raise "Abstract method" end def link_all(text, &block) WikiEngine.with_text_parts_only(text) do |token| token.gsub(link_pattern) do |match| prefix, page, title = $1, $2, $3 page = page.gsub(%r{ +}, ' ').strip title = title.blank? ? page : title.strip page.starts_with?('\\') ? match.gsub(/\\/, '') : yield(match, prefix, page, title) end end end def link_pattern %r{ \[\[ (?:(F|I)[\|\:])? (\\?[ \w-]{2,}) (?:[\|\:]([^\]]+))? \]\] }x end end class TextileBasedEngine < AbstractEngine def markup_examples examples = super examples[_('Paragraphs')] = [ "A single paragraph\n\nFollowed by another", "p. A single paragraph\n\np. Followed by another", "p<. A left-aligned paragraph", "p>. A right-aligned paragraph", "p=. A centered paragraph", "p<>. A justified paragraph", "p(. A left idented paragraph", "p((. A stronger left idented paragraph", "p>). A right aligned & idented paragraph", "I spoke.\nAnd none replied\n\nI spoke. And none replied" ] examples[_('Headers')] = [ "h1. Header 1\n\nh2. Header 2\n\nh3. Header 3" ] examples[_('Blocks')] = [ "bq. A block quotation", ] examples[_('Lists')] = [ "# Fuel could be:\n## Coal\n## Gasoline\n## Electricity", "* Fuel could be:\n** Coal\n** Gasoline\n** Electricity" ] examples[_('Links')] = [ "You can find Retrospectiva\nunder http://www.retrospectiva.org", "Please visit\n\"Retrospectiva\":http://www.retrospectiva.org\nfor more information", ] examples[_('References')] = [ "!http://www.retrospectiva.org/images/logo_small.png!" ] examples[_('Tables')] = [ "| name | age | sex |\n| joan | 24 | f |\n| archie | 29 | m |\n| bella | 45 | f |", "|_. name |_. age |_. sex |\n| joan | 24 | f |\n| archie | 29 | m |\n| bella | 45 | f |", "|_. attribute list |\n|<. align left |\n|>. align right|\n|=. align center |\n|<>. align justify |\n|^. valign top |\n|~. valign bottom |", "|\\2. two column span |\n| col 1 | col 2 |" ] examples[_('Formats')] = [ "strong: I *believe* every word\n\n"+ "emphased: I _believe_ every word\n\n" + "citation: I ??believe?? every word\n\n" + "inserted: I +believe+ every word\n\n" + "deleted: I -believe- every word\n\n" + "superscript: I ^believe^ every word\n\n" + "subscript: I ~believe~ every word\n\n" + "inline-code: I @believe@ every word" ] examples end end class TextileEngine < TextileBasedEngine def markup(text) RedCloth.new(text, [:sanitize_html, :filter_styles, :filter_classes, :filter_ids]).to_html end end class RetroEngine < TextileBasedEngine def markup_examples examples = super examples[_('Paragraphs')] += [ "I spoke.[[BR]]And none replied" ] examples[_('Headers')] += [ "= Header 1 =\n\n== Header 2 ==\n\n=== Header 3 ===" ] examples[_('Blocks')] += [ "bc. A code block", "{{{\n public String toString() {\n this.entity.getNodeName();\n }\n}}}" ] examples end def markup(text) WikiEngine::Retro.new(text).to_html end end class MarkDownEngine < AbstractEngine def markup_examples examples = super examples[_('Paragraphs')] = [ "I spoke.\nAnd none replied\n\nI spoke. And none replied", "Insert two spaces at the end of the line \nto force a line break" ] examples[_('Headers')] = [ "# Header 1#\n\n## Header 2##\n\n### Header 3###" ] examples[_('Formats')] = [ "strong: I **believe** every word\n\n"+ "emphased: I *believe* every word\n\n" + "inline-code: I `believe` every word" ] examples[_('Links')] = [ "An inline link to\n[Retrospectiva](http://retrospectiva.org/).", ] examples[_('Blocks')] = [ "> A block quotation", "This is a normal paragraph:\n\n This is a code block" ] examples[_('Lists')] = [ "* Fuel could be:\n * Coal\n * Gasoline\n * Electricity", "1. Fuel could be:\n 1. Coal\n 2. Gasoline\n 3. Electricity" ] examples end def markup(text) BlueCloth.new(text).to_html end end class RDocEngine < AbstractEngine def markup_examples examples = super examples[_('Headers')] = [ "= Header 1\n\n== Header 2\n\n=== Header 3" ] examples[_('Formats')] = [ "strong: I *believe* every word", "emphased: I _believe_ every word" ] examples[_('Links')] = [ "You can find Retrospectiva\nunder http://www.retrospectiva.org", ] examples[_('Lists')] = [ "* Fuel could be:\n * Coal\n * Gasoline\n * Electricity", "Fuel could be:\n1. Coal\n2. Gasoline\n3. Electricity" ] examples end def markup(text) WikiEngine::RDoc.new(text).to_html end end end
true
a1428059bf60265ae5515af7cbe8ac69b487bbe7
Ruby
tstrachota/hammer-tests
/lib/utils.rb
UTF-8
87
2.53125
3
[]
no_license
class Hash def slice(*keys) Hash[select { |k, v| keys.include?(k) }] end end
true
79ccfe32ef09690df9d79d622f63ab4e05a5c428
Ruby
xldenis/dynamit
/app/models/user.rb
UTF-8
984
2.53125
3
[]
no_license
class User include Mongoid::Document has_many :sources has_many :posts def self.find_or_create_by_hash(auth_hash) @user = nil @source = Source.where(:provider => auth_hash["provider"], :identifier => auth_hash["uid"]) if @source.first #assert only one source @user = @source.first.user else if @user = User.create @source = @user.sources.new( provider: auth_hash["provider"], identifier: auth_hash["username"], token: auth_hash["credentials"]["token"], secret: auth_hash["credentials"]["secret"], expire_time: auth_hash["credentials"]["expires_at"] ) @source.user = @user if @source.save @user else @user.destroy #error saving source end end #couldnt create user, error end end @user end end
true
486d34c1106492a10a78656b1100d1db08a7c984
Ruby
johnfelipe/dashboard
/test/models/user_test.rb
UTF-8
1,929
2.671875
3
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
require 'test_helper' class UserTest < ActiveSupport::TestCase test "validations" do good_data = { email: 'foo@bar.com', password: 'foosbars', username: 'user.12-34', name: 'tester'} user = User.create(good_data.merge({email: 'foo@bar'})) assert user.errors.messages.length == 1 user = User.create(good_data.merge({username: 'tiny'})) assert user.errors.messages.length == 1 user = User.create(good_data.merge({username: 'superreallydoublelongusername'})) assert user.errors.messages.length == 1 user = User.create(good_data.merge({username: 'bo gus'})) assert user.errors.messages.length == 1 # actually create a user user = User.create(good_data) #puts user.errors.messages.inspect assert user.valid? user = User.create(good_data.merge({email: 'FOO@bar.com', username: 'user.12-35'})) assert user.errors.messages.length == 1, "Email should be rejected as a dup" user = User.create(good_data.merge({email: 'OTHER@bar.com', username: 'USER.12-34'})) assert user.errors.messages.length == 1, "username should be rejected as a dup" end test "birthday validation" do good_data = { email: 'foo@bar.com', password: 'foosbars', username: 'user.12-34', name: 'tester'} assert_no_difference('User.count') do # birthday in the future (this date is actually a mysql error) user = User.create(good_data.merge({birthday: '03/04/20140'})) assert user.errors.messages.length == 1, "Invalid birthday should be rejected" end assert_difference('User.count') do user = User.create(good_data.merge({birthday: 'xxxxx'})) # if it's totally invalid just ignore it assert_equal nil, user.birthday end assert_difference('User.count') do user = User.create(good_data.merge({birthday: '03/04/2010', username: 'anewone', email: 'new@email.com'})) assert_equal Date.new(2010, 4, 3), user.birthday end end end
true
a5dae337a4ab7f4320ad4d7337bf49500ecfbde8
Ruby
pj0616/download-archive-2
/CONTAINER/App-Academy-master/Intro To Programming/Array Methods/abbreviate_sentence.rb
UTF-8
724
4.78125
5
[]
no_license
# Write a method abbreviate_sentence that takes in a sentence string and returns a new sentence # where every word longer than 4 characters has all of it's vowels removed. def abbreviate_sentence(str) words = str.split(" ") new_words = [] words.each do |word| if word.length > 4 new_word = "" word.each_char do |char| if !["a", "e", "i", "o", "u"].include?(char) new_word << char end end new_words << new_word else new_words << word end end return new_words.join(" ") end puts abbreviate_sentence("follow the yellow brick road") # => "fllw the yllw brck road" puts abbreviate_sentence("what a wonderful life") # => "what a wndrfl life"
true
a864e7a74bfb19e2c53b3f45f3c56f10070ca422
Ruby
johnbagley/ruby
/change_calculator.rb
UTF-8
479
3.421875
3
[]
no_license
quarter = 25 dime = 10 nickel = 5 penny = 1 cash = 1234.23 * 100 number_of_quarters = (cash / quarter).floor cash = cash - number_of_quarters * 25.0 number_of_dimes = (cash / 10).floor cash = cash - number_of_dimes * 10.0 number_of_nickels = (cash / 5).floor cash = cash - number_of_nickels * 5.0 number_of_pennies = cash.floor puts "#{number_of_quarters} quarters" puts "#{number_of_dimes} dimes" puts "#{number_of_nickels} nickels" puts "#{number_of_pennies} pennies"
true
2c4fa02be04b85083d4522dff78026ae233f0287
Ruby
sesposito/bowling-api
/app/interactors/update_game_status.rb
UTF-8
1,403
2.546875
3
[]
no_license
# frozen_string_literal: true class UpdateGameStatus def initialize( game:, throw:, current_frame:, frame_repository: FrameRepository, game_repository: GameRepository, frame_status_class: FrameStatus ) @game = game @throw = throw @current_frame = current_frame @frame_repository = frame_repository @game_repository = game_repository @frame_status = frame_status_class end def call frame_results = frame_status.new(frame: current_frame, throw: throw).call frame_repository.update!( frame: current_frame, data: frame_results ) update_previous_frames_scores if final_frame? && frame_results[:ended] game_repository.end_game!(game: game) elsif frame_results[:ended] create_new_frame end end private attr_reader :game, :throw, :current_frame, :frame_repository, :game_repository, :frame_status def final_frame? current_frame.number == 10 end def update_previous_frames_scores frame_repository.update_previous_frames_scores!( game_id: game.id, frame_number: current_frame.number, points: throw.points ) end def create_new_frame new_frame_number = current_frame.number + 1 game_repository.update_current_frame_number!(game: game, number: new_frame_number) frame_repository.create!(game_id: game.id, number: new_frame_number) end end
true
8007545d3bb735c8be4fbb933cb1b45b24a22785
Ruby
magas4891/test_w
/lib/rule.rb
UTF-8
575
3.203125
3
[]
no_license
class Rule def apply(basket, **args) total_price = basket.inject(0) { |sum, item| sum += item[:price] } if args.has_key?(:item) multi_price(basket, args) elsif args.has_key?(:basket_total) return args[:discount] if total_price >= args[:basket_total] 0 end end def multi_price(basket, **args) items_arr = basket.select { |item| item[:name] == args[:item] } if items_arr.length >= args[:quantity] value = items_arr.inject(0) { |sum, it| sum += it[:price] } return value - args[:total_price] end 0 end end
true
0374454b7e284a1a4810275de65884ba0c846835
Ruby
siuying/mtrupdate_analyze
/lib/mtrupdate/raw_importer.rb
UTF-8
1,880
2.78125
3
[]
no_license
require 'twitter' module Mtrupdate # Import raw mtrupdate data from twitter class RawImporter attr_reader :twitter, :path attr_reader :username def initialize(twitter, path, username="mtrupdate") @twitter = twitter @path = path @username = username end # Find the maximum tweet id in the path def last_tweet_id filenames = Dir["#{path}/*.json"] last_id = filenames.collect {|filename| filename.match(%r{^data/raw/([0-9]+)\.json$})[1].to_i }.sort.last rescue nil return last_id ? last_id.to_s : nil end # Find all tweets from user timeline # # since_id - only update tweets after specific twitter id def save_all_tweets(since_id=nil) user = twitter.user(username) collect_with_max_id do |max_id| options = {:count => 200, :include_rts => false} options[:max_id] = max_id unless max_id.nil? options[:since_id] = since_id unless since_id.nil? tweets = twitter.user_timeline(user, options) tweets.each do |tweet| save_tweet(tweet) end end end # Save a tweet to disk, using the tweet id + .json as filename, to the path of the importer def save_tweet(tweet) data = { :id => tweet.id, :text => tweet.text, :created_at => tweet.created_at, :lang => tweet.lang, :reply_to => tweet.in_reply_to_screen_name } fullpath = File.join(path, "#{tweet.id}.json") json = JSON.pretty_generate(data) File.open(fullpath, 'w') { |file| file.write(json) } end private def collect_with_max_id(collection=[], max_id=nil, &block) response = yield max_id collection += response response.empty? ? collection.flatten : collect_with_max_id(collection, response.last.id - 1, &block) end end end
true
fd98f70afa73093b6d2766a59b9bc87c2c4968ab
Ruby
jsoong1962/prime-ruby-nyc-web-080618
/prime.rb
UTF-8
283
2.984375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Add code here! def prime?(int) array = Array (2...int) value = true if int < 2 value = false elsif int == 2 value else index = 0 while index < array.size if int % array[index] == 0 value = false end index += 1 end end value end
true
33230c66b6d7cf15497867f9b30d04116c73791d
Ruby
jjgutierrez0314/CSC600-Ruby-HW
/Question2.rb
UTF-8
977
4.0625
4
[]
no_license
class Array def limited(amin,amax,array) if amin <= array.min && amax >= array.max return true else return false end end def sorted(array) count1 = 0 count2 = 0 0.upto(array.length-2) { |index| if array[index] == array[index+1] count1 += 1 count2 += 1 elsif array[index] < array[index+1] count1 += 1 elsif array[index] > array[index+1] count2 += 1 end } if(count1 == array.length-1) return '+1' elsif (count2 == array.length-1) return '-1' else return '0' end end end array = [1,2,3,4,5] array1 = [5,4,3,2,1] array2 = [1,7,2,8,0] puts Array.new.sorted(array) puts Array.new.sorted(array1) puts Array.new.sorted(array2) puts Array.new.limited(1,5,array) puts Array.new.limited(2,4,array)
true
a87b9950454e63e707726c1930216423c349e02e
Ruby
Jhowden/chess
/spec/board_setup_commands_spec.rb
UTF-8
3,052
2.640625
3
[]
no_license
require 'spec_helper' describe BoardSetupCommands do let(:board) { double() } let(:player) { double() } let(:piece) { double() } let(:user_commands) { double() } let(:game) { Game.new( board, user_commands ).extend( described_class ) } describe "#set_player_team" do it "instantiates a player object" do expect( game.set_player_team( "white" ) ). to be_an_instance_of Player end end describe "#create_team" do it "creates a team of 16 pieces" do expect( game.create_team( :black ).size ).to eq( 16 ) end it "creates a piece with the right attribuets" do pawn = game.create_team( :black ).first expect( pawn.team ).to eq( :black ) expect( pawn.position.file ).to eq( "a" ) expect( pawn.position.rank ).to eq( 2 ) expect( pawn.board_marker ).to eq( "♟" ) expect( pawn.orientation ).to eq( :up ) expect( pawn.en_passant ).to be_an_instance_of EnPassant end end describe "#place_pieces_on_board" do it "populates the board with the player's pieces" do expect( board ).to receive( :place_pieces_on_board ).with player game.place_pieces_on_board player end end describe "#set_players_team_pieces" do it "sets the player's pieces array with the newly created pieces" do allow( player ).to receive( :find_king_piece ) expect( player ).to receive( :set_team_pieces ).with [piece] game.set_players_team_pieces( player, [piece] ) end it "find and sets the player's king piece" do allow( player ).to receive( :set_team_pieces ).with [piece] expect( player ).to receive( :find_king_piece ) game.set_players_team_pieces( player, [piece] ) end end describe "#set_up_players_half_of_board" do it "places the pieces on the board" do allow( player ).to receive( :set_team_pieces ) allow( player ).to receive( :find_king_piece ) expect( board ).to receive( :place_pieces_on_board ).with player game.set_up_players_half_of_board( :black, player ) end it "sets the needed pieces on the player" do allow( board ).to receive( :place_pieces_on_board ) expect( player ).to receive( :set_team_pieces ) expect( player ).to receive( :find_king_piece ) game.set_up_players_half_of_board( :black, player ) end end describe "#get_player_teams" do before( :each ) do allow( STDOUT ).to receive( :puts ) allow( Player ).to receive( :set_team_pieces ) allow( Player ).to receive( :find_king_piece ) allow( board ).to receive( :place_pieces_on_board ) allow( user_commands ).to receive( :user_team_input ).and_return "black" end it "gets the team color" do expect( user_commands ).to receive( :user_team_input ).and_return "black" game.get_player_teams end it "sets the team color for each player" do game.get_player_teams expect( game.player1.team ).to eq( :black ) expect( game.player2.team ).to eq( :white ) end end end
true
694af82da32c50540d016fd7c2cd7811b036d013
Ruby
burke/coderetreat
/session3/lib/universe.rb
UTF-8
719
3.5625
4
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
class Universe def initialize @grid = {} end def get_cell_at(x, y) return nil unless @grid[x] @grid[x][y] end def set_alive_at(x, y) @grid[x] ||= {} @grid[x][y] = Cell.alive end def evolve @grid.each do |x, hash| hash.each do |y, cell| cell.tick(number_of_live_neighbours_at(x,y)) end end end def number_of_live_neighbours_at(x,y) [ get_cell_at(x + 1, y + 1), get_cell_at(x + 1, y), get_cell_at(x + 1, y - 1), get_cell_at(x, y + 1), get_cell_at(x, y - 1), get_cell_at(x - 1, y + 1), get_cell_at(x - 1, y), get_cell_at(x - 1, y - 1) ].count { |cell| cell && cell.alive? } end end
true
40bd9d729778f1849f1010259f153dd46e0ee413
Ruby
ideeli/ideeli_spinup
/spec/hostname.rb
UTF-8
950
2.703125
3
[]
no_license
require 'ideeli_spinup' describe IdeeliSpinup::Hostname do context "normal" do let(:hostname) { IdeeliSpinup::Hostname.new('foo12.bar.com') } describe '#to_s' do it "should return the hostname string" do hostname.to_s.should == "foo12.bar.com" end end describe '#each' do it "should return the first part of the hostname" do hostname.first.should == 'foo12' end end end context "numeric hostname" do let(:hostname) { IdeeliSpinup::Hostname.new('foo12.bar.com') } describe '#numeric_part' do it "should return the numeric part of the hostname" do hostname.numeric_part.should == 12 end end end context "non-numeric hostname" do let(:hostname) { IdeeliSpinup::Hostname.new('foo.bar.com') } describe '#numeric_part' do it "should return nil" do hostname.numeric_part.nil?.should be_true end end end end
true
a11174b6d19e88a864e3779be8b966f62421871e
Ruby
Plasmarobo/f.ragment
/app/helpers/fragment_api_helper.rb
UTF-8
2,862
2.71875
3
[]
no_license
module FragmentApiHelper COMMON_FRAGMENT_TYPES = [ "Data access", "Data read", "Data clear", "Data validate", "Conditional", "Log/Print", "Thread Start", "Collision", "Loop", "Scope", "End", "Push", "Pop", "Insert", "Remove", "Index" ] PLAYER_FRAGMENT_TYPES = [ "Data change", "Thread Sync", "Comment" ] SYSTEM_FRAGMENT_TYPES = [ "Chance", "Security Start", "Memory Page" ] ACCESS_TYPE = [ "Reg", "Mem" ] def blocks_to_js(blocks) javascript = "" while(!blocks.empty?) current_block = blocks.unshift fragment_refs = current_block.get_ordered_fragments javascript += self.fragment_refs_to_js(fragment_refs) end return javascript end def fragment_refs_to_js(fragment_refs) string = "" current_fragment_ref = fragment_refs.unshift if(!fragment_refs.empty?) #Check for threading/parallel fragments if fragment_refs.front.line == current_fragment_ref.line #Threaded! string += "fragment_thread( '#{current_fragment_ref.fragment.function}'" while(fragment_refs.front.line == current_fragment_ref.line) current_fragment_ref = fragment_refs.unshift string += ",\n '#{current_fragment_ref.fragment.function}'" end string += ");\n" else #Not threaded string += "#{current_fragment_ref.fragment.function};\n" end end return string += fragment_refs_to_js(fragment_refs) end def gen_player_fragment(workspace) #Select a player fragment at random fragment_domain = PLAYER_FRAGMENT_TYPES + COMMON_FRAGMENT_TYPES selection = Random.rand() % fragment_domain.size self.generate_fragment(fragment_domain[selection], workspace) end def gen_system_fragment(workspace) #Select a system fragment at random fragment_domain = SYSTEM_FRAGMENT_TYPES + COMMON_FRAGMENT_TYPES selection = Random.rand() % fragment_domain.size self.generate_fragment(fragment_domain[selection], workspace) end def generate_fragment(selector, workspace) case selection when "Data access" dest = self.get_random_location(workspace) source = self.get_random_location(workspace) when "Data read" when "Data clear" when "Data validate" when "Conditional" when "Log/Print" when "Thread Start" when "Collision" when "Loop" when "Scope" when "End" when "Push" when "Pop" when "Insert" when "Remove" when "Index" when "Data change" when "Thread Sync" when "Comment" when "Chance" when "Security Start" when "Memory Page" else end ] end def get_random_location(workspace) #Generate new variable? type = ACCESS_TYPE[Random.rand() % 2] end end
true
4b3f8ba1b375f9283e03ecebd52601c8455ca77a
Ruby
stemkit-collection/stemkit-util
/scripts/sk/subordinator.rb
UTF-8
3,913
3.03125
3
[ "MIT" ]
permissive
=begin vim: sw=2: Copyright (c) 2008, Gennady Bystritsky <bystr@mac.com> Distributed under the MIT Licence. This is free software. See 'LICENSE' for details. You must read and accept the license prior to use. Author: Gennady Bystritsky =end require 'set' require 'pp' module SK class Subordinator attr_reader :entries class CycleError < RuntimeError def initialize(entry) super "Cyclic dependency detected (#{entry.inspect})" end end def initialize(*items) @entries = [] normalize_and_order items, Hash.new { |_h, _k| _h[_k] = Set.new } end class << self def master_to_slave(*items) new(*items) end def slave_to_master(*items) master_to_slave *items.map { |_item| Array(Hash[*_item]).map { |_entry| _entry.reverse } } end end def slaves @entries.map { |_entry| _entry.last }.flatten end def masters @entries.map { |_entry| _entry.first } end def lineup(*items) pickup(*figure_items_for_lineup(items)).flatten.uniq end private ####### def figure_items_for_lineup(items) items.empty? ? masters : (entries.flatten & items) end def pickup(*items) items.map { |_item| [ _item, pickup(*Array(Array(@entries.assoc(_item)).last)) ] } end def normalize_and_order items, hash items.each do |_item| Hash[*_item.flatten].each do |_master, _slave| hash[_master] << _slave end end order Array(hash) end def order(array) processed = Hash.new { |_h, _k| _h[_k] = 0 } while entry = array.shift if array.detect { |_item| _item.last.include? entry.first } raise CycleError, entry if processed[entry] > 10 processed[entry] += 1 array << entry else @entries << [ entry.first, entry.last.to_a ] end end end end end if $0 == __FILE__ require 'test/unit' require 'mocha' require 'timeout' class ::Symbol def <=>(other) self.to_s <=> other.to_s end end module SK class SubordinatorTest < Test::Unit::TestCase attr_reader :array def test_slaves 100.times do assert_equal Set[3, 4, 5, 6, 7, 8, 9, 17, 18, 19], Set[*Subordinator.slave_to_master(*randomize(array)).slaves] end end def test_masters 100.times do assert_equal Set[ 1, 3, 5, 6 ], Set[*Subordinator.slave_to_master(*randomize(array)).masters] end end def randomize(array) array.sort_by { rand } end def test_cycle_detection a = [ [ 1, 2 ], [ 2, 1 ] ] timeout 3 do assert_raises Subordinator::CycleError do Subordinator.slave_to_master(*a).masters end end end def test_other a = [ [ 16973, 1 ], [ 16975, 1 ], [ 16976, 16973 ], [ 16977, 16973 ], [ 17217, 16977 ], ] 100.times do assert_equal Set[ 16973, 16975, 16976, 16977, 17217], Set[*Subordinator.slave_to_master(*randomize(a)).slaves] end end def test_strings h = Hash[ :gena => :felix, :dennis => :gena, :vika => :gena, :felix => :klim, :vika => :dennis ] assert_equal [ :klim, :felix, :gena, :dennis, :vika ], Subordinator.slave_to_master(*h).lineup end def setup @array = [ [ 3, 1 ], [ 4, 1 ], [ 6, 3 ], [ 5, 3 ], [ 7, 5 ], [ 8, 5 ], [ 9, 5 ], [ 17, 6 ], [ 18, 6 ], [ 19, 6 ], ] end end end end
true
4646717e28abe8b2633c18c4a83e339185492c27
Ruby
GeekG1rl/learn_to_program
/ch11-reading-and-writing/safer_picture_downloading.rb
UTF-8
476
3.203125
3
[]
no_license
# your code here # Safer picture downloading. Adapt the picture-downloading/file-renaming # program to your computer by adding some safety features to make sure you # never overwrite a file. A few methods you might find useful are File.exist? # (pass it a filename, and it will return true or false) and exit (like if # return and Napoleon had a baby—it kills your program right where it stands; # this is good for spitting out an error message and then quitting).
true
432269464ce6e40655b60c9428021a894a4edbca
Ruby
tangyz007/hw-ruby-intro
/lib/ruby_intro.rb
UTF-8
2,195
3.84375
4
[]
no_license
# When done, submit this entire file to the autograder. # Part 1 def sum arr # YOUR CODE HERE return arr.inject(0, :+) end def max_2_sum arr # YOUR CODE HERE return 0 if arr.empty? == true return arr[0] if arr.size == 1 def sum arr return arr.inject(0, :+) end return sum(arr.max(2)) end def sum_to_n? arr, n # YOUR CODE HERE return false if arr.empty? == true return false if arr.size == 1 hash = {} array = [] arr.each_with_index do |value,index| y = n - value if(hash.find{|key,val| key == value}) array << hash[value] array << index return true else hash[y] = index end end return false end # Part 2 def hello(name) # YOUR CODE HERE return "Hello, ".concat(name) end def starts_with_consonant? s # YOUR CODE HERE return false if s.empty? == true return false if (s[0] =~ /\w/) == nil return false if (s[0] =~ /\D/) == nil return false if s.start_with?("A","E","I","O","U","a","e","i","o","u") == true return true end def binary_multiple_of_4? s # YOUR CODE HERE return false if s.empty? == true return false if (s =~ /\D/) != nil return false if (s =~ /2/) != nil return false if (s =~ /3/) != nil return false if (s =~ /4/) != nil return false if (s =~ /5/) != nil return false if (s =~ /6/) != nil return false if (s =~ /7/) != nil return false if (s =~ /8/) != nil return false if (s =~ /9/) != nil return true if s == '0' return false if s.end_with?("100") == false return true end # Part 3 class BookInStock # YOUR CODE HERE attr_reader :isbn, :price #creates getters def initialize(isbn_i,price_i) #constructor self.isbn=(isbn_i) self.price=(price_i) end #setter def isbn=(isbn_i) if !(isbn_i.is_a? String) raise ArgumentError.new('Not a String!!!') elsif isbn_i.length < 1 raise ArgumentError.new('ISBN is empty!!!') else @isbn = isbn_i end end def price=(price) if price <= 0 raise ArgumentError.new('Price Error!!!') end @price = price end def price @price end def price_as_string "$#{@price.round(2)}" #round to 2 digits sprintf("$%#.2f", @price) end end
true
60c8ff66e6b5ad105b4c1f4e5de7e2cea20f5b81
Ruby
tsmsogn/exercism
/ruby/pangram/pangram.rb
UTF-8
146
2.828125
3
[]
no_license
module BookKeeping VERSION = 6 end class Pangram def self.pangram?(phrase) ('a'..'z').all? { |s| phrase.downcase.include?(s) } end end
true
0347ed5bf457000573713288714c644b3c1e6481
Ruby
christophermanahan/tictactoe-ruby
/lib/game.rb
UTF-8
446
3.234375
3
[]
no_license
class Game attr_reader :board def initialize(board) @board = board end def over? win? || tie? end def win? board.combinations.any? do |in_a_row| unique = in_a_row.uniq !unique.first.nil? && unique.size == 1 end end def tie? !win? && board.full? end def move(symbol:, to:) Game.new(board.put(symbol: symbol, at: to)) end def available_moves board.available_positions end end
true
c601ae54b31b22161f418138b442c41fb34a2f6d
Ruby
mdeepak98/blockchain_database
/app/block_chain/database.rb
UTF-8
934
2.578125
3
[]
no_license
class Database include ActiveModel::Model mattr_accessor :block_chain # def initialize # @@block_chain = BlockChain.new # @@block_chain.create_transactions # end @@block_chain = BlockChain.new class << self def initialize_block_chain return if @@block_chain.present? create_transactions end def create_transactions puts "======== Adding transaction 1 =============" @@block_chain.add_block({caratlane: 1_00_00_000}) puts "======== Adding transaction 2 =============" @@block_chain.add_block({b:10}) puts "======== Adding transaction 3 =============" @@block_chain.add_block({c:10}) end def print_transactions JSON.pretty_generate @@block_chain.chain.map(&:instance_values) end def validate unless @@block_chain.valid? raise ActiveModel::ValidationError.new(@@block_chain) end end end end
true
4b8e1f101c04c870bf9dcfa23309068ff8f8e885
Ruby
dontpanic917/ruby-class-variables-and-class-methods-lab-web-022018
/lib/song.rb
UTF-8
670
3.328125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song attr_reader :name, :artist, :genre @@count=0 @@genres=[] @@artists=[] def initialize(name, artist, genre) @genre=genre @name=name @artist=artist @@artists<<artist @@genres<<genre @@count += 1 end def self.count @@count end def self.genres @@genres.uniq end def self.artists @@artists.uniq end def self.genre_count genre_count={} @@genres.uniq.map{|key| genre_count.store(key, @@genres.count(key))} return genre_count end def self.artist_count artist_count={} @@artists.uniq.map{|key| artist_count.store(key, @@artists.count(key))} return artist_count end end
true
e2f19ac6dd3e226aca1f31b762b633dc5135fa60
Ruby
cmloegcmluin/AppAcademy-exercises-archive
/minesweeper/board.rb
UTF-8
4,924
3.5
4
[]
no_license
require 'colorize' class Board attr_accessor :cursor, :is_over def initialize(size = 9, difficulty = 5) @size = size @difficulty = difficulty @tiles = Array.new(size) { Array.new(size) { Tile.new } } @is_over = false @cursor = [@size / 2, @size / 2] end def [](pos) x, y = pos[0], pos[1] @tiles[x][y] end def set_bomb(pos) self[pos].is_bomb = true end def change_mark(pos) unless self[pos].is_revealed if self[pos].mark == :unmarked self[pos].mark = :marked elsif self[pos].mark == :marked self[pos].mark = :unsure elsif self[pos].mark == :unsure self[pos].mark = :unmarked end end end def reveal(pos) queue = [pos] until queue.empty? current_pos = queue.shift if self[current_pos].is_bomb self.is_over = true elsif self[current_pos].is_revealed neighbors(current_pos).each do |neighbor| if neighbor.is_bomb self.is_over = true else neighbor.is_revealed = true end end else unless self[current_pos].is_revealed || self[current_pos].mark != :unmarked self[current_pos].is_revealed = true if self[current_pos].bomb_count == 0 neighbors(current_pos).each do |neighbor| queue << neighbor end end end end end end def move(x_offset, y_offset) new_pos = [@cursor[0] + x_offset, @cursor[1] + y_offset] @cursor = new_pos if on_board?(new_pos) end def on_board?(pos) x, y = pos[0], pos[1] x.between?(0, @size - 1) && y.between?(0, @size - 1) end def neighbors(pos) neighbors = [] x, y = pos[0], pos[1] (-1..1).each do |x_offset| (-1..1).each do |y_offset| neighbor_pos = [x + x_offset, y + y_offset] if !(x_offset == 0 && y_offset == 0) && on_board?(neighbor_pos) neighbors << neighbor_pos end end end neighbors end def show system("clear") @tiles.each_with_index do |row, x| row.each_with_index do |tile, y| #setpos(x,y*2) if @cursor == [x,y] if is_over print "X ".colorize(:light_white).on_light_black #addstr("X") else print "\u2316 ".colorize(:light_white).on_light_black #addstr("#") end elsif tile.mark == :marked if is_over print "X ".colorize(:light_magenta).on_light_black #addstr("X") else print "\u2691 ".colorize(:white).on_light_black #addstr("F") end elsif tile.mark == :unsure if is_over print "X ".colorize(:light_magenta).on_light_black #addstr("X") else print "? ".colorize(:light_black).on_light_black #addstr("?") end elsif tile.is_revealed if tile.bomb_count == 0 print "_ ".colorize(:light_black).on_light_black #addstr("_") else show_number(tile) #addstr("#{tile.bomb_count}") end elsif tile.is_bomb if is_over print "\u2735 ".colorize(:light_yellow).on_light_black #addstr("B") else print "` ".colorize(:light_black).on_light_black #addstr("`") end else print "` ".colorize(:light_white).on_light_black #addstr("`") end end print "\n" end #refresh end def show_number(tile) color_sym = case tile.bomb_count when 1 :light_blue when 2 :green when 3 :light_red when 4 :blue when 5 :red when 6 :cyan when 7 :magenta when 8 :yellow end print "#{tile.bomb_count} ".colorize(color_sym).on_light_black end def place_bombs @difficulty.times do bomb_placed = false until bomb_placed rand_x = rand(@size) rand_y = rand(@size) unless self[[rand_x, rand_y]].is_bomb set_bomb([rand_x,rand_y]) bomb_placed = true end end end end def each_position() 0.upto(@size - 1) do |x| 0.upto(@size - 1) do |y| yield [x, y] end end end def set_bomb_counts each_position do |current_pos| current_tile = self[current_pos] neighbors(current_pos).each do |pos| if self[pos].is_bomb current_tile.bomb_count += 1 end end end end def board_won? no_unmarked_or_unrevealed_tiles? && no_false_marks? end def no_unmarked_or_unrevealed_tiles? each_position do |pos| if self[pos].mark != :marked && !self[pos].is_revealed return false end end true end def no_false_marks? each_position do |pos| if self[pos].mark == :marked && !self[pos].is_bomb return false end end true end end
true
857286e22e23f726f0140d4b6e7c8636edb26f80
Ruby
vinhnglx/dupco
/lib/dupco/raw.rb
UTF-8
1,589
3.140625
3
[ "MIT" ]
permissive
class Raw attr_reader :body attr_accessor :client # Public: Create constructor # # Parameter # # body - array of Html elements # # Example # # Raw.new([#<Nokogiri::XML::Element:0x3fe1b19d4dec name="div" ... ]) # # Returns nothing def initialize(body, client) @body = body @client = client end # Public: Strategy method # # Returns nothing def process client.process(self) end # Public: Get title of element # # Parameters # element - Html element # title_class - class name of element # # Example # client.title(element, ".title") # # => Wine beauty # # Returns title of element def title(element, title_class) element.css(title_class).text.strip unless element.css(title_class).empty? end # Public: Get src of image # # Parameters # element - Html element # image_class - class name of element # # Example # client.image_src(element, ".image") # # => "http://example.com/1/sample.jpg" # # Returns source of an image def image_src(element, image_class) require 'uri' URI(element.css(image_class).attribute('src').text).path unless element.css(image_class).empty? end # Public: Get url of a link # # Parameters # element - Html element # link_class - class name of element # # Example # client.hyper_link(element, ".title") # # => "http://example.com/1/" # # Returns source of link def hyper_link(element, link_class) element.css(link_class).attribute('href').text unless element.css(link_class).empty? end end
true
a193ff928d2290af0fede871a3acb9556e74a92a
Ruby
kim2214/Datastructure
/atcoder/20_03_01/B - Bingo.rb
UTF-8
1,913
3.703125
4
[]
no_license
# A = Array.new(3) # # for num1 in 0..2 do # A[num1] = gets.chomp.split(' ').map(&:to_i) # end # # N = gets.chomp.to_i # # arr = Array.new(N) # # for num1 in 0..N - 1 do # arr[num1] = gets.chomp.to_i # end # # for num1 in 0..2 do # for num2 in 0..arr.size - 1 do # if A[0][num1] == arr[num2] # A[0][num1] = 1 # end # # if A[1][num1] == arr[num2] # A[1][num1] = 1 # end # # if A[2][num1] == arr[num2] # A[2][num1] = 1 # end # end # end # # bingo = 0 # # # 가로 # for num1 in 0..2 do # for num2 in 0..2 do # if A[num1][num2] == 1 # bingo += 1 # end # end # end # # # 세로 # for num1 in 0..2 do # for num2 in 0..2 do # if A[num2][num1] == 1 # bingo += 1 # end # end # end # # # 대각선 # if A[0][0] == 1 && A[1][1] == 1 && A[2][2] # bingo += 1 # end # # if A[0][2] == 1 && A[1][1] == 1 && A[2][0] # bingo += 1 # end # # if bingo > 0 # puts 'Yes' # else # puts 'No' # end N1 = gets.chomp.split(' ').map(&:to_i) N2 = gets.chomp.split(' ').map(&:to_i) N3 = gets.chomp.split(' ').map(&:to_i) N = gets.chomp.to_i arr = Array.new(N) for num1 in 0..arr.size - 1 do arr[num1] = gets.chomp.to_i end for num1 in 0..2 do for num2 in 0..arr.size - 1 do if N1[num1] == arr[num2] N1[num1] = 1 end if N2[num1] == arr[num2] N2[num1] = 1 end if N3[num1] == arr[num2] N3[num1] = 1 end end end # 가로 bingo = 0 if N1[0] == 1 && N1[1] == 1 && N1[2] == 1 bingo += 1 end if N2[0] == 1 && N2[1] == 1 && N2[2] == 1 bingo += 1 end if N1[0] == 1 && N1[1] == 1 && N1[2] == 1 bingo += 1 end # 대각선 if N1[0] == 1 && N2[1] == 1 && N3[3] == 1 bingo += 1 end if N1[2] == 1 && N2[1] == 1 && N3[0] == 1 bingo += 1 end # 세로 for num1 in 0..2 do if N1[num1] == 1 && N2[num1] == 1 && N3[num1] bingo += 1 end end if bingo > 0 puts 'Yes' else puts 'No' end
true
1dfcd325ad268277900ccbffafff29d21a18ea55
Ruby
bengus101/ruby-rio-grande
/starter-code/lib/Book.rb
UTF-8
182
2.84375
3
[]
no_license
require_relative 'Item.rb' class Book < Item def initialize name, price super(name,price) end def properties(pages, author) @pages = num @author = author end end
true
63e50b2b01ebdc4b1d1dab9645440a8cad03a62e
Ruby
skotchpine/qwerty
/src/qwerty/models.rb
UTF-8
1,479
2.625
3
[]
no_license
# # Models # class User < Sequel::Model one_to_many :submissions plugin :secure_password end class Lesson < Sequel::Model one_to_many :exercises %i[complete accurate fast].each do |m| define_method m do |user_id| return false unless exercises.any? ret = true exercises.each do |exercise| unless exercise.send(m, user_id) ret = false break end end ret end end end Lesson.dataset_module { order :ordered, :position } class Exercise < Sequel::Model many_to_one :lesson one_to_many :submissions %i[complete accurate fast].each do |m| define_method m do |user_id| submissions.any? do |submission| submission.user_id == user_id and submission.send(m) end end end end Exercise.dataset_module { order :ordered, :position } class Submission < Sequel::Model many_to_one :exercise many_to_one :user def self.from_results(user_id, exercise_id, right, wrong, accuracy, wpm) exercise = Exercise.where(id: exercise_id).first complete = wrong <= exercise.max_typos && wpm >= exercise.min_wpm accurate = complete && wrong.zero? fast = complete && wpm >= exercise.fast_wpm create \ user_id: user_id, exercise_id: exercise_id, right: right, wrong: wrong, accuracy: accuracy, wpm: wpm, complete: complete, accurate: accurate, fast: fast, created_at: DateTime.now end end
true
b864a14ea94e04c6ea89665b9361fd714d7759e8
Ruby
ezzye/borisBikes
/spec/feature_spec.rb
UTF-8
719
3
3
[]
no_license
# require './lib/docking_station' # require './lib/bike' # docking_station = DockingStation.new # bike1 = Bike.new # 20.times do # bike = Bike.new # docking_station.dock(bike) # end # p docking_station.bikes # begin # docking_station2 = DockingStation.new # docking_station2.release_bike # rescue Exception => e1 # puts "Test for empty #{e1.inspect} " # end # begin # 21.times do # bike = Bike.new # docking_station.dock(bike) # end # rescue Exception => e2 # puts "Test for capacity working #{e2.inspect} " # end # begin # docking_station3 = DockingStation.new 30 # p docking_station3.capacity # rescue Exception => e3 # puts "Capacity feaure not found #{e3.inspect}" # end
true
9bdd0e422ae6a4e14dd8ba2923206910298c4c50
Ruby
chathhorn/soco
/app/models/cis_subject.rb
UTF-8
867
2.625
3
[]
no_license
class CisSubject < ActiveRecord::Base has_many :cis_courses #static method which finds a course written textually def self.search_for_course(name) name.upcase! (subject, white, number) = name.scan(/^([A-Z]*)(\s*)(\d*)$/)[0] if subject == nil return [] end if number.blank? && white.empty? subjects = find :all, :conditions => [ 'cis_subjects.code LIKE ?', subject + '%' ], :limit => 10 else subjects = find :all, :conditions => [ 'cis_subjects.code = ? AND cis_courses.number LIKE ?', subject, number + '%' ], :joins => "LEFT JOIN cis_courses ON cis_courses.cis_subject_id = cis_subjects.id", :limit => 10 end return subjects end #returns SUBJECT def to_s return code end end
true
fe9d191eafeff662f4fbc0c49a100f563b70cf2e
Ruby
Austin2016/chess
/dialogue.rb
UTF-8
163
3.140625
3
[]
no_license
class Dialogue def self.prompt(board) puts "#{Color.to_s(board.turn)}, it's your turn!" user_entry = gets.chomp user_entry end end
true
154989e121af685a02a57de5f1d6f3b31aa75f95
Ruby
chrissschin/introtoruby
/loops_iterators/perform_again.rb
UTF-8
289
3.703125
4
[]
no_license
# perform rb # loop do # puts "Do you want to do that again?" # answer = gets.chomp # if answer != 'y' # break # end # end # ranges x = gets.chomp.to_i x_x = [1,3,4,5,6,7,8] for i in 1..x do puts i end puts "done" # collection for i in x_x do puts i end puts"done"
true
1dfed352a47cc5754d9a372bfb2ebc85c5965171
Ruby
leequarella/VirtualMerchant-Ruby
/lib/virtual_merchant/amount.rb
UTF-8
466
2.78125
3
[ "MIT" ]
permissive
module VirtualMerchant class Amount attr_accessor :total, :tax, :next_payment_date, :billing_cycle, :end_of_month def initialize(info) @total = sprintf( "%0.02f", info[:total]) if info[:tax] @tax = sprintf( "%0.02f", info[:tax]) else @tax = "0.00" end @next_payment_date = info[:next_payment_date] @billing_cycle = info[:billing_cycle] @end_of_month = info[:end_of_month] || 'Y' end end end
true
d8beadd97517c15389639cc4d16d4f971bb7f9f2
Ruby
ManojParmar93/cs_integration
/app/services/non_rss_feeds/dow_jones/articles_downloader.rb
UTF-8
4,254
2.75
3
[]
no_license
# frozen_string_literal: true module NonRssFeeds module DowJones # Downloads the Articles # and transforms them # for the ArticlesToRssFeeder. class ArticlesDownloader # rubocop:disable ClassLength def initialize(headlines) @headlines = headlines end def articles return [] unless @headlines.is_a?(Array) @headlines.reduce([]) do |array, headline| array + headline_articles(headline) end rescue StandardError => error ::Rails.logger.error( "#{self.class.name}##{__method__} - ERROR! #{error}" ) [] end private def headline_articles(headline) filter_headline_articles_json( headline_articles_json(headline) ).map do |article_json| headline.merge( id: headline[:article_ref], description: article_description(article_json), content: article_content(article_json['Body']), copyright: article_copyright(article_json), section: article_section(article_json) ) end end def filter_headline_articles_json(json) json.select do |element| element.respond_to?(:key?) && element.key?('Body') end end def article_description(article_json) article_json['Title'].first['Items'].first['Value'].strip rescue StandardError => error ::Rails.logger.warn( "#{self.class.name}##{__method__} - WARN! #{error}" ) nil end def article_content(article_json_body) article_json_body.map do |body_object| paragraph(body_object) end.join.delete("\n").delete("\r") end def article_copyright(article_json) article_json['Copyright']['Items'].first['Value'].strip rescue StandardError => error ::Rails.logger.warn( "#{self.class.name}##{__method__} - WARN! #{error}" ) nil end def paragraph(body_object) [ '<p>', transform_paragraph_objects( filter_pragraph_objects( body_object['Items'] ) ).flatten, '</p>' ].join end def filter_pragraph_objects(paragraph_objects) paragraph_objects.select do |object| %(text elink entityreference).include?( object['__type'].downcase ) end end def article_section(article_json) article_json['Section'] end def transform_paragraph_objects(paragraph_objects) paragraph_objects.map do |paragraph_object| transform_paragraph_object(paragraph_object) end end def transform_paragraph_object(paragraph_object) case paragraph_object['__type'].downcase when 'text' text_object(paragraph_object) when 'elink' elink_object(paragraph_object) when 'entityreference' entity_reference_object(paragraph_object) end end def text_object(paragraph_object) paragraph_object['Value'] end def entity_reference_object(paragraph_object) "<b>#{paragraph_object['Name']}</b>" end def elink_object(paragraph_object) "<a href='#{paragraph_object['Reference']}' " \ "title='#{paragraph_object['Text']}'>" \ "#{paragraph_object['Text']}</a>" end def headline_articles_json(headline) JSON.parse( download_headline_articles(headline).body )['Articles'] rescue StandardError => error ::Rails.logger.error( "#{self.class.name}##{__method__} - ERROR! #{error}" ) {} end def download_headline_articles(headline) Faraday.get( api_url, { articleRef: headline[:article_ref], encryptedToken: headline[:encrypted_token] }, {} ) end def api_url 'https://api.dowjones.com/api/public/2.0/Content/article/articleRef/json' end def article_refs @article_refs ||= @headlines.map { |hash| hash['article_ref'] }.compact end end end end
true
8c91de7815ee09d9b47f006172ffc4bbd47de955
Ruby
mukarramali/dynamize_factories
/dynamize_factories.rb
UTF-8
1,911
3.078125
3
[]
no_license
class DynamizeFactories def initialize file @file = file @content = File.read file end def decomment val left = val[0..(val.index('#'))] right = val[(val.index('#'))..-1] not_comment = left.count('\'') != 0 && left.count('\'') == right.count('\'') && left.count('"') == right.count('"') not_comment ? val : val[0..(val.index('#')-1)] end def dynamize data begin value = data.split(' ', 2)[1] value = decomment(value).strip if value.include?'#' new_val = "{#{value}}" "#{data.sub(value, new_val)}" rescue puts "<==== Error search in #{@file}: {data} =====>" end end def evaluate lines = @content.split("\n") lines.each_with_index do |line, index| lines[index] = dynamize(line) if line.strip.size.positive? && type(line) end @result = lines.join("\n") @result end def put_it_back evaluate unless @result @file = File.new(@file, 'w') @file.write(@result) @file.close end private def type data return false if data.split(' ').size == 1 || # Single token data.split(' ')[1] == '=' || # Assignments data.strip == 'end' || # END block data.strip[0] == '#' || # Comment data[-1] == '}' || # DYNAMIC value data.strip.index('require') == 0 || # require syntax data.include?('association ') || # Association data.include?('FactoryBot.define') || # CLASS_BEGIN data.include?('create(:') || # Create another (data.split.last == 'do' || (data.include?('do') && data[-1] == '|')) # Do block true # Static assignment end def pad count " "*count end end
true
070e608e992f64e90cf8fa57c80bc5e39b31f4f3
Ruby
Sid-ah/hk-bc
/database-drill-one-to-many-schema-challenge/spec/screen_spec.rb
UTF-8
1,367
2.59375
3
[]
no_license
require_relative '../screen' describe Screen do let(:casablanca_screening) { double('screening', { movie_title: 'Casablanca', start_time: '11:00' }) } let(:gone_with_the_wind_screening) { double('screening', { movie_title: 'Gone with the Wind', start_time: '18:00' }) } let(:screen) { Screen.new(number: 1, screenings: [casablanca_screening, gone_with_the_wind_screening]) } it 'has a number' do expect(screen.number).to eq 1 end it 'has screenings' do expect(screen.screenings).to match_array [casablanca_screening, gone_with_the_wind_screening] end it 'adds a screening' do wizard_of_oz_screening = double('screening') expect(screen.screenings).to_not include wizard_of_oz_screening screen << wizard_of_oz_screening expect(screen.screenings).to include wizard_of_oz_screening end it 'cancels a screening' do expect(screen.screenings).to include casablanca_screening screen.cancel(start_time: '11:00', movie_title: 'Casablanca') expect(screen.screenings).to_not include casablanca_screening end it 'reassigns screenings' do wizard_of_oz_screening = double('screening') citizen_kane_screening = double('screening') screen.screenings = [wizard_of_oz_screening, citizen_kane_screening] expect(screen.screenings).to match_array [wizard_of_oz_screening, citizen_kane_screening] end end
true
1aab817d83271ee184aedc01b41306af5e4f53a3
Ruby
yasmineezequiel/Vanilla_Ruby
/Section_15_Time_Object/Predicate_Methods_for_the_Time_Object.rb
UTF-8
427
2.953125
3
[]
no_license
# Predicate methods for the Time object beatles_first_album = Time.new(1963, 03, 22) p beatles_first_album.monday? # false p beatles_first_album.tuesday? # false p beatles_first_album.wednesday? # false p beatles_first_album.thursday? # false p beatles_first_album.friday? # true p beatles_first_album.saturday? # false p beatles_first_album.sunday? # false # Day light saving time (.dst) p beatles_first_album.dst? # false
true
b47ab22339f0f93594f8ffb8bf3341111584a7a6
Ruby
JoaoCardoso193/TutorX
/app/models/student.rb
UTF-8
1,654
3
3
[]
no_license
class Student < ActiveRecord::Base has_many :appointments has_many :tutors, through: :appointments #creates and returns an hour long appointment, uses 24hr format ## work hours defined, if outside that range, drop error. also drop error if appointment already taken def create_appointment(tutor, year, month, day, hour, note) datetime = DateTime.new(year, month, day, hour) appointment = Appointment.find_by(begin_datetime: datetime, tutor_id: tutor.id) if appointment.taken == false appointment.taken = true appointment.student_id = self.id appointment.tutor_id = tutor.id appointment.note = note appointment.end_datetime = appointment.begin_datetime + 1.hours appointment.save appointment else puts "\nAppointment taken, please select another time slot".red.bold return 'failed' end end #cancels an appointment given its id def cancel_appointment(appointment_id) appointment = appointments.find {|appointment| appointment.id == appointment_id} appointment.student_id = nil appointment.taken = false appointment.note = nil appointment.end_datetime = nil appointment.save end #returns all appointments for student instance def appointments Appointment.all.select{|appointment| appointment.student_id == self.id} end #returns upcoming appointment for student instance def upcoming_appointments appointments.select{|appointment| appointment.begin_datetime > DateTime.now} end end
true
9fe3641edfed33aa0e4f30d4173fda8968fb79e2
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/grade-school/8252cf4928d7462f8657599343ef7634.rb
UTF-8
319
3.265625
3
[]
no_license
class School def initialize end def db @db ||= Hash.new { |hash, key| hash[key] = [] } end def add(student, grade) db[grade] << student end def grade(grade) db[grade] end def sort sorted_array = db.sort.each do |array| array[1].sort! end Hash[sorted_array] end end
true
bc5eb0cda387e92e10f1ff0dc03e4e80d2fc7acb
Ruby
DilyaZaripova/sinatra_di
/sinatradi.rb
UTF-8
1,655
2.515625
3
[]
no_license
require 'sinatra' require 'sinatra/base' require 'sequel' require 'sequel/extensions/seed' require 'sinatra/namespace' require 'pg' require 'json' require 'multi_json' #подтягивание всех файлов из перечисленных папок-сборка # Sequel ORM для работой с БД DB = Sequel.connect( adapter: :postgres, database: 'sinatra_di_dev', host: 'localhost', password: 'password', user: 'sinatra_di', max_connections: 10, ) %w{controllers models routes}.each{|dir|Dir.glob("./#{dir}/*.rb",&method(:require))} Sequel::Seed.setup :development Sequel.extension :seed Sequel::Seeder.apply(DB, './seeds') #module DiModule # class App < Sinatra::Base # register Sinatra::Namespace # namespace '/api/v1' do before do content_type 'application/json' #to see perfect in POSTMAN end get '/' do redirect to('/hello/Dilya') end # end get '/hello/:name' do |n| "Sinatra Di приветствует тебя, #{n}!" end get %r{/hello/([\w]+)} do |c| "Hello, #{c}!" end get '/*' do "I dont know what is the #{params[:splat]}.Its was your typed!" end # Необязательные параметры в шаблонах маршрутов get '/jobs.?:format?' do # соответствует "GET /jobs", "GET /jobs.json", "GET /jobs.xml" и т.д. "Да, работает этот маршрут!" end def collection_to_api(collection)#for Array MultiJson.dump(collection.map{|s|s.to_api}) end # end #end
true
0f7428eb400ae0f0efac1dfc064dd744a131531d
Ruby
evoloshchuk/production-facility-challenge
/app.rb
UTF-8
362
2.65625
3
[]
no_license
require_relative "lib/runner" require_relative "lib/producer/greedy" require_relative "lib/producer/rational" strategy = ARGV[0] STRATEGIES = { "greedy" => Producer::Greedy, "rational" => Producer::Rational } producer_class = STRATEGIES.fetch(strategy) capacity = ARGV[1].to_i if ARGV[1] runner = Runner.new(producer_class, capacity) runner.run(STDIN, STDOUT)
true
049c3e9d1944c125b38097b572201dad0bfa9f72
Ruby
Raudy2/Ruby
/crack.rb
UTF-8
445
3.3125
3
[]
no_license
require 'csv' require 'awesome_print' planets = [ [1, "Mercury", 0.55, 0.4], [2, "venus", 0.815, 0.7], [3, "Earth", 1.0, 1.0], [4, "Mars", 0.107, 1.5] ] headers = ["id", "name", "mass", "distance"] CSV.open("planet_data.csv", "w") do |file| file << headers planets.each do |planet| file << planet end end CSV.open("planet_data.csv", "r").each do |row| ap "#{row["id"]} has a mass of #{row["name"]} and distance of #{row[3]}." end
true
259e178851544b97029b2b8b10cffc7d4fc5490e
Ruby
thoughtsynapse/precisionFDA
/app/services/copy_service/file_copier.rb
UTF-8
3,009
2.671875
3
[ "CC0-1.0" ]
permissive
class CopyService class FileCopyError < StandardError; end # Copies files to another scope. class FileCopier class << self # Creates db copy of a file with another scope and project. # @param file [UserFile] A file to copy. # @param scope [String] A destination scope. # @param destination_project [String] A destination project. # @param attrs [Hash] Extra attributes for a new file. # @return [UserFile] A new file record. def copy_record(file, scope, destination_project, attrs = {}) existed_file = UserFile.find_by(dxid: file.dxid, project: destination_project) return existed_file if existed_file new_file = file.dup new_file.assign_attributes(attrs) new_file.scope = scope new_file.project = destination_project new_file.parent = file.asset? ? new_file : file new_file.parent_type = "Asset" if file.asset? new_file.save! new_file end end def initialize(api:, user:) @api = api @user = user end def copy(files, scope, folder_id = nil) attrs = check_and_assign_folder!(scope, folder_id) attrs[:user] = user files = Array.wrap(files) copies = Copies.new destination_project = UserFile.publication_project!(user, scope) files_grouped_by_project(copies, files, destination_project).each do |project, project_files| api.project_clone(project, destination_project, objects: project_files.map(&:dxid)) project_files.each do |file| copies.push( object: self.class.copy_record(file, scope, destination_project, attrs), source: file, ) end end copies end private attr_reader :api, :user # Checks if folder belongs to a scope and files can be created in it. # @param scope [String] A destination scope. # @param folder_id [Integer] A folder ID. # @return [Hash] Folder attributes. def check_and_assign_folder!(scope, folder_id) return {} unless folder_id folder = Folder.find(folder_id) if folder.scope != scope raise FileCopyError, "Folder '#{folder.name}' doesn't belong to a scope '#{scope}'" end folder_column = Folder.scope_column_name(scope) { folder_column => folder_id } end def files_grouped_by_project(copies, files, destination_project) files.uniq.each_with_object({}) do |file, projects| existed_file = UserFile.where.not(state: UserFile::STATE_COPYING). find_by(dxid: file.dxid, project: destination_project) if existed_file.present? copies.push( object: existed_file, source: file, copied: false, ) next end next if file.state != UserFile::STATE_CLOSED || destination_project == file.project projects[file.project] ||= [] projects[file.project].push(file) end end end end
true
4050a60205a0970aa0baf03f506e3c657a9a5e6c
Ruby
umadesai1/kwk-l1-reading-arrays-lab-kwk-students-l1-la-070918
/reading_arrays.rb
UTF-8
626
3.765625
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
STUDENT_NAMES = [ "Adele", "Beyoncé", "Cardi B", "Lady Gaga", "Nicki Minaj", "Rihanna" ] def first_student_by_index puts STUDENT_NAMES[0] end puts first_student_by_index def fourth_student_by_index puts STUDENT_NAMES[3] end puts fourth_student_by_index def last_student_by_index puts STUDENT_NAMES[5] end puts last_student_by_index def first_student_by_method puts STUDENT_NAMES.first end puts first_student_by_method def last_student_by_method puts STUDENT_NAMES.last end puts last_student_by_method def first_second_and_third_students puts STUDENT_NAMES[0,1,2] end puts first_second_and_third_students
true
16d752d7c8cb05d9a120dd1830d0268b29e30ff8
Ruby
ryanburnette/vfrmap
/lib/vfrmap/location.rb
UTF-8
624
2.8125
3
[ "MIT" ]
permissive
require 'geo/coord' require 'airports' class Vfrmap::Location def self.factory(location_string) coordinates = try_coordinates(location_string) return coordinates if coordinates airport = try_airport(location_string) return airport if airport end private def self.try_coordinates(location_string) Geo::Coord.parse(location_string) end def self.try_airport(location_string) case when location_string.length == 3 Airports.find_by_iata_code(location_string.upcase) when location_string.length == 4 Airports.find_by_icao_code(location_string.upcase) end end end
true
e74d830857bd28d55b4324b80adbb7fc19d3b28d
Ruby
JazziJazz/ruby-projects
/Exercícios/[048] — Ímpares multiplos de três.rb
UTF-8
232
3.703125
4
[ "MIT" ]
permissive
sum_odd = 0 count = 0 (1 .. 500).each do |value| if value.odd? and value % 3 == 0; sum_odd += value count += 1 end end puts("A soma total dos números é de #{sum_odd}, foi um total de #{count} números.")
true
32bb1f5941fdfe896953fee9b2819e2873c58806
Ruby
smintz93/Sublist-Sinatra-2
/controllers/GameController.rb
UTF-8
759
2.546875
3
[]
no_license
class GameController < ApplicationController # Json Body Filter before do payload_body = request.body.read if(payload_body != "") @payload = JSON.parse(payload_body).symbolize_keys puts "----------------------- HERE IS Payload" pp @payload puts "----------------------- HERE IS Payload" end end get "/" do games = Game.all { success: true, message: "You are hitting Game Controller", all_games: games }.to_json end get "/:id" do # Getting all games for whichever team name you want to enter team = Team.find params[:id] # binding.pry this_team_games = team.games { success: true, message: "Games for team #{team.team_name}", team_games: this_team_games }.to_json end end
true
d3513554b133cca8a492494b89881989fdaa1f98
Ruby
dewinterjack/familyTree
/person.rb
UTF-8
157
2.6875
3
[]
no_license
class Person attr_accessor :first_name, :last_name, :other_names attr_reader :id def initialize @id = 0 #Will be set to next available id end end
true
dd86b67b6c56a4af13822aa832e1f8afee7d674c
Ruby
alessandrogurgel/codility
/cyclic_rotation.rb
UTF-8
171
2.6875
3
[]
no_license
def solution(a, k) return a if k == 0 || a.empty? offset = a.length - (k % a.length) return a if offset == 0 a[offset..a.length - 1].concat(a[0..offset-1]) end
true
ea0752f83f40fcdce84ce39d0ab0b6230d28a185
Ruby
SebastianDelima/programming-univbasics-4-array-concept-review-lab-dc-web-091619
/lib/array_methods.rb
UTF-8
507
3.46875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def find_element_index(array, value_to_find) a = 0 while a < array.length if array[a] == value_to_find return a end a += 1 end end def find_max_value(array) max_value = 0 a = 0 while a < array.length if array[a] > max_value max_value = array[a] end a += 1 end return max_value end def find_min_value(array) min_value = array[0] count = 1 while count < array.length if array[count] < min_value min_value = array[count] end count += 1 end return min_value end
true
30a6dbde4c364ed43ec03d434a63fdc1e127c4a7
Ruby
nicholasspencer/koans
/hackerrank/synchronous.shopping.rb
UTF-8
2,884
3.28125
3
[]
no_license
#!/usr/bin/env ruby class Shop attr_accessor :wares attr_accessor :graph def initialize(wares = []) @wares = wares end def connect_roads graph.roads.select { |road| road.source == self } end def connect_shops connect_roads.map do |roads| graph.shops.select { roads.destination end end end class Road attr_accessor source, destination, length def initalize (source, destination, length) @source = source @destination = destination @length = length end def <=>(road) self.length <=> road.length end end class City attr_accessor :shops, :roads def initialize @shops = [] @roads = [] end def addShopAsString(string) addShopWithWares string.split(" ")[1 .. -1].map(&:to_i) end def addShopWithWares(wares) addShop(Shop.new(wares)) end def addShop(shop) @shops.push shop shop.graph = self end def addRoadAsString(string) addRoad(string.split(" ").map(&:to_i)) end def addRoad(source, destination, length) @roads.push Road.new(source, destination, length) #allow the graph to traverse backwards @roads.push Road.new(destination, source, length) end ##### class def solve end end input = File.open("synchronous.shopping.input").readlines # Counts = Struct.new(:shops, :roads, :fish) # counts = Counts.new(*input[0].split(" ").map(&:to_i)) # # vertex # Shop = Struct.new(:fish, :id) # shops = input[1 .. counts[:shops]].each_with_index.map do |shop, index| # shop = Shop.new(shop.split(" ")[1 .. -1].map(&:to_i), index+1) # shop.fish = shop.fish.reduce(:|) # shop # end # #edge # Road = Struct.new(:a, :b, :length) # roads = input[counts[:shops]+1 .. -1].map do |road| # road = road.split(" ").map(&:to_i) # ab = Road.new(*road) # road[0], road[1] = road[1], road[0] # ba = Road.new(*road) # [ab, ba] # end # roads.flatten! # def neighbors(shop, roads, queue) # road = roads.select do |road| # road.a == shop.id && queue.one? { |shop| road.b == shop.id } # end # end # def dijkstra(roads, shops, starting_shop) # distance = {} # previous = {} # queue = shops.clone # queue.each do |shop| # distance[shop] = Float::INFINITY # end # distance[starting_shop] = 0 # # until queue.empty? # closestShop = nil # distance.each do |shop, shop_distance| # if closestPath > shop_distance then # closestPath = shop_distance # closestShop = shop # end # end # queue.delete(closestShop) # neighbors = neighbors(closestShop, roads, queue) # neighbors.each do |shop| # alt = distance[closestShop] + vertices.length_between(closestShop, vertex) # if alt < distance[shop] # distance[shop] = alt # previouses[vertices] = closestShop # end # end # # end # end # dijkstra(roads, shops, shops.first)
true
172535775fe5a8d46eb27790bbb3ee316b6b81f3
Ruby
tied/DevArtifacts
/master/bookofruby_code/ch05/enum2.rb
UTF-8
444
3.75
4
[ "MIT" ]
permissive
# The Book of Ruby - http://www.sapphiresteel.com h = {'one'=>'for sorrow', 'two'=>'for joy', 'three'=>'for a girl', 'four'=>'for a boy'} y = h.collect{ |i| i } p( y ) p( h.include?( 'three' ) ) p( h.include?( 'six' ) ) # Note a Hash is not ordered numerically # and min and max return the ASCII order # of the key p( h.min ) p( h.max ) p( h.min{|a,b| a[0].length <=> b[0].length } ) p( h.max{|a,b| a[0].length <=> b[0].length } )
true
940aa743607232071aa89e4f48a0d49d3fb6d686
Ruby
jenmei/whats_up
/app/models/tweet.rb
UTF-8
756
2.59375
3
[]
no_license
class Tweet < ActiveRecord::Base validates_presence_of :content validates_presence_of :author validates_presence_of :date validates_presence_of :url validate :unique_tweet def self.pull_tweets search = Twitter::Search.new search.containing("Corvallis Oregon State").result_type("recent").per_page(10).each do |r| tweet_params={ :content => r.text, :author => r.from_user, :date => r.created_at, :url => "http://twitter.com/#{r.from_user}/status/#{r.id}" } Tweet.create(tweet_params) end end def unique_tweet tweets = Tweet.find(:all,:conditions =>{:content => self.content, :author => self.author, :date => self.date, :url => self.url}) if tweets.any? errors.add(:base,"Tweet must be unique") end end end
true
525dbe5aa2abac0f579736d73e23b06f84b766b7
Ruby
savonarola/pulse_meter_core
/spec/pulse_meter/sensor/base_spec.rb
UTF-8
3,057
2.6875
3
[ "MIT" ]
permissive
require 'spec_helper' describe PulseMeter::Sensor::Base do let(:name){ :some_sensor } let(:description) {"Le awesome description"} let!(:sensor){ described_class.new(name) } let(:redis){ PulseMeter.redis } describe '#initialize' do context 'when PulseMeter.redis is not initialized' do it "raises RedisNotInitialized exception" do PulseMeter.redis = nil expect{ described_class.new(:foo) }.to raise_exception(PulseMeter::RedisNotInitialized) end end context 'when PulseMeter.redis is initialized' do context 'when passed sensor name is bad' do it "raises BadSensorName exception" do ['name with whitespace', 'name|with|bad|characters'].each do |bad_name| expect{ described_class.new(bad_name) }.to raise_exception(PulseMeter::BadSensorName) end end end context 'when passed sensor name is valid' do it "successfully creates object" do expect(described_class.new("foo_@")).not_to be_nil end it "initializes attributes #redis and #name" do sensor = described_class.new(:foo) expect(sensor.name).to eq('foo') expect(sensor.redis).to eq(PulseMeter.redis) end it "saves dump to redis automatically to let the object be restored by name" do expect(described_class.restore(name)).to be_instance_of(described_class) end it "annotates object if annotation given" do described_class.new(:foo, :annotation => "annotation") sensor = described_class.restore(:foo) expect(sensor.annotation).to eq("annotation") end end end end describe '#annotate' do it "stores sensor annotation in redis" do expect {sensor.annotate(description)}.to change{redis.keys('*').count}.by(1) end end describe '#annotation' do context "when sensor was annotated" do it "returns stored annotation" do sensor.annotate(description) expect(sensor.annotation).to eq(description) end end context "when sensor was not annotated" do it "returns nil" do expect(sensor.annotation).to be_nil end end context "after sensor data was cleaned" do it "returns nil" do sensor.annotate(description) sensor.cleanup expect(sensor.annotation).to be_nil end end end describe "#cleanup" do it "removes from redis all sensor data" do sensor.event(123) sensor.annotate(description) sensor.cleanup expect(redis.keys('*')).to be_empty end end describe "#event" do context "when everything is ok" do it "does nothing and return true" do expect(sensor.event(nil)).to be end end context "when an error occures while processing event" do it "catches StandardErrors and return false" do allow(sensor).to receive(:process_event) {raise StandardError} expect(sensor.event(nil)).not_to be end end end end
true
1c4e0eabea43e9cc0df198d2ba0e95c41c9ce8d5
Ruby
Zainab-Omar/my-collect-onl01-seng-pt-070620
/lib/my_collect.rb
UTF-8
335
3.421875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_collect(array) i=0 collection=[] while i<array.length collection << yield(array[i]) i+=1 end collection end array = ["Tim Jones", "Tom Smith", "Jim Campagno"] my_collect(array) do |name| name.split(" ").first end collection = ['ruby', 'javascript', 'python', 'objective-c'] my_collect(collection) do |lang| lang.upcase end
true
96156db496e78fbdbc969a3308213512c1ca8b09
Ruby
trizoza/CodeClan_Project1_ayeWallet
/aye_wallet/models/specs/transaction_spec.rb
UTF-8
513
2.65625
3
[]
no_license
require ('minitest/autorun') require_relative ('../transaction') class TransactionSpec < MiniTest::Test def setup() @transaction01 = Transaction.new({"item" => "Saturday shopping", "merchant" => "Tesco", "value" => 30}) end def test_transaction_item() assert_equal("Saturday shopping", @transaction01.item()) end def test_transaction_merchant() assert_equal("Tesco", @transaction01.merchant()) end def test_transaction_value() assert_equal(30, @transaction01.value()) end end
true
8f3970053c592029b4eb4a9a7feca94ea5e23a14
Ruby
KyungGon-Lee/kakao_bot
/app/controllers/kakao_controller.rb
UTF-8
2,058
2.875
3
[]
no_license
require 'parser' # 헬퍼에다가 모듈화 해놧음 class KakaoController < ApplicationController # AIzaSyALWzqL8t1VXLVxCSIChKKGCv-UVHqvbQQ # 구글 커스텀 서치 api def keyboard # home_keyboard = { :type => "text"} home_keyboard = { :type => "buttons", :buttons => ["메뉴", "고양이", "영화", "로또"] } render json: home_keyboard end def message # 사용자가 보내준 텍스트를 그대로 다시 말하기 user_message = params[:content] return_text = "임시 텍스트" image = false # 로또 # 메뉴 # 다른 명령어가 들어왔을 때 if user_message == "로또" return_text = (1..45).to_a.sample(6).to_s elsif user_message == "메뉴" return_text = ["돈까스", "스테이크", "다이어트", "삼각김밥", "치킨", "피자", "햄버거", "샌드위치"].sample elsif user_message == "고양이" # 고양이 사진 return_text = "나만 고양이 없어 ㅠㅠ" image = true animal = Parser::Animal.new img_url = animal.cat elsif user_message == "영화" image = true naver_movie = Parser::Movie.new naver_movie_info = naver_movie.naver return_text = naver_movie_info[0] img_url = naver_movie_info[1] else return_text = "사용 가능 명령어 로또, 메뉴, 고양이, 영화 를 쳐보세요!" end # return_message = { # :message => { # :text => user_message # }, # # :keyboard = "" # 생략 가능 # } # home_keyboard = {:type => "text"} home_keyboard = { :type => "buttons", :buttons => ["메뉴", "고양이", "영화", "로또"] } return_message_with_img = { :message => { :text => return_text, :photo => {:url => img_url, :width => 640, :height => 480} }, :keyboard => home_keyboard } return_message = { :message => { :text => return_text, }, :keyboard => home_keyboard } if image render json: return_message_with_img else render json: return_message end end end
true
5769d284cf69e6e5a71549686e2df9ee6644d0cc
Ruby
nishimat/Euler
/p042.rb
UTF-8
278
3.171875
3
[]
no_license
require 'csv' csvdata = CSV.read("p042_words.txt") name_list = csvdata[ 0 ] count = 0 name_list.each{ |strname| val = strname.split(//).map{ |c| c.ord - 'A'.ord + 1 }.inject(:+) chkval = Math.sqrt( val * 2 ).to_i count += 1 if val * 2 == chkval * (chkval + 1) } puts count
true
3123e51dc3625e45adc3a49d46ce438b6f8a0575
Ruby
tamu222i/ruby01
/tech-book/5/5-34.rb
UTF-8
106
2.75
3
[]
no_license
# ブロックを取る場合 a = 'abcdefg-abcdefg' a.sub(/abc/){|str| 'xyz'} a.gsub(/abc/){|str| 'xyz'}
true
082c2f5e5d26e25fac5409b532ea1085f3f09553
Ruby
jordansissel/experiments
/ruby/retry/simple-retry.rb
UTF-8
739
3.328125
3
[]
no_license
$count = 0 # Mock a crappy remote API call that could toss an exception # on some upstream error. It also mocks a return value of ':pending' # when it's not complete and returns ':happy' when it's complete. def crappy_api_call $count += 1 # First two calls fail raise "OH SNAP" if $count < 3 # Next few calls say pending return :pending if $count < 5 # Then finally done return :happy if $count > 5 end begin # crappy_api_call throws an exception on upstream errors # but we also want to wait until it returns something other than :pending # so raise "still pending" if it's still :pending raise "still pending" if crappy_api_call == :pending rescue => e p :exception => e sleep 1 retry end puts "Ready!"
true
8e1a4076a89e60a2381484264fc344d36eef4fb9
Ruby
LenyTroncoso/Emprendimiento
/Ruby/curso068/clase.rb
UTF-8
604
3.984375
4
[]
no_license
class Usuario # en la clase se puede definir solo metodos #Setters para asignar el valor a un atributo def nombre=(val) @nombre = val #@nombre es el atributo end #getter retorna el valor def nombre return @nombre end end #instancia de una clase usuario1 = Usuario.new usuario2 = Usuario.new #usuario1 == usuario2 # =>false # un objeto es una clase, pero una clase no necesariamente es eun objeto usuario1.nombre = "Matz" #=> es el llamado a un metodo de la clase puts usuario1.inspect puts usuario1.nombre
true
5acfbc662988348cbd94ce0d9e1878d4749da00d
Ruby
djurre/advent_of_code_2020
/day14/puzzle1.rb
UTF-8
475
2.921875
3
[]
no_license
input = File.readlines("input.txt", chomp: true) mem = {} input.slice_before { |l| l.include?("mask") }.each do |m| mask = m[0].sub("mask = ", '') instructions = m[1..-1].map { |i| i.match(/mem\[(\d+)\] = (\d+)/).captures } instructions.each do |address, value| value_string = '%036b' % value mask.each_char.with_index { |char, index| value_string[index] = char if %w[0 1].include?(char) } mem[address] = value_string.to_i(2) end end pp mem.values.sum
true
a61b884ddecfa6a28dd4626f73ec058a84e65c5a
Ruby
ngs-archives/sinatra-webdav
/lib/dav/property_accessors.rb
UTF-8
1,213
2.71875
3
[ "MIT" ]
permissive
module DAV module PropertyAccessors def self.included(base) raise RuntimeError, 'This module only extends classes.' end def property(mapping) mapping.each do |method_name, node_name| accessor = PropertyAccessor.new(method_name) do |rw| rw.instance_eval(&Proc.new) if block_given? end define_method :"#{ method_name }" do fetch(node_name) { |node| accessor.read node } end define_method :"#{ method_name }=" do |value| node = fetch node_name node ||= add_property node_name accessor.write node, value end end end class PropertyAccessor < Struct.new(:property, :extension) def initialize(property) super property, Module.new extend extension yield self if block_given? end def reader(&block) extension.module_eval { define_method :read, block } self end def read(node) node.content end def writer(&block) extension.module_eval { define_method :write, block } self end def write(node, value) node.content = value end end end end
true
3461b365f0e4fa9dfb4db2d4992be6d800245d22
Ruby
katryc/wyn-works
/data_types2.rb
UTF-8
1,355
4.125
4
[]
no_license
##Ex. 1 #Iterate, display data correspondingly beatles = [ { name: nil, nickname: "The Smart One" }, { name: nil, nickname: "The Shy One" }, { name: nil, nickname: "The Cute One" }, { name: nil, nickname: "The Quiet One" } ] name = nil beatles.each do |member| # case-switch statement case member[:nickname] when "The Smart One" member[:name] = "John Lennon" when "The Shy One" member[:name] = "George Harrison" when "The Cute One" member[:name] = "Paul McCartney" when "The Quiet One" member[:name] = "Ringo Starr" end end beatles.each do |member| puts "Hi, I'm #{member[:name]}. I'm ''#{member[:nickname]}''" end #___________________________________________________________ ##Ex.2 #Simple Greeting puts"What's your name?" def say_hello() puts"What's your name?" name = gets.chomp.to_s.upcase.strip puts"Hello, #{name}" end puts"Hello, #{name}" say_hello puts"Hello, #{name}" #___________________________________________________________ ##Ex.3 #Add 2 to the number. def add_two(number) if number.respond_to? :+ if number.respond_to? :push number.push(2) else number + (2.to_s) end end end def test_add_two p add_two(1) p add_two(1.0) p add_two(nil) p add_two({}) p add_two([]) p add_two(false) p add_two("") end test_add_two
true
9babf402e8304b340754bcdbda1e458446cbf72a
Ruby
tiburce01/Chasse_aux_monstres
/app.rb
UTF-8
732
2.953125
3
[]
no_license
require_relative 'lib/dofus' stack_exchange = StackExchange.new("dofus", 1) monstre_larve = stack_exchange.questions("Larves") monstre_caverne = stack_exchange.questions("Monstres des cavernes") monstre_plaine_herbeuse = stack_exchange.questions("Monstres des Plaines herbeuses") #creation et edition du fichier sur le dossier db selon le type de monstre file = File.new("./db/monstre_larve.json", "w") file.puts "#{monstre_larve}" file.close file = File.new("./db/monstre_caverne.json", "w") file.puts "#{monstre_caverne}" file.close file = File.new("./db/monstre_plaine_herbeuse.json", "w") file.puts "#{monstre_plaine_herbeuse}" file.close puts "Fichier creer et contenir la liste des monstres selon leur types ,avec succes"
true
a2a9df62cb1184fd6931f06e5df3a792e8b941de
Ruby
Tomoyanoda/kadai-microposts
/app/models/micropost.rb
UTF-8
482
2.515625
3
[]
no_license
class Micropost < ApplicationRecord belongs_to :user validates :content, presence: true, length: { maximum:255 } has_many :favorites, dependent: :destroy has_many :liked_users, through: :favorites, source: :user def like(user) self.favorites.find_or_create_by(user_id: user.id) end def unlike(user) favorite = favorites.find_by(user_id: user.id) favorite.destroy if favorite end def like?(user) self.liked_users.include?(user) end end
true
cf2dc9a49ce92dcd1b1fa0bc0574d89531671819
Ruby
JuanmaLambre/myhealth-serv
/app/errors/my_health_error.rb
UTF-8
292
2.625
3
[ "MIT" ]
permissive
class MyHealthError < StandardError attr_reader :error attr_reader :error_message attr_reader :status_code def initialize(error, error_message, status_code = 400) super "#{error}: #{error_message}" @error = error @error_message = error_message @status_code = status_code end end
true
5d307b28101bcfc12c4eeb445a248e76289461d2
Ruby
ToTenMilan/Well-Grounded-Rubyist
/ruby/part2/concat.rb
UTF-8
127
2.96875
3
[]
no_license
class Person attr_accessor :name def to_s name end end david = Person.new david.name = "Dawid" puts "Witaj #{david}"
true
24d22095c419350ccf8adeabf9a158e962fff163
Ruby
yubrew/projecteuler
/problem14.rb
UTF-8
339
3.6875
4
[]
no_license
def collatz_sequence(n) sequence = 0 while n != 1 n = (n % 2 == 0) ? (n / 2) : (3 * n + 1) sequence += 1 end sequence + 1 end sequence = 0 starting_n = 0 (1..999999).each do |n| new_sequence = collatz_sequence(n) if new_sequence > sequence sequence = new_sequence starting_n = n end end puts sequence puts starting_n
true
354adff7f67e8764bfed11635458f19e06ae60eb
Ruby
jahonora/E9CP2A1
/ejercicio2.rb
UTF-8
1,326
3.78125
4
[]
no_license
require 'Date' class Courses attr_reader :name def initialize(name, init_date, final_date) @name = name @init_date = Date.parse(init_date) @final_date = Date.parse(final_date) end def to_s "#{@name}, #{@init_date}, #{@final_date}" end def start_before?(date) date = Date.today if date.nil? raise Exception, "La fecha es mayor a 2019-01-01" if date > Date.new(2019,1,1) @init_date < date end def finish_after?(date) date = Date.today if date.nil? raise Exception, "La fecha es mayor a 2019-01-01" if date > Date.new(2019,1,1) @final_date > date end end #METODOS DE REVISION def courses_start_before(date, courses_list) courses_list.each do |course| puts "El curso #{course.name} comienza antes de la fecha entregada" if course.start_before?(date) end end def courses_finish_after(date, courses_list) courses_list.each do |course| puts "El curso #{course.name} termina despues de la fecha entregada" if course.finish_after?(date) end end #EJECUCION courses_list = [] data = [] File.open('cursos.txt', 'r'){|file| data = file.readlines} data.each do |line| ls = line.split(", ") courses_list << Courses.new(*ls) end puts courses_list date = Date.new(2017,5,10) courses_start_before(date, courses_list) date = Date.new(2017,10,10) courses_finish_after(date, courses_list)
true
94d1d95c5f7d4e93eaebc2911999c1c469c29fe3
Ruby
yard/viddl-rb
/spec/integration/youtube/cipher_guesser_spec.rb
UTF-8
937
2.703125
3
[]
no_license
YOUTUBE_PLUGIN_PATH = File.join(File.dirname(File.expand_path(__FILE__)), '../../..', 'plugins/youtube') require 'minitest/autorun' require 'yaml' require_relative File.join(YOUTUBE_PLUGIN_PATH, 'cipher_guesser.rb') class CipherGuesserIntegrationTest < Minitest::Test def setup @cg = CipherGuesser.new @ciphers = read_cipher_array end def test_extracts_the_correct_cipher_operations_for_all_ciphers_in_the_ciphers_file @ciphers.each do |cipher| version = cipher.first operations = cipher.last.split begin assert_equal operations, @cg.guess(version), "Guessed wrong for cipher version #{version.inspect}" rescue => e puts "Error guessing the cipher for version #{version.inspect}: #{e.message}" fail end end end private def read_cipher_array path = File.join(YOUTUBE_PLUGIN_PATH, "ciphers.yml") YAML.load_file(path).to_a end end
true
1abfa73398b9e3c20a9c125996f70c2028195a6b
Ruby
EvgenyKungurov/codenamecrud
/binary_search/bst.rb
UTF-8
1,317
3.6875
4
[]
no_license
require './node' class BTS attr_accessor :root def initialize(root = nil) @root = Node.new(root) end def build_tree(arr) @root = Node.new(arr.shift) if @root.value == nil arr.each { |v| @root.insert(v) } end def breadth_first_search(v) queue = [root] until queue.empty? node = queue.shift return node.inspect if node.value == v queue.push node.left_child unless node.left_child.nil? queue.push node.right_child unless node.right_child.nil? end nil end def depth_first_search(v) stack = [root] until stack.empty? node = stack.pop return node.inspect if node.value == v stack.push node.left_child unless node.left_child.nil? stack.push node.right_child unless node.right_child.nil? end nil end def dfs_rec(v, current_node = root) return current_node if current_node.value == v result = dfs_rec(v, current_node.left_child) unless current_node.left_child.nil? return result if result result = dfs_rec(v, current_node.right_child) unless current_node.right_child.nil? return result if result nil end end bts = BTS.new(1000) bts.build_tree([1, 7, 4, 23, 8, 9, 4, 3, 5, 7, 9, 67, 6345, 324]) #puts bts.breadth_first_search(9) #puts bts.depth_first_search(9) puts bts.dfs_rec(9)
true
5ee3d4fdde94175bcb066c72d245b82e0b29614e
Ruby
coreyamano/arrays_select_practice
/arrays_select.rb
UTF-8
3,805
4.3125
4
[]
no_license
# 1. Start with an array of numbers and create a new array with only the numbers less than 20. # For example, [2, 32, 80, 18, 12, 3] becomes [2, 18, 12, 3]. numbers = [2, 32, 80, 18, 12, 3] less_than_twenties = [] numbers.each do |number| if number < 20 less_than_twenties << number end end p less_than_twenties # 2. Start with an array of strings and create a new array with only the strings that start with the letter "w". # For example, ["winner", "winner", "chicken", "dinner"] becomes ["winner", "winner"]. chickens = ["winner", "winner", "chicken", "dinner"] winners = [] chickens.each do |chicken| if chicken[0] == "w" winners << chicken end end p winners # 3. Start with an array of hashes and create a new array with only the hashes with prices greater than 5 (from the :price key). # For example, [{name: "chair", price: 100}, {name: "pencil", price: 1}, {name: "book", price: 4}] becomes [{name: "chair", price: 100}]. items = [{name: "chair", price: 100}, {name: "pencil", price: 1}, {name: "book", price: 4}] over_fives = [] items.each do |item| if item[:price] > 5 over_fives << item end end p over_fives # 4. Start with an array of numbers and create a new array with only the even numbers. # For example, [2, 4, 5, 1, 8, 9, 7] becomes [2, 4, 8]. nums = [2, 4, 5, 1, 8, 9, 7] evens = [] nums.each do |num| if num % 2 == 0 evens << num end end p evens # 5. Start with an array of strings and create a new array with only the strings shorter than 4 letters. # For example, ["a", "man", "a", "plan", "a", "canal", "panama"] becomes ["a", "man", "a", "a"]. words = ["a", "man", "a", "plan", "a", "canal", "panama"] short_words = [] words.each do |word| if word.length < 4 short_words << word end end p short_words # 6. Start with an array of hashes and create a new array with only the hashes with names shorter than 6 letters (from the :name key). # For example, [{name: "chair", price: 100}, {name: "pencil", price: 1}, {name: "book", price: 4}] becomes [{name: "chair", price: 100}, {name: "book", price: 4}]. products = [{name: "chair", price: 100}, {name: "pencil", price: 1}, {name: "book", price: 4}] short_ones = [] products.each do |product| if product[:name].length < 6 short_ones << product end end p short_ones # 7. Start with an array of numbers and create a new array with only the numbers less than 10. # For example, [8, 23, 0, 44, 1980, 3] becomes [8, 0, 3]. apples = [8, 23, 0, 44, 1980, 3] oranges = [] apples.each do |apple| if apple < 10 oranges << apple end end p oranges # 8. Start with an array of strings and create a new array with only the strings that don't start with the letter "b". # For example, ["big", "little", "good", "bad"] becomes ["little", "good"]. cards = ["big", "little", "good", "bad"] no_bees = [] cards.each do |card| if card[0] != "b" no_bees << card end end p no_bees # 9. Start with an array of hashes and create a new array with only the hashes with prices less than 10 (from the :price key). # For example, [{name: "chair", price: 100}, {name: "pencil", price: 1}, {name: "book", price: 4}] becomes [{name: "pencil", price: 1}, {name: "book", price: 4}]. inventory_items = [{name: "chair", price: 100}, {name: "pencil", price: 1}, {name: "book", price: 4}] cheap_stuffs = [] inventory_items.each do |inventory_item| if inventory_item[:price] < 10 cheap_stuffs << inventory_item end end p cheap_stuffs # 10. Start with an array of numbers and create a new array with only the odd numbers. # For example, [2, 4, 5, 1, 8, 9, 7] becomes [5, 1, 9, 7]. all_nums = [2, 4, 5, 1, 8, 9, 7] odd_nums = [] all_nums.each do |all_num| if all_num % 2 != 0 odd_nums << all_num end end p odd_nums
true
d954b82d0013b4e528d0905220464cfde2ba94cb
Ruby
JustinLove/ruby_closure_examples
/first_class_spec.rb
UTF-8
521
2.890625
3
[]
no_license
require 'rubygems' require 'spec' describe "First Class Functions" do it "may be named by variables" do x = lambda {:soul} x.call.should == :soul end it "may be stored in data structures" do x = [lambda {:soul}] x.first.call.should == :soul end it "may be passed as an argument" do def swallow(x) x.call.should == :soul end swallow(lambda {:soul}) end it "may be returned as a result" do def well lambda {:soul} end well.call.should == :soul end end
true
f574bfe486c4a3c57b4aa2cbdf34597d8d28b2dc
Ruby
linda-le1/pantry_1909
/lib/recipe.rb
UTF-8
637
3.453125
3
[]
no_license
class Recipe attr_reader :name, :ingredients def initialize(name) @name = name @ingredients = Hash.new end def ingredients_required @ingredients end def add_ingredient(name, amount) @ingredients[name] = amount end def amount_required(ingredient) ingredients_array = @ingredients.to_a amount = ingredients_array.find_all do |ingredient_element| ingredient_element[0].name == ingredient.name end.flatten amount[1] end def total_calories @ingredients.keys.map do |ingredient| ingredient.calories * amount_required(ingredient) end.sum end end
true
0403c6e8cce3886c55927c6d03d79ebd8fd807a2
Ruby
neeraji2it/workshop
/app/models/recommendation.rb
UTF-8
803
2.578125
3
[]
no_license
class Recommendation < ActiveRecord::Base attr_accessible :name, :user_id has_many :recommended_songs has_many :songs, :through => :recommended_songs belongs_to :user validates_presence_of :name validates_presence_of :user_id def to_s self.name end def find_recommended_song(song) self.recommended_songs.find_by_song_id(song.is_a?(Song) ? song.id : song).present? end def is_present?(song) self.find_recommended_song(song).present? end def add(song) r = self.find_recommended_song(song) unless r.present? r = self.recommended_songs.create(:song_id => (song.is_a?(Song) ? song.id : song)) end return r end def remove(song) r = self.find_recommended_song(song) if r.present? r.destroy end return r end end
true
f1b9067b641f1bc2b81e5c80f0d1c683b6a57415
Ruby
snebel29/challenge
/flatten_array/lib/core_ext/array.rb
UTF-8
153
3.140625
3
[]
no_license
class Array def my_flatten(memo=[]) self.each {|element| element.kind_of?(Array) ? element.my_flatten(memo) : memo << element } memo end end
true
93dabfa8dbbdf8192dcc0629d89ee117f3b2d3a6
Ruby
karthickpdy/CP
/a20j/before_exam.rb
UTF-8
553
3.109375
3
[]
no_license
n,actual_time = gets.split(" ").map(&:to_i) min = [] max = [] n.times do a,b = gets.split(" ").map(&:to_i) min << a max << b end min_sum = min.inject(0,:+) max_sum = max.inject(0,:+) ans = false ans_arr = [] if min_sum <= actual_time && actual_time <= max_sum ans = true rem_sum = actual_time - min_sum n.times do |i| ans_arr[i] = min[i] if rem_sum > 0 && max[i] != min[i] x = max[i] - min[i] x = rem_sum if rem_sum < x ans_arr[i] += x rem_sum -= x end end end if ans puts "YES" puts ans_arr.join(" ") else puts "NO" end
true
916c3c593d35a7c8e51aadbc9c4949529cf68173
Ruby
BerilBBJ/scraperwiki-scraper-vault
/Users/A/abulafia/phone-country-codes.rb
UTF-8
1,284
2.578125
3
[]
no_license
require 'nokogiri' url = "http://en.wikipedia.org/wiki/List_of_country_calling_codes" basepath = ".//*[@id='bodyContent']/div[4]/table[5]/tr" html = ScraperWiki.scrape(url) doc = Nokogiri::HTML(html) unique_keys = ['cc'] doc.xpath(basepath).each do |row| cname = row.xpath("./td[1]").text codes = row.xpath("./td[2]/a").map {|el| el.text} # split multiple codes in a row codes = codes.map {|c| c.split(",")}.flatten codes.each do |code| # remove junk code.gsub!(/(\W|\+)/,"") result = { 'name' => cname, 'cc' => code } ScraperWiki.save_sqlite(unique_keys, result) end end require 'nokogiri' url = "http://en.wikipedia.org/wiki/List_of_country_calling_codes" basepath = ".//*[@id='bodyContent']/div[4]/table[5]/tr" html = ScraperWiki.scrape(url) doc = Nokogiri::HTML(html) unique_keys = ['cc'] doc.xpath(basepath).each do |row| cname = row.xpath("./td[1]").text codes = row.xpath("./td[2]/a").map {|el| el.text} # split multiple codes in a row codes = codes.map {|c| c.split(",")}.flatten codes.each do |code| # remove junk code.gsub!(/(\W|\+)/,"") result = { 'name' => cname, 'cc' => code } ScraperWiki.save_sqlite(unique_keys, result) end end
true
a35dd5c8bc4b280d93a1b599478b3baa7c9e7346
Ruby
kmb5/ruby_exercises
/substrings.rb
UTF-8
426
3.8125
4
[]
no_license
def substrings(word, array) array.reduce(Hash.new(0)) do |result_dict, substr| if word.downcase.include? substr result_dict[substr] += 1 end result_dict end end dictionary = ["below","down","go","going","horn","how","howdy","it","i","low","own","part","partner","sit"] puts substrings("below", dictionary) puts substrings("Howdy partner, sit down! How's it going?", dictionary)
true