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
271a0f332673ca77f2989c4e062b5dd2d6393b9b
Ruby
brymacto/hospice_at_home
/app/models/time_range.rb
UTF-8
1,337
3.328125
3
[]
no_license
class TimeRange attr_reader :day, :start_time, :end_time def initialize(day, start_time, end_time) @day = day @start_time = start_time.to_i @end_time = end_time.to_i end def ==(other) day == other.day && start_time == other.start_time && end_time == other.end_time end def contains(other_time_range) day == other_time_range.day && start_time <= other_time_range.start_time && end_time >= other_time_range.end_time end def has_same_day(other_time_range) day == other_time_range.day end def borders(other_time_range) has_same_day(other_time_range) && (start_time == other_time_range.end_time || end_time == other_time_range.start_time) end def overlaps(other_time_range) has_same_day(other_time_range) && (partially_overlaps(other_time_range) || fully_overlaps(other_time_range)) end def overlaps_or_is_overlapped_by(other_time_range) overlaps(other_time_range) || other_time_range.overlaps(self) end private def partially_overlaps(other_time_range) ((@start_time <= other_time_range.start_time && @end_time >= other_time_range.start_time && @end_time <= other_time_range.end_time)) end def fully_overlaps(other_time_range) (@start_time >= other_time_range.start_time && @end_time <= other_time_range.end_time) end end
true
76129e68eb770814be17027a2706c2d89e29fbd5
Ruby
eneriberri/tdd_arrays_poker
/poker/lib/hand.rb
UTF-8
1,842
4.09375
4
[]
no_license
class Hand WEIGHT = { :royal_flush => 10, :straight_flush => 9, :four_of_a_kind => 8, :full_house => 7, :flush => 6, :straight => 5, :three_of_a_kind => 4, :two_pair => 3, :one_pair => 2, :no_pair => 1 } def initialize @cards = [] end def count @cards.length end def add_card(card) raise "Too many cards" if count == 5 @cards << card end def result raise "Not enough cards" unless count == 5 # return :no_pair if @cards.uniq.length == 5 values = @cards.map { |card| card.value }.sort if flush? return :royal_flush if values == [1, 10, 11, 12, 13] return :straight_flush if straight?(values) return :flush else freq = frequencies(values) return :four_of_a_kind if freq.has_value?(4) return :full_house if freq.has_value?(3) && freq.has_value?(2) return :straight if straight?(values) return :three_of_a_kind if freq.has_value?(3) return :two_pair if freq.values.count(2) == 2 return :one_pair if freq.has_value?(2) return :no_pair end end def high_card max = 2 @cards.each do |card| if card.value == 1 max = 1 elsif card.value > max && max != 1 max = card.value end end max end def <=>(other_hand) WEIGHT[self.result] <=> WEIGHT[other_hand.result] end private def flush? suit = nil @cards.all? do |card| suit ||= card.suit suit == card.suit end end def straight?(values) (0...values.length-1).each do |i| return false if values[i+1] - values[i] != 1 end true end def frequencies(values) freq = Hash.new(0) values.each do |val| freq[val] += 1 end freq end end
true
1615e3239394325dbf9cffd6f10a8d951e170f35
Ruby
wwood/finishm
/lib/kmer_multi_abundance_file.rb
UTF-8
1,295
3.25
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'csv' module Bio # A class to work with a kmer abundance file format, # where the kmer is first, then each abundance after that (no headings, space separated) class KmerMultipleAbundanceHash < Hash include Bio::FinishM::Logging def self.parse_from_file(path) obj = self.new kmer_length = nil num_abundances = nil CSV.foreach(path, :col_sep => ' ') do |row| kmer = row[0].upcase abundances = row[1...row.length] kmer_length ||= kmer.length if kmer.length != kmer_length raise "inconsistent length of kmer found in kmer abundance file, in line: #{row.inspect}" end num_abundances ||= abundances.length if num_abundances != abundances.length raise "inconsistent number of abundances found in kmer abundance file, in line: #{row.inspect}" end obj[kmer] = abundances end return obj end def kmer_length each do |kmer, abundances| return kmer.length end end def number_of_abundances each do |kmer, abundances| return abundances.length end end def [](kmer) abundances = super(kmer.upcase) abundances ||= [0]*number_of_abundances return abundances end end end
true
740f696f156660b29fd5aeb25468327fcaa28e07
Ruby
hausgold/pricehubble
/lib/pricehubble/entity/valuation.rb
UTF-8
1,597
2.765625
3
[ "MIT" ]
permissive
# frozen_string_literal: true module PriceHubble # The PriceHubble valuation result for a given property. # # @see https://docs.pricehubble.com/#international-valuation class Valuation < BaseEntity # Mapped and tracked attributes tracked_attr :currency, :sale_price, :sale_price_range, :rent_gross, :rent_gross_range, :rent_net, :rent_net_range, :confidence, :scores, :status, :deal_type, :valuation_date, :country_code # Define attribute types for casting typed_attr :currency, :string_inquirer typed_attr :confidence, :string_inquirer typed_attr :deal_type, :string_inquirer typed_attr :country_code, :string_inquirer typed_attr :sale_price_range, :range typed_attr :rent_gross_range, :range typed_attr :rent_net_range, :range # Associations with_options(persist: true, initialize: true) do has_one :property has_one :scores, class_name: ValuationScores end # A streamlined helper to get the value by the deal type. (sale price # if deal type is +sale+ or gross rent value if deal type is +rent+) # # @return [Integer, nil] the value of the property def value return sale_price if deal_type.sale? rent_gross end # A streamlined helper to get the value range by the deal type. (sale price # range if deal type is +sale+ or gross rent range if deal type is +rent+) # # @return [Range, nil] the value range of the property def value_range return sale_price_range if deal_type.sale? rent_gross_range end end end
true
a5256f01e31dcf871cfd0bbf98cd64d5b4faed46
Ruby
shofira/ruby-basic
/looping.rb
UTF-8
528
3.46875
3
[]
no_license
5.times do puts 'Selamat Belajar Ruby' end puts '======================' #untuk satu line 5.times {puts 'Semangat Belajar Ruby'} puts '======================' 5.times do |no| puts "Belajar Ruby #{no+2}" end puts '======================' 4.upto(7).each do |nomor| puts "#{nomor}. Selamat Datang" end puts '======================' 5.downto(1).each do |no| puts "#{no}. Semangat Belajar" end #while-do poin = 0 while poin < 4 do puts poin poin += 1 end #until-do until poin > 4 do puts poin poin += 1 end
true
c423ebfb7a1cb3491ef21237f5d735b1f6554a76
Ruby
tarunanandr/Day2
/Prg3.rb
UTF-8
387
3.421875
3
[]
no_license
class Details def get_det(name,regno) @name=name @regno=regno end def put_det puts "Name: "+@name+" Regno: "+@regno.to_s end def name=(name) @name=name end def regno=(regno) @regno=regno end end std1=Details.new std1.get_det("ABC", 122015001) std1.put_det std2=Details.new std2.get_det("BCD", 122015002) std2.put_det std2.name="CDE" std2.regno=122015003 std2.put_det
true
aafc1692a7593cb0807520bc07ef11eb8d866d9b
Ruby
longlong1/total-in-ruby
/spec/full_file_parse_spec.rb
UTF-8
15,723
2.5625
3
[ "MIT" ]
permissive
require "total_in" RSpec.describe TotalIn do describe "parse" do before :all do File.open File.join(__dir__, "fixtures/total_in_full_latin_1.txt"), encoding: "iso-8859-1" do |file| @document = TotalIn.parse file end end let :document do @document end it "find the document meta data" do expect(document.id).to eq "TI222222" expect(document.created_at.strftime("%Y-%m-%d %H:%M:%S")).to eq "2011-10-25 04:13:30" expect(document.delivery_number).to eq 1 expect(document.file_type).to eq "TL1" expect(document.name).to eq "TOTALIN" expect(document.number_of_lines).to eq 61 end it "finds two accounts" do expect(document.accounts.size).to eq 2 end describe "first account" do let :account do document.accounts.first end it "stores the posting date" do expect(account.date.to_s).to eq "2011-10-24" end it "knows the number of transactions" do expect(account.number_of_transactions).to eq 6 end it "has the total amount" do expect(account.amount).to eq 1919000 end it "has the statement reference" do expect(account.statement_reference).to eq "20111024001" end describe "payments" do it "finds all the payments" do expect(account.payments.size).to eq 5 end describe "first payment" do let :payment do account.payments[0] end it "parses the serial number" do expect(payment.serial_number).to eq 22222333334444451 end it "do not have a receiving_bankgiro_number" do expect(payment.receiving_bankgiro_number).to be nil end it "extracts the amount in cents" do expect(payment.amount).to eq(302550) end it "finds all reference numbers" do expect(payment.reference_numbers).to eq [ "38952344444", "38952345678", "38952145778" ] end it "parses all the messages" do expected_message = [ "FAKTURANR:38952344444", "INTERN REF: 9780858", "FAKTURANR:38952345678", "38952145778ABC" ].join("\n") expect(payment.message).to eq expected_message end describe "#sender_account" do let :sender_account do payment.sender_account end it "parses the sender account" do expect(sender_account.account_number).to eq "1234567" expect(sender_account.origin_code).to eq 1 expect(sender_account.company_organization_number).to eq "9999999999" expect(sender_account.name).to eq "TESTBOLAGET AB" expect(sender_account.address).to eq "GATAN 12" expect(sender_account.postal_code).to eq "12345" expect(sender_account.city).to eq "TESTSTAD" end end end describe "second payment" do let :payment do account.payments[1] end it "does not have any reference numbers" do expect(payment.reference_numbers).to eq [] end it "parses the serial number" do expect(payment.serial_number).to eq 22222333334444455 end it "parses the amount in cents" do expect(payment.amount).to eq 429735 end it "do not have a receiving_bankgiro_number" do expect(payment.receiving_bankgiro_number).to be nil end it "parses the message" do expect(payment.message).to eq "TACK FÖR LÅNET" end it "has a sender" do sender = payment.sender expect(sender.name).to eq "FÖRETAGET AB FRISKVÅRDAVD." end it "parses the sender account" do sender_account = payment.sender_account expect(sender_account.account_number).to eq "99999999" expect(sender_account.origin_code).to be nil expect(sender_account.company_organization_number).to be nil expect(sender_account.name).to eq "FÖRETAGET AB" expect(sender_account.address).to eq "GATAN 7" expect(sender_account.postal_code).to eq "88888" expect(sender_account.city).to eq "TESTORTEN" end end describe "third payment" do let :payment do account.payments[2] end it "does not have any reference numbers" do expect(payment.reference_numbers).to eq [] end it "parses the serial number" do expect(payment.serial_number).to eq 22222333334444467 end it "parses the amount in cents" do expect(payment.amount).to eq 210900 end it "do not have a receiving_bankgiro_number" do expect(payment.receiving_bankgiro_number).to eq "34523455" end it "parses the message" do expect(payment.message).to eq "BETALNING FÖR VARA 123" end it "has a sender" do sender = payment.sender expect(sender.name).to eq "TESTFABRIKEN AB" expect(sender.address).to eq "GATAN 22" expect(sender.postal_code).to eq "11111" expect(sender.city).to eq "TESTVIKEN" end it "parses the sender account" do sender_account = payment.sender_account expect(sender_account.account_number).to eq "98765433" expect(sender_account.origin_code).to eq 2 expect(sender_account.company_organization_number).to eq "9999999999" expect(sender_account.name).to eq "NORDEA BANK AB" expect(sender_account.address).to be nil expect(sender_account.postal_code).to eq "10571" expect(sender_account.city).to eq "STOCKHOLM" end end describe "fourth payment" do let :payment do account.payments[3] end it "does not have any reference numbers" do expect(payment.reference_numbers).to eq [] end it "parses the serial number" do expect(payment.serial_number).to eq 22222333334444472 end it "parses the amount in cents" do expect(payment.amount).to eq 148365 end it "do not have a receiving_bankgiro_number" do expect(payment.receiving_bankgiro_number).to be nil end it "parses the message" do expect(payment.message).to be nil end it "has no sender" do expect(payment.sender).to be nil end it "parses the sender account" do sender_account = payment.sender_account expect(sender_account.account_number).to eq "1222211" expect(sender_account.origin_code).to eq 1 expect(sender_account.company_organization_number).to eq "9999999999" expect(sender_account.name).to be nil expect(sender_account.address).to be nil expect(sender_account.postal_code).to be nil expect(sender_account.city).to be nil end end describe "fifth payment" do let :payment do account.payments[4] end it "does not have any reference numbers" do expect(payment.reference_numbers).to eq ["38952345555"] end it "parses the serial number" do expect(payment.serial_number).to eq 22222333334444423 end it "parses the amount in cents" do expect(payment.amount).to eq 880000 end it "do not have a receiving_bankgiro_number" do expect(payment.receiving_bankgiro_number).to be nil end it "parses the message" do expect(payment.message).to eq "FAKT 38952345555,FAKTURANR" end it "has no sender" do expect(payment.sender).to be nil end it "parses the sender account" do sender_account = payment.sender_account expect(sender_account.account_number).to eq "2232567" expect(sender_account.origin_code).to eq 1 expect(sender_account.company_organization_number).to eq "9999999999" expect(sender_account.name).to be nil expect(sender_account.address).to be nil expect(sender_account.postal_code).to be nil expect(sender_account.city).to be nil end it "is an international payment" do expect(payment.international?).to be true expect(payment.international.cost).to eq 0 expect(payment.international.cost_currency).to be nil expect(payment.international.amount).to eq 100000 expect(payment.international.amount_currency).to eq "EUR" expect(payment.international.exchange_rate).to eq 88000 end end end describe "deductions" do it "finds one deduction" do expect(account.deductions.size).to eq 1 end let :deduction do account.deductions.first end it "parses the amount" do expect(deduction.amount).to eq 52550 end it "has no receiving bankgiro number" do expect(deduction.receiving_bankgiro_number).to be nil end it "has no code" do expect(deduction.code).to be nil end it "has one reference number" do expect(deduction.reference_numbers).to eq ["987654123"] end it "finds all messages" do expected_message = [ "FAKTURA NR: 987654123 ABC", "KUNDNR: 123", "ÅTERBETALNING" ].join "\n" expect(deduction.message).to eq expected_message end it "parses the sender account" do sender_account = deduction.sender_account expect(sender_account.account_number).to eq "1234567" expect(sender_account.origin_code).to eq 1 expect(sender_account.company_organization_number).to eq "9999999999" expect(sender_account.name).to eq "TESTBOLAGET AB" expect(sender_account.address).to eq "GATAN 12" expect(sender_account.postal_code).to eq "12345" expect(sender_account.city).to eq "TESTSTAD" end end end describe "second account" do let :account do document.accounts.last end it "knows the number of transactions" do expect(account.number_of_transactions).to eq 3 end it "stores the posting date" do expect(account.date.to_s).to eq "2011-10-24" end it "has the total amount" do expect(account.amount).to eq 954434 end it "has the statement reference" do expect(account.statement_reference).to eq "20111024001" end describe "payments" do it "finds all the payments" do expect(account.payments.size).to eq 3 end describe "first payment" do let :payment do account.payments[0] end it "parses the serial number" do expect(payment.serial_number).to eq 11111222223333344 end it "do not have a receiving_bankgiro_number" do expect(payment.receiving_bankgiro_number).to be nil end it "extracts the amount in cents" do expect(payment.amount).to eq(923434) end it "has no reference numbers" do expect(payment.reference_numbers).to eq [] end it "parses all the messages" do expect(payment.message).to eq "BETALNING AVSEENDE KÖP 110902" end describe "#sender_account" do let :sender_account do payment.sender_account end it "parses the sender account" do expect(sender_account.account_number).to eq "1234567" expect(sender_account.origin_code).to eq 1 expect(sender_account.company_organization_number).to eq "9999999999" expect(sender_account.name).to eq "TESTBOLAGET AB" expect(sender_account.address).to eq "GATAN 12" expect(sender_account.postal_code).to eq "12345" expect(sender_account.city).to eq "TESTSTAD" end end end describe "second payment" do let :payment do account.payments[1] end it "does not have any reference numbers" do expect(payment.reference_numbers).to eq [ "38952678900", ] end it "parses the serial number" do expect(payment.serial_number).to eq 22222333334444477 end it "parses the amount in cents" do expect(payment.amount).to eq 10500 end it "do not have a receiving_bankgiro_number" do expect(payment.receiving_bankgiro_number).to be nil end it "has no message" do expect(payment.message).to be nil end it "has a sender" do sender = payment.sender expect(sender.name).to eq "TESTFÖRETAG ENHET 2.A" end it "parses the sender account" do sender_account = payment.sender_account expect(sender_account.account_number).to eq "54321" expect(sender_account.origin_code).to eq 1 expect(sender_account.company_organization_number).to eq "9999999999" expect(sender_account.name).to eq "TESTFÖRETAG" expect(sender_account.address).to eq "TESTV 55" expect(sender_account.postal_code).to eq "12345" expect(sender_account.city).to eq "TESTSTAD" end end describe "third payment" do let :payment do account.payments[2] end it "does not have any reference numbers" do expect(payment.reference_numbers).to eq [ "38952678888", "38952345999" ] end it "parses the serial number" do expect(payment.serial_number).to eq 22222333334444422 end it "parses the amount in cents" do expect(payment.amount).to eq 20500 end it "do not have a receiving_bankgiro_number" do expect(payment.receiving_bankgiro_number).to be nil end it "parses the message" do expect(payment.message).to eq "FAKTNR=38952348888 OCH\nFAKTNR=38952345999" end it "has no sender" do expect(payment.sender).to be nil end it "parses the sender account" do sender_account = payment.sender_account expect(sender_account.account_number).to eq "98765555" expect(sender_account.origin_code).to eq 1 expect(sender_account.company_organization_number).to eq "9999999999" expect(sender_account.name).to eq "TESTER AB" expect(sender_account.address).to eq "VÄGEN 1" expect(sender_account.postal_code).to eq "88888" expect(sender_account.city).to eq "TESTORTEN" end end end it "has no deductions" do expect(account.deductions.size).to eq 0 end end end end
true
628e96496c62e6d42fa868a1df9a9ef54c87e15c
Ruby
maetl/calyx
/lib/calyx/rule.rb
UTF-8
1,287
3.0625
3
[ "MIT" ]
permissive
module Calyx # Represents a named rule connected to a tree of productions that can be # evaluated and a trace which represents where the rule was declared. class Rule def self.build_ast(productions, registry) if productions.first.is_a?(Hash) # TODO: test that key is a string if productions.first.first.last.is_a?(String) # If value of the production is a strings then this is a # paired mapping production. Production::AffixTable.parse(productions.first, registry) else # Otherwise, we assume this is a weighted choice declaration and # convert the hash to an array Syntax::WeightedChoices.parse(productions.first.to_a, registry) end elsif productions.first.is_a?(Enumerable) # TODO: this needs to change to support attributed/tagged grammars Syntax::WeightedChoices.parse(productions, registry) else Syntax::Choices.parse(productions, registry) end end attr_reader :name, :tree, :trace def initialize(name, productions, trace) @name = name.to_sym @tree = productions @trace = trace end def size tree.size end def evaluate(options) tree.evaluate(options) end end end
true
999e5f1035cb3bf906f0c6f48dc0b84af601eed6
Ruby
tsuyopon/ruby
/rubocop/src/test.rb
UTF-8
202
2.90625
3
[]
no_license
# conding: utf-8 require "date" class SampleRubocop def initialize( key ) @key = key end def hey @key end end if __FILE__ == $0 hoge = SampleRubocop.new("hoge") p hoge.hey end
true
f6cad1c9527d77fbd483c909a5ff0feb33b392b4
Ruby
lishulongVI/leetcode
/ruby/821.Bricks Falling When Hit(打砖块).rb
UTF-8
4,751
3.609375
4
[ "MIT" ]
permissive
=begin <p>We have a grid of 1s and 0s; the 1s in a cell represent bricks.&nbsp; A brick will not drop if and only if it is directly connected to the top of the grid, or at least one of its (4-way) adjacent bricks will not drop.</p> <p>We will do some erasures&nbsp;sequentially. Each time we want to do the erasure at the location (i, j), the brick (if it exists) on that location will disappear, and then some other bricks may&nbsp;drop because of that&nbsp;erasure.</p> <p>Return an array representing the number of bricks that will drop after each erasure in sequence.</p> <pre> <strong>Example 1:</strong> <strong>Input:</strong> grid = [[1,0,0,0],[1,1,1,0]] hits = [[1,0]] <strong>Output:</strong> [2] <strong>Explanation: </strong> If we erase the brick at (1, 0), the brick at (1, 1) and (1, 2) will drop. So we should return 2.</pre> <pre> <strong>Example 2:</strong> <strong>Input:</strong> grid = [[1,0,0,0],[1,1,0,0]] hits = [[1,1],[1,0]] <strong>Output:</strong> [0,0] <strong>Explanation: </strong> When we erase the brick at (1, 0), the brick at (1, 1) has already disappeared due to the last move. So each erasure will cause no bricks dropping. Note that the erased brick (1, 0) will not be counted as a dropped brick.</pre> <p>&nbsp;</p> <p><strong>Note:</strong></p> <ul> <li>The number of rows and columns in the grid will be in the range&nbsp;[1, 200].</li> <li>The number of erasures will not exceed the area of the grid.</li> <li>It is guaranteed that each erasure will be different from any other erasure, and located inside the grid.</li> <li>An erasure may refer to a location with no brick - if it does, no bricks drop.</li> </ul> <p>我们有一组包含1和0的网格;其中1表示砖块。&nbsp;当且仅当一块砖直接连接到网格的顶部,或者它至少连接着(4个方向)相邻的砖块之一时,它才不会落下。</p> <p>我们会依次消除一些砖块。每当我们消除&nbsp;(i, j) 位置时, 对应位置的砖块(若存在)会消失,然后其他的砖块可能因为这个消除而落下。</p> <p>返回一个数组表示每次消除操作对应落下的砖块数目。</p> <pre> <strong>示例 1:</strong> <strong>输入:</strong> grid = [[1,0,0,0],[1,1,1,0]] hits = [[1,0]] <strong>输出:</strong> [2] <strong>解释: </strong> 如果我们消除(1, 0)位置的砖块, 在(1, 1) 和(1, 2) 的砖块会落下。所以我们应该返回2。</pre> <pre> <strong>示例 2:</strong> <strong>输入:</strong> grid = [[1,0,0,0],[1,1,0,0]] hits = [[1,1],[1,0]] <strong>输出:</strong>[0,0] <strong>解释:</strong> 当我们消除(1, 0)的砖块时,(1, 1)的砖块已经由于上一步消除而消失了。所以每次消除操作不会造成砖块落下。注意(1, 0)砖块不会记作落下的砖块。</pre> <p><strong>注意:</strong></p> <ul> <li>网格的行数和列数的范围是[1, 200]。</li> <li>消除的数字不会超过网格的区域。</li> <li>可以保证每次的消除都不相同,并且位于网格的内部。</li> <li>一个消除的位置可能没有砖块,如果这样的话,就不会有砖块落下。</li> </ul> <p>我们有一组包含1和0的网格;其中1表示砖块。&nbsp;当且仅当一块砖直接连接到网格的顶部,或者它至少连接着(4个方向)相邻的砖块之一时,它才不会落下。</p> <p>我们会依次消除一些砖块。每当我们消除&nbsp;(i, j) 位置时, 对应位置的砖块(若存在)会消失,然后其他的砖块可能因为这个消除而落下。</p> <p>返回一个数组表示每次消除操作对应落下的砖块数目。</p> <pre> <strong>示例 1:</strong> <strong>输入:</strong> grid = [[1,0,0,0],[1,1,1,0]] hits = [[1,0]] <strong>输出:</strong> [2] <strong>解释: </strong> 如果我们消除(1, 0)位置的砖块, 在(1, 1) 和(1, 2) 的砖块会落下。所以我们应该返回2。</pre> <pre> <strong>示例 2:</strong> <strong>输入:</strong> grid = [[1,0,0,0],[1,1,0,0]] hits = [[1,1],[1,0]] <strong>输出:</strong>[0,0] <strong>解释:</strong> 当我们消除(1, 0)的砖块时,(1, 1)的砖块已经由于上一步消除而消失了。所以每次消除操作不会造成砖块落下。注意(1, 0)砖块不会记作落下的砖块。</pre> <p><strong>注意:</strong></p> <ul> <li>网格的行数和列数的范围是[1, 200]。</li> <li>消除的数字不会超过网格的区域。</li> <li>可以保证每次的消除都不相同,并且位于网格的内部。</li> <li>一个消除的位置可能没有砖块,如果这样的话,就不会有砖块落下。</li> </ul> =end # @param {Integer[][]} grid # @param {Integer[][]} hits # @return {Integer[]} def hit_bricks(grid, hits) end
true
4071484a70c30395b203087dec46d26e2ea5cad9
Ruby
gmaetzig/AoC2018
/Day 8/license.rb
UTF-8
1,803
3.34375
3
[]
no_license
start_time = Time.new class Tree def initialize(childs, metadatas) @num_childs = childs @num_metadatas = metadatas @metadata = [] @children = [] end def get_num_childs() return @num_childs end def get_num_metadatas() return @num_metadatas end def get_metadata() return @metadata end def add_child(child) @children.append(child) end def add_metadata(metadata) @metadata.append(metadata) end def get_children() return @children end def has_children() return @num_childs > 0 end def has_metadata() return @num_metadatas > 0 end end $input = File.read('input').split(" ") $sum_of_metadatas = 0 def recurse() childs = $input[0].to_i metadatas = $input[1].to_i $input = $input.drop(2) new_node = Tree.new(childs, metadatas) if childs != 0 then for i in 0...childs do new_node.add_child(recurse()) end end if metadatas != 0 then for i in 0...metadatas do new_node.add_metadata($input[0].to_i) $sum_of_metadatas += $input[0].to_i $input = $input.drop(1) end end return new_node end def recurse2(node) sum = 0 if node.get_num_childs > 0 then childs = node.get_children node.get_metadata.each do |index| if index <= childs.length then sum += recurse2(childs[index-1]) end end else node.get_metadata.each do |x| sum += x end end return sum end node = recurse() sum = recurse2(node) puts $sum_of_metadatas puts sum end_time = Time.new puts "Total Execution Time : " + (end_time-start_time).inspect()
true
5c03ec373e6466092339630883f2987ee564e2ce
Ruby
undeadinu/gavrog
/jruby/cgd_to_ds.rb
UTF-8
669
2.703125
3
[ "Apache-2.0" ]
permissive
#!/bin/env jruby include Java import org.gavrog.joss.pgraphs.io.NetParser import org.gavrog.joss.tilings.FaceList def convert(input, output) File.open(output, "w") do |f| parser = NetParser.new(input) while !parser.at_end data = parser.parse_data_block if data.type.match(/TILING/i) name = data.get_entries_as_string "name" begin ds = FaceList.new(data).symbol rescue Exception => ex f.puts "#\@ error \"#{ex.to_s}\" on #{name || "unnamed"}" else f.puts "#\@ name #{name}" if name f.puts ds end f.flush end end end end convert ARGV[0], ARGV[1]
true
3955e55aeed4a10dcfa86890abebfb44f98289ec
Ruby
EmilReji/ruby_small_problems
/Medium_1/5_Diamonds.rb
UTF-8
816
4.3125
4
[]
no_license
=begin Write a method that displays a 4-pointed diamond in an n x n grid, where n is an odd integer that is supplied as an argument to the method. You may assume that the argument will always be an odd integer. number indicates number of stars along each axis run a loop n/2 times for each line; increment by 2 (1 to 3 to 5); ex. n = 9; 9/2 = 4 - print current line - current value represents number of stars - spaces to print before stars = n/2 decremented by 1 each iteration then print middle amount of n stars then repeat loop backwards decrementing =end def diamond(size) stars = 1 spaces = size/2 (size/2).times do puts " " * spaces + "*" * stars stars += 2 spaces -= 1 end (size/2 + 1).times do puts " " * spaces + "*" * stars stars -= 2 spaces += 1 end end diamond(5)
true
ac95c5465043dfd5aa0aa867f0ca41c734c8352d
Ruby
cunger/launch
/180/expenses/lib/expenses.rb
UTF-8
2,307
2.859375
3
[]
no_license
require 'pg' class Expenses def initialize @data = PG.connect(dbname: 'expenses') setup_schema end def list show_as_table all_expenses end def search(string) show_as_table expenses_like(string) end def add(amount, memo) add_expense amount, memo end def delete(id) e = get_expense id return nil if e.values.empty? delete_expense id show_as_table result end def delete_all delete_all_expenses end private attr_reader :data def setup_schema count = data.exec "SELECT COUNT(*) AS c FROM information_schema.tables \ WHERE table_schema = 'public' AND table_name = 'expenses';" if count.field_values("c")[0] == "0" data.exec File.read('data/schema.sql') end end def add_expense(amount, memo) query = "INSERT INTO expenses (amount, memo) VALUES ($1, $2);" data.exec_params(query, [amount, memo]) end def get_expense(id) query = "SELECT * FROM expenses WHERE id = $1;" result = data.exec_params(query, [id]) end def delete_expense(id) query = "DELETE FROM expenses WHERE id = $1;" data.exec_params(query, [id]) end def delete_all_expenses data.exec "DELETE FROM expenses;" end def all_expenses data.exec "SELECT * FROM expenses ORDER BY created_on DESC;" end def total data.exec "SELECT SUM(amount) FROM expenses;" end def expenses_like(string) query = "SELECT * FROM expenses WHERE memo ILIKE $1 ORDER BY created_on DESC;" data.exec_params(query, ["%#{string}%"]) end def show_as_table(results) return 'There are no expenses.' if results.values.empty? table = " ID | Date | Amount | Memo \n" table += "----+------------+---------------+------------------\n" results.each do |result| table += " %2s | %10s | %13s | %s " % [ result['id'], result['created_on'], result['amount'], result['memo'] ] table += "\n" end total = results.field_values('amount').map(&:to_f).sum.to_s table += "----------------------------------------------------\n" table += "Total: %13s " % total table end end
true
0da33b1bbf38b37c5fa9a2a061100ba1edd9a299
Ruby
vs4vijay/tron.rb
/sample/mouse.rb
UTF-8
1,009
2.609375
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require "curses" include Curses def show_message(*msgs) message = msgs.join width = message.length + 6 win = Window.new(5, width, (lines - 5) / 2, (cols - width) / 2) win.keypad = true win.attron(color_pair(COLOR_RED)){ win.box(?|, ?-, ?+) } win.setpos(2, 3) win.addstr(message) win.refresh win.getch win.close end init_screen start_color init_pair(COLOR_BLUE,COLOR_BLUE,COLOR_WHITE) init_pair(COLOR_RED,COLOR_RED,COLOR_WHITE) crmode noecho stdscr.keypad(true) begin mousemask(BUTTON1_CLICKED|BUTTON2_CLICKED|BUTTON3_CLICKED|BUTTON4_CLICKED) setpos((lines - 5) / 2, (cols - 10) / 2) attron(color_pair(COLOR_BLUE)|A_BOLD){ addstr("click") } refresh while( true ) c = getch case c when KEY_MOUSE m = getmouse if( m ) show_message("getch = #{c.inspect}, ", "mouse event = #{'0x%x' % m.bstate}, ", "axis = (#{m.x},#{m.y},#{m.z})") end break end end refresh ensure close_screen end
true
257f008a6653efb9edb4d9f55419e26bc6802670
Ruby
alanrsl10/estudos
/Programas/jogo.rb
UTF-8
839
4.34375
4
[]
no_license
# Jogo da adivinhação diferente jogar = "1" def limpa_texto(texto) texto.strip end def inicia_jogo puts "Adivinhe o número que eu sorteei entre 1 e 100" palpite = gets.to_i sorteado = Random.rand(99) + 1 tentativas = 1 while palpite != sorteado if palpite > sorteado puts "O número que você escolheu é maior do que o número que eu sorteei!" else puts "O número que você escolheu é menor do que o número que eu sorteei!" end tentativas += 1 puts "Tente novamente..." palpite = gets.to_i end puts "Parabéns, você acertou. O número sorteado era #{sorteado}" puts "Você usou #{tentativas} tentativas para acertar o número." end while jogar == "1" inicia_jogo puts "Deseja jogar novamente?" puts "[1] - Sim" puts "[0] - Não" jogar = limpa_texto(gets) end
true
0312bd52f72db5efe979a560125eaba6a64b24c7
Ruby
NicolasDontigny/books-manager
/db/seeds.rb
UTF-8
6,963
2.578125
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) require "open-uri" puts "Deleting all models..." Author.destroy_all Category.destroy_all Book.destroy_all puts "Creating authors..." nicolas = User.find_by(email: 'nicolas.dontigny1@gmail.com') goggins = Author.create( first_name: 'David', last_name: 'Goggins', ) jurek = Author.create( first_name: 'Scott', last_name: 'Jurek' ) friedman = Author.create( first_name: 'Steve', last_name: 'Friedman' ) braun = Author.create( first_name: 'Adam', last_name: 'Braun' ) starrett = Author.create( first_name: 'Kelly', last_name: 'Starrett' ) cordoza = Author.create( first_name: 'Glen', last_name: 'Cordoza' ) puts "Creating categories..." inspiration = Category.create( name: 'Inspiration' ) motivation = Category.create( name: 'Motivation' ) mobility = Category.create( name: 'Mobility' ) flexibility = Category.create( name: 'Flexibility' ) strength = Category.create( name: 'Strength' ) running = Category.create( name: 'Running' ) biography = Category.create( name: 'Biography' ) puts "Creating books and associations..." book1 = Book.create( title: "Can't Hurt Me", description: "For David Goggins, childhood was a nightmare -- poverty, prejudice, and physical abuse colored his days and haunted his nights. But through self-discipline, mental toughness, and hard work, Goggins transformed himself from a depressed, overweight young man with no future into a U.S. Armed Forces icon and one of the world's top endurance athletes. The only man in history to complete elite training as a Navy SEAL, Army Ranger, and Air Force Tactical Air Controller, he went on to set records in numerous endurance events, inspiring Outside magazine to name him \"The Fittest (Real) Man in America.\"", year_published: 2018, fiction: false, created_by: nicolas ) BookAuthor.create( book: book1, author: goggins ) BookCategory.create( book: book1, category: inspiration ) BookCategory.create( book: book1, category: motivation ) BookCategory.create( book: book1, category: running ) BookCategory.create( book: book1, category: biography ) file = URI.open('https://res.cloudinary.com/da3vccwkh/image/upload/v1581796842/books/w0b8ld0aswpebuhwdwi0.jpg') book1.cover_photo.attach(io: file, filename: 'cant-hurt-me.jpg', content_type: 'image/jpg') book2 = Book.create( title: "Eat and Run: My Unlikely Journey to Ultramarathon Greatness", description: "For nearly two decades, Scott Jurek has been a dominant force—and darling—in the grueling and growing sport of ultrarunning. Until recently he held the American 24-hour record and he was one of the elite runners profiled in the runaway bestseller Born to Run. In Eat and Run, Jurek opens up about his life and career as a champion athlete with a plant-based diet and inspires runners at every level. From his Midwestern childhood hunting, fishing, and cooking for his meat-and-potatoes family to his slow transition to ultrarunning and veganism, Scott’s story shows the power of an iron will and blows apart the stereotypes of what athletes should eat to fuel optimal performance. Full of stories of competition as well as science and practical advice—including his own recipes—Eat and Run will motivate readers and expand their food horizons.", year_published: 2012, fiction: false, created_by: nicolas ) BookAuthor.create( book: book2, author: jurek ) BookAuthor.create( book: book2, author: friedman ) BookCategory.create( book: book2, category: biography ) BookCategory.create( book: book2, category: running ) file = URI.open('https://res.cloudinary.com/da3vccwkh/image/upload/v1581796842/books/zpmnub7qempip8rekjwz.jpg') book2.cover_photo.attach(io: file, filename: 'eat-and-run.jpg', content_type: 'image/jpg') book3 = Book.create( title: "The Promise of a Pencil: How an Ordinary Person Can Create Extraordinary Change", description: "The riveting story of how a young man turned $25 into more than 200 schools around the world and the guiding steps anyone can take to lead a successful and significant life. Adam Braun began working summers at hedge funds when he was just sixteen years old, sprinting down the path to a successful Wall Street career. But while traveling he met a young boy begging on the streets of India, who after being asked what he wanted most in the world, simply answered, “A pencil.” This small request led to a staggering series of events that took Braun backpacking through dozens of countries before eventually leaving one of the world’s most prestigious jobs to found Pencils of Promise, the organization he started with just $25 that has since built more than 200 schools around the world.", year_published: 2014, fiction: false, created_by: nicolas ) BookAuthor.create( book: book3, author: braun ) BookCategory.create( book: book3, category: biography ) BookCategory.create( book: book3, category: inspiration ) BookCategory.create( book: book3, category: motivation ) file = URI.open('https://res.cloudinary.com/da3vccwkh/image/upload/v1581796842/books/uammymtiixxay9impoj8.jpg') book3.cover_photo.attach(io: file, filename: 'promise-of-a-pencil.jpg', content_type: 'image/jpg') book4 = Book.create( title: "Becoming a Supple Leopard 2nd Edition: The Ultimate Guide to Resolving Pain, Preventing Injury, and Optimizing Athletic Performance", description: "Improve your athletic performance, extend your athletic career, treat stiffness and achy joints, and prevent and rehabilitate injuries—all without having to seek out a coach, doctor, chiropractor, physical therapist, or masseur. In Becoming a Supple Leopard, Dr. Kelly Starrett—founder of MobilityWOD.com—shares his revolutionary approach to mobility and maintenance of the human body and teaches you how to hack your own movement, allowing you to live a healthier, more fulfilling life. This new edition of the New York Times and Wall Street Journal bestseller has been thoroughly revised to make it even easier to put to use.", year_published: 2018, fiction: false, created_by: nicolas ) BookAuthor.create( book: book4, author: starrett ) BookAuthor.create( book: book4, author: cordoza ) BookCategory.create( book: book4, category: strength ) BookCategory.create( book: book4, category: flexibility ) BookCategory.create( book: book4, category: mobility ) file = URI.open('https://res.cloudinary.com/da3vccwkh/image/upload/v1581796842/books/jhejauat8vb9euu1eigm.jpg') book4.cover_photo.attach(io: file, filename: 'becoming-a-supple-leopard.jpg', content_type: 'image/jpg') puts "Success!"
true
bff930338d73351216458c33225100a26b23b526
Ruby
tomtl/tealeaf-OOP-intro
/blackjack/blackjack-oo.rb
UTF-8
5,721
4.0625
4
[]
no_license
# blackjack-oo.rb # Tealeaf course 1, lesson 2 # Tom Lee, Feb 16, 2014 class Deck attr_accessor :cards RANKS = [2, 3, 4, 5, 6, 7, 8, 9, 10, "Jack", "Queen", "King", "Ace"] SUITS = ["Clubs", "Diamonds", "Hearts", "Spades"] VALUES = { 2 => 2, 3 => 3, 4 => 4, 5 => 5, 6 => 6, 7 => 7, 8 => 8, 9 => 9, 10 => 10, "Jack" => 10, "Queen" => 10, "King" => 10, "Ace" => 11 } def initialize @cards = [] build_deck end def build_deck 2.times do RANKS.each do |rank| SUITS.each do |suit| @cards << Card.new(rank, suit) end end end end def deal_one_card cards.shuffle!.pop end end class Card attr_accessor :rank, :suit, :value def initialize (rank, suit) @rank = rank @suit = suit @value = Deck::VALUES[rank] end def to_s "#{rank} of #{suit}" end end class Player attr_accessor :hand, :score def initialize @hand = [] @score = 0 end def add_card_to_hand(card) hand << card update_player_score end def update_player_score if score > 21 && aces_count > 0 calculate_hand_value_with_aces else calculate_hand_value_without_aces end score end def calculate_hand_value_with_aces ace_cards_count = aces_count ace_cards_value = ace_cards_count * 11 while ace_cards_count > 0 ace_cards_count -= 1 ace_cards_value -= 10 value = non_aces_value + ace_cards_value break if value <= 21 end @score = value end def calculate_hand_value_without_aces @score = 0 hand.each { |card| @score += card.value } score end def aces_count hand.select { |card| card.rank == "Ace" }.count end def non_aces_value non_ace_cards = hand.select { |card| card.rank != "Ace" } non_ace_cards_value = 0 non_ace_cards.each { |card| non_ace_cards_value += card.value} non_ace_cards_value end def to_s "#{@hand}" end end class Game attr_reader :deck, :person , :computer def initialize @deck = Deck.new @person = Player.new @computer = Player.new end def clear_screen system "cls" system "clear" end def display_welcome_message puts "Welcome to Blackjack!" end def display_initial_cards puts "Your cards are: #{person.hand}. Score: #{person.score}" puts "Dealer's first card is #{computer.hand.first}" end def display_all_cards puts "Your cards are: #{person.hand}. Score: #{person.score}" puts "Dealer's cards are: #{computer.hand}. Score: #{computer.score}" end def display_player_turn_message puts "" puts " -Your turn-" end def display_computer_turn_message puts "" puts " -Dealer's turn- " end def display_dealt_card(player) sleep(0.5) if player == @computer puts "Dealer received a #{@computer.hand.last}." else puts "You received a #{@person.hand.last}." end end def display_winner puts "" puts " -Final score-" display_all_cards if person.score > 21 puts "You have #{person.score} - Bust. You lose." elsif computer.score > 21 puts "Dealer busted, you win!" elsif person.score > computer.score puts "You win!" elsif computer.score > person.score puts "Dealer wins." else puts "It's a tie!" end end def display_endgame_message puts "" puts "Thanks for playing!" end def deal_to(player) if player == person person.add_card_to_hand(deck.deal_one_card) else computer.add_card_to_hand(deck.deal_one_card) end end def deal_initial_cards 2.times do [person, computer].each { |player| deal_to(player) } end end def check_for_blackjack if person.score == 21 puts "21, you win!" elsif computer.score == 21 puts "Dealer got 21!" end end def ask_player_to_hit puts "Do you want to hit? (y/n)" hit = gets.chomp until ["y", "n"].include?(hit.downcase) puts "Do you want another card? Please type 'y' or 'n'." hit = gets.chomp end hit end def player_turn display_player_turn_message begin display_initial_cards return nil if computer.score == 21 hit = ask_player_to_hit break if hit == "n" deal_to(person) display_dealt_card(person) end while person.score <= 21 puts "You stay on #{person.score}" end def dealer_turn display_computer_turn_message return nil if person.score > 21 while computer.score < 17 deal_to(computer) display_dealt_card(computer) end puts "Dealer stays on #{computer.score}" end def ask_play_again puts "" puts "Do you want to play again? (y/n)" play_again = gets.chomp.downcase end def play_again play_again = ask_play_again begin if play_again == 'y' start_new_game elsif play_again == 'n' exit_game else play_again = ask_play_again end end while ['y', 'n'].include?(play_again) end def start_new_game @deck = Deck.new @person.hand = [] @person.score = 0 @computer.hand = [] @computer.score = 0 run end def exit_game display_endgame_message exit end def run clear_screen display_welcome_message deal_initial_cards check_for_blackjack player_turn dealer_turn display_winner play_again end end Game.new.run
true
21dfd4cf8e08aebaaecb781565c7e24043cb3a55
Ruby
BrianBailey/data_mining
/stlreal/monkey_learn.rb
UTF-8
523
2.703125
3
[]
no_license
require "net/http" require "uri" require 'json' uri = URI.parse("https://api.monkeylearn.com/api/v1/categorizer/cl_zD7UNmJE/classify_text/") http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true request = Net::HTTP::Post.new(uri.request_uri) # Set POST data request.body = {text: "This is a text to test the API."}.to_json # Set headers request.add_field("Content-Type", "application/json") request.add_field("Authorization", "token f83dd3a972990653b0122b3789b8f3531b58dd03") puts(http.request(request).body)
true
3f84eebccda933a665a37848b7d87e66a660c8ee
Ruby
Mcents/Battle_ship
/test/validate_test.rb
UTF-8
2,028
3
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require './lib/validate' require './lib/player' require './lib/game_board' require "pry" class TestValidate < Minitest::Test def test_can_generate_random_coordinates player = Player.new(GameBoard.new) coordinates = Validate.random_coordinate_generator(1, 4) assert Validate.valid_ship_placement?(player, 1, coordinates) end def test_it_can_fill_in_coords result = [[0, 0], [0, 1], [0, 2], [0, 3]] assert_equal result, Validate.coordinate_fill([0, 0], [0, 3]) end def test_can_tell_if_coordinates_are_same_column_or_row assert Validate.unique_row_and_column?([1, 3], [1, 0]) refute Validate.unique_row_and_column?([1, 3], [3, 1]) end def test_that_ships_not_placed_on_same_square player = Player.new(GameBoard.new) player.board.assign_square([0, 2], "S") player.board.assign_square([1, 3], "S") assert Validate.ships_not_placed_on_same_square?(player, [1,2], [2,4]) end def test_if_can_find_distance assert_equal 3, Validate.distance([0, 0], [0, 3]) end def test_that_diagonal_placement_is_not_possible player = Player.new(GameBoard.new) assert Validate.valid_ship_placement?(player, 3, [[1, 1], [1, 3]]) refute Validate.valid_ship_placement?(player, 3, [[2, 2], [3, 3]]) end def test_for_valid_human_attack player = Player.new(GameBoard.new) player.board.assign_square([1, 4], "H") refute Validate.valid_human_attack?('e1', player.board) end def test_if_coords_are_inbounds assert Validate.inbounds?([2,1]) refute Validate.inbounds?([8,4]) end def test_if_can_generate_valid_random_ship_placement player = Player.new(GameBoard.new) coords = Validate.random_coordinate_generator(1,3) assert Validate.valid_ship_placement?(player, 2, coords) end def test_if_valid_human_attack player = Player.new(GameBoard.new) player.board.assign_square([1,2], "H") assert Validate.valid_human_attack?("B1", player.board) end end
true
4c19e0b94c42e2df8902ac00da1633743932b01d
Ruby
cregg/coast2coast
/app/controllers/goals_controller.rb
UTF-8
1,164
2.546875
3
[]
no_license
class GoalsController < ApplicationController helper_method :weekly_team_goals, :goal_totals, :cumulative_team_goals def home end def weekly_team_goals(name) team_weeks = Week.where(team: name) team_goals_array = team_weeks.map {|y| y.goals} team_goals_array end def goal_totals weeks = Week.all.order(:team) results = Array.new(Array.new) name_and_goals = Array.new name = "At the Helm" total_goals = 0 weeks.each do |week| if week.team == name total_goals = week.goals + total_goals else name_and_goals = name_and_goals << name << total_goals results = results << name_and_goals name = week.team total_goals = week.goals name_and_goals = Array.new end end name_and_goals = name_and_goals << name << total_goals results = results << name_and_goals end def cumulative_team_goals(name) team_weeks = Week.where(team: name) team_goals_array = team_weeks.map {|y| y.goals} team_goals_array.each_index do |index| next if index == 0 team_goals_array[index] = team_goals_array[index] + team_goals_array[index-1] end team_goals_array end end
true
15787762b2722aa38fb89cb74ef79bd4dbfe1528
Ruby
zdennis/yap-shell-core
/lib/yap/cli/options/generate.rb
UTF-8
1,462
2.609375
3
[ "MIT" ]
permissive
module Yap module Cli class Options::Generate include OptionsLoader attr_reader :command, :options def initialize(options:) @options = options @exit_status = 0 end def parse(args) if args.empty? args.unshift '--help' STDERR.puts "generate must be called with a component type!" @exit_status = 1 puts end option_parser.order!(args) end def command @command ||= load_command('generate').new end private def option_parser OptionParser.new do |opts| opts.banner = <<-TEXT.gsub(/^\s*\|/, '') |Usage: #{opts.program_name} generate [component-type] [options] | |#{Term::ANSIColor.cyan('yap generate')} can be used to generate yap components, like an addon. | |Generate commands: | | #{Term::ANSIColor.yellow('addon')} - generates a yap addon skeleton | |Generate options: TEXT opts.on('-h', '--help', 'Prints this help') do puts opts puts puts <<-TEXT.gsub(/^\s*\|/, '') |Example: Generating an addon | | #{opts.program_name} generate addon magical-key-bindings | TEXT exit @exit_status end end end end end end
true
b0ad86fdf6047b8c7b489ff5e199b647a50a2525
Ruby
emblou2/ruby-challenges
/love_loop.rb
UTF-8
207
3.59375
4
[]
no_license
puts "Do you love me yet? Please answer Y/N:" answer = gets.chomp.downcase while (answer == "n") puts "Do you love me yet? Please answer Y/N:" answer = gets.chomp.downcase end puts "I love you too!"
true
059b9aaace7aa3d72458393e5a9a7a5cf7ecf18d
Ruby
makandra/rails
/rack/test/spec_lock.rb
UTF-8
4,447
2.90625
3
[ "MIT" ]
permissive
require 'rack/lint' require 'rack/lock' require 'rack/mock' class Lock attr_reader :synchronized def initialize @synchronized = false end def synchronize @synchronized = true yield end def lock @synchronized = true end def unlock @synchronized = false end end module LockHelpers def lock_app(app, lock = Lock.new) app = if lock Rack::Lock.new app, lock else Rack::Lock.new app end Rack::Lint.new app end end describe Rack::Lock do extend LockHelpers describe 'Proxy' do extend LockHelpers should 'delegate each' do env = Rack::MockRequest.env_for("/") response = Class.new { attr_accessor :close_called def initialize; @close_called = false; end def each; %w{ hi mom }.each { |x| yield x }; end }.new app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, response] }) response = app.call(env)[2] list = [] response.each { |x| list << x } list.should.equal %w{ hi mom } end should 'delegate to_path' do lock = Lock.new env = Rack::MockRequest.env_for("/") res = ['Hello World'] def res.to_path ; "/tmp/hello.txt" ; end app = Rack::Lock.new(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, res] }, lock) body = app.call(env)[2] body.should.respond_to :to_path body.to_path.should.equal "/tmp/hello.txt" end should 'not delegate to_path if body does not implement it' do env = Rack::MockRequest.env_for("/") res = ['Hello World'] app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, res] }) body = app.call(env)[2] body.should.not.respond_to :to_path end end should 'call super on close' do env = Rack::MockRequest.env_for("/") response = Class.new { attr_accessor :close_called def initialize; @close_called = false; end def close; @close_called = true; end }.new app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, response] }) app.call(env) response.close_called.should.equal false response.close response.close_called.should.equal true end should "not unlock until body is closed" do lock = Lock.new env = Rack::MockRequest.env_for("/") response = Object.new app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, response] }, lock) lock.synchronized.should.equal false response = app.call(env)[2] lock.synchronized.should.equal true response.close lock.synchronized.should.equal false end should "return value from app" do env = Rack::MockRequest.env_for("/") body = [200, {"Content-Type" => "text/plain"}, %w{ hi mom }] app = lock_app(lambda { |inner_env| body }) res = app.call(env) res[0].should.equal body[0] res[1].should.equal body[1] res[2].to_enum.to_a.should.equal ["hi", "mom"] end should "call synchronize on lock" do lock = Lock.new env = Rack::MockRequest.env_for("/") app = lock_app(lambda { |inner_env| [200, {"Content-Type" => "text/plain"}, %w{ a b c }] }, lock) lock.synchronized.should.equal false app.call(env) lock.synchronized.should.equal true end should "unlock if the app raises" do lock = Lock.new env = Rack::MockRequest.env_for("/") app = lock_app(lambda { raise Exception }, lock) lambda { app.call(env) }.should.raise(Exception) lock.synchronized.should.equal false end should "unlock if the app throws" do lock = Lock.new env = Rack::MockRequest.env_for("/") app = lock_app(lambda {|_| throw :bacon }, lock) lambda { app.call(env) }.should.throw(:bacon) lock.synchronized.should.equal false end should "set multithread flag to false" do app = lock_app(lambda { |env| env['rack.multithread'].should.equal false [200, {"Content-Type" => "text/plain"}, %w{ a b c }] }, false) app.call(Rack::MockRequest.env_for("/")) end should "reset original multithread flag when exiting lock" do app = Class.new(Rack::Lock) { def call(env) env['rack.multithread'].should.equal true super end }.new(lambda { |env| [200, {"Content-Type" => "text/plain"}, %w{ a b c }] }) Rack::Lint.new(app).call(Rack::MockRequest.env_for("/")) end end
true
3011a8d9f71dff22e1172c50a6fd8380286ea1c2
Ruby
Angel-Garcia-Fernandez/shopping-cart
/models/pricing_rule.rb
UTF-8
1,306
3.390625
3
[]
no_license
# Pricing Rule classes. The Standard one (PricingRule) and # its specialities (GetFree and BulkDiscount). # It makes pricing calculation, from quantity and price applying # a specific pricing rule. class PricingRule attr_reader :offer, :offer_opts, :price, :quantity def initialize @price, @quantity = 0, 0 end def calculate_price(price, quantity) @price, @quantity = price, quantity efective_price * efective_quantity end def efective_price price end def efective_quantity quantity end end # Accepts :from option that means how many items needed to # get one free. 'from: 3' is like 3x2. 'from: 2' is like 2x1 class GetFree < PricingRule def initialize(offer_opts) super() @quantity_limit = offer_opts[:from] || 2 end def efective_quantity free = quantity / @quantity_limit quantity - free end end # Also accepts :from option. Also :new_price for exact new price, # :discount_amount for a specific reduction of the price or # :discount_percentage for a proportional reduction in price. class BulkDiscount < PricingRule def initialize(offer_opts) super() @quantity_limit = offer_opts[:from] || 2 @new_price = offer_opts[:new_price] end def efective_price quantity >= @quantity_limit ? @new_price : price end end
true
29b04e02b4c492847e3f78d02bdd61fc160ae7dd
Ruby
CircleAround/calib-rails
/lib/calib/lang/namespace.rb
UTF-8
587
2.640625
3
[ "MIT" ]
permissive
module Calib module Lang # == A Class for Namespace class Namespace # array of Modlules of _cls_ def self.as_modules(cls, array = []) parent = cls.parent return array if parent == Object as_modules(parent, array.unshift(parent)) end # array of Symbols of _cls_ def self.as_symbols(cls) # @see https://stackoverflow.com/questions/133357/how-do-you-find-the-namespace-module-name-programmatically-in-ruby-on-rails as_modules(cls).map {|ns| ns.to_s.demodulize.underscore.to_sym } end end end end
true
4b5004d67e48ef0b2b889802b15599e9b1734628
Ruby
happygiraffe/svenbot
/test/svenbot/user_manager_test.rb
UTF-8
2,375
2.609375
3
[ "BSD-2-Clause" ]
permissive
$:.unshift File.join(File.dirname(__FILE__),'..','lib') require 'test/unit' require 'svenbot/commit' require 'svenbot/user_manager' module Svenbot class UserManagerTest < Test::Unit::TestCase attr_reader :um # Sample data A_JID = 'me@example.com' # More sample data ANOTHER_JID = 'you@example.com' def setup @um = UserManager.new end def test_register_user um.register A_JID, '/' assert_equal 1, um.users.size assert_equal ['/'], um.users[A_JID].paths assert_equal 1, um.paths.size assert_equal [A_JID], um.paths['/'].collect { |u| u.jid } end def test_register_two_users_same_path um.register A_JID, '/proj' um.register ANOTHER_JID, '/proj' assert_equal 2, um.users.size assert_equal ['/proj'], um.users[A_JID].paths assert_equal ['/proj'], um.users[ANOTHER_JID].paths assert_equal 1, um.paths.size assert_equal [A_JID, ANOTHER_JID], jids_for_path(um, '/proj').sort end def test_register_two_paths um.register A_JID, '/proj1' um.register A_JID, '/proj2' assert_equal 1, um.users.size assert_equal ['/proj1', '/proj2'], um.users[A_JID].paths assert_equal 2, um.paths.size assert_equal [A_JID], jids_for_path(um, '/proj1') assert_equal [A_JID], jids_for_path(um, '/proj2') end def test_unregister um.register A_JID, '/proj1' um.unregister A_JID, '/proj1' assert_equal 0, um.users.size assert_equal 0, um.paths.size end def test_users_for_path um.register(A_JID, '/proj1') assert_equal [A_JID], um.users_for('/proj1') end def test_users_for_path_empty um.register(A_JID, '/') assert_equal [A_JID], um.users_for('') end def test_users_for_path_understands_prefixes um.register(A_JID, '/') assert_equal [A_JID], um.users_for('/proj1') end def test_users_for_path_with_multiple_users um.register(A_JID, '/proj1') um.register(ANOTHER_JID, '/proj1') assert_equal [A_JID, ANOTHER_JID], um.users_for('/proj1') end def test_paths_for um.register A_JID, '/proj1' um.register A_JID, '/proj2' assert_equal %w[ /proj1 /proj2 ], um.paths_for(A_JID).sort end private def jids_for_path(bot, path) bot.paths[path].collect { |u| u.jid } end end end
true
e4b61ab0de5894e6af11b1a6a6776d1c11ce0776
Ruby
osteele/sitters.ios
/app/models/update.rb
UTF-8
1,032
2.53125
3
[]
no_license
class Update attr_reader :contact attr_reader :description attr_reader :timestamp def self.all @updates ||= self.json.map { |data| self.new(data) } end def self.unread @unread ||= self.all[0...3] end def self.clear @unread = [] end def initialize(data) @contact = data['contact'] @description = data['description'] @timestamp = data['timestamp'] end def image person ? person.image : UIImage.imageNamed("people/#{self.contact.downcase.gsub(/ /, '-')}.jpg") end def person Sitter.all.find { |sitter| sitter.name == self.contact } end def today? self.timestamp =~ /[AP]M$/ end private def self.json @json ||= begin path = NSBundle.mainBundle.pathForResource('updates', ofType:'json') content = NSString.stringWithContentsOfFile(path ,encoding:NSUTF8StringEncoding, error:nil) NSJSONSerialization.JSONObjectWithData(content.dataUsingEncoding(NSUTF8StringEncoding), options:NSJSONReadingMutableLeaves, error:nil) end end end
true
e19ff3353846cc26f0388897fa7b4ec4598c0af3
Ruby
IanEarley/LoreQuest
/char_name.rb
UTF-8
469
3.828125
4
[]
no_license
class CharacterName attr_reader :char_name def char_name @char_name = gets.chomp.capitalize if @char_name == "" puts "\nPlease enter a name\n\n" char_name end puts "\nSo, your name is #{@char_name}? (Y) yes (N) no" choice = gets.chomp.downcase if choice.casecmp("y") == 0 || choice.casecmp("yes") == 0 else puts "\nMy mistake, what was your name?\n\n" char_name end end def get_name @char_name end end
true
47dae1547542f98d7a6659145239f467834a7e7f
Ruby
philainza/tealeaf
/tealeaf_precourse/03_methods/problem3.rb
UTF-8
223
4.15625
4
[]
no_license
def multiply(num1, num2) num1 * num2 end puts "Please enter a number" input_num1 = gets.chomp.to_f puts "Please enter another number" input_num2 = gets.chomp.to_f puts "The product is #{multiply(input_num1, input_num2)}"
true
9f6b9971f743ba94dacedba783be0d59662a4eb3
Ruby
popemray00/parrot-ruby-v-000
/parrot.rb
UTF-8
158
3.375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Create method `parrot` that outputs a given phrase and # returns the phrase def parrot(pharse="Squawk!") puts pharse return pharse "Pretty bird!" end
true
5329cdecec17292ee95efe263ed1aaa0826500f8
Ruby
etehtsea/homebrew
/lib/homebrew/cmd/help.rb
UTF-8
1,076
2.6875
3
[ "BSD-2-Clause" ]
permissive
module Homebrew HOMEBREW_HELP = <<-EOS Example usage: brew install FORMULA... brew uninstall FORMULA... brew search [foo] brew list [FORMULA...] brew update brew selfupdate brew upgrade [FORMULA...] brew [info | home] [FORMULA...] Troubleshooting: brew doctor brew install -vd FORMULA brew [--env | --config] Brewing: brew create [URL [--no-fetch]] brew edit [FORMULA...] open https://github.com/mxcl/homebrew/wiki/Formula-Cookbook Further help: man brew brew home EOS # NOTE Keep the lenth of vanilla --help less than 25 lines! # This is because the default Terminal height is 25 lines. Scrolling sucks # and concision is important. If more help is needed we should start # specialising help like the gem command does. # NOTE Keep lines less than 80 characters! Wrapping is just not cricket. # NOTE The reason the string is at the top is so 25 lines is easy to measure! def help_s HOMEBREW_HELP end module Cmd def self.help puts HOMEBREW_HELP end end end
true
def12045e499de411d4b160b384b263f563318eb
Ruby
EDalSanto/LaunchSchool
/courses/180_Databases/todos/session_persistence.rb
UTF-8
1,359
3.03125
3
[]
no_license
class SessionPersistence attr_accessor :session def initialize(session) @session = session @session[:lists] ||= [] end def find_list(id) session[:lists].find{ |list| list[:id] == id } end def all_lists session[:lists] end def create_new_list(list_name) id = next_element_id(all_lists) all_lists << { id: id, name: list_name, todos: [] } end def delete_list(id) all_lists.reject! { |list| list[:id] == id } end def update_list_name(id, new_name) list = find_list(id) list[:name] = new_name end def create_new_todo(list_id, todo_name) list = find_list(list_id) todo_id = next_element_id(list[:todos]) list[:todos] << { id: todo_id, name: todo_name, completed: false } end def delete_todo_from_list(list_id, todo_id) list = find_list(list_id) list[:todos].reject! { |todo| todo[:id] == todo_id } end def update_todo_status(list_id, todo_id, new_status) list = find_list(list_id) todo = list[:todos].find { |t| t[:id] == todo_id } todo[:completed] = new_status end def mark_all_todos_as_completed(list_id) list = find_list(list_id) list[:todos].each do |todo| todo[:completed] = true end end private def next_element_id(elements) max = elements.map { |todo| todo[:id] }.max || 0 max + 1 end end
true
0c7d32ff5ba2769e541242ee50c1a69d12d1e2dc
Ruby
m-walker/practice-problems
/problems/13-capitalize-words.rb
UTF-8
1,209
4.8125
5
[]
no_license
# Write a method that takes in a string of lowercase letters and # spaces, producing a new string that capitalizes the first letter of # each word. # # You'll want to use the `split` and `join` methods. Also, the String # method `upcase`, which converts a string to all upper case will be # helpful. # # Difficulty: medium. def capitalize_words(string) array = string.split(" ") capitalized_array = [] array.each do |word| capitalized_array << word.capitalize end capitalized_array.join(" ") end def capitalize(string) array = string.split(" ") result_array = [] array.each do |word| word[0] = word[0].upcase result_array << word end result_array.join(" ") end # These are tests to check that your code is working. After writing # your solution, they should all print true. puts capitalize("this is a sentence") puts capitalize("mike bloomfield") puts capitalize_words("this is a sentence") puts capitalize_words("mike bloomfield") puts( 'capitalize_words("this is a sentence") == "This Is A Sentence": ' + (capitalize_words("this is a sentence") == "This Is A Sentence").to_s ) puts( 'capitalize_words("mike bloomfield") == "Mike Bloomfield": ' + (capitalize_words("mike bloomfield") == "Mike Bloomfield").to_s )
true
5bf1b5683063f171c4eed3e14cf61a58bf84364c
Ruby
husgom/RSS-Club
/app/models/company.rb
UTF-8
678
2.515625
3
[]
no_license
# create_table "companies", :force => true do |t| # t.string "name" # t.integer "status_id" # t.string "name_in_demand" # t.datetime "created_at" # t.datetime "updated_at" # end class Company < ActiveRecord::Base has_many :users belongs_to :status validates_presence_of :name def initialize(*params) super(*params) self.status_id = Status::Company::VALPENDING self.name_in_demand ||= '' end HUMANIZED_ATTRIBUTES = { :name => "Firma Adı", :status_id => "Durum", :name_in_demand => "İhalede görülecek firma adı" } def self.human_attribute_name(attr) HUMANIZED_ATTRIBUTES[attr.to_sym] || super end end
true
2f2039628cff5d91ff7de53d9b2a8eef24b09588
Ruby
antramm/RailsLookup
/rails_lookup.gemspec
UTF-8
7,133
3.390625
3
[]
no_license
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{rails_lookup} s.version = "0.0.3" s.required_rubygems_version = Gem::Requirement.new(">= 1.2") if s.respond_to? :required_rubygems_version= s.authors = [%q{Nimrod Priell}] s.date = %q{2011-08-09} s.description = %q{Lookup tables with ruby-on-rails -------------------------------- By: Nimrod Priell This gem adds an ActiveRecord macro to define memory-cached, dynamically growing, normalized lookup tables for entity 'type'-like objects. Or in plain English - if you want to have a table containing, say, ProductTypes which can grow with new types simply when you refer to them, and not keep the Product table containing a thousand repeating 'type="book"' entries - sit down and try to follow through. Installation is described down the page. Motivation ---------- A [normalized DB][1] means that you want to keep types as separate tables, with foreign keys pointing from your main entity to its type. For instance, instead of ID | car_name | car_type 1 | Chevrolet Aveo | Compact 2 | Ford Fiesta | Compact 3 | BMW Z-5 | Sports You want to have two tables: ID | car_name | car_type_id 1 | Chevrolet Aveo | 1 2 | Ford Fiesta | 1 3 | BMW Z-5 | 2 And car_type_id | car_type_name 1 | Compact 2 | Sports The pros/cons of a normalized DB can be discussed elsewhere. I'd just point out a denormalized solution is most useful in settings like [column oriented DBMSes][2]. For the rest of us folks using standard databases, we usually want to use lookups. The usual way to do this with ruby on rails is * Generate a CarType model using `rails generate model CarType name:string` * Link between CarType and Car tables using `belongs_to` and `has_many` Then to work with this you can transparently read the car type: car = Car.all.first car.car_type.name # returns "Compact" Ruby does an awesome job of caching the results for you, so that you'll probably not hit the DB every time you get the same car type from different car objects. You can even make this shorter, by defining a delegate to car_type_name from CarType: *in car_type_name.rb* delegate :name, :to => :car, :prefix => true And now you can access this as car.car_type_name However, it's less pleasant to insert with this technique: car.car_type.car_type_name = "Sports" car.car_type.save! #Now let's see what happened to the OTHER compact car Car.all.second.car_type_name #Oops, returns "Sports" Right, what are we doing? We should've used car.update_attributes(car_type: CarType.find_or_create_by_name(name: "Sports")) Okay. Probably want to shove that into its own method rather than have this repeated in the code several times. But you also need a helper method for creating cars that way… Furthermore, ruby is good about caching, but it caches by the exact query used, and the cache expires after the controller action ends. You can configure more advanced caches, perhaps. The thing is all this can get tedious if you use a normalized structure where you have 15 entities and each has at least one 'type-like' field. That's a whole lot of dangling Type objects. What you really want is an interface like this: car.all.first car.car_type #return "Compact" car.car_type = "Sports" #No effect on car.all.second, just automatically use the second constant car.car_type = "Sedan" #Magically create a new type Oh, and it'll be nice if all of this is cached and you can define car types as constants (or symbols). You obviously still want to be able to run: CarType.where (:id > 3) #Just an example of supposed "arbitrary" SQL involving a real live CarType class But you wanna minimize generating these numerous type classes. If you're like me, you don't even want to see them lying around in app/model. Who cares about them? I've looked thoroughly for a nice rails solution to this, but after failing to find one, I created my own rails metaprogramming hook. Installation ------------ First, run `gem install rails_lookup` to install the latest version of the gem. The result of this hook is that you get the exact syntax described above, with only two lines of code (no extra classes or anything): In your ActiveRecord object simply add require 'active_record/lookup' class Car < ActiveRecord::Base #... include ActiveRecord::Lookup lookup :car_type #... end That's it. the generated CarType class (which you won't see as a car_type.rb file, obviously, as it is generated in real-time), contains some nice methods to look into the cache as well: So you can call CarType.id_for "Sports" #Returns 2 CarType.name_for 1 #Returns "Compact" and you can still hack at the underlying ID for an object, if you need to: car = car.all.first car.car_type = "Sports" car.car_type_id #Returns 2 car.car_type_id = 1 car.car_type #Returns "Compact" The only remaining thing is to define your migrations for creating the actual database tables. After all, that's something you only want to do once and not every time this class loads, so this isn't the place for it. However, it's easy enough to create your own scaffolds so that rails generate migration create_car_type_lookup_for_car will automatically create the migration class CreateCarTypeLookupForCar < ActiveRecord::Migration def self.up create_table :car_types do |t| t.string :name t.timestamps #Btw you can remove these, I don't much like them in type tables anyway end remove_column :cars, :car_type #Let's assume you have one of those now… add_column :cars, :car_type_id, :integer #Maybe put not_null constraints here. end def self.down drop_table :car_types add_column :cars, :car_type, :string remove_column :cars, :car_type_id end end I'll let you work out the details for actually migrating the data yourself. [1] http://en.wikipedia.org/wiki/Database_normalization [2] http://en.wikipedia.org/wiki/Column-oriented_DBMS I hope this helped you and saved a lot of time and frustration. Follow me on twitter: @nimrodpriell } s.email = %q{@nimrodpriell} s.extra_rdoc_files = [%q{README}, %q{lib/active_record/lookup.rb}] s.files = [%q{README}, %q{Rakefile}, %q{lib/active_record/lookup.rb}, %q{rails_lookup.gemspec}, %q{test/20110808002412_create_test_lookup_db.rb}, %q{test/test_lookup.rb}] s.homepage = %q{http://github.com/Nimster/RailsLookup/} s.rdoc_options = [%q{--line-numbers}, %q{--inline-source}, %q{--title}, %q{Rails_lookup}, %q{--main}, %q{README}] s.require_paths = [%q{lib}] s.rubyforge_project = %q{rails_lookup} s.rubygems_version = %q{1.8.7} s.summary = %q{Lookup table macro for ActiveRecords} s.test_files = [%q{test/test_lookup.rb}] if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then else end else end end
true
571e539a5ecad404eb8228aa0961e435758a4787
Ruby
learn-co-students/atlanta-web-033020
/10-activerecord-associations/app/app_cli.rb
UTF-8
1,989
3.546875
4
[]
no_license
class AppCLI def lists_users User.all.each do |user| puts "#{user.id}: #{user.name}" end end def login puts "===========================" puts "Login here" puts "===========================" puts "List of Users:" puts "===========================" lists_users puts "===========================" puts "Enter user id:" user_id = gets.chomp user = User.find_by(id: user_id) if user.nil? puts " " puts "ERRORR!!!" puts "User doesn't exist! Try again 🛑" puts " " login else welcome(user) end end def welcome(user) puts "===========================" puts "Welcome, #{user.name}!!!" puts "===========================" puts "Enter message:" puts "===========================" message = gets.chomp create_tweet(message,user) end def create_tweet(message,user) Tweet.create(message: message, user_id: user.id) puts "Tweet created successfully..." lists_tweets end def lists_tweets Tweet.all.each do |tweet| puts "#{tweet.user.name} says: #{tweet.message}" end end def show_options puts "1. Login" puts "2. Create A User" puts "3. Timeline" puts "4. Quit" end def main_menu # show_options # choice didn't go back to being nil after we ran a function # hence moving the choice inside the until block fixed it.. choice = nil until choice == 4 show_options puts "++++++++++++++++++++" puts "Enter your choice: " puts "++++++++++++++++++++" choice = gets.chomp.to_i puts "++++++++++++++++++++" case choice when 1 login when 2 puts "This is where you create a user" when 3 lists_tweets when 4 puts "Exiting... BYE" else puts "It invalid 🛑" end end end def run puts "Welcome to Teen Twitter!" main_menu end end
true
3b4e69e3f0e35876da4a82beec7f8f7b435cb375
Ruby
ahoward/ro
/lib/ro/template.rb
UTF-8
3,463
2.59375
3
[]
no_license
module Ro class Template require 'rouge' require 'kramdown' require 'kramdown-parser-gfm' require_relative 'template/rouge_formatter' def self.render(*args, &block) render_file(*args, &block) end def self.render_file(path, options = {}) path = File.expand_path(path.to_s.strip) options = Map.for(options.is_a?(Hash) ? options : { context: options }) content = IO.binread(path).force_encoding('utf-8') engines = File.basename(path).split('.')[1..-1].reverse context = options[:context] render_string(content, path: path, engines: engines, context: context) end def self.render_string(content, options = {}) content = String(content).force_encoding('utf-8') options = Map.for(options.is_a?(Hash) ? options : { context: options }) engines = Array(options.fetch(:engines) { ['erb'] }).flatten.compact path = options.fetch(:path) { '(string)' } context = options[:context] loop do break if engines.empty? engine = engines.shift.to_s.strip.downcase content = case engine when 'yml' YAML.load(content) when 'json' JSON.parse(content) when 'md', 'markdown' render_markdown(content) else tilt = Tilt[engine] Ro.error!("no rendering engine for path=#{path}, engine=#{engine}!") unless tilt render_partials = proc do |*_args| nil end tilt.new { content }.render(context, &render_partials) end end content end def self.render_markdown(content, options = {}) content = String(content).force_encoding('utf-8') options = Map.for(options.is_a?(Hash) ? options : { context: options }) theme = options.fetch(:theme) { 'github' } opts = { input: 'GFM', syntax_highlighter: 'rouge', syntax_highlighter_opts: { formatter: RougeFormatter, theme: theme } } ::Kramdown::Document.new(content, opts).to_html end def self.render_source(path, options = {}) path = File.expand_path(path.to_s.strip) options = Map.for(options.is_a?(Hash) ? options : { context: options }) content = IO.binread(path).force_encoding('utf-8') engines = File.basename(path).split('.')[1..-1].reverse context = options[:context] theme = options.fetch(:theme) { 'github' } language = engines.shift formatter = RougeFormatter.new(theme) lexer = Rouge::Lexer.find(language) || Ro.error!('no lexer found for ') content = render_string(content, path: path, engines: engines, context: context) if engines.size.nonzero? formatter.format(lexer.lex(content)) end end end if $0 == __FILE__ require_relative '../ro' if ARGV[0] path = ARGV[0] html = Ro::Template.render(path) puts html else context = Class.new do def initialize @date = Date.today end attr_reader :date end.new string = <<~____ <%= date %> --- - a - b - c ```ruby class C @ANSWER = 42 end a = 42 b = 42.0 ``` ____ html = Ro::Template.render_string(string, engines: %w[erb md], context: context) puts html puts '<hr /><hr /><hr />' html = Ro::Template.render_source(__FILE__) puts html end end
true
c6e2a9649ba825b5a67cada6829de9eb3ab0dd7d
Ruby
alu0100996081/P10-LPP
/lib/gema/lista.rb
UTF-8
4,662
3.453125
3
[ "MIT" ]
permissive
Node = Struct.new(:value, :nest, :prev) class List include Enumerable attr_reader :head, :tail def initialize(head, tail) @head = head @tail = tail end #inserta en la lista por la cola def insert_tail(value) nodo = Node.new(value,nil,nil) if(@tail == nil) @tail = nodo @head = nodo else nodo.prev = @tail @tail.nest = nodo @tail = nodo nodo.nest = nil end end #devuelve el valor de la cola def get_tail if(@tail == nil) puts "List Empty" else aux = @tail @tail = @tail.prev aux.prev = nil if(@tail!=nil) @tail.nest=nil end end return aux end #inserta por la cabeza def insert_head(value) nodo = Node.new(value,nil,nil) if(@head == nil) @tail = nodo @head = nodo else nodo.nest = @head @head.prev = nodo @head = nodo nodo.prev = nil end end #devuelve el elemento de cabeza de la lista def get_head if(@head == nil) puts "List Empty" else aux = @head @head = @head.nest if(head!=nil) @head.prev = nil end aux.nest = nil if(@head == nil) @tail = nil end end return aux end #comprueba si la lista esta vacia def vacio if(@tail==nil) return true else return false end end #imprime la lista def to_s puntero=@head cadena='[' if(@head!=nil) while (puntero!= nil) do cadena+=puntero.value.to_s + ']' if(puntero.nest!=nil) puntero=puntero.nest cadena+= '[' else puntero=nil end end end end #calcula los cases de los elementos d la lista def gases puntero=@head gases=0 if(@head!=nil) while(puntero!=nil) do gases+=puntero.value.gei if(puntero.nest!=nil) puntero=puntero.nest else puntero=nil end end end return gases end #calcula los gases de la lista def tierras puntero=@head gases=0 if(@head!=nil) while(puntero!=nil) do gases+=puntero.value.terreno if(puntero.nest!=nil) puntero=puntero.nest else puntero=nil end end end return gases end #calcula la energia total de los elementos de la lista def energia puntero=@head energia=0 if(@head!=nil) while(puntero!=nil) do energia+=puntero.value.energia if(puntero.nest!=nil) puntero=puntero.nest else puntero=nil end end end return energia end #devuleve el total de proteinas de la lista def get_proteinas puntero=@head total_proteinas=0 if(@head!=nil) while(puntero!=nil) do total_proteinas+=puntero.value.proteinas if(puntero.nest!=nil) puntero=puntero.nest else puntero=nil end end end return total_proteinas end #devuelve el total de nutrientes def get_nutrientes puntero=@head total_nutrientes=0 if(@head!=nil) while(puntero!=nil) do total_nutrientes+=puntero.value.proteinas + puntero.value.chidratos + puntero.value.lipidos if(puntero.nest!=nil) puntero=puntero.nest else puntero=nil end end end return total_nutrientes end #devuelve el total de lipidos def get_lipidos puntero=@head total_lipidos=0 if(@head!=nil) while(puntero!=nil) do total_lipidos+=puntero.value.lipidos if(puntero.nest!=nil) puntero=puntero.nest else puntero=nil end end end return total_lipidos end #devuelve el total de hidratos def get_chidratos puntero=@head total_chidratos=0 if(@head!=nil) while(puntero!=nil) do total_chidratos+=puntero.value.chidratos if(puntero.nest!=nil) puntero=puntero.nest else puntero=nil end end end return total_chidratos end #metodo enumerable def each(&block) puntero = @head while(puntero!=nil) do yield puntero.value puntero = puntero.nest end end end
true
2e2a8729f22069d3b885a89edd63edf577c9f47b
Ruby
TylerSell/sinatra-basic-routes-lab-v-000
/app.rb
UTF-8
282
2.515625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require_relative 'config/environment' class App < Sinatra::Base get '/name' do 'My name is Tyler Sell' end get '/hometown' do 'My hometown is Clinton, MO.' end get '/favorite-song' do 'My favorite song is "The City Never Sleeps" by Cartel.' end end
true
4d5137f980626a9784adb7d717987a668c0b5288
Ruby
cucumber/html-formatter
/ruby/lib/cucumber/html_formatter.rb
UTF-8
1,551
2.8125
3
[ "MIT" ]
permissive
require 'cucumber/messages' require 'cucumber/html_formatter/template_writer' require 'cucumber/html_formatter/assets_loader' module Cucumber module HTMLFormatter class Formatter attr_reader :out def initialize(out) @out = out @pre_message_written = false @first_message = true end def process_messages(messages) write_pre_message messages.each { |message| write_message(message) } write_post_message end def write_pre_message return if @pre_message_written out.puts(pre_message) @pre_message_written = true end def write_message(message) unless @first_message out.puts(',') end out.print(message.to_json) @first_message = false end def write_post_message out.print(post_message) end private def assets_loader @assets_loader ||= AssetsLoader.new end def pre_message [ template_writer.write_between(nil, '{{css}}'), assets_loader.css, template_writer.write_between('{{css}}', '{{messages}}') ].join("\n") end def post_message [ template_writer.write_between('{{messages}}', '{{script}}'), assets_loader.script, template_writer.write_between('{{script}}', nil) ].join("\n") end def template_writer @template_writer ||= TemplateWriter.new(assets_loader.template) end end end end
true
f75b4e88492af6e9db94c87f8ca48baaadc52a41
Ruby
ab16ruby/kelimeoynu
/app.rb
UTF-8
1,707
3.484375
3
[]
no_license
require('terminal-color') require('./yuksekpuan.rb') class App def self.ana_menu puts `clear` puts "KELİME OYUNUNA HOŞGELDİNİZ".bold.magenta puts "--------------------------".bold puts "Lütfen bir seçim yapın:" puts " " puts "1- OYUNA BAŞLA".bold.red puts "2- YÜKSEK PUANLAR".bold.blue puts "3- KELİME EKLE".bold.yellow puts "E- ÇIK".bold puts " " print "Seçiminiz: ".bold gets.chomp.upcase end def self.oyun_sonu(mesaj=nil) puts " " puts " " puts "---".bold puts "Çıkmak için E, Ana Menü için A#{mesaj.nil? ? "" : ", " + mesaj} yazınız: ".bold puts "---".bold print "Seçiminiz: ".bold gets.chomp.upcase end def self.yuksek_puan puanlar i = 1 puts "##{" " * 15}Kullanıcı#{" " * 15}Puan".bold puts "--------------------------------------------".bold puanlar.liste2.each do |kayit| veri = kayit.split(',') puts "#{i}#{" " * 15}#{veri[0]}#{" " * (24 - veri[0].length)}#{veri[1]}".bold i += 1 end end def self.basarili(kelime, kullanici, puan) puts " " puts "-----------".bold puts "TEBRİKLER #{kullanici}! Aranan kelimeyi buldunuz.".bold.green puts "Kelime: #{kelime}".bold.yellow puts "Kazandığınız Puan: #{puan}".bold.magenta yeniSkor = YuksekPuan.new() yeniSkor.ekle("#{kullanici},#{puan}") end def self.hatali(kelime, kullanici, puan) puts " " puts " " puts "-----------".bold puts "OYUN BİTTİ #{kullanici.bold.yellow}!".bold.red puts "Aranan kelimeyi bulamadınız.".bold puts "Kelime: #{kelime.green}".bold.yellow puts "Kazandığınız Puan: #{puan}".bold.magenta end def self.temizle puts `clear` end def self.mesaj mesaj puts " "; puts mesaj end end
true
3d3d9eccee6e06c7213dd73b08df02431c631e08
Ruby
icyleaf/teambition2
/lib/teambition2/api/stage_template.rb
UTF-8
620
2.515625
3
[ "MIT" ]
permissive
module Teambition2 module API module StageTemplate def stage_templates get('/api/stagetemplates') end def stage_template(title, key: 'title', limit: 1) result = stage_templates.select { |p| p[key].include?(title) } return nil if result.empty? case limit when 0 result when 1 result[0] else result.size >= limit ? result[0..limit] : result end end def create_stage_template(title, stages) post('/api/stagetemplates', { title: title, stages: stages } ) end end end end
true
64ed8c5f2234d7c25020b06245d4848d20cd166d
Ruby
troessner/reek
/lib/reek/ast/sexp_extensions/if.rb
UTF-8
1,129
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Reek module AST module SexpExtensions # Utility methods for :if nodes. module IfNode # # @return [Reek::AST::Node] the condition that is associated with a conditional node. # For instance, this code # # if charlie(bravo) then delta end # # would be parsed into this AST: # # s(:if, # s(:send, nil, :charlie, # s(:lvar, :bravo)), # s(:send, nil, :delta), nil) # # so in this case we would return this # # s(:send, nil, :charlie, # s(:lvar, :bravo)) # # as condition. # def condition children.first end # @quality :reek:FeatureEnvy def body_nodes(type, ignoring = []) children[1..].compact.flat_map do |child| if ignoring.include? child.type [] else child.each_node(type, ignoring | type).to_a end end end end end end end
true
df82ef72d6e6d4b9dbbd7d927a2208541ad43f0b
Ruby
ReLearnDeveloper/Ironhack-Web-Development
/week2/stubs_and_fakes/spec/stubs_and_fakes_spec.rb
UTF-8
693
2.609375
3
[]
no_license
require 'rspec' require_relative '../stubs_and_fakes' require 'pry' RSpec.describe 'WordChecker' do # @subjects = [ # "urgent", # "very urgent", # "good morning", # "very important", # "I love good morning" # ] describe 'check' do it "should return false if no subject given" do provider = EmailProviderFake.new(Array.new) checker = WordChecker.new(provider) expect(checker.check([])).to eq(true) end it "should return true when a word is included in subject" do provider = EmailProviderFake.new([]) checker = WordChecker.new(provider) expect(checker.check(["hello"])).to eq(false) end end end
true
5b0b8199d3a864363a5a74442913ddd24036db6d
Ruby
charleneChen/conference_track_management
/lib/talk.rb
UTF-8
668
3.921875
4
[]
no_license
class Talk # getters attr_reader :name, :minutes # input: String - name, minutes def initialize(name, minutes) @name = name @minutes = minutes end # Returns an integer def getMinutes @minutes.to_i end # input: an array of Talk instances # output: an integer def self.computeTotalTime(talks) total_time = 0 talks.each do |talk| time = talk.getMinutes total_time += time end return total_time end # input: an instance of Talk # output: true or false def eqlTo?(talk) if (self.name == talk.name && self.minutes == talk.minutes) return true else return false end end end
true
066bcac7f9d95e997022473d8f9544a3e137f404
Ruby
violake/element_search
/lib/data_search/base_search.rb
UTF-8
1,443
3.046875
3
[]
no_license
require 'data_search/searchable' ## DataSearch::BaseSearch Class # # Aim: search element by key value # # Design: with the searchable module, it just need to search the element_hash or search_hash # # Concern: 1. made assumption that all element keys are used for searching # 2. return empty array when could not find element by search value # this will also prevent and edge case when there are error associations # module DataSearch class BaseSearch extend ::DataSearch::Searchable class << self def search_keys search_hash.keys.unshift id_key end def valid_search_key?(key) search_keys.include?(key) end def find_elements_by_search_key(key, value) unless valid_search_key?(key) raise NoSearchKeyError, "Key(#{key}) is invalid for #{name}" end if key == id_key find_elements_by_id_key(value) else find_elements_by_search_hash_key(key, value) end end private def id_key @id_key ||= :_id end def find_elements_by_id_key(id) element = element_hash[id] element.nil? ? [] : [element_hash[id]] end def find_elements_by_search_hash_key(key, value) ids = search_hash[key][value] || [] element_hash.values_at(*ids) end end end class NoSearchKeyError < StandardError; end end
true
d6697dce9f2bc5d9a404c4f4a58e49044589d861
Ruby
mpokropowicz/tic_tac_toe
/app.rb
UTF-8
2,163
2.953125
3
[]
no_license
require "sinatra" require_relative "web_game.rb" require_relative "random_ai.rb" require_relative "unbeatable_ai.rb" require_relative "human.rb" enable :sessions get "/" do erb :start end get "/game" do session[:p1] = params[:p1] + "1" session[:p2] = params[:p2] + "2" session[:game] = WebGame.new(session[:p1], session[:p2], 3, 3) session[:p1human] = session[:game].p1.class == HumanPlayer ? "text" : "hidden" session[:p2human] = session[:game].p2.class == HumanPlayer ? "text" : "hidden" redirect "/p1" end get "/p1" do session[:game].change_player redirect "/p1human" if session[:game].p1.class == HumanPlayer move = session[:game].current_player.move_pos(session[:game].board) session[:game].make_move(move) redirect "/winner" if session[:game].winner? || session[:game].board.all_spots_occupied? redirect "p2" if session[:game].p2.class == HumanPlayer erb :p1 end get "/p1human" do erb :p1 end post "/p1human" do move = session[:game].current_player.move_pos_web(session[:game].board, params[:p1humanmove][0].to_i) - 1 session[:game].make_move(move) redirect "/winner" if session[:game].winner? || session[:game].board.all_spots_occupied? redirect "/p2" end get "/p2" do session[:game].change_player redirect "/p2human" if session[:game].p2.class == HumanPlayer move = session[:game].current_player.move_pos(session[:game].board) session[:game].make_move(move) redirect "/winner" if session[:game].winner? || session[:game].board.all_spots_occupied? redirect "p1" if session[:game].p1.class == HumanPlayer erb :p2 end get "/p2human" do erb :p2 end post "/p2human" do move = session[:game].current_player.move_pos_web(session[:game].board, params[:p2humanmove][0].to_i) - 1 session[:game].make_move(move) redirect "/winner" if session[:game].winner? || session[:game].board.all_spots_occupied? redirect "/p1" end get "/winner" do result = session[:game].current_player.marker == "X" ? "boardleft" : "boardright" winner = session[:game].winner? ? "#{session[:game].current_player.marker} has won the game!" : "It's a tie!" erb :winner, :locals => {result: result, winner: winner} end
true
20562e5958fef17487f276a93d12a4e35f5ce477
Ruby
thefrontiergroup/smeg-head
/lib/repository_manager.rb
UTF-8
3,408
2.921875
3
[]
no_license
require 'angry_shell' require 'fileutils' # The Repository Manager class acts a base for performing operations on a given repository. # This includes things such as manipulating and getting the state of the repository. class RepositoryManager class Error < StandardError; end class NonexistantRepository < Error; end attr_reader :repository def self.base_path Rails.root.join("repositories", Rails.env) end # Initializes a new repository manager with the given repository. def initialize(repository) @repository = repository end # Returns the directory name for this git repository. # @return [String] the directory name for this repository def directory_name @directory_name ||= "#{repository.identifier}.git" end # Gets a pathname object for the path to this repository. # @return [Pathname] the path to the current repository def path @path ||= self.class.base_path.join(directory_name) end # When it doesn't exist, creates (and initializes) a git bare repository. def create! return if path.exist? FileUtils.mkdir_p path in_repository do # TODO: Add a way to hook into the results of creating the repository. # E.g. so we can have post-create hooks. cmd(:git, '--bare', :init).ok? end end def destroy! FileUtils.rm_rf(path) if path.exist? end # Yields a block whilst in a given directory. # Used for situations where we want to run git commands. def in_repository Dir.chdir(path) { yield if block_given? } end def to_grit raise NonexistantRepository.new("The given repository does not exist") unless path.exist? Grit::Repo.new path end # Starts receive-pack in the repository. def receive_pack! exec_in_repo! "git-receive-pack", path.to_s end # Starts upload-pack inside the repository. def upload_pack! exec_in_repo! "git-upload-pack", path.to_s end private # Shell Code taken from stuff I (Darcy) wrote for RVM # Takes an array / number of arguments and converts # them to a string useable for passing into a shell call. def escape_arguments(*args) return if args.blank? args.flatten.map { |a| escape_argument(a.to_s) }.join(" ") end # Given a string, converts to the escaped format. This ensures # that things such as variables aren't evaluated into strings # and everything else is setup as expected. def escape_argument(s) return "''" if s.empty? s.scan(/('+|[^']+)/).map do |section| section = section.first if section[0] == ?' "\\'" * section.length else "'#{section}'" end end.join end # From a command, will build up a runnable command. If args isn't provided, # it will escape arguments. def build_command(command, *args) "#{command} #{escape_arguments(args)}".strip end # Runs a command inside the git repository, using exec and git-shell to avoid # the most common security attacks. def exec_in_repo!(*args) command = build_command('git-shell', '-c', *args) Dir.chdir path logger.info "Executing command in repo: \"#{command}\" in #{Dir.pwd}" exec *args end def cmd(*args, &blk) options = args.extract_options! command = build_command(*args) AngryShell::Shell.new(options.merge(:cmd => command), &blk) end def logger Rails.logger end end
true
75c87616a5c5b0bced28b3114d3456050cd27bde
Ruby
navry/es_rmduplicates
/es-rmduplicates.rb
UTF-8
5,864
2.625
3
[]
no_license
#!/usr/bin/env ruby #encoding:utf-8 require 'rubygems' require 'tire' require 'yajl/json_gem' require 'digest/sha1' VERSION = '0.0.2' STDOUT.sync = true # PARAMETERS __START__ def printHelp STDERR.puts "Script to search and remove duplicites dates from ES. Usage: #{__FILE__} <URL>/<INDEX> <ARGUMENTS> Required arguments: -i path to id (_id) -t path to type (_type) -d path to date (_source/date) -c path to duplicite content (_source/content) Examples: #{__FILE__} http://localhost:9200/database -i _id -t _type \\ -d _source/date -c _source/content > output.txt #(the best) #{__FILE__} http://localhost:9200/database -i _id -t _type \\ -d _source/date -c _source/content 2>&1 /dev/null for silent mode In first example there will be counter displayed on stderr\n" end if ARGV[0] if ARGV[0] =~ /^-(?:h|-?help)$/ printHelp exit 0 elsif ARGV[0] =~ /^-/ puts "#{__FILE__}: unknown parameter,\n use #{__FILE__} -h for help" exit 1 end else printHelp exit 1 end param,param_content,param_date,param_type,param_id = nil,nil,nil,nil,nil while ARGV[0] case arg = ARGV.shift when '-h' then printHelp exit 0 when '-c' then param_content = ARGV.shift when '-d' then param_date = ARGV.shift when '-t' then param_type = ARGV.shift when '-i' then param_id = ARGV.shift else !param ? (param = arg) : raise("Unexpected parameter '#{arg}'. Use '-h' for help.") end end urlS, index = '', '' if param =~ %r{^http://(.*?)/(.*?)$} urlS.replace $1 index.replace $2 else STDERR.puts "Url was not correct specified. Use '-h' for help" exit 1 end if param_content == nil || param_date == nil || param_type == nil || param_id == nil then STDERR.puts "Arguments were not fully specified. Use '-h' for help" exit 1 end # PARAMETERS __END__ STDERR.print "Url:", urlS, " index:", index, "\n" def retried_request method, url, data=nil """ Function for sending query to ES """ while true begin return data ? RestClient.send(method, url, data) : RestClient.send(method, url) rescue RestClient::ResourceNotFound # no point to retry puts "ERROR: no point to retry" return nil rescue => e warn "\nRetrying #{method.to_s.upcase} ERROR: #{e.class} - #{e.message}" end end end def tm_len l """ Function for converting time to legible form """ t = [] t.push l/86400; l %= 86400 t.push l/3600; l %= 3600 t.push l/60; l %= 60 t.push l out = sprintf '%u', t.shift out = out == '0' ? '' : out + ' days, ' out += sprintf('%u:%02u:%02u', *t) out end t, done = Time.now, 0 # COUNTER data = Hash.new {|h,k| h[k]=[]} shards = retried_request :get, "#{urlS}/#{index}/_count?q=*" shards = Yajl::Parser.parse(shards)['_shards']['total'].to_i scan = retried_request(:get, "#{urlS}/#{index}/_search" + "?search_type=scan&scroll=10m&size=#{1000 / shards}") scan = Yajl::Parser.parse scan scroll_id = scan['_scroll_id'] total = scan['hits']['total'] def trip (item, way) for each in way.split('/') do item = item[each] end return item end # LOAD DATABASE __START__ # Test to existed JSON paths predata = retried_request(:get, "#{urlS}/_search/scroll?scroll=10m&scroll_id=#{scroll_id}") # Get predata = Yajl::Parser.parse predata [param_content,param_date,param_type,param_id].each do |param| begin if trip(predata['hits']['hits'][0], param) == nil then STDERR.puts "ERROR: Invalid JSON path: #{param}" exit 1 end rescue NoMethodError STDERR.puts "ERROR: Invalid JSON path: #{param}" exit 1 end end while true do #(7..10).each do #DEBUG for 2000 tests predata = retried_request(:get, "#{urlS}/_search/scroll?scroll=10m&scroll_id=#{scroll_id}") # Get predata = Yajl::Parser.parse predata break if predata['hits']['hits'].empty? scroll_id = predata['_scroll_id'] predata['hits']['hits'].each{ | doc | sha1 = Digest::SHA1.hexdigest(trip(doc,param_content)) # calculate hash data[sha1].push(doc) # Add new document to hash done += 1 # COUNTER #print data[sha1][0]['_source']['content'] # DEBUG } eta = total * (Time.now - t) / done # COUNTER STDERR.printf " LOAD: %u/%u (%.1f%%) done in %s, E.T.A.: %s.\r", # COUNTER done, total, 100.0 * done / total, tm_len(Time.now - t), t + eta # COUNTER end # LOAD DATABASE __END__ STDERR.puts # FORMATING OUTPUT total = done # COUNTER done = 0 # COUNTER count = 0 # COUNTER # REMOVE DUPLICITES __START__ data.each do |arr| if arr[1].length > 1 then # if is more documents on same hash count += 1 # DEBUG arr[1].sort_by! { |item| # sort via Date/Time trip(item,param_date) }.reverse! print count,"#",arr[1][0],"\n" # DEBUG arr[1].delete_at 0 # Remove first document (the oldes, don't remove from ES) arr[1].each do |item| # Remove remaining documents in array id = trip(item,param_id) date = trip(item,param_date) type = trip(item,param_type) print count,"#",arr[0],"#",id,"#",date,"\n" # DEBUG RestClient.send(:delete, "#{urlS}/#{index}/#{type}/#{id}") end end done += 1 # COUNER eta = total * (Time.now - t) / done # COUNTER STDERR.printf "DELETE: %u/%u (%.1f%%) done in %s, E.T.A.: %s.\r", # COUNTER done, total, 100.0 * done / total, tm_len(Time.now - t), t + eta # COUNTER end # REMOVE DUPLICITES __END__ STDERR.puts # FORMATING OUTPUT
true
bd7a1a5d6c4ab180c1ceaaf36805f6936255c6ae
Ruby
Shawniii/Fort-Prog
/quick_sort.rb
UTF-8
630
3.515625
4
[]
no_license
def swap!(a,i,j) help = a[i] a[i] = a[j] a[j] = help end def q_sort!(a,l,r) swap!(a,l,l+rand(r-l)) if l>=r then return a else m = l for i in l+1 .. r do if a[i] < a[m] then help = a [i] a[i] = a[m+1] a[m+1] = a[m] a[m] = help m = m + 1 end end q_sort!(a,l,m-1) q_sort!(a,m+1,r) end end def quick_sort!(a) q_sort!(a,0,a.size-1) end def random_array(n) a = Array.new(n) a.map {|x| Random.rand(n) } end #a = [5,1,3,8,7,6,2,9,4] #a = random_array(10000) a = Array.new(10000000) for i in 0..a.size-1 do a[i] = i end quick_sort!(a)
true
7eabeefa1e9237a95951b256dc7fb79758e036b5
Ruby
knife/nlp
/lib/tagger/sentence.rb
UTF-8
322
3.171875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module NLP class Sentence attr_reader :tokens def initialize() @tokens = [] end def << tokens if tokens.is_a? Array @tokens.concat tokens else @tokens << tokens end self end def words_number @tokens.count{|t| !t.interp?} end end end
true
0b349823c9838ce212ff63e448008b8e270f5b4b
Ruby
Hama99o/Ruby2
/Exo2_corrected.rb
UTF-8
555
3.46875
3
[]
no_license
#allData student_percentage= { Peter: "80%", Michel: "68%", Martin: "60%", Thomas: "58%", Richard: "45%", Robert: "38%" } student_roll_numbers = { "678": "Peter", "677": "Michel", "676": "Martin", "675": "Thomas", "674": "Richard", "673": "Robert" } def main puts "Enter your roll number" $get_roll_number = gets.chomp.to_sym end main student_name = student_roll_numbers[$get_roll_number] if student_name percentage = student_percentage[student_name.to_sym] if percentage puts "#{student_name} has #{percentage}" end end
true
26bc981af5f40112f84ec15f7108f7787a1a902b
Ruby
YashUppal/appAcademy
/Intro to Programming/Arrays/doubler.rb
UTF-8
439
4.625
5
[]
no_license
# Write a method doubler(numbers) that takes an array of numbers and returns a new array # where every element of the original array is multiplied by 2. def doubler(numbers) double_arr = [] iterator = 0 while iterator < numbers.length double_arr << numbers[iterator] * 2 iterator = iterator + 1 end return double_arr end print doubler([1, 2, 3, 4]) # => [2, 4, 6, 8] puts print doubler([7, 1, 8]) # => [14, 2, 16]
true
ff8ebb1bf03fadbfd7f91a9b3260c10667c0ee44
Ruby
cloudfoundry-attic/git_pipeline
/app/models/git_submodule_change_log.rb
UTF-8
809
2.65625
3
[]
no_license
class GitSubmoduleChangeLog attr_reader :symbolic_from, :symbolic_to, :git_submodule_changes def self.from_git_log(git_repo, git_log) git_submodule_changes = GitSubmoduleChangeCollectionLazy.new(git_repo, git_log) new(git_log.symbolic_from, git_log.symbolic_to, git_submodule_changes) end def initialize(symbolic_from, symbolic_to, git_submodule_changes) @symbolic_from = symbolic_from @symbolic_to = symbolic_to @git_submodule_changes = git_submodule_changes end def aggregate_git_submodule_changes @aggregate_git_submodule_changes ||= build_aggregate_git_submodule_changes end private def build_aggregate_git_submodule_changes @git_submodule_changes .group_by(&:path) .map { |_, changes| changes.inject(:+) } .sort_by(&:path) end end
true
76ef00e59f328e03bc9157811d50ebc807a800e1
Ruby
joan2kus/ChartDirector
/railsdemo/app/controllers/surface3_controller.rb
UTF-8
3,177
2.84375
3
[ "IJG" ]
permissive
require("chartdirector") class Surface3Controller < ApplicationController def index() @title = "Surface Chart (3)" @ctrl_file = File.expand_path(__FILE__) @noOfCharts = 1 render :template => "templates/chartview" end # # Render and deliver the chart # def getchart() # The x and y coordinates of the grid dataX = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] dataY = [-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] # The values at the grid points. In this example, we will compute the values using # the formula z = Sin(x * x / 128 - y * y / 256 + 3) * Cos(x / 4 + 1 - Exp(y / 8)) dataZ = Array.new((dataX.length) * (dataY.length)) 0.upto(dataY.length - 1) do |yIndex| y = dataY[yIndex] 0.upto(dataX.length - 1) do |xIndex| x = dataX[xIndex] dataZ[yIndex * (dataX.length) + xIndex] = Math.sin( x * x / 128.0 - y * y / 256.0 + 3) * Math.cos(x / 4.0 + 1 - Math.exp( y / 8.0)) end end # Create a SurfaceChart object of size 750 x 600 pixels c = ChartDirector::SurfaceChart.new(750, 600) # Add a title to the chart using 20 points Times New Roman Italic font c.addTitle("Surface Energy Density ", "timesi.ttf", 20) # Set the center of the plot region at (380, 260), and set width x depth x height # to 360 x 360 x 270 pixels c.setPlotRegion(380, 260, 360, 360, 270) # Set the elevation and rotation angles to 30 and 210 degrees c.setViewAngle(30, 210) # Set the perspective level to 60 c.setPerspective(60) # Set the data to use to plot the chart c.setData(dataX, dataY, dataZ) # Spline interpolate data to a 80 x 80 grid for a smooth surface c.setInterpolation(80, 80) # Use semi-transparent black (c0000000) for x and y major surface grid lines. Use # dotted style for x and y minor surface grid lines. majorGridColor = 0xc0000000 minorGridColor = c.dashLineColor(majorGridColor, ChartDirector::DotLine) c.setSurfaceAxisGrid(majorGridColor, majorGridColor, minorGridColor, minorGridColor) # Set contour lines to semi-transparent white (80ffffff) c.setContourColor(0x80ffffff) # Add a color axis (the legend) in which the left center is anchored at (665, # 280). Set the length to 200 pixels and the labels on the right side. c.setColorAxis(665, 280, ChartDirector::Left, 200, ChartDirector::Right) # Set the x, y and z axis titles using 12 points Arial Bold font c.xAxis().setTitle("X Title\nPlaceholder", "arialbd.ttf", 12) c.yAxis().setTitle("Y Title\nPlaceholder", "arialbd.ttf", 12) c.zAxis().setTitle("Z Title Placeholder", "arialbd.ttf", 12) # Output the chart send_data(c.makeChart2(ChartDirector::JPG), :type => "image/jpeg", :disposition => "inline") end end
true
ea0f8ccac4173669e0bbeb6a54a59bc36c054f11
Ruby
darrdv/ruby_fundamentals1
/exercise4.rb
UTF-8
330
3.46875
3
[]
no_license
one_to_hundred = (1..100) one_to_hundred.each do |num| string_array = [] flag = 0 if num % 3 == 0 string_array.push('Bit') flag = 1 end if num % 5 == 0 string_array.push('Maker') flag = 1 end if flag == 0 puts num else puts string_array.join("") end end
true
d4b2643eb1d81e13105b575a8b4e186ff2c58f2c
Ruby
floum/pathfinder
/lib/pathfinder/character.rb
UTF-8
1,926
2.921875
3
[ "MIT" ]
permissive
require 'yaml' module Pathfinder CHARACTERISTICS =%i(strength dexterity constitution intelligence wisdom charisma) class Character attr_reader :name, :level, :feats, :traits, :skills, :caste, :archetype, :race, :hit_points, :movement def initialize(attrs = {}) @name = attrs.fetch('name') { nil } @race = attrs.fetch('race') { 'Human' } @caste = attrs.fetch('class') { 'Warrior' } @archetype = attrs.fetch('archetype') { '' } @level = attrs.fetch('level') { 1 } @hit_points = attrs.fetch('HP') { 1 } @movement = attrs.fetch('movement') { '9m' } @characteristics = attrs.fetch('characteristics') { {} } @abilities = attrs.fetch('abilities') { {} } @traits = attrs.fetch('traits') { [] } @feats = attrs.fetch('feats') { [] } @spells = attrs.fetch('spells') { {} } @skills = attrs.fetch('skills') { {} } @saving_throws = attrs.fetch('saving_throws') { {} } @combat = attrs.fetch('combat') { {} } @languages = attrs.fetch('languages') { [] } end CHARACTERISTICS.each do |characteristic| define_method characteristic do @characteristics[characteristic[0..2]] end end %i(racial class).each do |type| define_method "#{type}_abilities" do @abilities.fetch(type) { [] } end end %i(quickness toughness willpower).each do |saving_throw| define_method saving_throw do @saving_throws.fetch('quickness') { 0 } end end def initiative @combat.fetch('initiative') { {} } end def spellbook @spells.fetch('book') { {} } end def prepared_spells_per_day @spells.fetch('prepared') { {} } end def spells_cast_per_day @spells.fetch('per_day') { {} } end def self.from_yaml(yaml) character_info = YAML.load(yaml) || {} self.new(character_info) end end end
true
7577e0790fda3688ae3ee2b210b061ace678e0bb
Ruby
horandago/Waifu-Quest
/lib/armour.rb
UTF-8
333
2.734375
3
[]
no_license
class Armour attr_reader :is_armour, :is_weapon, :defence, :price, :is_item, :is_usable, :is_equipment, :is_sellable, :is_junk def initialize @is_armour = true @is_weapon = false @is_equipment = true @is_item = false @is_usable = false @is_sellable = true @is_junk = false end def to_s "#{@name}" end end
true
738f71eb43e508ccf3a15a693ab51c9d1741dfe7
Ruby
James-C-Wilson/launchschool_organized_answers
/lesson_4/practice_problem_4.rb
UTF-8
1,294
4.34375
4
[]
no_license
# What is the return value of each_with_object in the following code? Why? ['ant', 'bear', 'cat'].each_with_object({}) do |value, hash| hash[value[0]] = value end =begin According to the lesson (which I found rather easily), each_with_object takes a method argument. The method argument is a collection object that will be returned by the method. - the block takes 2 arguments on its own - first block argument represents the current element - the second block argument represents the collection object that was passed in as an argument to the method - once it's done iterating, the method returns the collection object that was passed in. their example: [1, 2, 3].each_with_object([]) do - At this point, I'm going to guess that it returns ["ant", "bear", "cat"] Seems like I was wrong. Thought it might return the orgiinal collection like the solution says, but this is not correct. - When we invoke each_with_object, we pass in an object {} as an argument - That object is then passed into the block and it's updated value is returned at the end of each iteration. - Once each_with_object has iterated over the calling collection, it returns the intially given object with now contains all of the updates => {"a"=>"ant", "b"=>"bear", "c"=>"cat"} 2.6.2 :004 > =end
true
caa21f995c1fef731d6400b1db69287fdd2d8861
Ruby
r0b0x-0/Launch-School
/RB100/intro_to_programming/1_the_basics/exercise_1.rb
UTF-8
70
2.890625
3
[]
no_license
first_name = "C" last_name = "Jones" puts "#{first_name} #{last_name}"
true
c216eb0509ee41cfb21a202b8145232f0bdf647f
Ruby
jcronk/convert_ibm390
/test/convert/test_ibm390.rb
UTF-8
2,994
2.90625
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
# frozen_string_literal: true require 'minitest/autorun' require 'test_helper' module Convert class IBM390Test < Minitest::Test describe 'IBM390.ascnum2num' do include Convert::IBM390 it 'converts a number with no implied decimals' do original = '008910' assert_equal(8910, ascnum2num(original)) end context 'when the number has implied decimals' do it 'places the decimal point in the correct position' do original = '000299' assert_equal(2.99, ascnum2num(original, 2), '000299 with 2 implied decimals is 2.99') end end end describe 'IBM390.asc_zoned2num' do include Convert::IBM390 it 'converts a positive signed number with no implied decimals' do original = '000299{' assert_equal( 2990, asc_zoned2num(original), 'a sign of "{" means the last digit is 0 and the number is positive' ) end it 'converts a negative signed number with no implied decimals' do original = '000299}' assert_equal( -2990, asc_zoned2num(original), 'a sign of "}" means the last digit is 0 and the number is negative' ) end it 'converts a negative signed number with implied decimals' do original = '000299J' assert_equal( -29.91, asc_zoned2num(original, 2), 'a sign of "J" means the last digit is 1 and the number is negative' ) end it 'converts a positive signed number with implied decimals' do original = '000299{' assert_equal( 29.90, asc_zoned2num(original, 2), 'with 2 implied decimals, a zoned "000299{" is 29.9' ) end end describe 'IBM390.zoned2num' do include Convert::IBM390 it 'converts a negative signed number' do nbr = "\xF2\xF9\xF9\xD0".b assert_equal(-2990, zoned2num(nbr, 0)) end it 'converts a positive signed number' do nbr = "\xF2\xF9\xF9\xC0".b assert_equal 2990, zoned2num(nbr, 0) end it 'converts a signed number with implied decimals' do nbr = "\xF2\xF9\xF9\xD0".b assert_equal(-29.90, zoned2num(nbr, 2)) end end describe 'IBM390.packed2num' do include Convert::IBM390 it 'converts an unsigned packed number' do packednbr = "\x1\x30\x50\x8C" assert_equal(130_508, packed2num(packednbr)) end it 'converts a signed packed number' do packed = "\x0\x0\x0\x70\x10\xD" assert_equal(-70_100, packed2num(packed)) end it 'converts a packed number with implied decimals' do packed = "\x0\x0\x0\x70\x10\xC" assert_equal(701.00, packed2num(packed, 2)) end end describe IBM390 do it 'can call its functions as class methods' do assert_equal('???', IBM390.eb2asc("\x6F\x6F\x6F")) end end end end
true
e5e70a74794d6fbf1fce7ed93696aab86eca1972
Ruby
betten/linguo
/spec/models/game_spec.rb
UTF-8
3,004
2.578125
3
[]
no_license
require 'spec_helper' describe Game do describe "next level" do before do @levels = [ Factory(:level, :number => 1), Factory(:level, :number => 2), Factory(:level, :number => 3) ] @game = Factory(:game, :language => Factory(:language, :levels => @levels)) @game.stub_chain(:language, :levels, :where).with(hash_including(:number)) { |hash| @levels.find_all{ |level| level.number == hash[:number] } } end describe "has_next_level" do it "should return true if there is a next level" do @game.level = @levels[1] @game.has_next_level?.should be end it "should return false if there is not a next level" do @game.level = @levels.last @game.has_next_level?.should_not be end end describe "goto_next_level" do it "should set the current level to the next level by number" do @game.level = @levels[1] lambda { @game.goto_next_level }.should change(@game, :level).from(@levels[1]).to(@levels[2]) end it "should maintain the current level if there is no next level" do @game.level = @levels.last lambda { @game.goto_next_level }.should_not change(@game, :level) end end end describe "current_level" do before do @level = Factory(:level, :number => 1) @language = Factory(:language, :levels => [@level]) end it "should not set the current level if level is nil and the language has no levels" do game = Factory(:game) game.level.should be_nil end it "should set the current level to the languages first level if no current level" do game = Factory(:game, :language => @language) game.levels.should_receive(:where).and_return([@level]) game.current_level.should == @level end it "should return the current level if current level exists" do game = Factory(:game, :language => @language, :level => Factory(:level, :number => 4)) game.current_level.number.should == 4 end end describe "current_level?" do it "should return true if game has a level" do game = Factory(:game, :level => Factory(:level)) game.current_level?.should be end it "should return false if game does not have a level" do game = Factory(:game) game.current_level?.should_not be end end describe "relationships" do before do @user = mock_model(User) @language = mock_model(Language) @level = mock_model(Level) end it "should have a user" do g = Game.new g.user = @user g.user.should be(@user) end it "should have a language" do g = Game.new g.language = @language g.language.should be(@language) end it "should have a current level" do g = Game.new g.level = @level g.level.should be(@level) g.current_level.should be(@level) end end end
true
6183cef7bb956101281c7468f299866a19513cbe
Ruby
dqmrf/dive-in-ruby
/sandbox/built_in/comparsions/bid.rb
UTF-8
316
3.375
3
[]
no_license
class Bid include Comparable attr_accessor :estimate def <=>(other_bid) if self.estimate < other_bid.estimate -1 elsif self.estimate > other_bid.estimate 1 else 0 end end end bid1 = Bid.new bid2 = Bid.new bid1.estimate = 100 bid2.estimate = 200 puts bid2 > bid1 #=> true
true
318e3e117cba6d8e730a5f2beecb0eed1998015a
Ruby
alpaca-tc/practices
/atcoder/contest#015/arc015_4.rb
UTF-8
1,657
3.4375
3
[]
no_license
require 'mathn' module Stub def gets @count = -1 unless @count @count += 1 [ # '10 2 0.5', # '0.5 10 1', # '0.5 2 1', # '100000 3 0.01', # '0.48175 7 77', # '0.033325 777 13', # '0.484925 1 100', '300 1 1', '1 2 1000' ][@count] end end extend Stub effects = [] T, N, P = gets.strip.split(/\s/).map { |v| v.to_f } N.to_i.times do # probability, pow, duration effects << gets.strip.split(/\s/).map { |v| v.to_f } end class CookieBabaa def initialize(t, p, effects) @time = 0 @duration = t @probability = p @cookie = 1 @golden_time = [] @effects = effects end def go_ahead @time += 1 evaluate_golden_time display_golden_cookie end def start 0.upto(@duration - 1) do go_ahead report end @cookie end private def report puts <<-CODE.gsub(/^\s/, '') -- #{@time} : #{@cookie} #{@golden_time} CODE end def evaluate_golden_time @golden_time.map! do |(probability, power, duration)| @cookie += power * probability duration -= 1 if duration == -1 nil else [probability, power, duration] end end @golden_time.reject! { |v| v.nil? } end def display_golden_cookie parsed_effects.dup.each { |v| @golden_time << v.dup } end def parsed_effects @parsed_effects ||= begin @effects.map! { |v| [v[0] * @probability, v[1], v[2]] } golden = @effects.transpose[0].inject(&:+) @effects << [1.0 - golden, 1, 1] if golden < 1 @effects end end end p CookieBabaa.new(T.to_i, P, effects).start
true
69c9ede8dc6dbdf23be7576b9a5f95366535360c
Ruby
nepalez/query_builder
/lib/query_builder/cql/modifiers/selected.rb
UTF-8
1,139
2.625
3
[ "MIT" ]
permissive
# encoding: utf-8 module QueryBuilder::CQL module Modifiers # Provides the list of selected columns for SELECT statement # module Selected # Adds a column # # @param [Array] values # # @return [QueryBuilder::Core::Statement] updated statement # def select(*values) return self if values.empty? hash = values.last.instance_of?(Hash) ? values.pop : {} list = values.map { |name| Clause.new(name: name) } list += hash.map { |as, name| Clause.new(name: name, as: as) } list.inject(self, :<<) end private def maybe_selected list = clauses(:selected) list.any? ? list.join(", ") : "*" end # The clause for adding to a statement # # @api private # class Clause < Base type :selected attribute :name, required: true attribute :as # @private def to_s [name, (as ? "AS" : nil), as].compact.join(" ") end end # class Clause end # module Selected end # module Modifiers end # module QueryBuilder::CQL
true
e0822c219b094dc539df273ec70cdc4e74ca9895
Ruby
rebagliatte/conf
/app/helpers/notifications_helper.rb
UTF-8
834
2.6875
3
[]
no_license
module NotificationsHelper def interpolable_variables_hint(notification) string = "Interpolable variables are:" if notification.recipients.blank? string += "<ul class=\"help-block\">" Notification::RECIPIENTS.each do |recipients| string += "<li>For #{recipients.to_s.humanize.downcase}:<ul>" string += interpolable_variables_list_for_recipients(recipients) string += "</li></ul>" end else string += interpolable_variables_list_for_recipients(notification.recipients.to_sym) end string.html_safe end private def interpolable_variables_list_for_recipients(recipients) string = "<ul class=\"help-block\">" Notification::INTERPOLABLE_VARIABLES[recipients].each do |var| string += "<li>{{ #{var} }}</li>" end string += "</ul>" end end
true
5f061025cf7c6913069a7068d91cbec2860eeb42
Ruby
maxim5/code-inspector
/data/ruby/1098ee3a17b8f8bf33164a6eedf36557_gap_test.rb
UTF-8
809
3.3125
3
[ "Apache-2.0" ]
permissive
# Algorithm G, pp.62 TAOCPvII class GapTest attr_accessor :range, :alpha, :beta, :j, :s, :r, :count def initialize(range, alpha=0, beta=1) self.range = range self.alpha = alpha self.beta = beta self.j = -1 self.s = 0 self.count = Hash.new end def set_r self.r = 0 end def test_value self.j += 1 if self.range[self.j] >= self.alpha || self.range[self.j < beta self.record_gap_length else self.inc_r end end def inc_r self.r += 1 self.test_value end def record_gap_length if r >= t self.count[t] += 1 else self.count[r] += 1 end end def n_gaps_found? self.s += 1 if s < n self.set_r(r) else self.chi_squared_test end end def chi_squared_test end end
true
52e46af7ae3ea93aed099444293705a108b72ba9
Ruby
TheNotary/exc1_sum_squares
/bin/exc1_sum_squares
UTF-8
1,317
2.90625
3
[]
no_license
#!/usr/bin/env ruby # The CLI interface is generated thanks to 'thor'. To use thor in your apps: # 1) Add thor as a dependency in *.gemspec and do a bundle install # 2) Create a bin folder, and create a bin script that you'd like exposed to your shell path (this file) # 3) Put the shebang at the top of the bin script # 4) Requirements - Require in thor and also your gem's name # 5) *Runner Class - Create a class that inherits from Thor. # 6) Customize your CLI commands as demonstrated in this file # 7) Start require 'thor' require 'exc1_sum_squares' class Exc1SumSquaresRunner < Thor default_task :help # create a default task desc "help", "Explains the gem's usage" def help Exc1SumSquares.help end desc "solve", "Solves the min and max square values of a 2D array" def solve(input, output_device = $>) # first we need to get the string and convert it into an array... yaml_array = input.gsub(/(\,)(\S)/, "\\1 \\2") array = YAML::load(yaml_array) s = Exc1SumSquares.solve(array) output = "Min: #{s.min}\nMax: #{s.max}" output_device.puts output return 0 end desc "version", "Prints Gas's version" def version Gas.version end map %w(-v --version) => :version end Exc1SumSquaresRunner.start
true
829aae39f22ab5f92f828b2b6840e1f3d7ebcb02
Ruby
ratnikov/ruby-presentation
/ruby/app/models/book.rb
UTF-8
323
3.171875
3
[]
no_license
class Book attr_accessor :name, :author, :isbn def description "#{name} by #{author}" end def initialize options = {} self.name = options.delete(:name) or raise("Must provide name") self.author = options.delete(:author) or raise("Must provide author") self.isbn = options.delete(:isbn) end end
true
6a34d9a6257ac5bdc66aa309542b87b64292ea4b
Ruby
rui-r-duan/courses
/ruby/test_closure.rb
UTF-8
161
3.21875
3
[]
no_license
def add_n (n) lambda {|x| n + x} end a_proc = add_n(5) # => #<Proc:0x00000001400f00@test_closure.rb:2 (lambda)> a_proc.call(3) # => 8 a_proc.call(10) # => 15
true
9186a67854c68ffc7fca2a40a96346b3c36a3822
Ruby
jbe/rcheck
/lib/rcheck/option_expander.rb
UTF-8
1,682
2.65625
3
[ "MIT" ]
permissive
module RCheck module OptionExpander def self.constantize(name) name.to_s.split('_').map(&:capitalize).join.to_sym end def self.[](name, value) return [] if value == :none case name when :colors then parse_theme value when :progress then to_instance(ProgressPrinters, *value) when :report then to_instance(ReportPrinters, *value) when :filters then to_instance(Filters, *value) when :anti_filters then to_instance(Filters::Anti, *value) when :headers then to_instance(Headers, *value) when :files, :initializers then parse_string_array value when :seed, :fail_code, :success_code value.to_s.to_i else value end end def self.to_instance(scope, *list) list.map do |item| case item when Class then item.new when String, Symbol then safer_const_get(scope, item.to_sym) else item end end end def self.safer_const_get(scope, item) if scope.const_defined?(constantize item) val = scope.const_get(constantize item) val.respond_to?(:new) ? val.new : val else raise Errors::ConfigParam, "#{item.inspect} not found in "\ "#{scope.inspect}" end end def self.parse_string_array(value) Array(value).map(&:to_s) end def self.parse_theme(theme) return theme if theme.is_a?(Hash) name = :"#{theme.upcase}" if Colors::Themes.const_defined?(name) Colors::Themes.const_get(name) else raise "Invalid color theme: #{theme.inspect}" end end end end
true
8d65cbfcc8edf915b9acb1b705daf38094b4017e
Ruby
marin-cabac/prime-ruby-v-000
/prime.rb
UTF-8
127
3.046875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def prime?(n) return false if n < 2 return true if n == 3 || n == 2 ((2...n).any?{|i| n % i == 0}) ? false : true end
true
67b6c5e6e98db9db00d6cf106eb26f11ca873c51
Ruby
donballz/Ruby-Crawl
/threadDict.rb
UTF-8
2,833
2.765625
3
[]
no_license
require_relative 'readThread.rb' require_relative 'common_funcs.rb' class ThreadDict # list of thread elements for faster searching ATTRS = [:pNums, :pPosters, :pQuoted, :pTimes, :tNums, :tTitles, :tOPs, :tNumsUnq, :tTitlesUnq, :tOPsUnq, :tTimesUnq] attr_reader(*ATTRS) def initialize(fnum) @fNum = fnum @pNums = [] @pPosters = [] @pQuoted = [] @pTimes = [] @tNums = [] @tTitles = [] @tOPs = [] @tNumsUnq = [] @tTitlesUnq = [] @tOPsUnq = [] @tTimesUnq = [] make_lists(fnum) end def write # write yaml file of this object path = '/Users/donald/Dropbox/AO Thread Crawl/Ruby Port/' File.open(path + "thread_dict_#{@fNum}.yml", 'w') { |f| f.write self.to_yaml } end def make_lists(fnum) # the real initialize method tcat = read("thread_cat_#{fnum}") tcat.each do |k, v| if v > 0 mt = read("Threads/#{k}") @tNumsUnq.push(k) @tTitlesUnq.push(mt.tTitle) @tOPsUnq.push(mt.tTitle) @tTimesUnq.push(mt.tPosts[0].pTime) mt.each do |post| @pNums.push(post.pNum) @pPosters.push(post.pPoster) @pQuoted.push(post.pQuoted) @pTimes.push(post.pTime) @tNums.push(k) @tTitles.push(mt.tTitle) @tOPs.push(mt.tTitle) end end end end def update(mt) # method to update the ThreadDict to keep in sync with active library unless @tNumsUnq.include?(mt.tNum) @tNumsUnq.push(mt.tNum) @tTitlesUnq.push(mt.tTitle) @tOPsUnq.push(mt.tTitle) @tTimesUnq.push(mt.tPosts[0].pTime) end mt.each do |post| unless @pNums.include?(post.pNum) @pNums.push(post.pNum) @pPosters.push(post.pPoster) @pQuoted.push(post.pQuoted) @pTimes.push(post.pTime) @tNums.push(mt.tNum) @tTitles.push(mt.tTitle) @tOPs.push(mt.tTitle) end end end end class ParseHistory # class to track parse history ATTRS = [:updateTimes, :threadTimes, :threadPosts] attr_reader(*ATTRS) def initialize(fnum, init) @fNum = fnum @updateTimes = [init] @threadTimes = {} @threadPosts = {} build_history(fnum, init) end def write # write yaml file of this object path = '/Users/donald/Dropbox/AO Thread Crawl/Ruby Port/' File.open(path + "parse_history_#{@fNum}.yml", 'w') { |f| f.write self.to_yaml } end def build_history(fnum, init) # the real initialize method tcat = read("thread_cat_#{fnum}") tcat.each do |k, v| if v > 0 # political initial time: #init = Time.new(2016,06,24,21,14,0) @threadTimes[k] = [init] @threadPosts[k] = [v] end end end def update(thread, posts, time) # func to add/update @updateTimes.push(time) unless @updateTimes.include?(time) if @threadPosts.include?(thread) @threadTimes[thread].push(time) @threadPosts[thread].push(posts) else @threadTimes[thread] = [time] @threadPosts[thread] = [posts] end end end
true
3483a78fa1bb715c2002d652ac50a249494738d4
Ruby
olbrich/ruby-units
/spec/ruby_units/date_spec.rb
UTF-8
1,904
2.640625
3
[ "MIT" ]
permissive
RSpec.describe RubyUnits::Date do subject(:date_unit) { date.to_unit } let(:date) { Date.new(2011, 4, 1) } it { is_expected.to be_a Unit } it { is_expected.to respond_to :to_unit } it { is_expected.to respond_to :to_time } it { is_expected.to respond_to :to_date } it { is_expected.to have_attributes(scalar: date.ajd, units: 'd', kind: :time) } describe 'offsets' do specify { expect(date + '5 days'.to_unit).to eq(::Date.new(2011, 4, 6)) } specify { expect(date - '5 days'.to_unit).to eq(::Date.new(2011, 3, 27)) } # 2012 is a leap year... specify { expect(date + '1 year'.to_unit).to eq(::Date.new(2012, 3, 31)) } specify { expect(date - '1 year'.to_unit).to eq(::Date.new(2010, 4, 1)) } # adding Time or Date objects to a Duration don't make any sense, so raise # an error. specify { expect { date_unit + Date.new(2011, 4, 1) }.to raise_error(ArgumentError, 'Date and Time objects represent fixed points in time and cannot be added to a Unit') } specify { expect { date_unit + DateTime.new(2011, 4, 1, 12, 0, 0) }.to raise_error(ArgumentError, 'Date and Time objects represent fixed points in time and cannot be added to a Unit') } specify { expect { date_unit + Time.parse('2011-04-01 12:00:00') }.to raise_error(ArgumentError, 'Date and Time objects represent fixed points in time and cannot be added to a Unit') } specify { expect(date_unit - Date.new(2011, 4, 1)).to be_zero } specify { expect(date_unit - DateTime.new(2011, 4, 1, 0, 0, 0)).to be_zero } specify do expect { (date_unit - Time.parse('2011-04-01 00:00')) }.to raise_error(ArgumentError, 'Date and Time objects represent fixed points in time and cannot be subtracted from a Unit') end specify { expect(Date.new(2011, 4, 1) + 1).to eq(Date.new(2011, 4, 2)) } end end
true
0a71b1762a3edf9fd16085bb4771e36d89d3c364
Ruby
kb-diangelo/phase-0
/week-6/guessing-game/my_solution.rb
UTF-8
3,235
4.46875
4
[ "MIT" ]
permissive
# Build a simple guessing game # I worked on this challenge by myself. # I spent [#] hours on this challenge. # Pseudocode # Input: A number # Output: A game that lets you guess the number, # => and reflects whether your guess was low or high # Steps: # 1. Define a method that takes a number as an argument # 1.1 Save that number to a variable # 2. Define a method guess that takes another number # 2.1 Compare that number to the correct number, return # :low if the guess is low and :high if the guess is high # and set the solve state to false # 2.2 Return :correct if the guess is correct # and set the solve state to true # 3. Define a method solved? that returns the solve state # Initial Solution class GuessingGame1 def initialize(answer) @answer = answer @solved = false end def guess(number) if number > @answer @solved = false return :high elsif number < @answer @solved = false return :low else @solved = true return :correct end end def solved? return @solved end end # Refactored Solution class GuessingGame def initialize(answer) @answer = answer end def guess(number) if number == @answer @solved = true :correct else @solved = false number > @answer ? :high : :low end end def solved? @solved end end # Reflection =begin * How do instance variables and methods represent the characteristics and behaviors (actions) of a real-world object? Instance variables (as discussed below) allow different "behaviors" (methods) of an object to work with the same information, which may be unique to that object. In this case, the correct answer was stored in an instance variable and that information was carried over to the guess method. Methods allow a Ruby object to have a set of behaviors that are the same between all the same instances of a class but whose output varies based on input. * When should you use instance variables? What do they do for you? Instance variables keep their value throughout the same object (instance of a class). They allow you to carry values from one method to another associated with the same object. They allow different instances of the same class to carry different values. You should use instance variables when you need the above to be true and you want a variable scoped to a single instance of a class. * Explain how to use flow control. Did you have any trouble using it in this challenge? If so, what did you struggle with? Flow control is branching the results of an operation in different directions. In Ruby if/elsif/else and case statements are used to branch code, as well as the ternary conditional operator ? I didn't have any trouble using it in this challenge initially but it was a little hard to refactor. * Why do you think this code requires you to return symbols? What are the benefits of using symbols? Symbols are unique and immutable and faster for Ruby to process than strings. However, they can easily be converted to strings. This code probably requires us to return symbols for efficiency. =end
true
1cbea701d7452fd5b348ca9558f6dacd34c39f1f
Ruby
BrandonM23/Tealeaf-Prep
/IntroEx.8.rb
UTF-8
67
2.625
3
[]
no_license
a = {one: '1', two: '2'} # new b = {:one => '1', :two => '2'} # old
true
7b78f19ef5f991c7648202b7b678febe33e83866
Ruby
hirokore/DIC_ruby_exam
/exam/test.rb
UTF-8
6,132
3.515625
4
[]
no_license
# 下記のコードが何をしているかを説明してください・・・(A)(8)最初の行(座席数と入店するグループの総数)の入力を受け付けます seats_and_groups = gets.split(/\s/) # 下記のコードが何をしているかを説明してください・・・(B) (10)座席を配列で作成します empty_seat = [*1..(seats_and_groups[0].to_i)] # 下記のコードが何をしているかを説明してください・・・(C)(13)座席の数を変数に入れておきます seats_count = empty_seat.count # 下記のコードが何をしているかを説明してください・・・(D)(11)何組のグループが入店するのか、その数を変数に入れておきます number_of_visitors = seats_and_groups[1].to_i # 下記のコードが何をしているかを説明してください・・・(E)(15)入店するグループの数だけループさせます [*1..number_of_visitors].each do # 下記のコードが何をしているかを説明してください・・・(F)(4)二行目以降の行(グループの人数と着席開始座席番号)の入力を受け付けます used_seats = gets.split(/\s/) # 下記のコードが何をしているかを説明してください・・・(G) (6)来店したグループの人数を変数に代入します users = used_seats[0].to_i # 下記のコードが何をしているかを説明してください・・・(H) (12)来店したグループの着席開始座席番号を変数に代入します seating_number = used_seats[1].to_i # 下記のコードが何をしているかを説明してください・・・(I) (9)来店したグループの最後の人間が着席した座席の番号を変数に代入します fill_last_number = ((seating_number + users) - 1) # 下記のコードが何をしているかを説明してください・・・(J)(14)最後の人間が着席した座席の番号が、最初に定義された座席の数を超えていた場合と、そうでない場合とで座席の埋め方をif文で分岐させます if fill_last_number > seats_count # 下記のコードが何をしているかを説明してください・・・(K) (3)もしも最後の人間が着席した座席の番号が、最初に定義された座席の数を超えていたら、最初の座席の数に戻して再計算します(円卓だから) # (下記のコードは理解が難しいので、下記にヒントを載せます) # 「今回のグループが最後に着席する座席の番号」 = 「今回のグループが最後に着席する座席の番号」-「そもそもの座席の総数」となる(円卓だから)。 # 例えば、fill_last_number == 13で、seats_countが12だったら、1 = 13 - 12となり、座席番号が1の座席に最後の人間が座る。 fill_last_number = fill_last_number - seats_count # (下記のコードは理解が難しいので、下記にヒントを載せます) # next_seat_candidateは、「その座席に既に人が座っていないか?」を判断するための配列 # ([*1..seats_count] - empty_seat)は、(「全ての座席」- 「まだ人が座っていない座席」)の意味。つまり、「既に人が座っている座席」の数字が、([*1..seats_count] - empty_seat) # [*seating_number..seats_count]は、[*「今回のグループが最初に着席する座席の番号」..「最後の座席の番号」]の意味 # [*1..fill_last_number]は、[*「1(最初の座席)」..「今回のグループが最後に着席する座席の番号」]の意味 # なので、next_seat_candidate = ([*1..seats_count] - empty_seat) + [*seating_number..seats_count] + [*1..fill_last_number]は、 # next_seat_candidate = 「既に人が座っている座席」+ [*「今回のグループが最初に着席する座席の番号」..「最後の座席の番号」] + [*「1(最初の座席)」..「今回のグループが最後に着席する座席の番号」]となる。 # つまり、 next_seat_candidateの配列の中に、同じ数字が含まれていれば、「既に埋まっている座席に新たなグループの人間が座ろうとしている」ということになる next_seat_candidate = ([*1..seats_count] - empty_seat) + [*seating_number..seats_count] + [*1..fill_last_number] else # 下記のコードが何をしているかを説明してください・・・(L) # (下記のコードは理解が難しいので、下記にヒントを載せます) # next_seat_candidate = 「既に人が座っている座席」+ [*「今回のグループが最初に着席する座席の番号」..「今回のグループが最後に着席する座席の番号」]となる # つまり、 next_seat_candidateの配列の中に、同じ数字が含まれていれば、「既に埋まっている座席に新たなグループの人間が座ろうとしている」ということになる next_seat_candidate = ([*1..seats_count] - empty_seat) + [*seating_number..fill_last_number] end # 下記のコードが何をしているかを説明してください・・・(M) if next_seat_candidate.count == next_seat_candidate.uniq.count # 下記のコードが何をしているかを説明してください・・・(N) if ((seating_number + users) - 1) > seats_count # 下記の二行のコードが何をしているかを説明してください・・・(O) empty_seat = empty_seat - [*1..fill_last_number] empty_seat = empty_seat - [*seating_number..seats_count] else # 下記のコードが何をしているかを説明してください・・・(P) empty_seat = empty_seat - [*seating_number..fill_last_number] end end end # 下記のコードが何をしているかを説明してください・・・(Q) puts seats_count - empty_seat.count
true
73c59deceb4465021600dc18a0c99f8ab6652632
Ruby
rx/presenters
/lib/voom/presenters/web_client/helpers/expand_hash.rb
UTF-8
656
2.671875
3
[ "MIT" ]
permissive
# Expands a hash ensuring all values are hash's # POM object models expand to a hash using :to_hash # JSON is serialized in as recursive OpenStruct's, they need special expansion logic. module Voom::Presenters::WebClient::Helpers module ExpandHash def expand_hash(h) HashExt::Traverse.traverse(h.to_h) do |k,v| if !v.is_a?(Array) && v.respond_to?(:to_h) v = v.is_a?(OpenStruct) ? expand_hash(v.to_h) : v.to_h elsif v.is_a?(Array) v = v.map {|v| v.is_a?(OpenStruct) ? expand_hash(v.to_h) : v} elsif v.respond_to?(:to_hash) v = v.to_hash end [k,v] end end end end
true
598c61c1a95bd1d7a0a21c55d644eaf3f39bce9e
Ruby
shadabahmed/leetcode-problems
/hit-counter.rb
UTF-8
3,769
3.515625
4
[]
no_license
class PriorityQueue attr_accessor :arr, :comparator def initialize(&block) self.arr = [] self.comparator = block end def compare(first_idx, other_idx) comparator.call(arr[first_idx], arr[other_idx]) end def swap(first_idx, other_idx) arr[first_idx], arr[other_idx] = arr[other_idx], arr[first_idx] end def parent(idx) (idx - 1) / 2 end def left(idx) 2 * idx + 1 end def right(idx) 2 * idx + 2 end def heapify_up(idx) return if idx >= size parent_idx = parent(idx) if compare(idx, parent_idx) swap(idx, parent_idx) heapify_up(parent_idx) end end def heapify_down(idx) return if idx >= size left_idx = left(idx) right_idx = right(idx) priority_idx = idx priority_idx = left_idx if left_idx < size && compare(left_idx, priority_idx) priority_idx = right_idx if right_idx < size && compare(right_idx, priority_idx) if priority_idx != idx swap(idx, priority_idx) heapify_down(priority_idx) end end def insert(item) arr << item heapify_up(arr.size - 1) end def delete_top last = arr.pop if !arr.empty? top = arr[0] arr[0] = last heapify_down(0) top else last end end def top arr[0] end def size arr.size end def empty? arr.empty? end end class MedianFinder attr_accessor :lq, :hq # initialize your data structure here. def initialize self.lq = PriorityQueue.new { |a, b| a > b } self.hq = PriorityQueue.new { |a, b| a < b } end # :type num: Integer # :rtype: Void def add_num(num) # binding.pry if lq.size == 19 if lq.empty? || num <= lq.top lq.insert(num) else hq.insert(num) end if lq.size > hq.size + 1 hq.insert(lq.delete_top) elsif hq.size > lq.size lq.insert(hq.delete_top) end end # :rtype: Float def find_median return nil if lq.empty? && hq.empty? if lq.size == hq.size (lq.top + hq.top) / 2.0 else lq.top end end end class HitCounter # Initialize your data structure here. attr_accessor :timestamp_map, :min_heap, :total, :window def initialize(_window = 300) self.min_heap = PriorityQueue.new { |a, b| a < b } self.timestamp_map = {} self.total = 0 self.window = 300 end # Record a hit. # @param timestamp - The current timestamp (in seconds granularity). # :type timestamp: Integer # :rtype: Void def hit(timestamp) if timestamp_map.key?(timestamp) timestamp_map[timestamp] += 1 else clear_expired_hits(timestamp) min_heap.insert(timestamp) timestamp_map[timestamp] = 1 end self.total += 1 end # Return the number of hits in the past 5 minutes. # @param timestamp - The current timestamp (in seconds granularity). # :type timestamp: Integer # :rtype: Integer def get_hits(timestamp) clear_expired_hits(timestamp) self.total end def clear_expired_hits(timestamp) while !min_heap.empty? && timestamp - min_heap.top >= window self.total -= timestamp_map.delete(min_heap.delete_top) end end end # Your HitCounter object will be instantiated and called as such: # obj = HitCounter.new() # obj.hit(timestamp) # param_2 = obj.get_hits(timestamp) counter = HitCounter.new(); # hit at timestamp 1. counter.hit(1); counter.hit(1); # hit at timestamp 2. counter.hit(2); # hit at timestamp 3. counter.hit(3); # get hits at timestamp 4, should return 3. p counter.get_hits(4); # hit at timestamp 300. counter.hit(300); counter.hit(300); # get hits at timestamp 300, should return 4. p counter.get_hits(300); # get hits at timestamp 301, should return 3. p counter.get_hits(301);
true
a91817e4a588a0c9096ff99cc3ba81a3a798c647
Ruby
johnglynn/Ironhack
/IH_Week_1/IH_Week1_Day4/lib/car.rb
UTF-8
95
2.546875
3
[]
no_license
class Car def number_of_wheels 4 end def sound "The sound I make is zoooom" end end
true
ed42e0eeffb573a6d011d278e5641b093b4d4bc2
Ruby
tsmsogn/AOJ
/Volume_001/0124_League_Match_Score_Sheet.rb
UTF-8
416
3.265625
3
[]
no_license
has_prev = false while line = gets n = line.chomp.to_i break if n == 0 teams = Hash.new(0) n.times do data = gets.chomp.split teams[data[0]] = data[1].to_i * 3 + data[3].to_i end teams = teams.sort do |(k1, v1), (k2, v2)| if v1 == v2 -1 else v2 <=> v1 end end puts if has_prev teams.each do |key, value| puts "#{key},#{value}" end has_prev = true end
true
7a28772cd11c1cbaa45b26245e9044330749f3f7
Ruby
TetianaFilonenko/homework4
/Rakefile
UTF-8
5,767
2.5625
3
[]
no_license
require 'gmail' require 'pry' require 'zip' require 'csv' require 'active_support/all' desc "Make coffee" task :download_homeworks_and_unzip do results = [] students = [] Gmail.connect('test', 'test').mailbox("HomeWork4").emails.each_with_index do |email, counter| begin puts '=' * 80 student_grade = [] student_name = email.message.subject.split('.')[0] next if students.include?(student_name) students << student_name puts "checking #{student_name}, #{counter}" student_grade << counter << student_name FileUtils.mkdir "#{Dir.pwd}/tmp#{counter}" FileUtils.mkdir "#{Dir.pwd}/tmp#{counter}/sandbox#{counter}" email.message.attachments.each do |f| File.write(File.join("#{Dir.pwd}/tmp#{counter}", 'ruby_bursa_task_4.zip'), f.body.decoded) end Zip::File.open("#{Dir.pwd}/tmp#{counter}/ruby_bursa_task_4.zip") do |zip_file| zip_file.each { |f| zip_file.extract(f, File.join("#{Dir.pwd}/tmp#{counter}/sandbox#{counter}", f.name)) } end puts student_grade.to_s results << student_grade rescue Exception => e puts e.message puts e.backtrace.inspect end end CSV.open("hw_4_grades.csv", "a+") do |csv| results.each{ |res| csv << res } end end desc "Make tea" task :check_homework do results = [] file_name = 'library' homework_count = Dir.entries('.').reject{ |d| d.scan(/tmp.*/).empty? }.sort_by{ |q| q.split('tmp')[1].to_i } homework_count.each do |dir| begin counter = dir.split('tmp')[1] puts '=' * 80 puts dir path = "./#{dir}/sandbox#{counter}/library/#{file_name}.rb" if File.exist?(path) require path else directories = Dir.glob("./#{dir}/sandbox#{counter}/*").select{ |e| File.directory? e } raise 'directory not found' if directories[0].blank? path = directories[0]+"/library/#{file_name}.rb" require path end @leo_tolstoy = Library::Author.new(1828, 1910, 'Leo Tolstoy') @oscar_wilde = Library::Author.new(1854, 1900, 'Oscar Wilde') @agatha_christie = Library::Author.new(1890, 1976, 'Agatha Christie') @war_and_peace = Library::PublishedBook.new(@leo_tolstoy, 'War and Peace', 1400, 3280, 1996) @picture_of_dorian_gray = Library::PublishedBook.new(@oscar_wilde, 'The Picture of Dorian Gray', 900, 1280, 2001) @poirot_investigates = Library::PublishedBook.new(@agatha_christie, 'Poirot investigates', 700, 2280, 2007) @ivan_testenko = Library::Reader.new('Ivan Testenko', 130) @semen_pyatochkin = Library::Reader.new('Semen Pyatochkin', 110) @vasya_pupkin = Library::Reader.new('Vasya Pupkin', 140) comment_cool = "cool" comment_fine = "fine" comment_nice = "nice" @war_and_peace.add_comment(comment_cool) @poirot_investigates.add_comment(comment_fine) @leo_tolstoy.add_comment(comment_cool) @leo_tolstoy.add_comment(comment_fine) first, second, third = 3.times.map{0} # check module begin if [:Author,:Book, :PublishedBook, :Reader, :Manager].all? { |e| Library.constants.include?(e) } first += 10 end rescue Exception => e puts e.message puts e.backtrace.inspect end # check commentable begin if Library.constants.include?(:Commentable) if Library::Commentable.class_variables.include?(:@@total_comments_counter) second += 2 second += 2 if Library::Commentable.total_comments_quantity == 4 end if [Library::Author, Library::Book, Library::PublishedBook].all? { |e| e.method(:comments_quantity).parameters.count.zero? } second += 3 second += 2 if Library::PublishedBook.comments_quantity == 2 second += 2 if Library::Author.comments_quantity == 2 end if [@poirot_investigates, @war_and_peace, @leo_tolstoy].all? { |e| e.instance_variables.include?(:@comments) } second += 3 second += 2 if @poirot_investigates.comments.include?(comment_fine) second += 2 if @war_and_peace.comments.include?(comment_cool) second += 2 if @leo_tolstoy.comments.include?(comment_cool) end end rescue Exception => e puts e.message puts e.backtrace.inspect end # check identifier begin if Library.constants.include?(:Identifier) third += 5 if [Library::PublishedBook, Library::Reader].all?{ |e| e.class_variables.include?(:@@group_identifier) } third += 5 if [@war_and_peace, @ivan_testenko].all? { |e| e.instance_variables.include?(:@identifier)} third += 5 unless @war_and_peace.eql? @picture_of_dorian_gray third += 5 unless @ivan_testenko.eql? @semen_pyatochkin end rescue Exception => e puts e.message puts e.backtrace.inspect end total = [first, second, third].sum student_grade = [counter, total, first, second, third] results << student_grade rescue Exception => e puts e.message puts e.backtrace.inspect end if defined? Library [:Author, :Commentable, :Identifier, :Manager, :PublishedBook, :Reader, :ReaderWithBook, :Book].each{ |s| Library.send(:remove_const, s) if Library.constants.include?(s) } Object.send(:remove_const, :Library) end end CSV.open("hw_4_grades.csv", "a+") do |csv| results.each{ |res| csv << res } end end desc "And clear" task :remove_homeworks do results = [] begin system('rm -rf tmp*') rescue Exception => e puts e.message puts e.backtrace.inspect end CSV.open("hw_4_grades.csv", "a+") do |csv| results.each{ |res| csv << res } end end
true
2b2e3c4cc053a617b9847a058fcb3ac878652e7f
Ruby
pyromaniac/contextuality
/lib/contextuality/context.rb
UTF-8
951
2.890625
3
[ "MIT" ]
permissive
module Contextuality class Context def initialize @scopes = [] end def scope_inspect scope scope.map do |name, value| "#{name}: #{value.inspect}" end.to_a.join(', ') end def push variables @scopes.unshift Hash[variables.map { |(name, variable)| [name.to_s, variable] }] Contextuality.log "#{'=' * @scopes.size} Entering scope: #{scope_inspect @scopes.first}" end def pop Contextuality.log "#{'=' * @scopes.size} Exiting scope" @scopes.shift end def [] name name = name.to_s scope = @scopes.detect { |scope| scope.key? name } scope ? scope[name] : Contextuality.defaults[name.to_sym] end def key? name name = name.to_s @scopes.any? { |scope| scope.key? name } end def empty? !@scopes.any? { |scope| !scope.empty? } end def method_missing method, *args, &block self[method] end end end
true
5067094ccf7357921a6f488faaa854fd4eb2e0aa
Ruby
dtz900/Launch-school
/small_problems/easy1g.rb
UTF-8
510
4.5625
5
[]
no_license
# Write a method that takes one argument, a positive integer, and returns a string of # alternating 1s and 0s, always starting with 1. The length of the string should match the # given integer. def stringy(size) numbers = [] size.times do |index| number = index.even? ? 1 : 0 numbers << number end numbers.join end # examples: puts stringy(6) == '101010' # => true puts stringy(9) == '101010101' # => true puts stringy(4) == '1010' # => true puts stringy(7) == '1010101' # => true
true
91fb0d65047decf816fd7e7d795ed2fe811dd788
Ruby
YuriiHorbach/ruby_examples
/lesson17/sendDemo7.rb
UTF-8
113
2.921875
3
[]
no_license
def left puts "go left" end def rigth puts "go rigth" end print "Where to go? " a = gets.strip send a
true
934d725babd50885b3bf76dfd738c1470362678f
Ruby
sogilis/sogishort
/lib/gitkvstore.rb
UTF-8
1,402
2.96875
3
[]
no_license
require_relative 'kvstore' require_relative 'git' require 'thread' class GitKVStore < KVStore def initialize @@mutex = Mutex.new @git = Git.new @index = nil end # @param [String] key # @return [Bool] def exists?(key) !get(key).nil? end # @param [String] key # @return [String] def get(key) @git.read_blob key end # @param [String] key # @param [String] value # @return [String] value def set(key, value) @@mutex.synchronize { do_set key, value } end def multi_set() @git.write "set" do |index| @index = index yield end @index = nil end # @param [String] key # @param [String] value def add(key, value) return if @index.nil? index.add @git.blob(value, key) end # @param [String] key def incr(key) @@mutex.synchronize { val = get key do_set key, (val.to_i + 1).to_s } end # @param [String] key_prefix # @return [Array] def multi_get_under(key_prefix) result = [] @git.read_tree(key_prefix).each_blob do |blob| key = blob[:name] value = @git.read(blob[:oid]).data result << {:key => key, :value => value} end result end private # @param [String] key # @param [String] value # @return [String] value def do_set(key, value) @git.write "set" do |index| index.add @git.blob(value, key) end end end
true
219fb81f4331ef260feb3873bd1eee37e714cce2
Ruby
jalidchaer/proyectoLaboratorioIIISICIP
/app/models/user.rb
UTF-8
2,949
2.5625
3
[]
no_license
require 'httparty' class User < ActiveRecord::Base VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i VALID_CI_REGEX = /[V,v|E,e]{1}+[0-9]/ include HTTParty has_secure_password validates :correo, uniqueness: {case_sensitive: false ,message: "Este correo ya fue registrado"}, format: { with: VALID_EMAIL_REGEX } attr_accessor :remember_token, :activation_token, :reset_token before_save :downcase_correo before_create :create_activation_digest validates :nombre, presence: true, length: { maximum: 50 } #validates :cedula, presence: true, format: { with: VALID_CI_REGEX } # Returns true if the given token matches the digest. def authenticated?(attribute, token) digest = send("#{attribute}_digest") return false if digest.nil? BCrypt::Password.new(digest).is_password?(token) end =begin # Activates an account. def activate update_attribute(:activated, true) update_attribute(:activated_at, Time.zone.now) end =end def User.digest(string) cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST : BCrypt::Engine.cost BCrypt::Password.create(string, cost: cost) end # Returns a random token. def User.new_token SecureRandom.urlsafe_base64 end # Remembers a user in the database for use in persistent sessions. def remember self.remember_token = User.new_token update_attribute(:remember_digest, User.digest(remember_token)) end # Activates an account. def activate update_attribute(:activated, true) update_attribute(:activated_at, Time.zone.now) end # Sends activation email. def send_activation_correo UserMailer.account_activation(self).deliver_now end # Sets the password reset attributes. def create_reset_digest self.reset_token = User.new_token update_attribute(:reset_digest, User.digest(reset_token)) update_attribute(:reset_sent_at, Time.zone.now) end # Sends password reset email. def send_password_reset_correo UserMailer.password_reset(self).deliver_now end # Sends mensaje. def enviar_mensaje UserMailer.enviar_mensaje(self).deliver_now end # Returns true if a password reset has expired. def password_reset_expired? reset_sent_at < 2.hours.ago end private # Converts email to all lower-case. def downcase_correo self.correo = correo.downcase end # Creates and assigns the activation token and digest. def create_activation_digest self.activation_token = User.new_token self.activation_digest = User.digest(activation_token) end def self.servidor @json = get("http://192.168.43.52:3000/profesors.json") @json = @json.to_json @parsed_json = ActiveSupport::JSON.decode(@json) return @parsed_json end end
true
36ebc58574e766bbf694c97e8f0c6f496b24f9c4
Ruby
mike1011/fetch_from_twitter
/app/models/tweet.rb
UTF-8
1,143
2.75
3
[]
no_license
class Tweet < ActiveRecord::Base require 'twitter' attr_accessor :value_to_search, :tweets validates_presence_of :value_to_search validates_length_of :value_to_search, :minimum => 2,:allow_blank => false attr_reader :errors ####Connect to the Twitter API and pull down the latest tweets""" def get_tweets ##added the rescue block to handle exceptions during no internet connection begin # hit the API Tweet.client.search(:value_to_search, :count => 10, :result_type => "recent").collect do |tweet| self.tweets << "#{tweet.urls}" end rescue errors.add :base, "It seems that something has went wrong,Please try after some time" if self.tweets == nil end end private #basic configuration using the credentials def self.client Twitter::REST::Client.new do |config| config.consumer_key = TWITTER_CREDENTIALS['consumer_key'] config.consumer_secret = TWITTER_CREDENTIALS['consumer_secret'] config.access_token = TWITTER_CREDENTIALS['token'] config.access_token_secret = TWITTER_CREDENTIALS['token_secret'] end end
true
fbe3cf9ecdb31c95caeb3fefdf27620f896f85db
Ruby
zergov/adventofcode2017
/day14/solution.rb
UTF-8
1,549
3.40625
3
[]
no_license
#!/usr/bin/env ruby require 'set' # from my day 10 solution def knot_hash(input) list = (0...256).to_a current = 0 skip = 0 lengths = input.chars.map(&:ord) + [17, 31, 73, 47, 23] 64.times do lengths.each do |n| # update current position list.rotate!(current) list = list.shift(n).reverse + list list.rotate!(-current) current += n + skip # increate skip skip += 1 end end # sparse hash 16.times .map { list.shift(16).reduce(:^) } .map {|x| x.to_s(16).rjust(2, '0')} .join end input = File.read('input.txt').strip grid = [] 128.times.each do |n| key = knot_hash("#{input}-#{n}") grid << key.chars.map {|x| x.hex.to_s(2).rjust(4, "0")}.join end # part1 p grid.flatten.join.count('1') def find_connections(start, grid, visited, current_area = Set.new) x, y = start # visit this dude visited << start current_area << start neighbors = [ [x, y + 1], [x, y - 1], [x + 1, y], [x - 1, y], ] .select {|(x, y)| x < 128 && x >= 0 && y < 128 && y >= 0 } .select {|(x, y)| grid[y][x] == '1'} .select {|position| !visited.include?(position) } neighbors.each do |neighbor| find_connections(neighbor, grid, visited, current_area) end current_area end # part2 area_count = 0 visited = Set.new 128.times do |y| 128.times do |x| next if grid[y][x] == '0' || visited.include?([x, y]) connections = find_connections([x, y], grid, visited) area_count += 1 if connections.size >= 1 end end # part2 p area_count
true
def76e887d97d52d4d85978baaa8f208d227ac55
Ruby
vitivey/reverse-each-word-v-000
/reverse_each_word.rb
UTF-8
323
3.546875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
string ="Hello there, and how are you?" def reverse_each_word(string) array = string.split #new_array=[] array.collect do |word| #new_array.push(word.reverse) USE THESE COMMENTED LINES FOR .each METHOD word.reverse! end puts array array.join(" ") #new_array.join(" ") end reverse_each_word(string)
true
8c0a65c2cd38b39cae2d6613c9d3cac9ffbe2924
Ruby
yyddcc/sample_app
/app/helpers/sessions_helper.rb
UTF-8
1,810
2.875
3
[]
no_license
module SessionsHelper # logs in the given user def log_in(user) session[:user_id] = user.id # why use id instead of email? end # remember a user in a persistent session. def remember(user) user.remember cookies.permanent.signed[:user_id] = user.id cookies.permanent[:remember_token] = user.remember_token end # Return true if the given user is the current user. def current_user?(user) user == current_user end #Return the user corresponding to the remember token cookie. def current_user if (user_id = session[:user_id]) #if session of user id exists @current_user ||= User.find_by(id: session[:user_id]) elsif (user_id = cookies.signed[:user_id]) #if persistent session of user id exists. user = User.find_by(id: user_id) if user && user.authenticated?(:remember, cookies[:remember_token]) # if the remember token is matched with remember digest in model log_in user # why log in user? since user was logged in when session was created @current_user = user end end end def logged_in? !current_user.nil? end # forgets a persistent session. def forget(user) user.forget #update the remember digest with nil cookies.delete(:user_id) cookies.delete(:remember_token) end # Logs out the current user. def log_out forget(current_user) session.delete(:user_id) @current_user = nil end # Redirects to stored location (or to the default. def redirect_back_or(default) redirect_to(session[:forwarding_url] || default) session.delete(:forwarding_url) # why delete? end # Stores the URL trying to be accessed. # puts the requested URL in the session variable under the key :forwarding_url only for a GET request. def store_location session[:forwarding_url] = request.url if request.get? # why if? end end
true
9e5681afd2c17de2df372250853ef095a6f3761f
Ruby
courts/snippets
/xsrfify/xsrfify.rb
UTF-8
2,907
2.875
3
[]
no_license
#!/usr/bin/env ruby ############################################################## # # # Written by Patrick Hof <courts@offensivethinking.org> # # http://www.offensivethinking.org # # # # This software is licensed under the Creative # # Commons CC0 1.0 Universal License. # # To view a copy of this license, visit # # http://creativecommons.org/publicdomain/zero/1.0/legalcode # # # ############################################################## # This script takes a POST request from stdin and returns a form with the action # set to the POST request's URL and hidden form fields for all of the parameters # in the body. # # Be aware of a common pitfall: If you have an element with the name or id # "submit" in your post data (and the chances are high), then the JavaScript # submit() function won't work anymore. Just use the "-d" option or delete the # element from the HTML source manually. require 'cgi' require 'optparse' options = { :delimiter => "\r\n", :full => false, :delsubmit => false } OptionParser.new do |opts| opts.banner = "Usage: #{__FILE__} [options]" opts.on("-n", "--newlines", 'Use \n as line delimiter when parsing the POST request instead of \r\n') do |n| options[:delimiter] = "\n" end opts.on("-f", "--full-page", "Print a full HTML page ready for XSRF instead of just the form") do options[:full] = true end opts.on("-d", "--delete-submit", 'Automatically delete parameters with the name "submit"') do options[:delsubmit] = true end opts.on("-h", "--help", "Show this help") do puts opts exit end end.parse! # HTML header and footer for a full HTML page with JavaScript for automatic # submission of the form data. This will trigger the post request as soon as the # HTML page is fully loaded. html_header = <<EOF <html> <head> <script type="text/javascript"> function send() { if (document.forms[0]) { var el = document.getElementById("submitform"); el.submit(); } else { setTimeout("send()", 1000); } } </script> </head> <body onload="send()"> EOF html_footer = " </body>\n</html>" headers, body = $stdin.read().split(options[:delimiter]*2) if body puts html_header if options[:full] url = headers.split("\r\n")[0].split(" ")[1] data = CGI.unescape(body.chomp).split("&").map { |x| x.split("=") } puts %Q( <form action="#{url}" id="submitform" method="post">) data.each do |i| unless (options[:delsubmit] && i[0] == "submit") puts %Q( <input type="hidden" name="#{i[0]}" value="#{i[1]}">) end end puts " </form>" puts html_footer if options[:full] end
true
e9c0fe2e14b0a17620f30a3257d4c0f00fb12901
Ruby
achan/ignoramos
/lib/commands/tweet_command.rb
UTF-8
370
2.640625
3
[ "MIT" ]
permissive
require 'fileutils' require 'tweets/tweet_option_parser' class TweetCommand attr_reader :publisher, :persister, :tweet def initialize(*args) @tweet = args.first options = TweetOptionParser.new.parse(args) @publisher = options.publisher @persister = options.persister end def execute persister.persist(publisher.publish(tweet)) end end
true
f24088d6bf0e5764ed72c60090f2e429dd88069f
Ruby
SethPerna/enigma
/spec/enigma_spec.rb
UTF-8
1,741
2.921875
3
[]
no_license
require_relative './spec_helper' require 'date' require './lib/enigma' RSpec.describe Enigma do let(:enigma) {Enigma.new} it 'exists' do expect(enigma).to be_an_instance_of(Enigma) end it 'has #char_set' do expect(enigma.char_set.count).to eq(27) end it "has date" do expect(enigma.today_date).to eq("111621") end it '#encrypt' do expected = {message: "keder ohulw", key: "02715", date: "040895"} expect(enigma.encrypt("hello world", "02715", "040895")).to eq(expected) end it '#encrypt without argument' do expect(enigma.encrypt("My name is Seth")).to be_an(Hash) end it 'can #decrypt' do expected = {message: "hello world", key: "02715", date: "040895"} expect(enigma.decrypt("keder ohulw", "02715", "040895")).to eq(expected) end it '#encrypt with #today_date' do expected = {message: "ojllkbeh", key: "12345", date: "111621"} expect(enigma.encrypt("Whats up", "12345")).to eq(expected) end it '#decrypt with #today_date' do enigma.encrypt("Whats up", "12345") expected = {message: "whats up", key: '12345', date: "111621"} expect(enigma.decrypt("ojllkbeh", "12345", "111621")).to eq(expected) end it '#encrypt and ignore special characters' do expected = {message: "keder ohulw!", key: "02715", date: "040895"} expect(enigma.encrypt("hello world!", "02715", "040895")).to eq(expected) end it '#decrypt and ignore special characters' do expected = {message: "hello world!", key: "02715", date: "040895"} expect(enigma.decrypt("keder ohulw!", "02715", "040895")).to eq(expected) end it '#encrypt with #today_date and #key_generator' do expect(enigma.encrypt("hello world")).to be_an_instance_of(Hash) end end
true
09e86d4a443c7c46a22cbb9b8587c849761ac6cc
Ruby
tochman/rps_demo
/spec/models/rps_spec.rb
UTF-8
1,399
2.90625
3
[]
no_license
require 'rps' describe RPS do it 'generates a computer responce' do allow(RPS).to receive(:computer_move).and_return('rock') computer_move = RPS.computer_move expect(computer_move).to eq 'rock' end describe 'declares computer a looser' do it 'if player = rock & computer = scissors' do allow(RPS).to receive(:computer_move).and_return('scissors') result = RPS.play('rock') expect(result[:message]).to eq 'computer lost' end it 'if player = paper & computer = rock' do allow(RPS).to receive(:computer_move).and_return('rock') result = RPS.play('paper') expect(result[:message]).to eq 'computer lost' end it 'if player = scissors & computer = paper' do allow(RPS).to receive(:computer_move).and_return('paper') result = RPS.play('scissors') expect(result[:message]).to eq 'computer lost' end end describe 'declares a draw' do it 'if both player and computer make the same move' do allow(RPS).to receive(:computer_move).and_return('paper') result = RPS.play('paper') expect(result[:message]).to eq 'it\'s a draw' end end describe 'computer wins' do it 'if player = scissors & computer = rock' do allow(RPS).to receive(:computer_move).and_return('rock') result = RPS.play('scissors') expect(result[:message]).to eq 'you lost' end end end
true
ad9540731af612ed1e76bd69dcc0f4d1bd910970
Ruby
alecn2002/HR.rb
/lib/lib/segment_tree.rb
UTF-8
4,045
2.9375
3
[]
no_license
class Range def shift(n) exclude_end? ? (first+n ... last+n) : (first+n .. last+n) end alias __cover? cover? def cover?(v) return __cover?(v) unless v.kind_of?(Range) return false if empty? || v.empty? __cover?(v.first) && __cover?(v.last - (v.exclude_end? ? 1 : 0)) end def split_to_halves return nil if size <= 1 mid = first + size / 2 [(first ... mid), (exclude_end? ? (mid ... last) : (mid .. last))] end def empty? size <= 0 end def intersect?(other) return false if empty? || other.empty? cover?(other) || [first, last - (exclude_end? ? 1 : 0)].any? {|v| other.__cover?(v) } end end module Enumerable def self._def_f(sym) ssym = sym.to_s last_char = ssym.end_with?('?', '!') ? ssym[-1] : "" fname = [ssym[0 .. -1 - last_char.size], last_char].join("f") to_eval = "def #{fname}(fun, *args); #{ssym} {|v| v.send(fun, *args)}; end" eval(to_eval) end def self.def_f(*args) args.each {|n| self._def_f(n)} end def_f :map, :all?, :any?, :each alias collectf mapf end class Array def to_range (min .. max) end end class SegmentTree def self.node_factory(st, range) return nil if range.empty? ((range.size == 1) ? SegmentTreeLeafNode : SegmentTreeNode).new(st, range) end class SegmentTreeLeafNode attr_reader :st, :range def initialize(st, range) @st, @range = st, range end def get(r) # $stderr << "SegmentTreeLeafNode{range=#{range}} # get(#{r})\n" return nil unless range.intersect?(r) # $stderr << " intersects\n" return st.ar[range.first] end def update!(*args) end end class SegmentTreeNode attr_reader :st, :range, :val attr_reader :children def initialize(st, range) # $stderr << "ar=#{ar} range=#{range}\n" range_spl = range.split_to_halves @st, @range, @children, @val = st, range, (range_spl.nil? ? [] : range_spl.map {|r| SegmentTree.node_factory(st, r) }.compact), nil end def get(r) # $stderr << "SegmentTreeNode{range=#{range}} # get(#{r})\n" return nil unless r.intersect?(range) # $stderr << " intersects\n" if r.cover?(range) then return val unless val.nil? # $stderr << " @val is nil, recalc-ing\n" # @val = st.fun.call( children.mapf(:get, r).compact ) @val = children.mapf(:get, r).compact.min else # $stderr << " Partial coverage\n" # st.fun.call( children.mapf(:get, r).compact ) children.mapf(:get, r).compact.min end end def update!(r) return nil unless range.cover?(r) @val = nil children.eachf(:update!, r) end def to_s(level = 0) "#{" "*2*level}SegmentTreeNode range = #{range} #{ children.mapf(:to_s, level+1).join("\n")}" end end attr_reader :ar, :tree, :fun def initialize(ar, fun) @ar, @fun = ar, fun @tree = SegmentTree.node_factory(self, (0...ar.size)) # $stderr << "Tree: #{tree}\n\n" end def get(range) # $stderr << "SegmentTree#get(#{range})\n" return nil if range.size < 1 return ar[range.first] if range.size == 1 tree.get(range) end def update!(r, v) ar[r] = v tree.update!(r) end end class MinSegmentTree < SegmentTree def initialize(ar) super(ar, lambda {|v| v.min } ) end end if __FILE__ == $0 then n, q = readline.strip.split(' ').mapf(:to_i) st = MinSegmentTree.new(readline.strip.split(' ').mapf(:to_i)) readlines.each {|l| spl = l.strip.split(' ') xy = spl[1..2].mapf(:to_i) case spl.first when 'q' puts st.get( xy.to_range.shift(-1) ) when 'u' st.update!( xy.first-1, xy.last ) else $stderr >> "Unknown command '#{spl.first}'\n" end } end
true
5391565701bf5139744f0c02eb7dbce1653dc5cc
Ruby
jalil/chatripper
/app/models/event.rb
UTF-8
934
2.8125
3
[]
no_license
class Event < ActiveRecord::Base validates :actor, presence: true validates :occurred_at, presence: true validates :action, presence: true def self.search_by_hour(time_one,time_two) where('time(occurred_at) BETWEEN ? AND ?', time_one, time_two) end def self.hourly_summary(time_one,time_two) summaries = self.search_by_hour(time_one,time_two) actions_array = [] counts = Hash.new(0) summaries.each { |summary| actions_array << summary.action } actions_array.each {|action| counts[action] +=1 } return counts end def self.retval_uniq_hours orig_val = 0 occurred_at_array = [] Event.all.each do |event| if orig_val != event.occurred_at.strftime("%H") orig_val = event.occurred_at.strftime("%H") occurred_at_array << orig_val end end return occurred_at_array end end
true
173a6590ac6e9d486db779b8a76794f951c10273
Ruby
Aurea-Li/grocery-store
/lib/order.rb
UTF-8
1,467
3.265625
3
[]
no_license
class Order attr_reader :id, :customer, :products attr_accessor :fulfillment_status def initialize(id, products, customer, fulfillment_status=:pending) @id = id @customer = customer @products = products unless [:pending, :paid, :processing, :shipped, :complete ].include?(fulfillment_status) raise ArgumentError, "Invalid fulfillment status #{fulfillment_status}. Please try again." end @fulfillment_status = fulfillment_status end def self.all CSV.open("data/orders.csv", "r").map do |row| customer = Customer.find(row[2]) # Parse out products from string format products = {} row[1].split(';').each do |product_string| product = product_string.split(':') products[product[0]] = product[1].to_f end Order.new(row[0].to_i, products, customer, row[3].to_sym) end end def self.find(id) orders = self.all return orders.find{ |order| order.id == id } end def self.find_by_customer(customer_id) orders = self.all return orders.find_all do |order| order.customer.id == customer_id end end def total return ( @products.sum{ |product, price| price } * 1.075 ).round(2) end def add_product(product_name, price) if @products.include?(product_name) raise ArgumentError, "Product #{product_name} is already included in products list. Please try again." end @products[product_name] = price end end
true
5fffeadc54c0f3e60a4d2ce49538ec3439ca2088
Ruby
moolitayer/kubeclient
/test/test_watch_notice.rb
UTF-8
1,646
2.515625
3
[ "MIT" ]
permissive
require_relative 'test_helper' class TestWatchNotice < MiniTest::Test # # Checks that elements of arrays are converted to instances of `RecursiveOpenStruct`, and that the # items can be accessed using the dot notation. # def test_recurse_over_arrays json = JSON.parse(open_test_file('node_notice.json').read) notice = Kubeclient::Common::WatchNotice.new(json) assert_kind_of(Array, notice.object.status.addresses) notice.object.status.addresses.each do |address| assert_kind_of(RecursiveOpenStruct, address) end assert_equal('InternalIP', notice.object.status.addresses[0].type) assert_equal('192.168.122.40', notice.object.status.addresses[0].address) assert_equal('Hostname', notice.object.status.addresses[1].type) assert_equal('openshift.local', notice.object.status.addresses[1].address) end # # Checks that even when arrays are converted to instances of `RecursiveOpenStruct` the items can # be accessed using the hash notation. # def test_access_array_items_as_hash json = JSON.parse(open_test_file('node_notice.json').read) notice = Kubeclient::Common::WatchNotice.new(json) assert_kind_of(Array, notice.object.status.addresses) notice.object.status.addresses.each do |address| assert_kind_of(RecursiveOpenStruct, address) end assert_equal('InternalIP', notice.object.status.addresses[0]['type']) assert_equal('192.168.122.40', notice.object.status.addresses[0]['address']) assert_equal('Hostname', notice.object.status.addresses[1]['type']) assert_equal('openshift.local', notice.object.status.addresses[1]['address']) end end
true