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
a4589a39f702b138193ec39daab9137c20bce096
Ruby
sharat94/dictor
/lib/run_me.rb
UTF-8
977
2.78125
3
[]
no_license
#!/usr/bin/env ruby require 'optparse' require_relative 'dictor' @options= {} OptionParser.new do |opts| opts.on("-v", "--verbose", "Show logs") do @options[:verbose] = true end opts.on('--dictionary DICTFILE', '-d', 'Specify dictionary file') { |file| File.open(file) { |f| @options[:dict] = f.readlines } } opts.on('--phonenumbers PHONEFILE', '-p', 'Specify phone numbers file') { |file| File.open(file) { |f| @options[:phones] = f.readlines } } end.parse! phones = @options[:phones] dict = @options[:dict] || File.open('dict.txt') { |f| @options[:dict] = f.readlines } if phones.nil? puts 'Enter phone number' while phone = gets phone.gsub!(/[^\d]/, '') next if phone.empty? phones = [phone] Dictor.new(verbose: @options[:verbose], dict: dict, phones: phones).process! end end Dictor.new(verbose: @options[:verbose], dict: dict, phones: phones).process!
true
90512c21f53afb22f5f930de9e84837cadb9ac76
Ruby
thomas-holmes/rspec-spy_on
/lib/rspec/spy_on/example_methods.rb
UTF-8
1,607
2.6875
3
[ "MIT" ]
permissive
module RSpec::SpyOn module ExampleMethods # Enables an RSpec::Mocks::TestDouble or any other object to act as # a test spy. Delegates to RSpec::Mocks to configure the allowing of # the messages # # In particular, `spy_on` makes this act of configuring real objects # as spies easier by providing more concise syntax for configuring # spying on multiple methods while forwarding the messages along # to the original implementations. # # @example # person = Person.new("Ally", 22) # spy_on(person, :name, :age) # # use `person` in a test # expect(person).to have_received(:name) # expect(person).to have_received(:age) # # @param target [Object/RSpec::Mocks::TestDouble] The object to be spied on # @param messages [Array] Array of symbols for messages that should configured for spying # @return (target) def spy_on(target, *messages) if target.is_a?(RSpec::Mocks::TestDouble) messages.each { |m| RSpec::Mocks.allow_message(target, m) } else messages.each { |m| allow_partial(target, m) } end target end private # If a non RSpec::Mocks::TestDouble is to be a spy then it any messags # sent should be forwarded to the original object # # @private def allow_partial(target, message) if target.respond_to?(message) RSpec::Mocks.allow_message(target, message).and_call_original else RSpec::Mocks.allow_message(target, message) end end end end RSpec.configuration.include RSpec::SpyOn::ExampleMethods
true
5ff9f0bc1477baa5c6ddec134b7b095215c08319
Ruby
ihassin/alexa_verifier
/lib/alexa_verifier.rb
UTF-8
3,421
2.828125
3
[ "MIT" ]
permissive
require 'net/http' require 'openssl' require 'base64' require 'time' require 'json' class AlexaVerifier VERSION = '0.1.0' class VerificationError < StandardError; end DEFAULT_TIMESTAMP_TOLERANCE = 150 VALID_CERT_HOSTNAME = 's3.amazonaws.com' VALID_CERT_PATH_START = '/echo.api/' VALID_CERT_PORT = 443 class Builder attr_accessor :verify_signatures, :verify_timestamps, :timestamp_tolerance def initialize @verify_signatures = true @verify_timestamps = true @timestamp_tolerance = DEFAULT_TIMESTAMP_TOLERANCE end def create AlexaVerifier.new(verify_signatures, verify_timestamps, timestamp_tolerance) end end def self.build(&block) builder = Builder.new block.call(builder) builder.create end def initialize(verify_signatures = true, verify_timestamps = true, timestamp_tolerance = DEFAULT_TIMESTAMP_TOLERANCE) @cert_cache = {} @verify_signatures = verify_signatures @verify_timestamps = verify_timestamps @timestamp_tolerance = timestamp_tolerance end def verify!(cert_url, signature, request) verify_timestamp!(request) if @verify_timestamps if @verify_signatures x509_cert = cert(cert_url) public_key = x509_cert.public_key unless public_key.verify(hash_type, Base64.decode64(signature), request) raise VerificationError.new, 'Signature does not match!' end end true end private def verify_timestamp!(request) request_json = JSON.parse(request) if request_json['request'].nil? or request_json['request']['timestamp'].nil? raise VerificationError.new, 'Timestamp field not present in request' end unless Time.parse(request_json['request']['timestamp']) >= (Time.now - @timestamp_tolerance) raise VerificationError.new, "Request is from more than #{@timestamp_tolerance} seconds ago" end end def hash_type OpenSSL::Digest::SHA1.new end def cert(cert_url) if @cert_cache[cert_url] @cert_cache[cert_url] else cert_uri = URI.parse(cert_url) validate_cert_uri!(cert_uri) @cert_cache[cert_url] = OpenSSL::X509::Certificate.new(download_cert(cert_uri)) end end def download_cert(uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_PEER http.start response = http.request(Net::HTTP::Get.new(uri.request_uri)) http.finish if response.code == '200' response.body else raise VerificationError, "Failed to download certificate at: #{uri}. Response code: #{response.code}, error: #{response.body}" end end def validate_cert_uri!(cert_uri) unless cert_uri.scheme == 'https' raise VerificationError, "Certificate URI MUST be https: #{cert_uri}" end unless cert_uri.port == VALID_CERT_PORT raise VerificationError, "Certificate URI port MUST be #{VALID_CERT_PORT}, was: #{cert_uri.port}" end unless cert_uri.host == VALID_CERT_HOSTNAME raise VerificationError, "Certificate URI hostname must be #{VALID_CERT_HOSTNAME}: #{cert_uri}" end unless cert_uri.request_uri.start_with?(VALID_CERT_PATH_START) raise VerificationError, "Certificate URI path must start with #{VALID_CERT_PATH_START}: #{cert_uri}" end end end
true
9e21cde41bafe1cf01b74dee245429557ebae4eb
Ruby
thefulltimereader/reblog
/app/example_user.rb
UTF-8
322
3.03125
3
[]
no_license
class Example_user attr_accessor :name, :email # gives us getter/setter def initialize(attributes = {}) @name = attributes[:name] @email = attributes[:email] end def formatted_email "#{@name} <#{@email}>" end #exercises ch 4 def shuffle_str(str) str.split('').to_a.shuffle.join end end
true
257a677f3ab9b4d37a1f4aaeba37344f759e0ebb
Ruby
learn-co-students/seattle-web-071519
/04-one-to-many/apollo/lib/mission.rb
UTF-8
193
3.078125
3
[]
no_license
class Mission attr_reader :name attr_accessor :crew @@all = [] def initialize(name, crew) @name = name @crew = crew @@all << self end def self.all @@all end end
true
63bd4490db687ad9eef600f093bddd6d819c673c
Ruby
GreenRabite/Algorithms
/Practice Problems/mock_interview_02.rb
UTF-8
1,351
3.484375
3
[]
no_license
# How to build a LRU Cache # LRU cache is a combination of Hashed Maps and LinkedLists using the # best of both worlds. You will have an array of linked lists that # will periodically kick out from memory the oldest saved value from # the cache # To do this you must first understand what a Linkedlist and #hashed map is. A hashed map is an abstract datastructure that is estenially # an array of linked lists. The linked lists is another abstract data type that # hold the actual objects for fast lookup memory # How this works is that you want to input something into memory. Since this # was recently seen, this will become the head of the linked list. in terms # of actually implementing it, it will become the tail of the linked list. # Now when you want to add something else, the LRU cache checks to see # if the hash already exist by looking at the hash map. If it does exist, # it will remove that node in the linked list from whatever spot it was at # and move it to the most recently seen which is commonly the tail # Otherwise if it doesnt exist it will shove it to the end of the LinkedList # Once the length of the linkedlist reach the capcity, the uncached # version will get hashed and shoved as the tail of the linked list. the #element that is not at the head will get 'ejected' (estenially removing it # self from the linkedlist)
true
cea9c2c2ffe8fb7505c7bebdc490ffca21479d4a
Ruby
fgrehm/clipper
/lib/clipper/query/query.rb
UTF-8
1,035
2.5625
3
[]
no_license
module Clipper class Query def initialize(mapping, options, conditions) @mapping = mapping @conditions = conditions if options @limit = options.fetch(:limit, nil) @offset = options.fetch(:offset, nil) @order = options.fetch(:order, nil) end end def mapping @mapping end def limit @limit end def offset @offset end def order @order end def conditions @conditions end def paramaters case @conditions when nil then [] when Condition then [@conditions.value] else begin @conditions.values.map { |condition| condition.value } rescue NoMethodError => nme p @conditions raise end end end def fields case @conditions when nil then [] when Condition then [@conditions.field] else @conditions.values.map { |condition| condition.field } end end end end
true
a0ac157bc8c11282a6c011f3e3168f1ec5d2e04d
Ruby
flywheelnetworks/rails-google-visualization-plugin
/lib/google_visualization.rb
UTF-8
5,214
2.671875
3
[ "MIT" ]
permissive
# GoogleVisualization module GoogleVisualization class GoogleVis attr_reader :collection, :collection_methods, :options, :size, :helpers, :procedure_hash, :name @@vis_types = { 'motionchart' => 'MotionChart', 'linechart' => 'LineChart', 'annotatedtimeline' => 'AnnotatedTimeLine', 'table' => 'Table', 'geomap' => 'GeoMap' } def columns case @vis_type when 'motionchart' [:label, :time, :x, :y, :color, :bubble_size] when 'annotatedtimeline' [:time] else [] end end def method_missing(method, *args, &block) if self.columns.include?(method) procedure_hash[method] = [args[0], block] else helpers.send(method, *args, &block) end end def initialize(view_instance, collection, vis_type, options={}, *args) @helpers = view_instance @collection = collection @vis_type = vis_type @collection_methods = collection_methods @options = options.reverse_merge({:width => 600, :height => 300}) @columns = [] @rows = [] if self.columns.include?(:color) @procedure_hash = {:color => ["Department", lambda {|item| label_to_color(@procedure_hash[:label][1].call(item)) }] } else @procedure_hash = {} end @size = collection.size @name = "google_vis_#{self.object_id.to_s.gsub("-","")}" @labels = {} @color_count = 0 end def header content_tag(:div, "", :id => name, :style => "width: #{options[:width]}px; height: #{options[:height]}px;") end def body javascript_tag do "var data = new google.visualization.DataTable();\n" + "data.addRows(#{size});\n" + render_columns + render_rows + "var #{name} = new google.visualization.#{@@vis_types[@vis_type]}(document.getElementById('#{name}'));\n" + "#{name}.draw(data, #{options.to_json});" end end def render header + "\n" + body end def render_columns if required_methods_supplied? self.columns.each { |c| @columns << google_vis_add_column(procedure_hash[c]) } procedure_hash.each { |key, value| @columns[key] = google_vis_add_column(value) if not self.columns.include?(key) } @columns.join("\n") end end def render_rows if required_methods_supplied? collection.each_with_index do |item, index| self.columns.each_with_index {|name,column_index| @rows << google_vis_set_value(index, column_index, procedure_hash[name][1].call(item)) } procedure_hash.each {|key,value| @rows << google_vis_set_value(index, key, procedure_hash[key][1].call(item)) unless self.columns.include?(key) } end @rows.join("\n") end end def required_methods_supplied? self.columns.each do |key| unless procedure_hash.has_key? key raise "GoogleVis Must have the #{key} method called before it can be rendered" end end end def google_vis_add_column(title_proc_tuple) title = title_proc_tuple[0] procedure = title_proc_tuple[1] "data.addColumn('#{google_type(procedure)}','#{title}');\n" end def google_vis_set_value(row, column, value) "data.setValue(#{row}, #{column}, #{Mappings.ruby_to_javascript_object(value)});\n" end def google_type(procedure) Mappings.ruby_to_google_type(procedure.call(collection[0]).class) end def google_formatted_value(value) Mappings.ruby_to_javascript_object(value) end def label_to_color(label) hashed_label = label.downcase.gsub(" |-","_").to_sym if @labels.has_key? hashed_label @labels[hashed_label] else @color_count += 1 @labels[hashed_label] = @color_count end end def extra_column(title, &block) procedure_hash[procedure_hash.size] = [title, block] end end module Mappings def self.ruby_to_google_type(type) type_hash = { :String => "string", :Fixnum => "number", :Float => "number", :Date => "date", :Time => "datetime", :NilClass => 'string', } type_hash[type.to_s.to_sym] end def self.ruby_to_javascript_object(value) value_hash = { :String => lambda {|v| "'#{v}'"}, :Date => lambda {|v| "new Date(#{v.to_s.gsub("-",",")})"}, :Fixnum => lambda {|v| v }, :Float => lambda {|v| v }, :NilClass => lambda {|v| 'null'}, } value_hash[value.class.to_s.to_sym].call(value) end end module Helpers # types: an array of packages like: 'motionchart', 'geomap', etc def setup_google_vis(types) packages = '"' + types.to_a.join('", "') + '"' "<script type=\"text/javascript\" src=\"http://www.google.com/jsapi\"></script>\n" + javascript_tag("google.load(\"visualization\", \"1\", {packages:[#{packages}]});") end def google_vis_for(collection, vis_type, options={}, *args, &block) google_vis = GoogleVis.new(self, collection, vis_type, options) yield google_vis concat(google_vis.render) end end end
true
e3e17f0e5fe66fed7f521eeae61bcadb359c19d3
Ruby
ErikNPeterson/Erik-s-Ruby-Math-Game-
/playerManager.rb
UTF-8
685
3.375
3
[]
no_license
require_relative './question' class PlayerManager # determining which players turn it is attr_reader :current_player, :enemy_player def initialize(players) @players = players.shuffle @current_player = nil @round = 1 end def get_current_player @players.first end def next_turn @current_player = get_current_player puts "------ Round##{@round} ------" puts "" puts "Question for #{@current_player.name}" @question = Question.new @round += 1 puts "" puts @question.question @players.rotate! end def check_answer(answer) if !@question.check_answer(answer) @current_player.wrong_answer end end end
true
d5634f4d1f5e74a9c4693ef7acdb5659ded93006
Ruby
alve-svaren-nti-johanneberg/school
/programmering1/overleaf_uppgifter/average.rb
UTF-8
346
3.453125
3
[]
no_license
require_relative "./average_number.rb" def average(numbers) if numbers.class != Array raise TypeError, "'numbers' must be an array" end for number in numbers if !number.is_a? Numeric raise TypeError, "'numbers' must only contain numeric values" end end return average_number(numbers) end
true
f30e483cb41f99733c5547863bd17e888b745542
Ruby
briiking/AdTopics
/Ruby-labs/Greetings-lab.rb
UTF-8
132
3.8125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
puts "How many years old are you?" years = gets.chomp.to_i def age(years) puts "You are #{years * 365} days old." end age(years)
true
64788f0902089eb50bfe41ec9f27848fbbae68ea
Ruby
kuboj/bitstat-test
/spec/unit/ticker_spec.rb
UTF-8
1,345
2.734375
3
[ "Apache-2.0" ]
permissive
require 'spec_helper' describe Bitstat::Ticker do describe '#new' do it 'takes only one argument - interval' do expect { Bitstat::Ticker.new() }.to raise_error(ArgumentError) expect { Bitstat::Ticker.new(10) }.not_to raise_error end end let(:interval) { 0.1 } let(:ticker) { Bitstat::Ticker.new(interval) } describe '#start' do it 'takes block as argument' do expect { ticker.start(10) }.to raise_error(ArgumentError) expect { ticker.start {} }.not_to raise_error end it 'calls given block each `interval` seconds' do t = [] ticker.start { t << (Time.now.to_f * 10).to_i } sleep 0.8 (t[1] - t[0]).should eql 1 (t[2] - t[1]).should eql 1 (t[3] - t[2]).should eql 1 end end describe '#stop' do let(:m) { Mutex.new } it 'prevents from next execution of block given in #start' do i = 0 ticker.start do sleep 0.3 m.synchronize { i = 1 } end ticker.stop ticker.join m.synchronize { i }.should eql 1 end end describe '#stop!' do let(:m) { Mutex.new } it 'kills inner ticker thread' do i = 0 ticker.start do sleep 1 m.synchronize { i = 1 } end ticker.stop! ticker.join m.synchronize { i }.should eql 0 end end end
true
14bdc48b7ce64bdd95a0251c3912981cfa593d2d
Ruby
furafura/intro-to-simple-array-manipulations-001-prework-web
/lib/intro_to_simple_array_manipulations.rb
UTF-8
660
3.234375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def using_push(array, char) array.push(add) end def using_unshift(array, char) array.unshift(char) end def using_push(array, char) array.push(char) end def using_pop(array) array.pop end def pop_with_args(array) array.pop(2) end def using_shift(array) array.shift end def shift_with_args(array) array.shift(2) end def using_concat(array, new_array) array.concat(new_array) end def using_insert(array, value) array.insert(4,value) end def using_uniq(array) array.uniq end def using_flatten(array) array.flatten end def using_delete(array, value) array.delete(value) end def using_delete_at(array, index) array.delete_at(index) end
true
5799bc26b2b22679bf9ef6969fbfbd1a298098be
Ruby
nippysaurus/credit-card-validation
/classes/credit_card_number.rb
UTF-8
1,247
3.578125
4
[]
no_license
require_relative '../helpers/string' class CreditCardNumber attr_accessor :number def initialize(number) @number = number.strip_whitespace end # Attempts to classify the card type. def card_type return 'AMEX' if is_amex_card? return 'Discover' if is_discover_card? return 'MasterCard' if is_mastercard_card? return 'VISA' if is_visa_card? 'Unknown' end def is_amex_card? /^(34|37)\d{13}$/ =~ @number end def is_discover_card? /^6011\d{12}$/ =~ @number end def is_mastercard_card? /^(51|52|53|54|55)\d{14}$/ =~ @number end def is_visa_card? /^4(\d{12}|\d{15})$/ =~ @number end # Performs the standard Luhn Algorythm check. # http://en.wikipedia.org/wiki/Luhn_algorithm def luhn_algorythm_check number_copy = @number.clone number_copy.prepend('0') if number_copy.length.odd? number_copy.reverse! sum = 0 number_copy.chars.each_slice(2) do |slice| sum += slice[0].to_i doubled = slice[1].to_i * 2 doubled -= 9 if doubled > 9 sum += doubled end sum % 10 == 0 end alias :valid? :luhn_algorythm_check def to_s "#{card_type}: #{@number}".ljust(30) + "(#{ valid? ? 'valid' : 'invalid' })" end end
true
b25d5c3bc89e2c0b08b647c9188c1ec132c56eff
Ruby
alansparrow/learningruby
/http_checking_error_and_redirect.rb
UTF-8
673
2.953125
3
[]
no_license
#!/usr/bin/env ruby require 'net/http' def get_web_document(url) uri = URI.parse(url) response = Net::HTTP.get_response(uri) case response when Net::HTTPSuccess return response.body when Net::HTTPRedirection puts "This is redirect link: " + response['Location'].to_s return get_web_document(response['Location']) when Net::HTTPNotFound puts "File not found" when Net::HTTPForbidden puts "Forbidden area!" else return "Fuck you!" end end puts get_web_document('http://www.rubyinside.com/test.txt') puts get_web_document('http://www.rubyinside.com/non-existent') puts get_web_document('http://www.rubyinside.com/redirect-test')
true
a33a2eea987541050e2b4d7a57e1895b60189470
Ruby
monora/stream
/test/teststream.rb
UTF-8
5,717
3.171875
3
[ "Ruby", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'test/unit' require 'stream' module StreamExamples def new_collection_stream (1..5).create_stream; end # a stream which is aquivalent to new_collection_stream def new_implicit_stream Stream::ImplicitStream.new { |s| x = 0 s.at_beginning_proc = proc { x < 1 } s.at_end_proc = proc { x == 5 } s.forward_proc = proc { x += 1 } s.backward_proc = proc { y = x; x -= 1; y } s.set_to_begin_proc = proc { x = 0 } s.set_to_end_proc = proc { x = 5 } } end def filtered_streams [ new_collection_stream.filtered { |x| true }, new_collection_stream.filtered { |x| false }, new_collection_stream.filtered { |x| x > 3 }, new_collection_stream.filtered { |x| x % 2 == 0 }, new_collection_stream.filtered { |x| x % 2 == 0 }.filtered { |x| x > 3 } ] end def new_concatenated_stream [1, 2, 3].create_stream.concatenate_collected { |i| [i, -i].create_stream } end def all_examples [ new_collection_stream, new_implicit_stream, new_collection_stream.remove_first, new_collection_stream.remove_last, new_collection_stream.remove_first.remove_last, Stream::WrappedStream.new(new_collection_stream), Stream::IntervalStream.new(6), Stream::IntervalStream.new(1), new_collection_stream.collect { |x| x * 2 }, # Some concatenated streams Stream::EmptyStream.instance.concatenate, new_concatenated_stream, # concatenated inside concatenated new_concatenated_stream + new_concatenated_stream, new_collection_stream + Stream::EmptyStream.instance, Stream::EmptyStream.instance + new_collection_stream ].concat(filtered_streams) end private def standard_tests_for(s) array_stream = s.to_a.create_stream # A collection stream that should be OK assert_equal(s.to_a, array_stream.to_a) # Tests at end of stream assert_equal(s.at_end?, array_stream.at_end?) assert_raises(Stream::EndOfStreamException) { s.forward } assert_equal(s.at_beginning?, array_stream.at_beginning?) assert_equal(s.peek, s) unless array_stream.at_beginning? assert_equal(array_stream.current, s.current) assert_equal(array_stream.backward, s.backward) end assert_equal(array_stream.at_end?, s.at_end?) # Tests at begin of stream s.set_to_begin; array_stream.set_to_begin assert_raises(Stream::EndOfStreamException) { s.backward } assert_equal(s.at_beginning?, array_stream.at_beginning?) assert_equal(s.at_end?, array_stream.at_end?) assert_equal(s.current, s) unless array_stream.at_end? assert_equal(s.peek, array_stream.peek) assert_equal(s.forward, array_stream.forward) assert_equal(s.current, array_stream.current) unless array_stream.at_end? assert_equal(s.peek, array_stream.peek) end end end end class TestStream < Test::Unit::TestCase include StreamExamples def test_enumerable s = new_collection_stream assert_equal([2, 4, 6, 8, 10], s.collect { |x| x * 2 }.entries) assert_equal([2, 4], s.select { |x| x[0] == 0 }) # even numbers end def test_collection_stream s = new_collection_stream assert_equal([1, 2, 3, 4, 5], s.entries) assert(s.at_end?) assert_raises(Stream::EndOfStreamException) { s.forward } assert_equal(5, s.backward) assert_equal(5, s.forward) assert_equal(5, s.current) assert_equal(s, s.peek) s.set_to_begin assert(s.at_beginning?) assert_raises(Stream::EndOfStreamException) { s.backward } assert_equal(s, s.current) assert_equal(1, s.peek) assert_equal(1, s.forward) assert_equal(1, s.current) assert_equal(2, s.peek) # move_forward_until assert_equal(4, s.move_forward_until { |x| x > 3 }) assert_equal(nil, s.move_forward_until { |x| x < 3 }) assert(s.at_end?) s.set_to_begin assert_equal(nil, s.move_forward_until { |x| x > 6 }) end def test_standard_for_examples all_examples.each do |example_stream| standard_tests_for(example_stream) end end def test_for_examples_reversed all_examples.each do |example_stream| assert_equal(example_stream.entries.reverse, example_stream.reverse.entries) assert_equal(example_stream.entries, example_stream.reverse.reverse.entries) standard_tests_for(example_stream.reverse) standard_tests_for(example_stream.reverse.reverse) end end def test_filtered_stream [(1..6).create_stream.filtered { |x| x % 2 == 0 }].each do |s| standard_tests_for(s) end end def test_interval_stream s = Stream::IntervalStream.new 6 standard_tests_for(s) assert_equal([0, 1, 2, 3, 4, 5], s.entries) s.increment_stop assert(!s.at_end?) assert_equal([0, 1, 2, 3, 4, 5, 6], s.entries) standard_tests_for(s) end def test_enumerable_protocol s = [1, 2, 3, 4, 5].create_stream assert(s.include?(2)) assert_equal(3, s.detect { |x| x > 2 }) assert_equal(nil, s.detect { |x| x < 0 }) assert_equal([1, 2], s.find_all { |x| x < 3 }) end def test_modified_stream a = [1, 2, 3] assert_equal([2, 3], a.create_stream.remove_first.to_a) assert_equal([1, 2], a.create_stream.remove_last.to_a) assert_raises(Stream::EndOfStreamException) { [1].create_stream.remove_last.forward } assert_raises(Stream::EndOfStreamException) { [1].create_stream.remove_first.forward } end def test_concatenated_empty_stream s = Stream::EmptyStream.instance + Stream::EmptyStream.instance assert s.at_end? assert s.at_beginning? end end
true
3b9e5aa735035e49ff15474aee2144da57b6ab95
Ruby
zosiu/nand2tetris
/hack_assembler/lib/nodes.rb
UTF-8
1,410
2.625
3
[]
no_license
# frozen_string_literal: true module Hack class Vars attr_accessor :variables, :next_var def initialize @variables = { 'R0' => 0, 'R1' => 1, 'R2' => 2, 'R3' => 3, 'R4' => 4, 'R5' => 5, 'R6' => 6, 'R7' => 7, 'R8' => 8, 'R9' => 9, 'R10' => 10, 'R11' => 11, 'R12' => 12, 'R13' => 13, 'R14' => 14, 'R15' => 15, 'SCREEN' => 16_384, 'KBD' => 24_576, 'SP' => 0, 'LCL' => 1, 'ARG' => 2, 'THIS' => 3, 'THAT' => 4 } @next_var = 16 end end DirectAddress = Struct.new(:value) do def address_value value end def generate(_ins_num, _vars); end end NamedAddress = Struct.new(:name) do def generate(_ins_num, vars) @address_value ||= vars.variables[name] return if @address_value @address_value = vars.next_var vars.variables[name] = @address_value vars.next_var += 1 end def address_value @address_value end end AInstruction = Struct.new(:address) do def generate(ins_num, vars) address.generate(ins_num, vars) address.address_value.to_i.to_s(2).rjust(16, '0') end end Label = Struct.new(:name) do def generate(ins_num, vars) vars.variables[name] ||= ins_num nil end end DInstructon = Struct.new(:dest, :comp, :jump) do def generate(_ins_num, _vars) "111#{comp}#{dest}#{jump}" end end end
true
54405de0bb949e902e30649d3f6837a9a70ed5db
Ruby
martinkilmartin/Web-Framework
/framework.rb
UTF-8
1,200
2.90625
3
[ "MIT" ]
permissive
class App def initialize(&block) @routes = RouteTable.new(block) end def call(env) request = Rack::Request.new(env) @routes.each do |route| content = route.match(request) return [200, {'Content-Type' => 'text/html'}, [content.to_s]] if content end [404, {}, ["Not found"]] end class RouteTable def initialize(block) @routes = [] instance_eval(&block) end def get(route_spec, &block) @routes << Route.new(route_spec, block) p @routes end def each(&block) @routes.each(&block) end end class Route < Struct.new(:route_spec, :block) def match(request) path_components = request.path.split('/') spec_components = route_spec.split('/') params = {} return nil unless path_components.length == spec_components.length path_components.zip(spec_components).each do |path_comp, spec_comp| is_var = spec_comp.start_with?(':') if is_var key = spec_comp.sub(/\A:/, '') params[key] = URI.decode(path_comp) else return nil unless path_comp == spec_comp end end block.call(params) end end end
true
e8996daa394b527e857131ba2220aaab2ce11aaa
Ruby
DagmaraSz/learn_to_program
/ch10-nothing-new/shuffle.rb
UTF-8
685
3.875
4
[]
no_license
=begin Defining perfect shuffle as one where no card happens after the same card it did before. Implementation here inspired by the "faro in-shuffle" =end def shuffle arr #split the array in two left, right = arr.each_slice((arr.size/2.0).round).to_a #generate new array where the two arrays intertwine i = 0 shuffled = [] while i < right.length shuffled << left[i] shuffled << right[i] i += 1 end shuffled << left[i] if i < left.length # for case when arr.length is odd #move the first element to the end shuffled << shuffled[0] shuffled.delete_at(0) return shuffled end puts shuffle([1,2,3,4,5]).to_s puts shuffle([10,20,30,40]).to_s
true
28a341ae2dc2ee5cde8b4985a65d830850283cf7
Ruby
lsethi-xoriant/angular_rails_material_example
/lib/param_filters/posts_param_filter.rb
UTF-8
2,385
2.71875
3
[ "MIT" ]
permissive
class PostsParamFilter < ParamFilter LEAGUE_JOIN_KEY = :leaguejoin class << self def custom_params super + %w(q league_type) end def exclusions %w(id league_id post_id league_type user_id deleted_at) end def possible_hockey_league_params possible_params_for_class HockeyLeague, %w(id), joinable_keys: LEAGUE_JOIN_KEY end def possible_football_league_params possible_params_for_class FootballLeague, %w(id), joinable_keys: LEAGUE_JOIN_KEY end def possible_baseball_league_params possible_params_for_class BaseballLeague, %w(id), joinable_keys: LEAGUE_JOIN_KEY end end def joinables !!filtered_league_type ? {LEAGUE_JOIN_KEY => filtered_league_type} : {} end def filter_league_type(value) return value if LeagueLike::ALL_LEAGUE_CLASSES.map(&:to_s).include?(value) end def filter_q(value) return value.to_s.split /\W+/ end def filter_sort_order(value) table, column = value.split '.' super_value = super(value) return super_value if !!super_value || !column # Handle any sorting of joined tables filtered_class = self.class.filtered_class filtered_table = filtered_class.table_name if !!filtered_league_type # Already joining a certain league type, so we must limit the ordering to # that league's attributes. if can_order_by_table_column?(filtered_league_type.constantize, table, column) [table, column].join '.' end elsif filtered_league_type = filter_league_type(table.classify) if can_order_by_table_column?(table.classify.constantize, table, column) [table, column].join '.' end end end private def filtered_league_type @filtered_league_type ||= filter_league_type(initial_params[:league_type]) end # Only `Post` params if `league_type` is nil. # Otherwise, include params based on `league_type`.\ def possible_params super + possible_league_params end def possible_league_params if !!filtered_league_type league_param_ivar_name = "#{filtered_league_type.underscore}_params" memoized_league_params = instance_variable_get "@#{league_param_ivar_name}" memoized_league_params ||= instance_variable_set "@#{league_param_ivar_name}", self.class.public_send("possible_#{league_param_ivar_name}") else [] end end end
true
1ffcab8af17eee2fe9632120017d8912cf4ba48d
Ruby
robinrob/ruby
/practice/read_file.rb
UTF-8
621
3.328125
3
[]
no_license
#!/usr/bin/env ruby $LOAD_PATH << '.' require 'lib/log.rb' # Example 1 - Read File and close counter = 1 file = File.new("read_file.rb", "r") while (line = file.gets) printf "%02d: %s".green, counter, line counter = counter + 1 end file.close puts # Example 2 - Pass file to block counter = 1 File.open("read_file.rb", "r") do |infile| while (line = infile.gets) printf "%02d: %s".yellow, counter, line counter = counter + 1 end end contents = File.open("read_file.rb", "r") do |infile| contents = "" while (line = infile.gets) contents << line.magenta end contents end print contents
true
d67e110038eb68a2c7f09ac784ac9a725b0eda0b
Ruby
joshy91/test-guide
/kilosSon.rb
UTF-8
201
3.796875
4
[]
no_license
def yoSon puts "Yo Son" end yoSon yoSon yoSon def pound_kilo num = gets.chomp kilo = num.to_f * 0.45359 return kilo end puts "Enter a number of pounds to convert to kilos son! " puts pound_kilo
true
78356fbd20585d6b5ed09bae67c6da6a30ffcacd
Ruby
Freygarr/disgaea-2-save-editor
/app/models/character/images.rb
UTF-8
831
3.03125
3
[ "MIT" ]
permissive
class Character module Images def self.included(base) base.send(:extend, ClassMethods) base.send(:include,InstanceMethods) end module ClassMethods def image_path(image_type,class_name,rank_id = 0) path = ['images','characters'] class_name = CLASS_IDS[class_name] if class_name.is_a?(Numeric) path << class_name #path << rank_id path << 0 #FIXME: always using base rank for now path << "#{image_type.to_s}.#{IMAGE_TYPE_EXTENSIONS[image_type]}" '/' + path.join('/') end end module InstanceMethods def image_path(image_type) self.class.image_path(image_type,class_id,rank_colour) end end end IMAGE_TYPE_EXTENSIONS = { :cut => 'jpg', :face => 'jpg', :sprite => 'png' } end
true
e58ac44d08da017f6520af582788ce5a3a1ee849
Ruby
maggieholbling/2-player-game
/game.rb
UTF-8
1,343
3.75
4
[]
no_license
class Game attr_reader :player1, :player2 attr_accessor :current_player, :number1, :number2, :random def initialize @player1 = @current_player = Player.new(1) @player2 = Player.new(2) random_question end def random_question @number1 = rand(1..20) @number2 = rand(1..20) @random = Question.new(@number1, @number2) end def switch_player(current_player) if current_player == @player1 @current_player = @player2 else @current_player = @player1 end end def game_turn puts "Player #{current_player.player_number}: What does #{number1} + #{number2} equal?" answer = gets.chomp @random.validate(answer) @current_player.lives += @random.score puts "P1: #{@player1.lives}/3 vs P2: #{@player2.lives}/3" switch_player(@current_player) end def transition puts "----- NEW TURN -----" random_question end def game_end puts "Player #{@current_player.player_number} wins with a score of #{@current_player.lives}/3" puts "----- GAME OVER -----" puts "Good bye!" end def play loop do game_turn if @player1.lives != 0 and @player2.lives != 0 transition end break if @player1.lives == 0 or @player2.lives == 0 end game_end end end
true
31320d53028d58f3b5696e17a1f0c0696af82cc4
Ruby
lyntco/wdi_melb_homework
/gumballs/tim_grut/wk1d5 - dogs_n_stuff/pet.rb
UTF-8
504
3.1875
3
[]
no_license
class Pet attr_accessor :name, :age, :gender, :species, :multiple_toys def initialize(pet_details) @name = pet_details[:name] @age = pet_details[:age] @gender = pet_details[:gender] @species = pet_details[:species] @multiple_toys = pet_details[:multiple_toys] end end # jenny_details= { # :name => "Jenny", # :age => 89, # :gender => "Male", # :occupation => "Works on the bloc", # :is_funny => false, # } # jenny =Tenant.new(jenny_details) # p jenny.name # p jenny.is_funny
true
387e8c2c088f782dcfd8b0f66c11865cddc57a2a
Ruby
conimorales/ProyectosEnRuby
/ruby.ciclosanidados/ruby/listas.rb
UTF-8
251
3.109375
3
[]
no_license
n_externo = ARGV[0].to_i n_interno = ARGV[1].to_i puts "<ul>" n_externo.times do |j| puts "<li> \n" puts "\t <ul>" n_interno.times do |i| puts "\t\t<li> #{j}.#{i} </li>" end puts "\t </ul>" puts "</li>" end puts "</ul>"
true
0d93006a4d99849509b87746c02f18e0a5709dac
Ruby
sambshapiro/slack-fooda-bot
/lib/fooda-bot/storage.rb
UTF-8
696
2.859375
3
[ "MIT" ]
permissive
require 'json' class Storage LATEST_KEY = 'latest' attr_reader :redis def initialize(redis) @redis = redis end def get_latest parse_latest(redis.get(encode(LATEST_KEY))) end def set_latest(name) redis.set(encode(LATEST_KEY), { time: Time.new, name: name }.to_json) end def push(name, value) redis.lpush(encode(name), value) end def lookup(name) redis.lindex(encode(name), 0) end private def encode(name) "fooda-bot:#{name}" end LatestEvent = Struct.new(:time, :name) def parse_latest(latest) return nil unless latest result = JSON.parse(latest) LatestEvent.new(Time.parse(result['time']), result['name']) end end
true
58b4c5a6f7e43a9f308b1bf1267d4b90b5f81c1d
Ruby
idej/ai
/app/ai.rb
UTF-8
4,944
2.765625
3
[]
no_license
require 'sinatra/base' require 'haml' require 'pry' require 'json' require_relative 'question.rb' class Ai < Sinatra::Base @@rules_array = [] @@conditions_list = {} @@context_stack = {} @@main_aim @@aims_stack = [] @@questions = [] helpers do def aims_options aims = [""] aims += @@rules_array.map{ |r| r.result.keys.first } aims.uniq end def input_list list = @@conditions_list @@rules_array.map do |r| key = r.result.keys.first value = r.result.values.first list[key] = [] unless list.key?(key) list[key] << value unless list[key].include?(value) end list end end get '/' do clear_variables parse_json create_conditions_list haml :index end post '/result' do @@main_aim = params[:aim] params[:context].each do |key,value| @@context_stack[key.gsub('-', ' ')] = value unless value.empty? end calculate end post '/additional_info' do @@context_stack[@@aims_stack.last[0]] = params[:additional_info] write_log("ответ на вопрос: #{@@aims_stack.last[0]}? #{params[:additional_info]}") a = @@aims_stack.pop calculate(a[1]) end private def calculate(number=nil) a = main_method(number) if a @aim = @@main_aim @result = @@context_stack[@aim] haml :result else @input_param = @@aims_stack.last[0] @values = input_list[@input_param] if @input_param == @@main_aim @aim = @@main_aim @result = "невозможно определить" haml :result else haml :aditional_info end end end def parse_json file = open(File.expand_path('database.json', settings.public_folder)) json = file.read file.close parsed = JSON.parse(json) parsed["questions"].each do |que| q = Question.new(que) @@rules_array << q end @@rules_array end def create_conditions_list @@rules_array.each do |elem| elem.conditions.each do |key, value| @@conditions_list[key] = [] unless @@conditions_list.key?(key) @@conditions_list[key] << value unless @@conditions_list[key].include?(value) end end end def main_method(q_num=nil) @@aims_stack << [@@main_aim, -1] && write_log("стек целей: #{@@main_aim}") unless q_num b = false until b last_aim = @@aims_stack.last[0] rule_number = q_num ? q_num : find_rule_number(@@aims_stack.last[0]) q_num = nil if rule_number b = analyze_rule(rule_number, last_aim) else return false end end @@context_stack[@@main_aim] end def find_rule_number(aim) a = @@rules_array.select {|r| r.result.key?(aim) && r.mark != :forbid } a.first.id unless a.empty? end def analyze_rule(rule_number, aim) return_value = false case can_find_aim?(rule_number, aim) when 1 @@rules_array.each do |r| if (r.id == rule_number) @@context_stack[aim] = r.result[aim] message = "истина, контекстный стек: #{aim} - #{@@context_stack[aim]}" write_log("Правило #{rule_number}: #{message}" ) r.mark = :accept break end end @@aims_stack.pop return_value = true if @@aims_stack.empty? when -1 @@rules_array.each do |r| if (r.id == rule_number) r.mark = :forbid break end end message = "ложь" write_log("Правило #{rule_number}: #{message}" ) when 0 r = find_rule_by_id(rule_number) r.conditions.each do |key, value| unless @@context_stack.key?(key) @@aims_stack << [key, rule_number] message = "неизвестно, стек целей: #{key}, правило #{rule_number}" write_log("Правило #{rule_number}: #{message}" ) break end end end return_value end def can_find_aim?(rule_number, aim) return_value = 1 r = find_rule_by_id(rule_number) r.conditions.each do |key, value| if @@context_stack.key?(key) unless @@context_stack[key] == value return_value = -1 r.mark = :forbid break end else return_value = 0 end end return_value end def find_rule_by_id(rule_number) @@rules_array.each do |r| if (r.id == rule_number) return r end end end def clear_variables @@rules_array.clear @@conditions_list.clear @@context_stack.clear @@aims_stack.clear @@questions.clear file = open(File.expand_path('log.txt', settings.public_folder), "w") file << '' file.close end def write_log(message) file = open(File.expand_path('log.txt', settings.public_folder), "a") file << message + "\n" file.close end end
true
74dd915f1a3f3111b7c9786b3fc6f4fa8e80b236
Ruby
kuna/swpprefactoringpractice
/PrimeGetter.rb
UTF-8
1,578
3.96875
4
[]
no_license
class PrimeGetter attr_accessor :upperlimit, :prime_array, :prime_candidate, :errormessage def initialize(upperlimit) @upperlimit = upperlimit end def geterrormessage unless @upperlimit.is_a? Integer return "n must be an integer." end if @upperlimit < 0 return "n must be greater than 0." end return "" end def isvalidinput return (geterrormessage == "") end def is_candidate_prime is_prime = true @prime_array.each do |prime| if (@prime_candidate % prime == 0) is_prime = false break elsif (prime > Math.sqrt(@prime_candidate)) break end end return is_prime end def prime_not_upper_than if (not isvalidinput) puts @errormessage return nil end if (@upperlimit <= 1) return [] end @prime_array = [2] @prime_candidate = 3 while (@prime_candidate < @upperlimit) do if is_candidate_prime @prime_array.push(@prime_candidate) end @prime_candidate = @prime_candidate+1 end return @prime_array end end if __FILE__ == $0 prime = PrimeGetter.new(ARGV[0].to_i) puts prime.prime_not_upper_than end # Get prime numbers not upper than maximum number # # pseudo code # if maximum number is not a integer or lower than 1 # print error message and return nil # # start with prime numbers = [2] and number = 3 # while (number is not upper than maximum number) # if number is prime number # add the number to prime numbers # increase the number by 1 # return prime numbers
true
314739e17dc9cca3cf94f0a956b0c4dc0e02695c
Ruby
siso25/ruby-practices
/02.calendar/calendar.rb
UTF-8
1,302
3.703125
4
[]
no_license
#!/usr/bin/env ruby require 'date' require 'optparse' def positive_integer?(string) return !string.nil? && string.match?(/\d+/) && string.to_i > 0 end def within_range_of_month?(str_month) month = str_month.to_i january = 1 december = 12 return january <= month && month <= december end def calculate_start_position(first_date) width_of_day = 2 right_blank = 1 start_position = (width_of_day + right_blank) * first_date.wday end # コマンドライン引数の取得 options = ARGV.getopts("y:", "m:") option_year = options["y"] option_month = options["m"] year = if positive_integer?(option_year) option_year.to_i else Date.today.year end month = if positive_integer?(option_month) && within_range_of_month?(option_month) option_month.to_i else Date.today.month end # 年と月の表示 puts "#{month}月 #{year}".center(20) # 曜日を表示 days_of_week = %w(日 月 火 水 木 金 土) puts days_of_week.join(" ") # 日付部分の表示 first_date = Date.new(year, month, 1) last_date = Date.new(year, month, -1) (first_date..last_date).each do |date| blank = " " if date.day == 1 print blank * calculate_start_position(date) end print date.day.to_s.rjust(2) + blank if date.saturday? print "\n" end end puts "\n\n"
true
af7010d5d98de20b0658095b0f7e7c47ee2b6f49
Ruby
mauricioedu/cursorubySenac
/Exercicio01/Questao8.rb
UTF-8
186
3.234375
3
[]
no_license
puts "Quanto voce ganha por hora" hora = gets.chomp.to_i puts "Quantos hora voce trabalho nesse mes" mes = gets.chomp.to_i salario = hora*mes puts "Nesse mes voce recebera :#{salario}"
true
5d28b8c722c95b2ae1ce1d9a0c5f4d530aa2b46f
Ruby
zihanoo/copycats
/script/fancies.rb
UTF-8
4,347
2.625
3
[ "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
# encoding: utf-8 #### # use: # $ ruby -I ./lib script/fancies.rb require 'copycats' pp FANCIES buf = "" buf += <<TXT # Updates - Fancy / Exclusive / Special Edition Cats - Timeline see <https://updates.cryptokitties.co> TXT def kitties_kitty_url( id ) "https://www.cryptokitties.co/kitty/#{id}" end def kitties_search_url( key, h ) ## note: use (official) chinese name for search param if present param = h[:name_cn] ? h[:name_cn] : key if h[:special] q = "specialedition:#{param}" ## todo: urlescape param - why? why not? elsif h[:exclusive] ## just use fancy too - why? why not? q = "exclusive:#{param}" else ## assume fancy q = "fancy:#{param}" end "https://www.cryptokitties.co/search?include=sale,sire,other&search=#{q}" end specials = {} # special edition fancies exclusives = {} # exclusive fancies fancies = {} # "normal" fancies FANCIES.each do |key,h| if h[:special] specials[key] = h elsif h[:exclusive] exclusives[key] = h else fancies[key] = h end end def build_fancy( key, h ) name = "" name << h[:name] name << " (#{h[:name_cn]})" if h[:name_cn] # add chinese name if present line = "[**#{name}**]" line << "(#{kitties_search_url( key, h )})" line << " (#{h[:limit] ? h[:limit] : '?'}" # add limit if present/known line << "+#{h[:overflow]}" if h[:overflow] line << ")" line end def build_fancies( fancies ) buf = "" fancies.each do |key,h| buf << build_fancy( key, h ) buf << "\n" end buf end buf << "## Special Edition Cats (#{specials.size})" buf << "\n\n" buf << build_fancies( specials ) buf << "\n\n\n" buf << "## Exclusive Cats (#{exclusives.size})" buf << "\n\n" buf << build_fancies( exclusives ) buf << "\n\n\n" buf << "## Fancy Cats (#{fancies.size})" buf << "\n\n" buf << build_fancies( fancies ) buf << "\n\n\n" ################## ## step 2 - add fancy cat details / chronic month = nil year = nil last_date = nil ## start of kitties blockchain / genesis genesisdate = Date.new( 2017, 11, 23) ## 2017-11-23 FANCIES.each do |key,h| date = Date.strptime( h[:date], '%Y-%m-%d' ) if year != date.year buf << "\n" buf << "\n" buf << "## #{date.year}" buf << "\n" end if month != date.month buf << "\n" buf << "### #{date.strftime( '%B')}" buf << "\n" end year = date.year month = date.month if last_date != date buf << "\n" buf << date.strftime( '%b %-d, %Y') day_count = (date.to_date.jd - genesisdate.jd)+1 buf << " (#{day_count}d)" buf << "\n" end last_date = date line = "" name = "" line << "- " if h[:special] line << "Special Edition " elsif h[:exclusive] line << "Exclusive " else end name << h[:name] name << " (#{h[:name_cn]})" if h[:name_cn] # add chinese name if present line << "[**#{name}**]" line << "(#{kitties_search_url( key, h )})" line << " (#{h[:limit] ? h[:limit] : '?'}" # add limit if present/known line << "+#{h[:overflow]}" if h[:overflow] if h[:ids] id_links = h[:ids].map { |id| "[##{id}](#{kitties_kitty_url(id)})" } line << " - #{id_links.join(', ')}" end line << ")" if h[:special] line << " Fancy Cat released" line << " -- #{h[:desc]}" if h[:desc] line << "." line << " #Fancy Cat #Special Edition" elsif h[:exclusive] line << " Fancy Cat released" line << " -- #{h[:desc]}" if h[:desc] line << "." line << " #Fancy Cat #Exclusive" else line << " Fancy Cat discovered" line << " -- #{h[:desc]}" if h[:desc] line << "." line << " #Fancy Cat" end buf << line buf << "\n" buf << "\n" if h[:variants] h[:variants].each do |variant_key,variant_h| buf << "![](https://cryptocopycats.github.io/media/kitties/100x100/fancy-#{key}-#{variant_key}.png)" buf << "\n" end else buf << "![](https://cryptocopycats.github.io/media/kitties/100x100/fancy-#{key}.png)" buf << "\n" end end puts buf File.open( "./updates/FANCIES.md", 'w:utf-8' ) do |f| f.write buf end puts "Done."
true
aad502a63b5031f4723d705834bef2505ca888df
Ruby
adamsanderson/metric_adapter
/test/reek_adapter_test.rb
UTF-8
1,303
2.703125
3
[]
no_license
require "minitest/autorun" require "metric_adapter" require "reek" class ReekAdapterTest < MiniTest::Unit::TestCase SAMPLE_PATH = 'dirty.rb' include MetricAdapter def test_empty_examiner examiner = Reek::Examiner.new([]) adapter = ReekAdapter.new(examiner) assert_equal [], adapter.metrics end def test_examiner_adapts_locations adapter = examine_sample metric = adapter.metrics.first assert_equal SAMPLE_PATH, metric.path, "Should have included the path" assert metric.line > 0, "Should have a non zero line number" end def test_examiner_returns_metrics_for_each_line_of_each_smell adapter = examine_sample metrics = adapter.metrics total_lines = adapter.examiner.smells.inject(0){|sum, s| sum + s.lines.length} assert_equal total_lines, metrics.length, "Should have included a metric per line, per smell" end private def examine_sample examiner = Reek::Examiner.new(sample) ReekAdapter.new(examiner) end def sample Reek::Source::SourceCode.new(<<-SAMPLE, SAMPLE_PATH) # Reek Sample Code class Dirty def a puts @s.title @s = fred.map {|x| x.each {|key| key += 3}} puts @s.title end end SAMPLE end end
true
315b4becaab63a2d6af2ff363124892bf8a17adf
Ruby
tk0358/meta_programming_ruby2
/chapter5/10paragraph.rb
UTF-8
265
2.921875
3
[]
no_license
class Paragraph def initiazlize(text) @text = text end def title?; @text.upcase == @text; end def reverse; @text.reverse; end def upcase; @text.upcase; end #... end def index(paragraph) add_to_index(paragraph) if paragraph.title end
true
20109b25d8e726038d705bab81fa56c1a004e76f
Ruby
hasinaniaina/DecouverteDeRuby
/exo_15.rb
UTF-8
155
3.359375
3
[]
no_license
puts "entrer votre année de naissance" i = gets.chomp nombre = i.to_i y = 0 for x in nombre..2017 puts " en #{x} vous aviez: #{y} an(s) " y +=1 end
true
d31cbb71ea52cdca807b13ce1b4ce7627dfa9421
Ruby
bburnett86/league
/parser.rb
UTF-8
266
2.75
3
[]
no_license
class Parser def input_teams(file_location) games = File.open(file_location).read.split("\n") end def create_file(output) File.open("final.txt", "w+") do |f| output.each { |element| f.puts(element) } end end end
true
6cb12035cc42344aeb3b4d55487cf87a35b20c71
Ruby
ajnassar/Chess
/pieces/pawn.rb
UTF-8
425
3.15625
3
[]
no_license
class Pawn < Piece #if starting position def deltas delts = [] if color == :black delts += [[0, 1],[0, 2]] elsif color == :white delts += [[0, -1],[0, -2]] end delts end def moves self.deltas.map do |delt| [position.first + delt.first, position.last + delt.last] end.select {|x,y| on_board?([x,y]) } end def attack? [[-1, 1],[1, -1],[-1, -1],[1, 1]] end end
true
358976ada5e73db22dd36ea35d2644c18c8060d1
Ruby
ukcrpb6/skyrim-alchemy
/bin/ingredient-minima
UTF-8
2,640
2.875
3
[]
no_license
#!/usr/bin/env ruby # require 'csv' require 'json' require 'pp' require 'set' @ingredients = Hash.new json = JSON.parse(File.read(File.expand_path("../../json/ingredients.json", __FILE__))) json.each do |ingredient| ingredient = ingredient.map { |k, v| [k.to_sym, v]}.to_h @ingredients[ingredient[:ingredient]] = ingredient unless ingredient[:dlc] end @ingredients.delete("berit's-ashes(identical-to-bone-meal") @effects = Hash.new @ingredients.each do |name, ingredient| [:primary_effect, :secondary_effect, :tertiary_effect, :quaternary_effect].each do |key| (@effects[ingredient[key]] ||= []) << ingredient[:ingredient] end end def effects(name) [:primary_effect, :secondary_effect, :tertiary_effect, :quaternary_effect].map { |key| @ingredients[name][key] }.to_set end def rank(ingredients, effects) effects.inject(0) { |acc, e| ingredients.inject(acc) { |i_acc, i| if @recorded_effects[i].include?(e) i_acc else i_acc + 1 end } } end def find_best_reaction(key, ingredient, found_effects) name = ingredient[:ingredient] effect = ingredient[key] if found_effects.include?(effect) return nil end reagents = @effects[effect] - [name] permutations = reagents.permutation(2).map { |p| p + [name]} rank = 0 result = nil permutations.each { |p| perms = p.permutation(2).map { |pair| pair.map { |reagent| effects(reagent) }.reduce(:&) }.reduce(:+).to_a our_rank = rank(p, perms) if our_rank > rank result = { ingredients: p, effects: perms } rank = our_rank end } result end @reactions = Hash.new @recorded_effects = Hash.new @ingredients.each { |name, ingredient| @recorded_effects[name] = Set.new } count = 0 @ingredients.each do |name, ingredient| [:primary_effect, :secondary_effect, :tertiary_effect, :quaternary_effect].each do |key| reaction = find_best_reaction(key, ingredient, @recorded_effects[name]) if reaction reaction[:ingredients].each do |reagent| @recorded_effects[reagent] += effects(reagent).to_set & reaction[:effects].to_set end count += 1 unless @reactions[name] @reactions[name] = { obtained: @ingredients[name][:obtained], concoctions: [] } end @reactions[name][:concoctions] << { effect: reaction[:effects], ingredients: reaction[:ingredients].sort } end end end puts "Found #{count} necessary reactions" File.open(File.expand_path("../../json/concoctions.json", __FILE__), File::CREAT | File::TRUNC | File::RDWR) do |f| f << JSON.pretty_generate(@reactions) end
true
1850e780d0905b6b55f4b689c058173c93843760
Ruby
axelletrt/movie_searcher
/app/services/search_movie.rb
UTF-8
753
2.734375
3
[]
no_license
class SearchMovie def initialize(request) # Tmdb::Api.key(Rails.application.credentials.dig[:access_key_id]) Tmdb::Api.key(Rails.application.credentials.access_key_id) @request= request end def search(request) array = [] @search = Tmdb::Search.new @search.resource('movie') # determines type of resource @search.query(request) # the query to search against results = @search.fetch # makes request results.each do |movie| hash = Hash.new hash['title'] = movie['title'] hash['release'] = movie['release_date'] #hash['director'] = director(movie['id'].to_i) array << hash end return array end def perform search(@request) end end
true
5e1304baf8bb77c4628244e15736f942c7b91311
Ruby
Jounikononen/Koulu-ja-muita-koodeja
/Ruby/Jakso7.rb
UTF-8
1,164
3.4375
3
[]
no_license
#Jakso 7 tehtävät #Tehtävä 1 #Tarkastetaan onko luku alkuluku print ("Monenteenko lukuun asti etsitään?: ") luku = gets.to_i lista = Array.new lista.push(2) puts("2 on alkuluku!") jako = 3 while jako < luku for luvut in lista if (jako % luvut == 0) puts "#{jako} ei ole alkuluku." break elsif lista.index(luvut) == (lista.length - 1) puts "#{jako} on alkuluku!" lista.push(jako) break end end jako += 1 end #Tehtävä 2 #Tiedoston sisällä olevien sanojen järjestäminen tiedosto = File.open("7-2a_tiedosto.txt","r") tekstit = Array.new tiedosto.each{|rivi| tekstit.push(rivi)} tiedosto.close tekstit = tekstit.sort tekstit = tekstit.uniq File.open("7-2b_tiedosto.txt","w").puts(tekstit) #Tehtävä 3 #Salasanageneraattori (Tiedoston sisältä haetaan numeroita vastaava kirjain) lista = "" File.open("7-3_tiedosto.txt","r").each{|rivi| lista += rivi} i = 1 salasana = "" puts "Luodaan salasana." while i < 10 print "Anna #{i}. luku väliltä 0-999: " luku = gets.to_i salasana += lista[luku] i += 1 end puts "Ohjelma loi salasanan #{salasana}"
true
d14955e9368f8159542ed7657ce792fd97bf6610
Ruby
nikkamille/badges-and-schedules-onl01-seng-pt-021020
/conference_badges.rb
UTF-8
507
3.6875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def badge_maker(name) "Hello, my name is #{name}." end def batch_badge_creator(names) badges = [] names.each {|name| badges << "Hello, my name is #{name}."} badges end def assign_rooms(attendees) room_assignments = [] attendees.each_with_index {|name, index| room_assignments << "Hello, #{name}! You'll be assigned to room #{index + 1}!"} room_assignments end def printer(list) batch_badge_creator(list).each {|message| puts message} assign_rooms(list).each {|message| puts message} end
true
a1008c047ca05edfaa9db8618c3b33e8a1b9eb9e
Ruby
upstart/Kraken
/generator/bin/kraken
UTF-8
2,482
2.5625
3
[]
no_license
#!/usr/bin/env ruby # 1.9 adds realpath to resolve symlinks; 1.8 doesn't # have this method, so we add it so we get resolved symlinks # and compatibility unless File.respond_to? :realpath class File #:nodoc: def self.realpath path return realpath(File.readlink(path)) if symlink?(path) path end end end $: << File.expand_path(File.dirname(File.realpath(__FILE__)) + '/../lib') CONFIG_ROOT = File.expand_path(File.dirname(File.realpath(__FILE__)) + '/../config') require 'rubygems' require 'gli' require 'kraken_version' require 'folders' require 'files' require 'yaml' include GLI program_desc 'kraken - a legendary sea monster of giant proportions. But this is just a tool that terrorizes small children.' version Kraken::VERSION #Command: generate desc 'Create something new' arg_name 'item' command :generate do |c| c.action do |global_options,options,args| if args.length < 1 raise 'You specify what it is that you want to generate. Try "folders".' end root = File.expand_path(".") case args[0].downcase when 'folders' if args.length < 2 raise 'You must supply a json hash or array of folders to create' end data = args[1] createFolders(root, data, options) else raise "Don't know how to generate item: #{ args[0] }" end end end #Hook: pre # Code to run before every command. # The pre hook is useful for setting up global data that most or all of your commands will need. pre do |global,command,options,args| # Pre logic here # Return true to proceed; false to abort and not call the # chosen command # Use skips_pre before a command to skip this block # on that command only true end #Hook: post # Code to run after every command that didn't experience an error. # The post hook is called after your command runs, assuming there has been no error. post do |global,command,options,args| # Post logic here # Use skips_post before a command to skip this # block on that command only end #Hook: on_error # Your commands should simply raise exceptions if anything went wrong and you wish to halt program execution. # The Error hook is called in these cases. # The error hook is also called at any other part of the application lifecycle, # so the parsed command line options may not be available. on_error do |exception| # Error logic here # return false to skip default error handling true end exit GLI.run(ARGV)
true
4a408d5fb45e5c40747502fa889aca3ef35f2b0a
Ruby
austinthelolzcat/lesson1
/app/models/formatter.rb
UTF-8
1,303
3.5
4
[]
no_license
class Formatter def int(value) realreal(value) end def real(value) first = value / 2**3 value = value % 2**3 second = value / 2**2 value = value % 2**2 third = value / 2 value = value % 2 fourth = value / 2**0 result = first.to_s+second.to_s+third.to_s+fourth.to_s puts first puts second puts third puts fourth result end def realreal(value) puts "Calculating value for #{value}" result = '' while value > 0 bit = value % 2 value = value / 2 puts value result = bit.to_s+ result puts result end puts result result.rjust(4,'0') end def yolo (value) value.to_s(2) result = value puts result end def cheat(value) case value when 0 '0000' when 1 '0001' when 2 '0010' when 3 '0011' when 4 '0100' when 5 '0101' when 6 '0110' when 7 '0111' when 8 '1000' when 9 '1001' when 10 '1010' when 11 '1011' when 12 '1100' when 13 '1101' when 14 '1110' when 15 '1111' else raise 'Numbers > 15 not supported' end end end
true
faaf43e047d7aef2ee1a7fbf3c4791fb9484b655
Ruby
nickrim/qa_repo
/BTA/HW_16/script_16_09.rb
UTF-8
159
3.5625
4
[]
no_license
# script_16_09.rb # Display result of the comparison using .eql? operator of following: (1, 1 1, 1.0 qa, qa) puts 1.eql?1 puts 1.eql?(1.0) puts "qa".eql?"qa"
true
0f344f260419d7b7b01281d99683e59452ceda3f
Ruby
mlomnicki/automatic_foreign_key
/spec/support/matchers/have_index.rb
UTF-8
1,307
2.640625
3
[ "MIT" ]
permissive
module AutomaticForeignKeyMatchers class HaveIndex def initialize(expectation, options = {}) set_required_columns(expectation, options) end def matches?(model) @model = model @model.indexes.any? do |index| index.columns.to_set == @required_columns && (@unique ? index.unique : true) && (@name ? index.name == @name.to_s : true) end end def failure_message_for_should(should_not = false) invert = should_not ? "not to" : "" "Expected #{@model.table_name} to #{invert} contain index on #{@required_columns.entries.inspect}" end def failure_message_for_should_not failure_message_for_should(true) end def on(expectation) set_required_columns(expectation) self end private def set_required_columns(expectation, options = {}) @required_columns = Array(expectation).collect(&:to_s).to_set @unique = options.delete(:unique) @name = options.delete(:name) end end def have_index(*expectation) options = expectation.extract_options! HaveIndex.new(expectation, options) end def have_unique_index(*expectation) options = expectation.extract_options! options[:unique] = true HaveIndex.new(expectation, options) end end
true
76f4b1b85dc14e25b2969a1bbc4cd2bd611028e9
Ruby
MikeBlyth/ptbase
/app/helpers/selectable_items_helper.rb
UTF-8
2,804
2.8125
3
[]
no_license
require 'pry' module SelectableItemsHelper # Set up HTML table containing checkboxes supplied by SectionName.visit_fields, and pre-checked # according to their status in record. def check_boxes(record, section_name, columns=4) # section is attribute name for table to use e.g., symptoms section= section_name.to_s.singularize.camelize.constantize # e.g. Symptom fields = section.visit_fields # return nil if fields.empty? rows = ((fields.length + columns -1) / columns).to_i # how many rows table_contents = ''.html_safe 0.upto(rows-1) do |row| row_contents = ''.html_safe 0.upto(columns-1) do |column| i = column*rows + row # which diagnosis to put here field = fields[i] unless i >= fields.count #box = check_box :visit, field.to_tag #box = check_box_tag("visit[#{section_name}][#{field.name}]", 1, record.send(section_name)[field.name]) #box_with_label = label_tag "visit_#{section_name}_#{field.name}", box+field.to_label, class: 'checkbox inline' # ************************** name = "visit[#{section_name}][#{field.name}]" id = "visit_#{section_name}_#{field.name}" checked = record.send(section_name).try(:[], field.name) box_with_label = twitter_box(id, name, field.name, checked) # ************************** comment = field.with_comment ? text_field_tag("visit[#{section_name}][#{field.name}_comment]") : nil row_contents << content_tag(:td, box_with_label+comment) end end table_contents << content_tag(:tr, row_contents) end return content_tag(:table, table_contents, {class: 'table-striped checkbox-table', style: 'width: 100%'}) end def selections_to_string(record, section_name) merged = selectable_selected(record, section_name) merged.map do |k,v| v = v.blank? ? nil : v [k,v].compact.join(': ') end.join('; ') end # Given a store of features and associated comments, like # {:headache=>'true', :fever=>'high', :cough => 'true', :headache_comment => 'improving', :fever_comment=>'night sweats'} # return a hash like # {:headache=>'improving', :fever=>'high--night sweats', :cough => ''} def selectable_selected(record, section_name) merged = Hash.new {|h,k| h[k] = ''} stored_hash = record.send(section_name) return {} if stored_hash.nil? comments, basic =stored_hash.partition {|x| x[0] =~ /_comment\Z/} basic.each { |b| merged[b[0]] = (b[1] == 'true' || b[1] == '1') ? '' : b[1] } comments.select{|comment| comment[1].present?}.each do |comment| source_key = comment[0][0..-9] merged[source_key] = [merged[source_key], comment[1]].join ('--') end return merged end end
true
105826f88c83aca91c64c8daecaa90a7aefd6f9d
Ruby
cmu-is-projects/quizzing
/app/models/year_team.rb
UTF-8
2,594
3.28125
3
[]
no_license
#written based on YearQuizzer #TODO: test this whole thing; do not use until tested class YearTeam def initialize(team, quiz_year=QuizYear.new) @year = quiz_year @team = team @name = team.name @results = get_results_for_each_quiz_this_year # i.e., event_teams for this year @division = team.division end attr_reader :team, :year attr_reader :name, :results attr_reader :division def total_points #top down design assuming event_team written with a total_yt_points method self.results.inject(0){|sum, event_team| sum += event_team.total_points} end def total_accuracy eq_array = Array.new results.each{ |et| eq_array << et.students.map{|s| EventQuizzer.new(s,et.event)} } eq_array = eq_array.flatten total_correct = eq_array.map{|s| s.student_quizzes.inject(0){|sum,sq| sum+=sq.num_correct}}.sum total_attempts = eq_array.map{|s| s.student_quizzes.inject(0){|sum,sq| sum+=sq.num_attempts}}.sum if total_attempts.zero? acc_rate = 0.0 else acc_rate = (total_correct.to_f / total_attempts).round(3) end end # Class method to get all the year_teams for a particular year and division def self.get_all_teams_for_division_for_year(division, quiz_year=QuizYear.new) teams_this_year = self.get_all_teams_who_quizzed_in_year(quiz_year) teams = Array.new teams_this_year.each do |team_id| year_team = YearTeam.new(Team.find(team_id), quiz_year) teams << year_team if year_team.division == division end sorted = teams.sort_by{|yt| yt.total_points}.reverse end private def self.get_all_teams_who_quizzed_in_year(quiz_year) tmp = Array.new events = self.find_scored_events_for_year(quiz_year) events.each do |event| tmp << QuizTeam.for_event(event).map(&:team_id).uniq end teams_this_year = tmp.flatten.compact.uniq end def self.find_scored_events_for_year(quiz_year) if Date.today > quiz_year.end_date events = Event.where("start_date >= ? and end_date <= ?", quiz_year.start_date, quiz_year.end_date) else events = Event.where("start_date >= ? and end_date <= ?", quiz_year.start_date, Date.today) end events end def get_results_for_each_quiz_this_year event_quizzes = Array.new YearTeam.find_scored_events_for_year(self.year).each do |event| event_quizzes << EventTeam.new(team, event) end # sort chronologically by start_date sorted = event_quizzes.sort_by{|eq| eq.event.start_date} end end
true
b9c6e363cb66a74b1105c5e59068a9b04b285939
Ruby
timurb/sidekiq-failover-test
/lib/validate.rb
UTF-8
217
3.25
3
[ "MIT" ]
permissive
checkins = Hash.new(0) File.readlines('checkins.txt').each do |line| checkins[line.to_i] += 1 end (1..10000).each do |n| val = checkins[n] puts "#{n}: #{val}" if val != 1 end puts "Total: #{checkins.count}"
true
cf4196bf8b88369a96dd0164902a43a9b00b567c
Ruby
255BITS/wtf-is
/1-gitflow/example.rb
UTF-8
182
2.8125
3
[ "Apache-2.0" ]
permissive
require 'sinatra' get '/:year' do answer = "NO" year = params[:year] answer = "YES" if year.to_i <= Time.now.year """<h1>Is It #{year} yet?</h1> <h2>#{answer}</h2>""" end
true
7a6372a6ef0abcf24c44c9799cff68fd70dc506f
Ruby
itsolutionscorp/AutoStyle-Clustering
/assignments/ruby/combine_anagrams/src/19426.rb
UTF-8
306
3.203125
3
[]
no_license
def combine_anagrams(words) g = {} words.each do |w| sample = w.downcase.chars.sort { |a, b| a.casecmp(b) }.join g.has_key?(sample) ? ((g[sample] << w)) : (g[sample] = [w]) end gr = [] g.each do |k, v| subgr = [] v.each { |w| (subgr << w) } (gr << subgr) end return gr end
true
d8a3bc47d306275842f90f791117fb2056c47891
Ruby
tiimgreen/tabbit
/lib/tabbit.rb
UTF-8
2,295
3.609375
4
[ "MIT" ]
permissive
require 'toc' class Tabbit attr_reader :table # When Tabbit.new is called, takes a undefined amount of headers to add # to the table. # Table initialized as an Array def initialize(*headers) @table = [[]] headers.each { |h| @table[0].push h } end # Adds line to @table in form of Array def add_row(*items) line = [] items.each { |i| line.push i } @table.push line end # Changes @table Array into String def to_s @string = '' @table[0].length.times do |n| self.instance_variable_set "@max_length_#{n}", 0.0 # Finds the longest string in column @table.each do |line| if line[n].to_s.length > self.instance_variable_get("@max_length_#{n}") self.instance_variable_set "@max_length_#{n}", line[n].length.to_f end end end @string << divider('=', @table, new_line: true) @table[0].length.times do |n| difference = self.instance_variable_get("@max_length_#{n}") - @table[0][n].to_s.length + 2 cell = '|' + (' ' * 2) + @table[0][n].to_s.bold.red + (' ' * difference) @table[0][n] == @table[0].last ? @string << "#{cell}|\n" : @string << cell end @string << divider('=', @table, new_line: true) # Write the table body, amount of spaces depends on the maximum length of # that column. @table.length.times do |n| unless n == 0 line = @table[n] line.length.times do |i| item = line[i] difference = self.instance_variable_get("@max_length_#{i}") - item.to_s.length + 2 cell = '|' + (' ' * 2) + item.to_s + (' ' * difference) item == line.last ? @string << "#{cell}|\n" : @string << cell end end end @string << divider('=', @table) @string end def size @table.length - 1 end private # Takes the table being passed and calculates the width of the full table to write the divider. def divider(char, table, options = {}) @divider = '' total_title_length = 0 table[0].length.times { |n| total_title_length += self.instance_variable_get("@max_length_#{n}") } statement = char * ((table[0].length * 5) + total_title_length + 1) options[:new_line] ? @divider << "#{statement}\n" : @divider << statement @divider end end
true
3794802c4781d46a41059bf50bd802e047418eb5
Ruby
chexton/aws
/awis-query-ruby/urlinfo.rb
UTF-8
1,165
2.6875
3
[]
no_license
#/usr/bin/ruby require "cgi" require "base64" require "openssl" require "digest/sha1" require "uri" require "net/https" require "rexml/document" require "time" ACCESS_KEY_ID = "AKIAJHGZRLLGTY3RSO6A" SECRET_ACCESS_KEY = "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" action = "UrlInfo" responseGroup = "TrafficData" url = ARGV[0] timestamp = ( Time::now ).utc.strftime("%Y-%m-%dT%H:%M:%S.000Z") signature = Base64.encode64( OpenSSL::HMAC.digest( OpenSSL::Digest::Digest.new( "sha1" ), SECRET_ACCESS_KEY, action + timestamp)).strip url = URI.parse( "http://awis.amazonaws.com/?" + { "Action" => action, "AWSAccessKeyId" => ACCESS_KEY_ID, "Signature" => signature, "Timestamp" => timestamp, "ResponseGroup" => responseGroup, "Url" => url }.to_a.collect{|item| item.first + "=" + CGI::escape(item.last) }.join("&") # Put key value pairs into http GET format ) print "\n\nRequest:\n\n" print url xml = REXML::Document.new( Net::HTTP.get(url) ) print "\n\nResponse:\n\n" xml.write rank = REXML::XPath.first( xml, "//aws:Rank" ).text print "\n\nTraffic rank: "+rank
true
d09606b050695a9adcc21283fe503ca01c5eb2c6
Ruby
mezohe/cll
/scripts/xml_preprocess.rb
UTF-8
19,161
2.890625
3
[]
no_license
require 'nokogiri' require 'yaml' require 'byebug' mydir=File.expand_path(File.dirname(__FILE__)) require "#{mydir}/util.rb" #************************************************** # FUNCTIONS #************************************************** # Splits a node's text up by words into table columns # # The reason this gets complicated is things like: # # <gloss>The-one-named <quote>bear</quote> [past] creates the story.</gloss> # # We want to break up all the bits except the quote, and still keep it all in one row. # def table_row_by_words node newchildren = [] node.children.each do |child| if child.text? words = child.text.gsub('--',"\u00A0").split( %r{\s+} ) # Hide ellipses for now words.delete('…') words.each_index do |word_index| word = words[word_index] unless word =~ %r{^\s*$} td = $document.parse("<td></td>").first td.content = word # Handle word-hyphen-quote, i.e.: lerfu-<quote>c</quote>, # which should stay together if word_index == words.length-1 && word[-1] == "-" && child.next && !(child.next.text?) && child.next.element? && child.next.name == 'quote' td << child.next.dup # Skip processing the quote since we just included it child.next['skip'] = 'true' end newchildren << td end end elsif child.element? and child['skip'] != 'true' newchildren << $document.parse("<td>#{child}</td>").first end end newnode = node.replace( "<tr class='#{node.name}'></tr>" ).first newnode.children = Nokogiri::XML::NodeSet.new( $document, newchildren ) return newnode end # Add index information ; put the index entry element as the first # child of this node def indexify!( node:, indextype:, role: nil ) if role == nil role = node.name end node.children.first.add_previous_sibling %Q{<indexterm type="#{indextype}"><primary role="#{role}">#{node.text}</primary></indexterm>} return node end # Converts a node's name and sets the role (to the old name by # default), with an optional language def convert!( node:, newname:, role: nil, lang: nil ) unless role role = node.name end if lang node['xml:lang'] = lang end if ['tr', 'td'].include? newname node['class'] = role else node['role'] = role end node.name = newname node end # Loops over the children of a node, complaining if a bad child is # found and handling non-element children. def handle_children( node:, allowed_children_names:, ignore_others: false, &proc ) node.children.each do |child| unless child.element? next end if ! allowed_children_names.include?( child.name ) if ignore_others next else abort "Found a bad element, #{child.name}, as a child of #{node.name}. Context: #{node.to_xml}" end end yield child end end # Wrap node in a glossary entry def glossify node, orignode $stderr.puts "glosscheck: #{orignode} -- #{orignode['glossary']} -- #{orignode['valid']}" if orignode['glossary'] == 'false' or orignode['valid'] == 'false' return node else node.replace(%Q{<glossterm linkend="valsi-#{slugify(orignode.text)}">#{node}</glossterm>}) end end # Makes something into a table/informaltable with one colgroup def tableify node # Convert title to caption (see # http://www.sagehill.net/docbookxsl/Tables.html ) node.css("title").each { |e| convert!( node: e, newname: 'caption' ) } caption = node.css('caption') node.css('caption').remove # Add a colgroup and caption as the first children, to make docbook happy node.children.first.add_previous_sibling "#{caption}<colgroup/>" # Save the old name node['role'] = node.name node['class'] = node.name # Turn it into a table if node.css('caption').length > 0 node.name = 'table' else node.name = 'informaltable' end return node end # Break a table into two tables; anything that matches css_string # goes into the second table, preserving order def table_split( node, css_string ) if node['split'] != 'false' && node.css(css_string).length > 0 && node.css(css_string).length != node.children.length newnode = node.clone newnode.children.each do |child| if child.css(css_string).length == 0 child.remove end end node.children.each do |child| if child.css(css_string).length > 0 child.remove end end node.add_next_sibling newnode end node end #************************************************** # MAIN CODE #************************************************** $document = Nokogiri::XML(File.open ARGV[0]) do |config| config.default_xml.noblanks end ## <lujvo-making> ## <jbo>bralo'i</jbo> ## <gloss><quote>big-boat</quote></gloss> ## <natlang>ship</natlang> ## </lujvo-making> # # Turn lujvo-making into an informaltable with one column per row $document.css('lujvo-making').each do |node| # Convert children into docbook elements node.css('jbo,natlang,gloss').each { |e| convert!( node: e, newname: 'para' ) } node.css('score').each { |e| convert!( node: e, newname: 'para', role: 'lujvo-score' ) } node.css('inlinemath').each { |e| convert!( node: e, newname: 'mathphrase' ) ; e.replace("<inlineequation role='inlinemath'>#{e}</inlineequation>" ) } node.css('rafsi').each { |e| convert!( node: e, newname: 'foreignphrase', lang: 'jbo' ) } node.css('veljvo').each { |e| convert!( node: e, newname: 'foreignphrase', lang: 'jbo' ) ; indexify!(node: e, indextype: 'lojban-phrase') ; e.replace("<para>from #{e}</para>") } # Make things into rows node.children.each { |e| e.replace("<tr><td>#{e}</td></tr>") } tableify node end # Handle interlinear-gloss, making word-by-word tables. # # <interlinear-gloss> # <jbo>pa re ci vo mu xa ze bi so no</jbo> # <gloss>one two three four five six seven eight nine zero</gloss> # <math>1234567890</math> # <natlang>one billion, two hundred and thirty-four million, five hundred and sixty-seven thousand, eight hundred and ninety.</natlang> # # </interlinear-gloss> $document.css('interlinear-gloss').each do |node| unless (node.xpath('jbo').length > 0 or node.xpath('jbophrase').length > 0) and (node.xpath('natlang').length > 0 or node.xpath('gloss').length > 0 or node.xpath('math').length > 0) abort "Found a bad interlinear-gloss element; it must have one jbo or jbophrase sub-element and at least one gloss or natlang or math sub-element. Context: #{node.to_xml}" end handle_children( node: node, allowed_children_names: [ 'jbo', 'jbophrase', 'gloss', 'math', 'natlang', 'para' ] ) do |child| if child.name == 'jbo' or child.name == 'gloss' table_row_by_words child elsif child.name == 'math' child.replace("<tr class='informalequation'><td colspan='0'>#{child}</td></tr>") else convert!( node: child, newname: 'para' ) child.replace("<tr class='para'><td colspan='0'>#{child}</td></tr>") end end tableify node # If there are natlang, comment or para lines, turn it into *two* tables table_split( node, 'td[colspan="0"] [role=natlang],td[colspan="0"] [role=comment],td[colspan="0"] [role=para]' ) end # handle interlinear-gloss-itemized # # <interlinear-gloss-itemized> # <jbo> # <sumti>mi</sumti> # <elidable>cu</elidable> # <selbri>vecnu</selbri> # <sumti>ti</sumti> # <sumti>ta</sumti> # <sumti>zo'e</sumti> # </jbo> # ... $document.css('interlinear-gloss-itemized').each do |node| handle_children( node: node, allowed_children_names: [ 'jbo', 'gloss', 'natlang', 'sumti', 'selbri', 'elidable', 'comment' ] ) do |child| if child.name == 'jbo' or child.name == 'gloss' handle_children( node: child, allowed_children_names: [ 'sumti', 'selbri', 'elidable', 'cmavo', 'comment' ] ) do |grandchild| if grandchild.name == 'elidable' if grandchild.text == '' grandchild.content = '-' else grandchild.content = "[#{grandchild.content}]" end end convert!( node: grandchild, newname: 'para' ) end child.children.each { |e| e.replace("<td>#{e}</td>") } child['class'] = child.name child.name = 'tr' else convert!( node: child, newname: 'para' ) child.replace("<tr class='para'><td colspan='0'>#{child}</td></tr>") end end tableify node # If there are natlang, comment or para lines, turn it into *two* tables table_split( node, 'td[colspan="0"] [role=natlang],td[colspan="0"] [role=comment],td[colspan="0"] [role=para]' ) end # Math ## <natlang>Both <inlinemath>2 + 2 = 4</inlinemath> and <inlinemath>2 x 2 = 4</inlinemath>.</natlang> $document.css('inlinemath').each { |e| convert!( node: e, newname: 'mathphrase' ) ; e.replace("<inlineequation role='inlinemath'>#{e}</inlineequation>" ) } ## <math>3:22:40 + 0:3:33 = 3:26:13</math> $document.css('math').each { |e| convert!( node: e, newname: 'mathphrase' ) ; e.replace("<informalequation role='math'>#{e}</informalequation>" ) } ## <pronunciation> ## <jbo>.e'o ko ko kurji</jbo> ## <jbo role="pronunciation">.E'o ko ko KURji</jbo> ## </pronunciation> ## ## <compound-cmavo> ## <jbo>.iseci'i</jbo> ## <jbo>.i se ci'i</jbo> ## </compound-cmavo> $document.css('pronunciation, compound-cmavo').each do |node| handle_children( node: node, allowed_children_names: [ 'jbo', 'ipa', 'natlang', 'comment' ] ) do |child| role = "#{node.name}-#{child.name}" convert!( node: child, newname: 'para', role: role ) child.replace(%Q{<listitem role="#{role}">#{child}</listitem>}) end convert!( node: node, newname: 'itemizedlist' ) end ## <valsi>risnyjelca</valsi> (heart burn) might have a place structure like:</para> $document.css('valsi').each do |node| # We make a glossary entry unless it's marked valid=false if node[:valid] == 'false' convert!( node: node, newname: 'foreignphrase' ) else orignode = node.dup convert!( node: node, newname: 'foreignphrase', lang: 'jbo' ) indexify!( node: node, indextype: 'lojban-words', role: orignode.name ) node = glossify node, orignode $stderr.puts "valsi: #{node.to_xml}" end end ## <simplelist> ## <member><grammar-template> ## X .i BAI bo Y ## </grammar-template></member> $document.css('grammar-template').each do |node| # Phrasal version if [ 'title', 'term', 'member', 'secondary' ].include? node.parent.name convert!( node: node, newname: 'phrase' ) else # Block version convert!( node: node, newname: 'para' ) node.replace("<blockquote role='grammar-template'>#{node}</blockquote>") end end ## <para><definition><content>x1 is a nest/house/lair/den for inhabitant x2</content></definition></para> $document.css('definition').each do |node| node.css('content').each do |child| convert!( node: child, newname: 'phrase', role: 'definition-content' ) end if [ 'title', 'term', 'member', 'secondary' ].include? node.parent.name # Phrasal version convert!( node: node, newname: 'phrase' ) else # Block version convert!( node: node, newname: 'para' ) node.replace("<blockquote role='definition'>#{node}</blockquote>") end end # Turn it into an informaltable with maximally wide rows $document.css('lojbanization').each do |node| handle_children( node: node, allowed_children_names: [ 'jbo', 'natlang' ] ) do |child| origname=child.name convert!( node: child, newname: 'para', role: child['role'] ) child.replace("<tr class='#{origname}'><td colspan='0'>#{child}</td></tr>") end tableify node end $document.css('jbophrase').each do |node| # For now, jbophrase makes an *index* but not a *glossary* indexify!( node: node, indextype: 'lojban-phrase' ) convert!( node: node, newname: 'foreignphrase', lang: 'jbo' ) if node.parent.name == 'example' convert!( node: node, newname: 'para', role: 'jbophrase' ) end end $document.css('cmavo-list').each do |node| # Handle cmavo-list # # <cmavo-list> # <cmavo-list-head> # <td>cmavo</td> # <td>gismu</td> # <td>comments</td> # </cmavo-list-head> # <title>Monosyllables of the form CVV:</title> # <cmavo-entry> # <cmavo>nu</cmavo> # <description>event of</description> # </cmavo-entry> # # More: # # <cmavo-entry> # <cmavo>pu'u</cmavo> # <description>process of</description> # <gismu>pruce</gismu> # <rafsi>pup</rafsi> # <description role="place-structure">x1 is a process of (the bridi)</description> # </cmavo-entry> # <cmavo-entry> # <gismu>fasnu</gismu> # <rafsi>nun</rafsi> # <description role="place-structure">x1 is an event of (the bridi)</description> # # other options: # # <modal-place>as said by</modal-place> # <modal-place se="se">expressing</modal-place> # # <series>mi-series</series> # # <pseudo-cmavo>[N]roi</pseudo-cmavo> # # <attitudinal-scale point="sai">discovery</attitudinal-scale> # # </cmavo-entry> handle_children( node: node, allowed_children_names: [ 'cmavo-list-head', 'title', 'cmavo-entry' ] ) do |child| if child.name == 'cmavo-list-head' origname=child.name new = convert!( node: child, newname: 'tr' ) new.replace( %Q{<thead role="#{origname}">#{new}</thead>} ) elsif child.name == 'title' # do nothing elsif child.name == 'cmavo-entry' # <cmavo>ju'i</cmavo> # <gismu>[jundi]</gismu> # <attitudinal-scale point="sai">attention</attitudinal-scale> # <attitudinal-scale point="cu'i">at ease</attitudinal-scale> # <attitudinal-scale point="nai">ignore me/us</attitudinal-scale> # <description role="long"> # # <quote>Attention/Lo/Hark/Behold/Hey!/Listen, X</quote>; indicates an important communication that the listener should listen to. # </description> if child.xpath('./cmavo').length > 0 and child.xpath('./description').length > 0 # Deal with various grandchildren, removing them so we can # be sure we got everything newchildren = [] oldchild = child.clone child.xpath('.//comment()').remove handle_children( node: child, allowed_children_names: [ 'gismu', 'cmavo', 'selmaho', 'series', 'rafsi', 'compound' ], ignore_others: true ) do |gc| new = gc.clone convert!( node: new, newname: 'td' ) newchildren << new gc.remove end [ 'sai', "cu'i", 'nai' ].each do |point| scale_bits = child.xpath("./attitudinal-scale[@point=\"#{point}\"]") if scale_bits.length > 0 new = scale_bits.first.clone convert!( node: new, newname: 'td' ) new.content = scale_bits.map { |x| x.text }.join(' ; ') new['class'] = "attitudinal-scale-#{point}".gsub("'",'h') new.attributes['point'].remove newchildren << new scale_bits.remove end end descs=child.xpath('./description') # Check if we missed something (we have if there's # anything left except descriptions) if descs.length != child.children.length abort "Unhandled node in cmavo-list. #{descs.length} != #{child.children.length} I'm afraid you'll have to look at the code to see which one. Here's the whole thing: #{oldchild.to_xml}\n\nhere's what we have left: #{child.to_xml}\n\nand here's what we have so far: #{Nokogiri::XML::NodeSet.new( $document, newchildren ).to_xml}" end # Make new rows for the longer description elements short_descs=[] long_descs=[] descs.each do |desc| $stderr.puts "desc info: #{desc['role']} -- #{desc}" if desc['role'] and (desc['role'] == 'place-structure' or desc['role'] == 'long') long_descs << desc else short_descs << desc end end short_descs.each do |desc| new = desc.clone convert!( node: new, newname: 'td', role: desc['role'] ) # No "role" for td if new['role'] new['class'] = new['role'] new.attributes['role'].remove end newchildren << new end trs = [] newchildrengroup = Nokogiri::XML::NodeSet.new( $document, newchildren ) tr1 = $document.parse("<tr class='cmavo-entry-main'>#{newchildrengroup}</tr>").first trs << tr1 long_descs.each do |desc| convert!( node: desc, newname: 'para', role: desc['role'] ) trs << $document.parse("<tr class='cmavo-entry-long-desc'><td colspan='0'>#{desc}</td></tr>").first end group = Nokogiri::XML::NodeSet.new( $document, trs ) child = child.replace group else handle_children( node: child, allowed_children_names: [ 'gismu', 'cmavo', 'selmaho', 'series', 'rafsi', 'compound', 'modal-place', 'attitudinal-scale', 'pseudo-cmavo', 'description' ] ) do |grandchild| role=grandchild.name if grandchild[:role] role=grandchild[:role] elsif grandchild.name == 'series' role='cmavo-series' elsif grandchild.name == 'compound' role='cmavo-compound' elsif grandchild.name == 'modal-place' role="modal-place-#{grandchild[:se]}" elsif grandchild.name == 'attitudinal-scale' role="attitudinal-scale-#{grandchild[:point]}".gsub("'",'h') end convert!( node: grandchild, newname: 'para', role: role ) end child.children.each { |e| e.replace("<td class='#{e['role']}'>#{e}</td>") } convert!( node: child, newname: 'tr' ) end else abort "Bad node in cmavo-list: #{child.to_xml}" end end tableify node end $document.css('letteral,diphthong,cmevla,morphology,rafsi').each do |node| convert!( node: node, newname: 'foreignphrase', lang: 'jbo' ) end $document.css('comment').each do |node| convert!( node: node, newname: 'emphasis' ) end $document.css('comment').each do |node| convert!( node: node, newname: 'emphasis' ) end # Drop attributes that docbook doesn't recognize $document.xpath('//@glossary').remove $document.xpath('//@delineated').remove $document.xpath('//@elidable').remove $document.xpath('//@valid').remove $document.xpath('//@split').remove $document.xpath('//@se').remove $document.xpath('//@point').remove doc = $document.to_xml # Put in our own header doc = doc.gsub( %r{^.*<book [^>]*>}m, '<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V5.0//EN" "dtd/docbook-5.0.dtd"[ <!ENTITY % allent SYSTEM "xml/iso-pub.ent"> %allent; ]> <book xmlns:xlink="http://www.w3.org/1999/xlink"> ' ) puts doc exit 0
true
8e6cd8433fb2daa76e1c860181783b42eb676560
Ruby
dosmode/Sinatra-Website-Practice
/app.rb
UTF-8
3,147
2.65625
3
[]
no_license
require "sinatra" require_relative "authentication.rb" require "stripe" set :publishable_key, "pk_test_xDS9v0c1IEmvkHsdji07ge8M" set :secret_key, "sk_test_c1cGu9GOwWXSqlKrxtNYTNWv" Stripe.api_key = settings.secret_key # need install dm-sqlite-adapter # if on heroku, use Postgres database # if not use sqlite3 database I gave you if ENV['DATABASE_URL'] DataMapper::setup(:default, ENV['DATABASE_URL'] || 'postgres://localhost/mydb') else DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/app.db") end class Video include DataMapper::Resource property :id, Serial property :title, Text property :description, Text property :video_url, Text property :pro,Boolean, :default => false #fill in the rest end DataMapper.finalize User.auto_upgrade! Video.auto_upgrade! #make an admin user if one doesn't exist! if User.all(administrator: true).count == 0 u = User.new u.email = "admin@admin.com" u.password = "admin" u.administrator = true u.save end def admin_only authenticate! if current_user.administrator == false redirect '/' end end get "/videos" do authenticate! if current_user.pro || current_user.administrator @videos =Video.all else @videos =Video.all(pro: false) end u=User.get(current_user.id) u.pro=true erb :videos end get '/videos/new' do admin_only erb :new_videos end post '/videos/create' do admin_only if params["title"] &&params["description"]&&params["video_url"] v= Video.new v.title=params["title"] v.description=params["description"] v.video_url=params["video_url"] v.pro = true if params["pro"]=="on" v.save end end get '/upgrade' do authenticate! if current_user.pro || current_user.administrator redirect '/' else erb :pay end end post '/charge' do begin # Amount in cents @amount = 500 customer = Stripe::Customer.create( :email => 'customer@example.com', :source => params[:stripeToken] ) charge = Stripe::Charge.create( :amount => @amount, :description => 'Sinatra Charge', :currency => 'usd', :customer => customer.id ) current_user.pro=true current_user.save erb :charge rescue erb :error end end def youtube_embed(youtube_url) if youtube_url[/youtu\.be\/([^\?]*)/] youtube_id = $1 else # Regex from # http://stackoverflow.com/questions/3452546/javascript-regex-how-to-get-youtube-video-id-from-url/4811367#4811367 youtube_url[/^.*((v\/)|(embed\/)|(watch\?))\??v?=?([^\&\?]*).*/] youtube_id = $5 end %Q{<iframe title="YouTube video player" width="640" height="390" src="https://www.youtube.com/embed/#{ youtube_id }" frameborder="0" allowfullscreen></iframe>} end youtube_embed('youtu.be/jJrzIdDUfT4') #the following urls are included in authentication.rb # GET /login # GET /logout # GET /sign_up # authenticate! will make sure that the user is signed in, if they are not they will be redirected to the login page # if the user is signed in, current_user will refer to the signed in user object. # if they are not signed in, current_user will be nil get "/" do erb :index end
true
e7c911773b6062ccdac94d13e7ce9d72edb1b695
Ruby
ClaudeJardin/Pre-course-Exercises
/Chapter07/exercise07_1.rb
UTF-8
696
3.921875
4
[]
no_license
#“99 Bottles of Beer on the Wall....” #Write a program that prints out the lyrics to that beloved classic, #that field-trip favorite: “99 Bottles of Beer on the Wall.” i = 99 while i >= 2 puts i.to_s + ' bottles of beer on the wall, ' + i.to_s + ' bottles of beer.' puts 'Take one down and pass it around, ' + (i - 1).to_s + ' bottles of beer on the wall.' puts '' i = i - 1 end puts '1 bottle of beer on the wall, 1 bottle of beer.' puts 'Take one down and pass it around, no more bottles of beer on the wall.' puts '' puts 'No more bottles of beer on the wall, no more bottles of beer.' puts 'Go to the store and buy some more, 99 bottles of beer on the wall.'
true
4be27f13960d859b3d1600f6ed0da9d8612ff45c
Ruby
kevalwell/seussscore
/parse.rb
UTF-8
403
2.953125
3
[]
no_license
require 'csv' # require 'pry' module Parse def self.dictionary(file) dictionary_hash = {} CSV.foreach(file, headers: true, header_converters: :symbol, col_sep: " ") do |row| dictionary_hash[row[:word]] = row[:pronunciation] end dictionary_hash end end # f = File.open('abridged_dictionary.txt') # f.gsub(//, '') dict = Parse.dictionary('dictionary.txt') puts dict['GREEN']
true
fbbc92ef60043fbffdec0940fde9bc0edced156c
Ruby
julienemo/thp-w6-eventbrite
/app/models/event.rb
UTF-8
987
2.53125
3
[]
no_license
class Event < ApplicationRecord validates :location, presence: true validates :title, presence: true, length: {in: 5..140} validates :description, presence: true, length:{in:20..1000} validates :price, inclusion:{in:0..1000} validate :duration_be_positive_and_multiple_of_5 validate :cant_start_in_the_past belongs_to :admin, foreign_key: 'admin_id', class_name: "User" has_one_attached :photo has_many :attendances, dependent: :destroy has_many :participants, through: :attendances, class_name: 'User' def duration_be_positive_and_multiple_of_5 unless duration.present? && duration > 0 && duration % 5 ==0 errors.add(:duration, "has to be positive and multiple of 5.") end end def cant_start_in_the_past unless start_time.present? && start_time > DateTime.now errors.add(:start_time, "must exist and can't be in the past") end end def end_time end_time = start_time + duration * 60 end end
true
317cfb6b16fd0af9ad1c894c645a548f2aa85f2c
Ruby
seanmsmith23/sonder
/spec/helper_methods.rb
UTF-8
1,402
2.78125
3
[]
no_license
require_relative "object_creation_methods" def sign_in(user) visit '/sessions/new' fill_in "user[email]", with: user.email fill_in "user[password]", with: "1" click_button "Sign In" end def create_user_and_memorial user = create_user memorial = create_memorial create_membership(user, memorial) sign_in(user) visit_memorial(memorial) end def fill_in_story(text) click_button("Story") fill_in "story[story]", with: text click_button("Add Story") end def story_length 500 end def fill_in_post(overrides = {}) post = {title: "Some Title", content: ("a" * 700)}.merge(overrides) fill_in "post[title]", with: post[:title] fill_in "post[content]", with: post[:content] click_button("Add post") end def post_length 2000 end def visit_memorial(memorial) visit "/memorials/#{memorial.id}" end def register_user(name="hotfeet@hotmail.com") visit '/registration/new' fill_in "user[first_name]", with: "Rex" fill_in "user[last_name]", with: "Ryan" fill_in "user[email]", with: name fill_in "user[password]", with: "1234" fill_in "user[password_confirm]", with: "1234" click_button "Sign Up" end def signin_user(name="hotfeet@hotmail.com") visit '/sessions/new' fill_in "user[email]", with: name fill_in "user[password]", with: "1234" click_button "Sign In" end def register_and_signin(name="hotfeet@hotmail.com") register_user(name) signin_user(name) end
true
8b17a1b86c612a6c6a11345b367484a85e94debf
Ruby
jamiepg1/alephant-publisher
/lib/alephant/publisher/views.rb
UTF-8
477
2.71875
3
[ "MIT" ]
permissive
module Alephant module Publisher module Views @@views = {} def self.register(klass) @@views[underscorify(klass.name.split('::').last)] = klass end def self.get_registered_class(id) @@views[id] end def self.underscorify(str) str.gsub(/::/, '/'). gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). gsub(/([a-z\d])([A-Z])/,'\1_\2'). tr("-", "_"). downcase end end end end
true
6c797e71e76461694607089792d470bc6ff69ff3
Ruby
LubyRuffy/utility-belt
/lib/cipher_suites.rb
UTF-8
456
3.015625
3
[]
no_license
require_relative 'cipher_constants' class CipherSuites def initialize(data) @data = data end def supported_ciphers list = [] @data.scan(/..../).each do |cipher_id| name = CIPHER_MAP[cipher_id.hex] name = "UNKNOWN (0x" + cipher_id + ")" if name.nil? list << name end return list end def print_supported_ciphers supported_ciphers.each do |supported_cipher| puts supported_cipher end end end
true
a5859c68420aebd598dcf65023053419186f7c0d
Ruby
kelleysislander/victoria_test_deploy
/app/models/map.rb
UTF-8
14,409
2.625
3
[]
no_license
class Map # a virtual model used as a container for the SQL and search logic include ActionView::Helpers::TextHelper # for "pluralize" include ActiveModel::Validations include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :retailer_name, :retailer_addr, :retailer_category_id, :advertiser_name, :radius_distance, :location_addr, :current_lat, :current_lng # RadiusDistance = Array.new(20) {|i| Array.new.push("#{i+1} miles",i+1)} # for "radius_distance" selectbox options RadiusDistances = Array.new(20) {|i| Array.new.push("#{i+1} #{(i+1 == 1 ? 'kilometer' : 'kilometers')}",i+1)} TZ_Offset = (Time.zone.utc_offset / 3600).to_s << ":00" validates_length_of :retailer_name, :within => 3..50, :unless => lambda{ |obj| obj.retailer_name.blank? } validates_length_of :retailer_addr, :within => 5..80, :unless => lambda{ |obj| obj.retailer_addr.blank? } validates_length_of :location_addr, :within => 5..80, :unless => lambda{ |obj| obj.location_addr.blank? } validates_presence_of :radius_distance, :unless => lambda{ |obj| obj.location_addr.blank? } validates_numericality_of :radius_distance, :unless => lambda{ |obj| obj.location_addr.blank? } def initialize(attributes = {}) attributes.each do |name, value| send("#{name}=", value) end end def persisted? false end def self.search Retailer.all end =begin self[0] is the first point in the polygon, self[1] is the second, and so on. Also, point.x gives you the x value of the point. Oh, and self.size returns the number of points in the polygon "point" is the x,y coordinate to test existence within the polygon "polygon_points" is an array of (x,y) coords in longitude, latitude order that defines the polygon Map_Points_in_Polygon_Zone_1, below, is an example Zone 1 Mixco 14.63200, -90.599785 Zone 2 5A Calle @ 15 14.649273, -90.499535 Zone 3 Club de Golf San Isidro 14.598778, -90.471725 Not in a zone 32.8575, -96.7558 Using reversed coordinates so that x = longitude and y = latitude point = [14.63200, -90.599785].reverse! Map.contains_point?( point , Map::Map_Points_in_Polygon_Zone_1 ) point = [32.8575, -96.7558].reverse! Map.contains_point?( point, Map::Map_Points_in_Polygon_Zone_1 ) Using the "normal" latitude / longitude (x, y) coordinates point = [14.63200, -90.599785] Map.contains_point?( point , Map::Polygon_Points_Zone_1 ) point = [32.8575, -96.7558] Map.contains_point?( point, Map::Polygon_Points_Zone_1 ) =end private X, Y = 0, 1 Zones = [ # Displayed stored in DB [ "Not in a Zone", 0 ], [ "Zone 1", 1 ], [ "Zone 2", 2 ], [ "Zone 3", 3 ], ] Polygon_Points = { 1 => [14.67, -90.63], 2 => [14.67, -90.44], 3 => [14.55, -90.44], 4 => [14.55, -90.63], 5 => [14.67, -90.54], 6 => [14.658, -90.540304], 7 => [14.623292, -90.516658], 8 => [14.622160, -90.517945], 9 => [14.600528, -90.520949], 10 => [14.600528, -90.535326], 11 => [14.571705, -90.538909], 12 => [14.55, -90.543780], 13 => [14.623908, -90.516014], 14 => [14.623908, -90.483634], 15 => [14.615769, -90.471103], 16 => [14.602397, -90.465567], 17 => [14.583168, -90.461683], 18 => [14.583168, -90.44], 19 => [14.583168, -90.482690], # 17 => [14.582587, -90.461683], # 18 => [14.582587, -90.44], # 19 => [14.582587, -90.482690], 20 => [14.581922, -90.488613], 21 => [14.579762, -90.497003], 22 => [14.564561, -90.493355], 23 => [14.55, -90.484128], } # points that define the polygons used on the Guatemala map Polygon_Points_Zone_1 = [ Polygon_Points[1], Polygon_Points[5], Polygon_Points[6], Polygon_Points[7], Polygon_Points[8], Polygon_Points[9], Polygon_Points[10], Polygon_Points[11], Polygon_Points[12], Polygon_Points[4], Polygon_Points[1], ] Polygon_Points_Zone_2 = [ Polygon_Points[5], Polygon_Points[2], Polygon_Points[18], Polygon_Points[17], Polygon_Points[16], Polygon_Points[15], Polygon_Points[14], Polygon_Points[13], Polygon_Points[7], Polygon_Points[6], Polygon_Points[5] ] Polygon_Points_Zone_3 = [ Polygon_Points[18], Polygon_Points[3], Polygon_Points[23], Polygon_Points[22], Polygon_Points[21], Polygon_Points[20], Polygon_Points[19], Polygon_Points[17], Polygon_Points[18] ] Polygon_Points_Zone_4 = [ Polygon_Points[12], Polygon_Points[11], Polygon_Points[10], Polygon_Points[9], Polygon_Points[8], Polygon_Points[7], Polygon_Points[13], Polygon_Points[14], Polygon_Points[15], Polygon_Points[16], Polygon_Points[17], Polygon_Points[19], Polygon_Points[20], Polygon_Points[21], Polygon_Points[22], Polygon_Points[23], Polygon_Points[12] ] Polygon_Points_Border = [ Polygon_Points[1], Polygon_Points[2], Polygon_Points[3], Polygon_Points[4], Polygon_Points[1] ] =begin point = [14.63200, -90.599785] Map.which_zone?( point ) point = [32.8575, -96.7558] Map.which_zone?( point ) point = [32.8575, -96.7558] zone = Map.which_zone?( point ) if zone puts "Zone #{zone}" else puts "No Zone" end point = [14.63200, -90.599785] zone = Map.which_zone?( point ) if zone puts "Zone #{zone}" else puts "No Zone" end point = [14.63200, -90.599785] zone = Map.which_zone?( point ) zone ||= 0 point = [32.8575, -96.7558] zone = Map.which_zone?( point ) zone ||= 0 point = [14.612, -90.5338] zone = Map.which_zone?( point ) zone ||= 0 =end def self.which_zone?( point ) # loop through the 4 Polygon_Points_Zone_* arrays of points to see if the "point" is in any of them zone = nil # n = 0 4.times.each_with_index do |n| polygon_points = eval("Polygon_Points_Zone_#{n + 1}") result = contains_point?( point, polygon_points ) if result zone = n + 1 break end end zone end # Inspired by: http://jakescruggs.blogspot.com/2009/07/point-inside-polygon-in-ruby.html def self.contains_point?( point, polygon_points ) contains_point = false i = -1 j = polygon_points.length - 1 while (i += 1) < polygon_points.length a_point_on_polygon = polygon_points[i] trailing_point_on_polygon = polygon_points[j] if point_is_between_the_ys_of_the_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon) if ray_crosses_through_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon) contains_point = !contains_point end end j = i end return contains_point end def self.point_is_between_the_ys_of_the_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon) (a_point_on_polygon[Y] <= point[Y] && point[Y] < trailing_point_on_polygon[Y]) || (trailing_point_on_polygon[Y] <= point[Y] && point[Y] < a_point_on_polygon[Y]) end def self.ray_crosses_through_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon) (point[X] < (trailing_point_on_polygon[X] - a_point_on_polygon[X]) * (point[Y] - a_point_on_polygon[Y]) / (trailing_point_on_polygon[Y] - a_point_on_polygon[Y]) + a_point_on_polygon[X]) end end # class =begin def contains_point?(point) contains_point = false i = -1 j = self.size - 1 while (i += 1) < self.size a_point_on_polygon = self[i] trailing_point_on_polygon = self[j] if point_is_between_the_ys_of_the_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon) if ray_crosses_through_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon) contains_point = !contains_point end end j = i end return contains_point end private def point_is_between_the_ys_of_the_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon) (a_point_on_polygon.y <= point.y && point.y < trailing_point_on_polygon.y) || (trailing_point_on_polygon.y <= point.y && point.y < a_point_on_polygon.y) end def ray_crosses_through_line_segment?(point, a_point_on_polygon, trailing_point_on_polygon) (point.x < (trailing_point_on_polygon.x - a_point_on_polygon.x) * (point.y - a_point_on_polygon.y) / (trailing_point_on_polygon.y - a_point_on_polygon.y) + a_point_on_polygon.x) end =end # scope :retailer_search, lambda{ |query| q = "%#{query.downcase}%"; { :conditions => ['lower(retailers.name) LIKE ?', q] } } # NOTE: we are reversing these coords because the maps#contains_point? algorithm needs (x,y) coordinates which means (longitude, latitude) order =begin Map_Points_in_Polygon_Zone_1 = [] Map_Points_Zone_1.each_with_index do |point, idx| Map_Points_in_Polygon_Zone_1[ idx ] = point.reverse end Map_Points_in_Polygon_Zone_2 = [] Map_Points_Zone_2.each_with_index do |point, idx| Map_Points_in_Polygon_Zone_2[ idx ] = point.reverse end Map_Points_in_Polygon_Zone_3 = [] Map_Points_Zone_3.each_with_index do |point, idx| Map_Points_in_Polygon_Zone_3[ idx ] = point.reverse end ==end =begin var zone_1_coords = [ // Zone 1, starting at upper left and moving clockwise new google.maps.LatLng(14.69, -90.67), new google.maps.LatLng(14.69, -90.59), new google.maps.LatLng(14.54, -90.534), new google.maps.LatLng(14.54, -90.67), new google.maps.LatLng(14.69, -90.67) ]; var zone_2_coords = [ // Zone 2, starting at upper left and moving clockwise new google.maps.LatLng(14.69, -90.59), new google.maps.LatLng(14.69, -90.44), new google.maps.LatLng(14.64, -90.44), new google.maps.LatLng(14.62, -90.56386225), new google.maps.LatLng(14.69, -90.59) ]; var zone_3_coords = [ // Zone 3, starting at upper left and moving clockwise new google.maps.LatLng(14.62, -90.56386225), new google.maps.LatLng(14.64, -90.44), new google.maps.LatLng(14.54, -90.44), new google.maps.LatLng(14.54, -90.534), new google.maps.LatLng(14.62, -90.56386225) ]; =end # class Map < Tableless # # belongs_to :retailers # # column :retailer_category_id, :integer # column :retailer_name, :string # column :advertiser_name, :string # column :retailer_addr, :string # column :location_addr, :string # column :radius_distance, :integer # # RadiusDistance = Array.new(10) {|i| Array.new.push("#{i+1} miles",i+1)} # for "radius_distance" selectbox options # # validates_length_of :retailer_name, :within => 3..50, :unless => lambda{ |obj| obj.retailer_name.blank? } # validates_length_of :advertiser_name, :within => 3..50, :unless => lambda{ |obj| obj.advertiser_name.blank? } # validates_length_of :retailer_addr, :within => 5..80, :unless => lambda{ |obj| obj.retailer_addr.blank? } # # validates_length_of :location_addr, :within => 5..80, :unless => lambda{ |obj| obj.location_addr.blank? } # validates_presence_of :radius_distance, :unless => lambda{ |obj| obj.location_addr.blank? } # validates_numericality_of :radius_distance, :unless => lambda{ |obj| obj.location_addr.blank? } # # scope :retailer_search, lambda{ |query| q = "%#{query.downcase}%"; { :conditions => ['lower(retailers.name) LIKE ?', "%dar%"] } } # # end # Original works except for "scope": =begin attr_accessor is ruby code and is used when you do not have a column in your database, but still want to show a field in your forms. The only way to allow this is to attr_accessor :fieldname and you can use this field in your View, or model, if you wanted, but mostly in your View. attr_accessible allows you to list all the columns you want to allow Mass Assignment, as andy eluded to above. The opposite of this is attr_protected which means this field i do NOT want anyone to be allowed to Mass Assign to. More then likely it is going to be a field in your database that you don't want anyone monkeying around with. Like a status field, or the like. # named scopes for search filters scope :retailer_search, lambda{ |query| q = "%#{query.downcase}%"; { :conditions => ['lower(retailers.name) LIKE ?', q] } } # Map.scope :retailer_name_search, lambda { |query| q = "%#{query.downcase}"; { :conditions => [ 'lower(retailers.name) LIKE ?', q] } } =end =begin Polygon_Points_Zone_1 = [ [14.67, -90.63], # 1 [14.67, -90.54], # 5 [14.658, -90.540304], # 6 [14.623292, -90.516658], # 7 [14.622160, -90.517945], # 8 [14.600528, -90.520949], # 9 [14.600528, -90.535326], # 10 [14.571705, -90.538909], # 11 [14.55, -90.543780], # 12 [14.55, -90.63], # 4 [14.67, -90.63] # 1 ] Polygon_Points_Zone_2 = [ [14.67, -90.54], # 5 [14.67, -90.44], # 2 [14.582587, -90.44], # 18 [14.582587, -90.461683], # 17 [14.602397, -90.465567], # 16 [14.615769, -90.471103], # 15 [14.623908, -90.483634], # 14 [14.623908, -90.516014], # 13 [14.623292, -90.516658], # 7 [14.658, -90.540304], # 6 [14.67, -90.54] # 5 ] Polygon_Points_Zone_3 = [ [14.582587, -90.44], # 18 [14.55, -90.44], # 3 [14.55, -90.484128], # 23 [14.564561, -90.493355], # 22 [14.579762, -90.497003], # 21 [14.581922, -90.488613], # 20 [14.582587, -90.482690], # 19 [14.582587, -90.461683], # 17 [14.582587, -90.44] # 18 ] Polygon_Points_Zone_4 = [ [14.55, -90.543780], # 12 [14.571705, -90.538909], # 11 [14.600528, -90.535326], # 10 [14.600528, -90.520949], # 9 [14.622160, -90.517945], # 8 [14.623292, -90.516658], # 7 [14.623908, -90.516014], # 13 [14.623908, -90.483634], # 14 [14.615769, -90.471103], # 15 [14.602397, -90.465567], # 16 [14.582587, -90.461683], # 17 [14.582587, -90.482690], # 19 [14.581922, -90.488613], # 20 [14.579762, -90.497003], # 21 [14.564561, -90.493355], # 22 [14.55, -90.484128], # 23 [14.55, -90.543780] # 12 ] =end
true
5c32f63aca8360975495048a1bba9e34b7935b4e
Ruby
lucanioi/exercism-ruby
/binary-search-tree/binary_search_tree.rb
UTF-8
583
3.5625
4
[]
no_license
class Bst def initialize(data) @data = data end attr_reader :left, :right, :data def insert(new_data) new_data <= data ? insert_left(new_data) : insert_right(new_data) end def each(&blk) return to_enum unless block_given? tap do left.each(&blk) if left blk.call(data) right.each(&blk) if right end end private def insert_left(new_data) left ? left.insert(new_data) : @left = self.class.new(new_data) end def insert_right(new_data) right ? right.insert(new_data) : @right = self.class.new(new_data) end end
true
936ea17abab80a74e28c7843148850adbf7c32cb
Ruby
masahino/mruby-lsp-client
/examples/example.rb
UTF-8
149
3.109375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Hoge def aaaa(n) if n == 1 puts "hoge" else puts "huga" end end end h = Hoge.new puts("test") clas
true
46288cc63daac1d55b9b04dd3717a4246bab940d
Ruby
johnmiller/CommandPattern
/ruby/lib/robot.rb
UTF-8
341
3.046875
3
[]
no_license
class Robot attr_accessor :position, :direction def initialize(position, direction) @position = position @direction = direction @commands_executed = [] end def execute_instruction(command) command.execute @commands_executed << command end def reset @commands_executed.reverse_each{|x| x.undo} end end
true
2d6a5db1484b297c90fe00782d38b73d86ce1fd5
Ruby
werebus/moretticamp
/config/initializers/date_time_formats.rb
UTF-8
479
2.53125
3
[ "MIT" ]
permissive
# frozen_string_literal: true Time::DATE_FORMATS[:ics] = ->(time) { time.utc.strftime '%Y%m%dT%H%M%SZ' } Date::DATE_FORMATS[:unix] = ->(date) { date.to_time(:local).to_i } Date::DATE_FORMATS[:short_ordinal] = lambda { |date| day_format = ActiveSupport::Inflector.ordinalize(date.day) date.strftime "%b #{day_format}" } Date::DATE_FORMATS[:long_ordinal] = lambda { |date| day_format = ActiveSupport::Inflector.ordinalize(date.day) date.strftime "%A, %B #{day_format}" }
true
54e534452e97c2dfd34c2dbe3545f49956faa621
Ruby
paulstefanort/play_analyzer
/spec/lib/analyzer_spec.rb
UTF-8
2,432
2.84375
3
[]
no_license
require 'rails_helper' require 'analyzer' describe Analyzer do it 'should load an XML file' do file_name = 'all_well.xml' file_path = File.expand_path('../../../data', __FILE__) analyzer = Analyzer.new(file: open("#{file_path}/#{file_name}")) expect(analyzer.file).to be_a(Nokogiri::XML::Document) end it 'should parse speech details' do speech = "<SPEECH><SPEAKER>MALCOLM</SPEAKER>\n <LINE>This is the sergeant</LINE>\n <LINE>Who like a good and hardy soldier fought</LINE>\n <LINE>'Gainst my captivity. Hail, brave friend!</LINE>\n <LINE>Say to the king the knowledge of the broil</LINE>\n <LINE>As thou didst leave it.</LINE></SPEECH>" analyzer = Analyzer.new(file: speech) parsed_speech = analyzer.parse_speech(Nokogiri::XML(speech).xpath('//SPEECH').first) expect(parsed_speech[:speaker]).to eq 'Malcolm' expect(parsed_speech[:lines]).to eq 5 end it 'should parse a collection of speeches and speakers' do speeches_xml = "<ACT><SPEECH> <SPEAKER>DUNCAN</SPEAKER> <LINE>O valiant cousin! worthy gentleman!</LINE> </SPEECH> <SPEECH> <SPEAKER>Sergeant</SPEAKER> <LINE>As whence the sun 'gins his reflection</LINE> <LINE>Shipwrecking storms and direful thunders break,</LINE> <LINE>So from that spring whence comfort seem'd to come</LINE> <LINE>Discomfort swells. Mark, king of Scotland, mark:</LINE> <LINE>No sooner justice had with valour arm'd</LINE> <LINE>Compell'd these skipping kerns to trust their heels,</LINE> <LINE>But the Norweyan lord surveying vantage,</LINE> <LINE>With furbish'd arms and new supplies of men</LINE> <LINE>Began a fresh assault.</LINE> </SPEECH> <SPEECH> <SPEAKER>DUNCAN</SPEAKER> <LINE>Dismay'd not this</LINE> <LINE>Our captains, Macbeth and Banquo?</LINE> </SPEECH></ACT>" analyzer = Analyzer.new(file: speeches_xml) parsed_speeches = analyzer.analyze_speeches expect(parsed_speeches.count).to eq 3 expect(parsed_speeches).to eq [ {speaker: 'Duncan', lines: 1}, {speaker: 'Sergeant', lines: 9}, {speaker: 'Duncan', lines: 2} ] analyzed_speakers = analyzer.analyze_speakers expect(analyzed_speakers).to eq [ {name: 'Sergeant', lines: 9}, {name: 'Duncan', lines: 3} ] end end
true
9621aff2dab2604de2b33b97914e7c3ace7ceb5c
Ruby
nachi412/mjai-silica
/silica.rb
UTF-8
8,762
2.546875
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- require 'pai.rb' require 'protocol.rb' require 'util.rb' require 'use_mjai_component.rb' require 'tehai.rb' require 'score.rb' require 'yama.rb' require 'furiten_checker.rb' require 'dojun_checker.rb' require 'pai_count.rb' require 'yakuhai.rb' require 'dora.rb' require 'silica_stats.rb' require 'pais.rb' require 'silica_risk_estimate.rb' require 'silica_eval_info.rb' require 'silica_heuristics.rb' require 'reach_others.rb' require 'progress.rb' require 'kuikae.rb' class Silica < UseMjaiComponent def initialize(name, room) super() @name = name @room = room @tehai = add_component(Tehai.new) @scores = add_component(Score.new) @yama = add_component(Yama.new) @furiten = add_component(FuritenChecker.new) @dojun = add_component(DojunChecker.new) @pai_count = add_component(PaiCount.new) @yakuhai = add_component(Yakuhai.new) @reach = add_component(Reach.new) @dora = add_component(Dora.new) @furo = add_component(Furo.new) @risk = add_component(SilicaRiskEstimate.new) @reach_others = add_component(ReachOthers.new) @progress = add_component(Progress.new) @kuikae = add_component(KuikaeChecker.new) add_component(SilicaStats.new) end def hello(action) super Action::join(@name, @room) end def start_game(action) super @id = action['id'] Action::none() end def start_kyoku(action) super Action::none() end def yakuari yaku_anko = Pais.JIHAIS.any? do |pai| @yakuhai.check(pai) && @tehai.count(pai) >= 3 end yaku_naki = @furo.any? do |f| f[:type] != :chi && @yakuhai.check(f[:consumed][0]) end yaku_anko || yaku_naki end def menzen @furo.empty? end def mask if menzen Shanten::NORMAL | Shanten::CHITOI else Shanten::NORMAL end end def should_ori @reach_others.check && (@tehai.shanten(yakuari || menzen, mask) > 0 || @furiten.check(@tehai)) end def what_to_discard(tsumo_pai) cs = @tehai.select{|pai|!@kuikae.check(pai)}.map do |pai| SilicaEvalInfo.new( pai, @tehai.shanten_removed(pai, yakuari || menzen, mask), @tehai.ukeire_removed(@pai_count, pai, yakuari || menzen, mask), (-1) * SilicaHeuristics::pai_point(pai, @yakuhai, @dora), @risk.estimate(pai) ) end cs.each do |e| $stderr.puts e.to_s end if should_ori cs.max_by{|c| c.risk * (-1000000) + c.to_i}.pai else cs.max_by{|c| c.to_i}.pai end end # silica#discard # 切るものがwhat_to_discardで返ってきて、リーチするかを決めてActionを返す。 def discard(pai) d_pai = what_to_discard(pai) $stderr.puts "tehai: = #{@tehai.to_s}" $stderr.puts "selected_pai = #{d_pai}" $stderr.puts "shanten = #{@tehai.shanten_removed(d_pai, true, mask)}" $stderr.puts "@id = #{@id}" $stderr.puts "@furo.empty? = #{@furo.empty?}" $stderr.puts "@yama.length = #{@yama.length}" if @furo.empty? && @yama.length >= 4 && @scores[@id] >= 1000 && @tehai.shanten_removed(d_pai, true, mask) == 0 @reach_pending = Action::dahai(@id, d_pai, d_pai == pai) Action::reach(@id) else Action::dahai(@id, d_pai, d_pai == pai) end end # silica#can_agari # trueなら絶対役あり def can_agari(pai) tanyao = (!pai.yaochu?) && @tehai.all?{|p|!p.yaochu?} && @furo.all?{|f|(!f[:pai].yaochu?) && f[:consumed].all?{|p|!p.yaochu?}} $stderr.puts "yakuari = #{yakuari}" $stderr.puts "reach = #{@reach.check}" $stderr.puts "tanyao = #{tanyao}" yakuari || @reach.check || tanyao end # silica#tsumo # 自分以外のツモなら、何もしない # 和了れるなら和了る # リーチしている場合はツモ切り # その他の場合はdiscard関数へ def tsumo(action) # fixed super pai = Pai.parse(action['pai']) if action['actor'] == @id if @tehai.shanten(true, mask) == -1 && can_agari(pai) Action::hora(@id, @id, pai) elsif @reach.check Action::dahai(@id, pai, true) # この時点では手牌から取り除かない else discard(pai) end else Action::none() end end # silica#eval_try_meld # 鳴いてみて評価する # これは役牌ポンには使わないのでyakuariはこれでOK # def eval_meld_discard(md) SilicaEvalInfo.new( md.discard, @tehai.shanten_list_removed(md.consumed_discard, yakuari || @yakuhai.check(md.discard), Shanten::NORMAL), @tehai.ukeire_list_removed(@pai_count, md.consumed_discard, yakuari || @yakuhai.check(md.discard), Shanten::NORMAL), 0, @risk.estimate(md.discard) ) end # silica#dahai # 自分の打牌なら、なにもしない # もしロンできるならする # 自分がリーチしてるまたは山が0枚の場合はスルー # 自分以外の誰かがリーチしていて、自分が聴牌してない場合はオリ(スルー) # 役牌対子が鳴けるなら鳴く # 以上どれにも当てはまらない場合は、鳴きをスルー含めて列挙して、一番良さそうなのを選ぶ def dahai(action) super pai = Pai.parse(action['pai']) actor = action['actor'] if actor == @id Action::none() else $stderr.puts "shanten_added = #{@tehai.shanten_added(pai, true, mask)}" $stderr.puts "can_agari = #{can_agari(pai)}" $stderr.puts "furiten = #{@furiten.check(@tehai)}" $stderr.puts "dojun = #{@dojun.check}" if @tehai.shanten_added(pai, true, mask) == -1 && can_agari(pai) && !@furiten.check(@tehai) && !@dojun.check Action::hora(@id, actor, pai.to_s) # ロン else if @reach.check || @yama.length == 0 # ルール上鳴けない Action::none() elsif @reach_others.check # リーチを受けてる時は鳴かない Action::none() else # 全列挙して比較する alternatives = @tehai.list_naki_dahai(pai, (@id - actor + 4) % 4 == 1).select do |meld| yakuari || @yakuhai.check(pai) || meld.all?{|p|!p.yaochu?} end alternatives << MeldDiscard::None $stderr.puts alternatives.to_s sel = alternatives.max_by do |md| if md.type == :none SilicaEvalInfo.new(nil, @tehai.shanten(yakuari || menzen, mask), @tehai.ukeire(@pai_count, yakuari || menzen, mask), 50, 5).to_i # TODO: FIXME: 5 is hyper-tenuki else eval_meld_discard(md).to_i end end case sel.type when :none Action::none() when :pon Action::pon(@id, actor, pai, sel.consumed) when :chi Action::chi(@id, actor, pai, sel.consumed) when :daiminkan Action::daiminkan(@id, actor, pai, sel.consumed) else raise "assertion: ai#dahai: naki_type is invalid." end end end end end # silica#reach # 自分なら、決めておいた行動をする # それ以外なら何もしない def reach(action) super actor = action['actor'] if actor == @id then @reach_pending else Action::none() end end def reach_accepted(action) super Action::none() end # silica#pon # 自分ならdiscard # それ以外なら何もしない def pon(action) super if action['actor'] == @id then discard(nil) else Action::none() end end # silica#chi # 自分ならdiscard # それ以外なら何もしない def chi(action) super if action['actor'] == @id then discard(nil) else Action::none() end end def daiminkan(action) super Action::none() end def ankan(action) super Action::none() end def kakan(action) super Action::none() end def hora(action) super Action::none() end def ryukyoku(action) super Action::none() end def end_kyoku(action) super Action::none() end def end_game(action) super Action::none() end def dora(action) super Action::none() end # silica#dump # デバッグ用 def dump(f) f.puts "id: #{@id}" f.puts "#{@progress.kyoku}局#{@progress.honba}本場" f.puts "#{@scores}" f.puts "リーチ: #{@reach.check}" f.puts "場風: #{@yakuhai.bakaze}" f.puts "自風: #{@yakuhai.jikaze}" f.puts "ドラ: #{@dora}" f.puts "手牌: #{@tehai}" f.puts "副露: #{@furo}" f.puts "残り山: #{@yama.length}" end end
true
cf9940f4ebec40a0e0cfadb54cb01a37c992e188
Ruby
ratzan/post-bootcamp-challenges
/01-Ruby/03-Iterators-Blocks/03-Burger-restaurant/spec/interface_spec.rb
UTF-8
2,155
2.90625
3
[]
no_license
require 'open3' require 'interface_helper' require 'interface' locals = @variables describe "interface.rb" do before(:all) do Open3.popen2('ruby ./lib/interface.rb') do |i, o, th| @result = o.read end end describe "bigger_burger" do before(:all) do @burger = ["bread", "FISH", "mayo", "salad", "bread"] end after(:all) do display_burgers(locals[:bigger_burger], @burger, locals[:bigger_burger] == @burger) end it 'should work with lowercase "fish", "mayo" and "salad" as choices' do bigger_burger = locals[:bigger_burger] expect(bigger_burger).to be_truthy expect("bigger_burger").to pass_the_right_arguments("fish", "mayo", "salad") end it "should be a perfect burger with string transformed to uppercase" do bigger_burger = locals[:bigger_burger] expect(bigger_burger).to be_ordered_burger(@burger) end end describe "juicy_burger" do before(:all) do @burger = ["bread", "st~~k", "barbecue", "cheddar", "bread"] end after(:all) do display_burgers(locals[:juicy_burger], @burger, locals[:juicy_burger] == @burger) end it 'should work with lowercase "steak", "barbecue" and "cheddar" as choices' do expect("juicy_burger").to pass_the_right_arguments("steak", "barbecue", "cheddar") end it "should be a perfect burger with vowels replaced by '~'" do juicy_burger = locals[:juicy_burger] expect(juicy_burger).to be_ordered_burger(@burger) end end describe "spicy_burger" do before(:all) do @burger = ["bread", "*chicken*", "ketchup", "cheddar", "bread"] end after(:all) do display_burgers(locals[:spicy_burger], @burger, locals[:spicy_burger] == @burger) end it 'should work with lowercase "chicken", "ketchup" and "cheddar" as choices' do expect("spicy_burger").to pass_the_right_arguments("chicken", "ketchup", "cheddar") end it "should should be a perfect burger with the sign '*' before and after the string" do spicy_burger = locals[:spicy_burger] expect(spicy_burger).to be_ordered_burger(@burger) end end end
true
4a6b2f071b86aa45e5891c34cf34e11803882acd
Ruby
barbs89/Hola-Aloha-app
/db/seeds.rb
UTF-8
561
2.546875
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) # seed languages into table # {en: 'English'} languages = [] LanguageList::COMMON_LANGUAGES.each do |lang| languages.push({en: lang.name}) end Language.create!(languages) {|l| p l.en}
true
21c75c7f66078a7be3f13e72ce5fa51671dc8aa5
Ruby
bjjb/loveos-chunky_bacon
/lib/loveos/chunky_bacon/client.rb
UTF-8
644
2.609375
3
[ "MIT" ]
permissive
require 'open-uri' module LoveOS module ChunkyBacon # A silly client. A real client would do more interesting things (and also # handle errors, and whatnot). class Client attr_accessor :host, :port, :last_response def initialize(options = {}) @host = options[:host] || "localhost" # would really come from LoveOS @port = options[:port] || "9292" # would really come from LoveOS end def get(number = 1) @last_response = open("#{uri}/#{number}").read @last_response.split("\n") end def uri URI("http://#{host}:#{port}").to_s end end end end
true
c21b3631a9b6cedf4d8655605cb4366887c79714
Ruby
marcolivier0930/dji
/lib/dji/scraper.rb
UTF-8
574
2.921875
3
[ "MIT" ]
permissive
# did not need to require any gem since it's all called in the environment.rb require_relative 'devices.rb' class Scraper def self.scrape doc = Nokogiri::HTML(open("https://store.dji.com/")) doc.css('.index__section-item___1aGxi').each do |info| hash = { # the code below will get both the name and the price of the devices name: info.css('.style__title___3zLsG').children.text, price: info.css('span')[1].text } Devices.new(hash) end end end
true
063ab8c20e8cb22d06be8aaec2e1a7ac2301816d
Ruby
GilbertMiao/cc169
/chap2_linked_lists/list_sum.rb
UTF-8
671
3.640625
4
[]
no_license
require_relative 'linked_list' require 'pry' def list_sum(l1, l2) max_length = l1.length > l2.length ? l1.length : l2.length sum = 0 l1_head = l1.head l2_head = l2.head (1..max_length).each do |i| # binding.pry if l1_head&.val.nil? sum += l2_head.val * (10 ** i) elsif l2_head&.val.nil? sum += l1_head.val * (10 ** i) else sum += (l1_head.val + l2_head.val) * (10 ** i) end l1_head = l1_head&.succ l2_head = l2_head&.succ end sum_arr = sum.to_s.split('').map(&:to_i).reverse LinkedList.new(sum_arr) end list_1 = LinkedList.new([1, 2, 3, 5]) list_2 = LinkedList.new([2, 3, 4]) puts list_sum(list_1, list_2)
true
3d9a545d9565fc88c32b0d798917fb304b72dbeb
Ruby
trizen/sidef
/scripts/RosettaCode/reverse_a_string.sf
UTF-8
153
3.265625
3
[ "Artistic-2.0" ]
permissive
#!/usr/bin/ruby # ## http://rosettacode.org/wiki/Reverse_a_string # say "asdf".reverse; # fdsa say "résumé niño".reverse; # oñin émusér
true
b11377e9ce83d7b93e0016276bf491bc561976c3
Ruby
bbryant7/ruby-exercises
/count_in_list.rb
UTF-8
948
4.3125
4
[]
no_license
# Method name: count_in_list(list, item_to_count) # Inputs: 1. a list of anything, 2. an item for us to count in the list # Returns: The number of times our item is contained in the input list # Prints: Nothing # # For example, # count_in_list([1,2,3], 1) == 1 # count_in_list([1,2,3], -1) == 0 # count_in_list([1,1,1], 1) == 3 # --- NOTE --- # Ruby has a built-in method to do this, but the purpose of this kata is # to write it yourself. # # See: http://www.ruby-doc.org/core-2.1.2/Array.html#method-i-count # OPTION 1 # def count_in_list(list, item_to_count) # total = 0 # list.each do |i| # if i === item_to_count # total += 1 # end # end # return total # end # OPTION 2 def count_in_list(list, item_to_count) list.count(item_to_count) end if __FILE__ == $PROGRAM_NAME p count_in_list(["z", "z", "b"], "z") == 2 p count_in_list([1, 2, 3], 4) == 0 p count_in_list([1, 2, 3], 1) == 1 end
true
c1d9932cd01f121d799a3f3cbba55c6a4111d724
Ruby
stellard/unite
/spec/lookup/simple_unit_spec.rb
UTF-8
1,311
2.546875
3
[ "MIT" ]
permissive
# -*- encoding : utf-8 -*- require 'spec_helper' require 'unite/lookup/simple_unit.rb' module Unite describe SimpleUnit do it { should ensure_inclusion_of(:dimension).in_array(Dimension::LIST) } it { should validate_presence_of(:si_factor)} it { should validate_presence_of(:dimension)} %w{ $ £ € m }.each do |unit| it "should allow valid unit #{unit}" do Fabricate.build(:simple_unit, :name => unit).should be_valid end end %w{km^3 m/g km*tonne}.each do |unit| it "should not allow invalid unit #{unit}" do Fabricate.build(:simple_unit, :name => unit).should_not be_valid end end describe "no dimension" do subject { SimpleUnit.new(:name => "", :si_factor => 1, :dimension => :none) } it { should be_valid } its(:property_name) { should == :none } end describe "instance methods" do let(:dimension) { :length } subject { Fabricate.build :simple_unit, :name => "m", :si_factor => 1, :dimension => :length } its(:dimension_vector) { should == Dimension::VECTOR_LIST.map{|d| d == dimension ? 1 : 0}} its(:property_name) { should == :distance } end describe "class methods" do subject { SimpleUnit } end include_examples "dimension integer" end end
true
fbe2f3cfcb22ae612a038abab3596e4986999516
Ruby
ketwalters/unbeatable_tic_tac_toe
/ruby/human.rb
UTF-8
379
3.25
3
[]
no_license
require_relative 'ui' class Human def get_human_spot(board, mark) spot = User_Interface.new.pick_spot if spot.between?(0,8) && board[spot] != "X" && board[spot] != "O" board[spot] = mark else if spot < 0 || spot > 8 puts "Invalid number. Please choose a number from 0 - 8" get_human_spot(board,mark) end end end end
true
67d3ab22602a85b10a8d60ccf98889f827bf9b64
Ruby
Okeibunor/ruby-coderbyte-solutions
/challenge5.rb
UTF-8
194
3.28125
3
[]
no_license
def Division(num1,num2) factors1 = [] factors2 = [] (1..num1).each { |x| factors1 << x if num1 % x == 0 } (1..num2).each { |x| factors2 << x if num2 % x == 0 } (factors1 & factors2).max end
true
f159ec2217d82a9132dcb2ae3316fdbad0e36b23
Ruby
saurookadook/sinatra-nested-forms-lab-superheros-v-000
/app/models/team.rb
UTF-8
140
2.78125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Team attr_accessor :name, :motto def initialize(info_hash) @name = info_hash[:name] @motto = info_hash[:motto] end end
true
d1a668800fd369b0c99c423ad8a9e8290bb06c32
Ruby
katymccloskey/phase-0-tracks
/ruby/gps2_2.rb
UTF-8
1,963
4.25
4
[]
no_license
# Method to create a list # input: string of items separated by spaces (example: "carrots apples cereal pizza") # steps: # [fill in any steps here] # set default quantity # print the list to the console [can you use one of your other methods here?] # output: [what data type goes here, array or hash?] def create_list(str) grocery_list = {} list_arr = str.split(" ") list_arr.each do |item| grocery_list[item] = 0 end grocery_list end # Method to add an item to a list # input: list, item name, and optional quantity # steps: define method that takes the 3 parameters above # move item name and quantity of that item to the list # output:hash def add_item(list, item, quant = 0) list[item] = quant list end def remove_item(list, item) list.delete(item) list end def update_quantity(list, item, quantity) list[item] = quantity print pretty_list(list) end def pretty_list(list) list.each_with_index do |item, index| puts "#{index +1}: #{item}" end end grocery_list = create_list("zuchinni, eggs, butter") p add_item(grocery_list, "bacon", 4) update_quantity(grocery_list, "eggs", 12) p pretty_list(grocery_list) #p grocery_list.pretty_list #p add_item(grocery_list, "bacon", 4) #p remove_item(grocery_list, "eggs") #grocery_list = {} #grocery_list.add_item(new_list, "banana", 4) #grocery_list.add_item(grocery_list, "banana", 4) # Method to remove an item from the list # input:list, item # steps: define the method that takes 2 parameters #remove item form the list # output:hash # Method to update the quantity of an item # input:list, item # steps: define method with that takes list and item parameters #update quantity based on the key # output: hash # Method to print a list and make it look pretty # input: list # steps:define method that takes the list as a parameter #setup a loop to run through the whole hash #inside the loop print each key/ Value pair in pretty fashion # output:strings
true
c758e4a12154912f2c512589263fa4a902a96ece
Ruby
jeffdeville/sherlock_homes
/lib/sherlock_homes/mapper/zillow.rb
UTF-8
1,084
2.5625
3
[]
no_license
module SherlockHomes class Mapper::Zillow < Mapper def self.map(raw_property) mapper = new(raw_property) mapper.map_basic_info mapper.map_estimate # TODO invoke methods to map other groups of data mapper.property end def map_basic_info property.property_type = raw_property.use_code property.year_built = raw_property.year_built property.house_sqft = raw_property.finished_square_feet property.lot_sqft = raw_property.lot_size_square_feet property.bedrooms = raw_property.bedrooms property.total_rooms = raw_property.total_rooms end def map_estimate property.estimate = Property::Estimate.new( last_updated: raw_property.last_updated, value_change: raw_property.change, value_change_duration: raw_property.change_duration, valuation: raw_property.price, valuation_range_low: raw_property.valuation_range[:low], valuation_range_hi: raw_property.valuation_range[:high], percentile: raw_property.percentile ) end end end
true
1259a1da56144aee0514861f2d74ad2c40a3117f
Ruby
rok/IKS
/create.rb
UTF-8
505
2.546875
3
[]
no_license
print "Title: " title = gets.chomp print "Tag: " tag = gets.chomp print "Location: " location = gets.chomp time = Time.now.strftime("%d %B %Y") post = "#{Time.now.strftime("%Y-%m-%d")} #{title.downcase}".gsub(/ /,'-') file = "_posts/#{post}.textile" File.open(file,"w") do |f| f.write <<EOF --- layout: post title: #{title} tag: #{tag} location: #{location} time: #{time} --- h2. {{ page.title }} p(meta). {{ page.time }} - {{ page.location }} EOF end #system "mate #{file}" system "notepad++ #{file}"
true
af1c2795be4f1160f9a8b0326dea296663a21902
Ruby
b0gok/thinknetica-ruby-basics
/lesson6/route.rb
UTF-8
1,629
3.296875
3
[]
no_license
# frozen_string_literal: true require_relative 'instance_counter.rb' require_relative 'validation.rb' # Маршрут # Имеет начальную и конечную станцию, а также список промежуточных станций. Начальная и конечная станции указываютсся при создании маршрута, а промежуточные могут добавляться между ними. # Может добавлять промежуточную станцию в список # Может удалять промежуточную станцию из списка # Может выводить список всех станций по-порядку от начальной до конечной class Route include InstanceCounter include Validation attr_reader :first_station, :last_station def initialize(first_station, last_station) @first_station = first_station @last_station = last_station @transfer_stations = [] validate! end def add_station(station) @transfer_stations << station @transfer_stations.uniq! @transfer_stations end def remove_station(station) @transfer_stations.delete(station) @transfer_stations end def stations_list [@first_station, *@transfer_stations, @last_station] end def show_stations_list stations_list.each_with_index { |station, index| puts "#{index} — #{station.name}" } end protected def validate! raise "First station can't be nil" if first_station.nil? raise "Last station can't be nil" if last_station.nil? end end
true
4bf4080d54dd5acbcab9c5da3cfa9d053c085650
Ruby
wasamasa/aoc
/2015/21.rb
UTF-8
6,710
3.75
4
[ "Unlicense" ]
permissive
require_relative 'util' # --- Day 21: RPG Simulator 20XX --- # Little Henry Case got a new video game for Christmas. It's an RPG, # and he's stuck on a boss. He needs to know what equipment to buy at # the shop. He hands you the controller. # In this game, the player (you) and the enemy (the boss) take turns # attacking. The player always goes first. Each attack reduces the # opponent's hit points by at least 1. The first character at or below # 0 hit points loses. # Damage dealt by an attacker each turn is equal to the attacker's # damage score minus the defender's armor score. An attacker always # does at least 1 damage. So, if the attacker has a damage score of 8, # and the defender has an armor score of 3, the defender loses 5 hit # points. If the defender had an armor score of 300, the defender # would still lose 1 hit point. # Your damage score and armor score both start at zero. They can be # increased by buying items in exchange for gold. You start with no # items and have as much gold as you need. Your total damage or armor # is equal to the sum of those stats from all of your items. You have # 100 hit points. # Here is what the item shop is selling: # Weapons: Cost Damage Armor # Dagger 8 4 0 # Shortsword 10 5 0 # Warhammer 25 6 0 # Longsword 40 7 0 # Greataxe 74 8 0 # # Armor: Cost Damage Armor # Leather 13 0 1 # Chainmail 31 0 2 # Splintmail 53 0 3 # Bandedmail 75 0 4 # Platemail 102 0 5 # # Rings: Cost Damage Armor # Damage +1 25 1 0 # Damage +2 50 2 0 # Damage +3 100 3 0 # Defense +1 20 0 1 # Defense +2 40 0 2 # Defense +3 80 0 3 # You must buy exactly one weapon; no dual-wielding. Armor is # optional, but you can't use more than one. You can buy 0-2 rings (at # most one for each hand). You must use any items you buy. The shop # only has one of each item, so you can't buy, for example, two rings # of Damage +3. # For example, suppose you have 8 hit points, 5 damage, and 5 armor, # and that the boss has 12 hit points, 7 damage, and 2 armor: # - The player deals 5-2 = 3 damage; the boss goes down to 9 hit # points. # - The boss deals 7-5 = 2 damage; the player goes down to 6 hit # points. # - The player deals 5-2 = 3 damage; the boss goes down to 6 hit # points. # - The boss deals 7-5 = 2 damage; the player goes down to 4 hit # points. # - The player deals 5-2 = 3 damage; the boss goes down to 3 hit # points. # - The boss deals 7-5 = 2 damage; the player goes down to 2 hit # points. # - The player deals 5-2 = 3 damage; the boss goes down to 0 hit # - points. # In this scenario, the player wins! (Barely.) # You have 100 hit points. The boss's actual stats are in your puzzle # input. What is the least amount of gold you can spend and still win # the fight? input = File.open('21.txt') { |f| f.read.scan(/\d+/).map(&:to_i) } class RPGSim def initialize(player, boss) @player = player.clone @boss = boss.clone end def done? @player[:hp] <= 0 || @boss[:hp] <= 0 end def win_or_loss? return :loss if @player[:hp] <= 0 return :win if @boss[:hp] <= 0 nil end def player_turn damage = [@player[:damage] - @boss[:armor], 1].max @boss[:hp] -= damage end def boss_turn damage = [@boss[:damage] - @player[:armor], 1].max @player[:hp] -= damage end def run loop do player_turn return win_or_loss? if done? boss_turn return win_or_loss? if done? end end end rpg = RPGSim.new({ hp: 8, damage: 5, armor: 5 }, { hp: 12, damage: 7, armor: 2 }) assert(rpg.run == :win) WEAPONS = { dagger: { cost: 8, damage: 4, armor: 0 }, shortsword: { cost: 10, damage: 5, armor: 0 }, warhammer: { cost: 25, damage: 6, armor: 0 }, longsword: { cost: 40, damage: 7, armor: 0 }, greataxe: { cost: 74, damage: 8, armor: 0 } }.freeze ARMOR = { leather: { cost: 13, damage: 0, armor: 1 }, chainmail: { cost: 31, damage: 0, armor: 2 }, splintmail: { cost: 53, damage: 0, armor: 3 }, bandedmail: { cost: 75, damage: 0, armor: 4 }, platemail: { cost: 102, damage: 0, armor: 5 } }.freeze RINGS = { damage1: { cost: 25, damage: 1, armor: 0 }, damage2: { cost: 50, damage: 2, armor: 0 }, damage3: { cost: 100, damage: 3, armor: 0 }, defense1: { cost: 20, damage: 0, armor: 1 }, defense2: { cost: 40, damage: 0, armor: 2 }, defense3: { cost: 80, damage: 0, armor: 3 } }.freeze EQUIPMENT = WEAPONS.merge(ARMOR).merge(RINGS).freeze def equipment_choices weapons = WEAPONS.keys.combination(1).to_a armor = ARMOR.keys.combination(1).to_a + [[]] rings = RINGS.keys.combination(1).to_a + RINGS.keys.combination(2).to_a + [[]] weapons.product(armor, rings) end def make_equipment(choice) cost = 0 damage = 0 armor = 0 choice.each do |things| things.each do |thing| cost += EQUIPMENT[thing][:cost] damage += EQUIPMENT[thing][:damage] armor += EQUIPMENT[thing][:armor] end end [cost, damage, armor] end def easy(input) boss_hp, boss_damage, boss_armor = input boss = { hp: boss_hp, damage: boss_damage, armor: boss_armor } player_hp = 100 ranked_choices = equipment_choices.map { |c| make_equipment(c) } .sort_by { |c| c[0] } ranked_choices.each do |choice| cost, player_damage, player_armor = choice player = { hp: player_hp, damage: player_damage, armor: player_armor } rpg = RPGSim.new(player, boss) return cost if rpg.run == :win end end puts "easy(input): #{easy(input)}" # --- Part Two --- # Turns out the shopkeeper is working with the boss, and can persuade you to buy whatever items he wants. The other rules still apply, and he still only has one of each item. # What is the most amount of gold you can spend and still lose the fight? def hard(input) boss_hp, boss_damage, boss_armor = input boss = { hp: boss_hp, damage: boss_damage, armor: boss_armor } player_hp = 100 ranked_choices = equipment_choices.map { |c| make_equipment(c) } .sort_by { |c| c[0] }.reverse ranked_choices.each do |choice| cost, player_damage, player_armor = choice player = { hp: player_hp, damage: player_damage, armor: player_armor } rpg = RPGSim.new(player, boss) return cost if rpg.run == :loss end end puts "hard(input): #{hard(input)}"
true
272400116d22f0f7c282ab1c9f7bfd46a2b5c2c7
Ruby
pachacamac/kasten
/examples/desktop_annotations.rb
UTF-8
1,826
2.828125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # This example uses the Kasten Gem and several Unix tools to allow you to # interactively draw colored, annotated areas on (a copy of) your XFCE desktop wallpaper. # It utilizes: # - zenity for interactive dialog boxes and the color picker # - xfconf to get and set your XFCE desktop wallpaper # - xrandr to get the current screen resolution # - imagemagick to manipulate the wallpaper require 'kasten' system("zenity --info --text='To create an annotation draw a box around the area you want to annotate!'") loop do box = Kasten::Box.new text = `zenity --entry --text='Please enter a label for that area'`.chomp color = `zenity --color-selection`.chomp r, g, b, a = (color.empty? ? '127,127,127' : color).scan(/(\d+),(\d+),(\d+)(?:,([\d\.]+))?/).first a ||= 1 wp_current = `xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/workspace0/last-image`.chomp c_width, c_height = `identify #{wp_current}`.scan(/(\d+)x(\d+)/).first.map(&:to_f) s_width, s_height = `xrandr`.scan(/current (\d+) x (\d+)/).first.map(&:to_f) fw, fh = c_width / s_width, c_height / s_height x1, y1, x2, y2 = box.x * fw, box.y * fh, (box.x + box.w) * fw, (box.y + box.h) * fh wp_new = File.expand_path(File.join(File.dirname(wp_current), '_wp_annotated.jpg')) system([ "convert '#{wp_current}'", "-strokewidth 0 -fill \"rgba(#{r},#{g},#{b},#{a})\"", # "-draw \"rectangle #{x1},#{y1} #{x2},#{y2}\"", "-draw \"roundrectangle #{x1},#{y1} #{x2},#{y2} 5,5\"", "-font Helvetica -pointsize 24 -draw \"text #{x1+2},#{y1-2} '#{text}'\"", "'#{wp_new}'" ].join(' ') ) system("xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/workspace0/last-image -s '#{wp_new}'") break unless system("zenity --question --text 'Would you like to create another annotation?'") end
true
a137a66810d720913d28b809ee00f1006b8f05d9
Ruby
emanon001/atcoder-ruby
/abc007/c/main.rb
UTF-8
635
2.625
3
[]
no_license
R, C = gets.split.map(&:to_i) sy, sx = gets.split.map { |n| n.to_i - 1 } gy, gx = gets.split.map { |n| n.to_i - 1 } board = R.times.map { gets.chomp.chars } dy = [-1, 0, 1, 0] dx = [0, 1, 0, -1] visited = Array.new(R) { Array.new(C, false) } visited[sy][sx] = true queue = [[sy, sx, 0]] while !queue.empty? i, j, c = queue.shift 4.times do |d| y = i + dy[d] x = j + dx[d] next if y < 0 || y >= R || x < 0 || x >= C next if board[y][x] == '#' next if visited[y][x] visited[y][x] = true new_c = c + 1 if y == gy && x == gx puts new_c exit 0 end queue.push([y, x, new_c]) end end
true
6f2bf6e987b60083930a0701a0d0bfc923719904
Ruby
JoeStanton/baseline-agent
/lib/string_helpers.rb
UTF-8
106
2.640625
3
[]
no_license
class StringHelpers def self.slugify(str) str.downcase.gsub(/[^a-z1-9]+/, '-').chomp('-') end end
true
a85928fdb784681094f4e084ee7b3de600006bb6
Ruby
KeithHanson/opal-screeps
/ruby/threat_assessor.rb
UTF-8
243
2.78125
3
[]
no_license
class ThreatAssessor def self.assess(room) Debug.debug "ThreatAssessor assessing threat level for #{room.name}..." level = 0 Debug.debug "ThreatAssessment: #{level}" return level # dumb 100 point scale right now end end
true
648a7edb121c063fa1025a8f3dab69978e475765
Ruby
ianchesal/babbler
/lib/babbler.rb
UTF-8
1,036
3.09375
3
[ "MIT" ]
permissive
require "babbler/version" require "babbler/words" module Babbler class << self def babble(seed = nil) prng = Random.new(seed || Random.new_seed) adjectives = [] Babbler.config.num_adjectives.times do adjectives.push(ADJECTIVES[prng.rand(ADJECTIVES.length)]) end noun = NOUNS[prng.rand(NOUNS.length)] "#{adjectives.join(' ')} #{noun}" end ########################################################################### # # Configuration machinery. # # To configure Babbler, put the following code in your applications # initialization logic (eg. in the config/initializers in a Rails app) # # Babbler.configure do |config| # ... # end # def configure yield config end def config @configuration ||= Configuration.new end class Configuration attr_accessor :num_adjectives def initialize @num_adjectives = 1 super end end end end
true
a619b639a0365aba2cf4491b829856cbfaf2dc73
Ruby
ivanbrennan/vim-splice
/spec/support/tmux.rb
UTF-8
950
2.625
3
[]
no_license
module Tmux def spawn_new_session(session_name) sidestep_nested_restriction do run_silent_command("new-session -d -s #{session_name}") end end def spawn_new_session!(session_name) ensure_tmux_present spawned = spawn_new_session(session_name) raise SpawnSessionError unless spawned end def kill_session(session_name) run_silent_command("kill-session -t #{session_name}") end private def ensure_tmux_present version_present = run_silent_command('-V') raise NotPresentError unless version_present end def run_silent_command(command) system("tmux #{command} &>/dev/null") end def sidestep_nested_restriction if ENV.has_key?('TMUX') ENV['TMUX_OLD'] = ENV.delete('TMUX') end yield if ENV.has_key?('TMUX_OLD') ENV['TMUX'] = ENV.delete('TMUX_OLD') end end class SpawnSessionError < RuntimeError; end class NotPresentError < RuntimeError; end end
true
99dae796c6c8d704ffb7bb466c1cb31f262e0ed4
Ruby
switch-ch/well_rested
/lib/well_rested/utils.rb
UTF-8
674
2.8125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'generic_utils' module WellRested module Utils extend GenericUtils extend self # Turn any nested resources back into hashes before sending them def objects_to_attributes(obj) if obj.respond_to?(:attributes_for_api) obj.attributes_for_api elsif obj.kind_of?(Hash) new_attributes = {}.with_indifferent_access obj.each do |k, v| new_attributes[k] = objects_to_attributes(v) end new_attributes elsif obj.kind_of?(Array) obj.map { |e| self.objects_to_attributes(e) } else obj #raise "Attributes was not a Hash or Enumerable" end end end end
true
8994e4fd9b27e00d01eb8ca25076cf44cf057770
Ruby
alaibe/bank_holidays
/app/helpers/bank_holidays_helper.rb
UTF-8
267
2.796875
3
[]
no_license
module BankHolidaysHelper def parenthesis(name_in_country) return if name_in_country.empty? " (#{name_in_country})" end def to_sentence(countries) countries.map do |country| "#{country.name} (#{country.iso})" end.to_sentence end end
true
459b6883f4d6c6f86e271cfb783bf6cf46df0c71
Ruby
BillMux/codewars
/rb/sudoku/lib/sudoku_done_or_not.rb
UTF-8
631
3.453125
3
[]
no_license
def sudoku_is_valid(grid) valid?(grid) && valid?(grid.transpose) && valid?(squares(grid)) end def valid?(grid) grid.each do |arr| return false if arr.uniq != arr || arr.sum != 45 || arr.any? { |x| x > 9 } end true end def squares(grid) squares, i, j = [], 0, 0 while i < grid.length while j < grid[0].length squares << get_squares(grid, i, j) j += 3 end i += 3 end squares end def get_squares(grid, i, j) [ grid[i][j], grid[i][j + 1], grid[i][j + 2], grid[i + 1][j], grid[i + 1][j + 1], grid[i + 1][j + 2], grid[i + 2][j], grid[i + 2][j + 1], grid[i + 2][j + 2] ] end
true
09a685b8f441296ced42e853eb43209e9a307151
Ruby
WhitehawkVentures/split
/lib/split/alternative.rb
UTF-8
15,489
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'split/zscore' require 'active_support/all' require 'simple-random' # TODO - take out require and implement using file paths? module Split class Alternative attr_accessor :name attr_accessor :experiment_name attr_accessor :weight include Zscore def initialize(name, experiment_name) @experiment_name = experiment_name if Hash === name @name = name.keys.first @weight = name.values.first else @name = name @weight = 1 end end def to_s name end def unmemoize @participant_count = nil @completed_count = nil @completed_value = nil @completed_values = nil end def goals self.experiment.goals end def participant_count @participant_count ||= Split.redis.with do |conn| conn.hget(key, 'participant_count').to_i end end def participant_count=(count) Split.redis.with do |conn| conn.hset(key, 'participant_count', count.to_i) end end def completed_count(goal = nil) unless @completed_count @completed_count = ActiveSupport::HashWithIndifferentAccess.new # add nil so we include overall completed count (self.goals + [nil]).each do |goal| field = set_field(goal) @completed_count[goal] = Split.redis.with do |conn| conn.hget(key, field).to_i end end end @completed_count[goal] || 0 end def unique_completed_count(goal = nil) unless @unique_completed_count @unique_completed_count = ActiveSupport::HashWithIndifferentAccess.new # add nil so we include overall completed count (self.goals + [nil]).each do |goal| field = set_field(goal, true) @unique_completed_count[goal] = Split.redis.with do |conn| conn.hget(key, field).to_i end end end @unique_completed_count[goal] || 0 end def completed_value(goal = nil) unless @completed_value @completed_value = ActiveSupport::HashWithIndifferentAccess.new self.goals.each do |goal| field = set_value_field(goal) @completed_value[goal] = Split.redis.with do |conn| list = conn.lrange(key + field, 0, -1) if list.size > 0 list.sum{|n| n.to_f}/list.size else "N/A" end end end end @completed_value[goal] || [] end def combined_value(goal = nil) if completed_value(goal) != "N/A" && completed_count(goal) > 0 completed_value(goal).to_f * (completed_count(goal).to_f/participant_count.to_f) else "N/A" end end def completed_values(goal = nil) unless @completed_values @completed_values = ActiveSupport::HashWithIndifferentAccess.new self.goals.each do |goal| field = set_value_field(goal) @completed_values[goal] = Split.redis.with do |conn| list = conn.lrange(key + field, 0, -1).collect{|n| n.to_f} end.collect{|n| [0,n].max} end end @completed_values[goal] || [] end def all_completed_count if goals.empty? completed_count else goals.inject(completed_count) do |sum, g| sum + completed_count(g) end end end def unfinished_count(goal = nil) participant_count - completed_count(goal) end def set_field(goal, unique = false) if unique field = "unique_completed_count" else field = "completed_count" end field += ":" + goal unless goal.nil? return field end def set_value_field(goal, unique = false) if unique field = ":unique_completed_value" else field = ":completed_value" end field += ":" + goal unless goal.nil? return field end def set_completed_count (count, goal = nil) field = set_field(goal) Split.redis.with do |conn| conn.hset(key, field, count.to_i) end end def increment_participation(count = 1) Split.redis.with do |conn| conn.hincrby key, 'participant_count', count end end def increment_completion(goal = nil, value = nil) Split.redis.with do |conn| field = set_field(goal) if value conn.lpush(key + set_value_field(goal), value) end conn.hincrby(key, field, 1) end end def increment_unique_completion(goal = nil, value = nil) Split.redis.with do |conn| field = set_field(goal, true) conn.hincrby(key, field, 1) end end def control? experiment.control.name == self.name end def conversion_rate(goal = nil) return 0 if participant_count.zero? (completed_count(goal).to_f)/participant_count.to_f end def unique_conversion_rate(goal = nil) return 0 if participant_count.zero? (unique_completed_count(goal).to_f)/participant_count.to_f end def experiment @experiment ||= Split::Experiment.find(experiment_name) end def z_score(goal = nil) # p_a = Pa = proportion of users who converted within the experiment split (conversion rate) # p_c = Pc = proportion of users who converted within the control split (conversion rate) # n_a = Na = the number of impressions within the experiment split # n_c = Nc = the number of impressions within the control split control = experiment.control alternative = self return 'N/A' if control.name == alternative.name p_a = alternative.conversion_rate(goal) p_c = control.conversion_rate(goal) n_a = alternative.participant_count n_c = control.participant_count z_score = Split::Zscore.calculate(p_a, n_a, p_c, n_c) end def log_normal_probability_better_than_control(goal = nil) return "N/A" if experiment.control.name == self.name return "Needs 50+ participants." if self.completed_values(goal).size < 50 if !self.completed_values(goal).blank? && !experiment.control.completed_values(goal).blank? bayesian_log_normal_probability(self.completed_values(goal), experiment.control.completed_values(goal)) else "N/A" end end def beta_samples(alternative, control) if alternative.is_a?(Array) non_zeros_a = alternative.size non_zeros_b = control.size else non_zeros_a = alternative non_zeros_b = control end total_a = self.participant_count total_b = experiment.control.participant_count alpha = 1 beta = 1 a_samples = [] random_generator = SimpleRandom.new random_generator.set_seed(Time.now) 10000.times do a_samples << random_generator.beta(non_zeros_a+alpha, [total_a-non_zeros_a, 0].max+beta) end b_samples = [] random_generator.set_seed(Time.now) 10000.times do b_samples << random_generator.beta(non_zeros_b+alpha, [total_b-non_zeros_b, 0].max+beta) end return a_samples, b_samples end def beta_probability_better_than_control(goal = nil) return "N/A" if experiment.control.name == self.name return "Needs 50+ participants." if self.participant_count < 50 if self.completed_count(goal) > 0 && experiment.control.completed_count(goal) > 0 bayesian_beta_probability(self.completed_count(goal), experiment.control.completed_count(goal)) else "N/A" end end def unique_beta_probability_better_than_control(goal = nil) return "N/A" if experiment.control.name == self.name return "Needs 50+ participants." if self.participant_count < 50 if self.unique_completed_count(goal) > 0 && experiment.control.unique_completed_count(goal) > 0 bayesian_beta_probability(self.unique_completed_count(goal), experiment.control.unique_completed_count(goal)) else "N/A" end end def combined_probability_better_than_control(goal = nil) return "N/A" if experiment.control.name == self.name return "Needs 50+ participants." if self.completed_values(goal).size < 50 if self.combined_value(goal) != "N/A" && experiment.control.combined_value(goal) > 0 bayesian_combined_probability(self.completed_values(goal), experiment.control.completed_values(goal)) else "N/A" end end def bayesian_combined_probability(alternative, control) a_rps_samps, b_rps_samps = bayesian_combined_samples(alternative, control) sum = 0 a_rps_samps.each_with_index do |num, index| if num > b_rps_samps[index] sum += 1 end end prob_A_greater_B = sum.to_f/a_rps_samps.size.to_f end def bayesian_combined_samples(alternative, control) a_conv_samps, b_conv_samps = beta_samples(alternative, control) a_order_samps, b_order_samps = log_normal_samples(alternative, control) a_rps_samps = [a_conv_samps, a_order_samps].transpose.map {|x| x.reduce(:*)} b_rps_samps = [b_conv_samps, b_order_samps].transpose.map {|x| x.reduce(:*)} return a_rps_samps, b_rps_samps end def bayesian_beta_probability(alternative, control) a_samples, b_samples = beta_samples(alternative, control) sum = 0 a_samples.each_with_index do |num, index| if num > b_samples[index] sum += 1 end end prob_A_greater_B = sum.to_f/a_samples.size.to_f end def log_normal_samples(alternative, control) a_data = alternative b_data = control # a_data = [45,78,35,8,23,56,8,6,2,34,77,2,667,234,23,7,434,76,25,21,79,34,752] # b_data = [45,78,35,8,23,56,8,6,2,34,77,2,667,234,23,7,434,76,25,21,79,34,753] m0 = 4.0 # guess about the log of the mean k0 = 1.0 # certainty about m. compare with number of data samples s_sq0 = 1.0 # degrees of freedom of sigma squared parameter v0 = 1.0 # scale of sigma_squared parameter # step 3: get posterior samples a_posterior_samples = draw_log_normal_means(a_data,m0,k0,s_sq0,v0) b_posterior_samples = draw_log_normal_means(b_data,m0,k0,s_sq0,v0) return a_posterior_samples, b_posterior_samples end def bayesian_log_normal_probability(alternative, control) a_posterior_samples, b_posterior_samples = log_normal_samples(alternative, control) # step 4: perform numerical integration sum = 0 a_posterior_samples.each_with_index do |num, index| if num > b_posterior_samples[index] sum += 1 end end prob_A_greater_B = sum.to_f/a_posterior_samples.size.to_f # or you can do more complicated lift calculations diff = [a_posterior_samples, b_posterior_samples].transpose.map {|x| x.reduce(:-)} temp_array = [diff, b_posterior_samples].transpose.map {|x| x.reduce(:/)}.collect{|n| n.to_f*100} # diff = a_posterior_samples - b_posterior_samples sum = 0 temp_array.each_with_index do |num, index| if num > 1 sum += 1 end end lift_calc = sum.to_f/b_posterior_samples.size.to_f print lift_calc return prob_A_greater_B end def draw_log_normal_means(data,m0,k0,s_sq0,v0,n_samples=10000) # log transform the data log_data = data.select{|n| n > 0}.collect{|n| Math.log(n)} # get samples from the posterior mu_samples, sig_sq_samples = draw_mus_and_sigmas(log_data,m0,k0,s_sq0,v0,n_samples) log_normal_mean_samples = [sig_sq_samples.collect{|n|n/2}, mu_samples].transpose.map {|x| x.reduce(:+)}.collect{|n| Math.exp(n)} return log_normal_mean_samples end def draw_mus_and_sigmas(data,m0,k0,s_sq0,v0,n_samples) # number of samples n = data.size # find the mean of the data the_mean = data.sum{|n| n.to_f}/data.size # sum of squared differences between data and mean ssd = data.sum{|n| (n-the_mean)**2} # combining the prior with the data - page 79 of Gelman et al. # to make sense of this note that # inv-chi-sq(v,s^2) = inv-gamma(v/2,(v*s^2)/2) kN = k0.to_f + n.to_f mN = (k0.to_f/kN.to_f)*m0.to_f + (n.to_f/kN.to_f)*the_mean.to_f vN = v0.to_f + n.to_f vN_times_s_sqN = v0.to_f*s_sq0.to_f + ssd.to_f + (n.to_f*k0.to_f*(m0.to_f-the_mean.to_f)**2)/kN.to_f # 1) draw the variances from an inverse gamma # (params: alpha, beta) alpha = vN/2 beta = vN_times_s_sqN/2 # thanks to wikipedia, we know that: # if X ~ inv-gamma(a,1) then b*X ~ inv-gamma(a,b) random_generator = SimpleRandom.new random_generator.set_seed(Time.now) sig_sq_samples = [] (size=n_samples).times do sig_sq_samples << random_generator.inverse_gamma(alpha, beta) end # 2) draw means from a normal conditioned on the drawn sigmas # (params: mean_norm, var_norm) mean_norm = mN var_norm = sig_sq_samples.collect{|n| Math.sqrt(n/kN)} mu_samples = [] var_norm.each do |var| mu_samples << random_generator.normal(mean_norm, var) end # 3) return the mu_samples and sig_sq_samples return mu_samples, sig_sq_samples end def save Split.redis.with do |conn| conn.hsetnx key, 'participant_count', 0 conn.hsetnx key, 'completed_count', 0 conn.hsetnx key, 'unique_completed_count', 0 end end def validate! unless String === @name || hash_with_correct_values?(@name) raise ArgumentError, 'Alternative must be a string' end end def reset Split.redis.with do |conn| conn.hmset key, 'participant_count', 0, 'completed_count', 0, 'unique_completed_count', 0 unless goals.empty? goals.each do |g| field = "completed_count:#{g}" value_field = set_value_field(g) conn.hset key, field, 0 conn.del(key + value_field) field = "unique_completed_count:#{g}" value_field = set_value_field(g, true) conn.hset key, field, 0 conn.del(key + value_field) end end end end def delete Split.redis.with do |conn| conn.del(key) unless goals.empty? goals.each do |g| field = "completed_count:#{g}" value_field = set_value_field(g) conn.del(key + value_field) conn.del(key + field) field = "unique_completed_count:#{g}" value_field = set_value_field(g, true) conn.del(key + value_field) conn.del(key + field) end end end end def flatten_values Split.redis.with do |conn| unless goals.empty? goals.each do |g| value_field = set_value_field(g) avg = completed_value(g) conn.del(key + value_field) conn.lpush(key + value_field, avg) value_field = set_value_field(g, true) conn.del(key + value_field) end end end end private def hash_with_correct_values?(name) Hash === name && String === name.keys.first && Float(name.values.first) rescue false end def key "#{experiment_name}:#{name}" end end end
true
ba6dbeb9338f4ccaba13879cf7b4b7ce11d0cbab
Ruby
dvimont/ruby-objects-has-many-through-lab-cb-000
/lib/patient.rb
UTF-8
316
3.1875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Patient attr_reader :name, :appointments def initialize(name) @name = name @appointments = Array.new end def add_appointment(appointment) appointment.patient = self @appointments << appointment end def doctors() return self.appointments.collect{|appt| appt.doctor} end end
true
e15e15a9fe8c21f2278587890c446c403c6343a6
Ruby
grassynull0/Introduction_to_Programming
/flow_control/exercise_1.rb
UTF-8
422
3.640625
4
[]
no_license
## Write down whether the following expressions return true or false. # Then type the expressions into irb to see the results. # 1. (32 * 4) >= 129 # 2. false != !true # 3. true == 4 # 4. false == (847 == '847') # 5. (!true || (!(100 / 5) == 20) || ((328 / 4) == 82)) || false ## # 1. is false LS had false # 2. is false LS had false # 3. is true LS had false ********** # 4. is true LS had true # 5. is true LS had true
true
b7f543f9c60df303a03225779554819a550caa5f
Ruby
Emmanuelcole2017/ruby-collaborating-objects-lab-online-web-ft-112618
/lib/artist.rb
UTF-8
784
3.484375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist attr_accessor :name, :songs @@all = [] def initialize(name = "") @name = name @songs = [] instance = self @@all << instance end def add_song(song) @songs << song end def songs @songs end def save instance = self @@all << instance end def self.all @@all end def self.find_or_create_by_name(name) # finds or creates an artist by name instance = nil @@all.each do |element| if element.name == name instance = element end end if instance == nil instance = self.new instance.name = name @@all << instance instance else instance end end def print_songs @songs.each do |element| puts element.name end end end
true
4e231d5e35c0e5d08e608a233c7b8755391cb9e7
Ruby
NJCA88/W1D5
/skeleton/lib/KnightPathFinder.rb
UTF-8
1,014
3.390625
3
[]
no_license
require_relative "00_tree_node" class KnightPathFinder attr_accessor :added_moves, :move_tree def initialize(pos) @added_moves = [pos] @move_tree = PolyTreeNode.new(pos) build_move_tree(@move_tree) end def build_move_tree(node) return nil if node.nil? self.find_moves(node.value).each do |move| child = PolyTreeNode.new(move) node.add_child(child) @added_moves << move self.build_move_tree(child) end end def find_moves(pos) x,y = pos moves = [[x+2, y+1], [x+2, y-1], [x+1, y+2], [x+1, y-2], [x-2, y-1], [x-2, y+1], [x-1, y-2], [x-1, y+2]] moves.select{|move| is_valid?(move)} end def is_valid?(pos) x,y = pos x.between?(0,7) && y.between?(0,7) && !@added_moves.include?(pos) end def find_path(end_pos) node = @move_tree.bfs(end_pos) trace_path_back(node) end def trace_path_back(node) return [node.value] if node.parent.nil? trace_path_back(node.parent) + [node.value] end end
true
d3242265da882efdadc139e63b81a21663851272
Ruby
antonr/calculator
/spec/lib/calculator_spec.rb
UTF-8
277
2.6875
3
[]
no_license
require 'calculator' describe Calculator do it "adds numbers" do expect(subject.add(2, 3)).to eq(5) end it "subtracts numbers" do expect(subject.subtract(2, 3)).to eq(-1) end it "multiplies numbers" do expect(subject.multiply(2, 3)).to eq(6) end end
true
86873272e589231015306749c5b04d0556ff5090
Ruby
yuqiqian/ruby-leetcode
/62_uniq_path.rb
UTF-8
170
2.765625
3
[]
no_license
def unique_paths(m, n) result = 1 total = m+n-2 chosen = ([m,n].min)-1 total.downto(total-chosen+1){|i| result *= i} 0.upto(chosen-1){|i| result /= i+1} result end
true
0a32c5c1d1e691b1440d4b6d3ae8686577a91a2c
Ruby
masterzora/tawny-cdk
/examples/entry_ex.rb
UTF-8
2,185
3.28125
3
[ "BSD-3-Clause", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
#!/usr/bin/env ruby require_relative 'example' class EntryExample < Example def EntryExample.parse_opts(opts, param) opts.banner = 'Usage: dialog_ex.rb [options]' param.x_value = CDK::CENTER param.y_value = CDK::CENTER param.box = true param.shadow = false super(opts, param) end # This program demonstrates the Cdk dialog widget. def EntryExample.main title = "<C>Enter a\n<C>directory name." label = "</U/5>Directory:<!U!5>" params = parse(ARGV) # Set up CDK. curses_win = Ncurses.initscr cdkscreen = CDK::SCREEN.new(curses_win) # Start color. CDK::Draw.initCDKColor # Create the entry field widget. directory = CDK::ENTRY.new(cdkscreen, params.x_value, params.y_value, title, label, Ncurses::A_NORMAL, '.', :MIXED, 40, 0, 256, params.box, params.shadow) xxxcb = lambda do |cdktype, object, client_data, key| return true end directory.bind(:ENTRY, '?', xxxcb, 0) # Is the widget nil? if directory.nil? # Clean p cdkscreen.destroy CDK::SCREEN.endCDK puts "Cannot create the entry box. Is the window too small?" exit # EXIT_FAILURE end # Draw the screen. cdkscreen.refresh # Pass in whatever was given off of the command line. arg = if ARGV.size > 0 then ARGV[0] else nil end directory.set(arg, 0, 256, true) # Activate the entry field. info = directory.activate('') # Tell them what they typed. if directory.exit_type == :ESCAPE_HIT mesg = [ "<C>You hit escape. No information passed back.", "", "<C>Press any key to continue." ] directory.destroy cdkscreen.popupLabel(mesg, 3) elsif directory.exit_type == :NORMAL mesg = [ "<C>You typed in the following", "<C>(%.*s)" % [246, info], # FIXME: magic number "", "<C>Press any key to continue." ] directory.destroy cdkscreen.popupLabel(mesg, 4) else directory.destroy end # Clean up and exit. cdkscreen.destroy CDK::SCREEN.endCDK exit # EXIT_SUCCESS end end EntryExample.main
true