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
18a1cd8d28da6f24f8b172bc31feaaf6c1c90ae3
Ruby
hanniedong/DBC_Overflow
/dbc_overflow/app/helpers/sessions_helper.rb
UTF-8
287
2.546875
3
[ "MIT" ]
permissive
def current_user @current_user ||= User.find(session[:user_id]) if session[:user_id] end def logged_in? !!current_user end def logout session[:user_id] = nil end def login(user) @user.authenticate(params[:user][:email], params[:user][:password]) session[:user_id] = @user.id end
true
0d13c24b9ea47e614ef20ed6d15f9fab0581fcb5
Ruby
RayNovarina/planning-poker-03-15-17
/spec/models/team_spec.rb
UTF-8
1,250
2.703125
3
[ "Apache-2.0" ]
permissive
require 'rails_helper' describe Team do before :each do @daltons = Team.create(name: "Daltons") @joe = @daltons.team_members.create(name: "Joe") @avrell = @daltons.team_members.create(name: "Avrell") end it "has members" do expect(Team.find_by(name: "Daltons").team_members.size).to eq(2) end it "can have an animator" do @daltons.update(animator: @joe) expect(Team.find_by(name: "Daltons").animator).to eq(@joe) end it "picks the animator when needed" do @daltons.if_needed_pick_animator(@joe) expect(Team.find_by(name: "Daltons").animator).to eq(@joe) end it "sticks to previous the animator" do @daltons.update(animator: @joe) @daltons.if_needed_pick_animator(@avrell) expect(Team.find_by(name: "Daltons").animator).to eq(@joe) end it "avoids 2 members to become animator at the same time" do concurrent = Team.find_by(name: "Daltons") concurrent.if_needed_pick_animator(@joe) @daltons.if_needed_pick_animator(@avrell) expect(@daltons.animator).not_to be(@avrell) end it "knows if a member is animator" do @daltons.animator = @joe expect(@daltons.animator?(@joe)).to be true expect(@daltons.animator?(@avrell)).to be false end end
true
99e97ba679df76612e6bc728da6ce27560156533
Ruby
ksukhorukov/CodeEval
/TryToSolveIt/try_to_solve_it.rb
UTF-8
586
3.03125
3
[]
no_license
#!/usr/bin/env ruby code = {} code2 = {} code['A'] = 'U' code['B'] = 'V' code['C'] = 'W' code['D'] = 'X' code['E'] = 'Y' code['F'] = 'Z' code['G'] = 'N' code['H'] = 'O' code['I'] = 'P' code['J'] = 'Q' code['K'] = 'R' code['L'] = 'S' code['M'] = 'T' code.each_key { |key| code2[code[key]] = key } File.open(ARGV[0]).each_line do |line| decoded = '' line.chomp.split('').each do |char| if code.has_key? char.upcase decoded += code[char.upcase].downcase elsif code2.has_key? char.upcase decoded += code2[char.upcase].downcase end end puts decoded end
true
4685c7ec66eb75b4cca3f80f388d39f574f2f02f
Ruby
quinn/music_pigeon
/song_scrape.rb
UTF-8
1,904
2.78125
3
[]
no_license
require 'lib/general' require 'hpricot' require 'open-uri' class String # Transforms this string into an escaped POSIX shell argument. def shell_escape inspect.gsub(/\\(\d{3})/) {$1.to_i(8).chr} end end def recursive_mkdir dirs base= '' dirs.split('/').each do |dir| base+= dir+'/' begin FileUtils.mkdir base rescue puts 'dir already exists: '+base end end return base end def scrape_songs save_to, page_url doc= Hpricot open(page_url) doc.search("[@href*='mp3']|[@src*='mp3']").each do |song| url= song[:href] url= page_url+url unless url.match(/^http/) filename= File.basename url.sub(page_url, '') begin #puts "** DOWNLOADING #{url}" song= Song.create! :url=> url, :path=> save_to+filename %x[wget -c -O #{save_to+filename.shell_escape} #{url.shell_escape}] tags= ID3Lib::Tag.new(save_to+filename) unless tags.artist.nil? album_path= tags.album.nil? ? '' : tags.album+'/' dir= recursive_mkdir save_to+ tags.artist+'/'+ album_path FileUtils.mv save_to+filename, dir+filename song.path= dir+filename song.save! end puts 'waiting 3 seconds to download the next song.' sleep 3 puts "and we're back!" rescue #puts "already downloaded #{url}" end end end while true do Site.find(:all).each do |site| scrape_songs './downloads/', site.url end Keyword.find(:all).each do |key| scrape_songs './scraps/', URI.encode('http://skreemr.com/results.jsp?q='+key.word) end puts "*****************************************" puts "* LOOKS LIKE ALL DA SONGS R DOWNLAODEDZ *" puts "*****************************************" puts "we'll be back in an hour to check for more songs" sleep 3600 puts "we tirelessly toil but we never work." end
true
b45815bf0d443ef17fde09317d76787ef238e37a
Ruby
WeilerWebServices/textmagic
/textmagic-rest-ruby/lib/textmagic-ruby/rest/unsubscribers.rb
UTF-8
1,939
2.6875
3
[ "MIT" ]
permissive
module Textmagic module REST class Unsubscribers < ListResource ## # Get unsubscriber by ID. # Returns Unsubscriber object. # # uid:: Unsubscriber ID. Required. # # Example: # # @unsubscriber = client.unsubscribers.get 987 # def get(uid) super uid end ## # Unsubscribe phone from your communication by phone number. # Returns Unsubscriber object contains id and link to new Unsubscriber. # # The following *params* keys are supported: # # phone:: Phone number you want to unsubscribe. Required. # # Example: # # @unsubscriber = client.unsubscribers.create {:phone => '999920102'} # def create(params={}) super params end ## # Get all user unsubscribers. # Returns PaginateResource object, contains array of Unsubscriber objects. # # The following *params* keys are supported: # # page:: Fetch specified results page. Defaults 1 # # limit:: How many results on page. Defaults 10 # # Example: # # @unsubscribers = client.unsubscribers.list # def list(params={}) [:search, 'search'].each do |search| params.delete search end super params end ## # Deleting is not supported. # def delete(uid) raise '`delete` method is not available for this type of resource.' end ## # Updating is not supported. # def update(uid, params={}) raise '`update` method is not available for this type of resource.' end end ## # A Unsubscriber resource. # # ==== @id # # ==== @phone # # ==== @first_name # # ==== @last_name # # ==== @unsubscribe_time # class Unsubscriber < InstanceResource; end end end
true
638676cd78582500b2e951e23493353d4766a29b
Ruby
joshpied/f1-cli
/f1.rb
UTF-8
5,353
2.609375
3
[]
no_license
#!/usr/bin/env ruby require 'optparse' require 'net/http' require 'json' require 'time' require './colourize' # API available at https://ergast.com/mrd/ def get_JSON(url) uri = URI(url) response = Net::HTTP.get(uri) return JSON.parse(response) end OptionParser.new do |parser| parser.on("-l", "--logo") do puts " β–„β–„β–„β–„β–„β–„β–„β–„β–„β–„β–„ β–„β–„β–„β–„β–„β–„β–„β–„β–„β–„β–„ β–„β–„β–„β–„β–„β–„β–„β–„β–„β–„β–„ β–„β–„ β–„β–„ β–„ β–„ β–„ β–„β–„β–„β–„β–„β–„β–„β–„β–„β–„β–„ β–„β–„β–„β–„ β–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œβ–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œβ–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œβ–β–‘β–‘β–Œ β–β–‘β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œ β–„β–ˆβ–‘β–‘β–‘β–‘β–Œ β–β–‘β–ˆβ–€β–€β–€β–€β–€β–€β–€β–€β–€ β–β–‘β–ˆβ–€β–€β–€β–€β–€β–€β–€β–ˆβ–‘β–Œβ–β–‘β–ˆβ–€β–€β–€β–€β–€β–€β–€β–ˆβ–‘β–Œβ–β–‘β–Œβ–‘β–Œ β–β–‘β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–ˆβ–€β–€β–€β–€β–€β–€β–€β–ˆβ–‘β–Œ β–β–‘β–‘β–Œβ–β–‘β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œ β–€β–€ β–β–‘β–‘β–Œ β–β–‘β–ˆβ–„β–„β–„β–„β–„β–„β–„β–„β–„ β–β–‘β–Œ β–β–‘β–Œβ–β–‘β–ˆβ–„β–„β–„β–„β–„β–„β–„β–ˆβ–‘β–Œβ–β–‘β–Œ β–β–‘β–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–ˆβ–„β–„β–„β–„β–„β–„β–„β–ˆβ–‘β–Œ β–β–‘β–‘β–Œ β–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œ β–β–‘β–‘β–Œ β–β–‘β–ˆβ–€β–€β–€β–€β–€β–€β–€β–€β–€ β–β–‘β–Œ β–β–‘β–Œβ–β–‘β–ˆβ–€β–€β–€β–€β–ˆβ–‘β–ˆβ–€β–€ β–β–‘β–Œ β–€ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–ˆβ–€β–€β–€β–€β–€β–€β–€β–ˆβ–‘β–Œ β–β–‘β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œ β–β–‘β–‘β–Œ β–β–‘β–Œ β–β–‘β–ˆβ–„β–„β–„β–„β–„β–„β–„β–ˆβ–‘β–Œβ–β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œ β–β–‘β–Œβ–β–‘β–ˆβ–„β–„β–„β–„β–„β–„β–„β–ˆβ–‘β–Œβ–β–‘β–ˆβ–„β–„β–„β–„β–„β–„β–„β–„β–„ β–β–‘β–Œ β–β–‘β–Œ β–„β–„β–„β–„β–ˆβ–‘β–‘β–ˆβ–„β–„β–„ β–β–‘β–Œ β–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œβ–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œβ–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œβ–β–‘β–Œ β–β–‘β–Œ β–β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–‘β–Œ β–€ β–€β–€β–€β–€β–€β–€β–€β–€β–€β–€β–€ β–€ β–€ β–€ β–€ β–€β–€β–€β–€β–€β–€β–€β–€β–€β–€β–€ β–€β–€β–€β–€β–€β–€β–€β–€β–€β–€β–€ β–€ β–€ β–€β–€β–€β–€β–€β–€β–€β–€β–€β–€β–€ v1.0 " end parser.on("-r", "--results", "Results for the latest race") do race = get_JSON('https://ergast.com/api/f1/current/last/results.json')["MRData"]["RaceTable"]["Races"][0] raceDetails = " Latest Race Results ------------------------------ Round ##{race['round']} - #{race['raceName'].light_blue} #{race['Circuit']['circuitName']}, #{race['Circuit']['Location']['locality']}, #{race['Circuit']['Location']['country'] } on #{race['date']} " results = race['Results'].map{ |driver| "#{driver['position']}. #{driver['Driver']['familyName'].green} - pts: #{driver['points'].yellow}" } puts(raceDetails) puts("\nResults".yellow) puts(results) puts("\n") end parser.on("-s", "--schedule", "Schedule for the current season") do races = get_JSON('https://ergast.com/api/f1/current.json')["MRData"]["RaceTable"]["Races"] races = races.map { |race| "#{race['round']}. #{race['raceName'].light_blue} #{race['Circuit']['circuitName']}, #{race['Circuit']['Location']['locality']}, #{race['Circuit']['Location']['country'] } #{race['date']} @ #{Time.parse(race['time'].tr('Z', '')).getlocal} \n\n" } puts('') puts(races) end parser.on("-c", "--constructors", "Constructor standings for the current season") do constructor_standings = get_JSON('https://ergast.com/api/f1/current/constructorStandings.json')["MRData"]["StandingsTable"]["StandingsLists"][0]["ConstructorStandings"] constructor_standings = constructor_standings.map { |constructor| "#{constructor['position']}. #{constructor['Constructor']["name"].green} - #{constructor["points"].yellow} pts " } puts("Constructor Standings") puts(constructor_standings) end parser.on("-d", "--drivers", "Driver standings for the current season") do driver_standings = get_JSON('https://ergast.com/api/f1/current/driverStandings.json')["MRData"]["StandingsTable"]["StandingsLists"][0]["DriverStandings"] driver_standings = driver_standings.map { |driver| "#{driver['position']}. #{driver['Driver']['givenName'].green} #{driver['Driver']['familyName'].green} (#{driver['Constructors'][0]['name']}) - #{driver['points'].yellow} pts " } puts("Driver Standings") puts(driver_standings) end end.parse!
true
8e494d374dea6cfbb36719604ec9e549dff42dbb
Ruby
aquariumbio/protocol-base
/standard_libs/libraries/priority_queue/source.rb
UTF-8
2,253
3.828125
4
[ "MIT" ]
permissive
class PriorityQueue def initialize @heap = Heap.new() @priority_map = Hash.new() end def empty? @heap.empty? end def has_key?(key) @priority_map.has_key?(key) end def push(key, priority) node = PriorityNode.new(value: key, priority: priority) @priority_map[key] = priority @heap.add!(node) end def each(&blk) @priority_map.each(&blk) end def min @heap.peek.to_pair end def min_key return nil if empty? @heap.peek.value end def min_priority return nil if empty? @heap.peek.priority end # remove min and return pair def delete_min return nil if empty? min_node = @heap.remove! @priority_map.delete(min_node.value) min_node.to_pair end # remove min and return key def delete_min_return_key return nil if empty? min_value = @heap.remove!.value @priority_map.delete(min_value) min_value end private class PriorityNode include Comparable attr_reader :value, :priority def initialize(value:, priority:) @value = value @priority = priority end def <=>(node) @priority <=> node.priority end def to_pair [@value, @priority] end end end # Based on https://cs.lmu.edu/~ray/notes/pqueues/ class Heap def initialize @heap = [] end def add!(x) @heap.append(x) sift_up(@heap.length - 1) self end def empty? @heap.length == 0 end def peek @heap[0] end def remove! return nil if empty? value = @heap[0] if @heap.length == 1 @heap = [] else @heap[0] = @heap.pop sift_down(0) end value end def to_s @heap.to_s end private # Sift up the element at index i def sift_up(i) parent = (i - 1) / 2 if parent >= 0 and @heap[parent] > @heap[i] @heap[parent], @heap[i] = @heap[i], @heap[parent] sift_up(parent) end end # Sift down the element at index i def sift_down(i) child = (i * 2) + 1 return if child >= @heap.length child += 1 if child + 1 < @heap.length and @heap[child] > @heap[child+1] if @heap[i] > @heap[child] @heap[child], @heap[i] = @heap[i], @heap[child] sift_down(child) end end end
true
a1da374b5d72a480b6a6d88879f4903c95db616c
Ruby
MrJons/bank_tech_test
/lib/account.rb
UTF-8
996
3.609375
4
[]
no_license
# Responsible for enacting requests on the history made by the ATM class class Account def initialize(balance=0) @balance = balance @history = [] end attr_reader :balance, :history def add_funds(amount, date=Time.now.strftime("%d/%m/%Y")) @balance += amount record_history("deposit", amount, date) end def reduce_funds(amount, date=Time.now.strftime("%d/%m/%Y")) fail "Insuficcient funds" if amount > balance @balance -= amount record_history("withdrawl", amount, date) end def construct_statement fail "No account history" if history == [] puts "---date--- || credit || debit || balance" history.reverse.each do |entry| puts "#{entry[0]} || #{entry[1]} || #{entry[2]} || #{entry[3]}" end end private def record_history(type, amount, date) if type == "deposit" @history << [date, amount, "-" , @balance] elsif type == "withdrawl" @history << [date, "-" , amount, @balance] end end end
true
f047fb2af8b889d6c8f3f253c611dc4662e3eaf6
Ruby
h4hany/leetcode
/python_solutions/1030.matrix-cells-in-distance-order.rb
UTF-8
1,964
3.75
4
[]
no_license
# # @lc app=leetcode id=1030 lang=ruby # # [1030] Matrix Cells in Distance Order # # https://leetcode.com/problems/matrix-cells-in-distance-order/description/ # # algorithms # Easy (68.11%) # Total Accepted: 3.8K # Total Submissions: 5.5K # Testcase Example: '1\n2\n0\n0' # # We are given a matrix with R rows and C columns has cells with integer # coordinatesΒ (r, c), where 0 <= r < R and 0 <= c < C. # # Additionally, we are given a cell in that matrix with coordinatesΒ (r0, c0). # # Return the coordinates ofΒ all cells in the matrix, sorted by their distance # from (r0, c0)Β from smallest distance to largest distance.Β  Here,Β the distance # between two cells (r1, c1) and (r2, c2) is the Manhattan distance,Β |r1 - r2| # + |c1 - c2|.Β  (You may return the answer in any order that satisfies this # condition.) # # # # # Example 1: # # # Input: R = 1, C = 2, r0 = 0, c0 = 0 # Output: [[0,0],[0,1]] # Explanation: The distances from (r0, c0) to other cells are: [0,1] # # # # Example 2: # # # Input: R = 2, C = 2, r0 = 0, c0 = 1 # Output: [[0,1],[0,0],[1,1],[1,0]] # Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2] # The answer [[0,1],[1,1],[0,0],[1,0]] would also be accepted as correct. # # # # Example 3: # # # Input: R = 2, C = 3, r0 = 1, c0 = 2 # Output: [[1,2],[0,2],[1,1],[0,1],[1,0],[0,0]] # Explanation: The distances from (r0, c0) to other cells are: [0,1,1,2,2,3] # There are other answers that would also be accepted as correct, such as # [[1,2],[1,1],[0,2],[1,0],[0,1],[0,0]]. # # # # # Note: # # # 1 <= R <= 100 # 1 <= C <= 100 # 0 <= r0 < R # 0 <= c0 < C # # # # # # # @param {Integer} r # @param {Integer} c # @param {Integer} r0 # @param {Integer} c0 # @return {Integer[][]} def all_cells_dist_order(r, c, r0, c0) (0..r - 1).to_a.product((0..c - 1).to_a).sort { |a, b| (a[0] - r0).abs + (a[1] - c0).abs <=> (b[0] - r0).abs + (b[1] - c0).abs } end r = 2 c = 2 r0 = 0 c0 = 1 p all_cells_dist_order(r, c, r0, c0)
true
6f967068c3078367d0424cb66e56b50ec97f8da2
Ruby
philiplambok/cpractice
/leetcode/goat.rb
UTF-8
600
3.9375
4
[]
no_license
# @param {String} s # @return {String} def to_goat_latin(s) consonant = %w[a i u e o] a_counter = 1 s_arr = s.split(' ') s_arr.each_with_index do |word, index| if consonant.include?(word[0].downcase) a_word = 'a' * a_counter s_arr[index] = "#{word}ma#{a_word}" else first_char = word[0] a_word = 'a' * a_counter word[0] = '' s_arr[index] = "#{word}#{first_char}ma#{a_word}" end a_counter += 1 end s_arr.join(' ') end s = 'I speak Goat Latin' p to_goat_latin(s) s = 'The quick brown fox jumped over the lazy dog' ex = to_goat_latin(s)
true
aac59a4270bb0af685fe6ff7dc90fa9b6649b4fb
Ruby
gmalkas/timetablesonrails
/app/presenters/course_presenter.rb
UTF-8
489
2.859375
3
[]
no_license
## # # = CoursePresenter # # Decorates Course to encapsulate the knowledge associated # with course rendering. # class CoursePresenter attr_accessor :course def initialize(course) @course = course end ## # # Renders a course partial according to the course's state # (assigned to a manager or not). # def render(context) if @course.assigned? context.render 'courses/assigned_course', course: course else context.render course end end end
true
5ca1db6889f50db90a596b3f752cb4efcfa4b9dd
Ruby
diniscoelho/Ruby-FCT
/casewhen.rb
UTF-8
200
3.625
4
[]
no_license
print 'Insira a sua idade: ' idade = gets.to_i case idade when 0..12 puts "vocΓͺ Γ© uma crianΓ§a" when 13..17 puts "vocΓͺ Γ© um adolescente" else puts "vocΓͺ Γ© um adulto" end
true
281f352246771ef39e4c6a0b07e07cbca065e02b
Ruby
nicolai86/url_plumber
/lib/url_plumber/plumber.rb
UTF-8
1,634
2.90625
3
[ "MIT" ]
permissive
require "active_support/hash_with_indifferent_access" module UrlPlumber class Plumber attr_accessor :params def initialize params @params = dup(params) end def extract key_path keys = key_path.to_s.split('.').map(&:to_sym) key = keys[-1] scope = params keys[0..-2].each do |part| scope = scope.fetch(part) { HashWithIndifferentAccess.new } end if scope.has_key?(key) scope[key] else nil end end def plumb attributes = {} scope = dup(params) attributes.each do |key, value| scope = update_scope scope, key, value end scope end def update_scope scope, key_path, value = nil keys = key_path.to_s.split('.').map(&:to_sym) key = keys[-1] scopes = [] keys[0..-2].each do |part| scopes << scope scope = scope.fetch(part) { HashWithIndifferentAccess.new } end if value.nil? scope.delete key else scope[key] = value end keys[0..-2].reverse.each do |part| parent = scopes.pop parent[part] = scope scope = parent end scope end private # params.dup returns the original request parameters in Ruby on Rails # so we need to get our hands dirty to create an actual copy of the params def dup hash new_hash = ::HashWithIndifferentAccess.new hash.each do |key, value| if value.is_a?(Hash) new_hash[key] = dup(value) else new_hash[key] = value end end return new_hash end end end
true
bfe994e916af5a4c824e07d21d381b9c3c6f9d57
Ruby
drewwebs/DrivingHistoryReporter
/spec/trip_spec.rb
UTF-8
785
2.984375
3
[]
no_license
require "trip" describe Trip do let(:valid_trip) { Trip.new("00:00", "01:00", 60) } let(:invalid_trip) { Trip.new("00:00", "01:00", 150) } describe "#initialize" do it "should set up instance variables" do [:distance, :duration_in_hours].each do |attribute| expect(valid_trip).to respond_to attribute end end end describe "#valid_speed?" do context "given a speed between 5-100mph" do it "returns true" do expect(valid_trip.valid_speed?).to be true end end context "given an invalid speed" do it "returns false" do expect(invalid_trip.valid_speed?).to be false end end end end
true
1018608ca3d92f72b061877d0b02aa8156a3dd35
Ruby
krzyzak/road_runner
/lib/road_runner/reporters/classic.rb
UTF-8
1,472
2.859375
3
[ "MIT" ]
permissive
module RoadRunner module Reporters class Classic attr_reader :exceptions, :failures, :monitor def initialize(monitor: monitor) @monitor = monitor @failures = [] @exceptions = [] @tests = 0 end def report_seed_value(random) puts "Initialized with #{random.seed}" end def increment_tests_count! @tests += 1 end def report banner failures.each do |failure| puts failure.location # puts failure.backtrace end puts "\n Exceptions: \n" exceptions.each do |exception| puts exception#.backtrace end # puts "Slowest test_cases:" # print_results_sorted_by_time(@monitor.test_cases) # puts "Slowest methods:" # print_results_sorted_by_time(@monitor.tests) end def fail(failure) @failures << failure end def error(exception) @exceptions << exception end private def banner puts "\nFinished in #{monitor.total_execution_time} seconds" puts "#{@tests} examples, #{failed_tests_size} failures" puts "Failed Examples:\n" end def failed_tests_size exceptions.size end def print_results_sorted_by_time(results) results.sort_by{|_, v| v }.reverse.each do |key, time| puts "#{key} took #{time}" end end end end end
true
55df18450b932cfa0dc7f7f586292d26717c9a00
Ruby
harisr92/twitspam
/twitter_spam.rb
UTF-8
1,175
3.265625
3
[]
no_license
require 'twitter_classifier' require 'optiflag' module Args extend OptiFlagSet optional_flag "kf" do long_form "knowledge_file" default "twitter_spam.kf" description "knowledge file -- used for storing classification data" end flag "u" do long_form "user" description "the user to classify" end optional_flag "c" do long_form "category" description "The category that the user belongs to. If this is not specified then TwitterSpam will try to guess the user's correct classification." end and_process! end def show_usage() puts "twitter_span -knowledge_file [knowledge_file] -user <user> -category [category]" end knowledge_file = ARGV.flags.kf users = ARGV.flags.u.split(',') category = ARGV.flags.c if users.empty? then show_usage() return end classifier = TwitterClassifier.new(knowledge_file) if category then users.each do |user| classifier.classify(category,user) puts "#{user} is now considered #{category}" end else users.each do |user| spam_pct = classifier.how_spammy(user) puts "#{spam_pct*100}% of #{user}'s recent tweets look like spam" end end classifier.save knowledge_file
true
620af1bc86be913ebff2ae3155ae04f77d3a8b32
Ruby
kaji-hiro/AtCoder_beginner_contest
/ABC184/C-Super_Ryuma.rb
UTF-8
359
3.078125
3
[]
no_license
r1, c1 = gets.split.map(&:to_i) r2, c2 = gets.split.map(&:to_i) if r1 == r2 && c1 == c2 puts 0 elsif (r1 - r2).abs + (c1 - c2).abs <= 3 || ((r1 - r2).abs - (c1 - c2).abs).zero? puts 1 elsif (r1 + c1) % 2 == (r2 + c2) % 2 puts 2 elsif ((r1 - r2).abs - (c1 - c2).abs).abs <= 3 puts 2 elsif (r1 - r2).abs + (c1 - c2).abs <= 6 puts 2 else puts 3 end
true
dc43986089335caa81af6099473184c82080c714
Ruby
idhallie/sorting-string-manipulation
/lib/sort_by_length.rb
UTF-8
1,765
4.53125
5
[]
no_license
# A method which will return an array of the words in the string # sorted by the length of the word. # Time complexity: O(n^2); Turning a string into an array is O(n) because the program has to traverse each character of the string # in order to parse it into an array. Then, sorting the array w/Bubble sort is O(n^2) because for each element in the array O(n) it # has to do O(n) comparisons resulting in O(n^2) run time. # Space complexity: O(n); Turning a string into an array is O(n) because space is allocated for a new array in direct proportion to # the size of my_sentence. Bubble sort is O(1) because it creates the same number of variables (new storage) regardless of the size # of the array. Therefore, this method has O(n) space complexity since the O(n) takes precedence over the O(1) def sort_by_length(my_sentence) array = [] array_index = 0 sentence_length = my_sentence.length word_end = 0 array_word = "" # Instead of .split -- makes an array while word_end <= sentence_length if my_sentence[word_end] != " " && my_sentence[word_end] != nil array_word = array_word + my_sentence[word_end] word_end += 1 elsif array_word != "" array[array_index] = array_word array_index += 1 array_word = "" word_end +=1 else word_end +=1 end end # Arrange array using bubble sort w/optimization for already sorted arrays length = array.length i = 0 swapped = true while i < length-1 && swapped j = 0 swapped = false while j < length-i-1 if array[j].length > array[j+1].length temp = array[j] array[j] = array[j+1] array[j+1] = temp swapped = true end j += 1 end i += 1 end return array end
true
ec88ab4a41853bf8e7e7158e04913d0f3dd93799
Ruby
bitprophet/nanoc
/lib/nanoc3/helpers/html_escape.rb
UTF-8
1,562
3.375
3
[ "MIT" ]
permissive
# encoding: utf-8 module Nanoc3::Helpers # Contains functionality for HTML-escaping strings. module HTMLEscape require 'nanoc3/helpers/capturing' include Nanoc3::Helpers::Capturing # Returns the HTML-escaped representation of the given string or the given # block. Only `&`, `<`, `>` and `"` are escaped. When given a block, the # contents of the block will be escaped and appended to the output buffer, # `_erbout`. # # @example Escaping a string # # h('<br>') # # => '&lt;br&gt;' # # @example Escaping with a block # # <% h do %> # <h1>Hello <em>world</em>!</h1> # <% end %> # # The buffer will now contain β€œ&lt;h1&gt;Hello &lt;em&gt;world&lt;/em&gt;!&lt;/h1&gt;” # # @param [String] string The string to escape # # @return [String] The escaped string def html_escape(string=nil, &block) if block_given? # Capture and escape block data = capture(&block) escaped_data = html_escape(data) # Append filtered data to buffer buffer = eval('_erbout', block.binding) buffer << escaped_data elsif string string.gsub('&', '&amp;'). gsub('<', '&lt;'). gsub('>', '&gt;'). gsub('"', '&quot;') else raise RuntimeError, "The #html_escape or #h function needs either a " \ "string or a block to HTML-escape, but neither a string nor a block was given" end end alias h html_escape end end
true
02a69d2ae2a92454fa83425a6fb97e9ed0d2e951
Ruby
standardgalactic/euler
/solutions/problem96.rb
UTF-8
3,167
3.171875
3
[]
no_license
require 'colored' def constraints(puzzle, index) r = row(puzzle, index) c = col(puzzle, index) b = block(puzzle, index) (1..9).select do |i| not r.include? i and not c.include? i and not b.include? i end end def parse_puzzle(str) str.chars.map { |i| i.to_i } end def row(puzzle, index) r = index / 9 puzzle[r*9...r*9+9] end def col(puzzle, index) c = index % 9 puzzle.values_at(*(0...9).map { |i| i*9 + c }) end def block(puzzle, index) r = index / 9 r = r - (r % 3) c = index % 9 c = c - (c % 3) tr = r * 9 + c puzzle.values_at(*[tr, tr + 1, tr + 2, tr + 9, tr + 10, tr + 11, tr + 18, tr + 19, tr + 20]) end def print_puzzle(puzzle, emph = []) print "\n" + "-".blue * 25 + "\n" puzzle.each_with_index do |n, i| print "| ".blue if i % 3 == 0 if emph.include? i print "#{n} ".red elsif n == 0 print "#{n} ".yellow else print "#{n} " end print "|".blue if i % 9 == 8 puts if i % 9 == 8 print "-".blue * 25 + "\n" if i % 9 == 8 and i/9 % 3 == 2 end puts end str = "003020600900305001001806400008102900700000008006708200002609500800203009005010300" # str = "200080300060070084030500209000105408000000000402706000301007040720040060004010003" # str = "300200000000107000706030500070009080900020004010800050009040301000702000000008006" # str = "004000000000030002390700080400009001209801307600200008010008053900040000000000800" # str = "608070502050608070002000300500090006040302050800050003005000200010704090409060701" puzzle = parse_puzzle(str) $count = 0 def solve(puzzle, depth = 2) bf = 1 while puzzle.include? 0 progress = false puzzle.each_with_index do |n, i| next unless n == 0 cons = constraints(puzzle, i) if cons.size == 0 $count += 1 puts $count return false elsif cons.size == 1 puzzle[i] = cons.first progress = true elsif cons.size <= bf cons.each do |c| branch = puzzle.clone branch[i] = c solution = solve(branch, depth - 1) return solution if solution end end end unless progress unless depth <= 0 bf += 1 depth -= 1 else return false end end end return puzzle end def solve_bfs(puzzle) bf = 1 while puzzle.include? 0 progress = false puzzle.each_with_index do |n, i| next unless n == 0 cons = constraints(puzzle, i) if cons.size == 0 $count += 1 puts $count return false elsif cons.size == 1 puzzle[i] = cons.first progress = true elsif cons.size <= bf cons.each do |c| branch = puzzle.clone branch[i] = c solution = solve(branch, depth - 1) return solution if solution end end end unless progress unless depth == 0 bf += 1 else return false end end end return puzzle end print_puzzle(puzzle) for depth in 1..Float::INFINITY solution = solve(puzzle, depth) next if solution end print_puzzle(solution) if solution
true
e4e8a6761bb09a5bf149a3a9dc6dd71ae693987a
Ruby
prisara/object_oriented_programming1
/mars_rover/mars_rover.rb
UTF-8
2,347
4.5
4
[]
no_license
# create Rover class class Rover attr_accessor :name, :x_coordinate, :y_coordinate, :direction # initialize location and direction properties def initialize(name, x_coordinate, y_coordinate, direction) @name = name @x_coordinate = x_coordinate @y_coordinate = y_coordinate @direction = direction end # method to accept instruction and decide whether to tell the rover to move or turn def read_instruction puts "Earth to Mars Rovers. Earth to Mars Rovers. State your name and position please." puts "This is #{@name} at #{@x_coordinate} #{@y_coordinate} facing #{@direction}. Standby Mode. Awaiting next dispatch mission:" mission = gets.chomp @instructions = mission.split(//) # .split mission string into substrings and return an array @instructions.each do |instruction| # iterate over instructions array if instruction == "M" def move elsif instruction == "L" def turn elsif instruction == "R" def turn end end end # method to affect rover's position and update the x or y coordinates def move(@direction, @x_coordinate, @y_coordinate) if @direction == N @y_coordinate += 1 elsif @direction == E @x_coordinate += 1 elsif @direction == S @y_coordinate -= 1 else @direction == W @x_coordinate -= 1 end end # method to affect direction of the rover def turn(@direction, @instructions) if @direction == "N" && @instructions == "R" @direction = "E" elsif @direction == "N" && @instructions == "L" @direction == "W" elsif @direction == "E" && @instructions == "R" @direction == "S" elsif @direction == "E" && @instructions == "L" @direction == "N" elsif @direction == "S" && @instructions == "R" @direction == "W" elsif @direction == "S" && @instructions == "L" @direction == "E" elsif @direction == "W" && @instructions == "R" @direction == "N" else @direction == "W" && @instructions == "L" @direction == "S" end end end puts "Navigation complete. This is #{@name} at #{@x_coordinate} #{@y_coordinate} facing #{@direction}. Transmitting data... Transmission complete. Good-bye." # instances of Rover class rover1 = Rover.new("SpaceOddity", 1, 2, "N") rover2 = Rover.new("SpaceCadet", 3, 3, "E")
true
23940e3a48d638caa27db7d7305daef9e05a6c47
Ruby
sunnyrajrathod/sample-code-ruby
/REST/WebHooks/create-webhook.rb
UTF-8
1,654
2.671875
3
[ "MIT" ]
permissive
require 'authorizenet_rest' require 'json' require '../config.rb' def createAWebhook() # object creation for WebhooksApi class api_instance = AuthorizeNetRest::WebhooksApi.new # object creation for external config class commonObj = AuthorizeNetRestConfiguration::Common.new authorisation = commonObj.credentials eventTypes = ["net.authorize.customer.created"] # object creation for CreateWebhookBody class create_webhook_body = AuthorizeNetRest::CreateWebhookBody.new create_webhook_body.name = "WebhooksEvent" create_webhook_body.url = "https://requestb.in/1kzkehe1" create_webhook_body.event_types = eventTypes create_webhook_body.status = "InActive" begin # call to api response = api_instance.create_webhook(create_webhook_body,:authorization=>authorisation) # access the data from response with the key name as in the respective model class Eg:in response if the key name is customerName, # then in model class it will be customer_name,so access like response.customer_name.(attribute match as per response JSON field # is handled in each model class) puts "Webhooks created!" puts "Webhook Id: #{response.webhook_id}" puts "Name : #{response.name}" # Exception part rescue AuthorizeNetRest::ApiError=>e if e.response_body !=nil resp = JSON.parse(e.response_body) puts "Webhooks creation failed:" puts "Status:#{resp['status']}" puts"Reason: #{resp['message']}" else puts "#{e}" end end response end if !(Dir.pwd).include? "TestRunner" createAWebhook() end
true
723877817b80af99b530ab2ae22f3e43f1a2f5f5
Ruby
dharmjeetkr/Api_app
/app/models/todo.rb
UTF-8
1,039
2.609375
3
[]
no_license
class Todo < ApplicationRecord has_many :items, dependent: :destroy validates_presence_of :title, :created_by Results1="Results" #def self.params() # "hello worlds, india, america" #end def self.ody(title) #logger.info "#{title[:title].inspect}----------------" od1 = Odyssey.flesch_kincaid_re(title[:title], true) od2 = Odyssey.Flesch_Kincaid_Gl(title[:title], true) od3 = Odyssey.flesch_kincaid_re(title[:title], false) od4 = Odyssey.Flesch_Kincaid_Gl(title[:title], false) od5 = Odyssey.analyze_multi(title[:title], ['FleschKincaidRe', 'FleschKincaidGl'], true) od6 = Odyssey.analyze_multi(title[:title], ['FleschKincaidRe', 'FleschKincaidGl'], false) p Results1=>"{ {SCORE1:[ FleschKincaidRe => {#{od3}}], FleschKincaidRe => #{od1} }, {SCORE2:[ FleschKincaidGl => {#{od4}}], FleschKincaidGl => #{od2} }, { SCORE3:[ mix of both => #{od6}], mix of both => #{od5} } }" end end
true
64cae3bfc291cec6cdbe0f7117177655843a994f
Ruby
mobius-network/mobius-tipbot-ruby
/tip_bot/tipped_message.rb
UTF-8
1,827
2.71875
3
[]
no_license
# Saves stats for tipped message class TipBot::TippedMessage extend Dry::Initializer # @!method initialize # @param message [Telegram::Bot::Types::Message] Telegram message object # @!scope instance param :message # Returns overall tips sum in currency for the message # @return [Float] tips sum def balance TipBot.redis.get(key(:balance)).to_f end # Tips the message # @param nickname [String] tipper's nickname # @param value [Numeric] tip's value # @return [Integer] 1 if tip was successful def tip(nickname, value = TipBot.config.rate) TipBot.redis.incrbyfloat(key(:balance), value || TipBot.config.rate) TipBot.redis.zadd(key(:lock), count + 1, nickname) end # Returns true if user with given nickname tipped the message already # @param nickname [String] user's nickname # @return [Boolean] def tipped?(nickname) !TipBot.redis.zscore(key(:lock), nickname).nil? end # Returns overall tips count for the message # @return [Integer] tips count def count TipBot.redis.zcard(key(:lock)).to_i end def all_tippers @all_tippers ||= TipBot.redis.zrange(key(:lock), 0, -1).map { |u| TipBot::User.new(username: u) } end # Stores id of bot's message with tip button for future references # @param keyboard_message_id Telegram message id def attach_button(keyboard_message_id) TipBot.redis.set(key(:keyboard_message), keyboard_message_id) end # Returns id of bot's message with tip button # @ return [Integer] Telegram message id def button_message_id TipBot.redis.get(key(:keyboard_message))&.to_i end def author @author ||= TipBot::User.new(message.from) end private def key(scope) "#{BASE_KEY}:#{scope}:chat:#{message.chat.id}:#{message.message_id}".freeze end BASE_KEY = "message".freeze end
true
54b8236c4fdb0829e0c6e005f1bf74cf1cf8821c
Ruby
pbc/poker-test
/lib/poker_game/game_engine.rb
UTF-8
655
3.078125
3
[]
no_license
module PokerGame class GameEngine def sort_hands_by_rank(poker_hands) collections = collection_factory.split_into_collections(poker_hands) collections.each do |collection| collection.sort! end collections.sort do |collection_x,collection_y| collection_x <=> collection_y end collections.map do |collection| collection.poker_hands end.flatten end def collection_factory PokerGame::RankedCollectionFactory.new end def create_poker_hands(poker_hands_data) poker_hands_data.map do |cards| PokerGame::PokerHand.new(cards) end end end end
true
190a4392698a3f6de812e35ab7535333e4c120b2
Ruby
ramikhalaf/Ruby
/song-list.rb
UTF-8
1,004
3.953125
4
[]
no_license
class SongList def initialize @songs = Array.new end def append(aSong) @songs.push(aSong) self end def deleteFirst @songs.shift end def deleteLast @songs.pop end def [](key) return @songs[key] if key.kind_of?(Integer) return @songs.find { |aSong| aSong.name == key } end end class Song def initialize(name, artist, duration) @name = name @artist = artist @duration = duration @plays = 0 end @@plays = 0 attr_reader :name, :artist, :duration attr_writer :duration def durationInMinutes @duration/60.0 end def durationInMinutes=(value) @duration = (value*60).to_i end def play @plays += 1 @@plays += 1 "This song: #{@plays} plays. Total #{@@plays} plays" end def to_s "Song: #{@name} == #{@artist} (#{@duration})" end end list = SongList.new list. append(Song.new('title1', 'artist1', 1)). append(Song.new('title2', 'artist2', 2)). append(Song.new('title3', 'artist3', 3)). append(Song.new('title4', 'artist4', 4)) puts list[0]
true
86c994448c62d5f6654acdc6bc8a412909447a69
Ruby
barrywilso/Project-Gameshop
/models/customer.rb
UTF-8
1,298
3.296875
3
[]
no_license
require_relative("../db/sql_runner") class Customer attr_reader :id attr_accessor :first_name, :last_name def initialize(customer) @id = customer['id'].to_i() if customer['id'] @first_name = customer['first_name'] @last_name = customer['last_name'] end def save() sql = "INSERT INTO customers (first_name, last_name) VALUES ($1, $2) RETURNING id" values = [@first_name, @last_name] result = SqlRunner.run(sql, values) @id = result[0]['id'].to_i() end def format_name() return "#{@first_name} #{@last_name}" end def self.all() sql = "SELECT * FROM customers" customers = SqlRunner.run(sql) return customers.map {|customer| Customer.new(customer)} end def self.find(id) sql = "SELECT * FROM customers WHERE id = $1" values = [id] customer = SqlRunner.run(sql, values).first() return Customer.new(customer) end def update() sql = "UPDATE customers SET (first_name, last_name) = ($1, $2) WHERE id = $3" values = [@first_name, @last_name, @id] SqlRunner.run(sql, values) end def self.delete_all() sql = "DELETE FROM customers" SqlRunner.run(sql) end def delete() sql = "DELETE FROM customers WHERE id = $1" values = [@id] SqlRunner.run(sql, values) end end
true
10018a7cfc73679c74a6e51b9242c67913ff0da6
Ruby
Njunu-sk/Ruby
/Test/obj.rb
UTF-8
96
3.40625
3
[]
no_license
obj = Object.new def obj.talk puts "Iam an object" puts "Simon is my name" end obj.talk
true
e7516f2bcf1b04ffa722d69e6c7fa2be15a1f154
Ruby
IceDragon200/mruby-nanovg
/docstub/paint.rb
UTF-8
766
2.796875
3
[]
no_license
module Nanovg # A pattern or painting object class Paint # @!attribute xform # @return [Transform] attr_accessor :xform # @!attribute extent # @return [Array<Float>] 2 floats defining the extent attr_accessor :extent # @!attribute radius # @return [Float] attr_accessor :radius # @!attribute feather # @return [Float] attr_accessor :feather # @!attribute inner_color # @return [Color] attr_accessor :inner_color # @!attribute outer_color # @return [Color] attr_accessor :outer_color # @!attribute image # @return [Integer] attr_accessor :image # Initializes the underlying Paint structure # # @return [self] def initialize end end end
true
23fd794969055d077268710882aa6aef72a27215
Ruby
adinsley/Festival_project
/app/models/performance.rb
UTF-8
2,166
2.75
3
[]
no_license
class Performance < ActiveRecord::Base has_many :users, through: :bookings has_many :bookings, dependent: :destroy belongs_to :genre belongs_to :show belongs_to :venue scope :venue_check, -> (v_id){where("venue_id == ?", v_id)} scope :finish_after, -> (start){where("finish > ?", start)} scope :start_before, -> (finish){where("start < ?", finish)} scope :overlap_check, -> (v_id,start,finish){venue_check(v_id).finish_after(start).start_before(finish)} validates :start, :finish, :price, presence: true validates :price, numericality: {greater_than: 0} validates :restrictions, :description, length: {maximum: 2000, too_long:"2000 characters is the maximum allowed in restrictions and description"} validate :finish_time_is_after_start_time validate :set_max_duration def self.search(query) # where(:title, query) -> This would return an exact match of the query where("description", "%#{query}%") end def self.newest_performances all = Performance.all.order(("created_at DESC")) all.first(4) end def human_readable_start_date start.strftime('%A, %B %-d %Y') end def human_readable_start_time start.strftime('%H:%M') end def human_readable_end_date finish.strftime('%A, %B %-d %Y') end def human_readable_end_time finish.strftime('%H:%M') end def duration_in_minutes ((finish - start)/60).to_i end def tickets_sold array = self.bookings.map do |booking| booking.tickets end array.sum end def remaining_capacity capacity = self.venue.capacity.to_i capacity - self.tickets_sold end def ten_percent_remain if remaining_capacity < ((self.venue.capacity.to_i)/10) return "Last Few Tickets" else return "Good Ticket Availability" end end def finish_time_is_after_start_time if self.finish < self.start errors.add(:finish, "cannot be before the start time") end end def set_max_duration if ((self.finish - self.start)/3600) > 6 errors.add(:finish, "Duration of performance cannot be more than 6 hours") end end end
true
9e03f37892a0b994d7c10c5452e8849c9b81bb4f
Ruby
chess1424/Programming_contests
/Hacker_rank/Strings/anagram.rb
UTF-8
409
3.359375
3
[]
no_license
t = gets.chomp.to_i t.times do hash = Array.new(26,0); ans = 0; str = gets.chomp if str.length.odd? puts "-1" else for i in str.length / 2 .. str.length-1 hash[str[i].ord - 'a'.ord] += 1 end for i in 0 .. str.length/2 - 1 if hash[str[i].ord - 'a'.ord] == 0 ans += 1 else hash[str[i].ord - 'a'.ord] -= 1 end end puts ans end end
true
6efd030bd05117f710b665464ab440d0f5fd72d2
Ruby
scottdensmore/WoWUpdater
/Addon.rb
UTF-8
964
2.78125
3
[]
no_license
require 'pathname' class Addon attr_accessor :name, :remote_version, :url, :dependencies @local_version = nil @@addons_folder = nil VER_FILE_NAME = "current.ver" def initialize @dependencies = Array.new end def Addon.addons_folder=(value) @@addons_folder = value end def Addon.addons_folder return @@addons_folder end def dir Pathname.new(@@addons_folder) + @name end def local_version if @local_version == nil then ver_file = dir + VER_FILE_NAME if ver_file.exist? then @local_version = ver_file.read.chomp else @local_version = "(no version)" end end @local_version end def local_version=(new_val) if new_val != @local_version then ver_file = dir + VER_FILE_NAME ver_file.open("w") do |file| file.write new_val end @local_version = new_val end end def update_needed? return local_version != remote_version end end
true
48fa10635c38e6983554c42106d522f113241ab7
Ruby
yamiacat/matt-n-charlie-WIZARDS
/models/house.rb
UTF-8
874
3.3125
3
[]
no_license
require_relative("../db/sql_runner.rb") class House attr_reader :id, :house_name, :logo def initialize(params) @id = params['id'].to_i @house_name = params['house_name'] @logo = params['logo'] end def save() sql = "INSERT INTO houses (house_name, logo) VALUES ('#{@house_name}', '#{@logo}' ) RETURNING id;" house_data = SqlRunner.run(sql).first() @id = house_data['id'].to_i() end def House.delete_all() sql = "DELETE FROM houses;" SqlRunner.run(sql) end def House.all() sql ="SELECT * FROM houses;" returned_array = SqlRunner.run(sql) houses = returned_array.map {|house| House.new(house)} return houses end def House.find(id) sql = "SELECT * FROM houses WHERE id = '#{id}';" returned_result = SqlRunner.run(sql) house = House.new(returned_result.first) return house end end
true
ef1ee87751c2a3895dafc9da7abbee4cad4aae9e
Ruby
JoseyKinnaman/leetspeak
/spec/leetspeak_spec.rb
UTF-8
826
3.34375
3
[ "MIT" ]
permissive
require ('rspec') require ('leetspeak') describe ('String#leetspeak') do it('replaces every "e" or "E" in a string with a "3"') do expect('beE'.leetspeak).to(eq('b33')) end it('replaces every "o" or "O" in a string with a "0"') do expect('Oops'.leetspeak).to(eq('00pz')) end it('replaces every "I" in a string with a "1" but ONLY for uppercase I') do expect('I am high'.leetspeak).to(eq('1 am high')) end it('replaces every "s" in a sring with a "z"') do expect("roses".leetspeak).to(eq("r0z3z")) end it('does NOT replace the first letter when it is an s') do expect("saSsafrass".leetspeak).to(eq("sazzafrazz")) end it('replaces letters correctly in a string of words') do expect("So I love writing codes so much".leetspeak).to(eq("S0 1 l0v3 writing c0d3z z0 much")) end end
true
db135fbd911d7f812356c95bd895c9b4cd2cba9d
Ruby
gitkseniya/garage_2102
/test/owner_test.rb
UTF-8
1,116
3.296875
3
[]
no_license
require_relative 'test_helper' class OwnerTest < Minitest::Test def setup @owner_1 = Owner.new('Regina George', 'Heiress') @car_1 = Car.new({description: 'Green Ford Mustang', year: '1967'}) @car_2 = Car.new({description: 'Silver BMW 3-Series', year: 2001}) @car_3 = Car.new({description: 'Red Chevrolet Corvette', year: 1963}) end def test_it_exists assert_instance_of Owner, @owner_1 end def test_it_has_attributes assert_equal "Regina George", @owner_1.name assert_equal "Heiress", @owner_1.occupation end def test_it_can_return_cars assert_equal [], @owner_1.cars @owner_1.buy('1967 Green Ford Mustang') assert_equal [@car_1], @owner_1.cars @owner_1.buy('2001 Silver BMW 3-Series') assert_equal [@car_1, @car_2], @owner_1.cars end def test_it_can_buy_a_car assert_equal @car_1, @owner_1.buy('1967 Green Ford Mustang') end def test_it_can_return_vintage_cars @owner_1.buy('1967 Green Ford Mustang') @owner_1.buy('2001 Silver BMW 3-Series') @owner_1.buy('1963 Red Chevrolet Corvette') assert_equal [@car_1, @car_3] end end
true
96b3257937d2ae6677d9a37229a070f110e15cfc
Ruby
Salaizrm/prime-ruby-onl01-seng-pt-012220
/prime.rb
UTF-8
118
3.375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(num) if num > 1 (2..num-1).none? {|prime| num % prime == 0} else false end end
true
70d7337517294ae8b9f77dd123943f322fba09ad
Ruby
taurusismysign/iotmicroservices
/app/sync/sync_data.rb
UTF-8
549
2.546875
3
[]
no_license
require 'httparty' class SyncData def self.follow @experts = Expert.limit(10) t = TwitterSync.new t.Follow(@experts) end def self.process #DEVELOPER NOTE: #Get all the tweets. Later on we could horizontally split it #to scale by pulling experts based on certain filter criteria #for each horizontal process #connect to the "catalog" service and get all the experts response = HTTParty.get(ENV['ExpertLookupService'], {timeout: 15}) t = TwitterSync.new t.SyncTweets(response.body) end end
true
20a14b9f4735d6c862d834df9d3f33bc14a1c391
Ruby
NiranjanSarade/ruby_gunner_client
/player_state.rb
UTF-8
561
3.09375
3
[]
no_license
require File.expand_path('../orientation', __FILE__) class PlayerState attr_accessor :name, :x, :y, :orientation, :weaponOrientation, :energy def initialize(name="", x=0.0, y=0.0, orientation=0.0, weaponOrientation=0.0, energy=0.0) @name = name @x = x @y = y @orientation = Orientation.new(orientation) @weaponOrientation = Orientation.new(weaponOrientation) @energy = energy end end class MathUtil def self.clamp(val,min,max) clamped_value = [min,[val,max].min].max.round(3) end end
true
df37cfb30b956902e7bc1e6920316612b26c8e56
Ruby
beachio/hammer-gem
/test/hammer/unit/cacher_test.rb
UTF-8
2,752
2.6875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require '../test_helper' unless defined?(Hammer) require 'rake' require 'tmpdir' require 'hammer' require 'hammer/cacher' # A cacher object for a Hammer project. # Takes project-wide dependencies, and wildcard dependnecies # Dependencies: # {'index.html' => ['about.html']} # Wildcard Dependencies: # {'index.html' => {'about' => ['about.html']} class CacherTest < Test::Unit::TestCase context "A cacher" do setup do @input_directory = Dir.mktmpdir @output_directory = Dir.mktmpdir @cache_directory = Dir.mktmpdir @dependencies = {} @wildcard_dependencies = {} @object = Hammer::Cacher.new(@input_directory, @cache_directory, @output_directory) end teardown do FileUtils.rm_rf @input_directory FileUtils.rm_rf @output_directory FileUtils.rm_rf @cache_directory end # should "return false if checking the caching of an object" do # assert !@object.cached?('index.html') # end context "having cached a file" do setup do @file = File.join(@input_directory, 'index.html') File.open(@file, 'w') { |f| f.puts "Input" } @object.cache('index.html', @file) @object.write_to_disk @object = Hammer::Cacher.new(@input_directory, @cache_directory, @output_directory) end should "have a valid cache" do assert @object.cached?('index.html') end should "have a valid cache until the file is changed" do File.open(@file, 'w') { |f| f.puts "Modified Input" } assert !@object.cached?('index.html') end end # context "with two files" do # setup do # @this_file = File.join(@input_directory, 'index.html') # @other_file = File.join(@input_directory, 'about.html') # File.open(@this_file, 'w') do |file|; file.puts("A"); end # File.open(@other_file, 'w') do |file|; file.puts("B"); end # end # context "with dependencies" do # setup do # @object.dependencies = {'index.html' => ['about.html']} # @object.cache('index.html', @this_file) # end # should "have a cache if the other file is cached too" do # assert !@object.cached?('index.html') # @object.cache('about.html', @other_file) # assert @object.cached?('index.html') # end # end # context "with wildcard dependencies" do # setup do # @object.wildcard_dependencies = {'index.html' => {'about' => ['about.html']}} # @object.cache('index.html', @this_file) # end # should "have a cache of this file" do # assert @object.cached?('index.html') # end # end # end end end
true
21c910b2606ad95de252477f1306a2be0311fcb4
Ruby
Lightspeed-Systems/clever-ruby
/lib/clever-ruby/api_operations/list.rb
UTF-8
4,988
3.0625
3
[ "Apache-2.0", "MIT" ]
permissive
module Clever # API Operations module APIOperations # A list of API resource instances module List # Class methods for those that include List # @api public module ClassMethods # Get all elements of a resource # @api public # @deprecated This can be costly since it places all matching elements # in memory. Instead just iterate over the collection using each. # @param filters [Hash] parameters to apply, as per the Clever API spec # @return [Array] array of all elements matching the request # @example # Clever::District.all def all(filters = {}, headers = {}) accum = [] Clever::APIOperations::PageList.new(url, filters, headers).each do |page| accum += page.all end accum end # Get elements of a resource. Supports 1 or more ids, or open-ended query # @api public # @param id [String, Array, nil] ID or array of ids to match, or nil # for query # @param filters [Hash, nil] Query parameters to pass, as per Clever API spec # @return [Clever::APIResource, Clever::APIOperations::ResultsList] # single resource or iterable list of results # @raise [ArgumentError] Bad ID/IDs provided # @example # # Get first 20 clever districts # districts = Clever::District.find.take 20 # # # Get specific district # id = '...' # district = Clever::District.find id # # # Get districts with given ids # ids = ['...', '...'] # districts = Clever::District.find ids def find(id = nil, filters = {}, headers = {}) if id.is_a? Array unless id.select { |e| !Clever::Util.valid_id? e }.empty? fail ArgumentError, 'Array of IDs must only contain valid ObjectIDs' end filters[:where] = JSON.dump(_id: { :'$in' => id }) end if id.nil? || id.is_a?(Array) Clever::APIOperations::PageList.new(url, filters, headers).to_results_list elsif Clever::Util.valid_id? id retrieve id else fail ArgumentError, 'id must be a valid ObjectID, an array of them, or nil.' end end # Query for the first element or n elements in the resource # @api public # @param num [nil, Integer] If nil, first elem; else, num elems to fetch # @param filters [Hash] Filters to request with, as per Clever API spec # @return [CleverObject, Clever::APIOperations::Page] elem, or # elems found. # @example # first_elem = Clever::District.first # first_elems = Clever::District.first 20 # first_elems.each do |e| # puts e.name # end def first(num = nil, filters = {}, headers = {}) if num.nil? filters[:limit] = 1 response = Clever.request :get, url, filters, headers Util.convert_to_clever_object response[:data].last else filters[:limit] = num Clever::APIOperations::PageList.new(url, filters, headers).first end end # Query for the last element or n elements in the resource # @api public # @param num [nil, Integer] If nil, last elem; else, num elems to fetch # @param filters [Hash] Filters to request with, as per Clever API spec # @return [CleverObject, Clever::APIOperations::ResultsList] elem, or # elems found. If list, sorted in ascending order of ids. # @example # last_elem = Clever::District.last # last_elems = Clever::District.last 20 # last_elems.each do |e| # puts e.name # end def last(num = nil, filters = {}, headers = {}) filters[:ending_before] = 'last' if num.nil? filters[:limit] = 1 response = Clever.request :get, url, filters, headers Util.convert_to_clever_object response[:data].last else filters[:limit] = num Clever::APIOperations::PageList.new(url, filters, headers).to_results_list end end # Requests number of elements matching the query # @api public # @param filters [Hash, nil] Query parameters to pass, as per Clever API spec # @return [Integer] Number of elements matching # @example # num_districts = Clever::District.count def count(filters = {}, headers = {}) filters[:count] = true response = Clever.request :get, url, filters, headers response[:count] end end # Add ClassMethods to classes that include List # @api private # @return [nil] def self.included(base) base.extend ClassMethods end end end end
true
64f663cb5993c034fba2a9012ee376e81c4ad4c7
Ruby
KeenanJones1/Lectio-Victoria-v1
/test/models/user_test.rb
UTF-8
858
2.53125
3
[]
no_license
require 'test_helper' class UserTest < ActiveSupport::TestCase def setup @user = users(:valid) end test 'valid user' do assert @user.valid?, "Please check user requirements" end test 'invalid without name' do @user.name = nil # refute - Fails if test is a true value refute @user.valid?, 'saved user without name' # asert_not_nil tests if expression is not nil assert_not_nil @user.errors[:name], 'no validation error for name present' end test '#stats' do assert_equal 7, @user.stats.size end test 'invalid without email' do @user.email = nil refute @user.valid? assert_not_nil @user.errors[:email], 'no validation error for email present' end # @user.email = nil # refute @user.valid? # assert_not_nil @user.errors[:email], 'no validation error for email present' end
true
df46ab76d692e7e2a92d9feb40f5fda626131ba1
Ruby
RubyCamp/rc2012w_g1
/scenes/stages/characters/simplemove.rb
SHIFT_JIS
1,020
3.0625
3
[]
no_license
require_relative "character" require "dxruby" require "dxrubyex" module SimpleMove #def self.included(base); puts "#{base}.included #{self}" end def move #puts "move" super if @mvstt == :hide && rand < 0.01 #Μ’lς邱ƂŏoΟ‚ @mvstt = :out @mvtimes = @speed end if @mvstt == :out @mv ||= Math.sqrt(@mx ** 2 + @my ** 2).round @x += (((@mv / @speed) * @mx) / @mv).round @y += (((@mv / @speed) * @my) / @mv).round @mvtimes -= 1 #puts "#@x #@y #@tempx #@tempy" if @mvtimes == 0 @mvstt = :stop @waittime = rand(300) + 1 end end if @mvstt == :stop if @waittime == 0 @mvstt = :back @mvtimes = @speed else @waittime -= 1 end end if @mvstt == :back @x -= (((@mv / @speed) * @mx) / @mv).round @y -= (((@mv / @speed) * @my) / @mv).round @mvtimes -= 1 if @mvtimes == 0 @mvstt = :hide end end end end
true
dca79aa4abdc075eb69995aa6bcabe1996ca6064
Ruby
fuchsto/aurita
/lib/aurita/base/bits/time_ago.rb
UTF-8
1,971
3.421875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# options # :start_date, sets the time to measure against, defaults to now # :later, changes the adjective and measures time forward # :round, sets the unit of measure 1 = seconds, 2 = minutes, 3 hours, 4 days, 5 weeks, 6 months, 7 years (yuck!) # :max_seconds, sets the maximimum practical number of seconds before just referring to the actual time # :date_format, used with <tt>to_formatted_s<tt> # # Modified usage, like: # puts time_ago(Time.now-100, :round => 5, :format => 'vor %d', :format_less => 'vor weniger als %d') # def time_ago(original, options = {}) start_date = options.delete(:start_date) || Time.now later = options.delete(:later) || false round = options.delete(:round) || 7 max_seconds = options.delete(:max_seconds) || 32556926 date_format = options.delete(:date_format) || :default # array of time period chunks chunks = [ [60 * 60 * 24 * 365 , "Jahr", 'Jahren'], [60 * 60 * 24 * 30 , "Monat", 'Monaten'], [60 * 60 * 24 * 7, "Woche", 'Wochen'], [60 * 60 * 24 , "Tag", 'Tagen'], [60 * 60 , "Stunde", 'Stunden'], [60 , "Minute", 'Minuten'], [1 , "Sekunde", 'Sekunden'] ] if later since = original.to_i - start_date.to_i else since = start_date.to_i - original.to_i end time = [] if since < max_seconds # Loop trough all the chunks totaltime = 0 for chunk in chunks[0..round] seconds = chunk[0] count = ((since - totaltime) / seconds).floor name = chunk[1] if count == 1 name = chunk[2] if count > 1 # time << pluralize(count, name) unless count == 0 time << (count.to_s + ' ' + name) unless count == 0 totaltime += count * seconds end if time.empty? options[:format_less].gsub('%d', '1 ' << chunks[round-1][1]) else # "#{time.join(', ')} #{later ? 'later' : 'ago'}" options[:format].gsub('%d',time[0..1].join(', ')) end else original.to_formatted_s(date_format) end end
true
98787ac07c1a21487fd1a95647910725cd02b6f4
Ruby
Tonyjlum/nyc-pigeon-organizer-nyc-web-111918
/nyc_pigeon_organizer.rb
UTF-8
381
2.90625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def nyc_pigeon_organizer(data) # write your code here! pigeon_list = {} data.each do |key1, value1| value1.each do |key2, names| names.each do |name| pigeon_list[name] = {} if pigeon_list[name].nil? pigeon_list[name][key1] = [] if pigeon_list[name][key1].nil? pigeon_list[name][key1] += [key2.to_s] end end end pigeon_list end
true
3621cb541fc522d6e2b55f2c76c82eb42e7499a3
Ruby
miriamtocino/miritosar
/app/models/company.rb
UTF-8
626
2.578125
3
[]
no_license
class Company < ActiveRecord::Base validates :name, :founded_in, :website, presence: true validates :description, length: { minimum: 25 } validates :staff, numericality: { greater_than: 0 } validates :logo, allow_blank: true, format: { with: /\w+.(gif|jpg|png)\z/i, message: "must reference a GIF, JPG, or PNG image" } default_scope { order('name ASC') } scope :small, -> { where('staff < 15') } scope :medium, -> { where('staff >= 15 || staff <= 50') } scope :large, -> { where('staff > 50') } has_many :reviews, dependent: :destroy def average_stars reviews.average(:stars) end end
true
3575a050628aa715704b774b24122b8ba086d2eb
Ruby
paultag/ocd-division-ids
/scripts/country-ca/ca_census_divisions.rb
UTF-8
1,473
2.71875
3
[]
no_license
#!/usr/bin/env ruby # coding: utf-8 require File.expand_path(File.join("..", "utils.rb"), __FILE__) # Scrapes census division codes and names from statcan.gc.ca class CensusDivisions < Runner def names type_names = census_division_type_names # @see http://www12.statcan.gc.ca/census-recensement/2011/dp-pd/hlt-fst/pd-pl/index-eng.cfm file = open("http://www12.statcan.gc.ca/census-recensement/2011/dp-pd/hlt-fst/pd-pl/FullFile.cfm?T=701&LANG=Eng&OFT=CSV&OFN=98-310-XWE2011002-701.CSV") # The CSV has an extra header row. file.gets # The CSV is in ISO-8859-1. text = file.read.force_encoding("ISO-8859-1").encode("UTF-8") puts CSV.generate_line(%w(id name name_fr classification)) CSV.parse(text, :headers => true, :skip_blanks => true).each do |row| code = row.fetch("Geographic code") name = row.fetch("Geographic name") type = row.fetch("Geographic type") # Skip "Canada" row. next if code == "01" # Stop before footer. break if code == "Note:" value = name. squeeze(" "). # Remove extra spaces, e.g. "Lot 1" sub(/ \([^)]+\)\z/, "") # Remove region, e.g. "Toronto (Ont.)" # @see http://www.statcan.gc.ca/subjects-sujets/standard-norme/sgc-cgt/2001/2001-supp4-eng.htm parts = value.split(" / ", 2) output("cd:", code, parts[0], parts[1] || parts[0], type) end end end CensusDivisions.new("ca_census_divisions.csv").run(ARGV)
true
0db882d19b45ca09cd38f35ce891077d344e0a9d
Ruby
gabrielalewandowska/functions-paired-lab
/ruby_functions_practice.rb
UTF-8
962
3.84375
4
[]
no_license
def return_10() return 10 end def add(number1, number2) return number1 + number2 end def subtract(num1, num2) return num1 - num2 end def multiply(num1, num2) return num1 * num2 end def divide(num1, num2) return num1 / num2 end def length_of_string(string) return string.length end def join_string (str1, str2) return str1 + str2 end def add_string_as_number (str1, str2) return str1.to_i + str2.to_i end def number_to_full_month_name(num) case num when 1 return "January" when 2 return "February" when 3 return "March" when 9 return "September" end end def number_to_short_month_name(num) case num when 1 return "Jan" when 3 return "Mar" when 9 return"Sep" end end def volume_of_cube(length) return 6*(length**2) end def volume_of_sphere(radius) return 4/3*(3.16*(radius)**3) end def farenheit_to_celsius(farenheit) celsius = (farenheit - 32) * 5/9 return celsius.to_i end
true
20d131ff099718eb8608f3db43432497399508d5
Ruby
toshiemon18/tnct_classchange_line_bot
/lib/helper.rb
UTF-8
1,030
2.640625
3
[]
no_license
module TmNCTClassChangeLINEBOT class Helper CLASS_NAME_LIST = { "1εΉ΄1η΅„" => ["1-1"], "1εΉ΄2η΅„" => ["1-2"], "1εΉ΄3η΅„" => ["1-3"], "1εΉ΄4η΅„" => ["1-4"], "1εΉ΄5η΅„" => ["1-5"] } def initialize @yaml = YAML.load_file("./config/app.yml") end def line_client client = TmNCTClassChangeLINEBOT::EasyLineAPI.new( channel_id: @yaml["line"]["channel_id"], channel_secret: @yaml["line"]["channel_secret"], mid: @yaml["line"]["mid"], proxy: @yaml["line"]["proxy"] ) end def classchange_client TmNCTClassChangeLINEBOT::TmNCTClassChangeAPI.new(date) end def translate_to_key(class_name) CLASS_NAME_LIST.each do |key, val| if key == class_name yield key else val.each do |cn| yield key if cn == class_name end end end return false end def has_classchange?(class_name, classchange) chasschange.has_key?(class_name) end end end
true
fd9b607beb6c41f3532c950b0a86aafaea276bc9
Ruby
brianpattison/ingredients
/app/models/recipe.rb
UTF-8
398
2.90625
3
[]
no_license
class Recipe < ActiveRecord::Base has_many :used_ingredients has_many :ingredients, :through => :used_ingredients validates_presence_of :name, :yield validates_numericality_of :yield def cost cost = 0 self.used_ingredients.each do |used_ingredient| cost += used_ingredient.cost end return cost end def cost_each return self.cost/self.yield end end
true
2b03972e2078fde14ae179e867675c4438f9d808
Ruby
mglazner/Homework
/HW8.rb
UTF-8
622
3.96875
4
[]
no_license
# Update this program to keep a running tally of the same stats we were # puts'ing in babylibrary v1. # # > A string here # > Another string here # > exit # A # string # here # Another # string # here # # EXTRA CREDIT! Rather than tallying up the strings, instead process each # string and hold onto another form of data until the end, and print output # from that. require_relative "babylibrary" def main(s) separate_line(s) upcase(s) replace_spaces(s) count_words(s) count_punct(s) sort(s) end s1="" loop do s=gets.chomp if s!="exit" s1<<s else main(s1) break end end
true
22d1c417e5d57447ba65c561b0877b0fbe4d0e52
Ruby
asdFletcher/data-structures-and-algorithms
/src/code-challenges/leetcode/easy/range-sum-bst.rb
UTF-8
1,324
4.21875
4
[ "MIT" ]
permissive
# Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). # The binary search tree is guaranteed to have unique values. # Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 # Output: 32 # Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 # Output: 23 # 30 min # Note: # The number of nodes in the tree is at most 10000. # The final answer is guaranteed to be less than 2^31. # Definition for a binary tree node. class TreeNode attr_accessor :val, :left, :right def initialize(val) @val = val @left, @right = nil, nil end end # @param {TreeNode} root # @param {Integer} l # @param {Integer} r # @return {Integer} def range_sum_bst(root, l, r) sum = 0 return 0 if !root sum += root.val if root.val <= r && root.val >= l sum += range_sum_bst(root.left,l,r) unless root.left == nil sum += range_sum_bst(root.right,l,r) unless root.left == nil return sum end a = TreeNode.new(10) b = TreeNode.new(4) c = TreeNode.new(15) d = TreeNode.new(2) e = TreeNode.new(6) f = TreeNode.new(11) g = TreeNode.new(17) # 10 # 4 15 # 2 6 11 17 # a # b c # d e f g a.left = b a.right = c b.left = d b.right = e c.left = f c.right = g res = range_sum_bst(a, 0, 100) puts "result: #{res}"
true
025167b2ae268f1466e6e38501f9c266d5cf1fc9
Ruby
AJDot/Launch_School_Files
/Exercises/Small_Problems_101-109/easy_3/palindromic_strings_part_2.rb
UTF-8
1,914
4.46875
4
[]
no_license
# palindromic_string_part_2.rb #Understand the problem # - same as part 1 but now case-insensitive and ignore all non-alphanumeric # - characters. May call palindrome? from part 1 # - Input: string # - Output: boolean based on real_palindrome # #Examples / Test Cases # real_palindrome?('madam') == true # real_palindrome?('Madam') == true # (case does not matter) # real_palindrome?("Madam, I'm Adam") == true # (only alphanumerics matter) # real_palindrome?('356653') == true # real_palindrome?('356a653') == true # real_palindrome?('123ab321') == false # #Data Structures # - Input: string # - Output: boolean # #Algorithm / Abstraction # - input string (str) # - modified_string = remove all non-alphanumeric characters from # - str using select # - modified_string = modified_string.downcase # - does modified_string == modified_string.reverse? # - if true, return true, otherwise return false # Program def palindrome?(str) str == str.reverse end def real_palindrome?(str) modified_str = str.downcase.scan(/[a-zA-Z]/).join palindrome?(modified_str) end puts real_palindrome?('madam') == true puts real_palindrome?('Madam') == true # (case does not matter) puts real_palindrome?("Madam, I'm Adam") == true # (only alphanumerics matter) puts real_palindrome?('356653') == true puts real_palindrome?('356a653') == true puts real_palindrome?('123ab321') == false #Further Exploration def real_palindrome_further?(str) modified_str = str.downcase.delete('^a-z0-9') palindrome?(modified_str) end puts real_palindrome_further?('madam') == true puts real_palindrome_further?('Madam') == true # (case does not matter) puts real_palindrome_further?("Madam, I'm Adam") == true # (only alphanumerics matter) puts real_palindrome_further?('356653') == true puts real_palindrome_further?('356a653') == true puts real_palindrome_further?('123ab321') == false
true
f1e4379d43b648f69b923d97c40d7089b8414d7f
Ruby
jamiemonserrate/sales_tax
/lib/sales_tax.rb
UTF-8
595
3.171875
3
[]
no_license
require 'yaml' class SalesTax SALES_TAX_RATE = 0.1 def initialize(product) @product = product end def amount return 0 if is_exempt? round @product.price_before_tax * SALES_TAX_RATE end private def is_exempt? exempt_products.any? {|exempt_product| @product.name.include?(exempt_product)} end def exempt_products YAML::load(File.open(sales_tax_exemptions_config_file).read) end def sales_tax_exemptions_config_file File.dirname(__FILE__) + '/config/sales_tax_exemptions.yml' end def round(amount) amount.round_to_nearest(0.05) end end
true
5d39fa571bd4c6983cbd9cce2170a49ad227ebc6
Ruby
yuan-xy/smally
/c-sky/inst32-16/test2.rb
UTF-8
415
2.71875
3
[]
no_license
lines = [] File.open("16.txt").each_line do |line| lines << line end (1..100).each {|x| lines << "" } puts lines.size count=0 File.open("32.txt").each_line do |line| puts "#{count}: #{line.split[0]} ~ #{lines[count].split[0]}" lines.insert(count," \r\n") if line.split[0] != lines[count].split[0] count+=1 end puts lines.size File.open("16-2.txt","w") do |f| lines.each{|x| f << x} end
true
60cecf5cd2c7fb41a8e819431d7613c72f223f56
Ruby
chetna1726/vinsol_campus_hiring
/app/models/response.rb
UTF-8
1,567
2.578125
3
[]
no_license
class Response < ActiveRecord::Base auto_strip_attributes :answer, squish: true belongs_to :user belongs_to :quiz belongs_to :question belongs_to :option validates :user_id, uniqueness: { :scope => [:quiz_id, :question_id], message: "cannot take quiz more than once"} validates :question_id, uniqueness: { :scope => [:quiz_id, :user_id], message: "cannot have same question in a quiz" } validates :quiz_id, uniqueness: { :scope => [:question_id, :user_id], message: "cannot have the same quiz for a user" } scope :unattempted, -> { where(attempted: false) } scope :by_quiz, ->(quiz_id) { where(quiz_id: quiz_id)} scope :attempted, -> { where(attempted: true) } delegate :value, to: :option, prefix: true, allow_nil: true def self.mark_unattempted(quiz_id) where(quiz_id: quiz_id).unattempted.each do |response| response.update(attempted: true) end end def record_answer(value) unless attempted? if question.type == 'MCQ' update_attributes(option_id: value, attempted: true) else update_attributes(answer: value, attempted: true) end end end def is_correct? if question.type == 'MCQ' correct = ( question.answers[0].id == option_id) else correct = (answer.downcase).in?(question.answers.map{ |a| a.value.downcase }) end correct end def marks_scored is_correct? ? question.points : (-1 * Float(question.points * quiz.negative_marking)/100 ) end def answer_value (question.type == 'MCQ') ? option_value : answer end end
true
96e4a309426894c7a4f480f8ef0fd40b2ec404b6
Ruby
rubyworks/realms
/work/reference/environment.rb
UTF-8
15,731
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
require 'time' require 'roll/core_ext/rbconfig' require 'roll/core_ext/hash' require 'roll/xdg' class Library # An ... represents a set of libraries to be served by Rolls. # class Environment include Enumerable # Instantiate environment given +name+ or file. def initialize(file=nil) @file = File.expand_path(file || Environment.file) @name = File.basename(@file).chomp('.roll') @lookup = [] @index = [] #Hash.new{ |h,k| h[k] = [] } @metadata = {} load end # Environment file. attr :file # TODO: rename to label ? attr :name # Lookup is an Array of directory paths or globs. # # @return [Array] directory names or globs attr :lookup # Project index is a Hash. # The index is generated via #sync based on the `lookup` table. attr :index # Synchronize index to lookup table. def sync @index = lookup_index end ## Environment file (full-path). #def file # @file ||= ( # Library.config.find_environment_file(name) || default_file # ) #end # TODO: Use array instead of Hash to store cache so it will be faster. # TODO: Use simple File read and write instead of Marshal for more speed. def load return unless File.exist?(file) #require_without_rolls 'yaml' #data = YAML.load(File.new(file)) @lookup = [] @index = [] ::File.readlines(file).each do |line| line = line.strip next if line.empty? next if line =~ /^#/ @lookup << line end if ::File.exist?(file + '.cache') begin @index = Marshal.load(File.new(file + '.cache')) rescue TypeError => error warn error.message lookup_index end #::File.readlines(file + '.cache').each do |line| # line = line.strip # next if line.empty? # next if line =~ /^#/ # row = line.split(',') # @index << { # :name => row[0], # :version => Version.new(row[1]), # :date => normalize_date(row[2]), # :location => row[3], # :loadpath => row[4].split(':') # } #end else lookup_index end end # def normalize_date(date) date = date.to_s.strip case date when "" Time.new else Time.parse(date) end end =begin # Save environment file. def save require 'fileutils' out = {:lookup=>lookup, :index=>index}.inspect #.to_yaml file = ::File.join(self.class.home, name) if ::File.exist?(file) old = File.read(file) return false if out == old else dir = File.dirname(file) FileUtils.mkdir_p(dir) unless File.exist?(dir) end ::File.open(file, 'w'){ |f| f << out } @file = file end =end # Save environment cache file. def save require 'fileutils' dump = Marshal.dump(index) file = ::File.join(self.class.home, name + '.cache') dir = ::File.dirname(file) ::FileUtils.mkdir_p(dir) unless File.exist?(dir) File.open(file, 'w') do |writer| writer << dump end @file = file end # Save environment file. def save_lookup require 'fileutils' file = ::File.join(self.class.home, name) dir = ::File.dirname(file) ::FileUtils.mkdir_p(dir) unless File.exist?(dir) File.open(file, 'w') do |writer| writer << lookup.join("\n") end end # Create a new environment +new_name+ with the contents # of the current enviroment. def copy(new_name) new_env = dup new_env.instance_eval do @name = new_name @file = nil end new_env end # Merge two environments. +Other+ can either be an Environment object # or the name of one. # # NOTE: It is probably best to re-sync the environment after this. def merge!(other) if !(Environment === other) other = Environment.new(other) # self.class.new(other) end @lookup = lookup | other.lookup @index = index.merge(other.index) self end # Generate index from lookup list. def lookup_index index = [] lookup.each do |glob| # dev? locations = find_projects(glob) locations.each do |location| data = metadata(location).to_h name = data[:name] name = nil if name && name.empty? next if name == 'roll' # do not include roll itself! if name #&& vers #data[:development] = !!dev # TODO: what does dev do again? index << data else warn "roll: invalid .ruby file, omitting -- #{location}" end end end index end # Loop through the lookup paths and locate all projects within # them. Projects are identified by having .ruby/ entries, # or being an installed gem. def locate lookup.map{ |dir_or_glob| # dev? find_projects(dir_or_glob) }.flatten end # Search a given directory for projects upto a given depth. Projects # directories are determined by containing a .ruby directory or being # a rubygems location. # # Even though Rolls can locate gems, adding a set of .ruby entries # to you project is adventageous as it allows Rolls operate faster. def find_projects(dir_or_glob) #depth = Integer(depth || 3) libs = [] #(0..depth).each do |i| # star = ::File.join(dir, *(['*'] * i)) search = ::Dir.glob(dir_or_glob) search.each do |path| if dotruby?(path) libs << path elsif gemspec?(path) libs << path end end libs.uniq end # Return Metadata for given +location+. The Metadata object # is cached based on the +location+. def metadata(location) @metadata[location] ||= Metadata.new(location) end # Iterate over the index. def each(&block) index.each(&block) end # Size of the index. def size ; index.size ; end # Append an entry to the lookup list. def append(path, depth=3, live=false) path = ::File.expand_path(path) depth = (depth || 3).to_i @lookup = @lookup.reject{ |(p, d)| path == p } @lookup.push([path, depth, !!live]) end # Remove an entry from lookup list. def delete(path) @lookup.reject!{ |p,d| path == p } end # Returns name and loadpath of project at +location+. #def libdata(location) # data = # name = data.name # version = data.version # loadpath = data.loadpath # return name, loadpath #end # Does this location have .ruby/ entries? # TODO: Really is should at probably have a `version` too. def dotruby?(location) file = ::File.join(location, '.ruby') return false unless File.file?(file) return true end # Is this location a gem home location? def gemspec?(location) #return true if Dir[File.join(location, '*.gemspec')].first pkgname = ::File.basename(location) gemsdir = ::File.dirname(location) specdir = ::File.join(File.dirname(gemsdir), 'specifications') gemspec = ::Dir[::File.join(specdir, "#{pkgname}.gemspec")].first end # Does the environment include any entires that lie within the *current* # gem directory? def has_gems? dir = (ENV['GEM_HOME'] || ::Config.gem_home) rex = ::Regexp.new("^#{Regexp.escape(dir)}\/") return true if lookup.any? do |(path, depth)| rex =~ path end return true if index.any? do |name, vers| vers.any? do |path, loadpath| rex =~ path end end return false end # def inspect "#<#{self.class}:#{object_id} #{name} (#{size} libraries)>" end # Returns a string representation of lookup and index # exactly as it is stored in the environment file. def to_s out = '' out << "#{name} " out << "(%s libraries)\n" % [index.size] out << "\nLookup:\n" out << to_s_lookup out << "\n" out << "(file://#{file})" out end # Returns a String of lookup paths and depths, one on each line. def to_s_lookup str = "" max = lookup.map{ |path| path.size }.max lookup.each do |path| str << (" - %-#{max}s \n" % [path]) #, dev ? '(development)' : '']) end str end # Returns a string representation of lookup and index # exactly as it is stored in the environment file. def to_s_index max = ::Hash.new{|h,k| h[k]=0 } list = index.dup list.each do |data| data[:loadpath] = data[:loadpath].join(' ') data[:date] = iso(data[:date]) data.each do |k,v| max[k] = v.to_s.size if v.to_s.size > max[k] end end max = max.values_at(:name, :version, :date, :location, :loadpath) list = list.map do |data| data.values_at(:name, :version, :date, :location, :loadpath) end list.sort! do |a,b| x = a[0] <=> b[0] x != 0 ? x : b[1] <=> a[1] # TODO: use natcmp end mask = max.map{ |size| "%-#{size}s" }.join(' ') + "\n" out = '' list.each do |name, vers, date, locs, lpath| str = mask % [name, vers, date, locs, lpath] out << str end out end # def iso(date) case date when ::Time date.strftime("%Y-%m-%d") else date.to_s end end # Make sure each project location in the index has .ruby entries. # If it does not have .ruby entries then it will attempt to create # them. # # TODO: Rename this method. #def prep # locate.each do |path| # dotruby_ensure(path) # end # report_dotruby_write_errors #end # Ensure a project +location+ has .ruby entries. #def dotruby_ensure(location) # data = metadata(location) # begin # success = data.dotruby_ensure # rescue Errno::EACCES # success = false # dotruby_write_errors << location # end # if !success # # any other way to do it? # dotruby_missing_errors << location # end # success #end # Stores a list of write errors from attempts to auto-create .ruby entries. #def dotruby_write_errors # @dotruby_write_errors ||= [] #end # #def dotruby_missing_errors # @dotruby_missing_errors ||= [] #end # Output to STDERR the list of projects that failed to allow .ruby entries. #def report_dotruby_write_errors # return if dotruby_write_errors.empty? # $stderr.puts "Rolls attempted to write .ruby/ entries into each of the following:" # $stderr.puts # $stderr.puts " " + dotruby_write_errors.join("\n ") # $stderr.puts # $stderr.puts "but permission to do so was denied. Rolls needs these entries" # $stderr.puts "to operate at peak performance. Please grant it permission" # $stderr.puts "(e.g. sudo), or add the entries manually. These libraries cannot" # $stderr.puts "be served by Rolls until this is done. You might want to encourage" # $stderr.puts "the package maintainer to include .ruby/ entries in the distribution." # $stderr.puts #end class << self # Location of environment files. This includes user location, but also # read-only sytems-wide locations, should an administratore want to set # any of those up. #DIRS = ::Config.find_config('roll', 'environments') # Roll's user home temporary cache directory. #ROLL_CACHE_HOME = File.join(xdg_cache_home, 'roll') # Roll's user home configuration directory. #ROLL_CONFIG_HOME = File.join(xdg_config_home, 'roll') # Default environment name. DEFAULT_ENVIRONMENT = 'production' # 'master' ? # Project local environments directory. #def local # Library.config.local_environment_directory #end # Default environment name. def default #Library.config.default_environment 'master' end # Returns the current environment file. def file if roll_file roll_file elsif roll_name File.join(home, roll_name) else File.join(home, default) end end # Returns the <i>calling name</i> of the current environment. # TODO: rename this method to #label ? def name #Library.config.current_environment File.basename(file).chomp('.roll') end # Current roll file as designated in environment variables. # If `roll_file` is set it takes precedence over `roll_name`. def roll_file config.roll_file end # Current roll name as designated in environment variables. def roll_name config.roll_name end # Returns the name of the current environment. # TODO: change this to return the actual environment object. def current #Library.config.current_environment file end # List of environments defined in standard config locations. def list Library.config.environments end # def config Library.config end # Lookup environment. #-- # TODO: Why is $LOAD_GROUP set here? #++ def [](name) if name Environment.new(name) else $LOAD_GROUP ||= Environment.new #(name) end end # Environment home directory. def home config.home_environment_directory end end class << self # Synchronize an environment by +name+. If a +name+ # is not given the current environment is synchronized. def sync(name=nil) env = new(name) env.sync env.save end # Check to see if an environment is in-sync by +name+. If a +name+ # is not given the current environment is checked. def check(name=nil) env = new(name) env.index == env.lookup_index end # Add path to current environment. def insert(path, depth=3, live=false) env = new env.append(path, depth, live) env.sync env.save return path, env.file end # Alias for #insert. #alias_method :in, :insert # Remove path from current environment. def remove(path) env = new env.delete(path) env.sync env.save return path, env.file end # Alias for #remove. #alias_method :out, :remove # Go thru each roll lib and collect bin paths. def path binpaths = [] list.each do |name| lib = library(name) if lib.bindir? binpaths << lib.bindir end end binpaths end # Verify dependencies are in current environment. #-- # TODO: Instead of Dir.pwd, lookup project root. #++ def verify(name=nil) if name open(name).verify else Library.new(Dir.pwd).verify end end # Sync environments that contain locations relative to the # current gem home. def sync_gem_environments resync = [] environments.each do |name| env = environment(name) if env.has_gems? resync << name env.sync env.save end end resync end end end end
true
a83b8d74f8be4accc045f276f189075093e831e6
Ruby
legoabram/OpenSplitTime
/app/services/interactors/errors.rb
UTF-8
1,761
2.53125
3
[ "MIT" ]
permissive
module Interactors module Errors def resource_error_object(record) {title: "#{record.class} #{record} could not be saved", detail: {attributes: record.attributes.compact, messages: record.errors.full_messages}} end def active_record_error(exception) {title: 'An ActiveRecord exception occurred', detail: {exception: exception}} end def distance_mismatch_error(child, new_parent) {title: 'Distances do not match', detail: {messages: ["#{child} cannot be assigned to #{new_parent} because distances do not coincide"]}} end def lap_mismatch_error(child, new_parent) {title: 'Distances do not match', detail: {messages: ["#{child} cannot be assigned to #{new_parent} because laps exceed maximum required"]}} end def live_time_mismatch_error {title: 'Live times do not match', detail: {messages: ['One or more live times is not related to the provided event']}} end def sub_split_mismatch_error(child, new_parent) {title: 'Distances do not match', detail: {messages: ["#{child} cannot be assigned to #{new_parent} because sub splits do not coincide"]}} end def mismatched_organization_error(old_event_group, new_event_group) {title: 'Event group organizations do not match', detail: {messages: ["The event cannot be updated because #{old_event_group} is organized under #{old_event_group.organization}, but #{new_event_group} is organized under #{new_event_group.organization}"]}} end def effort_offset_failure_error(effort) {title: 'Effort offset could not be adjusted', detail: {messages: ["The starting split time for #{effort} was beyond an existing later split time"]}} end end end
true
dcbf1d8f1a3bda9ce44d41190c4c2e86381c1d71
Ruby
seannam/codecademy
/movies.rb
UTF-8
1,349
3.265625
3
[]
no_license
movies = { avatar: 4, inception: 4, horeee: 1 } done = false while (!done) puts "What would you like to do?" choice = gets.chomp case choice when "add" puts "What movie do you want to add?" title = gets.chomp title = title.to_sym if movies[title.to_sym] == nil puts "What is the rating?" rating = gets.chomp rating = rating.to_i movies[title] = rating puts "Added!" else puts "Error! Movie already exists" end when "update" puts "What movie do you want to update?" title = gets.chomp title = title.to_sym puts "What is the new rating?" new_rating = gets.chomp if movies[title.to_sym] != nil new_rating.to_i movies.delete(title) movies[title] = new_rating puts "Updated!" else puts "Error! Movie not found" end when "display" movies.each { |title, rating| puts "#{title}: #{rating}"} when "delete" puts "What movie do you want to delete?" title = gets.chomp.to_s title = title.to_sym if movies[title] == nil puts "Error! Movie not found" else movies.delete(title) puts "Deleted" end when "done" done = true else puts "Error!" end end
true
555da56e710be80e7bd9b76236579e58c4d3b065
Ruby
itggot-elias-stenhede/yardoc-sinatra-guide
/app.rb
UTF-8
3,086
2.609375
3
[]
no_license
require_relative 'model/model.rb' require 'sinatra' require 'slim' enable :sessions include Model # Wat dis? # Display Landing Page # get('/') do slim(:index) end # Displays search result based on search parameters # # @param [String] query_string, The search parameters delimited by spaces get('/articles/search') do result = find_articles(params) slim(:search_result, locals:{articles:result}) end # Displays a single Article # # @param [Integer] :id, the ID of the article # @see Model#get_article get('/articles/:id') do article = get_article(params) slim(:article, locals:{article:article}) end # Creates a new article and redirects to '/articles' # # @param [String] title, The title of the article # @param [String] content, The content of the article # # @see Model#create_article post('/articles') do success = create_article(params) if success redirect('/articles') else session[:error_msg] = "Article creation failed" redirect('/error') end end # Updates an existing article and redirects to '/articles' # # @param [Integer] :id, The ID of the article # @param [String] title, The new title of the article # @param [String] content, The new content of the article # # @see Model#update_article post('/articles/:id/update') do success = update_article(params) if success redirect('/articles') else session[:error_msg] = "Updating article failed" redirect('/error') end end # Deletes an existing article and redirects to '/articles' # # @param [Integer] :id, The ID of the article # @param [String] title, The new title of the article # @param [String] content, The new content of the article # # @see Model#delete_article post('/articles/:id/delete') do success = delete_article(params) if success redirect('/articles') else session[:error_msg] = "Deleting article failed" redirect('/error') end end # Displays a login form # get('/login') do slim :login end # Displays a register form # get('/login') do slim :register end # Attempts login and updates the session # # @param [String] username, The username # @param [String] password, The password # # @see Model#login post('/login') do user_id = login(params) if user_id session[:user_id] = user_id redirect('/') else session[:error_msg] = "Invalid Credentials" redirect('/error') end end # Attempts login and updates the session # # @param [String] username, The username # @param [String] password, The password # @param [String] repeat-password, The repeated password # # @see Model#register_user post('/register') do result = register_user(params) if result[:error] == false session[:user_id] = result[:user_id] redirect('/') else session[:error_msg] = result[:message] redirect back end end # Displays an error message # get('/error') do error_msg = session[:error_msg].dup session[:error_msg] = nil slim(:error, locals:{message:error_msg}) end
true
b9c299daae65732b95af7ff7a30bd81912d643f5
Ruby
theowright2017/Sinatra-web-app-rock-paper-scissors-homework
/specs/game_spec.rb
UTF-8
705
3.015625
3
[]
no_license
require 'minitest/autorun' require_relative '../models/game.rb' class TestGame < Minitest::Test def setup() @game = Game.new("rock", "scissors") @game1 = Game.new("paper", "scissors") @game2 = Game.new("paper", "paper") end # def test_hand1_wins() assert_equal("Hand 1 wins with rock", @game.winner) end def test_hand2_wins() assert_equal("Hand 2 wins with scissors", @game1.winner) end def test_game_is_draw() assert_equal("It is a draw", @game2.winner) end # def test_hand1_winner() # assert_equal("Hand 1 wins", @game.random) # end # #unable to test as using .sample and gives random outcome each time. How would this be resolved?? # end
true
b65adf24e4492ccb0bd69d50040b62e7fd5902c8
Ruby
natalieweesh/ice-cream-finder
/ice_cream_finder.rb
UTF-8
2,552
3.203125
3
[]
no_license
require 'rest-client' require 'json' require 'addressable/uri' require 'addressable/template' require 'nokogiri' require 'sanitize' class QueryProcessor def self.validate(name, value) return !!(value =~ /^[\w ]+$/) if name == "query" return true end def self.transform(name, value) return value.gsub(/ /, "+") if name == "query" return value end end def get_key(api_filename) File.readlines(api_filename).first.chomp end def query_uri(address_str) uri = Addressable::Template.new( "http://maps.googleapis.com/maps/api/geocode/json?address={query}&sensor=false" ).expand( {"query" => address_str}, QueryProcessor ).to_str end def get_coordinates(address) uri = query_uri(address) response = JSON.parse(RestClient.get(uri)) response["results"].first["geometry"]["location"].values end def search_nearby(lat, long, types="food", keyword="icecream") uri = Addressable::URI.new( scheme: "https", host: "maps.googleapis.com", path: "maps/api/place/nearbysearch/json", query_values: {location: "#{lat},#{long}", radius: 500, types: "#{types}", sensor: "false", keyword: "#{keyword}", key: get_key('APIkey.txt')}).display_uri.to_s results = JSON.parse(RestClient.get(uri))["results"] end def display_location(index, location_hash) puts "[#{index}] #{location_hash['name']}" puts "Rating: #{location_hash['rating']}" unless location_hash['rating'].nil? puts location_hash['vicinity'] puts "" end def get_directions(origin, dest) uri = Addressable::URI.new( scheme: "https", host: "maps.googleapis.com", path: "/maps/api/directions/json", query_values: {origin: "#{origin[0]},#{origin[1]}", destination: "#{dest[0]},#{dest[1]}", sensor: "false"}).display_uri.to_s legs = JSON.parse(RestClient.get(uri))["routes"].first["legs"] puts "DRIVING DIRECTIONS" legs.each do |leg| leg["steps"].each do |step| puts Nokogiri::HTML(step["html_instructions"]).text end end end def main print "Enter you address > " address = gets.chomp.sub(",", "") curr_lat, curr_long = get_coordinates(address) search_results = search_nearby(curr_lat, curr_long) search_results[0..9].each_with_index do |result, i| display_location(i+1, result) end dest_index = nil until (0..9).include?(dest_index) print "Enter the number of your destination > " dest_index = gets.chomp.to_i - 1 end end_lat, end_long = search_results[dest_index]["geometry"]["location"].values get_directions([curr_lat, curr_long], [end_lat, end_long]) end main
true
8d602550ee7b37e45c14870177300df47abaab0a
Ruby
seanjams/AAhomework
/w1d3/lib/recursion_project.rb
UTF-8
2,557
3.609375
4
[]
no_license
require 'byebug' def merge_sort(arr) return [arr[0]] if arr.length == 1 idx = arr.length/2 halves = [arr[0...idx], arr[idx..-1]] result = [] halves.each do |half| result << merge_sort(half) end merge(result) end def merge(pair) result = [] if pair.all? { |arr| arr == arr.flatten } until pair[0].empty? && pair[1].empty? first_num = pair[0].first || pair[1].first second_num = pair[1].first || pair[0].first result << pair[0].shift if first_num <= second_num result << pair[1].shift if first_num >= second_num result.compact! end result else [merge(pair[0]), merge(pair[1])] end end def b_search(arr, target) idx = arr.length/2 return idx if arr[idx] == target if arr[idx] > target b_search(arr[0...idx], target) else arr[idx] < target idx + b_search(arr[idx..-1], target) end end def permutations(arr) return [arr, arr.reverse] if arr.length == 2 result = [] arr.each_index do |i| smaller_arr = arr[0...i] smaller_arr += arr[i+1..-1] unless i == arr.length-1 #result << [arr[i]] + smaller_arr #debugger permutations(smaller_arr).each do |perm| result << [arr[i]] + perm end end result end def array_subsets(arr) debugger return [arr] if arr.empty? small_subsets = [] large_subsets = [] array_subsets(arr[0...-1]).each do |subset| small_subsets << subset large_subsets << subset + [arr[-1]] end small_subsets + large_subsets end def r_fibonacci(n) return [0,1] if n == 2 y = r_fibonacci(n-1)[-1] x = r_fibonacci(n-1)[-2] r_fibonacci(n-1) << x + y end def fibonacci(n) results = [0,1] return results[0] if n==1 return results if n==2 (n-2).times do |i| results << results[i] + results[i+1] end results end def deep_copy(arr) return arr.dup if arr == arr.flatten new_arr = arr.dup new_arr.each_index do |i| new_arr[i] = deep_copy(new_arr[i]) if new_arr[i].is_a?(Array) end new_arr end #deep_copy([5,["a","b"],"string",["c",["d","e"]]]) def exp(base, num) return 1 if num == 0 base * exp(base, num-1) end def exp2(base, num) return 1 if num == 0 return base if num == 1 if num.even? exp2(base, num / 2) * exp2(base, num/2) else base * exp2(base, (num- 1) / 2) ** 2 end end def range(first, last) return [] if first > last [first] + range(first + 1, last) end def arr_sum(arr) return arr[0] if arr.length == 1 sum = arr[-1] sum += arr_sum(arr[0...-1]) end if __FILE__ == $PROGRAM_NAME merge_sort([2,1,6,3,5,9,7,4]) end
true
f6e41a9cd5a6d46db303b3394798b3cd5c5b6bf3
Ruby
aleknak/guesser
/lib/guesser/player.rb
UTF-8
142
2.8125
3
[ "Beerware" ]
permissive
module Guesser class Player attr_accessor :player_name def initialize(name = 'John Doe') @player_name = name end end end
true
dfe728daac84eae8a22549c258d5abd6683de0b6
Ruby
sh0kunin/find-like
/lib/find_like/utils/util.rb
UTF-8
965
2.765625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module FindLike # Util class for any utilities in FindLike class Util class << self # Maps `arguments` in parallel and performs a block on each. # @param arguments [Array<Argument>] A list of arguments # @yieldparam argument [Argument] Argument from `arguments` passed # @return [Array] A list of results made after performing a block on each # argument. def parallelize(arguments) threads = arguments.map do |argument| thread = Thread.new do begin Thread.current[:result] = yield(argument) rescue => ex Log.fatal("#{ex}\n#{ex.backtrace.pretty_inspect}") Thread.main.raise(ex) end end thread.abort_on_exception = true thread end threads.each.map do |thread| thread.join thread[:result] end end end end end
true
7cf141668224a303ca1577acc12caf491308fc76
Ruby
Samkttn/ruby-thp
/exo_13.rb
UTF-8
147
3.15625
3
[]
no_license
puts "Ton annΓ©e de naissance ? :" number = gets.to_i nombre = number number = 2018 - nombre number.times do nombre += 1 puts nombre.to_s end
true
26889cc9c7e71db22e4f27eee0f73330a07c213d
Ruby
aungaungNMK/ruby_learning_for_gold
/chapter 9 Ruby Platform/enumerators_and_iterators.rb
UTF-8
713
3.015625
3
[]
no_license
#Enumerable::Enumerator, print e = [1..10].to_enum print e = "test".enum_for(:each_byte) print e = "test".each_byte puts #IF repeated application are possible, you can start and external iterator before StorIteration has been raised bu calling rewind print "Ruby".each_char.max puts iter = "Ruby".each_char #loop { print iter.next } puts print iter.next # R puts iter.rewind # forct it to restart nw print iter.next puts print "Ruby".each_char.with_index{|c,i| puts "#{i}:#{c}"} *Note Give any Enumerator e, like all Enumerable Object, are splattable:you can prefix an Enumerator with an asterisk to expends it into individual values for methods invocation or paralel assignment.
true
45ac2436c12d0ea806d7b36e954e698523f5769d
Ruby
ashleyjbland/knitting_patterns
/lib/knitting_patterns/category.rb
UTF-8
437
2.640625
3
[ "MIT" ]
permissive
class KnittingPatterns::Category attr_accessor :title, :patterns @@all = [] def initialize @patterns = [] end def self.all @@all end def save @@all << self end #def patterns # KnittingPatterns::Pattern.all.keep_if {|pattern| pattern.category == self} #end def self.pattern_count patterns = KnittingPatterns::Pattern.all.each {|pattern| pattern.category == self} patterns.count end end
true
104bf4203198e3bd8daf175b5f9fb083b44af1e7
Ruby
logaan/clojure-workshop
/ruby-examples/multiples.rb
UTF-8
889
4.375
4
[ "MIT" ]
permissive
# Multiples of 3 and 5 # # If we list all the natural numbers below 10 that are multiples of 3 or 5, we # get 3, 5, 6 and 9. The sum of these multiples is 23. # # Find the sum of all the multiples of 3 or 5 below 1000. # # ANSWER: 233168 counter = 1 sum = 0 while counter < 10 if counter % 3 == 0 || counter % 5 == 0 sum = sum + counter end counter = counter + 1 end puts sum ########################################### good_numbers = [] for number in 1...10 if number % 3 == 0 || number % 5 == 0 good_numbers << number end end puts good_numbers.reduce(&:+) ########################################### total = (1...10).reduce(0) do |total, number| if number % 3 == 0 || number % 5 == 0 total + number else total end end puts total ########################################### puts (1...10).find_all{|n| n % 3 == 0 || n % 5 == 0 }.reduce(&:+)
true
66eaa6897f20e47e6256992f8b523bcbb4d521a0
Ruby
jessemcready/OO-Auto-Shop-nyc-web-080618
/app/models/mechanic.rb
UTF-8
785
3.4375
3
[]
no_license
class Mechanic attr_reader :name, :specialty @@all = [] def initialize(name, specialty) @name = name @specialty = specialty @@all << self end # initialize def self.all @@all end # self.all def self.car_owners(mechanic) cars = Car.all.select do |car| car.mechanic == mechanic end # cars = cars.map do |car| car.car_owner end.uniq # cars.map end # car_owners def self.find_all_cars(mechanic) Car.all.select do |car| car.mechanic == mechanic end # Car.all.select end # cars def self.car_owners_to_mechanic(mechanic) cars = Car.all.select do |car| car.mechanic == mechanic end # cars = cars.map do |car| car.car_owner.name end # cars.map end # car_owners_to_mechanic end
true
a5735a7b9102946be0af4f9b6127118dda30b6bc
Ruby
chaione/hue-jenkins
/hue.rb
UTF-8
1,300
2.5625
3
[ "MIT" ]
permissive
require 'rubygems' require 'bundler/setup' Bundler.require require 'open-uri' require 'json' if ENV['JENKINS_URL'].nil? raise "This script requires the JENKINS_URL env var to be defined." end light_index = ENV['HUE_LIGHT_INDEX'].nil? ? 0 : ENV['HUE_LIGHT_INDEX'].to_i jenkins_url = ENV['JENKINS_URL'] + "/api/json" pattern = ENV['JENKINS_JOB_PATTERN'] http_basic_auth = [ENV['JENKINS_HTTP_BASIC_USERNAME'], ENV['JENKINS_HTTP_BASIC_PASSWORD']] if ENV['JENKINS_HTTP_BASIC_USERNAME'] && ENV['JENKINS_HTTP_BASIC_PASSWORD'] class Job attr_reader :name, :color def initialize(hash) @name = hash["name"] @color = hash["color"] end def failed? color =~ /red/ end end hue = Hue::Client.new light = hue.lights[light_index] puts "Checking for build status..." uri = URI.parse(jenkins_url) json = JSON.parse(open(uri, http_basic_authentication: http_basic_auth).read) jobs = json["jobs"].map {|j| Job.new(j)} jobs = jobs.select {|j| j.name =~ /#{pattern}/} if pattern failed_jobs = jobs.select {|j| j.failed? } if failed_jobs.any? puts "The following job(s) failed: #{failed_jobs.map(&:name)}" light.set_state(:hue => 0, :sat => 255, :bri => 255) else puts "builds #{jobs.map(&:name)} passing, setting green" light.set_state(:hue => 25500, :sat => 100, :bri => 255) end
true
967264571b9f66b01519a7586fffa4670434be9d
Ruby
alexeybokov/binary_tree
/index.rb
UTF-8
1,297
3.953125
4
[]
no_license
require_relative 'navigation' require_relative 'node' require_relative 'binary_tree' @current_tree = BinaryTree.new(0) loop do puts '___________________________________________________' puts 'Allowed commands:' puts ' 1 - Create binary-tree' puts ' 2 - Add new item' puts ' 3 - Remove item ( its deletes all children if they exist! )' puts ' 4 - Start navigation for binary-tree' puts ' 5 - Exit' command = gets.chomp unless (1..5).to_a.include? command.to_i puts "Wrong command - #{command}" next end case command.to_i when 1 puts 'To create binary-tree enter root value:' root = gets.chomp binary_tree = BinaryTree.new(root) @current_tree = binary_tree puts "Now your binary-tree look so: #{binary_tree.to_s}" when 2 puts 'Enter item for add into binary-tree:' item = gets.chomp @current_tree.add(item) puts "Inserting #{item}......" puts "Now your binary-tree look so: #{@current_tree.to_s}" when 3 puts 'Enter item to delete (also deletes children if they exist!):' r_item = gets.chomp @current_tree.remove_node_with_children(r_item) puts "Now your binary-tree look so: #{@current_tree.to_s}" when 4 @current_tree.navigation when 5 puts 'Good Bye!' return end end
true
412ce63da56fd608ae209cd178012cd609ad774c
Ruby
patrickwhardy/enigma
/lib/rotation.rb
UTF-8
1,286
3.296875
3
[]
no_license
require 'pry' require 'Date' class Rotation attr_reader :a, :b, :c, :d, :a_offset, :b_offset, :c_offset, :d_offset attr_accessor :offset_array, :key, :today def initialize(key='') @key = key #'12345' - use when hard-coding for test @today = '' end def setup # generate_key # date_format key_rotation offset_rotation final_offset build_offset_array end def generate_key 5.times do i = Random.rand(0..9) @key << i.to_s end @key end #use when hard-coding - (date = Date.new(2016, 2, 16).to_s) def date_format(date = Date.today.to_s) @today = date.slice(8..9) + date.slice(5..6) + date.slice(2..3) @today end def key_rotation @a_key = @key[0..1].to_i @b_key = @key[1..2].to_i @c_key = @key[2..3].to_i @d_key = @key[3..4].to_i end def offset_rotation square = @today.to_i * @today.to_i last_four = square.to_s[-4..-1] @a_offset = last_four[0].to_i @b_offset = last_four[1].to_i @c_offset = last_four[2].to_i @d_offset = last_four[3].to_i end def final_offset @a = @a_key + @a_offset @b = @b_key + @b_offset @c = @c_key + @c_offset @d = @d_key + @d_offset end def build_offset_array @offset_array = [@a, @b, @c, @d] end end
true
1f35c53d3599b552d02f15ca039c449ecbc89092
Ruby
srwatlanta/algorithms
/exercises/cutthesticks.rb
UTF-8
130
3.140625
3
[]
no_license
def cutTheSticks(arr) lengths = [] while arr.length > 0 lengths << arr.length arr.delete(arr.min) end lengths end
true
49f33b4c2af235322e67c5fba1d25e11276e5c1c
Ruby
s-dney/sid-arthur-module1
/functions/view_list.rb
UTF-8
1,290
3.109375
3
[ "MIT" ]
permissive
require_relative '../config/environment' require 'pry' def view_list(selected, sortstring) system("clear") sleep(0.2) display_table(selected, sortstring) # $prompt.ask('') $prompt.select("What do you want to do?") do |menu| menu.choice "Sort list", -> {choose_sort(selected)} menu.choice "Add a new book", -> {add_entry(selected)} menu.choice "View/edit a book record", -> {select_book(selected)} menu.choice "Back to my lists", -> {view_all} menu.choice "Delete this list", -> {delete_list(selected) view_all} menu.choice "Back to main menu", -> {system("clear") main_menu} end end def select_book(list) title = $prompt.ask("Enter the title of the book you want to view.").to_s bookarray = list.find_in_list_by_title(title) if bookarray.size == 1 book = bookarray.first view_book(book, list) elsif bookarray.size >=2 author = $prompt.ask("Two or more entries by that title. Please enter author name.").to_s book = list.find_in_list_by_title_and_author(title, author).first view_book(book, list) else puts "Sorry, I can't find a book with that title in this list." select_book(list) end # binding.pry end
true
40aaea6658d262929d425667f5a0fa065b7306b4
Ruby
dnnp2011/tdd-rspec-bootcamp
/current_age_for_birth_year.rb
UTF-8
93
2.890625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def current_age_for_birth_year(birth_year) return Time.now.year.to_i - birth_year.to_i; end
true
dde7cc8c814887a649dea836daa8f090984363b1
Ruby
danie16arrido/week03_day05_homework
/db/console.rb
UTF-8
1,847
3.03125
3
[]
no_license
require('pry-byebug') require_relative('../models/film.rb') require_relative('../models/customer.rb') require_relative('../models/ticket.rb') require_relative('../models/screening.rb') require_relative('../db/sql_runner.rb') customer1 = Customer.new({"name" => "Daniel", 'funds' => 100.2}) customer2 = Customer.new({"name" => "Maria", 'funds' => 55.5}) customer3 = Customer.new({"name" => "Juan", 'funds' => 5.5}) customer1.save() customer2.save() customer3.save() film1 = Film.new({"title" => "X men", "price" => 4.5}) film2 = Film.new({"title" => "Batman", "price" => 14.99}) film1.save() film2.save() data = {} data['film_id'] = film1.id data['start_time'] = '12:00' data['finish_time'] = '15:00' data['screening_date'] = "1 3 2009" data['capacity'] = 200 screening1 = Screening.new(data) screening1.save() data['film_id'] = film1.id data['start_time'] = '18:00' data['finish_time'] = '21:00' data['screening_date'] = "1 3 2009" data['capacity'] = 122 screening2 = Screening.new(data) screening2.save() def buy_ticket(customer, screening) ticket_details = create_ticket_data(customer, screening) ticket = Ticket.new(ticket_details) film = Film.find_by_id(screening.film_id) charge_for(film.price.to_f, customer) customer.update() screening.tickets_sold +=1 screening.update ticket.save() end def create_ticket_data(customer, screening) data = {} data["customer_id"] = customer.id data["screening_id"] = screening.id return data end def charge_for(amount, customer) customer.funds -= amount end # ticket1 = Ticket.new( {"customer_id" => customer1.id, "screening_id" => screening1.id} ) # ticket2 = Ticket.new( {"customer_id" => customer2id, "screening_id" => screening2.id} ) buy_ticket(customer2, screening1) buy_ticket(customer2, screening2) buy_ticket(customer1, screening1) binding.pry nil
true
50df5a1e8fdc952696ebaf443ce583d6d53d921c
Ruby
reneenordholm/ruby-music-library-cli-online-web-pt-041519
/lib/artist.rb
UTF-8
773
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist extend Concerns::Findable attr_accessor :name @@all = [] def initialize(name) @name = name @songs = [] end def self.all @@all end def self.destroy_all @@all.clear end def save @@all << self end def self.create(artist) created_artist = Artist.new(artist) created_artist.save created_artist end def songs @songs end def add_song(song_to_add) song_to_add.artist = self unless song_to_add.artist == self #Song is the artist's unless the song is already the artist's @songs << song_to_add unless @songs.include?(song_to_add) #add song the artist's collection unless it is already included in the collection end def genres songs.collect {|song| song.genre}.uniq end end
true
c5bc25fd39971c92ab2a983720f7bd7bd35c622e
Ruby
macbury/detox
/app/services/extract/image_details.rb
UTF-8
816
2.546875
3
[]
no_license
module Extract # Fetch size details from image url class ImageDetails < Service def initialize(image_url) @image_url = image_url end def call return unless image_url PosterMetaData.new( url: image_url, width: size[0], height: size[1], resolution: size[0] * size[1] ) rescue FastImage::SizeNotFound, FastImage::ImageFetchFailure, FastImage::UnknownImageType => e error "Could not fetch: #{image_url} because #{e}" nil end private attr_reader :image_url def size @size ||= Rails.cache.fetch(cache_key, expires_in: 1.day) do FastImage.size(image_url, raise_on_failure: true, timeout: 60).map(&:to_i) end end def cache_key ['ImageSize', image_url].join('::') end end end
true
35672e1ebca99ccde22021808a9b06902e18cc17
Ruby
AdamClemons/sql-table-relations-crowdfunding-join-table-lab
/lib/sql_queries.rb
UTF-8
1,143
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your sql queries in this file in the appropriate method like the example below: # # def select_category_from_projects # "SELECT category FROM projects;" # end # Make sure each ruby method returns a string containing a valid SQL statement. def selects_the_titles_of_all_projects_and_their_pledge_amounts_alphabetized_by_title "SELECT projects.title, SUM(pledges.amount) FROM projects JOIN pledges ON projects.id = pledges.project_id GROUP BY projects.title ORDER BY projects.title" end def selects_the_user_name_age_and_pledge_amount_for_all_pledges_alphabetized_by_name "Write your SQL query Here" end def selects_the_titles_and_amount_over_goal_of_all_projects_that_have_met_their_funding_goal "Write your SQL query Here" end def selects_user_names_and_amounts_of_all_pledges_grouped_by_name_then_orders_them_by_the_summed_amount "Write your SQL query Here" end def selects_the_category_names_and_pledge_amounts_of_all_pledges_in_the_music_category "Write your SQL query Here" end def selects_the_category_name_and_the_sum_total_of_the_all_its_pledges_for_the_books_category "Write your SQL query Here" end
true
42a2d727bbe9471b32fa313cd514dd059faeb7d4
Ruby
taiyoslime/procon
/atcoder/031_A.rb
UTF-8
56
2.859375
3
[]
no_license
a,b = gets.split.map(&:to_i) puts (a>b)?a*(b+1):(a+1)*b
true
a217bfcdae4acba2a90a587c5c14d018651e2ad0
Ruby
mkeshita/scratchpad
/lib/scratchpad/common/hash_tree_cache_driver.rb
UTF-8
6,678
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'set' # :nodoc: namespace module Scratchpad # Manages a HashTreeCache. class HashTreeCacheDriver # Creates a new cache driver. # # Args: # hash_tree:: the hash tree being cached # cache_capacity:: the number of lines in the cache def initialize(hash_tree, cache_capacity) @tree = hash_tree @cache_lines = Array.new(cache_capacity) do { :node => 0, :left => nil, :right => nil } end @cache_lines[0][:node] = 1 # Node 0 points to line 0 so we get old_parent_lines for empty lines. @tree_nodes = { 0 => 0, 1 => 0 } end # The operations that will get a leaf node loaded into the cache. # # Args: # leaf_id:: the number of the leaf to be loaded (0-based) # # Returns a Hash with the following keys: # :line:: the cache line that will hold the verified leaf # :ops:: an array following the specifications for perform_ops def load_leaf(leaf_id) nodes = missing_nodes_for_read(leaf_id) ops, mapped = load_nodes nodes[:load], nodes[:keep], [@tree.leaf_node_id(leaf_id)] { :line => mapped.first, :ops => ops } end # The operations that will load the nodes needed to perform a leaf update. # # Args: # leaf_id:: the number of the leaf to be updated (0-based) # # Returns a Hash with the following keys: # :path:: the path of cache lines needed to update the leaf # :ops:: an array following the specifications for perform_ops def load_update_path(leaf_id) nodes = missing_nodes_for_write(leaf_id) ops, mapped = load_nodes nodes[:load], nodes[:keep], nodes[:path] { :path => mapped, :ops => ops } end # Updates the driver state to reflect cache operations. # # Args: # ops:: an array with one Hash per operation, with the following keys: # :op:: the operation to be performed, :load or :verify # :line:: (load) the cache line number # :node:: (load) the node number # :old_parent_line:: (load) the cache line number for the old parent # :parent:: (verify) the cache line number for the parent node # :left:: (verify) the cache line number for the left child # :right:: (verify) the cache line number of the right child # # The method is only guaranteed to accurately update the driver's state when # given an array operations produced by calls to this driver. def perform_ops(operations) operations.each do |op| case op[:op] when :load if (old_node = @cache_lines[op[:line]][:node]) != 0 @tree_nodes.delete old_node if HashTree.left_child? old_node @cache_lines[op[:old_parent_line]][:left] = nil else @cache_lines[op[:old_parent_line]][:right] = nil end end @cache_lines[op[:line]][:node] = op[:node] @cache_lines[op[:line]][:left] = nil @cache_lines[op[:line]][:right] = nil @tree_nodes[op[:node]] = op[:line] when :verify @cache_lines[op[:parent]][:left] = op[:left] @cache_lines[op[:parent]][:right] = op[:right] end end end # The nodes that must be loaded in the tree to validate a leaf. # # Args: # leaf_id:: the number of the leaf to be validated # # Returns a Hash with the following keys: # :keep:: array of nodes that need to stay in the tree, sorted # :load:: array of nodes to be loaded in the tree, sorted def missing_nodes_for_read(leaf_id) nodes = [] anchor = nil @tree.visit_path_to_root(leaf_id) do |node| if @tree_nodes.has_key? node anchor = node break end nodes << node sibling = HashTree.sibling node nodes << sibling unless @tree_nodes.has_key?(sibling) end { :keep => [anchor], :load => nodes.reverse } end # The nodes that must be loaded in the tree to update a leaf. # # Args: # leaf_id:: the number of the leaf to be updated # # Returns a Hash with the following keys: # :keep:: array of nodes that need to stay in the tree, sorted # :load:: array of nodes to be loaded in the tree, sorted # :path:: the original update path def missing_nodes_for_write(leaf_id) path = @tree.leaf_update_path(leaf_id) keep, load = path.reverse.partition { |node| @tree_nodes.has_key?(node) } { :keep => keep, :load => load, :path => path } end # The operations that will load a bunch of nodes in the cache. # # Args: # load_nodes:: the nodes to be loaded in the cache, in increasing order # keep_nodes:: the nodes to be mapped in the cache # map_nodes:: array of nodes to be mapped to cache lines # # Returns: operations, mapped_lines # operations:: conforms to the specifications of perform_ops # mapped_lines:: cache lines that will be holding the nodes in map_nodes def load_nodes(load_nodes, keep_nodes, map_nodes) free_lines = find_lines load_nodes.count, keep_nodes lines = load_nodes.zip free_lines ops = lines.map do |node, line| old_parent_line = @tree_nodes[HashTree.parent(@cache_lines[line][:node])] { :op => :load, :line => line, :node => node, :old_parent_line => old_parent_line } end new_lines = Hash[*lines.flatten] verified_parents = Set.new([]) lines.each do |node, line| parent_node = HashTree.parent(node) next if verified_parents.include? parent_node verified_parents << parent_node parent_line = new_lines[parent_node] || @tree_nodes[parent_node] sibling_node = HashTree.sibling(node) sibling_line = new_lines[sibling_node] || @tree_nodes[sibling_node] if HashTree.left_child?(node) ops << { :op => :verify, :parent => parent_line, :left => line, :right => sibling_line } else ops << { :op => :verify, :parent => parent_line, :left => sibling_line, :right => line } end end return ops, map_nodes.map { |node| new_lines[node] || @tree_nodes[node] } end # Locates lines that should be used to load new nodes. # # Args: # load_count:: the desired number of lines # keep_lines:: lines that should not be removed from the cache # # Returns an array of lines. def find_lines(load_count, keep_lines) lines = [] @cache_lines.each_with_index { |line, i| lines << i if line[:node] == 0 } lines = lines[0, load_count] load_count -= lines.length raise "TODO(costan): implement cache replacement policy" if load_count > 0 lines end end # class Scratchpad::HashTreeCacheDriver end # namespace Scratchpad
true
edcaddfc80c4efd5c0d0afd7dfb56600e214f067
Ruby
Pandenok/ruby_rspec_TOP
/spec/14_find_number_spec.rb
UTF-8
8,518
3.703125
4
[]
no_license
# frozen_string_literal: true require_relative '../lib/14_find_number' # The file order to complete this lesson: # 1. Familarize yourself with the initialize method in lib/14_find_number.rb # 2. Start reading spec/14_find_number_spec.rb, which will also include # instructions to add methods to lib/14_find_number.rb # This file focuses on test-driven development (TDD). One important # TDD technique is using a 'double' for any object outside of the class being # tested. A 'double' is a generic ruby object that stands in for the real # object, like a stunt double. # Doubles are very useful in TDD because you can create test functionality that # is not coded yet with them. # In this lesson, we will be testing the class 'FindNumber'. Look at the # lib/14_find_number.rb file. An instance of 'FindNumber' is initialized with # a 'RandomNumber' object (unless a third argument is given to the initialize # method). # The 'RandomNumber' class has not been written, so we will use a double for it # in these tests. # https://relishapp.com/rspec/rspec-mocks/v/3-9/docs/basics/test-doubles # Learning about doubles can be very confusing, because many resources use # doubles/mocks/stubs interchangeably. If you want to dig a little deeper, # here are a few additional resources to check out: # https://www.tutorialspoint.com/rspec/rspec_test_doubles.htm # https://www.codewithjason.com/rspec-mocks-stubs-plain-english/ describe FindNumber do # There are two ways to specify the messages that a double can receive. describe '#initialize' do # Doubles are strict, which means you must specify (allow) any messages # that they can receive. If a double receives a message that has not been # allowed, it will trigger an error. # This first example creates the double, then allows specific methods. context 'when creating the double and allowing method(s) in two steps' do let(:random_number) { double('random_number') } subject(:game) { described_class.new(0, 9, random_number) } context 'when random_number is 8' do it 'returns 8' do allow(random_number).to receive(:value).and_return(8) solution = game.answer expect(solution).to eq(8) end end end # This second example creates the double & specific methods together. context 'when creating the double and allowing method(s) in one step' do # A hash can be used to define allowed messages and return values. # When passing a hash as the last argument, the { } are not required. # let(:random_number) { double('random_number', { value: 3 }) } let(:random_number) { double('random_number', value: 3) } subject(:game) { described_class.new(0, 9, random_number) } context 'when random_number is 3' do it 'returns 3' do solution = game.answer expect(solution).to eq(3) end end end # When testing the same method in multiple tests, it is possible to add # method names to subject. context 'when adding method names to subject for multiple tests' do let(:random_number) { double('random_number', value: 5) } subject(:game_solution) { described_class.new(0, 9, random_number).answer } context 'when random_number is 5' do it 'returns 5' do expect(game_solution).to eq(5) end end end end end # ASSIGNMENT # For this assignment you will be doing TDD for 3 methods: #make_guess, # #game_over?, and #update_range. # After you have some experience using TDD, you can use the typical # Red-Green-Refactor workflow. # https://thoughtbot.com/upcase/videos/red-green-refactor-by-example # Since this is probably your first experience with TDD, let's extend the # workflow to include a few more steps: # 1. Read & understand the requirement for one method only. # 2. Write one test for that method that you think it will pass. # 3. Write the method to fulfill the requirement. # 4. Run the test that you wrote. If it doesn't pass, redo steps 1-3. # 5. When your first test is passing, write the additional tests. # 6. Run all of the tests. If any do not pass, redo steps 3-5. # 7. Optional: Refactor your code and/or tests, keeping all tests passing. describe FindNumber do # ASSIGNMENT: METHOD #1 # The basic idea of 'FindNumber' is to program a computer to guess a # random_number using binary search. Remember the binary search video # that you watched in the Computer Science section: # https://www.youtube.com/watch?v=T98PIp4omUA # The computer will update min and max values to help find the correct number. describe '#make_guess' do # Create a random_number double & allow it to receive 'value' and return any # number between 0 and 9, in one of the two ways explained above. subject(:game) { described_class.new(0, 9, random_number) } # Before you write the #make_guess method: # Write a test that would expect #make_guess to return the average of # the min and max values (rounded down). Don't expect this test to be # able to pass as you haven't written #make_guess yet! context 'when min is 0 and max is 9' do end # Now write a method in 14_find_number.rb called #make_guess that returns # the average of the min and max values (rounded down). # You can now run the above test and it should pass. # Write a test for each of the following contexts: context 'when min is 5 and max is 9' do end context 'when min is 8 and max is 9' do end context 'when min is 0 and max is 3' do end context 'when min and max both equal 3' do end end # ASSIGNMENT: METHOD #2 describe '#game_over?' do # In a long test file, it can be helpful to declare variables in each # describe block, to make the tests more readable. When creating another # instance of the random number and/or subject, use a meaningful name to # differentiate between instances. # Create a subject and random_number double with meaningful names. # A helpful tip is to combine the purpose of the test and the object. # E.g., ending_number & ending_game or completing_random & completing_game. # Allow the double to receive 'value' and return a number from 0 to 9. # Write a test that would expect game to be_game_over when a guess equals # the random_number double's value above. Remember that this test will not # be able to pass yet because you haven't written the method! context 'when guess and random_number are equal' do end # Write the corresponding method in 14_find_number.rb called #game_over? # that returns true when a guess equals the value of the random_number. # Write a test that would expect game to NOT be_game_over when a guess does # NOT equal the random_number double's value above. context 'when guess and random_number are not equal' do end end # ASSIGNMENT: METHOD #3 describe '#update_range' do let(:updating_number) { double('random_number', value: 8) } subject(:updating_game) { described_class.new(0, 9, updating_number) } # Write four tests for #update_range that test the values of min and max. # When the guess is less than the answer: # - min updates to one more than the guess # - max stays the same # When the guess is more than the answer: # - min stays the same # - max updates to one less than the guess # Note: updating_game in each context block starts off with # min = 0 and max = 9. context 'when the guess is less than the answer' do before do updating_game.instance_variable_set(:@guess, 4) updating_game.update_range end xit 'updates min' do end xit 'does not update max' do end end context 'when the guess is more than the answer' do xit 'does not update min' do end xit 'updates max' do end end # Now, write the method in 14_find_number.rb called #update_range that will # do the following: # When the guess is less than the answer: # - min updates to one more than the guess # When the guess is not less than the answer: # - max updates to one less than the guess # Write a test for any 'edge cases' that you can think of, for example: context 'when the guess is 7, min=5, and max=8' do xit 'updates min to the same value as max' do end xit 'does not update max' do end end end end
true
92643b267deaf4467f4333d466aee07f0251027f
Ruby
nrser/yard-link_stdlib
/lib/yard/cli/link_stdlib/search.rb
UTF-8
3,632
2.828125
3
[ "BSD-3-Clause", "MIT" ]
permissive
# encoding: UTF-8 # frozen_string_literal: true # Requirements # ======================================================================= ### Stdlib ### require 'optparse' ### Deps ### # We need {YARD::CLI::Command} require 'yard' ### Project / Package ### require_relative './command_helper' # Namespace # ======================================================================= module YARD module CLI class LinkStdlib < Command # Definitions # ======================================================================= # Hooks into {YARD::LinkStdlib::ObjectMap#grep} to search for names using # regular expressions. # class Search < Command include CommandHelper DESCRIPTION = "Find stdlib names that match Regexp patterns" USAGE = "yard stdlib search [OPTIONS] TERMS..." def run *args # Default format is `:plain` opts[ :format ] = :plain OptionParser.new { |op| add_header op, <<~END Examples: 1. {Pathname} instance methods $ yard stdlib search '^Pathname#' 2. All `#to_s` methods $ yard stdlib search '#to_s$' 3. Print results in serialized formats. All `#to_s` instance methods in JSON: $ yard stdlib search --format=json '#to_s$' Supports a short `-f` flag and first-letter formats too. Instance methods of {Array} in YAML: $ yard stdlib search -f y '^Array#' END add_version_opt op op.on( '-u', '--urls', %(Print doc URLs along with names) ) { |urls| opts[ :urls ] = !!urls } op.on( '-f FORMAT', '--format=FORMAT', %(Specify print format: (p)lain, (j)son or (y)aml) ) { |format| opts[ :format ] = \ case format.downcase when 'p', 'plain' :plain when 'j', 'json' :json when 'y', 'yaml' :yaml else log.fatal \ %(Unknown format - expected "plain", "json" or "yaml"; ) + %(given #{ format.inspect }) exit false end } }.parse! args if args.empty? YARD::LinkStdlib::ObjectMap. current. names. sort_by( &:downcase ). each { |key| log.puts key } exit true end terms = args.map { |arg| begin Regexp.new arg rescue RegexpError => error Regexp.new \ Regexp.escape( YARD::LinkStdlib.normalize_name( arg ) ) end } log.debug "Terms:\n " + terms.map( &:to_s ).join( "\n " ) names = YARD::LinkStdlib.grep *terms results = \ if opts[ :urls ] names.each_with_object( {} ) { |name, hash| hash[ name ] = YARD::LinkStdlib::ObjectMap.current.url_for name } else names end case opts[ :format ] when :plain results.each do |entry| if entry.is_a? ::Array log.puts "#{ entry[0] } <#{ entry[ 1 ]}>" else log.puts entry end end when :json require 'json' log.puts JSON.pretty_generate( results ) when :yaml require 'yaml' log.puts YAML.dump( results ) end exit true end end # class Search # /Namespace # ======================================================================= end # class LinkStdlib end # module CLI end # module YARD
true
b1955df75169d504956b3f6e87972291ed4946bc
Ruby
eliellds/nivelamento-aluno
/14-exercicio.rb
UTF-8
3,065
3.890625
4
[]
no_license
def exibe_array(array) for n in (0..array.size-1) print array[n] if n < array.size-1 print "," end end puts end def existe_no_array(array, elemento) for conferir in (0..array.size-1) if array[conferir] == elemento return true end end return false end def sortear_numeros(qtd, limite_inicio, limite_fim) numeros_sorteados = [] indice = 0 dezenas = 0 until indice == 6 && dezenas == 6 numeros = rand(limite_inicio..limite_fim) if existe_no_array(numeros_sorteados, numeros) == false numeros_sorteados[indice] = numeros indice = indice + 1 dezenas = dezenas + 1 end end return numeros_sorteados end # qtd = 6 # limite_inicio = 1 # limite_fim = 60 # sorteio = sortear_numeros(qtd, limite_inicio, limite_fim) # puts exibe_array(sorteio) def validadorChute(chute) if chute.to_i >= 1 && chute.to_i <= 60 return true else return false end end def obter_apostas(qtd, limite_inicio, limite_fim) numeros_apostados = [] indice = 0 dezenas = 0 puts "Digite os nΓΊmeros apostados ou digite OK para encerrar a aposta." while indice < 15 && dezenas < 15 print (dezenas+1).to_s + "a. dezena: " numeros = gets.chomp if validadorChute(numeros) numeros = numeros.to_i if existe_no_array(numeros_apostados, numeros) == false numeros_apostados[indice] = numeros indice = indice + 1 dezenas = dezenas + 1 else puts "NΓ£o Γ© permitido repetir nΓΊmeros!" puts end else if indice >= 6 && (numeros == "OK" || numeros == "ok") return numeros_apostados elsif indice < 6 && (numeros == "OK" || numeros == "ok") puts "Insira ao menos 6 dezenas." puts else puts "Insira apenas nΓΊmeros inteiros de 1 a 60." puts end end end return numeros_apostados end # apostas = obter_apostas(qtd, limite_inicio, limite_fim) # puts apostas # exibe_array(apostas) def verificar_acertos(sorteados, apostados) numeros_acertados = [] conferir = 0 for repeticao in (1..sorteados.size) for incluir in (1..apostados.size) if sorteados[repeticao-1] == apostados[incluir-1] numeros_acertados[conferir] = apostados[incluir-1] conferir = conferir + 1 end end end return numeros_acertados end # acertos = verificar_acertos(sorteio, apostas) # print verificar_acertos(sorteio, apostas) def mega_sena() sorteados = sortear_numeros(6, 1, 60) apostados = obter_apostas(6, 1, 60) acertados = verificar_acertos(sorteados, apostados) puts "Numeros sorteados: #{sorteados.to_s()}" puts "Numeros apostados: #{apostados.to_s()}" puts "Acertos: #{acertados.to_s()}" end mega_sena()
true
2e5d8f3c7c1c57df8201c10d7786be700e1fd0a9
Ruby
climber2002/dcstore
/spec/models/csv_importer_spec.rb
UTF-8
2,012
2.578125
3
[]
no_license
require 'spec_helper' describe CsvImporter do context "import" do it "should be able to import categories from a local file" do category_names = ['Cameras', 'WhiteGoods', 'Audio', 'Computers and Tablets'] category_names.each do |category_name| expect(Category.find_by(name: category_name)).to be_nil end expect(CsvImporter.import "#{Rails.root}/db/csv/products.csv").to be_true category_names.each do |category_name| expect(Category.find_by(name: category_name)).not_to be_nil end end it "should be able to import products from a local file" do expect do CsvImporter.import "#{Rails.root}/db/csv/products.csv" end.to change{ Product.count }.from(0).to(17) end it "should return false from a non exist location" do expect(CsvImporter.import "#{Rails.root}/db/csv/nonexist.csv").to be_false end # We assume that this dropbox link will always be available it "should be able to import from a remote file" do expect do CsvImporter.import "https://dl.dropboxusercontent.com/u/6582068/products.csv" end.to change{ Product.count }.from(0).to(17) end it "should be idempotent if import twice" do CsvImporter.import "https://dl.dropboxusercontent.com/u/6582068/products.csv" expect do CsvImporter.import "https://dl.dropboxusercontent.com/u/6582068/products.csv" end.to_not change { Product.count } end end context "import!" do it "shouldn't throw exception when import! from a valid remote location" do expect do CsvImporter.import! "https://dl.dropboxusercontent.com/u/6582068/products.csv" end.to change{Product.count}.from(0).to(17) end it "should throw an ImportError when import! from a non exist location" do expect do CsvImporter.import! "https://dl.dropboxusercontent.com/u/6582068/nonexist.csv" end.to raise_error(CsvImporter::ImportError) end end end
true
dcc9a3c456e5a76458ee909d552d2c7c12090038
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/filtered-submissions/7aaef901a1de4a74a5b132f53c94cb72.rb
UTF-8
244
3.203125
3
[]
no_license
def compute(s1, s2) hamming_count = 0 s1_a = s1.split(//) s2_a = s2.split(//) s1_a.each_with_index do |item, index| if item != s2_a[index] hamming_count = hamming_count+1 end end hamming_count end
true
ad5ab501e85a69aaf1b1b950999713d136ff8cb1
Ruby
ryanduchin/Various-Projects
/SQL-Projects/w3d2_QuestionsDatabase/QuestionLike.rb
UTF-8
2,481
2.65625
3
[]
no_license
class QuestionLike attr_accessor :id, :liked, :user_id, :question_id def initialize(options = {}) @id = options['id'] @liked = options['liked'] @user_id = options['user_id'] @question_id = options['question_id'] end def self.all results = QuestionsDatabase.instance.execute('SELECT * FROM question_likes') results.map { |result| QuestionLike.new(result) } end def self.find_by_id(id) result = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM question_likes WHERE id = ? SQL QuestionLike.new(result.first) end def self.likers_for_question_id(question_id) users = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT users.* FROM users JOIN question_likes ON users.id = question_likes.user_id WHERE question_likes.question_id = ? SQL users.map { |user| User.new(user) } end def self.num_likes_for_question_id(question_id) count = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT COUNT(*) as count FROM users JOIN question_likes ON users.id = question_likes.user_id WHERE question_likes.question_id = ? SQL count.first['count'] end def self.liked_questions_for_user_id(user_id) questions = QuestionsDatabase.instance.execute(<<-SQL, user_id) SELECT questions.* FROM questions JOIN question_likes ON questions.id = question_likes.question_id WHERE question_likes.user_id = ? SQL questions.map { |question| Question.new(question) } end #test def self.most_liked_questions(n) questions = QuestionsDatabase.instance.execute(<<-SQL, n) SELECT questions.* FROM questions JOIN question_likes ON questions.id = question_likes.question_id GROUP BY question_likes.question_id ORDER BY COUNT(question_likes.id) DESC LIMIT ? SQL questions.map { |question| Question.new(question) } end def create raise 'already saved!' unless self.id.nil? params = [self.liked, self.user_id, self.question_id] QuestionsDatabase.instance.execute(<<-SQL, *params) INSERT INTO question_likes (liked, user_id, question_id) VALUES (?, ?, ?) SQL @id = QuestionsDatabase.instance.last_insert_row_id end end
true
51d4605d3d540e2765776bbf6cd831c7f81d063e
Ruby
curquiza/gegene
/src/gegene.rb
UTF-8
2,486
2.921875
3
[]
no_license
# frozen_string_literal: true require_relative 'current_config' class Gegene def initialize(filename) @filename = filename @current_config = nil @comment_prefix = comment_prefix_value end def fetch_code_samples_in_test_file code_samples = {} File.foreach(@filename) do |line| if gegene_is_active? line = apply_gegene_config_to_line(line) current_id = @current_config.code_sample_id code_samples[current_id] = add_line(code_samples[current_id], line, @current_config.indent) @current_config.nb_lines -= 1 @current_config = nil if @current_config.nb_lines.zero? elsif gegene_line?(line) @current_config = CurrentConfig.new(line, @comment_prefix) end end code_samples end private def gegene_is_active? !@current_config.nil? end def gegene_line?(line) line.strip.start_with?(@comment_prefix) end def comment_prefix_value "#{comment_chars} GEGENE" end def comment_chars if @filename.end_with?('.py', '.rb') '#' else '//' end end def apply_gegene_config_to_line(line) line = apply_final_variable_removal(line) if should_remove_final_variable?(line) line = apply_replacers(line) if should_apply_replacers? line = remove_comment_chars(line) if line.strip.start_with? comment_chars line end def add_line(previous_line, new_line, indent_base) if previous_line.nil? " #{new_line.strip}" else indented_new_line = new_line.delete_prefix(indent_base).gsub(/\n/, '') "#{previous_line}\n #{indented_new_line}" end end def should_remove_final_variable?(line) @current_config.display_final_variable == false && @current_config.nb_lines == 1 && line.include?(' = ') end def apply_final_variable_removal(line) # WARNING: currently not work for the Go (` := `) line.chars.last(line.length - line.index(' = ') - 3).join end def should_apply_replacers? !@current_config.replacers.empty? end def apply_replacers(line) @current_config.replacers.each do |replacer| split_index = replacer.index(' ') to_search = replacer[0...split_index] replace_by = replacer[(split_index + 1)..] line = line.gsub(to_search, replace_by) end line end def remove_comment_chars(line) if line.strip.start_with? "#{comment_chars} " line.sub("#{comment_chars} ", '') else line.sub(comment_chars, '') end end end
true
7874a0f30161e393d1a7a6582260b6a7c28cc385
Ruby
richardrice/bookstore_prj
/memcached.rb
UTF-8
735
2.890625
3
[]
no_license
require 'dalli' require_relative './book_in_stock' # options = { :namespace => "app_v1", :compress => true } dc = Dalli::Client.new('localhost:11211') isbn = '1234' book = nil version = dc.get "v_#{isbn}" # Is book 1234 in the cache? if version serial = dc.get "#{version}_#{isbn}" book = BookInStock.from_cache serial book.price -= 2.0 # Increment version and update cacheed book dc.set "#{version + 1}_#{book.isbn}", book.to_cache dc.set "v_#{book.isbn}",version+1 else # Not in cache, so add it. book = BookInStock.new '1234', 'Ruby Programming','Dave Thomas', 'Programming',20.0,10 dc.set "v_#{book.isbn}",1 # Create the version entry dc.set "1_#{book.isbn}", book.to_cache end puts book
true
bbb54b703ae4ef23fb2f1ec5390c3aa5a181e838
Ruby
asaloff/tealeaf-intro-to-programming
/variables/name.rb
UTF-8
275
3.9375
4
[]
no_license
# name.rb # greet user: puts 'What is your first name?' first_name = gets.chomp puts 'What is your last name?' last_name = gets.chomp puts 'Hello ' + first_name + ' ' + last_name + '.' # prints users name 10 times: 10.times do puts first_name + ' ' + last_name end
true
282597f61b8646fbac755d261ea8077223bee6f4
Ruby
antcliffoc/boris_bikes-1
/spec/docking_station_spec.rb
UTF-8
1,565
2.953125
3
[]
no_license
require 'docking_station' describe DockingStation do let (:ds) { DockingStation.new(10, 10) } it { should respond_to(:release_bike)} it { should respond_to(:dock)} it { should respond_to(:bikes)} it "accepts a capacity argument" do expect(ds.capacity).to eq(10) end it "defaults to a capacity of 20 when none is set" do expect(subject.capacity).to eq(20) end context "full station" do let (:full_station) { DockingStation.new(20,20) } it "raises an error when attempting to dock a full station" do bike = Bike.new expect {full_station.dock(bike)}.to raise_error(ArgumentError) end it 'releases a bike' do expect(full_station.release_bike).to be_instance_of(Bike) end it 'displays the bikes that are docked' do expect(full_station.bikes.length).to eq(20) end end context "empty station" do let (:empty_station) { DockingStation.new(20)} it 'raises error when no bikes are present' do expect {empty_station.release_bike}.to raise_error(ArgumentError) end it 'docks a bike' do bike = Bike.new empty_station.dock(bike) expect(empty_station.bikes).to include(bike) end it "reports a broken bike when docking" do bike = Bike.new empty_station.dock(bike, 'report') expect(bike.working?).to_not eq(true) end it "doesn't release a broken bike" do bike = Bike.new.report_broken empty_station.dock(bike) expect {empty_station.release_bike}.to raise_error(NoMethodError) end end end
true
9014b273a6f0a93fb65163f32009e2dd1e067a7f
Ruby
chewieee/the-odin-project
/ruby/cp_chap4.rb
UTF-8
659
4.21875
4
[]
no_license
# Chris Pine Chapter 2 Things to Try # Program that asks for First, Middle, Last name and greets user # If statement to handle no middle name puts "Hi, what's your first name?" first = gets.chomp puts "Do you have a middle name?" middle = gets.chomp puts "And finally, your last name?" last = gets.chomp if ["no", "nope", "nah"].include?(middle.downcase) puts "Hello, #{first} #{last}!" else puts "Hello, #{first} #{middle} #{last}!" end # Asks for number and suggests bigger number is better puts "What is your favorite number?" favorite = gets.chomp new_fav = favorite.to_i + 1 puts "That's cool and all, but #{new_fav} is bigger and better."
true
1951aa91727f8235abafa64ba19f047a4d373a4c
Ruby
beniutek/online_voting
/administrator/test.rb
UTF-8
2,571
2.921875
3
[]
no_license
def foo message = "hello world!" vkey = OpenSSL::PKey::RSA.new(512) akey = OpenSSL::PKey::RSA.new(512) rsa = OnlineVoting::RSABlindSigner.new # msg = OpenSSL::Digest::SHA224.hexdigest(message) cipher = OpenSSL::Cipher::AES256.new :CBC cipher.encrypt iv = cipher.random_iv key = SecureRandom.hex(16) cipher.key = key encrypted_message = cipher.update(message) + cipher.final encoded_encrypted_message = Base64.encode64(encrypted_message) puts "Message: #{message}" puts "MSG: #{encrypted_message}" blinded_encoded_encrypted_message, r = rsa.blind(encoded_encrypted_message, akey.public_key) signed_blinded_encoded_encrypted_message = rsa._sign(blinded_encoded_encrypted_message, vkey) puts "\nblinded: " puts blinded_encoded_encrypted_message puts "\nblinded signed: " puts signed_blinded_encoded_encrypted_message signed_by_admin_blinded_encoded_encrypted_message = nil if rsa.verify(signed: signed_blinded_encoded_encrypted_message, message: blinded_encoded_encrypted_message, key: vkey.public_key) puts "\nMESSAGE IS OK" signed_by_admin_blinded_encoded_encrypted_message = rsa._sign(blinded_encoded_encrypted_message, akey) if rsa.verify(signed: signed_by_admin_blinded_encoded_encrypted_message, message: blinded_encoded_encrypted_message, key: akey.public_key) puts "\nADMIN MESSAGE IS OK" signed_by_admin_encoded_encrypted_message = rsa.unblind(signed_by_admin_blinded_encoded_encrypted_message, r, akey.public_key) puts "\nUNBLINDED: " puts signed_by_admin_encoded_encrypted_message msg_int = rsa.text_to_int(encoded_encrypted_message) if rsa.verify(signed: signed_by_admin_encoded_encrypted_message, message: msg_int, key: akey.public_key) puts "\nUNLINDED SIGNED VERIFIED!" puts "GOOD JOB!" decoded64 = Base64.decode64(encoded_encrypted_message) decipher = OpenSSL::Cipher::AES256.new :CBC decipher.decrypt decipher.iv = iv decipher.key = key plain_text = decipher.update(decoded64) + decipher.final puts "============================" puts plain_text puts "============================" puts "\nFIN" else puts "\nFAILED TO VERIFY SIGNED BY ADMIN UNLBINDED" puts "signed by admin and unlbinded: #{signed_by_admin_encoded_encrypted_message}" puts "message: #{msg_int}" end else puts "\nFAILED TO VERIGY SIGNED BY ADMIN MESSAGE" end else puts "\nFAILED TO VERIFY BLINDED SIGNED MESSAGE WITH VKEY" end end
true
fffaf2a4e0adcfa0f85348f61923e49aaa883ec7
Ruby
tensins/uw_sfinder
/app/helpers/rooms_helper.rb
UTF-8
2,505
3.390625
3
[]
no_license
module RoomsHelper # gets all buildings # returns the building def get_buildings() # gets all the buildings used for classes / tutorials building_names = Room.select("building").distinct.order("building ASC") return building_names end # gets rooms for building # returns the room names as well as a bool array indicating if they're # vacant or not def get_rooms(building, curr_time) rooms = Room.where(building: building).order("room_name ASC") vacancy = [] # for each room, determine whether it's vacant or not sort_by_time(rooms) rooms.each do |room| vacant, next_time = room.is_vacant?(curr_time) if !vacant vacancy.push(nil) else if next_time.nil? # indiciates rest of day is free for this room vacancy.push({room_name: room.room_name, classes: room.classes, hours: -1}) else hours, mins, seconds = time_until(curr_time, next_time) vacancy.push({room_name: room.room_name, classes: room.classes, hours: hours, mins: mins, seconds: seconds}) end end end return rooms, vacancy end def all_nil?(arr) arr.each do |element| if !element.nil? return false end end return true end # sort the the class array by start times and also sort the rooms by # their room numbers def sort_by_time(all_rooms) all_rooms = all_rooms.map do |room| sort_class(room.classes) # returns the sorted the classes of each room room end all_rooms.sort_by! do |room| room[:room_name].split(' ')[1].to_i end end def sort_class(all_classes) # sort all classes for a particular room all_classes.sort! do |class_1,class_2| class_1_hour = class_1["start_time"].split(":")[0].to_i class_1_min = class_1["start_time"].split(":")[1].to_i class_2_hour = class_2["start_time"].split(":")[0].to_i class_2_min = class_2["start_time"].split(":")[1].to_i Time.new(2016,1,1,class_1_hour,class_1_min,0,0).to_i <=> Time.new(2016,1,1,class_2_hour,class_2_min,0,0).to_i end end # will convert Time object that's in utc +0000 to -0500 ie. EST def toronto_time(curr_time) # have to go previous date return curr_time - 5.hour end # count how long we have until next time # 4:50:20 - 6:20:01 = 1:29:39 def time_until(curr_time, next_time) time_diff = next_time - curr_time hours = (time_diff/3600).floor % 24 time_diff -= hours * 3600 minutes = (time_diff/60).floor % 60 time_diff -= minutes * 60 seconds = time_diff % 60 return hours, minutes, seconds end end
true
0de18be36365a3dc7b17846162ca1c95050d3646
Ruby
hookbil/ruby_learning
/lesson_1/right_triangle.rb
UTF-8
535
3.640625
4
[]
no_license
print "Π’Π²Π΅Π΄ΠΈΡ‚Π΅ a: " a = gets.chomp.to_f print "Π’Π²Π΅Π΄ΠΈΡ‚Π΅ b: " b = gets.chomp.to_f print "Π’Π²Π΅Π΄ΠΈΡ‚Π΅ c: " c = gets.chomp.to_f teorema = a**2 + b**2 == c**2 if teorema == true puts "Π’Ρ€Π΅ΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊ ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½Ρ‹ΠΉ" else puts "Π’Ρ€Π΅ΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊ Π½Π΅ ΠΏΡ€ΡΠΌΠΎΡƒΠ³ΠΎΠ»ΡŒΠ½Ρ‹ΠΉ" end if a == b && b == c puts "Π’Ρ€Π΅ΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊ равносторонний ΠΈ Ρ€Π°Π²Π½ΠΎΠ±Π΅Π΄Ρ€Π΅Π½Π½Ρ‹ΠΉ" elsif a == b || b == c || c == a puts "Π’Ρ€Π΅ΡƒΠ³ΠΎΠ»ΡŒΠ½ΠΈΠΊ Ρ€Π°Π²Π½ΠΎΠ±Π΅Π΄Ρ€Π΅Π½Π½Ρ‹ΠΉ" end
true
2f1098e53cda026696e8ce25cc1057b2cbf07461
Ruby
dynomatix/errbit-client-ios
/app/host_settings_store.rb
UTF-8
2,121
2.578125
3
[]
no_license
class HostSettingsStore def self.shared # Our store is a singleton object. @shared ||= HostSettingsStore.new end def hosts @hosts ||= begin # Fetch all hosts from the model, sorting by the creation date. request = NSFetchRequest.alloc.init request.entity = NSEntityDescription.entityForName('Host', inManagedObjectContext:@context) request.sortDescriptors = [NSSortDescriptor.alloc.initWithKey('name', ascending:true)] error_ptr = Pointer.new(:object) data = @context.executeFetchRequest(request, error:error_ptr) if data == nil raise "Error when fetching data: #{error_ptr[0].description}" end data end end def add_host # Yield a blank, newly created Host entity, then save the model. yield NSEntityDescription.insertNewObjectForEntityForName('Host', inManagedObjectContext:@context) save end def update_server(host, &block) yield host save end def remove_host(host) # Delete the given entity, then save the model. @context.deleteObject(host) save end private def initialize # Create the model programmatically. Our model has only one entity, the Host class, and the data will be stored in a SQLite database, inside the application's Documents folder. model = NSManagedObjectModel.alloc.init model.entities = [Host.entity] store = NSPersistentStoreCoordinator.alloc.initWithManagedObjectModel(model) store_url = NSURL.fileURLWithPath(File.join(NSHomeDirectory(), 'Documents', 'Hosts.sqlite')) error_ptr = Pointer.new(:object) unless store.addPersistentStoreWithType(NSSQLiteStoreType, configuration:nil, URL:store_url, options:nil, error:error_ptr) raise "Can't add persistent SQLite store: #{error_ptr[0].description}" end context = NSManagedObjectContext.alloc.init context.persistentStoreCoordinator = store @context = context end def save error_ptr = Pointer.new(:object) unless @context.save(error_ptr) raise "Error when saving the model: #{error_ptr[0].description}" end @hosts = nil end end
true
79851f6f8e1b76c68bdd0485724a42e89944e43a
Ruby
Sigurami97/knight_travails
/lib/vertices.rb
UTF-8
134
2.625
3
[]
no_license
Vertices = Struct.new(:x, :y, :parent) do attr_accessor :coordinates def coordinates @coordinates = [self.x, self.y] end end
true
f6f08c2d85d7b1ac301e1edeab68db776a276f72
Ruby
djberg96/net-tnsping
/examples/example_tnsping.rb
UTF-8
661
2.546875
3
[ "LicenseRef-scancode-warranty-disclaimer", "Artistic-2.0" ]
permissive
####################################################################### # example_tnsping.rb # # Simple test script. Not required for installation. Modify as you see # fit. You can run this program via the 'example' rake task. ####################################################################### require "net/tnsping" dsn = ARGV[0] if dsn.nil? puts "Usage: ruby test.rb <datasource>" exit end t = Net::Ping::TNS.new(dsn) if t.ping_listener? puts "Listener ping successful" else puts "Listener ping problems: " + t.exception end if t.ping_database? puts "Database ping successful" else puts "Database ping problems: " + t.exception end
true
96e236dd0b0a5237e4bfd56b790c249551ef56ac
Ruby
372groupproject/milestones-team14-makaylaworden-jcollins1
/code/p4_small_program.ruby
UTF-8
1,688
3.96875
4
[]
no_license
# Jensen Collins, Makyala Worden # jcollins1, makaylaworden # CSC372, Collberg # p4_small_program.ruby # This file is the small snippet of code for Milestone 4 that shows # off some of the uniqueness with Ruby and dividing code within a # file. This short program computes and shows the average grades # amound some students. It can also compute and show and the max score # a student has received. It uses methods and classes to show how they # can be used. class StudentClass def getGrades return [14, 10, 3, 5, 6, 4] end end def main() students = ["Ali", "Ken", "Daniel"] grades = [[10, 16, 20, 13, 3, 17], [9, 16, 8, 19, 20, 20], [8, 10, 20, 20, 20, 20]] print(project_averages(students, grades)) print "\n" sGrades = StudentClass.new puts(max_score(sGrades.getGrades)) end # takes a dictionary ofr student to list of grades as a parameter # returns a list of the averages for each project. def project_averages(*students, grades) averages = [0,0,0,0,0,0] 0.upto(grades.length - 1) do |i| 0.upto(grades[i].length - 1) do |j| averages[j] = averages[i] + grades[i][j] end 0.upto(averages.length - 1) do |x| averages[x] = averages[x] / averages.length end end return averages end # takes a dictionary ofr student to list of grades as a parameter # takes a student name as a parameter # returns the number of the project that the student got their heighest # grade on. def max_score(student) max_grades = student[0] 1.upto(student.length - 1) do |i| if max_grades > student[i] do max_grades = student[i] end end return max_grades end end main()
true
baaacffe937b5feada3c6da6d8a8e6775ad76654
Ruby
Dcrame31/ruby-music-library-cli-onl01-seng-ft-032320
/lib/001_song_basics.rb
UTF-8
1,290
3.03125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song attr_accessor :name, :artist, :genre @@all=[] def initialize(name, artist= nil, genre= nil) @name= name self.artist = artist if artist self.genre = genre if genre end def self.all @@all end def self.destroy_all self.all.clear end def save @@all << self end def self.create(name) song = self.new(name) song.name = name song.save song end def artist=(artist) @artist= artist artist.add_song(self) if !artist.songs.include?(self) end def genre=(genre) @genre= genre genre.songs << self if !genre.songs.include?(self) end def self.find_by_name(name) @@all.detect {|song| song.name == name} end def self.find_or_create_by_name(name) self.all.include?(name) self.find_by_name(name)|| self.create(name) end def self.new_from_filename(file_name) parse_song = file_name.split(" - ") song_artist = Artist.find_or_create_by_name(parse_song[0]) song_genre = Genre.find_or_create_by_name(parse_song[2].chomp(".mp3")) Song.new(parse_song[1], song_artist, song_genre) end def self.create_from_filename(file_name) song = self.new_from_filename(file_name) song.save end end #rspec spec/010_music_library_controller_spec.rb
true