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
59e24cd3780edd0a2f1a42eebc315111cab1f743
Ruby
MatheusAlves00/exerAlgoritmoRuby
/ex021.rb
UTF-8
639
3.375
3
[]
no_license
numero_divisivel_n, numero_ate_x, count_divisiveis = [0, 0, 0] lista_divisiveis = Array.new print "Entre com o valor do número para ver seus divisíveis: " numero_divisivel_n = gets.chomp.to_i print "Entre com o valor de X para ver o intervalo de 1 até X: " numero_ate_x = gets.chomp.to_i (0..numero_ate_x).each do |item| count_divisiveis = item if (count_divisiveis % numero_divisivel_n) == 0 lista_divisiveis[item] = count_divisiveis end end print "\nOs números diviśiveis por "+numero_divisivel_n.to_s+" de 1 até "+numero_ate_x.to_s+" são:\n" (0..numero_ate_x).each do |item| puts lista_divisiveis[item].to_s end
true
443a03c03f83f27dd97cf3c631c237628af07144
Ruby
noda50/RubyItk
/Canvas/myCanvasTk.rb
UTF-8
4,238
2.78125
3
[ "Apache-2.0" ]
permissive
## -*- Mode:Ruby -*- ##Header: ##Title: Canvas Utility using tk ##Author: Itsuki Noda ##Type: class definition ##Date: 2004/12/01 ##EndHeader: ## this is not completed to implement. ## the problem is that tk can not understand state command. $LOAD_PATH.push(File::dirname(__FILE__)) ; require 'tk' ; require 'thread' ; require 'myCanvasDevBase.rb' ; class MyCanvasTk < MyCanvasDevBase attr :canvas, TRUE ; attr :drawListFore, TRUE ; attr :drawListBack, TRUE ; attr :thread, TRUE ; ##---------------------------------------------------------------------- ## setup ##---------------------------------------- ## initialize ## def initialize(param = {}) super(param) setupWindow(param) ; @drawListFore = [] ; @drawListBack = [] ; end ##-------------------- ## default size def dfltSizeX() return 512 ; end def dfltSizeY() return 512 ; end ##---------------------------------------- ## setup window ## def setupWindow(param) setupWindowCanvas(param) ; setupWindowQuit(param) ; end def setupWindowCanvas(param) myWidth = width() ; myHeight = height() ; @canvas = TkCanvas.new { width(myWidth) ; height(myHeight) ; pack ; } end def setupWindowQuit(param) ; @quitbutton = TkButton.new() { text("quit") ; command { exit(1) ; } ; pack ; } end ##---------------------------------------------------------------------- ## top facility ## ##---------------------------------------- ## run def run() @thread = Thread::new{ Tk.mainloop ; } @thread.run() ; # !!! <- key point !!! beginPage() ; end ##---------------------------------------- ## finish def finish() endPage() ; @thread.run() ; # !!! <- key point !!! sleep ; end ##---------------------------------------- ## flush def flush() ## hide fore objects @drawListFore.each{|obj| # obj.state('hidden') ; } ## swap fore and back objects drawList = @drawListFore ; @drawListFore = @drawListBack ; @drawListBack = drawList ; ## show new fore objects @drawListFore.each{|obj| # obj.state('normal') ; } end ##---------------------------------------- ## begin/end page def beginPage(color="white") # if color=nil, copy from old buffer ##??? clearPage(color) if(!color.nil?) ; end def endPage() flush() ; end ##---------------------------------------- ## clear page def clearPage(color="white") while(!@drawListBack.empty?) obj = @drawListBack.pop() ; @canvas.delete(obj) ; end obj = TkcRectangle.new(@canvas,0,0,width(),height(), "fill" => color, "outline" => color) ; registerInBuffer(obj) ; end ##---------------------------------------------------------------------- ## draw primitive def registerInBuffer(obj) # obj.state('hidden') ; @drawListBack.push(obj) ; end ##---------------------------------------- ## draw dashed line ## def drawDashedLine(x0,y0,x1,y1,thickness=1,color="grey") ##??? end ##---------------------------------------- ## draw solid line ## def drawSolidLine(x0,y0,x1,y1,thickness=1,color="black") obj = TkcLine.new(@canvas,valX(x0),valY(y0),valX(x1),valY(y1)) ; obj.fill(color) ; registerInBuffer(obj) ; end ##---------------------------------------- ## draw ellipse (circle) ## def drawEllipse(x,y,rx,ry,fillp,color="black") if(fillp) obj = TkcOval.new(@canvas,valX(x-rx),valY(y-ry),valX(x+rx),valY(y+ry), 'fill' => color, 'outline' => color) ; else obj = TkcOval.new(@canvas,valX(x-rx),valY(y-ry),valX(x+rx),valY(y+ry), 'outline' => color) ; end registerInBuffer(obj) ; end ##---------------------------------------- ## draw rectangle ## def drawRectangle(x,y,w,h,fillp,color="black") if(fillp) then obj = TkcRectangle.new(@canvas,valX(x),valY(y),valX(x+w),valY(y+h), 'fill' => color, 'outline' => color) ; else obj = TkcRectangle.new(@canvas,valX(x),valY(y),valX(x+w),valY(y+h), 'outline' => color) ; end registerInBuffer(obj) ; end end
true
d6c6a402351dcec69d46e8eed7881cc04808798b
Ruby
Breno-Silva1/Alien-Game
/stars.rb
UTF-8
421
2.953125
3
[]
no_license
require 'gosu' class Estrela attr_reader :x, :y def initialize(window) @game = window @x = rand(960) @y = 0 @x2 = rand(600) @y2 = 0 @star_green = Gosu::Image.load_tiles(@game, "media/star_green.png",36,36, false) @current_frame = @star_green[0] end def draw @current_frame.draw(@x,@y,3) @current_frame = @star_green[Gosu::milliseconds / 50 % @star_green.size] end def move @y += 10 end end
true
9ea610b72072c77bfae5e2acdb73ac6b557f3328
Ruby
EricRicketts/LaunchSchool
/exercises/Ruby/small_problems/medium/two/fifth_exercise.rb
UTF-8
2,020
3.875
4
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require 'pry-byebug' =begin Triangle Sides A triangle is classified as follows: equilateral All 3 sides are of equal length isosceles 2 sides are of equal length, while the 3rd is different scalene All 3 sides are of different length To be a valid triangle, the sum of the lengths of the two shortest sides must be greater than the length of the longest side, and all sides must have lengths greater than 0: if either of these conditions is not satisfied, the triangle is invalid. Write a method that takes the lengths of the 3 sides of a triangle as arguments, and returns a symbol :equilateral, :isosceles, :scalene, or :invalid depending on whether the triangle is equilateral, isosceles, scalene, or invalid. Examples: triangle(3, 3, 3) == :equilateral triangle(3, 3, 1.5) == :isosceles triangle(3, 4, 5) == :scalene triangle(0, 3, 3) == :invalid triangle(3, 1, 1) == :invalid AL: - develop methods for each option - invalid - equilateral - isosceles - scalene - case sides invalid then :invalid equilateral then :equilateral isosceles then :isosceles scalene then :scalene =end class FifthExercise < Minitest::Test def invalid(sides) sides.any?(&:zero?) || sides.min(2).sum < sides.max end def equilateral(sides) sides.uniq.length == 1 end def isosceles(sides) sides.uniq.length == 2 end def triangle(*sides) case when invalid(sides) then :invalid when equilateral(sides) then :equilateral when isosceles(sides) then :isosceles else :scalene end end def test_0 # skip assert_equal(:equilateral, triangle(3, 3, 3)) end def test_1 # skip assert_equal(:isosceles, triangle(3, 3, 1.5)) end def test_2 # skip assert_equal(:scalene, triangle(3, 4, 5)) end def test_3 # skip assert_equal(:invalid, triangle(0, 3, 3)) end def test_4 # skip assert_equal(:invalid, triangle(3, 1, 1)) end end
true
1186f7e3e8fe2e8952fdc74eb10b84ca7e8bc906
Ruby
kritoke/launchschool
/Exercises/Ruby-Basics/loops_2/empty_the_array.rb
UTF-8
249
4.5
4
[]
no_license
# Given the array below, use loop to remove and print each name. Stop the loop once names doesn't contain any more elements. names = ['Sally', 'Joe', 'Lisa', 'Henry'] loop do if names.size > 0 names.pop p names else break end end
true
2f012b1ae9c77110ca3c7f2083c93aedf167295a
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/cs169/800/feature686/whelper_source/18360.rb
UTF-8
208
3.140625
3
[]
no_license
def combine_anagrams(words) h = {} r = [] words.each { |x| h[x.downcase.chars.sort.join] = [] } words.each { |x| (h[x.downcase.chars.sort.join] << x) } h.each { |k, v| (r << h[k]) } return r end
true
a7a949a9b5e245ec3d03832001b5c837e70b7283
Ruby
progpyftk/webwiner
/lib/db/db_update.rb
UTF-8
1,024
2.546875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require_relative 'db_connection' # DBUpdate: update rows at tables class DBUpdate def self.row(conn_params, sql_params, field, field_value, table) string_sql(sql_params, field, field_value, table) conn = DB::Client.new(conn_params) conn.execute_params(@sql, @values) end def self.string_sql(sql_params, field, _field_value, table) index = 1 str_fields = String.new str_vars = String.new last_value = '' @values = [] sql_params.each do |k, v| if k.to_s == field last_value = v else str_fields.concat(k.to_s).concat(',') str_vars.concat('$').concat(index.to_s).concat(',') @values << v index += 1 end end @values << last_value str_fields.chop! str_vars.chop! str_cond_var = "$#{index}" str_fields = str_fields.sub("#{field},", '') str_vars = str_vars[0..-1] @sql = "UPDATE #{table} SET (#{str_fields}) = (#{str_vars}) WHERE #{field} = #{str_cond_var}" end end
true
698d893777e8e670eeaaf7d60be0bd13210ff231
Ruby
Gene5ive/Triangle
/lib/triangles.rb
UTF-8
684
3.171875
3
[]
no_license
class Triangle define_method(:initialize) do |side_a, side_b, side_c| @side_a = side_a @side_b = side_b @side_c = side_c end define_method(:triangle_type) do unless @side_a + @side_b > @side_c && @side_b + @side_c > @side_a && @side_c + @side_a > @side_b "Not a triangle" else if @side_a == @side_b && @side_b == @side_c "Equilateral" elsif @side_a == @side_b || @side_b == @side_c || @side_c == @side_a "Isosceles" else @side_a != @side_b && @side_b != @side_c && @side_c != @side_a "Scalene" end end end end
true
cac893f902a6408869e33020e3882adb699c2d16
Ruby
Seabreg/yawast
/lib/string_ext.rb
UTF-8
213
3.21875
3
[ "BSD-3-Clause" ]
permissive
class String #see if string is numeric def is_number? true if Float(self) rescue false end def trim trimmed = self.strip if trimmed == nil self else trimmed end end end
true
499bc360379317a4490474bfe2d7bfdbb2727e06
Ruby
JerryMtezH/newbie-S01
/LeerInformacionDeCSV.rb
UTF-8
793
3.46875
3
[]
no_license
require 'csv' class Person @@personas = [] def initialize(first_name, last_name, email, phone) @first_name = first_name @last_name = last_name @email = email @phone = phone @created_at = Time.new @@personas << {first_name: @first_name, last_name: @last_name, email: @email, phone: @phone, created_at: @created_at} end def self.personas @@personas end end class PersonParser @@persons_parsed = [] def initialize(file) CSV.foreach(file, headers: true) do |row| @@persons_parsed << row.to_hash end end def people @@persons_parsed.map {|i| Person.new(i["first_name"],i["last_name"],i["email"],i["phone"]) } end end parser = PersonParser.new('outfile.csv') array = parser.people p Person.personas.first(10)
true
4f4a3c5611425943abdac553c112391d16d712c0
Ruby
BojanapuMohan/group-app
/lib/time_range.rb
UTF-8
257
3.21875
3
[]
no_license
class TimeRange attr_accessor :start_time, :end_time def initialize(start_time, end_time) @start_time = start_time @end_time = end_time end def overlaps?(other) ( start_time <= other.end_time && other.start_time <= end_time ) end end
true
b078da5d2a0f12115423fa15c5d703a6d819ee8b
Ruby
srachal674/image-blur
/Image_Blur.rb
UTF-8
2,554
3.796875
4
[]
no_license
class Image attr_accessor :image def initialize(image) @image = image end def output_image(message = "Outputting Image") puts message @image.each do |a| puts a.join(" ") end end def make_copy output = [] @image.each do |row| row_copy = [] row.each do |cell| row_copy.push(cell) end output.push(row_copy) end return output end def blur (distance = 1) #puts "Blur starts distance #{distance}" distance.times do blur_1() end output_image("After") end def blur_1 #puts "Blur by 1" blur = [] last_row_number = @image.length() -1 new_image = make_copy() @image.each_with_index do |row, row_number| #puts "#{row_number} #{row}" row.each_with_index do |cell, cell_number| if cell == 0 #puts "Skipping 0" next else #If it's a 1 then check the top, bottom, left, and right cells. If they are 0 change them to a 1. top = row_number > 0 ? @image[row_number - 1][cell_number] : false bottom = row_number < last_row_number ? @image[row_number + 1][cell_number] : false left = row[cell_number - 1] right = row[cell_number + 1] #puts "T:#{top}, B:#{bottom}, L:#{left}, R:#{right}" if top == 0 #puts "***" new_image[row_number - 1][cell_number] = 1 end if bottom == 0 #puts "&&&" new_image[row_number + 1][cell_number] = 1 end if left == 0 #puts "%%%" new_image[row_number][cell_number - 1] = 1 end if right == 0 #puts "!!!" new_image[row_number][cell_number + 1] = 1 end end end end @image = new_image end end #row1 = [0,1,0,1,0] #row2 = [1,0,1,0,1] #row3 = [0,1,0,1,0] #row4 = [1,0,1,0,1] # row1 = [0,0,0,0,0] # row2 = [0,0,1,0,0] # row3 = [0,1,0,1,0] # row4 = [0,0,0,0,0] # row5 = [1,1,0,0,1] # row6 = [0,0,0,1,0] row1 = [0,0,0,0,0,0,0,0,0,0,0,0] row2 = [0,0,1,0,0,0,0,0,0,0,0,0] row3 = [0,1,0,1,0,0,0,0,0,1,0,0] row4 = [0,0,0,0,0,0,0,0,0,0,0,0] row5 = [1,1,0,0,1,0,0,0,0,0,0,0] row6 = [0,0,0,1,0,0,0,0,0,0,0,0] image = Image.new( [row1, row2, row3, row4, row5, row6] ) image.output_image("Before") image.blur(3)
true
619a9cbbc06ddc1e5e7fcfc7936307d82c15706a
Ruby
fs/sequence
/spec/sequence_spec.rb
UTF-8
622
2.96875
3
[]
no_license
require "sequence" describe Sequence do let(:sequence) { Sequence.new("1") } describe "#to_s" do it "returns initial value" do expect(sequence.to_s).to eql "1" end end describe "#next" do it "generates next state" do expect(sequence.next.to_s).to eql "11" end it "returns Sequence instance" do expect(sequence.next).to be_an_instance_of(Sequence) end it "generates next state 2 times" do expect(sequence.next.next.to_s).to eql "21" end it "generates next state 3 times" do expect(sequence.next.next.next.to_s).to eql "1211" end end end
true
5cae36c267310c29cbd723703bc8245dad71897b
Ruby
sfb673/ruby-for-linguists
/projects/chart_parser/specs/simple_chart_parser_spec.rb
UTF-8
2,300
2.8125
3
[]
no_license
%w(lexicon lex_entry).each do |k| require "../../mini-english/classes/#{k}" end %w(chart chart_entry rule rule_set simple_chart_parser).each do |k| require "../classes/#{k}" end describe Chart do before :each do # Hier wird eine reduzierte Version von Mini-English # eingesetzt - versuchen Sie mal, ob das volle Inventar # von Mini-English in Ihrer Ruby-Umgebung noch läuft, # ohne dass Sie minutenlang warten müssen... @rule_set = RuleSet.new @rule1 = Rule.new 'NP', ['N'] @rule2 = Rule.new 'NP', ['AD','N'] @rule3 = Rule.new 'NP_', ['D','NP'] @rule4 = Rule.new 'PP_', ['P','NP_'] @rule5 = Rule.new 'NP_', ['NP_','PP_'] @rule6 = Rule.new 'D', ['a'] @rule7 = Rule.new 'D', ['the'] @rule8 = Rule.new 'AD', ['happy'] @rule9 = Rule.new 'AD', ['sad'] @rule10 = Rule.new 'N', ['cat'] @rule11 = Rule.new 'N', ['zombie'] @rule12 = Rule.new 'P', ['with'] @rule13 = Rule.new 'P', ['for'] @rule_set.add_rule @rule1 @rule_set.add_rule @rule2 @rule_set.add_rule @rule3 @rule_set.add_rule @rule4 @rule_set.add_rule @rule5 @rule_set.add_rule @rule6 @rule_set.add_rule @rule7 @rule_set.add_rule @rule8 @rule_set.add_rule @rule9 @rule_set.add_rule @rule10 @rule_set.add_rule @rule11 @rule_set.add_rule @rule12 @rule_set.add_rule @rule13 @lexicon = Lexicon.new @scp = SimpleChartParser.new @lexicon, @rule_set @scp.set_input "the happy zombie with a sad cat" end context 'Construction' do it 'can be constructed' do @scp.should_not be nil end end context 'init charts' do it 'can init the charts' do @scp.register_start_values('NP_') end context 'expand' do it 'can expand charts' do @scp.register_start_values('NP_') @scp.expand puts @scp.chart @scp.chart.should_not be nil end end context 'scan' do it 'can scan charts' do @scp.register_start_values('NP_') @scp.expand @scp.scan @scp.chart.should_not be nil end end context 'parse' do # Sie können diesen Test verwenden, um Sätze zu parsen. it 'can parse' do @scp.parse "a zombie with a cat", 'NP_' end end end end
true
a2d39c245c3b2ce51df71fdc9f7ced30e584a8db
Ruby
aluisribeiro/academico-ads
/disciplina.rb
UTF-8
338
3.15625
3
[]
no_license
class Disciplina attr_reader :nome, :modulos, :professores def initialize (nome) @nome = nome @modulos = [] @professores = [] end def add_modulo modulo @modulos << modulo end def add_professor professor @professores << professor end end
true
597776c8fb6ac661c606e8fc08e4e9d8934eae67
Ruby
elena-ageeva/NPI-Lookup-Scraper
/lib/npi_lookup/scraper.rb
UTF-8
1,959
2.78125
3
[]
no_license
require 'open-uri' require 'pry' class NpiLookup::Scraper attr_accessor :doctors @doctors=[] #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #method is responsible for scraping the index page that lists all of the students #+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ def self.scrape_index_page(index_url='http://www.npinumberlookup.org/getResults.php') #html=File.read(index_url) doctors=Nokogiri::HTML(open(index_url)) #puts doctors #puts doctors.css("table tr")[0].text doctors.css("table tr").each_with_index do |doctor_css, i| if i>0 td=doctor_css.css("td") @doctors<<{ :last_name => td[1].text, :first_name =>td[3].text, :npi => td[0].text, :state => td[4].text, :zip => td[5].text, :details => doctor_css.css("td a")[0]["href"] } end end #@doctors=NpiLookup::Doctor.list #puts @doctors @doctors end def self.scrape_profile_page(profile_url) #html=File.read(profile_url) doctor=Nokogiri::HTML(open(profile_url)) #doctor_css=student.css("table tr") attributes=doctor.css("table tr") individual={ :gender =>attributes[3].css("td")[2].text, :provider_license =>attributes[4].css("td")[2].text, :entity =>attributes[8].css("td")[2].text, :last_update =>attributes[10].css("td")[2].text, :mailing_address =>attributes[13].css("td")[2].text, :m_phone =>attributes[14].css("td")[2].text, :m_fax =>attributes[15].css("td")[2].text, :business_address =>attributes[18].css("td")[2].text, :b_phone =>attributes[19].css("td")[2].text, :b_fax =>attributes[20].css("td")[2].text, :primary_taxonomy => attributes[23].css("td")[2].text, :secondary_taxonomy => attributes[24].css("td")[2].text, } individual end end
true
30116bb0b688749e4f8413a4aa0e39f3c1a33c8d
Ruby
vdice/epicodus-dealership
/lib/bicycle.rb
UTF-8
482
2.890625
3
[ "MIT" ]
permissive
class Bicycle @@bicycles = [] define_method(:initialize) do |make, bike_model, year| @make = make @bike_model = bike_model @year = year end define_method(:make) do @make end define_method(:model) do @bike_model end define_method(:year) do @year end define_method(:save) do @@bicycles.push(self) end define_singleton_method(:clear) do @@bicycles.clear() end define_singleton_method(:all) do @@bicycles end end
true
190b6d3b3c30f99c2bcf738137261827bea0ebf4
Ruby
NULL-OPERATOR/takeaway-challenge
/lib/menu.rb
UTF-8
199
3.296875
3
[]
no_license
class Menu attr_reader :menu_list MENU = {icecream: 5, dohnuts: 2, potatoes: 1} def initialize(menu=MENU) @menu_list = menu end def price(food) @menu_list[food.to_sym] end end
true
139fbde9f9e4c82f5105d57596bdd24d355354d8
Ruby
swcfischer/challenge_exercises
/protein_translation.rb
UTF-8
820
3.28125
3
[]
no_license
class Translation CODONS = { Methionine: ["AUG"], Phenylalanine: ["UUU", "UUC"], Leucine: ["UUA", "UUG"], Serine: ["UCU", "UCC", "UCA", "UCG"], Tyrosine: ["UAU", "UAC"], Cysteine: ["UGU", "UGC"], Tryptophan: ["UGG"], STOP: ["UAA", "UAG", "UGA"]} def self.of_codon(codon) CODONS.each do |key, value| return key.to_s if value.include?(codon) end raise(InvalidCodonError) unless self.valid?(codon) end def self.valid?(codon) CODONS.values.flatten.include?(codon) end def self.of_rna(rna) start = 0 limit = 2 result = [] while limit < rna.length result << self.of_codon(rna[start..limit]) start += 3 limit += 3 end if result.include?("STOP") result = result[0..result.index("STOP") - 1] end result end end
true
8f64cf7ff6fe236795e591417a64488302364dce
Ruby
Ricartho/deli-counter-noukod-000
/deli_counter.rb
UTF-8
783
3.78125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. katz_deli = [] def line(katz_deli) puts "The line is currently empty." if katz_deli.empty? if !katz_deli.empty? message = "The line is currently:" katz_deli.each_with_index do |val,index| message += " #{index.to_i+1}. #{val.strip}" end puts "#{message}" end end def take_a_number(katz_deli,name) if katz_deli.empty? katz_deli << "Ada" puts "Welcome, #{katz_deli[0]}. You are number 1 in line." elsif !katz_deli.empty? katz_deli << name puts "Welcome, #{name}. You are number #{katz_deli.size.to_i} in line." end end def now_serving(katz_deli) puts "There is nobody waiting to be served!" if katz_deli.empty? puts "Currently serving #{katz_deli[0]}." if !katz_deli.empty? katz_deli.shift end
true
b545dd19f0e003e33355d3a9e5425ce95ec48606
Ruby
abowler2/foundations
/lesson_2/mortgage_calc.rb
UTF-8
1,336
4.34375
4
[]
no_license
# Mortgage Calculator # need loan amount # need APR (annual percentage rate) # need loan duration # calculate monthly interest rate # calculate duration in months # formula: m = p * (j / (1 - (1 + j)**-n)) # m = monthly payment, p = loan amount, # j = monthly interest rate, n = loan duration in months def prompt(message) puts "=> #{message}" end def valid_number?(num) num.to_i.to_s == num && num.to_f > 0 end def valid_float?(num) num.to_f.to_s == num && num.to_f > 0 end def number?(input) valid_float?(input) || valid_number?(input) end prompt "Welcome to the Mortgage Calculator!" p = '' loop do prompt "Please enter your loan amount:" p = gets.chomp if valid_number?(p) break else puts "Please enter a valid loan amount." end end j = '' loop do prompt "What is your Annual Percentage Rate (APR)?" j = gets.chomp if number?(j) break else puts "Please enter a valid interest rate." end end duration = '' loop do prompt "How many years is your loan duration?" duration = gets.chomp if valid_number?(duration) break else puts "Please enter a valid duration in years for your loan." end end months = duration.to_i * 12 interest = (j.to_f / 12) / 100 m = p.to_i * (interest / (1 - (1 + interest)**-months)) puts "Your montly payment is $#{m.round(2)}"
true
934ae3fb5d329e4ec7f32951e603b7d5316080d3
Ruby
stockrt/latency
/latency.rb
UTF-8
7,176
2.640625
3
[]
no_license
#!/usr/bin/env ruby # coding: utf-8 # === Author # # Rogério Carvalho Schneider <stockrt@gmail.com> ############# ## DEFINES ## ############# # Distributed Ruby Objects. DRB_URL = 'druby://localhost:8787' ############## ## REQUIRES ## ############## require 'slop' require 'colorize' require 'net/http' require 'uri' require 'drb/drb' require_relative 'lib/stats' ########## ## MAIN ## ########## def main(opts) # URL. url = ARGV[0] # Wrong number of command line arguments. if url.nil? and not opts.help? puts opts exit 1 end # It is not an error to ask for help. exit 0 if opts.help? # Parse. uri = URI(url) # Splash. pubdelay_plural = opts[:pubdelay] == 1 ? '' : 's' maxlatency_plural = opts[:max] == 1 ? '' : 's' puts " URL: #{url} Host: #{uri.host} Port: #{uri.port} Channel: #{opts[:channel]} Pubdelay: #{opts[:pubdelay]} second#{pubdelay_plural} Outfile: #{opts[:outfile]} Pub URI: #{opts[:pub]} Sub URI: #{opts[:sub]} Max latency: #{opts[:max]} second#{maxlatency_plural} Verbosity: #{opts[:verbose]} ".light_cyan sleep 1 # Stats Server. Process.fork do begin stats = Stats.new DRb.start_service(DRB_URL, stats) DRb.thread.join rescue Interrupt puts puts puts "Published messages: #{stats.published}".light_cyan puts "Received messages: #{stats.received}".light_cyan puts end end # Pub. Process.fork do begin publisher(opts, uri) rescue Interrupt exit 0 end end # Sub. Process.fork do begin subscriber(opts, uri) rescue Interrupt exit 0 end end Process.waitall end # Pub. def publisher(opts, uri) stats = DRbObject.new_with_uri(DRB_URL) pub_uri = "#{opts[:pub]}?id=#{opts[:channel]}" pubdelay_plural = opts[:pubdelay] == 1 ? '' : 's' flag_first_conn = true # First request. puts '[Publisher] Connecting...'.light_yellow if opts[:verbose] > 0 Net::HTTP.start(uri.host, uri.port) do |http| puts '[Publisher] Connected'.light_yellow puts "[Publisher] URL: #{uri.scheme}://#{uri.host}:#{uri.port}#{pub_uri}".light_yellow if opts[:verbose] > 2 message = 'OPEN_CHANNEL' puts "[Publisher] Sending: #{message}".light_yellow if opts[:verbose] > 2 puts '[Publisher] First post'.light_yellow http.request_post(URI.escape(pub_uri), message) do |response| puts "[Publisher] Feedback: #{response.read_body}".light_yellow if opts[:verbose] > 0 end end puts '[Publisher] Disconnected'.light_yellow buffer = '' loop do if flag_first_conn puts '[Publisher] Connecting...'.light_yellow if opts[:verbose] > 0 else puts '[Publisher] Reconnecting...'.light_yellow if opts[:verbose] > 0 end Net::HTTP.start(uri.host, uri.port) do |http| if flag_first_conn flag_first_conn = false puts '[Publisher] Connected'.light_yellow else puts '[Publisher] Reconnected'.light_yellow end puts "[Publisher] URL: #{uri.scheme}://#{uri.host}:#{uri.port}#{pub_uri}".light_yellow if opts[:verbose] > 2 loop do send_timestamp = Time.now.strftime('%s.%L') message = "TS:#{send_timestamp}:" puts "[Publisher] Sending: #{message}".light_yellow if opts[:verbose] > 2 http.request_post(URI.escape(pub_uri), message) do |response| stats.published += 1 puts "[Publisher] Feedback: #{response.read_body}".light_yellow if opts[:verbose] > 0 end unless opts[:pubdelay] == 0 puts "[Publisher] Sleeping #{opts[:pubdelay]} second#{pubdelay_plural}".light_yellow if opts[:verbose] > 2 sleep opts[:pubdelay] end end end puts '[Publisher] Disconnected'.light_yellow sleep 1 end end # Sub. def subscriber(opts, uri) stats = DRbObject.new_with_uri(DRB_URL) sub_uri = "#{opts[:sub]}/#{opts[:channel]}" flag_first_conn = true buffer = '' loop do if flag_first_conn puts '[Subscriber] Connecting...'.light_cyan if opts[:verbose] > 0 else puts '[Subscriber] Reconnecting...'.light_cyan if opts[:verbose] > 0 end Net::HTTP.start(uri.host, uri.port) do |http| if flag_first_conn flag_first_conn = false puts '[Subscriber] Connected'.light_cyan else puts '[Subscriber] Reconnected'.light_cyan end puts "[Subscriber] URL: #{uri.scheme}://#{uri.host}:#{uri.port}#{sub_uri}".light_cyan if opts[:verbose] > 2 http.request_get(URI.escape(sub_uri)) do |response| response.read_body do |stream| recv_timestamp = Time.now.to_f buffer += stream # Compose line. while message = buffer.slice!(/.+\r\n/) puts "[Subscriber] Received: #{message}".light_cyan if opts[:verbose] > 0 # Parse sent timestamp. match_data = /TS:(?<ts>\d+\.\d+):/.match(message) send_timestamp = match_data ? match_data[:ts].to_f : nil puts "[Subscriber] Extracted timestamp: #{send_timestamp}".light_cyan if opts[:verbose] > 3 puts "[Subscriber] Timestamp now: #{recv_timestamp}".light_cyan if opts[:verbose] > 3 unless send_timestamp.nil? stats.received += 1 latency = recv_timestamp - send_timestamp # Max latency. if latency > opts[:max] puts "Latency: #{latency}".light_red else puts "Latency: #{latency}".light_green end # Write outfile. if opts.outfile? puts "[Subscriber] Appending latency value to outfile: #{opts[:outfile]}".light_cyan if opts[:verbose] > 2 outfile_handler = File.open(opts[:outfile], 'ab') outfile_handler.write("#{latency}\n") outfile_handler.close end end end end end end puts '[Subscriber] Disconnected'.light_cyan sleep 1 end end # Command line options. begin opts = Slop.parse(:help => true, :strict => true) do banner <<-EOS Usage: latency.rb url [options] Examples: latency.rb http://www.nginxpushstream.org --channel latency --pubdelay 1 --outfile output.txt latency.rb http://www.nginxpushstream.org -p /pub -s /sub --pubdelay 0.3 latency.rb http://www.nginxpushstream.org --max 0.5 latency.rb http://www.nginxpushstream.org -vvvv Options: EOS on :c=, :channel=, 'Channel name.', :default => 'latency' on :d=, :pubdelay=, 'Publisher delay (in seconds) between messages.', :as => Float, :default => 1 on :o=, :outfile=, 'Output file (write the last latency value to use in any external tool).' on :p=, :pub=, 'Pub URI.', :default => '/pub' on :s=, :sub=, 'Sub URI.', :default => '/sub' on :m=, :max=, 'Max latency before alert.', :as => Float, :default => 0.5 on :v, :verbose, 'Verbose mode.', :as => :count end rescue puts 'ERR: Invalid option. Try -h or --help for help.'.light_magenta exit 1 end begin main(opts) rescue Interrupt Process.waitall puts 'Exiting'.light_cyan exit 0 end
true
bc9589b0f9eca8b091f4603396384e7abbccfeb8
Ruby
valmikroy/lc-practice
/Arrays and Strings/Minimum Window Substring/problem.rb
UTF-8
2,172
3.375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # =begin Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, you are guaranteed that there will always be only one unique minimum window in S. =end =begin 3:56 start_idx middle_idx = 2nd occurance final_idxa = third occurance compare with length take a slice if needed else start from the middle idx position shortest = [] for main_str char by char take char and match with ever substring char end matched all chars flag match_sub_by_char with a closure 4:19 paused Failed in misrable manner 5:45 logic prepared two pointers start and mid 1st match where start = nil start = cur if start != nil and match is same as previous then start = cur if match is differ thant prev then mid = cur next match where start =! nil and mid != nil if match is same as start then start = mid and mid = current if match is same as previous then mid = current if match is new thne record string size make start = mid mid = current it took me a while to work with two position values but got it right in first try according to above logic =end shortest = [] S = "ADOBECODEBANC".split(//) T = "ABC".split(//) start = nil mid = nil cur = 0 loop do if T.include?(S[cur]) if start.nil? && mid.nil? start = cur end if !start.nil? if mid.nil? if S[cur] == S[start] start = cur else mid = cur end else if S[cur] == S[start] start = mid mid = cur elsif S[cur] == S[mid] mid = cur else tmp = S.slice(start,cur) if shortest.empty? shortest = tmp else shortest = tmp if shortest.length > tmp.length end start = mid mid = cur end end end end cur += 1 break if cur == S.length end p shortest
true
be4bc5a838582b0f2cdced529b23a773b6dc0b90
Ruby
raycast/script-commands
/templates/script-command.template.rb
UTF-8
900
2.59375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # Raycast Script Command Template # # Dependency: This script requires Ruby # Install Ruby: http://www.ruby-lang.org/ # # Duplicate this file and remove ".template." from the filename to get started. # See full documentation here: https://github.com/raycast/script-commands # # Required parameters: # @raycast.schemaVersion 1 # @raycast.title My First Script # @raycast.mode fullOutput # @raycast.packageName Raycast Scripts # # Optional parameters: # @raycast.icon 🤖 # @raycast.currentDirectoryPath ~ # @raycast.needsConfirmation false # @raycast.argument1 { "type": "text", "placeholder": "Placeholder text" } # # Documentation: # @raycast.description Write a nice and descriptive summary about your script command here # @raycast.author Your name # @raycast.authorURL An URL for one of your social medias # If accepting an argument: # arg1 = ARGV[0] puts "Hello World!"
true
8e8ddda50dec890430c3591a02cd13fbcc720fa0
Ruby
ECE421W17/Project2
/part2/prototype/timer
UTF-8
2,188
3.4375
3
[]
no_license
#! /usr/bin/env ruby require 'getoptlong' require 'test/unit/assertions' require_relative 'messageprinter' include Test::Unit::Assertions def print_help puts "timer [AMOUNT] [MESSAGE]" # The following range was chosen because the time in seconds will be of # time_t, which is of c type int, which can hold up to at least 32767 (on # a 32 bit architecture) and then, since the milliseconds are separated, # they can go up to 999 puts "AMOUNT: number of milliseconds to wait (between 0 and 32767999)" puts "MESSAGE: message to be displayed after timeout (up to 256 characters)" end def parse_command_input raise ArgumentError, "Wrong number of arguments" unless ARGV.size == 2 raise ArgumentError, "Time in milliseconds is not an integer" unless ARGV[0].respond_to?(:to_i) raise ArgumentError, "Time in milliseconds is not in the range 0 to 32767999" unless ARGV[0].to_i >= 0 and ARGV[0].to_i <= 32767999 raise ArgumentError, "Message is not a string" unless ARGV[1].respond_to?(:to_s) raise ArgumentError, "Message is too long" unless ARGV[1].to_s.length <= 256 end def parse_errno if (Messageprinter.errno == Errno::EINTR::Errno) raise Errno::EINTR, "The pause has been interrupted by a signal that was delivered to the process. Abort." elsif (Messageprinter.errno == Errno::EFAULT::Errno) raise Errno::EFAULT, "Problem with copying information from user space. Abort." elsif (Messageprinter.errno == Errno::EINVAL::Errno) raise Errno::EINVAL, "The value of nanoseconds in the sleep function was not within 0 to 999999999 or the value of seconds was negative. Abort." end end def drive_wait_and_print() begin parse_command_input amount = ARGV[0].to_i message = ARGV[1] rescue ArgumentError => ae puts "ERROR: #{ae}" puts "" print_help exit end exit if fork # Convert amount into seconds and nanoseconds for Messageprinter sec = amount/1000 nsec = (amount % 1000) * 1000000 ret = Messageprinter.wait_and_print(sec, nsec, message) if (ret == -1) parse_errno end end drive_wait_and_print
true
cabdeda051ab09113dd61ff4d6c4dc338521615c
Ruby
Jp1200/programming-univbasics-3-labs-with-tdd-austin-web-012720
/calculator.rb
UTF-8
211
2.71875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Add your variables here first_number = 69 second_number = 12 sum = first_number+second_number difference = first_number- second_number product= first_number*second_number quotient = first_number/second_number
true
858cf2b17712eb0a69afec3025ecf565c6c2a83c
Ruby
marcwright/WDI_ATL_1_Instructors
/REPO - DC - Students/w02/d02/Salil/bank_starter/lib/bank.rb
UTF-8
1,482
3.640625
4
[]
no_license
require "pry" class Bank attr_accessor :name def initialize(name) @name = name @accounts = [] end def accounts return @accounts end def empty? end def open_account(name, deposit) if deposit >= 200.0 accounts.push({:name => name, :balance => deposit}) else puts "You need more money fool" end end def last(name) return @accounts[name] end def find_account(name) account = [] accounts.find do |acct| if name == acct[:name] account = acct else return false end end return account end def return_balance(name) balance = 0 accounts.find do |acct| if name == acct[:name] balance = acct[:balance] else return false end end return balance end def withdraw(name, amount) balance = 0 accounts.find do |acct| if name == acct[:name] && acct[:balance] >= amount acct[:balance] -= amount balance = acct[:balance] elsif name == acct[:name] && acct[:balance] < amount acct[:balance] -= 30 balance = acct[:balance] else return false end end return balance end def deposit(name, deposit) balance = 0 accounts.find do |acct| if name == acct[:name] acct[:balance] = acct[:balance] + deposit balance = acct[:balance] else return false end end return balance end end
true
b37035b0c7ece8e563bfe4fd098ad1ffa7b29485
Ruby
railkun/ruby_routes_trie
/lib/trie/node.rb
UTF-8
402
3.203125
3
[]
no_license
module RubyRoutesTrie class Node DYNAMIC = 1 STATIC = 0 attr_reader :value, :children attr_accessor :method, :route, :type def initialize(value) @children = [] @value = value @method = '' @route = '' @type = value[0] == ':' ? DYNAMIC : STATIC end def dynamic? @type == DYNAMIC end end end
true
6647421e89b91f83b184dcc014a1651c4bab2f30
Ruby
kasumi8pon/nlp100
/01.rb
UTF-8
82
2.90625
3
[]
no_license
puts "パタトクカシーー".chars.map.with_index { |s, i| s if i.even? }.join
true
58d63881bd32546a9999768bb045b7bfa4e83a48
Ruby
foton/egg_hunt_api
/app/models/coordinate.rb
UTF-8
936
2.921875
3
[]
no_license
class Coordinate < ActiveRecord::Base has_many :locations, dependent: :destroy COORDINATES_REGEXP =/(\d*.\d*)([NSEW])\s*,\s*(\d*.\d*)([NSEW])/ def initialize(*args) if args.first.kind_of?(String) && (p_match=args.first.upcase.match(COORDINATES_REGEXP)) super({latitude_number: p_match[1].to_f, latitude_hemisphere: p_match[2], longitude_number: p_match[3].to_f, longitude_hemisphere: p_match[4]}) else super end raise "Wrong coordinate created #{args}: #{self.to_yaml}" if self.latitude_number.blank? || self.latitude_hemisphere.blank? || self.longitude_number.blank? || self.longitude_hemisphere.blank? end def to_s "#{lat_num}#{lat_hem}, #{long_num}#{long_hem}" end def long_num longitude_number end def lat_num latitude_number end def long_hem longitude_hemisphere.to_s.upcase end def lat_hem latitude_hemisphere.to_s.upcase end end
true
8b6dd96f0b8ccde04bc4d606d15663aa1a3c8d02
Ruby
ToccataN/rubyblock1
/CC.rb
UTF-8
380
3.765625
4
[]
no_license
puts "Phrase: " text = gets.chomp.downcase() puts "Number: " n = gets.chomp.to_i alpha = ('a'..'z').to_a letters= text.split('').to_a number = Hash[alpha.map.with_index.to_a] string = [] letters.each do |i| if number[i] == nil string.push(" ") else number2= number[i] -n newletter=alpha[number2] string.push(newletter.to_s) end end puts string.join("")
true
7a71815b8b79232db0233d97b4225f66704d61ae
Ruby
tmtmtmtm/stance-viewer-jekyll
/_bin/generate_issue_pages.rb
UTF-8
592
2.640625
3
[]
no_license
#!/usr/bin/ruby # Generate pages for each Issue require 'json' require 'yaml' require 'parallel' @data = JSON.parse(File.read('_data/issues.yaml')) es = ARGV[0].nil? ? @data : @data.select { |e| e['id'] == ARGV[0] } warn "Operating on #{es.count} entries" Parallel.each(es, :in_threads => 5) do |e| filename = "issue/#{e['id']}.md" warn "Processing #{e['id']} to #{filename}" data = { "layout" => 'issue', "id" => e['id'], "title" => e['text'], "html" => e['html'], "autogenerated" => true, } text = data.to_yaml + "---\n" File.write(filename, text) end
true
7926fe51b9824c41f6e0279dfb53b08be51d68fb
Ruby
jeltz/innate
/spec/innate/state/thread.rb
UTF-8
877
2.65625
3
[ "MIT" ]
permissive
require 'spec/helper' require 'innate/state/thread' describe Innate::State::Thread do T = Innate::State::Thread it 'sets value in current thread with #[]=' do t = T.new t[:a] = :b Thread.current[:a].should == :b end it 'gets value in current thread with #[]' do t = T.new Thread.current[:b] = :c t[:b].should == :c end it 'executes block in #wrap' do t = T.new t.wrap{ :foo }.should == :foo end it 'reraises exceptions occured in #wrap thread' do t = T.new Thread.abort_on_exception = false lambda{ t.wrap{ raise 'foo' } }.should.raise end it 'defers execution of passed block in #defer' do t = T.new t.defer{ :foo }.value.should == :foo end it 'copies thread variables to thread spawned in #defer' do t = T.new t[:a] = :b t.defer{ Thread.current[:a] }.value.should == :b end end
true
70602c83cab781e21e1adede04b06e280b2e911c
Ruby
Torgian/Ruby_Exercises
/ChapterOne/exercise_two.rb
UTF-8
101
2.96875
3
[]
no_license
puts 5283 / 1000 puts 9832 % 1000 / 100 #hundreds puts 8137 % 100 / 10 #tens puts 1394 % 10 / 1 #ones
true
4be7aa6b8ab03e28c5a1dacaf292e9ae33386eac
Ruby
zidailiu/rails-yelp-mvp
/db/seeds.rb
UTF-8
1,002
2.78125
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) puts "Cleaning database..." Restaurant.destroy_all puts "Creating restaurants" pizzahut = { name:"pizzahut", address: "3625 east avn", category: "french" } pandaexpress = { name:"pandaexpress", address: "273 central avn", category: "chinese" } mac = { name:"mac", address: "sunset boulevard east", category: "italian" } jose = { name:"jose", address: "277 rue bleury", category: "belgian" } ganadara = { name:"ganadara", address: "544 rue bishop", category: "japanese"} [ pizzahut, pandaexpress, mac, jose, ganadara ].each do |attr| restaurant = Restaurant.create!(attr) puts "Created #{restaurant.name}" end puts "Finished!"
true
693a32d4e89c90bf769b5561e44c04119702e431
Ruby
wyy1234567/ruby-enumerables-hash-practice-emoticon-translator-lab-nyc-web-030920
/lib/translator.rb
UTF-8
736
3.28125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# require modules here require "yaml" def load_library(file) # code goes here ans = {'get_meaning' => {}, 'get_emoticon' => {}} emoticons = YAML.load_file(file) emoticons.each do |key, value| ans['get_meaning'][value[1]] = key ans['get_emoticon'][value[0]] = emoticons[key][1] end ans end def get_japanese_emoticon(file, jEmotion) # code goes here hash = load_library(file) if !hash['get_emoticon'][jEmotion] return "Sorry, that emoticon was not found" end hash['get_emoticon'][jEmotion] end def get_english_meaning(file, jEmotion) # code goes here hash = load_library(file)['get_meaning'] if !hash[jEmotion] return "Sorry, that emoticon was not found" end hash[jEmotion] end
true
1c51296297bf623a721dc54e2721627fb0228673
Ruby
din982/yard-docco
/example/annotated_source.rb
UTF-8
9,288
3.140625
3
[ "MIT" ]
permissive
# An example pirate ship. class Example # @todo Yar! There be comments ahead, within these method. And if you are wise # you will view the annotated source. def a_word_of_warning # Comments are found and collected and matched to the code that immediately # follows the comments. You will be able to see these comments to the left # of the source code that follows self.to_s.capitalize end # You must have stolen a pirate's rum to have been given this fate. def walk_the_plank # @note A note should be parsed and appear in the comments. Which will make # it easier to find code that needs to be addressed. puts "Yo Ho, Yo Ho!" # I should have listened to the {#a_word_of_warning} (which I can link to # and visit immediately from within the method comments). Too late. puts "Walk the Plank!" # @todo Even todo tags will appear as well. This todo is telling me I should # code up the plank to walk. # # No code follows save for the end of the method, but the comment should still # appear paired with a block of code. end # # What? Even pirate ships need to export to XML. # # Create an xml representation of the specified class based on defined # HappyMapper elements and attributes. The method is defined in a way # that it can be called recursively by classes that are also HappyMapper # classes, allowg for the composition of classes. # # @param [Nokogiri::XML::Builder] builder an instance of the XML builder which # is being used when called recursively. # @param [String] default_namespace the name of the namespace which is the # default for the xml being produced; this is specified by the element # declaration when calling #to_xml recursively. # # @return [String,Nokogiri::XML::Builder] return XML representation of the # HappyMapper object; when called recursively this is going to return # and Nokogiri::XML::Builder object. # def to_xml(builder = nil,default_namespace = nil) # # If {#to_xml} has been called without a passed in builder instance that # means we are going to return xml output. When it has been called with # a builder instance that means we most likely being called recursively # and will return the end product as a builder instance. # unless builder write_out_to_xml = true builder = Nokogiri::XML::Builder.new end # # Find the attributes for the class and collect them into an array # that will be placed into a Hash structure # attributes = self.class.attributes.collect do |attribute| # # If an attribute is marked as read_only then we want to ignore the attribute # when it comes to saving the xml document; so we wiill not go into any of # the below process # unless attribute.options[:read_only] value = send(attribute.method_name) # # If the attribute defines an on_save lambda/proc or value that maps to # a method that the class has defined, then call it with the value as a # parameter. # if on_save_action = attribute.options[:on_save] if on_save_action.is_a?(Proc) value = on_save_action.call(value) elsif respond_to?(on_save_action) value = send(on_save_action,value) end end # # Attributes that have a nil value should be ignored unless they explicitly # state that they should be expressed in the output. # if value || attribute.options[:state_when_nil] attribute_namespace = attribute.options[:namespace] || default_namespace [ "#{attribute_namespace ? "#{attribute_namespace}:" : ""}#{attribute.tag}", value ] else [] end else [] end end.flatten attributes = Hash[ *attributes ] # # Create a tag in the builder that matches the class's tag name and append # any attributes to the element that were defined above. # builder.send(self.class.tag_name,attributes) do |xml| # # Add all the registered namespaces to the root element. # When this is called recurisvely by composed classes the namespaces # are still added to the root element # # However, we do not want to add the namespace if the namespace is 'xmlns' # which means that it is the default namesapce of the code. # if self.class.instance_variable_get('@registered_namespaces') && builder.doc.root self.class.instance_variable_get('@registered_namespaces').each_pair do |name,href| name = nil if name == "xmlns" builder.doc.root.add_namespace(name,href) end end # # If the object we are persisting has a namespace declaration we will want # to use that namespace or we will use the default namespace. # When neither are specifed we are simply using whatever is default to the # builder # if self.class.respond_to?(:namespace) && self.class.namespace xml.parent.namespace = builder.doc.root.namespace_definitions.find do |x| x.prefix == self.class.namespace end elsif default_namespace xml.parent.namespace = builder.doc.root.namespace_definitions.find do |x| x.prefix == default_namespace end end # # When a text_node has been defined we add the resulting value # the output xml # if text_node = self.class.instance_variable_get('@text_node') unless text_node.options[:read_only] text_accessor = text_node.tag || text_node.name value = send(text_accessor) if on_save_action = text_node.options[:on_save] if on_save_action.is_a?(Proc) value = on_save_action.call(value) elsif respond_to?(on_save_action) value = send(on_save_action,value) end end builder.text(value) end end # # for every define element (i.e. has_one, has_many, element) we are # going to persist each one # self.class.elements.each do |element| # # If an element is marked as read only do not consider at all when # saving to XML. # unless element.options[:read_only] tag = element.tag || element.name # # The value to store is the result of the method call to the element, # by default this is simply utilizing the attr_accessor defined. However, # this allows for this method to be overridden # value = send(element.name) # # If the element defines an on_save lambda/proc then we will call that # operation on the specified value. This allows for operations to be # performed to convert the value to a specific value to be saved to the xml. # if on_save_action = element.options[:on_save] if on_save_action.is_a?(Proc) value = on_save_action.call(value) elsif respond_to?(on_save_action) value = send(on_save_action,value) end end # Normally a nil value would be ignored, however if specified then # an empty element will be written to the xml # if value.nil? && element.options[:single] && element.options[:state_when_nil] xml.send(tag,"") end # # To allow for us to treat both groups of items and singular items # equally we wrap the value and treat it as an array. # if value.nil? values = [] elsif value.respond_to?(:to_ary) && !element.options[:single] values = value.to_ary else values = [value] end values.each do |item| if item.is_a?(HappyMapper) # # Other items are convertable to xml through the xml builder # process should have their contents retrieved and attached # to the builder structure # item.to_xml(xml,element.options[:namespace]) elsif item item_namespace = element.options[:namespace] || default_namespace # # When a value exists we should append the value for the tag # if item_namespace xml[item_namespace].send(tag,item.to_s) else xml.send(tag,item.to_s) end else # # Normally a nil value would be ignored, however if specified then # an empty element will be written to the xml # xml.send(tag,"") if element.options[:state_when_nil] end end end end end write_out_to_xml ? builder.to_xml : builder end end
true
7741277c61e676750ccaeb8dec47feff256eec27
Ruby
r3h4n/Intro_to_Programming_LS
/my_randoms/while_loop.rb
UTF-8
269
4.1875
4
[]
no_license
## Write a while loop that takes input from ## the user, performs an action, and only ## stops when the user types "STOP". ## Each loop can get info from the user. x = gets.chomp.to_s while x != "STOP" puts 'Say something' x = gets.chomp.to_s end puts "Done"
true
593e58bfaf5ddc41402cff91decd0ac0f4bd5167
Ruby
jmcaffee/ppmtogdl
/lib/ppmtogdl/ppmcontext.rb
UTF-8
2,061
2.953125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
############################################################################### # File:: ppmcontext.rb # Purpose:: PpmContext class holds ppm variable definitions # # Author:: Jeff McAffee 04/30/2015 # ############################################################################## module PpmToGdl class PpmContext attr_accessor :ppms attr_accessor :options def initialize() $LOG.debug "PpmContext::initialize()" @ppms = Hash.new end # initialize def setOptions(options) $LOG.debug "PpmContext::setOptions( #{options} )" @options = options end # Generate a valid guideline (GDL) ID # inname:: name to convert def createValidName(inname) $LOG.debug "PpmContext::createValidName( #{inname} )" outname = inname.gsub(/[\s\/\\?*#+]/,'') # Remove illegal chars (replace with underscore). outname.gsub!(/_+/,"_") # Replace consecutive uscores with single uscore. outname.gsub!(/\./,"-") # Replace period with dash. outname.gsub!(/[\(\)\$]/,"") # Remove L & R Parens, dollar signs. outname.gsub!(/\%/,"Perc") # Replace '%' with Perc. outname end def isPpmVar(var) isPpm = false case var.varType when 'app' isPpm = true when 'crd' isPpm = true when 'prd' isPpm = true end # case isPpm end # isPpmVar # Dump all PPM variables def dumpPpms() $LOG.debug "PpmContext::dumpPpms()" 79.times {print "="} puts puts "PPM DUMP".center(80) 79.times {print "="} puts if(@ppms.length > 0) ppms = @ppms.sort ppms.each do |key, ppm| puts "#{ppm.name}\t(#{ppm.alias})" end else puts "No PPM variables to dump." end puts "" end # dumpppms end # class PpmContext end # module PpmToGdl
true
061bb1e407cd94aa2593c2ce073d0acae05756ed
Ruby
TotodileNTHU/Totodile
/spec/account_spec.rb
UTF-8
2,660
2.515625
3
[]
no_license
require_relative './spec_helper' describe 'Testing unit level properties of accounts' do before do Posting.dataset.destroy Account.dataset.destroy @original_password = 'mypassword' @account = CreateAccount.call( name: 'soumya.ray', email: 'sray@nthu.edu.tw', password: @original_password) end it 'HAPPY: should hash the password' do _(@account.password_hash).wont_equal @original_password end it 'HAPPY: should re-salt the password' do hashed = @account.password_hash @account.password = @original_password @account.save _(@account.password_hash).wont_equal hashed end end describe 'Testing Account resource routes' do before do Posting.dataset.destroy Account.dataset.destroy end describe 'Creating new account' do before do registration_data = { name: 'test.name', password: 'mypass', email: 'test@email.com' } @req_body = registration_data.to_json end it 'HAPPY: should create a new unique account' do req_header = { 'CONTENT_TYPE' => 'application/json' } post '/api/v1/accounts/', @req_body, req_header _(last_response.status).must_equal 201 _(last_response.location).must_match(%r{http://}) end it 'SAD: should not create accounts with duplicate usernames' do req_header = { 'CONTENT_TYPE' => 'application/json' } post '/api/v1/accounts/', @req_body, req_header post '/api/v1/accounts/', @req_body, req_header _(last_response.status).must_equal 400 _(last_response.location).must_be_nil end end describe 'Finding an existing account' do before do @new_account = CreateAccount.call( name: 'test.name', email: 'test@email.com', password: 'mypassword') @new_postings = (1..3).map do |i| # method of add_owned_posting is created by sequel, # when we declare account has one_to_many relationshop with owned_posting in models/account.rb # owned_posting is naming, its class is Posting @new_account.add_owned_posting(content: "this is content of posting #{i}") end end it 'HAPPY: should find an existing account' do get "/api/v1/accounts/#{@new_account.id}" _(last_response.status).must_equal 200 results = JSON.parse(last_response.body) _(results['data']['id']).must_equal @new_account.id 3.times do |i| _(results['relationships'][i]['id']).must_equal @new_postings[i].id end end it 'SAD: should not return wrong account' do get "/api/v1/accounts/#{random_str(10)}" _(last_response.status).must_equal 401 end end end
true
dca98a4e3d285b2c83bc6d725767cef6025002a7
Ruby
jamestunnell/spnet
/lib/spnet/storage/link_state.rb
UTF-8
1,187
3.03125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module SPNet # Represent a Link object using only serializeable objects. # # @author James Tunnell class LinkState include Hashmake::HashMakeable # Define arg specs to use in processing hashed arguments during #initialize. ARG_SPECS = { :from => arg_spec(:reqd => true, :type => PortLocater), :to => arg_spec(:reqd => true, :type => PortLocater) } attr_reader :from, :to def initialize args hash_make args, ARG_SPECS end # Make a Link objet from the current LinkState object. def make_link blocks raise "from block #{@from.block_name} not found" unless blocks.has_key?(@from.block_name) raise "to block #{@to.block_name} not found" unless blocks.has_key?(@to.block_name) from_block = blocks[@from.block_name] to_block = blocks[@to.block_name] raise "from port #{@from.port_name} not found" unless from_block.out_ports.has_key?(@from.port_name) raise "to port #{@to.port_name} not found" unless to_block.in_ports.has_key?(@to.port_name) from_port = from_block.out_ports[@from.port_name] to_port = to_block.in_ports[@to.port_name] return Link.new(:from => from_port, :to => to_port) end end end
true
218fe1b338056f31e371fd9ceb3f68cc16d36c16
Ruby
txusyk/rubyIdeas
/IMDB-Manager/test/tc_actor_catalog.rb
UTF-8
809
2.8125
3
[]
no_license
require 'test/unit' require_relative '../actor_catalog' require_relative '../actor' class Tc_actor_catalog < Test::Unit::TestCase def test_initialize assert_not_nil(Actor_catalog.instance) p '*****'*5+'test_initialize'+'*****'*5 p 'Is Actor_catalog null? --->'+Actor_catalog.instance.nil?.to_s end def test_add_exist? Actor_catalog.instance.add(Actor.new('Josu','Alvarez')) assert_equal(true, Actor_catalog.instance.exist?('Josu','Alvarez')) p '*****'*5+'test_add_exist?'+'*****'*5 p "Actor: Josu Alvarez ---> #{Actor_catalog.instance.exist?('Josu','Alvarez')}" end def test_remove Actor_catalog.instance.remove(Actor.new('Josu','Alvarez')) p '*****'*5+'test_remove'+'*****'*5 p "Actor: Josu Alvarez ---> #{Actor_catalog.instance.exist?('Josu','Alvarez')}" end end
true
3a9b55f5223d6baa211c63feda14051e70a544d4
Ruby
TetsuyaNegishi/atcoder
/AtCoderProblems/ABC068/B.rb
UTF-8
98
3.1875
3
[]
no_license
N = gets.chomp.to_i result = 1 loop do break if result > N result *= 2 end puts result / 2
true
5384b7abac2006dac912e61630f4b3166933180a
Ruby
JoshuaHinman/101
/lesson3/easy1/question5.rb
UTF-8
58
3.015625
3
[]
no_license
if (0..100).include?(42) puts '42' else puts 'not' end
true
cc695439044219436d578364142f5aa03c140a9e
Ruby
christianlarwood/ruby_small_problems
/live_coding_exercises/repeated_substring_v2.rb
UTF-8
1,854
4.28125
4
[]
no_license
=begin Given a non-empty string, check if it can be constructed by taking a substring of it and appending multiple copies of the substring together. You may assume the given string consists of lowercase English letters only. Example 1: - Input "abab" - Output: True - Explanation: It's the substring 'ab' twice. Example 2: - Input: "aba" - Output: False input: string output: boolean algorithm: - find a substring that isn't the string itself - if substring is evenly divisible into string - AND when multiplied by the divisor it equals the string - return true - else return false - find all substrings that are less than and up to 1/2 the length of the string - iterate through those substrings and if any can be multiplied by the divisor of the string length divided by the substring length, return true - else return false =end def repeated_substring(string) substrings = [] max = string.size / 2 0.upto(max).each do |index| substrings << string[0..index] end substrings.each do |substring| if substring * (string.length / substring.length) == string return true end end false end # my original solution def repeated_substring(string) length = string.size (0...length).each do |index| (index...length).each do |index2| substring = string[index..index2] if substring != string if length % substring.length == 0 multiplier, rem = length.divmod(substring.length) if string == substring * multiplier return true end end end end end false end p repeated_substring('abab') == true p repeated_substring('aba') == false p repeated_substring('aabaaba') == false p repeated_substring('abaababaab') == true p repeated_substring('abcabcabcabc') == true p repeated_substring('aaaaa') == true
true
46cebc620af81d17a6dc807a66bcfce400fde699
Ruby
MrChriss/Ruby
/LS-ObjectOrientedProgramming-BackEnd/lesson_4/easy_1.rb
UTF-8
1,844
3.875
4
[]
no_license
# Question 1 # all of the folowing are objects # to find wich classes they belong to, # use .class instance method of Object class. # true.class # => TrueClass # "hello".class # => String # [1, 2, 3, "happy days"].class # => Array # 142.class # => Fixnum # Question 2 # by including the modlue Speed in the classes Car and Truck # to find out if a class has a method, call the method # on an instance of the class. # Question 3 # this is because we used ``self.class`` in method definition # self inside the method definition refers to the instance of the class # self.class therefore refers to the class of the instance, which is Car. # Question 4 # to initiate a new object of class AngryCat, we use # .new instance method of class Class. # Question 5 # class Pizza has an instance variable, # class Fruit has a local variable. # instance variables' names are preceded by ``@`` # alternatively, instance method .instance_variables, # could be called on object to get an array containig # all the instance variables of the object. # Question 6 # to access instance variable, we could define a ``getter method`` # by using instance method ``attr_reader`` of class Module. # or by "manualy" definig a method, which returns the instance variable. # or by calling the instance method .instance_variable_get of class Object # and supplying it with the instance variable. # Question 7 # calling to_s method on object, will print the object's class and an # encoding of the object id to the console. # Question 8 # ``self`` in the definition of an instance method refers to the instance # (object), that called the method. # Question 9 # ``self`` in the name of class mehod refers to the class itself # Question 10 # in this case, if we want to initialize a new instance, we have to call # the method .new, and suply it with two arguments.
true
4cae124a1f683753f713fd628fb90732d020d74b
Ruby
hgodinot/hgodinot-Launch_School
/RB_challenges/medium_1/6.rb
UTF-8
549
3.625
4
[]
no_license
class School def initialize @hsh = Hash.new end def to_h @hsh.sort.to_h end def add(name, grade) @hsh[grade].nil? ? @hsh[grade] = [name] : (@hsh[grade] << name).sort! end def grade(grd) @hsh[grd] || [] end end # other way: class School attr_reader :hash def initialize @hash = Hash.new { |hash, grade| hash[grade] = [] } end def to_h hash.sort.each { |grade, name| name.sort! }.to_h end def add(name, grade) hash[grade] << name end def grade(n) @hash[n] end end
true
b4f877e74d8158a0072a81b0aa75ff860af55f10
Ruby
miguelvieira123/BetESSEntrega
/MVC/SportEvent.rb
UTF-8
463
2.953125
3
[]
no_license
class SportEvent < Object attr_reader :event_id,:state,:team1,:team2,:result,:odd,:owner_id def initialize(owner, event_id) @event_id = event_id @state = false @team1 @team2 @result = "-" @odd = [1.0,1.0,1.0] @owner_id = owner end def setTeam1(team) @team1 = team end def setState(state) @state = state end def setTeam2(team) @team2 = team end def setOdd(odd) @odd = odd end def setResult(result) @result = result end end
true
f651e897603574ae4083ba26fde0e5c0aded687f
Ruby
apavlyut/geekbrainsror
/vehicle.rb
UTF-8
2,976
3.015625
3
[]
no_license
class Vehicle def initialize(name='ТС пользователя',doors=4,weels=4,distance=30.0, reaction=1.5, coef_road=0.7) @name=name @doors=doors @weels=weels @distance=distance # дистанция до впереди идущей машины @reaction=reaction # время реакции водителя @status='ok' @braking=0.0 #m тормозной путь @current_speed=0.0 #km/h @max_speed=80 # km/h @coef_road=coef_road @sprint=28.0 # м/сек.кв. Ускорение при разгоне end def speed_for_testing(speed) # принудительно меняет скорость ТС @current_speed=speed end def max_speed_value @max_speed end def distance # возвращает дистанцию до впереди идущего ТС @distance end def name # возвращает название ТС @name end def braking_distance #+ возвращает тормозной путь ТС @braking=(0.28*@current_speed*@reaction + @current_speed**2/(254.0*@coef_road)).round(2) end def move(sec) # Старт и равномерное движение на крейсерской скорости движение timer=sec.to_f speed=(@sprint*(timer-@reaction)*0.28).round(2) if timer>@reaction @current_speed= (speed<@max_speed)? speed : @max_speed end @current_speed end def braking(sec, ready) # торможение (время торможения, говоность водителя отреагировать) timer=sec.to_f # расчет ускорения торможения braker=(@current_speed**2/(2.0*@braking*7.84)).round(2) # расчет текущей скорости в момент торможения if ready==false brak_speed= (timer<=@reaction)? @current_speed : @current_speed - braker*(timer-@reaction) else brak_speed = @current_speed - braker*timer end if brak_speed>0.0 @current_speed=brak_speed.round(2) else @current_speed=0.0 end @current_speed end def crush # присвоение состояния - уничтожен @status='Транспортное средство уничтожено, звоните 112!' @current_speed=0.0 end def inspect # вывод всех параметров ТС "name: #{@name}, doors: #{@doors} , weels: #{@weels}, distance: #{@distance}, reaction: #{@reaction}, status: #{@status}, braking distances: #{@braking}, speed: #{@current_speed}, max_speed: #{@max_speed}, c_road: #{@coef_road}, sprint: #{@sprint}" end end
true
6889afa29677c12469dca849940c30703e6b5060
Ruby
AlondraZepeda96/Ruby_ejemplos2
/ejemplos/documento.rb
UTF-8
549
2.640625
3
[]
no_license
clase Documento attr_accessor : nombre , : tipo , : a ño def initialize ( nombre , tipo , a ño) @nombre = nombre @tipo = tipo @a ño = año fin fin clase Libro <Documento attr_accessor : autor def initialize ( autor , nombre , tipo , a ño) @autor = autor @nombre = nombre @tipo = tipo @a ño = año fin fin libro = Documento . nuevo ( " Las Leyendas Del Tec " , " Terror " , " 2018 " ) pone lirbo.nombre pone libro.tipo pone libro.año pone el libro
true
08c4fe13a10d2136fbc556031f2cc8d667254cd2
Ruby
myneworder/atmosphere
/lib/atmosphere/utils.rb
UTF-8
2,609
2.96875
3
[ "MIT" ]
permissive
module Atmosphere module Utils def min_elements_by(arr, &block) if block_given? min_elements_by_with_block(arr, &block) else min_elements_by_without_block(arr) end end def max_elements_by(arr, &block) if block_given? max_elements_by_with_block(arr, &block) else max_elements_by_without_block(arr) end end private def min_elements_by_with_block(arr, &block) min_elements, arr = first_elements_and_residue(arr, &block) return [] if arr.empty? && min_elements.nil? arr.each do |e| current_min_elements_value = yield(min_elements.first) element_value = yield(e) next unless current_min_elements_value && element_value if current_min_elements_value > element_value min_elements = [e] elsif current_min_elements_value == element_value min_elements << e end end min_elements end def first_elements_and_residue(arr) arr.compact! return [nil, []] if arr.empty? first_el = arr.shift until yield(first_el) || arr.empty? first_el = arr.shift end first_elements = if yield(first_el).nil? [] else [first_el] end [first_elements, arr] end def min_elements_by_without_block(arr) arr.compact! return [] if arr.empty? min_elements = [arr.shift] arr.each do |e| if min_elements.first > e min_elements = [e] elsif min_elements.first == e min_elements << e end end min_elements end def max_elements_by_with_block(arr, &block) max_elements, arr = first_elements_and_residue(arr, &block) return [] if arr.empty? && max_elements.nil? arr.each do |e| current_max_elements_value = yield(max_elements.first) element_value = yield(e) next unless current_max_elements_value && element_value if current_max_elements_value < element_value max_elements = [e] elsif current_max_elements_value == element_value max_elements << e end end max_elements end def max_elements_by_without_block(arr) arr.compact! return [] if arr.empty? max_elements = [arr.shift] arr.each do |e| if max_elements.first < e max_elements = [e] elsif max_elements.first == e max_elements << e end end max_elements end end end
true
839982427e1ed1f6f4d5f5120d30ccd3f2f7a2d4
Ruby
emrekutlu/bluebird
/lib/bluebird/strategies/via/strategy.rb
UTF-8
1,521
2.671875
3
[ "MIT" ]
permissive
module Bluebird module Strategies module Via class Strategy < Bluebird::Strategies::Base class << self def run(tweet, config) if run?(config.via.username) add_separator(tweet) tweet.add_partial(text(config.via), :via) end end private def run?(username) username_exists?(username) ? true : raise('Bluebird: config.via.username is missing.') end def add_separator(tweet) if add_separator?(tweet) add_separator_partial?(tweet) ? add_separator_partial(tweet) : add_space_to_last_partial(tweet) end end def text(via_config) "#{via_config.prefix} @#{via_config.username}" end def username_exists?(username) if username username.strip! !username.eql?('') else false end end def add_separator_partial?(tweet) !tweet.partials.last.text? end def add_separator?(tweet) tweet.partials.length > 0 end def add_separator_partial(tweet) tweet.add_partial(' ', :text) end def add_space_to_last_partial(tweet) last = tweet.partials.last unless last.content.end_with?(' ') last.content += ' ' end end end end end end end
true
d5987ee33075c20ee507b40cf42ffc9f549c27bb
Ruby
Dalf32/AdventOfCode2015
/Day1/day_1-2.rb
UTF-8
198
3.375
3
[]
no_license
#day_1-2.rb BASEMENT = -1 current_floor = 0 index = 0 open(ARGV.shift).each_char do |char| index += 1 current_floor += char == '(' ? 1 : -1 break if current_floor == BASEMENT end puts index
true
7ad2920da1ff83ab08f552b0488d2cf53c3cc42e
Ruby
QPC-WORLDWIDE/rubinius
/benchmark/app/rdoc-2.4.3/lib/rdoc/any_method.rb
UTF-8
3,217
2.921875
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'rdoc/code_object' require 'rdoc/tokenstream' ## # AnyMethod is the base class for objects representing methods class RDoc::AnyMethod < RDoc::CodeObject ## # Method name attr_writer :name ## # public, protected, private attr_accessor :visibility ## # Parameters yielded by the called block attr_accessor :block_params ## # Don't rename \#initialize to \::new attr_accessor :dont_rename_initialize ## # Is this a singleton method? attr_accessor :singleton ## # Source file token stream attr_reader :text ## # Array of other names for this method attr_reader :aliases ## # Fragment reference for this method attr_reader :aref ## # The method we're aliasing attr_accessor :is_alias_for ## # Parameters for this method attr_overridable :params, :param, :parameters, :parameter ## # Different ways to call this method attr_accessor :call_seq include RDoc::TokenStream ## # Resets method fragment reference counter def self.reset @@aref = 'M000000' end reset def initialize(text, name) super() @text = text @name = name @token_stream = nil @visibility = :public @dont_rename_initialize = false @block_params = nil @aliases = [] @is_alias_for = nil @call_seq = nil @aref = @@aref @@aref = @@aref.succ end ## # Order by #singleton then #name def <=>(other) [@singleton ? 0 : 1, @name] <=> [other.singleton ? 0 : 1, other.name] end ## # Adds +method+ as an alias for this method def add_alias(method) @aliases << method end ## # HTML id-friendly method name def html_name @name.gsub(/[^a-z]+/, '-') end def inspect # :nodoc: alias_for = @is_alias_for ? " (alias for #{@is_alias_for.name})" : nil "#<%s:0x%x %s%s%s (%s)%s>" % [ self.class, object_id, parent_name, singleton ? '::' : '#', name, visibility, alias_for, ] end ## # Full method name including namespace def full_name "#{@parent.full_name}#{pretty_name}" end ## # Method name def name return @name if @name @name = @call_seq[/^.*?\.(\w+)/, 1] || @call_seq end ## # Pretty parameter list for this method def param_seq params = params.gsub(/\s*\#.*/, '') params = params.tr("\n", " ").squeeze(" ") params = "(#{params})" unless p[0] == ?( if block = block_params then # yes, = # If this method has explicit block parameters, remove any explicit # &block params.sub!(/,?\s*&\w+/) block.gsub!(/\s*\#.*/, '') block = block.tr("\n", " ").squeeze(" ") if block[0] == ?( block.sub!(/^\(/, '').sub!(/\)/, '') end params << " { |#{block}| ... }" end params end ## # Path to this method def path "#{@parent.path}##{@aref}" end ## # Method name with class/instance indicator def pretty_name "#{singleton ? '::' : '#'}#{@name}" end def to_s # :nodoc: "#{self.class.name}: #{full_name} (#{@text})\n#{@comment}" end ## # Type of method (class or instance) def type singleton ? 'class' : 'instance' end end
true
c9aca1302d981ff9296d7035c46cd9ab979f8346
Ruby
johnmartirano/speller_test
/lib/matcher.rb
UTF-8
5,849
3.328125
3
[]
no_license
# Matcher.match attempts to select best match for an input_word from # an array of possabilities. The algorithm used is an experiment # which attempts to determine the 'distance' between 2 words. # This algorithm would be useless on arbitrary word comparisons but given # the grouping of normalized words in NormHash, it may be better than # random selection class Matcher # The reverse of the repeating rule will apply in matching # eg mispelled 'shep' (input) could match to 'sheep' (target) even though # mispelled word rules will never permute 'sheep' (input) to 'shep' # If filtered out, it would prevent some bad choices such as # 'por' (input) matches 'porr' (target) instead of 'par' # But accepting it catches cases such as # 'shep' (input) matches 'sheep' (target) def self.match( input_word, word_list=[] ) if word_list.nil? return "NO SUGGESTION" elsif word_list.include? input_word return input_word else # word_list.sample the_match, distance = self.do_match( input_word, word_list ) if distance == 1 return "NO SUGGESTION" else return the_match end end end protected def self.do_match( input_word, word_list ) closest = ['',1.0] closest = word_list.reduce(closest) do |still_closest,target_word| dist = word_distance( input_word, target_word ) if dist <= still_closest[1] still_closest = [target_word, dist] end still_closest end closest end # word_distance attempts to score (0-1) how different 2 words are, # its an experiment which compares 2 words on char-position coincidence, # In the event one word is longer, it shifts the smaller word for # multiple comparisons and then performs a bitwise or on the results. # # Since case is ignored and repeats are removed (from the input_word only) # one edge-case that must be considered is when a vowel permutation # results in a repeat vowel which is then removed. # # Examples: target=>misspelling=>matcher_encoding # louse=>luuse=>luse appeal=>appeel=>apel # good listserv louse louse lose loose tool appeal appeal appeal appeal # bad lestsurv luse luse luse luse tiol apel apel apel # *x***x** *xxxx|xx*** *x**|*xx** *x** **xxxx|xxxxx*|xx**xx ****x* # # The code below is dynamic enough to handle any argument length, # (ie word length diff) but as an example, it is merely doing the following: # # # This example based on comparing 'apel' to 'appeal' as seen above # a = [true, true, false, false, false, false] # args = [[false, false, false, false, false, true], # [false, false, true, true, false, false]] # p=eval 'Proc.new{|x,y,z| x|y|z}' # distance_vector = a.zip(*args).collect(&p) # # => [true, true, true, true, false, true] # sum = distance_vector.reduce(0) {|sum,cur| sum += cur ? 1 : 0 } # 1 - sum/distance_vector.length.to_f # def self.word_distance( input_word, target_word) # use downcase and no_repeats because repeats are randomly errors anyway # and lack of repeats will not effect score because of shifting input_word = input_word.no_repeats.downcase target_word = target_word.downcase if input_word.length <= target_word.length short_word = input_word long_word = target_word else short_word = target_word long_word = input_word end # create arrays for comparison diff_arrays = create_diff_arrays(short_word, long_word) the_proc = bitwise_proc( diff_arrays.length+1 ) first_array = diff_arrays.shift distance_vector = first_array.zip(*diff_arrays).collect(&the_proc) sum = distance_vector.reduce(0) {|sum,cur| sum += cur ? 1 : 0 } 1 - sum/distance_vector.length.to_f end # Given two strings input_word and target_word, create_diff_arrays # creates 1 or more arrays representing the differences between these # 2 words. The number of arrays generated is # num_arrays = ABS(input_word.length-target_word.length) + 1 # # The shorter word is placed at position 0...num_arrays # and compared with the longer word. So: # pious pious OR appeal appeal appeal OR ann # pius pius apel apel apel enn # 11000 00011 110000 001100 000001 011 # def self.create_diff_arrays(input_word, target_word) length_diff = target_word.length - input_word.length word_diffs = [] (0..length_diff).each do |n| word_diffs << Array.new(target_word.length) word_diffs[n] = compare_words(target_word, ' '*n+input_word) end word_diffs end # Compares 2 words of equal length, returning an array # of booleans. Elements are true if word1[i]==word2[i] def self.compare_words( word1, word2 ) diff = [] (0...word1.length).each do |n| diff[n] = word1[n] == word2[n] end diff end # Return the bitwise proc with indicated number of arguments, # Create and store the proc if necessary. def self.bitwise_proc( arg_length ) @@proc_hash={} unless defined? @@proc_hash the_proc = @@proc_hash[arg_length] || @@proc_hash[arg_length] = make_bitwise_proc(arg_length) end # make_bitwise_proc generates a Proc with arbitrary number of arguments # which will peform a bitwise or on the arguments. # arg_length is the number of arguments to construct the Proc with. # This will produce Procs of the following form: # eval 'Proc.new{|a1,a2,a3| a1|a2|a3}' def self.make_bitwise_proc( arg_length ) proc_string = 'Proc.new{|a1' proc_bitwise_string = 'a1' (2..arg_length).each do |arg_num| proc_string += ',' + 'a' + arg_num.to_s proc_bitwise_string += '|' + 'a' + arg_num.to_s end proc_string += "| #{proc_bitwise_string} }" eval proc_string end end
true
5c22e9ca31c06c2cb4164d6d1f1e2d51eb03ee0c
Ruby
nitehawk/jekyll-frontadder
/lib/jekyll-frontadder.rb
UTF-8
1,491
3.265625
3
[ "MIT" ]
permissive
# This Jekyll Generator plugin looks for specified hashes in a post's front matter and adds them up. # The final result is stored into the site's data tree for use in layouts module Jekyll # Here's our work horse class class JekyllFrontAdderGen < Jekyll::Generator # Called by Jekyll to run our plugin def generate(site) # Pickup array of frontmatter things to add up frontadd = site.config["frontadder"] if frontadd.nil? Jekyll.logger.warn 'Frontadder: frontadder not defined in _config.yml, skipping' return end Jekyll.logger.debug 'Frontadder: Will add listed hashes: ', frontadd # Initialize hashes for each hash to add frontadd.each do |addme| site.config[addme] ||= {} end # For each post, loop through the list of hashes to add and do it. site.posts.docs.each do |post| Jekyll.logger.debug 'Processing: ', post.url frontadd.each do |addme| next unless post.data[addme].respond_to?(:merge) site.config[addme] = addhashes(site.config[addme], post.data[addme]) post.data[addme]['runtotal'] = site.config[addme] end end end private # This will add two hases together and return the result - recursive def addhashes(h1, h2) if h1.respond_to?(:merge) && h2.respond_to?(:merge) return h1.merge(h2) { |_key, old, new| addhashes(old, new) } else return h1 + h2 end end end end
true
a34990e2911857086f3770a37b0de639262df3f4
Ruby
MaximeKjaer/jekyll-block
/lib/jekyll-block/block_tag.rb
UTF-8
1,335
2.6875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require "jekyll" module Jekyll module Block # A Jekyll Liquid {% block %} block tag that generates HTML for block-styled content. # The content of the block can contain Markdown, which will be parsed by kramdown. # # Usage: # {% block <type> ["Title"] %} # *Markdown content* # {% endblock %} # # The type argument is mandatory, and the title is optional. class BlockTag < Liquid::Block def initialize(tag_name, text, tokens) @type, @title = text.match(%r!\s*(\w+)\s+(?:\"(.*)\".*)?!im).captures @id = @title ? @type.downcase + ":" + Jekyll::Utils.slugify(@title) : nil super end attr_reader :type, :title, :id def render(context) text = super if @title "<div class=\"block #{@type}\" id=\"#{@id}\" markdown=\"block\">"\ "<a class=\"header\" href=\"##{id}\">"\ "#{@type.capitalize}: #{@title}"\ "</a>"\ "\n#{text}\n"\ "</div>" else "<div class=\"block #{@type}\" markdown=\"block\">"\ "<span class=\"header\">#{@type.capitalize}</span>"\ "\n#{text}\n"\ "</div>" end end end end end Liquid::Template.register_tag("block", Jekyll::Block::BlockTag)
true
b66ccd1f43229ce1738cbacd24a9e591fe6b9ebe
Ruby
mitsukan/chitter-challenge
/lib/chitter.rb
UTF-8
492
2.734375
3
[]
no_license
require 'pg' ENV["DB"] = "chitter" class Chitter def self.all con = PG.connect :dbname => ENV["DB"] result = con.exec "SELECT * FROM chitters" result.map {|post| [post['name'], post['peep'], post['timestamp']]} end def self.create(params) con = PG.connect :dbname => ENV["DB"] time = (Time.now + (60*60)).strftime("%H:%M") con.exec_params "INSERT INTO CHITTERS(name, peep, timestamp) VALUES($1, $2, $3)", [params[:name], params[:peep], "#{time}"] end end
true
b187b2d4297427b4e4d610af0045e35c3ad49754
Ruby
ruannawe/hell-triangule
/spec/message_spec.rb
UTF-8
382
2.53125
3
[]
no_license
require './lib/execute' describe Execute do describe '#hell_triangle' do context 'when receive valid array' do let(:valid_array) { '[[6],[3,5],[9,7,1],[4,6,8,4]]' } let(:valid_response) { [6,5,7,8] } it 'has the prescribed elements in valid_response' do expect(Execute.hell_triangle(valid_array)).to eql(valid_response) end end end end
true
22a10589e99326c1b15e0a30b1ef7c3009aeb705
Ruby
michaelHartling/launchschool-Intro-to-Programming
/ch_04/method_num_position.rb
UTF-8
516
4.9375
5
[]
no_license
# write program that takes a number from a user b/w 1 - 100 and gives back its position in blocks of 0 - 50, 51 - 100, greater than 100 def position(num) if num < 0 puts "Number is less than zero. Try another number." elsif num > 100 puts "Your number is greater than 100." elsif num > 51 puts "Your number is between 51 and 100." else puts "Your number is between 0 and 50" end end puts "Enter a number beween 0 and 100 and let's see where it sits: " num = gets.chomp.to_i position(num)
true
5bde43eec13aefc24df89dc309975866c9b84e1f
Ruby
yehudamakarov/growing
/app/models/day.rb
UTF-8
434
2.6875
3
[ "MIT" ]
permissive
class Day < ActiveRecord::Base has_many :day_tasks has_many :tasks, through: :day_tasks def self.sunday Day.find_by_id(1) end def self.monday Day.find_by_id(2) end def self.tuesday Day.find_by_id(3) end def self.wednesday Day.find_by_id(4) end def self.thursday Day.find_by_id(5) end def self.friday Day.find_by_id(6) end def self.saturday Day.find_by_id(7) end end
true
39a31776b3f4fd977026a4b61b1ef9bfc9bc95b5
Ruby
evertrue/shinken-cookbook
/files/default/plugins/check_mesos_resource
UTF-8
1,425
2.546875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby require 'unirest' require 'optimist' module ShinkenPlugins class CheckMesosResource def run pm = portion_resource print("MESOS #{opts[:resource].upcase} ") if pm > opts[:threshold].to_f printf("CRITICAL: %.2f/1.00\n", pm) exit 1 end printf("OK: %.2f/1.00\n", pm) exit 0 end def used response['slaves'].map { |s| s['used_resources'][opts[:resource]] }.inject(:+).to_f end def total response['slaves'].map { |s| s['resources'][opts[:resource]] }.inject(:+).to_f end def portion_resource used / total end private def response @response ||= Unirest.get("http://#{opts[:hostname]}:#{opts[:port]}/master/state.json").body end def opts @opts ||= Optimist.options do opt :hostname, 'Mesos host to check', short: '-I', required: true, type: :string opt :threshold, 'Threshold above which to return an error', short: '-t', default: 0.8 opt :resource, 'Metric to check (e.g. cpus, mem)', short: '-m', required: true, type: :string opt :port, 'Mesos management port', short: '-p', default: '5050' end end end end ShinkenPlugins::CheckMesosResource.new.run
true
612dbbff1be89822f2071f4e33e110aa439b7bf7
Ruby
kapelner/learnopedia
/lib/parse_and_rewrite_tools.rb
UTF-8
6,780
2.53125
3
[]
no_license
module ParseAndRewriteTools #Things that should be deleted from all wikipedia pages: #1) The "[edit]" links def rewrite_links_to_wikipedia_or_learnopedia(page, options) #titles_to_id_hash = Page.all.inject({}){|hash, p| hash[p.title] = p.id; hash} pages = Page.all titles_to_id = Hash[pages.map{|p| p.wiki_name}.zip(pages.map{|p| p.id})] doc = Nokogiri::HTML(page.html) #Remove edit links doc.xpath("//span[@class='editsection']").each {|edit| edit.remove} #Point links to learnopedia if the articles are in our database point_wiki_links_to_the_right_place(doc, titles_to_id, options) doc end def point_wiki_links_to_the_right_place(doc, known_title_id_hash, options) wiki_link_start = "http://en.wikipedia.org" linkstart = "page" student_link = "student_view" contributor_link = "contributor_view" doc.xpath("//a").each do |link| if link.has_attribute? "href" link["target"] ="_blank" link_value = link.attributes["href"].value if link_value.start_with?("/wiki") wiki_name = link_value.split("/").last if known_title_id_hash[wiki_name] link_value = %Q{/#{linkstart}/#{options[:contributor] ? contributor_link : student_link}?id=#{known_title_id_hash[wiki_name]}} else link_value = wiki_link_start + link_value end end link.attributes["href"].value = link_value end end end attr_accessor :num_tags_thus_far def add_bundle_element_tags(page, doc_with_rewritten_links, options={}) #first get the html and get just the relevant part of the body root_where_content_first_appears = doc_with_rewritten_links.xpath("//div[@id='mw-content-text']").first #set the counter @num_tags_thus_far = 0 #now start the recursion process tag_all_words_with_cb_tag(page, root_where_content_first_appears, doc_with_rewritten_links, options) add_cb_window_to_each_cb_html_block(page, doc_with_rewritten_links) #since we modified the nokogiri doc, all we have to do is send back the new one doc_with_rewritten_links end TagsThatAreNotAddableToCBs = %w(h1 h2 h3 h4 h5 table tbody td tr th html pre) TagsThatConstituteBundle = %w(text img sup sub a comment i b u code span) def node_is_bundleable?(node) #if node is bundleable, all its children have names that are in that array node.children.each do |child| return false unless child.name.in?(TagsThatConstituteBundle) end #if node is bundleable, then its tag must be addable return false if node.name.in?(TagsThatAreNotAddableToCBs) # puts "\n\n dl or dd text: blank? #{node.text.strip.blank?} #{node.to_s}" if node.name.in?(%w(dl dd)) #if node is empty, ie there's a bunch of whitespace, return false as well return false if node.text.strip.blank? and !node.name.in?(%w(dd dl img)) true end def tag_all_words_with_cb_tag(page, node, doc, options) if node_is_bundleable?(node) #iterate over children and make a node set for each child new_children_as_node_array = node.children.map do |ch| create_cb_tags_for_bundleable_node(page, ch, doc, options) end.flatten #now set this nodeset equal to the bundleable node's children node.children = Nokogiri::XML::NodeSet.new(doc, new_children_as_node_array) elsif !node.name.in?(TagsThatAreNotAddableToCBs) #just recurse to the point where the node is bundleable... node.children.each do |ch| tag_all_words_with_cb_tag(page, ch, doc, options) end end end def create_cb_tags_for_bundleable_node(page, node, doc, options) if node.text? text_cb_tags = node.text.split(/\s/).map{|text_bundle| create_cb_tag_node_from_text(page, text_bundle, doc, options)} text_cb_tags.map{|node| [node, Nokogiri::XML::Text.new("\n", doc)]}.flatten else create_cb_tag_node_from_text(page, node.to_s, doc, options) end end ActiveBundleClass = "learnopedia_bundle_element_active" InActiveBundleClass = "learnopedia_bundle_element_inactive" def create_cb_tag_node_from_text(page, text, doc, options) cb_tag = Nokogiri::XML::Node.new('span', doc) cb_tag['class'] = "#{InActiveBundleClass}" cb_tag['cb_id'] = "#{@num_tags_thus_far}" cb_tag.inner_html = text #if it's part of a concept bundle already, we need to mark it so and give it an ordinal number page.concept_bundles_in_text_order.each_with_index do |cb, i| if cb.bundle_elements_hash[@num_tags_thus_far] cb_tag['class'] = "#{ActiveBundleClass} #{ActiveBundleClass}_#{i + 1}" cb_tag['cb_active_tag_num'] = (i + 1).to_s #casting??? are you kidding? cb_tag['real_cb_id'] = cb.id.to_s #casting??? are you kidding? end end # puts "TAG ##{@num_tags_thus_far} cb_tag class: #{cb_tag.class} text: #{text}" @num_tags_thus_far += 1 cb_tag end ProblemAndVideoWindowClass = "problem_and_video_window" def add_cb_window_to_each_cb_html_block(page, doc) #first find all concept bundle tags page.concept_bundles_in_text_order.each_with_index do |cb, i| #first create the div tag itself pvw_wrap_tag = Nokogiri::XML::Node.new('span', doc) pvw_wrap_tag['id'] = "#{ProblemAndVideoWindowClass}_#{i + 1}" pvw_wrap_tag['real_cb_id'] = cb.id.to_s #then get the tags all_cb_tags = doc.xpath("//span[contains(@class, '#{ActiveBundleClass}_#{i + 1}')]") #now add the div at the end of the last span all_cb_tags.last.add_next_sibling(pvw_wrap_tag) end end TagsThatCannotBeHidden = %w(html body) def hide_page_except_for_cb(cb, doc) #first hide absolutely everything except the essentials doc.xpath("//*").each do |html_tag| next if html_tag.name.in?(TagsThatCannotBeHidden) html_tag['style'] = 'display:none' end #now unhide all concept bundle tags (doc.xpath("//span[contains(@class, '#{ActiveBundleClass}')]") + doc.xpath("//span[@class='#{InActiveBundleClass}']")).each do |cb_tag| #kill the active tag that makes it a color first cb_tag['class'] = ActiveBundleClass #if this tag IS part of the cb of interest, make it AND its parents appear if cb.bundle_elements_hash[cb_tag['cb_id'].to_i] make_tag_and_all_parents_appear(cb_tag) make_tag_and_all_children_appear(cb_tag) end end doc end def make_tag_and_all_parents_appear(tag) tag['style'] = '' if tag.name != "document" and tag.parent.present? make_tag_and_all_parents_appear(tag.parent) end end def make_tag_and_all_children_appear(tag) tag['style'] = '' tag.children.each{|ch| make_tag_and_all_children_appear(ch)} end end
true
dfcca4cb227ffaeb617eaf189c564f0fd4e856f5
Ruby
ATXkatrina/phase-0-tracks
/ruby/iteration.rb
UTF-8
636
4
4
[]
no_license
def test puts "This is a test" yield puts "This is a second message" end test {puts "This is a block message"} breakfast_foods = ["tacos", "eggs", "pancakes"] breakfast_drinks = { milk: "white", oj: "orange", coffee: "brown" } breakfast_foods.each do |list| p list end breakfast_drinks.each do |other_list| p other_list end breakfast_foods.map! do |list_three| puts list_three list_three.upcase end p breakfast_foods numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] p numbers.delete_if{|num| num % 2 == 0} p numbers.drop_while{|num| num < 4} p numbers.select {|num| num >= 9} p numbers.take_while{|num| num < 8}
true
a7f27d496fb2323fd5a8f1080daf892ecfc81c1d
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/hamming/a3c7b6febd3540b49886371fd4aecb1d.rb
UTF-8
391
3.609375
4
[]
no_license
class Hamming def self.compute(strand1, strand2) strand_length = strand1.length difference = 0 (0..strand_length-1).each do |i| # use ruby style each instead of traditional for loop if strand1[i] != strand2[i] # strand1[i] is the same as strand1[i,1] difference += 1 end end difference # same as return difference end end
true
27586707d9d2718b5a5323e17bc566b92cd58847
Ruby
QPC-WORLDWIDE/ruby-ode
/tests/world.tests.rb
UTF-8
2,444
2.8125
3
[ "CC-BY-4.0", "CC-BY-1.0" ]
permissive
#!/usr/bin/ruby $LOAD_PATH.unshift File::dirname(__FILE__) require "odeunittest" class World_test < ODE::TestCase def setup @world = ODE::World.new end def teardown @world = nil end def test_00_new assert_instance_of( ODE::World, @world ) end def test_01_gravity_get gravity = nil assert_nothing_raised { gravity = @world.gravity } assert_instance_of( ODE::Vector, gravity ) assert_in_delta( gravity.x, 0.0, 0.01 ) assert_in_delta( gravity.y, 0.0, 0.01 ) assert_in_delta( gravity.z, 0.0, 0.01 ) end def test_02_gravity_set assert_nothing_raised { @world.gravity = [1.0,1.0,1.0] } assert_in_delta( @world.gravity.x, 1.0, 0.001 ) assert_in_delta( @world.gravity.y, 1.0, 0.001 ) assert_in_delta( @world.gravity.z, 1.0, 0.001 ) assert_nothing_raised { @world.gravity = [1,1,1] } assert_in_delta( @world.gravity.x, 1.0, 0.001 ) assert_in_delta( @world.gravity.y, 1.0, 0.001 ) assert_in_delta( @world.gravity.z, 1.0, 0.001 ) assert_nothing_raised { @world.gravity = [-0.2,-1.0,4.0] } assert_in_delta( @world.gravity.x, -0.2, 0.001 ) assert_in_delta( @world.gravity.y, -1.0, 0.001 ) assert_in_delta( @world.gravity.z, 4.0, 0.001 ) assert_nothing_raised { @world.gravity = 0,1,2 } assert_in_delta( @world.gravity.x, 0.0, 0.001 ) assert_in_delta( @world.gravity.y, 1.0, 0.001 ) assert_in_delta( @world.gravity.z, 2.0, 0.001 ) assert_raises( ArgumentError ) { @world.gravity = 0,1 } assert_raises( TypeError ) { @world.gravity = {'x' => 1} } assert_raises( TypeError ) { @world.gravity = "none" } end def test_03_erp_get erp = nil assert_nothing_raised { erp = @world.erp } assert_in_delta( @world.erp, 0.2, 0.001 ) end def test_04_erp_set assert_nothing_raised { @world.erp = 0.15 } assert_in_delta( @world.erp, 0.15, 0.001 ) assert_raises( TypeError ) { @world.erp = {'x' => 1} } assert_raises( TypeError ) { @world.erp = "none" } end def test_05_cfm_get cfm = nil assert_nothing_raised { cfm = @world.cfm } assert_in_delta( @world.cfm, 1e-10, 1e-10 ) end def test_06_cfm_set assert_nothing_raised { @world.cfm = 1e-5 } assert_in_delta( @world.cfm, 1e-5, 1e-10 ) assert_raises( TypeError ) { @world.cfm = {'x' => 1} } assert_raises( TypeError ) { @world.cfm = "none" } end def test_07_step assert_nothing_raised { @world.step(0.05) } assert_raises( TypeError ) { @world.step("one") } end end
true
e15820dfd658f1ee20ff08dd83d1cbeb39a7a71e
Ruby
supun/RosettaCodeData
/Task/Sorting-algorithms-Selection-sort/Ruby/sorting-algorithms-selection-sort.rb
UTF-8
399
3.78125
4
[]
no_license
class Array def selectionsort! 0.upto(length - 2) do |i| (min_idx = i + 1).upto(length - 1) do |j| if self[j] < self[min_idx] min_idx = j end end if self[i] > self[min_idx] self[i], self[min_idx] = self[min_idx], self[i] end end self end end ary = [7,6,5,9,8,4,3,1,2,0] ary.selectionsort! # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
true
b16a3d64f96f6cce45e4096601921ff581a2289c
Ruby
georgian-se/pathfinder
/app/controllers/api/shortestpath_controller.rb
UTF-8
3,982
2.59375
3
[]
no_license
# -*- encoding : utf-8 -*- class Api::ShortestpathController < ApiController def index origins = ( if params[:from] and params[:to] from = params[:from].split(':').map{ |x| x.to_f } to = params[:to].split(':').map{ |x| x.to_f } [ from, to ] else params[:ids].map{|x| a=x.split('/'); a[0].constantize.find(a[1]).location } end ) closest_points = origins.map{|x| Objects::Path::Point.geo_near(x).spherical.first } dist = heur = ->(p1,p2){ distance_between(p1,p2) } if closest_points.length > 1 p1 = p2 = closest_points[0] graph = build_graph(closest_points) @responses = [] (1..closest_points.length-1).each do |idx| p2 = closest_points[idx] path = Shortest::Path.astar(dist, heur, graph, p1, p2) @responses << extract_path(path) p1 = p2 end else render json: { path: 'empty' } end end private def build_graph(points) graph = get_current_graph points_by_path = points.group_by { |point| point.pathline_ids.first } points_by_path.each do |line_id, split_by| line = Objects::Path::Line.find(line_id) point_ids = line.point_ids remove_graph_edge(graph, point_ids.first, point_ids.last) split_by = split_by.map{|x| x.id }.sort_by{ |id| point_ids.index(id) } i1, p1 = [ 0, point_ids.first ] split_by.each do |point_id| p2 = point_id ; i2 = point_ids.index(point_id) add_graph_edge(graph, p1, p2, line_length(line, i1, i2)) i1, p1 = [ i2, p2 ] end i2, p2 = [ point_ids.length - 1, point_ids.last ] add_graph_edge(graph, p1, p2, line_length(line, i1, i2)) end graph end def get_current_graph # check graph caching build_graph = ( $__graph.blank? || ($__graph_date < Objects::Path::Point.first.created_at) ) # re-create graph, if necessary if build_graph $__graph = build_default_graph $__graph_date = Time.now end # prepare search graph graph = $__graph.clone graph.edges = $__graph.edges.clone graph end def build_default_graph graph = Shortest::Path::Graph.new Objects::Path::Line.each do |line| point_ids = line.point_ids p1 = point_ids.first ; p2 = point_ids.last add_graph_edge(graph, p1, p2, line.length) end graph end def add_graph_edge(graph, p1, p2, length) point1 = Objects::Path::Point.find(p1) point2 = Objects::Path::Point.find(p2) graph << point1 unless graph.include?(point1) graph << point2 unless graph.include?(point2) graph.connect_mutually(point1, point2, length) end def remove_graph_edge(graph, p1, p2) point1 = Objects::Path::Point.find(p1) point2 = Objects::Path::Point.find(p2) graph.remove_edge(point1, point2) end def line_length(line, i1, i2) len = 0 ; points = line.points.to_a (i1 + 1 .. i2).each do |idx| p1 = points[idx-1] ; p2=points[idx] a1 = Geokit::LatLng.new(p1.lat, p1.lng) a2 = Geokit::LatLng.new(p2.lat, p2.lng) len += a1.distance_to(a2) end len end def extract_path(points) p1 = p2 = points[0] new_points=[] length=0 (1..points.length-1).each do |idx| p2 = points[idx] line=Objects::Path::Line.all(point_ids: [p1.id, p2.id]).first i1=line.point_ids.index(p1.id) ; i2=line.point_ids.index(p2.id) if i1 < i2 (i1..i2).each do |i| new_points << Objects::Path::Point.find(line.point_ids[i]) end else ary=[] (i2..i1).each do |i| ary << Objects::Path::Point.find(line.point_ids[i]) end ary.reverse.each do |p| new_points << p end end length += distance_between(p1, p2) p1 = p2 end {points: new_points, length: length} end def distance_between(p1,p2) a1 = Geokit::LatLng.new(p1.lat, p1.lng) a2 = Geokit::LatLng.new(p2.lat, p2.lng) a1.distance_to(a2) end end
true
7fa7d8de32c7d16519282eebbb9ac38536612870
Ruby
sunrick/kolla
/lib/kolla/display.rb
UTF-8
1,631
2.953125
3
[ "MIT" ]
permissive
module Kolla class Display attr_accessor :options, :output, :tab_size, :tab_character, :indent_count def initialize(opts = {}) self.options = Utils.merge(opts, Kolla.config.default_options) self.output = options[:display][:output] self.tab_size = options[:display][:tab_size] self.tab_character = options[:display][:tab_character] self.indent_count = 0 end def self.start(&block) if block.arity == 0 new.instance_eval(&block) else yield(new) end end def tab tab_character * tab_size end def indentation tab * indent_count end def line(value) output.puts("#{indentation}#{value}") end def empty_line output.puts end def hide_cursor output.print("\x1b[?25l") end def show_cursor output.print("\x1b[?25h") end def spinner(overrides = {}, &block) overrides = options[:spinner].merge({ before_animation: indentation }).merge( overrides ) Spinner.start(overrides, &block) end def progress(overrides = {}, &block) overrides[:title] = "#{indentation}#{overrides[:title]}" overrides = options[:progress].merge(display: self).merge(overrides) Progress.start(overrides, &block) end def table(overrides = {}, &block) overrides = options[:table].merge(overrides) Table.new(overrides, &block).to_s.split("\n").map { |l| line(l) } end def indent(times = 1, &block) self.indent_count += 1 * times yield self.indent_count -= 1 * times end end end
true
5ce0b02a632546d13565d291013e1725ed18d11c
Ruby
ffwu2001/ttt-8-turn-ruby-intro-000
/lib/turn.rb
UTF-8
1,067
4.1875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def display_board( board ) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end def input_to_index( input ) input = input.to_i input = input - 1 end def move( board, index, char = "X") board[index] = char end def position_taken?( board, index ) if board[index] == " " || board[index] == "" || board[index] == nil return false end if board[index] == "X" || board[index] == "O" return true end end def valid_move?( board, index ) if index < 0 || index > 8 return false end if position_taken?( board, index ) return false else position_taken?( board, index ) == false return true end end def turn( board ) puts "Please enter 1-9:" index = input_to_index( gets.strip ) if valid_move?( board, index ) == true move( board, index, "X" ) display_board( board ) elsif valid_move?( board, index ) == false display_board( board ) turn( board ) end end
true
0a53a396cc1598561d5bc8fa315eda86006642f3
Ruby
dan-vernon/cookbook-sinatra
/lib/cookbook.rb
UTF-8
886
3.421875
3
[]
no_license
require 'csv' require_relative 'recipe' require 'pry-byebug' class Cookbook attr_reader :recipes def initialize(csv_file_path) @csv = csv_file_path @recipes = [] load_csv end def load_csv CSV.foreach(@csv) do |row| @recipes << Recipe.new(row[0], row[1]) end end def all @recipes end def add_recipe(recipe) # add each recipe instance to @recipes array of instances @recipes << recipe save_csv # iterate over each recipe instance and add it to the CSV end def save_csv csv_options = { col_sep: ',', force_quotes: true, quote_char: '"' } CSV.open(@csv, "wb", csv_options) do |csv| @recipes.each do |recipe| # binding.pry csv << [recipe.name.to_s, recipe.description] end end end def remove_recipe(recipe_index) @recipes.delete_at(recipe_index) save_csv end end
true
e445729023eb6c4612799879e978d9f8ede70952
Ruby
kikihakiem/word_game
/spec/word_game_spec.rb
UTF-8
1,415
2.875
3
[]
no_license
require 'minitest/autorun' require_relative 'spec_helper' require_relative '../lib/word_game' describe WordGame do let(:level1_words) { %w(buku roti motor) } let(:level2_words) { %w(kualifikasi termometer transnasional) } let(:attempts) { %w(buuk buku roti) } let(:input) { BogusInput.new(attempts) } let(:all_words) { [BogusWordCollection.new(level1_words), BogusWordCollection.new(level2_words)] } let(:word_game) { WordGame.new(all_words, input) } describe '#play' do subject { word_game.play } describe 'when player get wrong answers on all 3 attempts' do let(:attempts) { %w(foo bar baz) } it 'returns 0' do subject.must_equal 0 end end describe 'when player get 2 correct answers & 1 wrong answer' do it 'returns 2' do subject.must_equal 2 end it 'does not increment level' do subject word_game.level.must_equal 0 end end describe 'when player get correct answers on all 4 attempts' do let(:attempts) { [*level1_words, 'kualifikasi'] } it 'returns 4' do subject.must_equal 4 end it 'increments level' do subject word_game.level.must_equal 1 end end end end
true
ac109970f0da52e843d703e8004acff807905fdc
Ruby
prashantmukhopadhyay/CatRentalRequest
/db/seeds.rb
UTF-8
489
2.546875
3
[]
no_license
cat1 = Cat.new({ name: "Whiskers", age: "3", color: "Yellow", sex: "M", birthday: "09/08/2010" }).save! cat2 = Cat.new({ name: "Carlos", age: "7", color: "Black", sex: "M", birthday: "09/08/2006" }).save! request1 = CatRentalRequest.new({ cat_id: 1, start_date: "11/11/2013", end_date: "27/11/2013", status: "PENDING" }).save! request2 = CatRentalRequest.new({ cat_id: 1, start_date: "15/11/2013", end_date: "29/11/2013", status: "PENDING" }).save!
true
2c50d665e4c6d69e92851df5d975d11d387eb48a
Ruby
blinded93/oo-cash-register-v-000
/lib/cash_register.rb
UTF-8
777
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class CashRegister attr_accessor :total, :discount, :items, :price, :last_item def initialize(discount=0) @total = 0 @discount = discount @items = [] @last_item = {cost: nil, amount: nil} end def apply_discount self.total = self.total*(100 - self.discount)*0.01 if self.discount == 0 "There is no discount to apply." else "After the discount, the total comes to $#{@total.to_i}." end end def add_item(title, price, quantity=1) self.last_item[:cost] = price*quantity self.total += self.last_item[:cost] self.last_item[:amount] = [title] * quantity self.items += self.last_item[:amount] end def void_last_transaction self.total = self.total - self.last_item[:cost] end end
true
82bd240ea41b49777bf2fe3fa9b5f71532ab3bd9
Ruby
Alixdb/Alixdb
/reboot/scraping.rb
UTF-8
1,295
3.421875
3
[]
no_license
# on scrap l'url : https://www.etsy.com/fr/search?q=elephants # Card => .v2-listing-card_info # => .text-body (name) # => .currency-value require 'open-uri' require 'nokogiri' # puts "quel catégorie t'intéresse" # ouvrir l'url pour récupérer le fichier html # file = open(url) # html_text = file.read # doc = Nokogiri::HTML(html_text) # Une fois qu'on un doc nokogiri # search(selector) renvoie un tableau d'élément qui ont la class # on peut ) nouveau chercher dans ces éléments # une fois qu'on accède à l'élément, 2 méthodes utiles # .text pour le contenu de la balise # ["href"] ["src"] pour récupérer la valeur d'un attribu # methode search prend en entrée la classe # doc.search('.v2-listing-card_info').each do |element| # p element.search('.text-body')[0].text.strip # p element.search('.currency-value')[0].text. # p element.search('.text-body')[0]["src"] # end def etsy_scraping(category) # construire et retourner le tableau de résultats result = [] url = "https://www.etsy.com/search?q=#{category}" file = open(url) html_text = file.read doc = Nokogiri::HTML(html_text) doc.search('.v2-listing-card_info').each do |element| result << element.search('.text-body')[0].text.strip end return result end
true
f28da539c2bc0c5131e9b4f434f874e0bb0936fe
Ruby
waleo/gauguin
/lib/gauguin/image.rb
UTF-8
1,221
2.90625
3
[ "MIT" ]
permissive
require 'rmagick' require 'forwardable' module Gauguin class Image extend Forwardable attr_accessor :image delegate [:color_histogram, :columns, :rows, :write] => :image def initialize(path = nil) return unless path list = Magick::ImageList.new(path) self.image = list.first end def self.blank(columns, rows) blank_image = Image.new transparent_white = Magick::Pixel.new(255, 255, 255, Pixel::MAX_TRANSPARENCY) blank_image.image = Magick::Image.new(columns, rows) do self.background_color = transparent_white end blank_image end def pixel(magic_pixel) Pixel.new(magic_pixel) end def pixel_color(row, column, *args) magic_pixel = self.image.pixel_color(row, column, *args) pixel(magic_pixel) end class Pixel MAX_CHANNEL_VALUE = 257 MAX_TRANSPARENCY = 65535 def initialize(magic_pixel) @magic_pixel = magic_pixel end def transparent? @magic_pixel.opacity >= MAX_TRANSPARENCY end def to_rgb [:red, :green, :blue].map do |color| @magic_pixel.send(color) / MAX_CHANNEL_VALUE end end end end end
true
3a902e664100098b6f3afe81b03c8bda0438e08a
Ruby
lawsonhung/Perfect-Desserts-Backend
/app/controllers/auth_controller.rb
UTF-8
13,261
3.234375
3
[]
no_license
class AuthController < ApplicationController # Make sure to uncomment 'bcrypt' gem in Gemfile # $$$$$$$$$$$$$$$$$$$$$$$$$$$$ Terminal/Command Line notes # Opens up the rails console # $ rails c # Creates a user with username:"kev" and password:"buffaloboy" # > User.create(username:"kev", password:"buffaloboy") # Test to see if user has been created successfully # > User.all # > User.first # Fine the user with the username:kev # > User.find_by(username:"kev") # => User Load (2.6ms) SELECT "users".* FROM "users" WHERE "users"."username" = $1 LIMIT $2 [["username", "kev"], ["LIMIT", 1]] # => #<User id: 1, username: "kev", password_digest: [FILTERED], created_at: "2020-02-26 23:14:51", updated_at: "2020-02-26 23:14:51"> # `_` underscore is just a shortcut for whatever was entered in console before. In this case, _ === User.find_by(username:"kev") # Then we set that to a variable name `kev` # > kev = _ # `.authenticate` method is basically an app telling you to "please enter your password here". It is where you enter your raw password to log the user in. It's like telling the user: # What's your username? kev # What's your password? buffaloboy # Authenticate is essentially the same thing as telling you to enter your password # > kev.authenticate("buffaloboy") # config/routes.rb `auth#login` will refer/point to this method def login # Find a user # `debugger` activates byebug in Rails APIs # ```debugger # Check to see what is in params # > params # We get the following because nothing is in params # => <ActionController::Parameters {"controller"=>"auth", "action"=>"login"} permitted: false> # `c` in byebug continues onto the next line. Make sure it's lowercase # > c ########### Postman start # POST request to localhost:3000/login # "Body" tab in "raw" "JSON" format # JSON only takes things in strings, so you have to put "" around username as well # { # "username": "kev" # } ########### Postman end # Send in Postman again to hit debugger in terminal # > params # Now we have a "username"=>"kev" because we sent that in the body request in Postman # <ActionController::Parameters {"username"=>"kev", "controller"=>"auth", "action"=>"login", "auth"=>{"username"=>"kev"}} permitted: false> # params[:username] is a key that returns "kev". Sort of like JSON format, hash map or dictionary # :username is a key in params (ActionController::Parameters) # params[:username] === "kev" # > params[:username] # => "kev" # User.find_by(username:params[:username]) === User.find_by(username:"kev") # > User.find_by(username:params[:username]) # => #<User id: 1, username: "kev", password_digest: [FILTERED], created_at: "2020-02-26 23:14:51", updated_at: "2020-02-26 23:14:51"> # Assign the variable `user` = `User.find_by(username: params[:username])` user = User.find_by(username: params[:username]) # If user exists, see if they really are the user via a password. AKA use `.authenticate()` to get them enter their password # The parameter to pass in is params[:password]. :password is a key within params. We'll pass this in the body request in Postman (below) ########## Postman start # { # "username": "kev", # "password": "buffaloboy" # } ########## Postman end # Send request in Postman and hit debugger # > params[:password] # => "buffaloboy" # > is_authenticated returns the User object if true. Else, if :password is wrong, is_authenticated returns false is_authenticated = user.authenticate(params[:password]) # If all is well, send back the user. That is, if `.authenticate()` is passed in the correct password parameter, then return back the user. # If `is_authenticated` returns true, meaning `user.authenticate(params[:password])` is true and `:password` is the correct password for the user, `is_authenticated` returns true # ```debugger if is_authenticated # API's are json in, json out # `render json` sends json out of the rails app # If is_authenticated is true and the user types in the correct password, return the user in json format # ```render json: user ############ Jumped up from Note1 # Now if the user is_authenticated, meaning they typed in the correct password and username, instead of returning the user, we want to return the token insead. # JWT.encode syntax: JWT.encode(<payload created/defined by us>, <secret>, <encryption method/algorithm we're using to encode>) # Assign that to a variable `token` # The secret is a server secret, which allows access to everyone on your app. Basically, a secret is a password for your app. It's like a password for the developer the encrypt stuff and log in to the app, with admin privileges # The only user-specific information is the payload. AKA the user_id and anything else specific only to the user # ```token = JWT.encode(payload, 'badbreathbuffalo', 'HS256') # However, we have not yet defined what payload is in this auth_controller, so doing that now # user was defined earlier, approx line 64, which is why user.id works and we can get the id of the user # We make a hash with the key of user_id and set that equal to user.id # Refactoring to put code in app/controllers/application_controller.rb to keep things DRY # ```payload = { user_id: user.id } # Refactoring code into app/controllers/application_controller.rb to keep things DRY # ```token = JWT.encode(payload, 'badbreathbuffalo', 'HS256') # Instead of returning the user, I want to return a JWT token instead # Create an object called token and assign it to token defined above # ```render json: { token: token } # Refactoring to use code in app/controllers/application_controller.rb so that it's DRY render json: { token: create_token(user.id) } # Test in Postman to make sure refactoring is okay ########### Postman Request Start # POST request to 'localhost:3000/login' # "Authorization" tab Type: "No Auth" # "Body" tab "raw" option # { # "username": "annie12", # "password": "ruby" # } # SEND ########### Postman Request End # Send a Post request in Postman and you should get back the token object as a response # A token is like a bracelet you get for entering a club. As long as you have the bracelet, you're able to enter the club. # A token is also like a membership card. Just show your membership card to prove that you are a member at the store. # Now we have to save this token in localStorage # In browser console: # Create a key `token` and assign it the value "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.lYHuRcAN30C20HHWkE28A1XyeORMzrLa6Bt1hfymATE" # > localStorage.token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.lYHuRcAN30C20HHWkE28A1XyeORMzrLa6Bt1hfymATE" # The only part of the token that contains user information is the payload. # We want to send this token back to the server to decode it so that we can identify the user # JWT.encode syntax: JWT.encode(<payload created/defined by us>, <secret>, <encryption method/algorithm we're using to encode>) # The only things that are hardcoded are the secret (parameter2) and the algorithm used to encode (parameter3) ######### Jump back down to line 217 to continue notes. Note2 else # Else return the message that the user entered the wrong password # ```render json: 'You entered the wrong username or password. Or you may not be real and just a bot trying to hack into the system... sorry' # A more standard thing to return is an error. Or rather an array of errors. # You can also return statuses. Google the "http code" to learn more about each status error # By putting the status outside of the object, you'll get a status 422 Unprocessable Entity in Postment, in the return section of the request render json: {errors: ['You entered the wrong username or password. Or you may not be real and just a bot trying to hack into the system... sorry']}, status: 422 end # API's are json in, json out # `render json` sends json out of the rails app # ```render json: 'hi' ############### LocalStorage # Browser - Console and Application tabs # localStorage stores data locally, meaning just your computer/machine # Store id and data in localStorage. Check Console > Application tab # In console: # Check what's in localStorage # > localStorage # Clear localStorage # > localStorage.clear() # Store stuff into localStorage # > localStorage.setItem('userId', 1) # To get stuff from localStorage # > localStorage.getItem('userId') # => "1" # Anything you store in localStorage automatically turns into a string. AKA everything is json.stringify()'ed # You can also do localStorage.userId # > localStorage.userId # => "1" # Or you can reassign localStorage.userId # > localStorage.userId = 0 # => 0 # You can also add new keys into localStorage # > localStorage.thisIsANewKey = "newKey" # => "newKey" # To remove items from localStorage # > localStorage.removeItem("thisIsANewKey") # => undefined # However, since you can simply reassign the value of localStorage.userId, this is not safe and easy to hack as someone can easily reassign localStorage.userId = 2 or any other Id they want ############### JWT # To prevent against this, we use Javascript Web Tokens (JWT) # Go to https://jwt.io/ # In the decoded JWT, change the payload(body) to: ########## Payload start # { # "userId": 1 # } ########## Payload end # In the signature, we can enter whatever secret we want. In this case, our secret will just be 'badbreathbuffalo' # Scroll down the jwt.io webpage until you find the Ruby signatures. # Look for something that says `$ gem install jwt` # If we Google "jwt rails", the first link we get is https://github.com/jwt/ruby-jwt # Click on that link and scroll down the ReadMe until you hit the "Using Bundler" section # It'll instruct you to add `gem 'jwt'` to your Gemfile, so go ahead and do that # Take down your server and run `bundle install` as instructed in the ReadMe # This will install the `gem 'jwt'` that you just added to the Gemfile # Start the server again with `$ rails s` # Add debugger above line 82, `if is_authenticated` # Refer back to the docs https://github.com/jwt/ruby-jwt under Algorithms & Usage > None # Make a post request in Postman to hit debugger # > user # => #<User id: 1, username: "kev", password_digest: [FILTERED], created_at: "2020-02-26 23:14:51", updated_at: "2020-02-26 23:14:51"> # > user.id # => 1 # Create an object/hash `{ user_id: user.id }` and save it to the variable `payload` # > payload = { user_id: user.id } # => {:user_id=>1} # Test to see if payload hash/object was properly created # > payload # => {:user_id=>1} # Call encode as a method on JWT with the payload data # Reference https://github.com/jwt/ruby-jwt to see where the following code for console comes from # > JWT.encode(payload, nul, 'none') # => "eyJhbGciOiJub25lIn0.eyJ1c2VyX2lkIjoxfQ." # Copy and paste eyJhbGciOiJub25lIn0.eyJ1c2VyX2lkIjoxfQ. into https://jwt.io/ encoded section and you'll see the decoded payload. You should see: ########### Postman Start # Header: "alg: none" # Payload: "user_id": 1 # Take out the Verify signature so that there is no secret. You'll get an "Invalid Signature" error because there is no secret entered. # Verify Signature: <no-secret> ########### Postman End # However, since there is no secret, this is not secure because attackers can just decode the encoded section ############# JWT.encode syntax: JWT.encode(<payload hash/object that we create>, <secret goes here>, <algorithm that we want to use to encode>) # The standard algorithm to use is HMAC (reference https://github.com/jwt/ruby-jwt) so we're going to use that. We're going with the HS256 - HMAC using SHA-256 hash algorithm # So back in the Rails console: # > JWT.encode(payload, 'badbreathbuffalo', 'HS256') # => "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.lYHuRcAN30C20HHWkE28A1XyeORMzrLa6Bt1hfymATE" # eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.lYHuRcAN30C20HHWkE28A1XyeORMzrLa6Bt1hfymATE is called the token, or Javascript Web Token (JWT) # Copy and paste eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.lYHuRcAN30C20HHWkE28A1XyeORMzrLa6Bt1hfymATE into https://jwt.io/ # In Decoded > Verify Signature, the secret should currently be empty, which is why you still see the "Invalid Signature" error message under encoded # Since the secret is empty, "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxfQ.lYHuRcAN30C20HHWkE28A1XyeORMzrLa6Bt1hfymATE" cannnot be decoded until given the secret # Enter 'badbreathbuffalo' into the Decoded section to decode the encoded JWT ############### Go back up to approx line 89: token = JWT.encode(payload, 'badbreathbuffalo', 'HS256'). Note1 ################### Note2 continued here # Make a UserController and make a custom route '/profile' # In terminal: # Turn off the server # control+c # Generate Users controller # $ rails g controller Users # Start server # $ rails s # Go to app/controllers/users_controller.rb to check that users_controller.rb was properly created # Go to config/routes.rb to create a custom route '/profile' end end
true
fda70329bfa2b0221c7e1be53cffdeec81907b8a
Ruby
jmay/pipeline
/mod/format.rb
UTF-8
1,049
2.890625
3
[]
no_license
#!/usr/bin/env ruby # Reformat the contents of columns in an NSF file def reformat(string, format) case format when "MM/YYYY" val = string.to_i sprintf("%02d/%4d", val % 12 + 1, val / 12) when /.*%.*f.*/ sprintf(format, string.to_f).gsub(/(\d)(?=\d{3}+(\.\d*)?[^0-9]*$)/, '\1,') when /.*%.*d.*/ sprintf(format, string.to_i).gsub(/(\d)(?=\d{3}+(\.\d*)?[^0-9]*$)/, '\1,') else string end end require "fastercsv" require "getoptlong" opts = GetoptLong.new( [ '--format', GetoptLong::REQUIRED_ARGUMENT ], [ '--column', GetoptLong::REQUIRED_ARGUMENT ] ) formatting = nil formats = [] begin opts.each do |opt, arg| case opt when '--format' output_format = arg when '--column' formatting = arg.split(/\s*,\s*/) end end rescue puts "BAD OPTIONS" exit 1 end formatting.each do |entry| colnum, fmt = entry.split(/:/) formats[colnum.to_i] = fmt end FasterCSV.filter(:col_sep => "\t") do |row| formats.each_with_index do |fmt, i| row[i] = reformat(row[i], fmt) end end
true
f9f53d75909db3d67223855e00bf4f66a469003d
Ruby
lavikoder/oo-cash-register-onl01-seng-pt-120819
/lib/cash_register.rb
UTF-8
1,094
3.53125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class CashRegister attr_accessor :total, :discount, :items, :price, :quantity def initialize(discount = 0) @total = 0 @discount = discount @quantity = quantity @items = [] end def add_item(title, price, quantity = 1) @price = price @quantity = quantity @total += (price * quantity) if quantity > 1 counter = 0 while counter < quantity @items << title counter += 1 end else @items << title end end def apply_discount if @discount <= 0 return "There is no discount to apply." elsif @discount > 0 puts "#{@total} :total amount" puts "#{@discount} :discount" amount_off = @total * (@discount.to_f / 100.to_f) puts "#{amount_off} :amount off" @total -= amount_off return "After the discount, the total comes to $#{self.total.to_i}." end end def void_last_transaction #make quantity accessible for all methods by initializing it price = @price * @quantity totes = self.total @total = totes - price @items.pop() end end
true
86d61a7a465b38b183dc9ab78bf4114f40002986
Ruby
dipzzzz/code-workout
/app/helpers/feedback_timeout_updater.rb
UTF-8
709
2.875
3
[]
no_license
require 'thread' require 'singleton' class FeedbackTimeoutUpdater include Singleton # constants in milliseconds MIN_THRESHOLD = 1700 # minus the 300 padding def initialize @semaphore = Mutex.new @avg_timeout = 1700 end attr_accessor :avg_timeout # Update the feedback_timeout config value based on # the given value. The argument is assumed to be in # milliseconds. def update_timeout(time_taken) @semaphore.synchronize do new_avg = ( ((9 * @avg_timeout) + time_taken) / 10 ) Rails.application.config.feedback_timeout = new_avg > MIN_THRESHOLD ? new_avg : MIN_THRESHOLD @avg_timeout = new_avg end end end
true
bd416e522d23d153434ccb8edf55f7fc311a7300
Ruby
scifisamurai/todo
/test/unit/task_test.rb
UTF-8
393
2.546875
3
[]
no_license
require 'test_helper' class TaskTest < ActiveSupport::TestCase test "should not save without description" do task = Task.new assert !task.save end test "should save with a description" do task = Task.new(:description => "Buy Bread") assert task.save assert_not_nil Task.find_by_description("Buy Bread"), "Failed to find item that was just added" end end
true
ee1d023e43f1930d1e49443cd71c2d48e1c47b0b
Ruby
bhawani11/cucumber-ruby
/features/common/All programs/Registration .rb
UTF-8
2,906
2.578125
3
[]
no_license
# load in the webdriver gem to interact with Selenium require 'selenium-webdriver' #Run Chrome driver.exe to get chrome browser driver = Selenium::WebDriver.for :chrome # use of explicit wait wait = Selenium::WebDriver::Wait.new(:timeout => 10) def document_initialised(driver) driver.execute_script('return initialised') end begin driver.get 'http://automationpractice.com/' #driver will wait untill locator is not visible wait.until { |document_initialised| driver } search_form = driver.find_element(:css, "a[class='login']").text "Hello from JavaScript!".eql? search_form #implicit wait driver.manage.window.maximize driver.manage.timeouts.implicit_wait = 10 driver.find_element(:css, "a[class='login']").click driver.find_element(:css, "input[name='email_create']").send_keys("bsingh23@gmail.com") driver.find_element(:css, "button[id='SubmitCreate']").click driver.find_element(:name, "id_gender").click driver.find_element(:id, "customer_firstname").send_keys("bhawani s") driver.find_element(:id, "customer_lastname").send_keys("rajpoot") driver.find_element(:id, "email").send_keys("") driver.find_element(:id, "passwd").send_keys("123456") driver.find_element(:css, "select[id='days']").click driver.find_element(:css, "select[id='days']").send_keys("15") driver.find_element(:css, "select[id='months']").click driver.find_element(:css, "select[id='months']").send_keys("march") driver.find_element(:css, "select[id='years']").click driver.find_element(:css, "select[id='years']").send_keys("1990") driver.find_element(:id, "newsletter").click driver.find_element(:id, "firstname").send_keys("") driver.find_element(:id, "lastname").send_keys("") driver.find_element(:id, "company").send_keys("EminenceSquareI") driver.find_element(:name, "address1").send_keys("Scheme number 78") driver.find_element(:name, "address2").send_keys("Vijay nagar 78") driver.find_element(:id, "city").send_keys("hyderabad") driver.find_element(:css, "select[id='id_state']").click driver.find_element(:css, "select[id='id_state']").send_keys("indiana") driver.find_element(:id, "postcode").send_keys("00002") driver.find_element(:css, "select[id='id_country']").click driver.find_element(:css, "select[id='id_country']").send_keys("united states") driver.find_element(:id, "other").send_keys("hello i am here") driver.find_element(:id, "phone").send_keys("90987654321") driver.find_element(:name, "phone_mobile").send_keys("98907654321") driver.find_element(:id, "alias").send_keys("L.I.G") driver.find_element(:xpath, "//button[@name='submitAccount']").click # Check that the checkbox exists elementb = wait.until { element = driver.find_element(:xpath, "//span[contains(text(),'Order history and details')]") element if element.displayed? } puts "Test Passed: The element is displayed/exists" elementb.click sleep(5) end
true
c3d718192d941585aa4daf5aeb79f448f2cc408c
Ruby
MaxfieldLewin/rails_lite
/lib/controller_base.rb
UTF-8
1,929
2.515625
3
[]
no_license
require 'active_support' require 'active_support/core_ext' require 'erb' require_relative './route_helper' require_relative './view_helpers' require_relative './flash' require_relative './params' require_relative './session' require_relative './authenticity_token' class InvalidCSRFTokenError < StandardError; end class ControllerBase DANGER_METHODS = [:post, :patch, :put, :delete] include RouteHelper include ViewHelper include AuthenticityToken attr_reader :req, :res, :params def initialize(req, res, route_params = {}, routes = {}) define_route_helpers(routes) @params = Params.new(req, route_params) @req = req @res = res if !@req.request_method.nil? && DANGER_METHODS.include?(@req.request_method.downcase.to_sym) unless check_form_auth_token(@params[:authenticity_token]) raise InvalidCSRFTokenError end end end def already_built_response? @already_built_response end def redirect_to(url) session.store_session(self.res) flash.store_flash(self.res) set_auth_token(self.res) self.res.status = 302 self.res.header['location'] = url self.render_content(nil, nil) end def render_content(content, content_type) session.store_session(self.res) flash.store_flash(self.res) set_auth_token(self.res) self.res.content_type = content_type raise RuntimeError if already_built_response? self.res.body = content @already_built_response = true end def render(template_name) file_str = "views/#{self.class.to_s.underscore}/#{template_name}.html.erb" template = ERB.new(File.read(file_str)) content = template.result(binding) render_content(content, "text/html") end def session @session ||= Session.new(self.req) end def flash @flash ||= Flash.new(self.req) end def invoke_action(name) self.send(name) render unless already_built_response? end end
true
12ef4d9782e4517aac0fd2deceaac6d9605d2e04
Ruby
rentalname/site_prism
/spec/section_spec.rb
UTF-8
2,453
2.59375
3
[ "BSD-3-Clause" ]
permissive
# frozen_string_literal: true require 'spec_helper' describe SitePrism::Page do describe '.section' do context 'second argument is not a Class and a block given' do context 'block given' do it 'should create an anonymous section with the block' do class PageWithSection < SitePrism::Page section :anonymous_section, '.section' do |s| s.element :title, 'h1' end end page = PageWithSection.new expect(page).to respond_to(:anonymous_section) end end end context 'second argument is not a class and no block given' do subject(:section) { Page.section(:incorrect_section, '.section') } it 'should raise an ArgumentError' do class Page < SitePrism::Page; end expect { section } .to raise_error(ArgumentError) .with_message('You should provide section class either as a block, or as the second argument.') end end end end describe SitePrism::Section do let(:a_page) { class Page < SitePrism::Page; end } it 'responds to element' do expect(SitePrism::Section).to respond_to(:element) end it 'responds to elements' do expect(SitePrism::Section).to respond_to(:elements) end it 'passes a given block to Capybara.within' do expect(Capybara).to receive(:within).with('div') SitePrism::Section.new(a_page, 'div') { 1 + 1 } end it 'does not require a block' do expect(Capybara).not_to receive(:within) SitePrism::Section.new(a_page, 'div') end describe 'instance' do subject(:section) { SitePrism::Section.new('parent', 'locator') } it 'responds to javascript methods' do expect(section).to respond_to(:execute_script) expect(section).to respond_to(:evaluate_script) end it 'responds to #visible? method' do expect(section).to respond_to(:visible?) end it 'responds to Capybara methods' do expect(section).to respond_to(*Capybara::Session::DSL_METHODS) end end describe 'page' do subject(:section) { SitePrism::Section.new('parent', root_element).page } let(:root_element) { 'root' } it { is_expected.to eq('root') } context 'when root element is nil' do let(:root_element) { nil } before { allow(Capybara).to receive(:current_session).and_return('current session') } it { is_expected.to eq('current session') } end end end
true
54608aeaf790a33ba692bd325118e709dd609269
Ruby
iachettifederico/my_new_app
/app/models/user.rb
UTF-8
128
2.765625
3
[]
no_license
class User < ActiveRecord::Base def say_hello [ "Hola,", "you", "soy", name ].join(" ") end end
true
4249f48afce930e731ccc1b701db45c722a9639e
Ruby
dotsi/spree_one_page_checkout
/app/services/create_payment.rb
UTF-8
402
2.6875
3
[ "BSD-3-Clause" ]
permissive
class CreatePayment def initialize(payment_factory, payment_method) @payment_factory = payment_factory @payment_method = payment_method end def call(total, source) payment_factory.create do |payment| payment.amount = total payment.payment_method = payment_method payment.source = source end end private attr_reader :payment_factory, :payment_method end
true
ea83f9914f4ad27b0b65e1726b44f920156e4ecd
Ruby
clm1403/OOP
/inheritance/exercise2.rb
UTF-8
1,648
4.09375
4
[]
no_license
module Towable def can_tow(pounds) pounds < 2000 ? true : false end class Vehicle attr_accessor :color attr_reader :year @@num_vehicles = 0 def self.total_num_vehicles puts "This program has created #{@@num_vehicles} vehicles" end def initialize @@num_vehicles += 1 end def initialize(year, model, color) @year = year @model = model @color = color @current_speed = 0 end def speed_up(number) @current_speed += number puts "You push the gas and accelerate #{number} mph." end def brake(number) @current_speed -= number puts "You push the brake and decelerate #{number} mph." end def current_speed puts "You are now going #{@current_speed} mph." end def shut_down @current_speed = 0 puts "Let's park this bad boy!" end def spray_paint(color) self.color = color puts "Your new #{color} paint job looks great!" end def self.gas_milage(gallons, miles) puts "Wow, #{gallons/miles} is your MPG for this trip." end def to_s "The car is a #{@model} and it is of #{color} color." end def age "Your #{self.model} is #{years_old} years old." end private def years_old Time.now.year - self.year end end class MyCar < Vehicle NUM_DOORS = 4 end class MyTruck < Vehicle include Towable NUM_DOORS = 2 end # Add a class variable to your superclass that can keep track of the number of objects created that inherit from the superclass. #Create a method to print out the value of this class variable as well. puts @@num_vehicles puts MyCar.ancestors puts MyTruck.ancestors puts Vehicle.ancestors
true
2b49875c727f21f26597cc0e32f034b76dfea623
Ruby
edgcastillo/Programming_Challenges
/ruby-test/coderbyte.rb
UTF-8
5,767
4.15625
4
[]
no_license
#Programming Challenges from Coderbyte.com Level: Easy #Reverse String - reverse a string def reverse_string(string) return string.reverse end p reverse_string("hola") #First Factorial - find the factorial of a given number def factorial(number) factorial = 1 (1..number).each do |x| factorial *= x end return factorial end puts factorial(5) #Find the largest word in a string def longestWord(sen) array = [] sen.gsub!(/[^0-9a-zA-Z\s]/i, '') sen = sen.split(' ') sen.each {|word| array.push(word)} array.sort! { |x,y| y.length <=> x.length } return array.first end p longestWord("a beautiful sentence^&!") #Letter Changes - Manipulate characters in a string based off their position in the alphabet #Using the Ruby language, have the function LetterChanges(str) #take the str parameter being passed and modify it using the following algorithm. #Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a). #Then capitalize every vowel in this new string (a, e, i, o, u) and finally return this modified string. def letterChanges(str) new_str = [] alphabet = ('a'..'z').to_a str = str.split('') str.each {|x| new_str.push(x) unless alphabet.include?(x) alphabet.each_index {|index| if(x.eql?(alphabet[index])) letter = alphabet[index + 1] if(%{a e i o u}.include?(letter)) letter = letter.upcase end new_str.push(letter) end } } return new_str.join('') end p letterChanges("this long cake@&") #Simple Adding - adding up all the numbers from 1 to n def adding(num) sum = 0 (1..num).each do |x| sum += x end return sum end p adding(8) #Letter Capitalize - For this challenge you will be capitalizing first word of each char in a string. def letterCapitalize(str) #str = str.split(' ') #str.map! {|word| word.capitalize} #str.join(' ') str.split(' ').map! {|word| word.capitalize}.join(' ') end p letterCapitalize("i am legend") #see simple symbols, for some reason coderbyte doesn't like with_index method def simpleSymbols(str) str = str.split('') str.map.with_index{|char,i| if(char =~ /[a-zA-Z]/) return false if str.index(char) == 0 if(str[i - 1] != "+" || str[i + 1] != "+") return false end end } return true end p simpleSymbols("+d+") #true p simpleSymbols("+d===+a+") #false p simpleSymbols("aaa") #false p simpleSymbols("+z+z+z+") #true p simpleSymbols("+a=") #false p simpleSymbols("2+a+a+") #true p simpleSymbols("+a++") #true p simpleSymbols("+z+z+==+a+") #true p simpleSymbols("==a+") #false p simpleSymbols("b") #false # determine the difference in hours and minutes between two given times. def timeConvert(num) return "#{num/60}:#{num%60}" end p timeConvert(126) #sort characters in a string def alphabetSoup(str) return str.split('').sort().join('') end p alphabetSoup("coderbyte") #count the vowels in a string def vowelCount(str) count = 0 str = str.split('').each{|x| count += 1 if(%(a e i o u).include?(x))} return count end p vowelCount("coderbyte") def exOh(str) countO = 0 countX = 0 str.split('').each{|x| countO += 1 if(x == "o")} str.split('').each{|y| countX += 1 if(y == "x")} return countO == countX end p exOh("oxoooxo") #determine if a string is written the same way forward and backwards def palindrome(str) return str.gsub(' ', '') == str.gsub(' ', '').reverse end p palindrome("never odd or even") #Determine if numbers within an array follow an arithmetic or geometric sequence def arithGeo(arr) baseNumArith = arr[1] - arr[0] baseNumGeo = arr[1] / arr[0] if(arr.last - arr[arr.size - 2] == baseNumArith) return "Arithmetic" elsif(arr.last / arr[arr.size - 2] == baseNumGeo && baseNumGeo != arr[1]) #for this problem - arr.last / arr[arr.size - 2] == baseNumGeo this algorithm works for almos all the tests #but if the array starts with 1 increments and ends with a geomtric sequence it will pass as truth. when in fact it is not: # EG. 1 - 2 - 3.....10 - 20 while the last two numbers make the stament truth: array[n - 1] / array[n - 2] = baseNum #the sequence at the beginning is not geometric. return "Geometric" else return -1 end end p arithGeo([2,4,16,24]) #it will return -1 p arithGeo([5,10,15]) #it will return Arithmetic p arithGeo([2,6,18,54]) #it will return Geometric p arithGeo([1,5,9]) #it will return Arithmetic p arithGeo([1,2,3,4,5,10,20]) #it will return -1 #Determine if numbers in an array can add up to a certain number in the array def arrayAdditionI(arr) arrSum = 0 largestNum = arr.sort.pop arr.each{|x| arrSum += x if(x < largestNum) } if(arrSum >= largestNum || arr.include?(arrSum - largestNum)) return true else return false end end p arrayAdditionI([4,6,23,10,1,3]) #it is true p arrayAdditionI([5,7,16,1,2]) #it is false p arrayAdditionI([31,2,90,50,7]) #it is true #Determine which word has the greatest numbers of repeated letters def letterCountI(str) # count = 0 # mostRepeatedLetters = '' # str = str.split('').each{|letter| # if(str.count(letter) > count) # count = str.count(letter) # mostRepeatedLetters = str # end # } # return mostRepeatedLetters letterCount = 0 letterMaxWord = '' str = str.split(' ').each{|word| word.split('').each{|letter| if(word.downcase.count(letter) > letterCount) letterCount = word.downcase.count(letter) letterMaxWord = word end }} letterCount > 1 ? (return letterMaxWord) : (return -1) end p letterCountI("Hello apple pie") #returns Hello p letterCountI("No word") #returns -1 p letterCountI("Banana Bananarama cocomelococo") #returns Bananarama def divisionStringified(num1, num2) result = (num1 / num2).next.to_s.reverse result = result.split('').gsub(/[0-9]/) end p divisionStringified(6874,67)
true
b779f62b87752b487bc0ae6cda7e6c71bb75f154
Ruby
GunioRobot/ESPN.COM-scoreboard-parser
/espn_nhl_parser.rb
UTF-8
1,636
3.03125
3
[]
no_license
require 'rubygems' require 'nokogiri' require 'open-uri' require 'timeout' page = nil games = [] url = "http://espn.go.com/nhl/scoreboard" # fetch URL begin timeout(60) do # Exit after 60 seconds while page.nil? do # and if internet connection not work begin # then loops after every 10 seconds page = Nokogiri::HTML(open(url)) rescue OpenURI::HTTPError,SocketError sleep 5 # sleep 5 seconds end end end rescue Timeout::Error puts "Internet connection problems" else page.css("div.game-header").each do |gametable| # gametable - html table of current game unless gametable.at_css("tr td div a").nil? # if game not started then skip teams = [] score = [] gametable.css("tr td div a").each do |team_name| # Searching two team names (for away and home teams) teams << team_name.text end away, home = teams gametable.css("td.team-score").each do |team_score| # Need to find two scores per game (for away and home teams) score << team_score.text end result = "#{score[1]}:#{score[0]}" # Away team - Home team game_info = gametable.at_css("ul.game-info li").text.scan(/Final|OT|SO/) game = "#{home}-#{away} #{result} #{game_info}" games << game end # unless end # each if games.empty? puts "Today no games" else puts games end end #else
true
7db8ca3f3fe2378fce08b08c7a9cee3ca685fde8
Ruby
idhallie/grocery-store
/lib/order.rb
UTF-8
3,574
3.609375
4
[]
no_license
require 'csv' require_relative 'customer' require 'pry' class Order attr_reader :id, :customer, :fulfillment_status, :products # Constructor def initialize(id, products, customer, fulfillment_status = :pending) @id = id @products = products @customer = customer @fulfillment_status = fulfillment_status allowed_statuses = [:pending, :paid, :processing, :shipped, :complete] unless allowed_statuses.include?(@fulfillment_status) raise ArgumentError.new("Invalid fulfillment status given.") end end def total order_sum = 0 tax = 1.075 if @products.length > 0 @products.each do |item, cost| order_sum += cost end else return 0 end total = (order_sum * tax).round(2) return total end def add_product(product_name, price) existing_products = @products.keys if existing_products.include?(product_name) raise ArgumentError.new("You are trying to add a duplicate product.") else @products[product_name] = price end end def remove_product(rem_product_name) existing_prods = @products.keys unless existing_prods.include?(rem_product_name) raise ArgumentError.new("Product is not in the catalog and therefore cannot be removed.") else @products.delete(rem_product_name) end end # Creates order instances from a CSV file def self.all csv_array = CSV.read('data/orders.csv').map(&:to_a) instance_array = [] csv_array.each do |column| products = self.make_hash(column[1]) instance_array << Order.new(column[0].to_i, products, Customer.find(column[2].to_i), column[3].to_sym) end return instance_array end # Helper method for self.all def self.make_hash(product_string) prod_array = product_string.split(";") prod_nested_array = [] prod_array.each do |item| prod_nested_array << item.split(":") end prod_hash = {} prod_nested_array.each do |product, price| prod_hash[product] = price.to_f end return prod_hash end # Looks for a specified ID and returns order instance, if found. def self.find(id) ord_instance_array = Order.all ord_instance_array.each do |order| if id == order.id return order end end return nil end # Optional - returns a list of order instances for specified customer id def self.find_by_customer(customer_id) all_orders_array = Order.all order_list = [] all_orders_array.each do |order| if order.customer.id == customer_id order_list << order end end if order_list.length == 0 raise ArgumentError.new("There are no orders for that ID.") end return order_list end # Wave 3 - Optional # Saves a list of objects to a specified file. def self.save(filename) # take a list of objects instances = Order.all order_array = [] instances.each do |order_instance| order_array << [order_instance.id, Order.break_hash(order_instance.products), order_instance.customer.id, order_instance.fulfillment_status] end File.write(filename, order_array.map(&:to_csv).join) end # Helper method for self.save to deconstruct the product def self.break_hash(hash) prod_array = [] hash.each do |key, value| prod_array << key + ":" + value.to_s end prod_string = prod_array.join(';') return prod_string end end
true
242e2e309293fdd53cc09291700f9e37addefdec
Ruby
BDCraven/learn-to-program
/chap07/ex1.rb
UTF-8
502
3.921875
4
[]
no_license
bottles = 5 while bottles > 2 puts "#{bottles} bottles of beer on the wall. #{bottles} bottles of beer." puts "Take one down and pass it around. #{bottles -1} bottles of beer on the wall." bottles -= 1 end puts "#{bottles} bottles of beer on the wall. #{bottles} bottle of beer." puts "Take one down and pass it around. #{bottles -1} bottles of beer on the wall." puts "1 bottle of beer on the wall. 1 bottle of beer." puts "Take it down and pass it around. No more bottles of beer on the wall."
true
8dbe0f43b1abb69002575f46c66de792d27db48c
Ruby
forest/fepfile
/lib/fepfile/transaction_detail_record.rb
UTF-8
4,704
2.828125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module FEPFileSpecification class TransactionDetailRecord include ActiveModel::Validations attr_accessor :receiver_id, :routing_number, :account_type, :account_number, :effective_date, :credit_or_debit_flag, :amount, :transaction_id validates_presence_of :receiver_id, :routing_number, :account_type, :account_number, :effective_date, :credit_or_debit_flag, :amount validates_length_of :receiver_id, :within => 1..15 validates_format_of :receiver_id, :with => /^[a-zA-Z0-9]*$/, :message => 'must be Alphanumeric' validates_length_of :routing_number, :is => 9 validates_length_of :account_number, :within => 5..17 validates_numericality_of :routing_number, :account_number # validates_length_of :account_type, :is => 3 validates_format_of :account_type, :with => /^(DDA|SAV)$/, :message => 'must be DDA or SAV' # validates_length_of :effective_date, :is => 8 validates_format_of :effective_date, :with => /^(19[0-9]{2}|2[0-9]{3})(0[1-9]|1[012])([123]0|[012][1-9]|31)$/, :message => "does not match YYYYMMDD" validates_format_of :credit_or_debit_flag, :with => /^[CD]$/, :message => 'must be C or D' validates_format_of :amount, :with => /^\d{1,8}\.\d\d$/, :message => 'does not match $$$$$$$$.cc' validates_length_of :transaction_id, :within => 0..15, :allow_blank => true validates_format_of :transaction_id, :with => /^[a-zA-Z0-9]*$/, :message => 'must be Alphanumeric' # Construct a new FEPFileSpecification::TransactionDetailRecord with parameters (see below) # # ==== Parameters # +receiver_id+:: This key matches the transaction back to the customer. # (Alphanumeric) # +routing_number+:: The Routing & Transit number of the financial institution where # the Receiver has his or her account. (Numeric) # +account_type+:: This field should contain the type of account, ‘DDA’ if the # account is a demand deposit account (i.e., checking, money market) # or ‘SAV’ if the account is a savings account. # +account_number+:: This field should contain the number of the Receiver’s account. # It is very important that this account number be left-justified # and padded with spaces id it is less than 17 characters. # +effective_date+:: The date the transaction should become effective, in other words, # the date the transaction should be credited to or debited # from the Receiver’s account. (YYYYMMDD) # +credit_or_debit_flag+:: This field should contain a ‘C’ it the amount is a credit or ‘D’ # if the amount is a debit to the Receiver’s account. # +amount+:: The amount to be credited to or debited from the Receiver’s account. # +transaction_id+:: This field can be used to identify a single transaction to the # Originator. For instance, if an insurance company is creating two # debits, one for health insurance and one for auto insurance, it # may specify the different account numbers for the different insurance # policies in this field. This is also an override to the # Receiver ID field. (Alphanumeric) def initialize(attributes = {}) @receiver_id = attributes[:receiver_id] @routing_number = attributes[:routing_number] @account_type = attributes[:account_type] @account_number = attributes[:account_number] @effective_date = attributes[:effective_date] @credit_or_debit_flag = attributes[:credit_or_debit_flag] @amount = attributes[:amount] @transaction_id = attributes[:transaction_id] end def to_s raise ValidationError, errors.full_messages unless valid? sprintf("TD000%-15s%s%s%17s%s%s%11s%-15s#{'0'*16}", receiver_id, routing_number, account_type, account_number, effective_date, credit_or_debit_flag, amount, transaction_id).gsub(' ', '0') end end end
true
883f4314043db8de2da146147c2882c8d251cf51
Ruby
bbensch09/phase-0
/week-6/nested_data_solution.rb
UTF-8
2,544
4.09375
4
[ "MIT" ]
permissive
=begin REFLECTION What are some general rules you can apply to nested arrays? - In general to call values you simply use a 2nd/3rd/4th bracket notation after the first one in order to retrive values from the 2nd/3rd/4th level inner arrays. What are some ways you can iterate over nested arrays? - pretty much any enumerable method used for iteration normally can be used over a nested array, you just have to nest the method calls within each other. Because the "do end"'s and/or { } can get confusing wiht many layer of nesting, we found that it was slightly easier to use the { } syntax, because then you're not confused by the presence of ends that are attached to if statements. Did you find any good new methods to implement or did you re-use one you were already familiar with? - We reused the map! destructive method mostly. What was it and why did you decide that was a good option? - It basically goes through each element in the array and executes your block of code on it, allowing you to modify the element as you wish. =end # RELEASE 2: NESTED STRUCTURE GOLF # Hole 1 # Target element: "FORE" array = [[1,2], ["inner", ["eagle", "par", ["FORE", "hook"]]]] # attempts: # ============================================================ # CORRECT # p array[1][1][2][0] # ============================================================ # Hole 2 # Target element: "congrats!" hash = {outer: {inner: {"almost" => {3 => "congrats!"}}}} # attempts: # ============================================================ # CORRECT # p hash[:outer][:inner]["almost"][3] # ============================================================ # Hole 3 # Target element: "finished" nested_data = {array: ["array", {hash: "finished"}]} # attempts: # ============================================================ # CORRECT # p nested_data[:array][1][:hash] # ============================================================ # RELEASE 3: ITERATE OVER NESTED STRUCTURES number_array = [5, [10, 15], [20,25,30], 35] number_array.map! { |element| if element.kind_of?(Array) element.map! { |inner| inner += 5 } else element += 5 end } # p number_array # Bonus: startup_names = ["bit", ["find", "fast", ["optimize", "scope"]]] # startup_names = ["bit", ["find", "fast"]] startup_names.map! { |element| if element.kind_of?(Array) element.map! { |inner| if inner.kind_of?(Array) inner.map! { |inner3| inner3.to_s + "ly"} else inner.to_s + "ly" end } else element.to_s + "ly" end } p startup_names
true
aedc3111d39e401f8a6b165d87ed29fc221852ee
Ruby
dantarian/bladesdb
/db/fixtures/races.rb
UTF-8
445
2.515625
3
[ "MIT" ]
permissive
# db/fixtures/races.rb # Character races Race.seed( :name ) do |r| r.name = "Human" r.death_thresholds = 10 end Race.seed( :name ) do |r| r.name = "Elf" r.death_thresholds = 3 end Race.seed( :name ) do |r| r.name = "Half Elf" r.death_thresholds = 6 end Race.seed( :name ) do |r| r.name = "Half Orc" r.death_thresholds = 7 end Race.seed( :name ) do |r| r.name = "Half Ogre" r.death_thresholds = 7 end
true
e86cbafa695e418151ea33f7dbed4f243f9415f1
Ruby
incredulous/hoodwinkd
/lib/clean-html.rb
UTF-8
1,657
2.53125
3
[]
no_license
class String BASIC_TAGS = { 'a' => ['href', 'title'], 'img' => ['src', 'alt', 'title'], 'br' => [], 'i' => nil, 'u' => nil, 'b' => nil, 'pre' => nil, 'kbd' => nil, 'code' => ['lang'], 'cite' => nil, 'strong' => nil, 'em' => nil, 'ins' => nil, 'sup' => nil, 'sub' => nil, 'strike' => nil, 'del' => nil, 'table' => nil, 'tr' => nil, 'td' => nil, 'th' => nil, 'ol' => nil, 'ul' => nil, 'li' => nil, 'p' => nil, 'h1' => nil, 'h2' => nil, 'h3' => nil, 'h4' => nil, 'h5' => nil, 'h6' => nil, 'blockquote' => ['cite'] } def clean_html!( tags = BASIC_TAGS ) gsub!( /<!\[CDATA\[/, '' ) gsub!( /<(\/*)(\w+)([^>]*)>/ ) do raw = $~ tag = raw[2].downcase if tags.has_key? tag pcs = [tag] tags[tag].each do |prop| ['"', "'", ''].each do |q| q2 = ( q != '' ? q : '\s' ) if raw[3] =~ /#{prop}\s*=\s*#{q}([^#{q2}]*)#{q}/i attrv = $1.to_s next if prop == 'src' and attrv !~ /^http/ pcs << "#{prop}=\"#{attrv.gsub('"', '\\"')}\"" break end end end if tags[tag] "<#{raw[1]}#{pcs.join " "}>" else " " end end end end
true
be014856f0b16274aa268949384ddedbbb58acb0
Ruby
strizzwald/algorithms-and-datastructures
/test.rb
UTF-8
151
2.65625
3
[]
no_license
def read_file(filename) begin document = File.open(filename, 'r') document.readlines end end file = ARGV[0] puts read_file(file).inspect
true
178aca3e104cb698feaaf4298ab34f81c35df252
Ruby
JeJones21/futbol
/spec/game_manager_spec.rb
UTF-8
2,309
2.96875
3
[]
no_license
require 'spec_helper' RSpec.describe GameManager do before(:each) do game_path = './data/games_sample.csv' team_path = './data/teams.csv' game_teams_path = './data/game_teams_sample.csv' locations = { games: game_path, teams: team_path, game_teams: game_teams_path } @game_manager = GameManager.new(locations) end it "exists" do expect(@game_manager).to be_a(GameManager) end it "is an array" do expect(@game_manager.games).to be_an(Array) end it "adds team scores together for total score" do result = [5, 5, 3, 5, 4, 3, 5, 3, 1, 3, 3, 4, 2, 3, 5, 3, 4, 4, 5, 5, 5, 3, 5, 5, 3, 4, 3, 3, 1, 5, 5, 3, 4, 5, 2, 5, 5, 5, 5, 3, 5, 5, 6, 2, 5, 4, 1, 5, 5, 3] expect(@game_manager.total_game_score).to eq(result) end it "finds the higest total score" do expect(@game_manager.highest_total_score).to eq(6) end it "finds the lowest total score" do expect(@game_manager.lowest_total_score).to eq(1) end it 'counts total games' do expect(@game_manager.total_games).to eq(50) end it 'has home wins count' do expect(@game_manager.home_wins_count).to eq(33) end it 'has home win percents' do expect(@game_manager.percentage_home_wins).to eq(0.66) end it 'has visitor wins count' do expect(@game_manager.visitor_wins_count).to eq(16) end it 'has visitor win percents' do expect(@game_manager.percentage_visitor_wins).to eq(0.32) end it 'has a tie count' do expect(@game_manager.tie_count).to eq(1) end it 'has tie percent' do expect(@game_manager.percent_ties).to eq(0.02) end it 'has games sorted by season' do expect(@game_manager.games_by_season).to be_a(Hash) hash_keys = @game_manager.games_by_season.keys expect(hash_keys.count).to eq(1) expect(@game_manager.games_by_season.values.flatten[0]).to be_a(Game) end it 'can return a single game by id' do expect(@game_manager.game_by_id('2012030221')).to be_a(Game) end it "can return games based on team id" do expect(@game_manager.games_by_team_id("3").count).to eq(10) end end # xit "is an array of season numbers" do # result = ["20122013", "20152016", "20132014", "20142015", "20172018", "20162017"] # expect(@game_manager.array_of_seasons).to eq(result) # end
true
e56da955ca37dc9fd577b9200e0c1540cb5bc23b
Ruby
josemarialopez/codewars
/challenges/reverse_or_rotate/tests.rb
UTF-8
304
2.59375
3
[ "MIT" ]
permissive
require './solution' describe "Reverse or Rotate" do context "Basic tests" do it { expect(revrot("1234", 0)).to eq("") } it { expect(revrot("", 0)).to eq("") } it { expect(revrot("1234", 5)).to eq("") } it { expect(revrot("733049910872815764", 5)).to eq("330479108928157") } end end
true
a1d2e46fdf6e27f9cb3e4128b2764fe470afcc2b
Ruby
greghynds/kata
/ruby/racing_car/spec/dummy_pressure.rb
UTF-8
146
3.0625
3
[]
no_license
class DummyPressureSource def initialize(pressure) @pressure = pressure end def sample_pressure @pressure end end
true
421ec087dfca70318649367c1d826109a11364ca
Ruby
parryjos1/sei35-homework
/ramteen-taheri/week4/mortgage-calculator/mortgage-calculator.rb
UTF-8
519
3.6875
4
[]
no_license
puts "***********************************" puts "Welcome to the mortgage calculator." puts "" puts "We are going to ask you some questions." print "What is the principal amount borrowed? $" p_amount = gets.chomp p_amount = p_amount.to_f print "Enter the total number of months in repayments: " months = gets.chomp months = months.to_i int_rate = 0.003 puts "Calculating..." repayments = p_amount * ( (int_rate*(1+int_rate)**months) / ((1+int_rate)**months - 1)) puts "Repayments: $#{repayments.round(2)} per month"
true