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
6a30f26de186b90475477377482f59bec8f23a50
Ruby
kipkosek/kele
/lib/kele.rb
UTF-8
964
2.671875
3
[]
no_license
require 'httparty' require 'json' require_relative 'roadmap' require_relative 'messages' class Kele include HTTParty include Roadmap include Messages base_uri "https://www.bloc.io/api/v1" def initialize(email, password) response = self.class.post("https://www.bloc.io/api/v1/sessions", body: { email: email, password: password }) @auth_token = response['auth_token'] if response.nil? || response['auth_token'].nil? raise ArgumentError.new("The system was unable to authorize you.") end end def get_me response = self.class.get("https://www.bloc.io/api/v1/users/me", headers: { "authorization" => @auth_token }) @current_user_hash = JSON.parse(response.body) end def get_mentor_availability(mentor_id) response = self.class.get("https://www.bloc.io/api/v1/mentors/#{mentor_id}/student_availability", headers: { "authorization" => @auth_token }) @mentor_schedule = JSON.parse(response.body) end end
true
6411cc5faa65bbceba3a73b0eba621021c3d8ee9
Ruby
djstozza/shift_care_code_test
/app/serializers/client_serializer.rb
UTF-8
886
2.546875
3
[]
no_license
# == Schema Information # # Table name: clients # # id :bigint not null, primary key # date_of_birth :date not null # email :citext not null # first_name :citext not null # last_name :citext not null # private_note :string # created_at :datetime not null # updated_at :datetime not null # # Indexes # # index_clients_on_email (email) UNIQUE # class ClientSerializer < BaseSerializer ATTRS = %w[ id email first_name last_name date_of_birth ].freeze def serializable_hash(*) attributes.slice(*ATTRS).tap do |attrs| attrs[:private_note] = private_note if includes[:private_note] attrs[:address] = serialized_address if includes[:address] end end private def serialized_address AddressSerializer.new(address) end end
true
bfccc2bc5864a7c04e6f3c6815da544864ca112e
Ruby
jwhiteman/zeromq
/ch3/asyncserv.rb
UTF-8
2,447
2.59375
3
[]
no_license
# socket.identity=() # poller.register_readable() # socket.recv_strings # poller.poll(msecs) => int # poller for async reading from a single socket # rand(n..m) # rand() # bare # ZMQ::Device.create() # ZMQ::QUEUE # poller sans poll in the server routine # ensure fucks up interrupts ? require "ffi-rzmq" require "openssl" require "pry" def hex_ident OpenSSL::Random.random_bytes(4). bytes. map { |b| sprintf("%02X", b) }. join("-") end # threads acting as separate processes def client context = ZMQ::Context.new socket = context.socket(ZMQ::DEALER) socket.identity = hex_ident socket.connect("tcp://localhost:5570") print("Client #{socket.identity} started\n") poller = ZMQ::Poller.new poller.register(socket, ZMQ::POLLIN) reqs = 0 loop do reqs = reqs + 1 socket.send_string("Request ##{reqs += 1}") puts "C1" 5.times do socket.recv_string(message = "") puts "C2" puts "#{socket.identity}: #{message.last}" $stdout.flush end end end def worker(context) loop do wsocket = context.socket(ZMQ::DEALER) if wsocket.nil? puts "Worker failed to connect. Retrying..." sleep 1 else wsocket.connect("inproc://backend") puts "Worker connected." loop do puts "W1" wsocket.recv_strings(message = []) puts "WORKER: I received #{message.inspect}" rand(1..4).times do sleep rand wsocket.send_strings(message) end end end if wsocket wsocket.close break else # no-op, repeat end end end clients = 5.times.map do Thread.new { client } end context = ZMQ::Context.new raise "STOP" unless context frontend = context.socket(ZMQ::ROUTER) frontend.setsockopt(ZMQ::ROUTER_MANDATORY, 1) frontend.bind("tcp://*:5570") backend = context.socket(ZMQ::DEALER) backend.bind("inproc://backend") workers = 5.times.map do Thread.new { worker(context) } end #ZMQ::Device.create(ZMQ::QUEUE, frontend, backend) #workers.each(&:join) # poller = ZMQ::Poller.new poller.register(frontend, ZMQ::POLLIN) poller.register(backend, ZMQ::POLLIN) loop do poller.poll poller.readables do |readable| if readable == frontend puts "Readable on frontend" elsif readable == backend puts "Readable on backend" else puts "unknown" end end end
true
3bafe1bf4971f757baac74f9a11a70f04dae1b9e
Ruby
MoMI-G/MoMI-G
/scripts/bam2gam/uuid.rb
UTF-8
523
2.9375
3
[ "MIT", "LicenseRef-scancode-w3c-03-bsd-license", "BSD-3-Clause", "CC-BY-4.0", "MIT-0", "GPL-1.0-or-later", "MPL-2.0", "WTFPL", "MIT-Wu", "CC0-1.0", "ISC", "GPL-2.0-only", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
#!/bin/ruby # # previous_line = [] count = 0 STDIN.each_line do |line| line = line.split(" ") current_id = line[3] if previous_line.length > 3 && previous_line[3] == current_id previous_line[3] += "_#{count}:#{previous_line[5]}" count += 1 else #count += 1 previous_line[3] += "_#{count}:#{previous_line[5]}" if previous_line.length > 3 count = 0 end puts previous_line.join(" ") previous_line = line end previous_line[3] += "_#{count}:#{previous_line[5]}" puts previous_line.join(" ")
true
f7aba3e608a3bbd7bb579796d87e2a5edb88fbf0
Ruby
arifk-repo/Homework
/test/category_spec.rb
UTF-8
1,652
2.5625
3
[]
no_license
require '../models/category' require '../controllers/category_controller' require 'erb' describe CategoryController do context '#category' do before(:each) do @category_controller = CategoryController.new end it "get all category from database" do actual_view = @category_controller.index_category category = Category.get_all_categories expected_output = ERB.new(File.read("../views/index_category.erb")).result(binding) expect(expected_output).to eq(actual_view) end it "add category" do actual_view = @category_controller.add_category expected_output = ERB.new(File.read("../views/create.erb")).result(binding) expect(expected_output).to eq(actual_view) end it "Show form to add" do actual_view = @category_controller.form_add expected_output = ERB.new(File.read("../views/new_category.erb")).result(binding) expect(expected_output).to eq(actual_view) end it "Edit Category" do id=5 actual_view = @category_controller.edit_category(id) category = Category.find_by_id(id) expected_output = ERB.new(File.read("../views/edit_category.erb")).result(binding) expect(expected_output).to eq(actual_view) end it "Update Category" do name = "Traditional" id = 5 actual = @category_controller.update_category(id,name) expected = Category.update(id,name) expect(expected).to eq(actual) end it "Delete Category" do id=7 actual = @category_controller.delete_category(id) expected = Category.delete(id) expect(expected).to eq(actual) end end end
true
d59ef736b18e577582523672e104697743c3aa2c
Ruby
AudreyLeeMe/bikle100
/app/cj/predictions/fx_past/run_fx_past_week.rb
UTF-8
1,968
3.03125
3
[]
no_license
# # run_fx_past_week.rb # # I use this script to loop through spool files created by sqlplus. require 'rubygems' require 'hpricot' # require 'ruby-debug' # I start by getting a list of spool files created by sqlplus: glb = Dir.glob("/pt/s/rl/bikle100/app/cj/predictions/fx_past/tmp_fx_past_week_20*.lst").sort glb.each{|fn| # For each file, make note of the date embedded in the filename. # The date should be a Sunday. # I use the date to identify a weeks worth of data: the_date = fn.sub(/tmp_fx_past_week_/,'').sub(/.lst/,'').gsub(/-/,'_').sub(/\/.*\//,'') # generate bread_crumbs from the_date bread_crumbs = "Site Map > Predictions > Forex > Past Forex Predictions #{the_date}" site_map = '<a href="/r10/site_map">Site Map</a>' predictions = '<a href="/predictions">Predictions</a>' forex = '<a href="/predictions/fx">Forex</a>' past_forex_predictions = '<a href="/predictions/fx_past">Past Forex Predictions</a>' bread_crumbs = "#{site_map} > #{predictions} > #{forex} > #{past_forex_predictions} > Week of: #{the_date}" # generate h5-element from the_date h5_element = "<h5>Week of: #{the_date}</h5>" # Next, I feed the file to Hpricot so I can access HTML in the file: doc = open(fn){ |f| Hpricot(f) } # Generate some a-elements from th-elements. th_elems = doc.search("th") th_elems.each {|elm| ei_h = elm.innerHTML ei_hclass = ei_h.gsub(/\n/,'').gsub(/\<br \/>/,'').gsub(/ /,'').downcase elm.innerHTML = "<a class='#{ei_hclass}'>#{ei_h}</a>" } # Load some html into a string: some_html=doc.search("table.table_fx_past_week").to_html # I want a file for this URL pattern: # href="/predictions/fx_past_wk2011_01_30" html_f=File.new("/pt/s/rl/bikle100/app/views/predictions/fx_past_wk#{the_date}.html.erb", "w") # Fill the file with HTML which I had obtained from sqlplus: html_f.puts bread_crumbs + h5_element + some_html p "#{html_f.path} File written" html_f.close }
true
6d583f9b78e49c4bccb928fe8194324437a42d35
Ruby
mkroman/blur
/library/blur/channel.rb
UTF-8
2,206
2.90625
3
[ "ISC" ]
permissive
# frozen_string_literal: true module Blur # The +Channel+ class is used for encapsulating a channel and its properties. # # Users inside the channel is stored in the {#channels} attribute. # # Modes can be set for a channel, but Blur is not # {http://www.irc.org/tech_docs/005.html ISupport}-compliant yet. # # @todo make so that channels *and* users belongs to the network, and not # like now where the user belongs to the channel, resulting in multiple # user instances. class Channel # @return [String] the channels name. attr_accessor :name # @return [String] the channels topic. attr_accessor :topic # @return [Array] list of references to users in the channel. attr_accessor :users # @return [String] all the modes set on the channel. attr_accessor :modes # @return [Network] a reference to the network. attr_accessor :network # Instantiate a user with a nickname, a network and a user list. def initialize name, network = nil @name = name @users = [] @modes = '' @network = network end # Merge the channels mode corresponding to the leading character (+ or -). # # @param [String] modes the modes to merge with. def merge_modes modes addition = true modes.each_char do |char| case char when '+' addition = true when '-' addition = false else addition ? @modes.concat(char) : @modes.delete!(char) end end end # Send a message to the channel. # # @param [String] message the message to send. def say message @network.say self, message end # Convert it to a debug-friendly format. def inspect "#<#{self.class.name}:0x#{object_id.to_s 16} " \ "@name=#{@name.inspect} " \ "@topic=#{@topic.inspect} " \ "@users=#{@users.inspect}>" end # Called when YAML attempts to save the object, which happens when a # scripts cache contains this user and the script is unloaded. def to_yaml options = {} @name.to_yaml options end # Get the channels name. def to_s @name end end end
true
ed1d308e3c9763cd9710518adc1905bc6ed63b9e
Ruby
omairqazi29/liquid-galaxy
/kamelopard/lib/kamelopard/geocode.rb
UTF-8
2,118
3.234375
3
[ "GPL-1.0-or-later", "Ruby", "GPL-2.0-only", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-or-later", "GPL-2.0-or-later", "Apache-2.0" ]
permissive
# vim:ts=4:sw=4:et:smartindent:nowrap require 'rubygems' require 'net/http' require 'uri' require 'cgi' require 'json' # Geocoder base class class Geocoder def initialize raise "Unimplemented -- some other class should extend Geocoder and replace this initialize method" end def lookup(address) raise "Unimplemented -- some other class should extend Geocoder and replace this lookup method" end end # Uses Yahoo's PlaceFinder geocoding service: http://developer.yahoo.com/geo/placefinder/guide/requests.html # Google's would seem most obvious, but since it requires you to display # results on a map, ... I didn't want to have to evaluate other possible # restrictions. The argument to the constructor is a PlaceFinder API key, but # testing suggests it's actually unnecessary class YahooGeocoder < Geocoder def initialize(key) @api_key = key @proto = 'http' @host = 'where.yahooapis.com' @path = '/geocode' @params = { 'appid' => @api_key, 'flags' => 'J' } end # Returns an object built from the JSON result of the lookup, or an exception def lookup(address) # The argument can be a string, in which case PlaceFinder does the parsing # The argument can also be a hash, with several possible keys. See the PlaceFinder documentation for details # http://developer.yahoo.com/geo/placefinder/guide/requests.html http = Net::HTTP.new(@host) if address.kind_of? Hash then p = @params.merge address else p = @params.merge( { 'q' => address } ) end q = p.map { |k,v| "#{ CGI.escape(k) }=#{ CGI.escape(v) }" }.join('&') u = URI::HTTP.build([nil, @host, nil, @path, q, nil]) resp = Net::HTTP.get u parse_response resp end def parse_response(resp) d = JSON.parse(resp) raise d['ErrorMessage'] if d['Error'].to_i != 0 d end end # EXAMPLE # require 'rubygems' # require 'kamelopard' # g = YahooGeocoder.new('some-api-key') # puts g.lookup({ 'city' => 'Springfield', 'count' => '100' })
true
db7a3dee41ce2acd4aa7d03049e0516a4c7940fe
Ruby
chrisberkhout/ffaker
/lib/ffaker/lorem.rb
UTF-8
2,494
2.65625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Faker # Based on Perl's Text::Lorem module Lorem extend ModuleUtils extend self def word WORDS.rand end def words(num = 3) WORDS.random_pick(num) end def sentence(word_count = 4) s = words(word_count + rand(6)) s = s.join(' ') s.capitalize! "#{s}." end def sentences(sentence_count = 3) (1..sentence_count).map { sentence } end def paragraph(sentence_count = 3) sentences(sentence_count + rand(3)).join(' ') end def paragraphs(paragraph_count = 3) (1..paragraph_count).map { paragraph } end WORDS = k %w(alias consequatur aut perferendis sit voluptatem accusantium doloremque aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo aspernatur aut odit aut fugit sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt neque dolorem ipsum quia dolor sit amet consectetur adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem ut enim ad minima veniam quis nostrum exercitationem ullam corporis nemo enim ipsam voluptatem quia voluptas sit suscipit laboriosam nisi ut aliquid ex ea commodi consequatur quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae et iusto odio dignissimos ducimus qui blanditiis praesentium laudantium totam rem voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident sed ut perspiciatis unde omnis iste natus error similique sunt in culpa qui officia deserunt mollitia animi id est laborum et dolorum fuga et harum quidem rerum facilis est et expedita distinctio nam libero tempore cum soluta nobis est eligendi optio cumque nihil impedit quo porro quisquam est qui minus id quod maxime placeat facere possimus omnis voluptas assumenda est omnis dolor repellendus temporibus autem quibusdam et aut consequatur vel illum qui dolorem eum fugiat quo voluptas nulla pariatur at vero eos et accusamus officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae itaque earum rerum hic tenetur a sapiente delectus ut aut reiciendis voluptatibus maiores doloribus asperiores repellat) end end
true
7a701facef4a442eff12e33920374bd5a460ad0c
Ruby
kevinjd/vivixx
/friday.rb
UTF-8
1,072
3.90625
4
[]
no_license
def convertion puts "Enter the temp in Celcius" tempc = gets.chomp.to_f tempf = (tempc * 9) / 5 + 32 puts tempf puts "Converting back to Celcius" temf = (tempf - 32) * 5 / 9 puts temf puts "Initial Fare is 35\n" puts "Enter the distance of destination in kilometers" dist = gets.chomp.to_f distConvert = dist * 1000 fareAdd = (distConvert / 400) * 2 puts "Your taxi fare is" totFare = fareAdd + 35 puts totFare.to_i puts "Enter how much US Dollar you would like to convert to Philippine Peso" usD = gets.chomp.to_f usdTotal = usD * 49.45 puts usdTotal puts "Enter how much Japanese Yen you would like to convert to Philippine Peso" jpY = gets.chomp.to_f jpyTotal = jpY * 0.45 puts jpyTotal.to_f end def exe convertion end @patak = 35 def convertF(tempf) return (tempc * 9) / 5 + 32 end puts "Enter temp in Celcius" tempc = gets.chomp.to_f puts "Temp convert from Celcius to Fahrenheit is: #{convertF(tempf)}" #$selection [ # {convert: 'Celcius to Fahrenheit', } #] #puts "Select what kind of convert would you like"
true
8f8fb92ff55a21c4125d1cbe2324efcacc1ed1b1
Ruby
nburt/weather_data_api
/spec/kelvin_converter_spec.rb
UTF-8
555
3.265625
3
[]
no_license
require 'spec_helper' require './lib/kelvin_converter' describe KelvinConverter do it 'can return temperature in Kelvin' do kelvin_converter = KelvinConverter.new(1) expect(kelvin_converter.convert('Kelvin')).to eq 1 end it 'can convert Kelvin to Fahrenheit' do kelvin_converter = KelvinConverter.new(1) expect(kelvin_converter.convert('Fahrenheit')).to eq -457.87 end it 'can convert Kelvin to Celsius' do kelvin_converter = KelvinConverter.new(1) expect(kelvin_converter.convert('Celsius')).to eq -272.15 end end
true
0c1c9745a5ca1dd8a531a56545e8aea88f0c7c3b
Ruby
PD2015/launch_school
/oop/lesson_4/medium1.rb
UTF-8
2,198
4.625
5
[]
no_license
# 4) # Let's practice creating an object hierarchy. # Create a class called Greeting with a single method called greet that takes a string # argument and prints that argument to the terminal. # Now create two other classes that are derived from Greeting: one called Hello and one # called Goodbye. The Hello class should have a hi method that takes no arguments and # prints "Hello". The Goodbye class should have a bye method to say "Goodbye". # Make use of the Greeting class greet method when implementing the Hello and Goodbye # classes - do not use any puts in the Hello or Goodbye classes. # class Greeting # def greet(string) # puts string # end # end # class Hello < Greeting # def hi # greet("Hello") # end # end # class Goodbye < Greeting # def bye # greet('Goodbye') # end # end # h = Hello.new # h.hi # gb = Goodbye.new # gb.bye # 5) # And the following specification of expected behavior: # Write additional code for KrispyKreme such that the puts # statements will work as specified above. # puts donut1 # => "Plain" # puts donut2 # => "Vanilla" # puts donut3 # => "Plain with sugar" # puts donut4 # => "Plain with chocolate sprinkles" # puts donut5 # => "Custard with icing" class KrispyKreme attr_reader :filling_type, :glazing def initialize(filling_type, glazing) @filling_type = filling_type @glazing = glazing end # def to_s # if filling_type != nil && glazing != nil # "#{filling_type} with #{glazing}" # elsif filling_type != nil && glazing == nil # filling_type # elsif filling_type == nil && glazing != nil # "Plain with #{glazing}" # elsif filling_type == nil && glazing == nil # "Plain" # end # end def to_s filling_string = filling_type ? filling_type : "Plain" glazing_string = glazing ? " with #{glazing}" : '' filling_string + glazing_string end end donut1 = KrispyKreme.new(nil, nil) donut2 = KrispyKreme.new("Vanilla", nil) donut3 = KrispyKreme.new(nil, "sugar") donut4 = KrispyKreme.new(nil, "chocolate sprinkles") donut5 = KrispyKreme.new("Custard", "icing") puts donut1 puts donut2 puts donut3 puts donut4 puts donut5
true
6441714fc723ed9505392085eee50553adeddab8
Ruby
kristianmandrup/twitter-bootstrap-helpers
/lib/twitter-bootstrap-helpers/view_helpers.rb
UTF-8
1,225
2.53125
3
[ "MIT" ]
permissive
module TwitterBoots class << self attr_writer :validate def validate @validate ||= true end alias_method :validate?, :validate def validate_type! type return true if !validate? || valid_type?(type) raise ArgumentError, "Not a valid type: #{type}, must be one of: #{valid_types}" end def validate_progress_type! type return true if !validate? || valid_progress_type?(type) raise ArgumentError, "Not a valid progress type: #{type}, must be one of: #{valid_progress_types}" end def valid_type? type valid_types.include? type.to_s end def valid_progress_type? type valid_progress_types.include? type.to_s end def valid_progress_types %w{info success warning danger} end def valid_types %w{success warning important info inverse} end def helper_modules %w{alert badge hero_unit icon label progress thumbnail} end end end module TwitterBootstrapHelpers module ViewHelpers TwitterBoots.helper_modules.each do |name| require "twitter-bootstrap-helpers/view_helpers/#{name}" include "TwitterBootstrapHelpers::ViewHelpers::#{name.camelize}".constantize end end end
true
82b8fa9a928fcaf97557eb342c9847f6fc2397ce
Ruby
vietluonghoang/ruby_data
/lib/test_chamber/app/creator/app_ui_base.rb
UTF-8
941
2.59375
3
[]
no_license
module TestChamber::Creator class App # Common logic needed for both V1 and V2 UI app creation module UiBase # The api and UI have different platform strings so translate them so we can find them in the UI def translate_platform_to_ui(platform) translated = { 'android' => 'Android', 'iphone' => 'iOS', 'windows' => 'Windows' }[platform] unless translated raise "Unknown api platform '#{platform}' so we can translate it into the string on the UI" end translated end # grab the last thing in the url def id_from_url url = URI.parse(current_url) self.id = url.path.split('/')[-1] unless TestChamber::UUID.uuid?(id) raise "We were looking for an id in the last part of the path but it doesn't look like a uuid. id: #{id}, url: #{url}" end id end end end end
true
cec9095e8a6b0159aa90f098222ee49ec43d17b7
Ruby
rickhull/compsci
/lib/compsci/graph.rb
UTF-8
14,515
3.203125
3
[]
no_license
require 'set' module CompSci class CycleError < RuntimeError; end class MultiGraphError < RuntimeError; end class UnexpectedError < RuntimeError; end # represents an edge between two vertices, *src* and *dest* Edge = Data.define(:src, :dest, :value) do def initialize(src:, dest:, value: nil) super(src: src, dest: dest, value: value) end def to_s format("%s --%s--> %s", src, value, dest) end end # consists of Vertices connected by Edges class Graph attr_reader :vtx def initialize @vtx = Set.new @edge = {} # keyed by the *src* vertex end # add a new edge to @edge, adding vertices to @vtx as needed def edge(src, dest, value) # check if this would create MultiGraph e = Edge.new(src, dest, value) if !self.is_a? MultiGraph and self.edge_between?(dest, src) raise(MultiGraphError, e.to_s) end self.add_edge e end def assert_edge(src: nil, dest: nil, value: nil) edges = self.edges(src: src, dest: dest, value: value) case edges.count when 0 raise(UnexpectedError, "no edges found") when 1 edges[0] else raise(UnexpectedError, "multiple edges found: #{edges.inspect}") end end # @edge[src][dest] => Edge; MultiGraph uses a different array impl def add_edge e @edge[e.src] ||= {} @edge[e.src][e.dest] = e @vtx.add(e.src) @vtx.add(e.dest) end def delete(edge) @edge.each_value { |hsh| hsh.delete_if { |_, e| e == edge } } self end def clear!(src: nil, dest: nil, value: nil) if src hsh = @edge[src] or return if dest if value # (src, dest, value) hsh.delete(dest) if hsh[dest]&.value == value else # (src, dest, _) hsh.delete(dest) end else if value # (src, _, value) hsh.delete_if { |_, e| e.value == value } else # (src, _, _) @edge.delete(src) end end else # (_, ?, ?) @edge.each_value { |hsh| if dest if value # (_, dest, value) hsh.delete(dest) if edge[dest]&.value == value else # (_, dest, _) hsh.delete(dest) end else # (_, _, ?) hsh.delete_if { |_, e| value and e.value == value } end } end end # remove empty structures; update @vtx def clean! @edge.delete_if { |_, hsh| hsh.empty? } @vtx.keep_if { |v| @edge.key?(v) or @edge.values.any? { |hsh| hsh.key? v } } self end # check both directions; return any edge found def edge_between?(src, dest) @edge.dig(src, dest) or @edge.dig(dest, src) end # return the (dest) vertex for an edge matching (src, value) def follow(src, value) hsh = @edge[src] or return false dests = hsh.values.select { |e| e.value == value }.map(&:dest) return false if dests.empty? dests.sample end # iterate edges like: graph.each_edge(**filters) { |e| puts e } def each_edge(src: nil, dest: nil, value: nil) if src hsh = @edge[src] or return self if dest # (src, dest, ?) if (e = hsh[dest]) yield e unless (value and e.value != value) end else # (src, _, ?) hsh.each_value { |e| yield e unless (value and e.value != value) } end else # (_, ?, ?) @edge.values.each { |hsh| if dest # (_, dest, ?) if (e = hsh[dest]) yield e unless (value and e.value != value) end else # (_, _, ?) hsh.each_value { |e| yield e unless (value and e.value != value) } end } end self end # return a flat list of edges def edges(src: nil, dest: nil, value: nil) ary = [] self.each_edge(src: src, dest: dest, value: value) { |e| ary << e } ary end # edges include vertices; one edge per line def to_s self.edges.join($/) end end # allow multiple edges between any two vertices # store edges with Array rather than Hash class MultiGraph < Graph # @edge[src] => [Edge, Edge, ...] def add_edge e @edge[e.src] ||= [] @edge[e.src] << e @vtx.add(e.src) @vtx.add(e.dest) e end def delete(edge) @edge.each { |src, ary| ary.delete_if { |e| e == edge } } self end def clear!(src: nil, dest: nil, value: nil) if src ary = @edge[src] or return if dest # (src, dest, ?) ary.delete_if { |e| e.dest == dest and (value.nil? or e.value == value) } else # (src, _, ?) if value.nil? # (src, _, _) @edge.delete(src) else # (src, _, value) ary.delete_if { |e| e.value == value } end end else # (_, ?, ?) @edge.each_value { |ary| ary.delete_if { |e| (dest.nil? and value.nil?) or # (_, _, _) (dest.nil? and e.value == value) or # (_, _, value) (value.nil? and e.dest == dest) or # (_, dest, _) (e.dest == dest and e.value == value)# (_, dest, value) } } end end def clean! @edge.delete_if { |_, ary| ary.empty? } @vtx.keep_if { |v| @edge.key?(v) or !self.edges(dest: v).empty? } self end # check both directions; return any edge found def edge_between?(src, dest) @edge[src].each { |e| return e if e.dest == dest } if @edge[src] @edge[dest].each { |e| return e if e.dest == src } if @edge[dest] false end # return the (dest) vertex for an edge matching (src, value) def follow(src, value) ary = @edge[src] or return false dests = ary.select { |e| e.value == value }.map(&:dest) return false if dests.empty? dests.sample end # iterate edges like: graph.each_edge(**filters) { |e| puts e } def each_edge(src: nil, dest: nil, value: nil) if src ary = @edge[src] or return self # filter on src ary.each { |e| next if dest and e.dest != dest # filter on dest next if value and e.value != value # filter on value yield e } else @edge.values.each { |ary| ary.each { |e| next if dest and e.dest != dest # filter on dest next if value and e.value != value # filter on value yield e } } end self end end # Undirected Acyclic Graph, not a MultiGraph class AcyclicGraph < Graph attr_accessor :check_add def initialize(check_add: false) @check_add = check_add super() end def reset_search @visited, @finished = {}, {} self end # @edge[src][dest] => Edge, like Graph # may raise CycleError, especially with @check_add def add_edge e raise(CycleError, e) if e.src == e.dest @edge[e.src] ||= {} @edge[e.src][e.dest] = e if @check_add # does the new edge create a cycle? begin self.check_cycle! rescue CycleError => error @edge[e.src].delete(e.dest) raise error end end @vtx.add(e.src) @vtx.add(e.dest) e end # perform depth first search from every vertex; may raise CycleError def check_cycle! self.reset_search @vtx.each { |v| self.dfs v } self.reset_search end # recursive depth first search; may raise CycleError def dfs(v, skip = nil) return true if @finished[v] raise(CycleError, "dfs(#{v})") if @visited[v] @visited[v] = true # search every neighbor (but don't search back to v) self.each_edge { |e| if e.dest == v and e.src != skip self.dfs(e.src, skip = v) elsif e.src == v and e.dest != skip self.dfs(e.dest, skip = v) end } @finished[v] = true end end FOREST = AcyclicGraph class AcyclicMultiGraph < MultiGraph attr_accessor :check_add def initialize(check_add: false) @check_add = check_add super() end def reset_search @visited, @finished = {}, {} self end # @edge[src][dest] => Edge, like Graph # may raise CycleError, especially with @check_add def add_edge e raise(CycleError, e) if e.src == e.dest @edge[e.src] ||= {} @edge[e.src][e.dest] = e if @check_add # does the new edge create a cycle? begin self.check_cycle! rescue CycleError => error @edge[e.src].delete(e.dest) raise error end end @vtx.add(e.src) @vtx.add(e.dest) e end # perform depth first search from every vertex; may raise CycleError def check_cycle! self.reset_search @vtx.each { |v| self.dfs v } self.reset_search end # recursive depth first search; may raise CycleError def dfs(v, skip = nil) return true if @finished[v] raise(CycleError, "dfs(#{v})") if @visited[v] @visited[v] = true # search every neighbor (but don't search back to v) self.each_edge { |e| if e.dest == v and e.src != skip self.dfs(e.src, skip = v) elsif e.src == v and e.dest != skip self.dfs(e.dest, skip = v) end } @finished[v] = true end end # TODO class DirectedAcyclicMultiGraph < AcyclicMultiGraph; end class DirectedAcyclicGraph < AcyclicGraph # roots have nothing pointing *to* them def roots invalid = Set.new @edge.each_value { |hsh| invalid.merge(hsh.values.map(&:dest)) } @vtx - invalid end # perform depth first search on every root; may raise CycleError def check_cycle! roots = self.roots raise(CycleError, "invalid state: no roots") if roots.empty? self.reset_search roots.each { |v| self.dfs(v) } self.reset_search end # recursive depth first search, following directed edges def dfs(v) return true if @finished[v] raise(CycleError, "dfs(#{v})") if @visited[v] @visited[v] = true # search via src -> dest @edge[v]&.each_value { |e| self.dfs(e.dest) } @finished[v] = true end end DAG = DirectedAcyclicGraph # Pre-made patterns # Note: these are available for Graph and all its subclasses (self.new) class Graph # single vertex; allowed by anything not Acyclic def self.loop1 graph = self.new graph.edge 0, 0, :loop graph end # two vertices; creates a MultiGraph; allowed by MultiGraph def self.loop2 graph = self.new graph.edge 0, 1, :out graph.edge 1, 0, :back graph end # three vertices; allowed by anything not Acyclic def self.loop3 graph = self.new graph.edge 0, 1, :a graph.edge 1, 2, :b graph.edge 2, 0, :c graph end def self.multigraph # multigraph, multiple (possibly directed) edges between 0 and 1 # # __a__ Graph: MultiGraphError # / \ MultiGraph: allow # 0 1 AcyclicGraph: MultiGraphError # \__b__/ DAG: MultiGraphError # FSM: allow graph = self.new graph.edge 0, 1, :a graph.edge 0, 1, :b graph end def self.diamond # diamond pattern, starts at 0, ends at 3 # 1 # / \ Graph: allow # a/ \c MultiGraph: allow # / \ AcyclicGraph: CycleError # 0 3 DAG: allow # \ / FSM: allow # b\ /d # \ / # 2 graph = self.new graph.edge 0, 1, :a graph.edge 0, 2, :b graph.edge 1, 3, :c graph.edge 2, 3, :d graph end def self.fork # fork pattern, 3 nodes, two edges with the same value # 1 # / Graph: allow # a/ Multigraph: allow # / AcyclicGraph: allow # 0 DAG: allow # \ FSM: allow # a\ Deterministic FSM: reject 2nd edge # \ # 2 graph = self.new graph.edge 0, 1, :a graph.edge 0, 2, :a graph end # two separate trees def self.forest graph = self.new graph.edge 0, 1, :root graph.edge 1, 2, :trunk graph.edge 2, 3, :branch graph.edge 2, 4, :branch graph.edge 5, 6, :root graph.edge 6, 7, :trunk graph.edge 7, 8, :branch graph.edge 7, 9, :branch graph end # one center vertex; the rest are leaves def self.star graph = self.new graph.edge 0, 1, :center graph.edge 0, 2, :center graph.edge 0, 3, :center graph.edge 0, 4, :center graph.edge 0, 5, :center graph end # allows chains, not just leaves def self.starlike graph = self.new graph.edge 0, 1, :center graph.edge 0, 2, :center graph.edge 0, 3, :center graph.edge 0, 4, :center graph.edge 0, 5, :center graph.edge 5, 6, :ray graph end # all vertices within distance 1 of a central path subgraph def self.caterpillar graph = self.new graph.edge 0, 1, :head graph.edge 1, 2, :trunk graph.edge 2, 3, :trunk graph.edge 3, 4, :trunk graph.edge 4, 5, :tail graph.edge 1, 6, :leg graph.edge 1, 7, :leg graph.edge 2, 8, :leg graph.edge 2, 9, :leg graph.edge 3, 10, :leg graph.edge 3, 11, :leg graph.edge 4, 12, :leg graph.edge 4, 13, :leg graph end # all vertices within distance 1 of a central path subgraph def self.lobster graph = self.caterpillar graph.edge 6, 14, :claw graph.edge 6, 15, :claw graph.edge 7, 16, :claw graph.edge 7, 17, :claw graph end end end
true
c572064ee3d242f70e21207541455de742b05b43
Ruby
skryl/cursed
/lib/cursed/elements/full_grid.rb
UTF-8
747
2.890625
3
[ "MIT" ]
permissive
class Cursed::FullGrid < Cursed::Grid CELL_SIZE = 2 def initialize(container, opts) super(container, opts) @cell_size = opts[:cell_size] || CELL_SIZE @box_size = @cell_size + 2 @cratio = @box_size @rratio = 2 end private def draw full_grid(1, 1) end #TODO: refactor me # def full_grid(row,col) cells = [] row_idx_sz = 3 print_indices(row, col, cell_size+1, rratio) rows.times do |r| rshift = (rratio - 1) * r cols.times do |c| cshift = (cratio - 1) * c rstart, cstart = row+r+rshift+1, col+c+cshift+row_idx_sz cells[r * cols + c] = [rstart+1,cstart+rratio] rect(rstart,cstart,rstart+4,cstart+box_size) end end cells end end
true
f8689e4de4a9ec9912fa7443d5c7905dd7173e7c
Ruby
froot/advent_2019
/day_1/p2.rb
UTF-8
322
3.46875
3
[]
no_license
filename = 'input_1.txt' fuels = [] modules = File.readlines(filename).map do |line| line.to_i end modules.each do |mass| fuels << (mass/3) - 2 while(fuels.last != 0) next_fuel = (fuels.last/3) - 2 if next_fuel.negative? fuels << 0 else fuels << next_fuel end end end puts fuels.sum
true
0a14efc33fcb3e103688cf28e62f0fe09b319a32
Ruby
max-codeware/rbLinCAS
/System/Intermediate/SymbolTable/SymbolTabEntry.rb
UTF-8
4,684
3.078125
3
[]
no_license
#! /usr/bin/env ruby ## # This is an implementation of a symbol table entry for LinCAS. # It collects datas on the entered identifier, and works like a symbol # table for all the identifier related to that one. A graphical # representation can be: # ``` # ENTRY: # |- NAME # |- DEFINITION # |- PATH # |- LEVEL # |- ATTRIBUTES # |__ # |- SYMBOL_TABLE # ``` # NAME is the name of the identifier, DEFINITION is the kind of identifier and can be: # * VOID # * CLASS # * MODULE # * GLOBAL_IDENT # * LOCAL_IDENT # * CONST # # PATH is the path of the ID in the symbol table, LEVEL is the nesting level, # while ATTRIBUTES is other information related to the ID. # # # Author:: Massimiliano Dal Mas (mailto:max.codeware@gmail.com) # License:: Distributed under MIT license class SymbolTabEntry < Hash # Instantiates the global variables def initialize(name,path,level = 0) @name = name @path = path.clone @level = level @def = nil @lineNum = [] @attrs = {} end # Sets the definition of the entry # # * **argument**: definition of the ID def setDef(definition) @def = definition end # Sets an attribute to the entry # # * **argument**: SymbolTabKey of the attribute # * **argument**: attribute def setAttr(key,attribute) @attrs[key] = attribute end # Adds a line number # # * **argument**: line number (Integer) def addLineNum(lineNum) @lineNum << lineNum end # * **returns**: name of the entry def getName @name end # * **returns**: path of this entry in the SymbolTable def getPath @path end # * **returns**: the nesting level of the entry def getLevel @level end # * **returns**: the definition of the entry def getDef @def end # * **returns**: an attribute of the entry def getAttr(key) return @attrs[key] if @attrs.keys.include? key nil end # * **returns**: all the attrs def getAttrs @attrs end # * **returns**: the line number of the symbol def getLineNums @lineNum end # Enters a symbol locally # # * **argument**: ID name # * **returns**: SymbolTabEntry def enterLocal(name) path = @path.clone path.addName(name) self[name] = SymTabGen.generateEntry(name,path,@level + 1) self[name] end # Looks a symbol up locally # # * **argument**: name of the symbol (symbol itself) # * **returns**: SymbolTabEntry if the symbol exists; +nil+ else def lookUpLocal(name) return self[name] if self.keys.include? name nil end # Forwards an #enterLocal, unless the path points to the current entry # # * **argument**: path to the sub-symbol table # * **argument**: name of the symbol # * **returns**: SymbolTabEntry # * **raises**: RuntimeError if the path does not exist or is empty def sendEnterLocal(path,name) unless path.empty? root = path.getRoot if self.keys.include? root return self[root].sendEnterLocal(path.getChild,name) else # Should never get here raise RuntimeError, "Unexisting symbol table path '#{path.to_s}'" end else return self.enterLocal(name) end end # Forwards an #importToLocal consuming the path # # * **argument**: path to the scope # * **argument**: SymbolTabEntry def sendImportToLocal(path,entry) raise RuntimeError, "Symbol table is receiving an empty path" if path.empty? root = path.getRoot raise RuntimeError, "Unexisting symbol table path '#{path.to_s}'" unless @name == root if path.hasChild? then self[root].senfImportToLocal(path.getChild,entry) else self[root].importToLocal(entry) end end # Imports an entry onto the current scope # # * **argument**: SymbolTabEntry def importToLocal(entry) name = entry.getName entry = entry.clone path = @path.clone path.addName(name) entry.setPath(path) self[name] = entry end # * **returns**: all the global variables (used for classes) def getGlobal global = [] self.each_key do |entryName| entry = self[entryName] global << entry if entry.getDef == Def.G_IDENT end global end # Gets an entry with the specified symbol table path # # * **argument**: path to the symbol # * **returns**: SymbolTabEntry if the path exists; +nil+ else def get(path) unless path.empty? root = path.getRoot if path.hasChild? then return self[root].get(path.getChild) if self.keys.include? root else return self[root] if self.keys.include? root end end nil end protected def setPath(path) @path = path.clone end end
true
ad2faf70fa17dc5c5cb43b8066bf33d1bd44dadc
Ruby
ronniekram/codewars
/leetcode/duplicates.rb
UTF-8
420
3.515625
4
[]
no_license
# @param {Integer[]} nums # @return {Boolean} def contains_duplicate(nums) new_nums = nums.each_with_object(Hash.new(0)) do |element, num_hash| num_hash[element] += 1 end new_nums.values.any? {|num| num > 1} ? true : false end # Runtime: 84 ms, faster than 11.00% of Ruby online submissions for Contains Duplicate. # Memory Usage: 214.4 MB, less than 6.70% of Ruby online submissions for Contains Duplicate.
true
34e1a408142b66453c426894aeb2754742b6b7d3
Ruby
Martin-Nyaga/emerald
/spec/error_spec.rb
UTF-8
886
2.578125
3
[]
no_license
require "spec_helper" require "emerald/error" describe Emerald::Error do it "shows a contextual error message for a single line script" do file = Emerald::Files::ScriptFile.new("foo @ world") raise Emerald::Error.new("test error", file, 4) rescue Emerald::Error => e message = <<~MSG Error: test error in #{file.path}:1 1| foo @ world | ^ here MSG expect(e.to_s).to eq(message) end it "shows a contextual error message for a multiline file/script" do file = Emerald::Files::ScriptFile.new("foo bar\n@ world") raise Emerald::Error.new("test error", file, 8) rescue Emerald::Error => e message = <<~MSG Error: test error in #{file.path}:2 1| foo bar 2| @ world | ^ here MSG expect(e.to_s).to eq(message) end end
true
4b08a5d5a76024cd0f5a87ae56a1704bd7fb8e06
Ruby
Kite0301/atcoder
/cf2015/team/class_test.rb
UTF-8
206
3.546875
4
[]
no_license
class Cat attr_accessor :name, :color def initialize(name, color) @name = name; @color = color end def add puts "#{self.name}-#{self.color}" end end cat=Cat.new("Tama", "white") cat.add
true
5116c12c66b727b8588b0f2e95a5115299e02227
Ruby
ColinOsborn/scrabble
/test/scrabble_test.rb
UTF-8
614
2.84375
3
[]
no_license
gem 'minitest' require_relative '../lib/scrabble' require 'minitest/autorun' require 'minitest/pride' require 'pry' class ScrabbleTest < Minitest::Test def test_it_can_score_a_single_letter assert_equal 1, Scrabble.new.score("a") assert_equal 4, Scrabble.new.score("f") end def test_it_can_be_a_full_word assert_equal 7, Scrabble.new.score("shit") assert_equal 22, Scrabble.new.score("QUIZ") end def test_it_likes_f1_names assert_equal 9, Scrabble.new.score("Vettel") assert_equal 6, Scrabble.new.score("Alonso") assert_equal 17, Scrabble.new.score("Raikkonen") end end
true
012628eb4ec257f5d7ef02b8f7823679cf622f4a
Ruby
abhi1988srivastava/Ruby
/exception_handling.rb
UTF-8
1,754
3.921875
4
[]
no_license
=begin Exception handling: similar to try-catch-finally of java.. try => begin catch => rescue finally => ensure =end begin res=1/0 rescue Exception => e x=0 puts(e.class) #prints out class : ZeroDivisionError, can also be achieved as puts($!.class) ; catches last exception puts(e) # description : divided by 0 end puts("================================================") def execCalc(num1,num2) begin res=num1/num2 rescue Exception=>e res=0 puts(e.class) puts(e) end return res end execCalc(10,0) puts("================================================") =begin multiple exceptions can be caught like" rescue TypeError, NoMethodError => e or rescue TypeError=> e #do something rescue NoMethodError => e #do other thing Always put the specific exception above the generalised one. Once the exception has been caught, the process down go further down the next exception. Sometimes, you want to execute some code ONLY when there is no exception, ruby comes to rescue with else clause. =end def execCalc(num1,num2) begin res=num1/num2 rescue Exception=>e res=0 puts(e.class) puts(e) else puts("I am only when no exception") ensure puts("I will run no matter what") end end execCalc(1,0) puts("================================================") def execCalc(num1,num2) begin res=num1/num2 rescue Exception=>e res=0 puts(e.class) puts(e) else puts("I am only when no exception") ensure puts("I will run no matter what") end end execCalc(1,1) puts("================================================") #to see complete list of errors and errorcodes ruby provides puts(Errno.constants) #puts(Errno.constants::Errno) --> to see all the numeric value associated with Err constants
true
7b1b8bfce67f2685c291422010ac6aeca79485e9
Ruby
littlethao/rectangle
/rectangle.rb
UTF-8
254
3.390625
3
[]
no_license
def print_rectangle length = ARGV[0].to_i height = ARGV[1].to_i top = "-" * length body = [] height.times do body.push("|" + (" " * (length - 2)) + "|") end last = "-" * length puts top puts body puts last end print_rectangle
true
961ce978a99389d5f2a604b3e2974d599b8657c9
Ruby
growenthall/thehardway
/ex1.rb
UTF-8
83
2.703125
3
[]
no_license
puts "hello world" puts "hello again" puts "I like typing this" puts "This is fun!"
true
f9ec4233ada1aaf63583945144bee7094d96104b
Ruby
Airvanne/Ruby_preparcours
/exo_13.rb
UTF-8
108
3.203125
3
[]
no_license
puts "Quelle est votre année de naissance ?" number = gets.to_i number.upto 2018 do |annee| puts annee end
true
bbe91f19341c1688ee3737a35d439e4fec404552
Ruby
gelisam/dotfiles
/bin-todo/subtract
UTF-8
612
3.109375
3
[]
no_license
#!/usr/bin/ruby # Only works if f2 is a strict subset of f1 #f2 = File.open(ARGV[1]) #File.open(ARGV[0]) {|f1| # next_kill = nil # begin # next_kill = f2.readline # rescue EOFError # next_kill = nil # end # f1.each_line {|line| # if line == next_kill # begin # next_kill = f2.readline # rescue EOFError # next_kill = nil # end # else # print line # end # } #} # always works, but takes more memory require 'set' f2 = Set.new(File.open(ARGV[1]) {|f| f.readlines}) File.open(ARGV[0]) {|f1| f1.each_line {|line| print line unless f2.include?(line) } }
true
1562e9c26752deb2d1fc811bab1faa55e7a1d3cf
Ruby
rajmohand/L-99-Ninety-Nine-Lisp-Problems-Solutions-Ruby
/11.rb
UTF-8
341
3
3
[]
no_license
def sort(array) finished = [array.first], i = 0 nw=[] array.each_cons(2) do |(a,b)| if b == a finished[i] << b else finished[i += 1] = [b] end end finished.each do |x| if x.count>1 then nw << [x.first,x.count] else nw << [x.first] end end p nw end data=%w[e s s e e] sort(data)
true
d77d716b14989599888b098c40ef33481d84985f
Ruby
mskeen/adventofcode
/2016/day06/day6.rb
UTF-8
362
2.9375
3
[]
no_license
lines = File.read('./input.txt').split("\n") digits = lines[0].size answer1 = answer2 = '' (0..(digits - 1)).each do |i| # puts i counts = Hash.new(0) lines.each do |line| counts[line[i]] += 1 end # Part a answer1 += counts.sort_by { |k,v| v }.last[0] # Part b answer2 += counts.sort_by { |k,v| v }.first[0] end puts answer1 puts answer2
true
03a222ff0dcd288d8c0995e498823437109bcca1
Ruby
DavidLohmann/week4-homework
/app/controllers/weather_controller.rb
UTF-8
533
2.78125
3
[]
no_license
require 'open-uri' # Only the names of classes are capitalized class WeatherController < ApplicationController # This is pulling an html file named search. # File must be in "views" folder then within "weather" folder def search end # @ creates a variable that files in your "views" file can access def conditions @city = params[:city] @url = URI.escape("http://api.openweathermap.org/data/2.5/weather?q=#{@city}&units=imperial") @json_data = open(@url).read @data = JSON.parse (@json_data) end end
true
7718cd2deea5388ec82c0aae9e52dee37ca8b2fb
Ruby
vbrazo/algorithms-archives
/math/power_of_three.rb
UTF-8
1,191
4.5625
5
[]
no_license
# Given an integer n, return true if it is a power of three. Otherwise, # return false. # An integer n is a power of three, if there exists an integer x such # that n == 3^x. # # Approach 1: Loop iteration # # One simple way of finding out if a number n is a power of a number b is to # keep dividing n by b as long as the remainder is 0. This is because we can # write: # n=b^x # n=b×b×…×b # Hence it should be possible to divide n by b x times, every time with a # remainder of 0 and the end result to be 1. # Notice that we need a guard to check that n != 0, otherwise the while loop # will never finish. For negative numbers, the algorithm does not make sense, # so we will include this guard as well. # Complexity Analysis # # Time complexity: O(log b(n)). In our case that is O(log(3n)). # The number of divisions is given by that logarithm. # Space complexity: O(1). We are not using any additional memory. def is_power_of_three(n) return false if n < 1 n /= 3 while n % 3 == 0 n == 1 end n = 27 is_power_of_three(n) # Output: true n = 0 is_power_of_three(n) # Output: false n = 9 is_power_of_three(n) # Output: true n = 45 is_power_of_three(n) # Output: false
true
5e2d734647ad9bed6a6bad29ea28670e9ca56b06
Ruby
balaji-kmty/RB101
/medium_exercises/sides_triangles.rb
UTF-8
763
4.34375
4
[]
no_license
# Write a method that takes the lengths of the 3 sides of a triangle as arguments, and returns a symbol :equilateral, :isosceles, :scalene, or :invalid depending on whether the triangle is equilateral, isosceles, scalene, or invalid. def valid?(tri) max_position = tri.find_index(tri.max) tri.reduce(:+) - tri[max_position] > tri[max_position] end def triangle(one, two, three) triangle = [one, two, three] return :invalid unless valid?(triangle) if one == two && one == three :equilateral elsif (one == two || two == three || one == three) :isosceles else :scalene end end triangle(3, 3, 3) == :equilateral triangle(3, 3, 1.5) == :isosceles triangle(3, 4, 5) == :scalene triangle(0, 3, 3) == :invalid triangle(3, 1, 1) == :invalid
true
c863391d923771058d44e98d5a671b3f7a395f5f
Ruby
rameshrvr/thorin
/spec/thorin_spec.rb
UTF-8
2,411
2.59375
3
[]
no_license
require 'spec_helper' require 'yaml' # Initialize file path for test yaml files SYNTAX_CHECK_PATH = File.dirname(__FILE__) + '/syntax_check/' USERNAME_CHECK_PATH = File.dirname(__FILE__) + '/verify_username/' RSpec.describe 'Thorin:' do it 'Verification on version number' do expect(Thorin::VERSION).to eq '0.1.0' end describe 'Validate Syntax checks: ' do it 'Syntax check should PASS for Good YAML file'.green do obj = Thorin::Shield.new(SYNTAX_CHECK_PATH + 'Test1.yaml', {}) expect(obj.syntax_check).to eq true end it 'Syntax check should FAIL for Bad YAML file'.green do obj = Thorin::Shield.new(SYNTAX_CHECK_PATH + 'Test2.yaml', {}) expect(obj.syntax_check).to eq false end it 'Syntax check on non-existing file'.green do obj = Thorin::Shield.new(SYNTAX_CHECK_PATH + 'Something.yaml', {}) res = false # Catch the exception and compare it with the message begin obj.syntax_check rescue RuntimeError => err # true if the exception matches the give string res = true if err.to_s.include?('File doesnot exists!!!') end expect(res).to eq true end it 'Syntax check on extension of the file'.green do obj = Thorin::Shield.new(SYNTAX_CHECK_PATH + 'Test3.yal', {}) res = false begin obj.syntax_check rescue RuntimeError => err # true if the exception matches the give string res = true if err.to_s.include?('Seems the extension is not .yaml !!!') end expect(res).to eq true end end # Verificaion related to username stuffs describe 'Validate Username checks: ' do it 'username check in Hash of Hash structure'.green do obj = Thorin::Shield.new(USERNAME_CHECK_PATH + 'Test1.yaml', {}) expect(obj.verify_username).to eq false end it 'username check in Hash of Array structure'.green do obj = Thorin::Shield.new(USERNAME_CHECK_PATH + 'Test2.yaml', {}) expect(obj.verify_username).to eq false end it 'username check in Hash structure'.green do obj = Thorin::Shield.new(USERNAME_CHECK_PATH + 'Test3.yaml', {}) expect(obj.verify_username).to eq false end it 'username check should pass for a perfect YAML'.green do obj = Thorin::Shield.new(USERNAME_CHECK_PATH + 'Test4.yaml', {}) expect(obj.verify_username).to eq true end end end
true
65d2d1b4a954b56fd01e3bea369a9df729dd4632
Ruby
turboladen/screenplay
/lib/screenplay/part.rb
UTF-8
3,503
3.03125
3
[ "MIT" ]
permissive
class Screenplay # Parts are a simple mechanism for allowing you to create your own grouping of # actions, usually to accomplish some task. Think of it like a script that # you can pass in some options to and call from other scripts. This is # similar to a Puppet Module, Chef Cookbook, or Ansible Playbook. # # You might, for example, want a Part that installs rbenv, RVM, or just plain # old Ruby built from scratch. You can create a Part for one (or all), then # stash it somewhere that Screenplay has access to, require it wherever you're # using a Screenplay::Host, and the Host can then run all of the actions in # the Part, simply by calling #play_part on the Host object. # # The only requirement for your Parts are that they a) inherit from this class # and b) define a #play method. # # There is a gem of popular Parts, +screenplay-parts+ that might be useful to # you... # # @example A partial MySQL part # # # A port of Opscode's MySQL Server Part could look something like: # class MySQL < Screenplay::Part # # Define this here, or in some other file. And use some other Ruby # # feature other than a constant--it's up to you. # PACKAGES = { # debian: 'mysql-server', # rhel: 'mysql-server', # fedora: 'mysql-server', # centos: 'mysql-server', # } # # def play(root_group: 'root', conf_dir: '/etc/mysql', package: PACKAGES[host.env.distribution]) # case host.env.operating_system # when :linux # case host.env.distribution # when :ubuntu # preseeding_dir = '/var/cache/local/preseeding' # preseeding_file = "#{preseeding_dir}/mysql-server.seed" # # host.directory path: preseeding_dir, owner: 'root', group: root_group, mode: '0755' # host.template path: preseeding_file, source: 'mysql-server.seed.erb', # owner: 'root', group: root_group, mode: '0600' # host.shell command: "debconf-set-selections #{preseeding_file}" # host.template path: "#{conf_dir}/debian.cnf", source: 'mysql-server.seed.erb', # owner: 'root', group: root_group, mode: '0600' # # host.apt package: PACKAGES[host.env.distribution] # when :centos # # Etc # end # when :darwin # # Etc # end # # end # # # Add any helper methods too, if you want to refactor #play... # end # # # Then your Host object could use that by: # # host = Screenplay::Host.new('localhost') # # # Use the default values defined for MySQL#play # host.play_part MySQL # # # Pass in other values # host.play_part MySQL, conf_dir: '/opt/mysql/conf', root_group: 'admin' class Part # @param [Screenplay::Host] host The host that should play the part. # @param [Hash] options Any options to pass on to the user-defined Part's # #play method. def self.play(host, **options) new(host, **options) end # @return [Screenplay::Host] Allows child objects easy access to a Host # object and its methods from within the Part. attr_reader :host # @param [Screenplay::Host] host The host that should play the part. # @param [Hash] options Any options to pass on to the user-defined Part's # #play method. def initialize(host, **options) @host = host options.empty? ? play : play(**options) end end end
true
445ea2600f8b8399553bae09b2e4ccb84e55ed14
Ruby
rsnorman/weekly_album_anniversaries
/lib/services/account_management/new_twitter_friend_accumulator.rb
UTF-8
792
2.515625
3
[]
no_license
# frozen_string_literal: true require_relative 'twitter_friend_id' module AccountManagement # Collects all new twitter friend accounts class NewTwitterFriendAccumulator def self.all new.all end def initialize(twitter_friend_ids: TwitterFriendId.all, current_follows: TwitterFollow.all, twitter_client: WistfulIndie::Twitter::Client.client) @twitter_friend_ids = twitter_friend_ids @current_follows = current_follows @twitter_client = twitter_client end def all untracked_friend_ids.map do |friend_id| @twitter_client.user(friend_id) end end private def untracked_friend_ids @twitter_friend_ids - @current_follows.pluck(:twitter_id).map(&:to_i) end end end
true
c9b2214a38fec2ee93044377fe0613960e1bc379
Ruby
rubykorea/codingdojo
/2012_10_25/imyostarr&wangsy/spec/discount_oil_spec.rb
UTF-8
546
2.71875
3
[]
no_license
require "spec_helper" require "discount_oil" describe DiscountOil do let(:discount_oil) { DiscountOil.new(75, [20, 40], [90, 80]) } describe "#quick_methods" do # it "test" do # discount_oil.first_method(35).should == 3000 # discount_oil.first_method(100).should == 7900 # discount_oil.second_method(35).should == 3000 # discount_oil.second_method(100).should == 7900 # end it "#price_for_amount" do discount_oil.price_for_amount(100).should == 7900 discount_oil.price_for_amount(35).should == 3000 end end end
true
59ae5aba19a848fd664de90de2a1dc6975c5a5e5
Ruby
trbradley/rps-challenge
/lib/computer.rb
UTF-8
225
2.8125
3
[]
no_license
class Computer attr_reader :weapon_choice def initialize(weapons_selection = Game::WEAPONS) @weapons_selection = weapons_selection end def choose_weapon @weapon_choice = @weapons_selection.sample end end
true
d218d9f4d073d39dfd89b7109649c4d1376ef6a0
Ruby
JediMindTricks/WDI
/WDI-Workspace/Week-04/Day-03/intro_to_ruby/first_ruby.rb
UTF-8
209
3.625
4
[]
no_license
# Defining a method then calling it def say_hello name p "Hello World! Nice to meet you " + name end say_hello "Michael" def product a,b return a * b end p product 5,5 i = 0 while i < 10 p i i+=1 end
true
7b1ffdca2d88ecedc7ae8a896ed3c9a2baa316be
Ruby
elitenomad/family-tree
/lib/family/tree/cli.rb
UTF-8
709
2.671875
3
[ "MIT" ]
permissive
module Family module Tree class CLI attr_reader :executor def initialize @executor = Family::Tree::Executor.new end def load(file) if !Family::Tree::ACCEPTED_FORMATS.include?(File.extname(file)) raise Family::Tree::FileFormatNotSupportedError.new end File.readlines(file).map do |line| Family::Tree::Command.parse(line) end end def run(commands) commands.each do |command, *args| begin puts executor.send(command, *args) unless command == :invalid rescue => e puts "#{e.message}" next end end end end end end
true
9cb5270bc557a0275fcda4bf07dffd9d1fe3a79a
Ruby
greedychipmunk/sieve-of-era
/sieveOfEratosthenes.rb
UTF-8
1,419
4.1875
4
[]
no_license
#!/usr/bin/env ruby # # Playing with the Sieve of Eratosthenes algorithm in Ruby # @author Dawson Blackhouse class Array def getFirstElement self.each { |e| if e != nil return e end } end def getLastElement last = self.reverse return last.getFirstElement end end def secret(number) return number end def primeToLimit(limit) primes = Array[1] if limit == 1 return primes end numbers = Array.new(limit+1){|index| index} numbers[0] = nil numbers[1] = nil begin start = numbers.index(numbers.getFirstElement) last = numbers.index(numbers.getLastElement) numbers[start] = nil primes.push(start) inc = start start = start * start i = start while i <= last numbers[i] = nil i = i + inc end end while start < limit return primes + numbers.compact end def isItSecretIsItSafe(primes) checked = Array.new() primes.each{|x| primes.each{|y| if !checked.index(y) secretXPlusY = secret(x + y) secretXPlusSecretY = secret(x) + secret(y) if secretXPlusY != secretXPlusSecretY return false end end } checked.push(x) } return true end limit = ARGV[0].to_i if limit < 1 puts 'Input (%s) not an integer or less than 1' % limit exit end puts 'Limit is %s' % limit puts 'Primes:' puts primeToLimit(limit) if isItSecretIsItSafe(primeToLimit(limit)) puts 'secret is an additive function' else puts 'secret is not an additive function' end
true
30af0d730374fca1651c3bd2c90534bbc8487460
Ruby
pierrebeaucamp/Exercism-Ruby
/difference-of-squares/difference_of_squares.rb
UTF-8
296
3.453125
3
[ "Unlicense" ]
permissive
class Squares VERSION = 1 def difference square_of_sums - sum_of_squares end def initialize x @x = x end def square_of_sums (@x * (@x + 1) / 2) ** 2 end def sum_of_squares (1..@x).inject do |sum, n| sum + n ** 2 end end end
true
e9d47e28e647af7f610de02c432438f6df959c3d
Ruby
kabligh/boris-bikes
/spec/docking_station_spec.rb
UTF-8
912
2.859375
3
[]
no_license
require 'docking_station' require 'bike' describe DockingStation do describe '#release_bike' do it { is_expected.to respond_to(:release_bike) } it 'raises an error when no bikes available' do expect { subject.release_bike }.to raise_error "No bikes available" end end # describe '#working?' do # it 'releases working bikes' do # subject.dock(Bike.new) # bike = subject.release_bike # expect(bike).to respond_to(:working?) # end # end describe '#dock' do # it 'docks bike at docking station' do # bike = Bike.new # station = DockingStation.new # expect(station.dock(bike)).to eq bike # end it 'raises an error when docking station is full' do DockingStation::DEFAULT_CAPACITY.times do subject.dock Bike.new end expect { subject.dock Bike.new }.to raise_error "Docking station full" end end end
true
f73434b4500dc7e6a310ac9d25582a2af9ddbf9e
Ruby
ccallebs/Moon-Critter
/lib/map_tile.rb
UTF-8
694
3.046875
3
[]
no_license
require 'gosu' require './lib/map_tiles/type' class MapTile HEIGHT = 50 WIDTH = 50 attr_accessor :window, :type, :x, :y def initialize(window, raw_type, x = 0, y = 0) @window = window @type = MapTiles::Type.new(raw_type) @image = Gosu::Image.new(@window, @type.image_path, false) if @type.has_image? @x = x @y = y end def draw if @type.has_image? @image.draw_rot(@x + 25, @y + 25, 1, 0.0) else @window.draw_quad(@x, @y, @type.hex_color, @x + WIDTH, @y, @type.hex_color, @x, @y + HEIGHT, @type.hex_color, @x + WIDTH, @y + HEIGHT, @type.hex_color, 1) end end end
true
f8325d8062f6fbebec929c733b8b22fb7619b963
Ruby
michaela260/slack-cli
/test/user_test.rb
UTF-8
1,891
2.9375
3
[]
no_license
require_relative 'test_helper' describe 'class user' do let(:user){Slack::User.new(id: "USLACKBOT", name: "slackbot", real_name: "Slackbot", status_text: "Print is dead", status_emoji: ":books:")} describe 'initialize' do it 'creates a new instance of User' do expect(user).must_be_instance_of Slack::User end it 'accurately stores attributes' do expect(user.id).must_be_instance_of String expect(user.id).must_equal "USLACKBOT" expect(user.name).must_be_instance_of String expect(user.name).must_equal "slackbot" expect(user.real_name).must_be_instance_of String expect(user.real_name).must_equal "Slackbot" expect(user.status_text).must_be_instance_of String expect(user.status_text).must_equal "Print is dead" expect(user.status_emoji).must_be_instance_of String expect(user.status_emoji).must_equal ":books:" end end describe 'self.list' do it "returns an array of user objects" do VCR.use_cassette("user_list_cassette") do list = Slack::User.list expect(list).must_be_instance_of Array list.each do |user| expect(user).must_be_instance_of Slack::User end end end end describe 'details' do let(:result){user.details} it 'returns a hash' do expect(result).must_be_instance_of Hash end it 'returns a hash with length 5' do expect(result.length).must_equal 5 end it "accurately stores the current user's information" do expect(result[:username]).must_equal 'slackbot' expect(result[:id]).must_equal 'USLACKBOT' expect(result[:real_name]).must_equal 'Slackbot' expect(result[:status_text]).must_equal 'Print is dead' expect(result[:status_emoji]).must_equal ':books:' end end end
true
1c41fe29c6b7da3e76babad21dd44a9a96d0b1a0
Ruby
tschaffer1618/module_0_capstone
/day_3/else_and_if.rb
UTF-8
658
4.1875
4
[]
no_license
people = 30 cars = 40 trucks = 15 if cars > people puts "We should take the cars." elsif cars < people puts "We should not take the cars." else puts "We can't decide." end if trucks > cars puts "That's too many trucks." elsif trucks < cars puts "Maybe we could take the trucks." else puts "We still can't decide." end if people > trucks puts "Alright, let's just take the trucks." else puts "Fine, let's stay home then." end # elsif puts another conditional option after the first if-statement # else is used for any other result than the specified conditional if cars > trucks && people >= cars puts "What?!?" else puts "OK." end
true
274d0056bd9ebbb3fb141ccd8a033a54528105cc
Ruby
mashiro/enver
/lib/enver/loader.rb
UTF-8
1,875
2.8125
3
[ "MIT" ]
permissive
require 'ostruct' module Enver class Loader attr_reader :attributes def initialize(env, prefix = '', &block) @env = env @prefix = prefix @attributes = OpenStruct.new instance_eval(&block) if block end def value(*args) options = extract_options! args has_default = options.key? :default name = args.shift env_name = args.shift || name.to_s.upcase value = fetch env_name, options value = yield value, options if !has_default && block_given? store name, value end def string(*args) value(*args) do |v| v end end def integer(*args) value(*args) do |v| Integer(v) end end def float(*args) value(*args) do |v| Float(v) end end def boolean(*args) value(*args) do |v, options| true_values = options[:true_values] || %w(1 t true y yes) true_values.include?(v) end end def array(*args) value(*args) do |v, options| pattern = options[:pattern] || ',' limit = options[:limit] || 0 v.split(pattern, limit) end end def partial(*args, &block) options = extract_options! args name = args.shift env_prefix = args.shift || "#{name.to_s.upcase}_" store name, Loader.new(@env, with_prefix(env_prefix), &block).attributes end private def extract_options!(args) args.last.is_a?(::Hash) ? args.pop : {} end def with_prefix(env_name) "#{@prefix}#{env_name}" end def store(name, value) @attributes.send("#{name}=", value) end def fetch(env_name, options = {}) env_name = with_prefix(env_name) if options.has_key? :default @env.fetch(env_name, options[:default]) else @env.fetch(env_name) end end end end
true
1955cd8a35472377d7f8807d6715d269c62d8a57
Ruby
Pi-hils/process_review
/leetcode/spec/robot_spec.rb
UTF-8
453
2.90625
3
[]
no_license
require 'robot' describe Robot do context "a robot starts from the origin and makes its movement, find out if it ends back to the origin" do #| "UD" | True #At Origin, 0,0| it 'starts from an origin and moves to the up, then down, does it return to origin?' do expect(subject.movement("UD")).to be true end it"the robot turns LR, it should also return back to origin" do expect(subject.movement("LR")).to be true end end end
true
9cc910376fd9f1453fadf127f9332a212b1c60ac
Ruby
ChicksEater/COS10009-Introduction-to-Programming
/projects/2.2T-Functions/hello_user_with_functions.rb
UTF-8
1,219
4.125
4
[]
no_license
require 'date' require './input_functions' # Multiply metres by the following to get inches: INCHES = 39.3701 # Insert into the following your hello_user code # from task 1.3P and modify it to use the functions # in input_functions def main() # HOW TO USE THE input_functions CODE # Example of how to read strings: name = read_string('What is your name?') puts "Your name is " + name + "!" family_name = read_string('What is your family name?') puts "Your family name is " + family_name + "!" year_born = read_integer('What year were you born?') age = Date.today.year - year_born.to_i puts 'So you are ' + age.to_s + ' years old' height = read_float('Enter your height in metres (i.e as a float): ') height_inches = height * INCHES puts ('Your height in inches is: ' + height_inches.to_s) continue = read_boolean("Do you want to continue?") if (continue) puts 'Ok, lets continue ' main() else puts 'ok, goodbye ' end # Now if you know how to do all that # Copy in your code from your completed # hello_user Task 1.3 P. Then modify it to # use the code in input_functions. # use read_string for all strings (this will # remove all whitespace) end main()
true
430a79d4c3538639d5a76587f089c59aae9faef5
Ruby
rove-rb/rove
/lib/rove/package.rb
UTF-8
1,501
2.578125
3
[ "MIT" ]
permissive
module Rove class Package < Option include Support::Storer attr_reader :settings class << self def [](id) id = id.to_sym; Package.all.select{|x| x.id == id}.first end end def [](id) id = id.to_sym; @settings.select{|x| x.id == id}.first end def initialize(id, &block) @settings = [] super(nil, id, self, &block) raise "You should set category for #{@id} package" if @category.blank? store end def category(title=false) return @category unless title @category = Rove::Category.build(title) end def finalizer(&block) @finalizer = block end def finalize(config) return config unless @finalizer @finalizer.call(config) end def configure(config, build) return {} unless @config result = case @config.arity when 0 @config.call when 1 @config.call config when 2 @config.call config, build end result = {} unless result.is_a?(Hash) result end def ensure_option!(parent, id, package, &block) ensure! Option.new(parent, id, package, &block) end def ensure_input!(parent, id, package, &block) ensure! Input.new(parent, id, package, &block) end def ensure!(entity) if @settings.map{|x| x.id}.include?(entity.id) raise "Setting '#{entity.id}' is taken within '#{@id}'!" end @settings << entity entity end end end
true
852768b115ac47dacb16fded20c546f072cfc490
Ruby
onosi/math_puzzle_1
/q17.rb
UTF-8
218
3.625
4
[]
no_license
@number = 30 @male, @female = "m" , "f" def add(seq) return 1 if seq.size == @number count = add(seq + @male) count += add(seq + @female) if seq[-1] == @male count end puts add(@male) + add(@female)
true
d732e04d4836592adef7c341dee4b64a25b5bd19
Ruby
cheif/RemotePlay
/server.rb
UTF-8
620
2.890625
3
[]
no_license
require 'rubygems' require 'em-websocket' require 'mediaplayer' puts "Starting server" soundcloudURL = Regexp.new(/soundcloud.com*/); youtubeURL = Regexp.new(/youtube.com\/watch\?*/); player = Mediaplayer.new EventMachine::WebSocket.start(:host => '0.0.0.0', :port => 2011) do |ws| ws.onopen { ws.send "Hello Client!" } ws.onmessage {|msg| if msg == "Hello Server!" puts "!!Handshake recived" else case when soundcloudURL.match(msg) then player.soundcloud(msg) when youtubeURL.match(msg) then player.youtube(msg) else puts "#{msg} is not a valid url" end end } ws.onclose {} end
true
54d80657ac6da72ccee6217ebd32c93e61a53a23
Ruby
jamiehodge/crdt
/lib/crdt/g_counter.rb
UTF-8
455
2.78125
3
[]
no_license
module Crdt module GCounter extend self def create Hamster.hash end def increment(counter, delta, node = Crdt.node) counter.put(node) {|v| v.to_i + delta.to_i } end def merge(counter, other) array = (counter.keys | other.keys).map do |key| [key, [counter[key].to_i, other[key].to_i].max] end Hamster.hash(array) end def value(counter) counter.values.sum end end end
true
b59ee44b4660b1be97bb2d39c7d1b9e307f1d91f
Ruby
birkirb/hue-lib
/lib/hue/config/abstract.rb
UTF-8
1,571
2.984375
3
[]
no_license
require 'yaml' require 'fileutils' module Hue module Config class NotFound < Hue::Error; end; class Abstract public attr_reader :path, :name def initialize(name, path) @path = path @name = name self.class.setup_file_path(self.path) end def write(overwrite_existing_key = false) yaml = YAML.load_file(self.path) rescue nil yaml ||= Hash.new if yaml.key?(name) && !overwrite_existing_key raise "Key named '#{name}' already exists in config file '#{self.path}'.\nPlease remove it before creating a new one with the same name." else add_self_to_yaml(yaml) dump_yaml(yaml) end end def delete yaml = YAML.load_file(self.path) rescue Hash::New if yaml.key?(name) yaml.delete(name) end dump_yaml(yaml) end def ==(rhs) lhs = self lhs.class == rhs.class && lhs.name == rhs.name end private def add_self_to_yaml(yaml) yaml[name] = {} end def dump_yaml(yaml) File.open(self.path, 'w+' ) do |out| YAML.dump(yaml, out) end end def self.setup_file_path(path) dir = File.dirname(path) FileUtils.mkdir_p(dir) unless Dir.exists?(dir) end def self.read_file(config_file) begin YAML.load_file(config_file) rescue => err raise Error.new("Failed to read configuration file", err) end end end end end
true
040ebba6847fcf69055a6de6159b55afa87f86b9
Ruby
Maxcutex/rubypractice
/hangman/lib/hangman.rb
UTF-8
4,262
3.3125
3
[]
no_license
class Hangman def initialize @secret_word = get_random_word @word_array = @secret_word.downcase.split("") @current_display = ('_' * @word_array.length).split("") # Array.new(@word.size, "_") @guesses_remaining = 6 @valid_guesses = ('a'..'z').to_a @previous_guesses = [] startoption end def startoption puts "Do you want to start a fresh game, enter 'start' or load a previously saved game, enter 'load'" startop = gets.chomp.downcase if startop == "start" playgame elsif startop == "load" display_saved_games else puts "You have not entered a valid option" startoption end end def get_random_word dictionary = File.read("5desk.txt").split("\r\n") valid_words = dictionary.select { |word| word.size >= 5 && word.size <= 12} word = valid_words.sample end def get_guesses puts "\nKindly enter your guess letter or type 'save' to save the game and 'quit' to quit the game entirely" guessed_letter = gets.chomp.downcase puts if guessed_letter == "save" save_game elsif guessed_letter == "quit" quit_game elsif @word_array.include?(guessed_letter) @word_array.each_with_index do |letter, index| @current_display[index] = guessed_letter if letter == guessed_letter end puts "The word contains the letter '#{guessed_letter}'!" else @guesses_remaining -= 1 puts "Sorry, the word does not contain that letter." end @previous_guesses << guessed_letter show_status end def save_game puts "Kindly enter the name for saving the game" filename = gets.chomp Dir.mkdir "saved_games" unless Dir.exists? "saved_games" filepath = "saved_games/#{filename}" remaining = @guesses_remaining.to_s saved_game = File.new(filepath, 'w') saved_game.write(@secret_word +"\n") saved_game.write(@current_display.join("") +"\n") saved_game.write(remaining +"\n") saved_game.write(@previous_guesses.join("")) saved_game.close puts "Game saved successfully!" continue_or_quit end def continue_or_quit puts "Kindly enter 'c' to continue or 'q' to quit!!!" confirm = gets.chomp if confirm == "c" puts "Game continues!!!" playgame elsif confirm == "q" quit_game else puts "You have not entered a valid option " continue_or_quit end end def quit_game puts "Are you sure you want to quit the game? Type 'Yes' or 'No'" confirm = gets.chomp.downcase if confirm == "yes" exit elsif confirm == "no" playgame else puts "You have not entered a valid option" quit_game end end def display_saved_games Dir.mkdir("saved_games") unless Dir.exists? "saved_games" games = Dir.glob('saved_games/*') if games.count == 0 puts "You have no saved games yet." puts "Let's start a new game." return playgame else games.each {|x| puts "Saved file: #{x.split("/")[1]}"} end puts "Type the name of the saved game you'd like to access." input = gets.chomp load_saved_game(input) end def load_saved_game(file_name) saved_game = File.readlines("saved_games/#{file_name}") @previous_guesses = [] @secret_word = saved_game[0] @word_array = @secret_word.downcase.split("") @current_display = saved_game[1].split("") @guesses_remaining = saved_game[2].to_i pr = saved_game[3] if !pr.nil? temp = saved_game[3].split("") temp.each { |tval| @previous_guesses << tval } end File.delete("saved_games/#{file_name}") playgame end def show_status puts "Guesses remaining to use: #{@guesses_remaining}" puts "Guessed letters: #{@previous_guesses.join(", ")}" puts "Word Built: #{@current_display.join()}" end def playgame puts "New game of Hangman started!" show_status get_guesses while !game_over? end def game_over? if @guesses_remaining == 0 puts "Oops, the word was '#{@secret_word}', you lose!" return true elsif !@current_display.include?("_") puts "You Win!" return true else return false end end end
true
e735ce7882db9111d9dd96e6a7ec0a2ac0c5f3e5
Ruby
blackbirdco/wit-ruby2
/lib/wit/result.rb
UTF-8
512
2.625
3
[ "MIT" ]
permissive
module Wit class Result attr_reader :id, :text, :intent, :confidence, :entities def initialize(hash) @id = hash['msg_id'] @text = hash['_text'] outcomes = hash['outcomes'].first if outcomes @intent = outcomes['intent'] @confidence = outcomes['confidence'] @entities = {} outcomes['entities'].each do |name, entity| @entities[name] = entity.map do |e| OpenStruct.new(e) end end end end end end
true
cbf5e3b608778afc2bb9a1710c5267dcd3cd1727
Ruby
lcloyola/upis-ror
/app/models/section.rb
UTF-8
887
2.59375
3
[]
no_license
class Section < ActiveRecord::Base validates_inclusion_of :year, :in => -3..12, :message => "can only be from -2 and 12." validates_numericality_of :year, :only_integer => true, :message => "can only be whole number." validates_uniqueness_of :name, :scope => [:schoolyear_id] validates_presence_of :schoolyear_id, :faculty_id, :batch_id, :year, :name belongs_to :schoolyear belongs_to :faculty belongs_to :batch has_many :courses has_many :members, :foreign_key => :section_id, :dependent => :destroy has_many :students, :through => :members, :source => :student, :dependent => :destroy def fullname return "#{self.year} - #{self.name}" end def year_type return "Extra Curricular" if self.year == -3 return "Work Program" if self.year == -2 return "Elective" if self.year == -1 return "Kinder" if self.year == 0 return year end end
true
c993063bdcb6ffec6d13cd10a345eaabb7d72555
Ruby
IsaacYung/collection-patterns
/adapter/adapter.rb
UTF-8
1,257
4.3125
4
[]
no_license
# Let's think of a class that takes two open files (a reader and a writer) and encrypts a file. class Encrypter def initialize(key) @key = key end def encrypt(reader, writer) key_index = 0 while not reader.eof? clear_char = reader.getc encrypted_char = clear_char ^ @key[key_index] writer.putc(encrypted_char) key_index = (key_index + 1) % @key.size end end end """ But what happens if the data we want to secure happens to be in a string, rather than in a file? We need an object that looks like an open file, that is, supports the same interface as the Ruby IO object. We can create an StringIOAdapter to achieve so: """ class StringIOAdapter def initialize(string) @string = string @position = 0 end def getc if @position >= @string.length raise EOFError end ch = @string[@position] @position += 1 return ch end def eof? return @position >= @string.length end end # Now we can use a String as if it were an open file (it only implements a small part of the IO interface, essentally what we need). encrypter = Encrypter.new('XYZZY') reader= StringIOAdapter.new('We attack at dawn') writer=File.open('out.txt', 'w') encrypter.encrypt(reader, writer)
true
078dd1e84b943b3ae3982789bc9ecf0a14239c05
Ruby
easing/evotest
/app/operations/create_status.rb
UTF-8
1,140
2.6875
3
[]
no_license
# frozen_string_literal: true ## # Создаёт запись в журнале состояний class CreateStatus # Создаёт запись в журнале состояний, если новое состояние хоста отличается от текущего # # @param [String] hostname # @param [String] status_type # @param [String] message # @return [Status] def self.call(hostname, status_type:, message:) # Если в актуальном статусе домена те же параметры, возвращаем актуальный статус и ничего не создаём current_status = Status.find_by(hostname: hostname, current: true, status_type: status_type, message: message) if current_status current_status.touch return current_status end # Создаём новый актуальный статус домена Status.transaction do Status.where(hostname: hostname, current: true).update_all(current: false) Status.create!(hostname: hostname, current: true, status_type: status_type, message: message) end end end
true
fc67685f46f8be3eaceec1540505658991701c2a
Ruby
holmesm8/ruby-exercises
/objects-and-methods/exercise-1/lib/bag.rb
UTF-8
299
3.578125
4
[]
no_license
class Bag attr_reader :count, :candies def initialize @count = 0 @candies = [] end def add_candy(candy) @candies << candy @count += 1 end def empty? true if @candies.length == 0 end def contains?(type) @candies.find {|candy| candy.type == type} end end
true
dcb64584abb4a0277f6363ae8230eb92ebf9922a
Ruby
jetthoughts/redminetk
/CronManager.rb
UTF-8
10,490
3.21875
3
[]
no_license
require 'tk' require 'CronJobMgr' ############################################################################### # Class: CronManager # This class provides the GUI interface to the CronJobMgr class. It is the # view and controller objects of the MVC paradigm. ############################################################################### class CronManager ####################################################################### # addCronJob # Creates a new cron job and adds it to the cron job manager object. ####################################################################### def addCronJob # Make sure the user has selected a command before proceeding if @command.value.to_s().length <= 0 TkWarning.new("You must choose a command before " + "you can enter a new cron job.") return end # Create a new cron job and populate it job = CronJob.new(@minute.value, @hour.value, @day.value, @month.value, @weekday.value, @command.value) # Add the new job to the list @cronJobMgr.push(job) # Deselect any jobs previously selected in the listbox @cronListbox.selection_clear(0, @cronListbox.size - 1) # Add the new job to the list box @cronListbox.insert('end', job) # Select the newly added job in the listbox @cronListbox.selection_set(@cronListbox.size - 1) end ####################################################################### # updateCronJob # Updates the current cron job. ####################################################################### def updateCronJob # Get the index of the selected job index = @cronListbox.curselection()[0] # Use a rescue clause to make sure the user selected a job begin # Get the selected job from the cron job mananger job = @cronJobMgr[index] # Update the selected job with the chosen values job.minute = @minute.value job.hour = @hour.value job.day = @day.value job.month = @month.value job.weekday = @weekday.value job.command = @command.value # Update the cron job in the listbox @cronListbox.delete(index) @cronListbox.insert(index, job) @cronListbox.selection_set(index) rescue TkWarning.new("You must select a job from the list " + "before pressing Update") end end ####################################################################### # deleteCronJob # Deletes the current cron job from the manager object. ####################################################################### def deleteCronJob # Get the index of the selected job index = @cronListbox.curselection()[0] # Use a rescue clause to make sure the user selected a job begin # Delete the job from the listbox @cronListbox.delete(index) # Delete the job from the manager object @cronJobMgr.delete_at(index) # Set the listbox selection and detail view accordingly if @cronListbox.size <= 0 resetDetailView() elsif index < @cronListbox.size @cronListbox.selection_set(index) else @cronListbox.selection_set('end') end rescue TkWarning.new("You must select a job from the list " + "before pressing Delete") end end ####################################################################### # setDetailView # This method is called whenever an item from the cron jobs listbox # is selected. It sets the detail view to the attributes of the # selected cron job. ####################################################################### def setDetailView # Get the index of the selected job index = @cronListbox.curselection()[0] begin # Get the cron job object job = @cronJobMgr[index] # Set the detail view to the cron job's attributes @minute.value = job.minute @hour.value = job.hour @day.value = job.day @month.value = job.month @weekday.value = job.weekday @command.value = job.command rescue # This just makes sure the program doesn't crash end end ####################################################################### # resetDetailView # Sets the detail view to its default values ####################################################################### def resetDetailView @minute.value = "*" @hour.value = "*" @day.value = "*" @month.value = "*" @weekday.value = "*" @command.value = "" end ####################################################################### # browseCommands # Opens a dialog that allows the user to browse for, and choose, the # the command they wish to add to the cron jobs list. It then sets # the commands drop-down list with the chosen command. ####################################################################### def browseCommands # Create a browse dialog and get the chosen command @command.value = Tk.getOpenFile('title'=>'Choose Command', 'initialdir'=>'~', 'parent'=>@root) end ####################################################################### # saveCronJobs # Save all of the jobs in the cronJobMgr object to a text file and # add them to the cron schedule by calling crontab on the file. ####################################################################### def saveCronJobs begin # Save all of the jobs to a text file @cronJobMgr.saveCronJobs(@filename) rescue TkWarning.new("There was a problem saving the file " + "cronjobs. Make sure you have permission " + "to read and write files on this system " + "and that you can call the crontab command.") end # Display a message that lets the user know everything is ok Tk.messageBox('parent'=>@root, 'default'=>'ok', 'type'=>'ok', 'message'=>'The save was successful ' + 'and the cron schedule has been updated.', 'title'=>'Save Successful') end ####################################################################### # initialize # This method creates all of the GUI components for the cron mananger # and allocates actions to each of the components. ####################################################################### def initialize # This holds the cronjobs file name @filename = "cronjobs" # Create a new cron job manager object @cronJobMgr = CronJobMgr.new() # Try to open the cronjobs file and load the jobs begin @cronJobMgr.loadCronJobs(@filename) rescue TkWarning.new("There was a problem loading the jobs " + "from the cronjobs file. Make sure that " + "you have permission to read/write files.") end # Create Proc objects for each action the GUI supports addButtonClicked = proc {addCronJob} updateButtonClicked = proc {updateCronJob} deleteButtonClicked = proc {deleteCronJob} browseButtonClicked = proc {browseCommands} saveButtonClicked = proc {saveCronJobs} # Create a new root object @root = TkRoot.new() {title 'Cron Manager'} ### # Create all of the components in the CronMananger ### # Create frames to hold the list view and detail view listViewFrm = TkFrame.new(@root).pack( 'side'=>'left', 'padx'=>10, 'pady'=>10, 'fill'=>'both') detailViewFrm = TkFrame.new(@root).pack( 'side'=>'left', 'padx'=>10, 'pady'=>10) # Create a scrollbar for the cron job listbox scrollbar = TkScrollbar.new(listViewFrm).pack( 'side'=>'right', 'fill'=>'y') # Create the listbox to hold all of the cron jobs @cronListbox = TkListbox.new(listViewFrm) { width 25 }.pack( 'fill'=>'y', 'expand'=>'true') # Bind the setDetailView method to the item selected event @cronListbox.bind("<ListboxSelect>") {setDetailView()} # Link the listbox to scrollbar @cronListbox.yscrollbar(scrollbar); # Populate the cron job listbox @cronJobMgr.each { |job| @cronListbox.insert('end', job) } # Create all of the labels for the GUI labels = ['Minute', 'Hour', 'Day', 'Month', 'Weekday', 'Command'].collect { |label| TkLabel.new(detailViewFrm, 'text'=>label) } # Add each of the labels to the dialog labels.each_index { |i| labels[i].grid('column'=>0, 'row'=>i, 'sticky'=>'w') } # Create the minute drop down list minutes = ['*'] + (0..59).to_a @minute = TkVariable.new() minuteOptionMenu = TkOptionMenubutton.new( detailViewFrm, @minute, *minutes) { width 1 }.grid('column'=>1, 'row'=>0, 'sticky'=>'w', 'padx'=>5) # Create the hour drop down list hours = ['*'] + (0..23).to_a @hour = TkVariable.new() hourOptionMenu = TkOptionMenubutton.new( detailViewFrm, @hour, *hours) { width 1 }.grid('column'=>1, 'row'=>1, 'sticky'=>'w', 'padx'=>5) # Create the day drop down list days = ['*'] + (1..31).to_a @day = TkVariable.new() dayOptionMenu = TkOptionMenubutton.new( detailViewFrm, @day, *days) { width 1 }.grid('column'=>1, 'row'=>2, 'sticky'=>'w', 'padx'=>5) # Create the month drop down list months = ['*'] + (1..12).to_a @month = TkVariable.new() monthOptionMenu = TkOptionMenubutton.new( detailViewFrm, @month, *months) { width 1 }.grid('column'=>1, 'row'=>3, 'sticky'=>'w', 'padx'=>5) # Create the weekday drop down list weekdays = ['*'] + (1..7).to_a @weekday = TkVariable.new() weekdayOptionMenu = TkOptionMenubutton.new( detailViewFrm, @weekday, *weekdays) { width 1 }.grid('column'=>1, 'row'=>4, 'sticky'=>'w', 'padx'=>5) # Create the command textfield @command = TkVariable.new() @commandEntry = TkEntry.new(detailViewFrm) { width 30 relief 'sunken' }.grid('column'=>1, 'row'=>5, 'sticky'=>'w', 'padx'=>5) # Set the textvariable, textvariable gets/sets the entry's data @commandEntry.textvariable(@command) # Create the browse for command button browseButton = TkButton.new(detailViewFrm) { text '...' command browseButtonClicked }.grid('column'=>2, 'row'=>5, 'sticky'=>'w') # Create Add, Update, Delete, and Save Buttons buttonFrm = TkFrame.new(detailViewFrm) buttonFrm.grid( 'column'=>0, 'row'=>6, 'columnspan'=>3, 'sticky'=>'w') addButton = TkButton.new(buttonFrm) { text 'Add' width 7 command addButtonClicked }.pack('side'=>'left') updateButton = TkButton.new(buttonFrm) { text 'Update' width 7 command updateButtonClicked }.pack('side'=>'left', 'padx'=>5) deleteButton = TkButton.new(buttonFrm) { text 'Delete' width 7 command deleteButtonClicked }.pack('side'=>'left') saveButton = TkButton.new(buttonFrm) { text 'Save' width 7 command saveButtonClicked }.pack('side'=>'left', 'padx'=>5) end end cronManager = CronManager.new() Tk.mainloop()
true
70d3e45b2d2929dc1a4291ef605f5ddfbe76584e
Ruby
ssteeg-mdsol/openapi3-generator
/gems/gems/prawn-table-0.2.2/manual/table/content_and_subtables.rb
UTF-8
1,488
3
3
[ "GPL-3.0-only", "GPL-2.0-only", "Ruby", "Apache-2.0" ]
permissive
# encoding: utf-8 # # There are five kinds of objects which can be put in table cells: # 1. String: produces a text cell (the most common usage) # 2. <code>Prawn::Table::Cell</code> # 3. <code>Prawn::Table</code> # 4. Array # 5. Images # # Whenever a table or an array is provided as a cell, a subtable will be created # (a table within a cell). # # If you'd like to provide a cell or table directly, the best way is to # use the <code>make_cell</code> and <code>make_table</code> methods as they # don't call <code>draw</code> on the created object. # # To insert an image just provide a hash with an with an <code>:image</code> key # pointing to the image path. # require File.expand_path(File.join(File.dirname(__FILE__), %w[.. example_helper])) filename = File.basename(__FILE__).gsub('.rb', '.pdf') Prawn::ManualBuilder::Example.generate(filename) do cell_1 = make_cell(:content => "this row content comes directly ") cell_2 = make_cell(:content => "from cell objects") two_dimensional_array = [ ["..."], ["subtable from an array"], ["..."] ] my_table = make_table([ ["..."], ["subtable from another table"], ["..."] ]) image_path = "#{Prawn::DATADIR}/images/stef.jpg" table([ ["just a regular row", "", "", "blah blah blah"], [cell_1, cell_2, "", ""], ["", "", two_dimensional_array, ""], ["just another regular row", "", "", ""], [{:image => image_path}, "", my_table, ""]]) end
true
41b47d826232f02648389b3cdda9d473ef382d39
Ruby
DrDrakula/module-one-final-project-guidelines-web-121117
/lib/models/command_line_interface.rb
UTF-8
14,024
3.109375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' require 'colorize' arter = Artii::Base.new puts arter.asciify("welcome").colorize(:blue) def welcome puts "Welcome to our group project. We hope you enjoy!".colorize(:light_yellow) end def user_input print "Input Here: " input = gets.chomp input.to_s end ################################# MAIN MENU ################################# def main_menu(user) puts "\n---------Main Menu---------".colorize(:blue) puts "Current User: #{user.name}" puts "\n1".colorize(:light_red)+".'Show All Shows'".colorize(:light_blue)+" to display all shows" puts "2".colorize(:light_red)+".'Write a Review'".colorize(:light_blue)+" to write a review for a selected show" puts "3".colorize(:light_red)+".'List My Reviews'".colorize(:light_blue)+" to see all the reviews of all the shows that you've made" puts "4".colorize(:light_red)+".'Recommended'".colorize(:light_blue)+" to show 5 recommended shows based on your reviews" puts "5".colorize(:light_red)+".'Top Rated'".colorize(:light_blue)+" to view 10 of the top rated shows" puts "6".colorize(:light_red)+".'Play'".colorize(:light_blue)+" to play a game of dice" puts "\n7".colorize(:light_red)+".'Log Out'".colorize(:light_blue) puts "8".colorize(:light_red)+".'Exit'".colorize(:light_blue) inp = user_input.downcase case inp when "1" puts "\nAll Shows:" TvShow.list_all_tv_shows tv_show_menu(user) when "show all shows" puts "\nAll Shows:" TvShow.list_all_tv_shows tv_show_menu(user) when "2" puts "\nAll Shows:" TvShow.list_all_tv_shows add_review(user) when "write a review" puts "\nAll Shows:" TvShow.list_all_tv_shows add_review(user) when "3" then review_menu(user) when "list my reviews" then review_menu(user) when "4" then recommended_shows(user) when "recommended" then recommended_shows(user) when "5" then top_rated(user) when "top rated" then top_rated(user) when "6" then welcome_to_dice_game(user) when 'play' then welcome_to_dice_game(user) when "log out" then login_menu when "7" then login_menu when "exit" then puts "Goodbye!" when "8" then puts "Goodbye!" else puts "Unknown option! Please try again." main_menu(user) end end ################################### TV SHOW MENU ############################## def tv_show_menu(user) puts "\n'back'".colorize(:light_blue)+" to go back to the main menu" puts "\nEnter a show's number to get it's information,\n"+"'list'".colorize(:light_blue)+" to list all shows, or "+"'back'".colorize(:light_blue)+" to go back to the menu" inp = user_input.downcase if inp == 'back' main_menu(user) elsif inp == 'list' TvShow.list_all_tv_shows tv_show_menu(user) else inp = inp.to_i if inp <= 0 || inp > TvShow.all_tv_shows.size puts "Invalid index! Choose again..." tv_show_menu(user) else show = TvShow.all_tv_shows[inp - 1] if TvShow.all_tv_shows.include?(show) puts "\nShow name: #{show.name}" puts "\n'rating'".colorize(:light_blue)+", "+"'genre'".colorize(:light_blue)+", "+"'status'".colorize(:light_blue)+", "+"'reviews'".colorize(:light_blue)+", or "+"'back'".colorize(:light_blue) inp2 = user_input.downcase if inp2 == 'rating' if show.rating puts " " puts show.rating puts "\nGet another show?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" puts " " inp3 = user_input.downcase inp3 == 'y' ? tv_show_menu(user) : main_menu(user) else puts " " puts "The show hasn't been rated yet." tv_show_menu(user) end elsif inp2 == 'back' main_menu(user) elsif inp2 == "genre" puts " " puts show.genre puts "\nGet another show?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" puts " " inp3 = user_input.downcase inp3 == 'y' ? tv_show_menu(user) : main_menu(user) elsif inp2 == 'status' puts " " puts show.status puts "\nGet another show?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" puts " " inp3 = user_input.downcase inp3 == 'y' ? tv_show_menu(user) : main_menu(user) elsif inp2 == 'reviews' count = 0 if show.reviews.empty? puts " " puts "The show has no reviews." puts "\nGet another show?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" puts " " inp3 = user_input.downcase inp3 == 'y' ? tv_show_menu(user) : main_menu(user) else puts " " show.reviews.each.with_index(1) {|rev, ind| puts "#{ind}.'#{rev.review}' by #{rev.user.name}"} puts "\nGet another show?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" puts " " inp3 = user_input.downcase inp3 == 'y' ? tv_show_menu(user) : main_menu(user) end else puts "Unknown option! Try again..." tv_show_menu(user) end elsif inp == 'back' main_menu(user) else puts " " puts "Can't find show" tv_show_menu(user) end end end end ################################### RECOMMENDED MENU ############################## def recommended_shows(user) genres = user.reviews.map {|review_instance| review_instance.tv_show.genre} if !genres.empty? sorted_genres = genres.sort_by {|genre| genres.count(genre)}.reverse most_rated_genre = sorted_genres[0] recommended_array = TvShow.all.select{|show| show.genre == most_rated_genre}.sample(5) recommended_by_rating = recommended_array.sort_by{|show| show.rating}.reverse recommended_array_names = recommended_by_rating.map {|show| "#{show.name}: #{show.rating}"} puts " " list_all(recommended_array_names) puts "\nGet 5 more recommendations?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" inp = user_input.downcase inp == 'y' ? recommended_shows(user) : main_menu(user) else puts "\nThere are no recommendations for you! Do you want to pick a genre?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" inp = user_input.downcase if inp == 'y' puts "Existing genres: #{TvShow.all_genres_array.join(", ")}" inp2 = user_input.downcase most_rated_genre = inp2.capitalize if TvShow.all_genres_array.include?(most_rated_genre) recommended_array = TvShow.all.select{|show| show.genre == most_rated_genre}.sample(5) recommended_by_rating = recommended_array.sort_by{|show| show.rating}.reverse recommended_array_names = recommended_by_rating.map {|show| "#{show.name}: #{show.rating}"} puts " " list_all(recommended_array_names) main_menu(user) else puts "Couldn't find the selected genre!" main_menu(user) end else main_menu(user) end end end ################################ 'ADD REVIEWS' MENU ############################### def add_review(user) puts "\nType "+"'back'".colorize(:light_blue)+" to go back to main menu" puts"\nEnter a number of the show you want to leave a review for:" inp = user_input.downcase if inp == 'back' main_menu(user) else inp = inp.to_i if inp <= 0 || inp > TvShow.all_tv_shows.size puts "Invalid index! Choose again..." add_review(user) else show = TvShow.all_tv_shows[inp - 1] puts "Insert a review for the show #{show.name}, or "+"'back'".colorize(:light_blue)+" to go back to the main menu" inp2 = user_input if inp2.downcase == "back" main_menu(user) else rev = Review.create(review: "#{inp2}") show.reviews << rev user.reviews << rev puts "\nReview has been added!" main_menu(user) end end end end ################################ TOP RATED SHOWS ############################# def top_rated(user) puts " " sorted_array = TvShow.order(rating: :desc).limit(10) final_array = sorted_array.map {|show| "#{show.name}: #{show.rating}"} list_all(final_array) puts "\nPress "+"'back'".colorize(:light_blue)+" to go back to the main menu" inp = gets.chomp main_menu(user) end ################################ 'REVIES MENU' ############################# def review_menu(user) puts "\nALL REVIEWS BY #{user.name}:" puts " " all_reviews(user) puts "\nType "+"'back'".colorize(:light_blue)+" to go back to the main menu" puts " " inp = user_input.downcase inp == "back" ? main_menu(user) : review_menu(user) end ################################ ARRAYS ############################# def list_all(array) array.each_with_index {|element, ind| puts "#{ind + 1}.".colorize(:light_red)+"#{element}".colorize(:light_blue)} end def all_reviews(user) if user.reviews.empty? puts "You haven't rated anything yet" else user.reviews.each { |review_instance| puts "'#{review_instance.review}': #{review_instance.tv_show.name}" } end end ################################ 'LOGIN MENU' ############################### def login_menu puts "\nType your user name to log-in,\n"+"'list'".colorize(:light_blue)+" to list all users, or "+"'exit'".colorize(:light_blue)+" to quit:" puts " " inp = user_input if User.user_names.include?(inp) user = User.find_by(name: inp) main_menu(user) elsif inp.downcase == 'list' puts "\nAll Users:" puts " " User.user_names.each do |user_name| print "- " puts "#{user_name}".colorize(:light_blue) end puts " " login_menu elsif inp.downcase == "exit" puts "Goodbye!" else if inp.split(" ").empty? puts "Invalid user name!" login_menu elsif inp.match(/\d/) puts "\nThe username can't contain numbers!" puts " " login_menu else inp.strip! inp = inp.split(" ").join(" ") puts "The user doesn't exists! Do you want to create a user with this username? (#{inp})(y/n)" inp2 = user_input if inp2 == 'y' user = User.create(name: inp) main_menu(user) else login_menu end end end end ################################ 'DICE GAME' ############################### def welcome_to_dice_game(user) puts " " arter = Artii::Base.new puts arter.asciify("welcome to dice").colorize(:yellow) game(user) end def game(user) puts "\n------------Game Menu------------".colorize(:blue) puts "\nDo you want to play vs "+"'computer'".colorize(:light_blue)+" or vs "+"'friend'".colorize(:light_blue)+"" puts "or do you want to go "+"'back'".colorize(:light_blue)+" to the game menu" puts " " inp = user_input.downcase case inp when 'computer' puts "#{user.name}, press"+" 'return'".colorize(:blue)+" to roll your dice" u_input = gets.chomp puts " " player1 = rand(6) + 1 puts "#{user.name}, you rolled a #{player1}.".colorize(:light_blue) com = rand(6) + 1 puts "The computer rolled a #{com}.".colorize(:light_yellow) if player1 > com puts "\nCongratulations #{user.name}! You won!".colorize(:yellow) puts " " puts " ƪ(˘⌣˘)ʃ ".colorize(:yellow)+"ƪ(˘⌣˘)┐".colorize(:yellow)+"┌(˘⌣˘)ʃ".colorize(:yellow) game(user) elsif player1 == com puts " " puts "It's a DRAW! Miserable...(╯°□°)╯︵ ┻━┻".colorize(:yellow) game(user) else puts " " puts "BOOOO #{user.name}! You lost... miserably...".colorize(:yellow) puts " " puts" "+"▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄".colorize(:yellow) puts" "+"████▌▄▌▄▐▐▌█████".colorize(:yellow) puts" "+"████▌▄▌▄▐▐▌▀████".colorize(:yellow) puts" "+"▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀".colorize(:yellow) game(user) end when 'friend' print "\nInsert the name of your friend: " puts " " friend = gets.chomp.to_s if friend.split(" ").empty? friend = "Unknown" dice(user, friend) elsif friend.match(/ /) friend.strip! friend = friend.split(" ").join(" ") dice(user, friend) elsif friend[0] == " " || friend[-1] == " " friend.strip! friend = friend.split(" ").join(" ") dice(user, friend) else dice(user, friend) end when 'back' then main_menu(user) else puts "Unknown option!" game(user) end end def dice(user, friend) puts "#{friend}, press"+" 'return'".colorize(:blue)+" to roll your dice" u_input = gets.chomp puts " " friend_roll = rand(6) + 1 puts "#{friend}, you rolled a #{friend_roll}.".colorize(:yellow) puts " " puts "#{user.name}, press"+" 'return'".colorize(:blue)+" to roll your dice" u_input = gets.chomp puts " " if user.name == "Nemanja" player1 = friend_roll + 1 else player1 = rand(6) + 1 end puts "#{user.name}, you rolled a #{player1}.".colorize(:blue) puts " " if friend_roll > player1 puts "\nCongratulations #{friend}! You ROCK!".colorize(:yellow) puts " " puts " ┗( ^o^)┛ ≡ ┏( ^o^)┓ ≡ ┗( ^o^)┛ ".colorize(:yellow) puts " " puts "\nRematch!?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" inp = user_input.downcase inp == 'y' ? dice(user, friend) : game(user) elsif friend_roll == player1 puts " " puts "It's a DRAW! You both suck..." puts "ヽ(#゚Д゚)ノ┌┛Σ(ノ´Д`)ノ".colorize(:yellow) puts " " puts "\nRematch!?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" inp = user_input.downcase inp == 'y' ? dice(user, friend) : game(user) else puts " " puts "\nGood job #{user.name}. Don't worry #{friend} you'll get him next time!".colorize(:yellow) puts " " puts "\nRematch!?("+"y".colorize(:green)+"/"+"n".colorize(:red)+")" inp = user_input.downcase inp == 'y' ? dice(user, friend) : game(user) end end
true
083682f919fd6958182316aff108f2b7e7338168
Ruby
antloewe/sudokusolver
/Block.rb
UTF-8
2,168
3.640625
4
[]
no_license
#encoding: UTF-8 # Klasse zum Darstellen von 3×3-Blöcken class Block # Erstellt einen Block. Nicht vorhandene Argumente werden mit Nullen (d. h. nicht gesetzt) aufgefüllt def initialize *args length = 3 abort "Zu viele Argumente!" if args.length > length ** 2 # Initialisiert Reihen-, Spalten- und Elemente-Array @rows = init_2dim_array length @cols = init_2dim_array length @elements = Array.new length ** 2 # Fügt Elemente in Reihen-, Spalten- und Elemente-Array ein. # Elemente in Reihen-, Spalten und Elemente-Array zeigen auf dasselbe Objekt, damit # Veränderungen in dem einen Array sich auch auf die anderen auswirken. (0...args.length).each do |i| arg = args[i].to_s @elements[i] = arg @rows[i / length][i % length] = arg @cols[i % length][i / length] = arg end (args.length...length ** 2).each do |i| value = '0' @elements[i] = value @rows[i / length][i % length] = value @cols[i % length][i / length] = value end end # Erstellt ein zweidimensionales quadratisches Array von Länge length def init_2dim_array length block = Array.new length block.each_index do |i| block[i] = Array.new length end return block end # Gibt ein Element aus def get_elem reihe, spalte return @rows[reihe][spalte] end # Gibt ein Element aus def elem reihe, spalte get_elem reihe, spalte end # Fügt ein Element ein def put_elem reihe, spalte, neuer_wert @rows[reihe][spalte].replace neuer_wert.to_s end # Gibt eine Reihe aus def row row return @rows[row] end # Gibt eine Spalte aus def col col return @cols[col] end # Prüft, ob eine Zahl vorkommt def include? number return @elements.include? number.to_s end # Gibt Anzahl der freien Zellen aus def count_free_cells return @elements.grep('0').size end # Gibt Anzahl der belegten Zellen aus def size return @elements.select { |v| v != "0" }.size end # Testfunktion def get_object_id length = 3 (0...length ** 2).each do |i| puts @rows[i / length][i % length].object_id puts @cols[i % length][i / length].object_id puts @elements[i].object_id end end private :init_2dim_array end
true
891754c08181825e0307cf865b4831c0d12b9e32
Ruby
mkrahu/launchschool
/exercises/small_problems/vers1/medium_1/1000_lights.rb
UTF-8
491
3.71875
4
[]
no_license
# 1000_lights.rb # 100 Lights exercise # Small Problems exercises from LaunchSchool def toggle_light(lights, n) lights[n] = !lights[n] end def n_lights(num) lights = [] num.times { lights << false } 1.upto(num) do |i| 0.upto(num - 1) do |n| toggle_light(lights, n) if ((n + 1) % i).zero? end end lights_to_num = lights.map.with_index { |light, index| index + 1 if light } lights_to_num.select { |light| light } end p n_lights(5) p n_lights(10) p n_lights(1000)
true
dd47b118de1ae4e36fa4f7c11f9620985c40ca1e
Ruby
waltersharpWEI/ruby_stock
/main.rb
UTF-8
265
2.5625
3
[ "MIT" ]
permissive
#!/usr/bin/ruby require_relative 'utils/dao_stock.rb' stock1 = Stock.new('data/stock.json',0) while true for i in 1..100000000 stock1.buyGood('Apple', 15) stock1.buyGood('Orange', 8) stock1.sellGood('Apple', 6) stock1.saveStock() end end
true
a8cb0517a7490ac9c0af23fad054bfbe9354cfd7
Ruby
Maheshkumar-novice/Mastermind
/archives/computer-player-knuth.rb
UTF-8
734
2.984375
3
[]
no_license
#!/usr/bin/env ruby # frozen_string_literal: true require_relative './player' require_relative './knuth' require_relative './modules/display' module Mastermind # Human Player Class class ComputerPlayer < Player include Display attr_accessor :current_guess, :guess def initialize super('Computer') end def make_code puts computer_code "#{rand(1..6)}#{rand(1..6)}#{rand(1..6)}#{rand(1..6)}" end def make_guess(feedback) init_guess if feedback.nil? print computer_guess self.current_guess = guess.create_guess(feedback, current_guess) puts current_guess current_guess end private def init_guess @guess = Knuth.new end end end
true
09eaaa528ab1dec9fec5140e29eae389b5df3a71
Ruby
bingxie/code-questions
/lib/leetcode/695_max-area-of-island.rb
UTF-8
1,011
3.40625
3
[ "MIT" ]
permissive
# number of islands的变种 # @param {Integer[][]} grid # @return {Integer} def max_area_of_island(grid) sizes = num_islands(grid) sizes.empty? ? 0 : sizes.max end def num_islands(grid) return [] if grid.empty? sizes = [] 0.upto(grid.size - 1) do |i| # (grid.size -1).times 0.upto(grid.first.size - 1) do |j| if grid[i][j] == 1 sizes.push bfs(i, j, grid) end end end sizes end def bfs(i, j, grid) size = 1 directions = [[-1, 0], [0, -1], [1, 0], [0, 1]] queue = Queue.new queue.push([i, j]) # 也可以用两个queue,比如: row_queue, col_queue until queue.empty? row, col = queue.pop grid[row][col] = 0 directions.each do |dr| new_r = row + dr[0] new_c = col + dr[1] if new_r >= 0 && new_c >= 0 && new_r < grid.size && new_c < grid.first.size && grid[new_r][new_c] == 1 queue.push([new_r, new_c]) grid[new_r][new_c] = '0' # mark as visited size += 1 end end end size end
true
9573e8fa7dddeccea8e045934cad5feb770efd3d
Ruby
jasondi/lita-ignore-me
/lib/lita/handlers/ignore_me.rb
UTF-8
2,396
2.578125
3
[ "MIT" ]
permissive
module Lita module Handlers class IgnoreMe < Handler include IgnoreRegistry route(/^ignore me$/i, :ignore_me, command: true, help: { "ignore me" => t('ignore_help') }) route(/^ignore me in (.+)$/i, :ignore_me_in_room, command: true, help: { "ignore me in #room" => t('ignore_help_with_room') }) route(/^listen to me$/i, :listen_to_me, command: true, help: { "listen to me" => t('listen_help') }) route(/^listen to me in (.+)$/i, :listen_to_me_in_room, command: true, help: { "listen to me in #room" => t('listen_help_with_room') }) def find_room(response) Lita::Room.fuzzy_find(response.matches[0][0]) end def ignore_me(response) ignore_source(response, response.message.source) end def ignore_me_in_room(response) room = find_room(response) user = response.message.source.user if room.nil? response.reply t('sorry_no_room', name: user.name) else source = Lita::Source.new(user: user, room: room) ignore_source(response, source) end end def ignore_source(response, source) name = source.user.name room = source.room_object.name if ignored? source response.reply t('already_ignored', name: name, room: room) else ignore source response.reply t('ignored', name: name, room: room) end end def listen_to_me(response) listen_to_source(response, response.message.source) end def listen_to_me_in_room(response) room = find_room(response) user = response.message.source.user if room.nil? response.reply t('sorry_no_room', name: user.name) else source = Lita::Source.new(user: user, room: room) listen_to_source(response, source) end end def listen_to_source(response, source) name = source.user.name room = source.room_object.name if ignored? source heed source response.reply t('listening', name: name, room: room) else response.reply t('already_listening', name: name, room: room) end end private :find_room, :ignore_source, :listen_to_source end Lita.register_handler(IgnoreMe) end end
true
2ee7c73f13e780f9035619c9f414b5049284fb29
Ruby
jamesfwz/evaluation-tests
/rails-test-6/app/models/mother.rb
UTF-8
109
2.859375
3
[]
no_license
class Mother < Parent include Person::Female def say_something 'Hello, I am your mother.' end end
true
f2417e391f2240f340d1de5a451cb9263a5b44fd
Ruby
ochko/prudge
/db/migrate/20130623065520_create_participants.rb
UTF-8
1,208
2.546875
3
[ "MIT" ]
permissive
class CreateParticipants < ActiveRecord::Migration def up create_table :participants do |t| t.integer :contest_id , :null => false t.integer :user_id , :null => false t.integer :rank t.float :points , :default => 0.0 end connection.select_values("SELECT id FROM contests").each do |contest_id| rank, point, time = 0, 0.0, 0.0 connection.select_rows("SELECT user_id, sum(point) AS point, sum(solved_in) AS time FROM solutions WHERE contest_id = #{contest_id} GROUP BY user_id ORDER BY point DESC, time ASC").each do |row| user_id, user_point, user_time = row[0], row[1].to_f, row[2].to_f if (point != user_point) || (user_time - time > 0.1) point = user_point rank += 1 end values = [contest_id, user_id, rank, user_point].map{|v| connection.quote v}.join(', ') connection.execute("INSERT INTO participants(contest_id, user_id, rank, points) VALUES(#{values})") end end add_index :participants, :contest_id add_index :participants, :user_id add_index :participants, [:contest_id, :user_id], :unique => true end def down drop_table :participants end end
true
d1aa39d2568de5a73a5192a1d221057679af5237
Ruby
Argonus/codility_others
/coderbyte/easy/first_reverse.rb
UTF-8
94
3.109375
3
[]
no_license
def FirstReverse(str) str.reverse! return str end puts FirstReverse("abcde")
true
db2168aea2309681c44201ddac38af02f4a5e851
Ruby
capveg/sidecar
/ip2ttls2db/calc-ipdistance.rb
UTF-8
6,313
2.890625
3
[]
no_license
#!/usr/bin/ruby # usage: calc-ipdistance.rb foo.adj table # 1) takes an adj file and DB table name # 2) foreach link in foo.adj # look up the ips of endpoints, calc their distance # and print UsageString='usage: calc-ipdistance.rb table [-adj foo.adj| -pairs thresholddistance | -rand k_times | -randThresh k max_thresh]' $sidecarDir=ENV['SIDCARDIR'] ? ENV['SIDECARDIR'] : "#{ENV['HOME']}/swork/sidecar" $libDir="#{$sidecarDir}/ip2ttls2db" $: << "#{$sidecarDir}/random_prober" $: << $libDir require 'ips2ttldistance2db.rb' # includes require dbi code require 'progressbar.rb' class File def each_progress(str,outfile=$stderr) # "12345 file\n" --> 12345 nLines=Kernel.open("|wc -l #{self.path}").gets.split[0].chomp.to_i #$stderr.puts "Got #{nLines} for #{self.path}" pb = ProgressBar.new(str,nLines,outfile) pb.set(0) self.each { |line| yield line pb.inc } end end class IpDistance attr_accessor :minThreshold def initialize(tablename) @ip2db=Ips2TTLdistance2db.new @tablename=tablename @dbh = DBI.connect("DBI:Pg:dbname=#{@ip2db.databasename};host=#{@ip2db.databasehost}", @ip2db.databaseuser, @ip2db.databasepasswd) @minThreshold=-255 # by default, list everything end def allIps if(!@allIps) $stderr.puts "Making list of all Ips in #{@tablename}" @allIps= @dbh.select_all("SELECT distinct ip from #{@tablename}") $stderr.puts "#{@allIps.length} Ips found in #{@tablename}" end @allIps end def processAdj(file,minThreshold=@minThreshold) File.open(file).each_progress("Adj"){ |line| # Link R10_A:206.196.177.126 -- R14_B:206.196.177.125 : RR if(line =~ /^Link\s+[^:]+:([\d.]+)\s+--\s+[^:]+:([\d.]+)/) # skip everything that doesn't begin with "Link" ip1=$1 ip2=$2 if( ip1 == ip2 ) $stderr.puts "Skipping bogus selflink #{ip1} -- #{ip2}" else d,n = calcIpDistance(ip1,ip2) if( n>=minThreshold) if block_given? yield ip1,ip2,d,n else puts "#{d} #{ip1} #{ip2} #{n}" end end end end } end def pickRandPairs(k,minThreshold=@minThreshold) $stderr.puts "#{Time.now}" k.times { |i| $stderr.puts "#{Time.now}" ip1=allIps[Kernel.rand(allIps.length)] ip2=allIps[Kernel.rand(allIps.length)-1] # this insures ip1!=ip2 ip2=allIps[allIps.length-1] if ip1 == ip2 # while staying totally random d,n = calcIpDistance(ip1,ip2) if(n>=minThreshold) if block_given? yield ip1,ip2,d,n else puts "#{d} #{ip1} #{ip2} #{n}" end end } $stderr.puts "#{Time.now}" end def getAllPairs(maxDistance=-1.0,outfile=$stderr) $stderr.puts "AllPairs maxDistance=#{maxDistance}" pb = ProgressBar.new("AllPairs",allIps.length*allIps.length,outfile) pb.set(0) allIps.each{ |ip1| cord1 = getIpCord(ip1) allIps.each{ |ip2| if( ip1.to_s < ip2.to_s) then d,n = calcIpDistance(ip1,ip2,cord1) # pass on/cache the value of the first cord if((d>=0)&&(d<=maxDistance)) then if block_given? then yield ip1,ip2,d,n else puts "#{ip1} #{ip2} #{d} #{n}" end end end pb.inc } } end def calcIpDistance(ip1,ip2,cord1=nil,cord2=nil) cord1 = getIpCord(ip1) unless cord1 # let the caller specify the cords if known cord2 = getIpCord(ip2) unless cord2 # let the caller specify the cords if known #$stderr.puts "#{ip1}=#{cord1}" #$stderr.puts "#{ip2}=#{cord2}" count=0.0 sum=0.0 cord1.each { |key,value| if cord2[key] count+=1 sum+= (cord2[key]-cord1[key]).abs end } return [((count>0) ?(sum/count):-1.0),count] end def getIpCord(ip) cord = Hash.new # get the list of the most recent,valid responses from all vantages for this ip @dbh.select_all("SELECT vantage,ip,udp,udpr,tcp,tcpr,icmp,icmpr from #{@tablename} where " + " ip='#{ip}' and ts in " + " (select max(ts) from #{@tablename} where ip='#{ip}' and " + " ( (udp>=0 and udpr='-') or " + " (tcp>=0 and tcpr='-') or " + " (icmp>=0 and icmpr='-') )" + " group by vantage,ip)" ) { |r| row=r.to_h #$stderr.puts "Read row #{row['vantage']}::#{row['ip']}" udp=row['udp'] tcp=row['tcp'] icmp=row['icmp'] udpr=row['udpr'] tcpr=row['tcpr'] icmpr=row['icmpr'] d=-1 # prefer udp cords over icmp cords over tcp cords, but take what is available d = tcp.to_i if (tcp and tcpr == "-" and tcp.to_i>0) d = icmp.to_i if (icmp and icmpr == "-" and icmp.to_i>0) d = udp.to_i if (udp and udpr == "-" and udp.to_i>0) # map ttl's into [0:64] to avoid bad comparisons between startttl=255 and startttl=64 routers d-=192 if d>192 # if start ttl=255, map down to [0:64] d-=64 if d>64 # if start ttl=128, map down to [0:64] cord[row['vantage']]=d } return cord end def pickRandPairsManyThresholds(k,maxThresh) filenameBase= "#{@tablename}.rand#{k}.thresh=" maxThresh.downto(0){ |t| $stderr.puts "picking #{k} pairs with thresh #{t}" File.open(filenameBase+t.to_s,"w+") { |f| pickRandPairs(k,t) { |ip1,ip2,d,n| f.puts "#{d} #{ip1} #{ip2} #{n}" } } } end end # end of class IpDistance if __FILE__ == $0 raise UsageString + " : needs to specify DB table name" unless ARGV[0] raise UsageString + " : needs to specify invocation type (-adj,-rand,etc)" unless ARGV[1] ipd = IpDistance.new(ARGV[0]) case ARGV[1] when '-adj' raise UsageString + " : need to specify adj file" unless ARGV[2] ipd.processAdj(ARGV[2]) when '-ip' raise UsageString + " : need to specify first ip" unless ARGV[2] raise UsageString + " : need to specify second ip" unless ARGV[3] d,n= ipd.calcIpDistance(ARGV[2],ARGV[3]) puts "#{ARGV[2]} #{ARGV[3]} :: #{d} from #{n} common vantages" when '-rand' raise UsageString + " : need to specify number of random pairs" unless ARGV[2] ipd.pickRandPairs(ARGV[2].to_i) when '-pairs' raise UsageString + " : need to specify threshold distance between pairs" unless ARGV[2] ipd.getAllPairs(ARGV[2].to_f) when '-randThresh' raise UsageString + " : need to specify number of random pairs" unless ARGV[2] raise UsageString + " : need to specify max threshold" unless ARGV[3] ipd.pickRandPairsManyThresholds(ARGV[2].to_i,ARGV[3].to_i) else raise UsageString + " : unknown invocation type (#{ARGV[1]})" end end
true
c4cb68dca0dad271a6bd3eda2c500898e1d25cd5
Ruby
kcartlidge/ruthless
/ruthless.rb
UTF-8
15,097
2.84375
3
[ "MIT" ]
permissive
#!/usr/bin/ruby # puts 'Ensuring dependencies (slower first time).' require 'fileutils' require 'find' require 'set' require 'bundler/inline' gemfile do source 'https://rubygems.org' gem 'inifile' gem 'kramdown' gem 'liquid' gem 'webrick' end # Get the command arguments. @new_site = (ARGV[0] && (ARGV[0] == 'new')) @build_site = (ARGV[0] && (ARGV[0] == 'build' or ARGV[0] == 'serve')) @serve_site = (ARGV[0] && (ARGV[0] == 'serve')) @folder = ARGV[1] unless ARGV.length < 2 # Define folder/file locations. if @folder @site_folder = File.join(File.dirname(__FILE__), @folder, 'site') @html_folder = File.join(File.dirname(__FILE__), @folder, 'www') @content_folder = File.join(@site_folder, 'content') @layouts_folder = File.join(@site_folder, 'theme') @includes_folder = File.join(@layouts_folder, 'includes') @sample_news_folder = File.join(@content_folder, 'news') @ini_file = File.join(@site_folder, 'ruthless.ini') @layout_file = File.join(@layouts_folder, 'layout.liquid') @theme_file = File.join(@layouts_folder, 'theme.css') end # Define some vars. @version = '2.2.0' @templatable = ['.md', '.txt'].to_set @menu = [] # ------------------------------------------------------------- # Define functions - code is below # ------------------------------------------------------------- # Display the error message then abort. def fatal(message) puts '-------------------------------------------' puts "ERROR: #{message}" abort end # Display the message then exit. def done(message) puts message exit end # Show some introductory/explanatory text. def show_intro puts puts "RUTHLESS #{@version} https://ruthless.io" puts 'Ruthlessly simple static site generator' puts puts 'ruby ruthless.rb <command>' puts ' new <folder> Create a new site' puts ' build <folder> Generate site output' puts ' serve <folder> Build and serve a site' puts puts 'The <folder> should have a "site" subfolder.' puts 'Builds are written to a sibling "www" folder.' puts 'If in doubt, run with "new" to see an example.' puts end # Create a new file and write the content. Human name is used for errors. def new_file(human_name, filename, content) @required_folder = File.dirname(filename) FileUtils.mkdir_p @required_folder fatal("Unable to create folder for file #{filename}") unless Dir.exist?(@required_folder) File.open(filename, 'w') do |s| s.puts content end fatal("Failed to create #{human_name} #{filename}") unless File.exist?(filename) end # Aborts if the file is not found. Human name is used for errors. def file_must_exist(filename, human_name) fatal("Cannot find #{human_name} #{filename}") unless File.exist?(filename) end # Aborts if a given ini file is missing a section/key. def key_must_exist(ini, section, key) fatal("Missing ini value #{section}, #{key}") unless ini[section][key] end # Load in the given file as an array of strings for yaml metadata and content. def get_metadata_and_content(filename) metadata = Hash.new content = '' in_meta = false lc = 0 f = File.open(filename, 'r') f.each_line do |line| lc += 1 if lc == 1 && line.start_with?('---') in_meta = true elsif lc > 1 && in_meta && line.start_with?('---') in_meta = false else if in_meta bits = line.rstrip.split(': ') # extra space means trim each bit fatal("Expected key=value, got #{line}") unless bits.length == 2 fatal("Key is empty in #{line}") unless bits[0].length > 0 fatal("Value is empty in #{line}") unless bits[1].length > 0 metadata[bits[0]] = bits[1] else content += (line.rstrip + "\n") end end end { metadata: metadata, content: content } end def do_create puts '-------------------------------------------' puts 'Creating new site and content folders' fatal('Site folder already exists') if Dir.exist?(@site_folder) FileUtils.mkdir_p @content_folder fatal('Unable to create folders') unless Dir.exist?(@content_folder) new_file('ruthless.ini', @ini_file, "[SITE] title = Sample Ruthless Site blurb = Welcome to my Ruthless-generated site footer = Created by <a href='https://github.com/kcartlidge/ruthless' target='_blank'>Ruthless.io</a> and <a href='https://www.ruby-lang.org' target='_blank'>Ruby</a>. keywords = ruthless,static,site,generator [OPTIONS] extentions = false [SETTINGS] google-analytics = # AB-123456789-0 disqus-comments = # account-name [MENU] Home = / Latest News = /news About = /about") new_file('home page', File.join(@content_folder, 'index.md'), "---\ntitle: Welcome to Ruthless\n---\n\nFor more information, see [the GitHub repository](https://github.com/kcartlidge/ruthless).\n\n* [Latest News](/news)\n* [About Ruthless](/about)") new_file('about page', File.join(@content_folder, 'about.md'), "---\ntitle: About Ruthless\n---\n\nLorem ipsum dolor sit amet adipiscing.") new_file('sample news page', File.join(@sample_news_folder, 'index.md'), "---\ntitle: Latest News\n---\n\nLorem ipsum dolor sit amet adipiscing.\n\n* [Sample News Item 1](sample-news-item-1)\n* [Sample News Item 2](sample-news-item-2)") new_file('sample news item 1 page', File.join(@sample_news_folder, 'sample-news-item-1.md'), "---\ntitle: Sample News Item #1\ndated: August 27, 2018\nauthor: Ruthless.io\nkeywords: news\n---\n\nLorem ipsum dolor sit amet adipiscing.\n\n* [Back to the Latest News](/news)") new_file('sample news item 2 page', File.join(@sample_news_folder, 'sample-news-item-2.md'), "---\ntitle: Sample News Item #2\ndated: January 23, 2019\nauthor: Ruthless.io\nkeywords: news\n---\n\nLorem ipsum dolor sit amet adipiscing.\n\n* [Back to the Latest News](/news)") new_file('template', @layout_file, "<!DOCTYPE html> <html lang='en'> <head> <meta charset='utf-8'> <meta http-equiv='X-UA-Compatible' content='IE=edge'> <meta name='viewport' content='width=device-width, initial-scale=1'> <meta name=generator content='Ruthless (Ruby)'> <meta name='keywords' content='{{ sitekeywords }},{{ keywords }}'> <meta name='description' content='{{ sitetitle }}'> <meta name='robots' content='follow,index,noarchive,noodp'> <meta name='google' content='nositelinkssearchbox'> <meta name='author' content='{{ author }}'> <link href='/theme.css' rel='stylesheet' type='text/css' /> <title>{{ title}} -- {{ sitetitle }}</title> </head> <body> <header> <h1>{{ sitetitle }}</h1> <aside>{{ siteblurb }}</aside> <nav> {% for option in sitemenu %}{{ option }}{% endfor %} </nav> </header> <section> <h1>{{ title}}</h1> <article> {% include 'page' %} {% if settings.disqus-comments %} <div id='disqus_thread'></div> {% endif %} </article> </section> <footer> {{ sitefooter }} </footer> <script> var ls = document.links; for (var i = 0, ln = ls.length; i < ln; i++) if (ls[i].hostname != window.location.hostname) ls[i].target = '_blank'; </script> {% if settings.google-analytics %} <!-- Global Site Tag (gtag.js) - Google Analytics --> <script async src='https://www.googletagmanager.com/gtag/js?id={{ settings.google-analytics }}'></script> <script> window.dataLayer = window.dataLayer || []; function gtag() { dataLayer.push(arguments) }; gtag('js', new Date()); gtag('config', '{{ settings.google-analytics }}'); </script> {% endif %} {% if settings.disqus-comments %} <script> var disqus_config = function () { // this.page.url = ' '; this.page.identifier = '{{ title }}'; }; (function () { var d = document, s = d.createElement('script'); s.src = 'https://{{ settings.disqus-comments }}.disqus.com/embed.js'; s.setAttribute('data-timestamp', +new Date()); (d.head || d.body).appendChild(s); })(); </script> {% endif %} </body> </html>") new_file('child template', File.join(@includes_folder, '_dated.liquid'), "<div class='dated'>{{ dated }}</div>") new_file('page template', File.join(@includes_folder, '_page.liquid'), "{% if dated %}{% include 'dated' %}{% endif %}\n{{ content }}") new_file('theme', @theme_file, "body { font-family: 'Noto Sans', Verdana, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; font-size: 13pt; background: #f8f8f8; color: #444; margin: 0; padding: 0.5rem 2rem; } a { color: #06d; text-decoration: none; border-bottom: solid 1px #8af; } a:hover { color: #359fe0; } header, section, footer { max-width: 50rem; margin: 0 auto; } header { margin-bottom: 4rem; } section { line-height: 140%; } footer { margin-top: 5rem; font-size: 0.9rem; } header nav { margin-top: 0.75rem; } header nav a { margin-right: 1rem; white-space: nowrap; } section img { max-width: 10rem; max-height: 10rem; float: right; margin: 1rem 0 1rem 2rem; background: #fff; padding: 0.4rem; box-shadow: 0 0 8px #00000033; } header h1 { font-size: 1.2rem; margin: 0.25rem 0; } header aside { color: #666; } h1 { font-size: 1.75em; color: #000; } h1,h2,h3,h4,h5,h6 { line-height: 110%; } table { margin: 2rem 0; } th, td { padding: 0.1rem 1rem 0.1rem 0; border-bottom: solid 1px #ccc; } li { margin: 0.25em 0; } pre { background: #fff; overflow: scroll; border: solid 1px #999; } code { background: #ddd; } pre, code { color: #222; padding: 0.2rem 0.3rem; } pre code { background: #fff; border: 0; padding: 0; } .dated { font-size: 0.8rem; margin-top: -1.25rem; color: #666; text-transform: uppercase; }") done('New site created') end def do_build # Show the folder paths. puts '-------------------------------------------' puts 'Reading ' + @site_folder puts 'Creating ' + @html_folder # Read and show the site options. puts 'Reading ' + @ini_file fatal('ruthless.ini file not found') unless File.exist?(@ini_file) ini = IniFile.load(@ini_file) key_must_exist(ini, 'SITE', 'title') key_must_exist(ini, 'SITE', 'blurb') key_must_exist(ini, 'SITE', 'footer') @site_title = ini['SITE']['title'] @site_blurb = ini['SITE']['blurb'] @site_footer = ini['SITE']['footer'] @site_keywords = ini['SITE']['keywords'] @extentions = ini['OPTIONS']['extentions'] @settings = ini['SETTINGS'] # Populate the (optional) menu. @menu = [] ini.each_section do |section| if section == 'MENU' ini[section].each do |k, v| @menu.push("<a href=\"#{v}\">#{k}</a>") end end end # Ensure we have required folders/files. fatal('Content folder not found') unless Dir.exist?(@content_folder) file_must_exist(@layout_file, 'layout template') file_must_exist(@theme_file, 'theme styles') Liquid::Template.error_mode = :strict Liquid::Template.file_system = Liquid::LocalFileSystem.new(@includes_folder) @layout = Liquid::Template.parse(File.read(@layout_file)) # Ensure we have a fresh, empty, output folder. if Dir.exist?(@html_folder) puts 'Removing output folder' fatal('Unable to remove folder') unless FileUtils.rmtree(@html_folder) end puts 'Creating output folder' FileUtils.mkdir @html_folder fatal('Unable to create folder') unless Dir.exist?(@html_folder) # Render the whole site folder tree. puts 'Rendering output' puts 'Using page extentions' if @extentions puts " #{File::SEPARATOR}" prefix = "#{@content_folder}#{File::SEPARATOR}" prefix_length = prefix.length FileUtils.copy(@theme_file, File.join(@html_folder, 'theme.css')) Find.find(@content_folder) do |path| next if File.directory? path fatal("Expected filename to start with #{prefix} - #{path}") unless path.start_with?(prefix) # Derive a path/filename based on the site vs output folders. rel_path = File.dirname(path[prefix_length, path.length]) abs_path = File.join(@html_folder, rel_path) # Create (and display) new subfolders as they are needed. unless Dir.exist?(abs_path) FileUtils.mkdir_p abs_path fatal("Unable to create content subfolder #{abs_path}") unless Dir.exist?(abs_path) puts " #{File::SEPARATOR}#{rel_path}" end # Derive the output filename. filename_no_ext = File.basename(path, '.*') ext = File.extname(path) use_template = (@templatable.include? ext) out_filename = File.join(abs_path, filename_no_ext) # Extentions/index page? Override for templates else use original. if @extentions || !use_template || (filename_no_ext == 'index') out_filename += use_template ? '.html' : ext else # No extentions? Create a folder and add an index file. unless Dir.exist?(out_filename) FileUtils.mkdir_p out_filename fatal("Unable to create page folder #{out_filename}") unless Dir.exist?(out_filename) out_filename = File.join(out_filename, 'index.html') end end # Write out the new file. if use_template File.open(out_filename, 'w') do |file| src = get_metadata_and_content(path) content = src[:content] if ext == '.md' content = Kramdown::Document.new(content).to_html elsif ext == '.txt' content = "<pre>#{content}</pre>" end data = src[:metadata] data['content'] = content data['sitetitle'] = @site_title data['siteblurb'] = @site_blurb data['sitefooter'] = @site_footer data['sitekeywords'] = @site_keywords data['sitemenu'] = @menu data['settings'] = @settings content = @layout.render(data).delete("\r") file.write content end else FileUtils.copy(path, out_filename) end end puts '-------------------------------------------' puts 'Generated.' end def do_serve puts '-------------------------------------------' puts 'Starting static server on http://localhost:1337 ... Ctrl+C stops' puts root = @html_folder server = WEBrick::HTTPServer.new Port: 1337, DocumentRoot: root, AccessLog: [], Logger: nil trap 'INT' do server.shutdown end server.start end # Return true/false deending upon user confirmation of quitting def confirm_quit choice = '' while(choice == '') puts("(R)estart or (Q)uit?") answer = STDIN.gets.strip.upcase if answer == 'R' or answer == 'Q' then return answer == 'Q' end end end # ------------------------------------------------------------- # Do the work # ------------------------------------------------------------- show_intro fatal('No folder specified') if ARGV.length < 2 do_create if @new_site # Repeatedly do the work (with Ctrl-C to stop an iteration) ongoing = true while(ongoing) do_build if @build_site do_serve if @serve_site puts ongoing = ! confirm_quit puts end done('Finis.')
true
cababf1ebf5fccbcbc70885ed2e36784ba729541
Ruby
alemohamad/book-of-ruby
/11 - Symbols/allsymbols.rb
UTF-8
325
3.78125
4
[]
no_license
# The Book of Ruby - http://www.sapphiresteel.com p( Symbol.all_symbols ) puts( p( Symbol.all_symbols.length ) ) # shows number of symbols in Ruby p( Symbol.all_symbols[0,10] ) # p [:a,:c,:b].sort #<= can't sort symbols in Ruby 1.8! Works in 1.9 str_arr = Symbol.all_symbols.collect{ |s| s.to_s } puts( str_arr.sort )
true
96f910b9c229a5be902ef81b0b79823d5e449f71
Ruby
zakkoltun/101_foundations
/small_problems_ex/easy_4/ex9.rb
UTF-8
459
3.84375
4
[]
no_license
DIGITS = { 0 => '0', 1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9' } def get_digit_place(num, place) (num % (place*10)) / place end def integer_to_string(int) digits = [] while int >= 0 digits << DIGITS[int % 10] int = int / 10 break if int == 0 end digits.join.reverse end puts integer_to_string 4321 puts integer_to_string 0 puts integer_to_string 5000
true
16039d7793810d95dfca35ad6882150a77bf7691
Ruby
touhidur-rahaman/Ruby-Practice
/Ruby/Animals.rb
UTF-8
54
2.671875
3
[]
no_license
class Animals def initialize(n) @head=n end end
true
7f7c8941d6aa8693914bffd449d844ddc52b179a
Ruby
tiagolupepic/freepass
/api/app/filters/hour.rb
UTF-8
450
2.8125
3
[ "MIT" ]
permissive
class HourFilterParams attr_reader :params def initialize(params) @params = params end def result valid_params.delete_if { |_, value| value.nil? } end private def valid_params { name: params[:name], start_at: params[:start_at], end_at: params[:end_at], days: days } end def days return if params[:days].blank? Hash[params[:days].map { |d| [d.to_sym, true] }] end end
true
e6807ed4fdeb36677a49c2fee5947d7fbe952708
Ruby
lbvf50mobile/til
/20190813_Tuesday/tests/conditional_instructions.rb
UTF-8
1,312
3.21875
3
[]
no_license
describe "Befunge-93 Conditional Instructions" do # https://coolefriend.com/know-names-of-symbols-in-your-computer-keyboard/ it "_: pop a value; move right if value = 0, left otherwise" do # _: pop a value; move right if value = 0, left otherwise: underscore state = {stack: [1], direction: 'left', x_position: 0, width: 3} Task.new.do_underscore(state) assert_equal [], state[:stack] assert_equal 2, state[:x_position] # move left if x != 0 assert_equal 'left', state[:direction] Task.new.do_underscore(state) assert_equal [], state[:stack] assert_equal 0, state[:x_position] assert_equal 'left', state[:direction] end it "|: pop a value; move down if value = 0, up otherwise: bar" do state = {stack: [1], direction: 'left', x_position: 0, y_position: 3, width: 3, height: 4} Task.new.do_bar(state) assert_equal [], state[:stack] assert_equal 2, state[:y_position] # up otherwise 3 => 2 Task.new.do_bar(state) assert_equal [], state[:stack] Task.new.do_bar(state) assert_equal [], state[:stack] # move down if value = 0 2 => 3 => 0 assert_equal 0, state[:y_position] assert_equal 'left', state[:direction] end end
true
3e1b8146957c530a917b0e5b5178977b956c54b3
Ruby
zmachine82/library-code
/csv_client.rb
UTF-8
564
3.375
3
[]
no_license
class CsvClient def initialize(file) @file = file end def read_file File.readlines(@file) end def append(line) File.open(@file, "a") do |file| file.puts line end end def write_to_file(lines) File.open(@file, "w") do |file| file.puts lines end end def delete_line(line) newlines = [] read_file.each do |l| if l != line newlines.push(l) end end write_to_file(newlines) end end
true
d603679c810e4105d77a532f9db2c67533df7082
Ruby
guinus70/tests-rubys
/lib/01_temperature.rb
UTF-8
147
3.140625
3
[]
no_license
def ftoc(tempe) tempeC = (tempe - 32)/1.8 return tempeC.round(1) end def ctof(tempe) tempeF = tempe*1.8 + 32 return tempeF.round(1) end
true
fa23e69658c66ed644d40dae9f079f5696ef5773
Ruby
cliftondavies/HackerRank
/Ruby/divisible_sum_pairs.rb
UTF-8
776
3.734375
4
[ "MIT" ]
permissive
# https://www.hackerrank.com/challenges/divisible-sum-pairs/problem def divisibleSumPairs(n, k, ar) # problem domain = integers and arrays # inputs: array length, divisor, array of n integers # store/track = index # process/algorithm = add each integer with all following integers, increment number of pairs if the total is divisible by k, return pairs when the end of the integer array is reached. # output = print the number of (i,j) pairs where i < j and a[i] + a[j] is evenly divisible by k # constraints = 2 <= n <= 100, 1 <= k <= 100, 1 <= ar[i] <= 100 pairs = 0 integers = ar.clone integers.each_with_index do |first_int, i| integers[i + 1..-1].each do |second_int| pairs += 1 if (first_int + second_int) % k == 0 end end pairs end
true
be9f4af9a7ba8633fd3217123f1057cb8b87a600
Ruby
BaptisteVeyssiere/208dowels
/208dowels
UTF-8
4,872
3.1875
3
[]
no_license
#!/usr/bin/ruby -w # coding: utf-8 require 'csv' if ARGV[0] == "-h" print "USAGE\n\t\t./208dowels O0 O1 O2 O3 O4 O5 O6 O7 08+\n\nDESCRIPTION\n\t\tOi\tsize of the observed class\n" exit(0) end if ARGV.length != 9 print "Program needs 9 arguments: got #{ARGV.length}\n" exit(84) end for i in 0..8 if ARGV[i] !~ /^[0-9]+$/ print "Invalid argument: #{ARGV[i]}\n" exit(84) end end $sum = 0 for i in 0..8 $sum += ARGV[i].to_i end if $sum != 100 print "Invalid sum (must be equal to 100)\nSum = #{$sum}\n" exit(84) end $array = Array.new $indice = Array.new for i in 0..8 if i == 0 $array.push(ARGV[i].to_i) $indice.push(i.to_s) elsif i == 8 if ARGV[i].to_i < 10 $array[$array.length-1] += ARGV[i].to_i if $indice[$indice.length-1].include? "-" $indice[$indice.length-1] = ($indice[$indice.length-1])[0..-3] end $indice[$indice.length-1] += '+' else $array.push(ARGV[i].to_i) $indice.push(i.to_s + '+') end else if ARGV[i].to_i < 10 if ARGV[i-1].to_i <= ARGV[i+1].to_i || ARGV[i-1].to_i < 10 $array[$array.length-1] += ARGV[i].to_i if $indice[$indice.length-1].include? "-" $indice[$indice.length-1] = ($indice[$indice.length-1])[0..-3] end $indice[$indice.length-1] += "-" + i.to_s else $array.push(ARGV[i].to_i) $indice.push(i.to_s) end else if $array[$array.length-1] >= 10 $array.push(ARGV[i].to_i) $indice.push(i.to_s) else $array[$array.length-1] += ARGV[i].to_i if $indice[$indice.length-1].include? "-" $indice[$indice.length-1] = ($indice[$indice.length-1])[0..-3] end $indice[$indice.length-1] += '-' + i.to_s end end end end print " x |" for i in 0..$indice.length-1 $before = (6 - $indice[i].length) / 2 + (6 - $indice[i].length) % 2 $after = (6 - $indice[i].length) / 2 print " " * $before + "#{$indice[i]}" + " " * $after + "|" end print " total\n Ox |" for i in 0..$array.length-1 $before = (6 - $array[i].digits.length) / 2 + (6 - $array[i].digits.length) % 2 $after = (6 - $array[i].digits.length) / 2 print " " * $before + "#{$array[i]}" + " " * $after + "|" end print " 100\n" $p = 0 for i in 1..8 $p += (i.to_f * ARGV[i].to_f) / 10000.0 end $t = Array.new $x = 0 for i in 0..7 $nf = (1..100).reduce(1, :*) $nrf = (1..100-i).reduce(1, :*) $rf = (1..i).reduce(1, :*) $ncr = ($nf.to_f / $nrf.to_f) / $rf.to_f $proba = $ncr * ($p.to_f ** i) * ((1.0 - $p.to_f) ** (100 - i)) $proba *= 100 if $indice[$x].to_i == i $t.push($proba) $x += 1 else $t[$t.length-1] += $proba; end end $proba = 100.0; for i in 0..$t.length-1 $proba -= $t[i] end if $indice[$x].to_i == 8 $t.push($proba) $x += 1 else $t[$t.length-1] += $proba; end print " Tx |" for i in 0..$t.length-1 $before = (6 - $t[i].round(1).to_s.split("").size) / 2 + (6 - $t[i].round(1).to_s.split("").size) % 2 $after = (6 - $t[i].round(1).to_s.split("").size) / 2 print " " * $before + "#{$t[i].round(1)}" + " " * $after + "|" end print " 100\ndistribution:\t\t\tB(100, #{$p.round(4)})\n" $s = 0 for k in 0..$array.length-1 if $t[k] == 0 break end $s = $s + (($array[k] - $t[k]) ** 2) / $t[k] end printf("sum of the square differences:\t%.3f\n", $s) $degree = $array.length - 2 print "freedom degrees:\t\t#{$degree}\n" $matrice = [ [0.00, 0.02, 0.06, 0.15, 0.27, 0.45, 0.71, 1.07, 1.64, 2.71, 3.84, 5.41, 6.63], [0.02, 0.21, 0.45, 0.71, 1.02, 1.39, 1.83, 2.41, 3.22, 4.61, 5.99, 7.82, 9.21], [0.11, 0.58, 1.01, 1.42, 1.87, 2.37, 2.95, 3.66, 4.64, 6.25, 7.81, 9.84, 11.35], [0.30, 1.06, 1.65, 2.19, 2.75, 3.36, 4.04, 4.88, 5.99, 7.78, 9.49, 11.67, 13.28], [0.55, 1.61, 2.34, 3.00, 3.66, 4.35, 5.13, 6.06, 7.29, 9.24, 11.07, 13.33, 15.01], [0.70, 2.20, 3.07, 3.83, 4.57, 5.35, 6.21, 7.23, 8.56, 10.64, 12.59, 15.03, 16.81], [1.24, 2.83, 3.82, 4.67, 5.49, 6.35, 7.28, 8.38, 9.80, 12.02, 14.07, 16.62, 18.48], [1.65, 3.49, 4.59, 5.53, 6.42, 7.34, 8.35, 9.52, 11.03, 13.36, 15.51, 18.17, 20.09], [2.09, 4.17, 5.38, 6.39, 7.36, 8.34, 9.41, 10.66, 12.24, 14.68, 16.92, 19.63, 21.67], [2.56, 4.87, 6.18, 7.27, 8.30, 9.34, 10.47, 11.78, 13.44, 15.99, 18.31, 21.16, 23.21] ] $line = $matrice[$degree-1] for i in 0..$line.length-1 if $line[i] > $s print "fit validity:\t\t\t" if i == 0 print "P>99%\n" elsif i == $line.length-1 print "P<1%\n" else if i == 1 $min = "90%" $max = "99%" elsif i == $line.length-2 $min = "1%" $max = "10%" else $max = (100 - (i - 1) * 10).to_s + "%" $min = (100 - i * 10).to_s + "%" end print "#{$min}<P<#{$max}\n" end break elsif $line.length-1 == i print "fit validity:\t\t\tP<1%\n" end end exit(0)
true
97d4a1d41fca3a08856d4587f261dc79c665d24e
Ruby
Maravk/EmilieMaraPTP
/EmilieMaraPTP/A03/kreis.rb
UTF-8
3,293
3.3125
3
[]
no_license
require_relative 'punkt' require_relative 'leinwand' require_relative 'einstellungen' # Author:: Birgit Wendholt # Author:: Bernd Kahlbrandt, an Ruby Style Guide angepasst. class Kreis # initialize wird aufgerufen, wenn Instanzen der Klasse erzeugt werden # '@xxxx' sind die Instanzvariablen der Instanzen def initialize() # Alle Kreise haben ihren Mittelpunkt zu Beginn im Punkt 100,100 @mittelpunkt= Punkt.new(20,60); # und einen Radius von 40 @radius = 15 # Diese Eigenschaften brauchen wir für die Darstellung # die Füllfarbe und Linienfarbe ist rot @farbe = 'red' # zu Beginn sind Kreise nicht gezeichnet @sichtbar = false end def mittelpunkt return @mittelpunkt end def radius return @radius end def farbe return @farbe end def sichtbar?() return @sichtbar end def sichtbar_machen() @sichtbar = true zeichnen() end def unsichtbar_machen() loeschen() @sichtbar = false end def nach_unten_bewegen() # Mittelpunkt um 10 Pixel nach unten verschieben bewegen_um_punkt(Punkt.new(0,10)) end def horizontal_bewegen(anzahl) # Mittelpukt um anzahl Pixel horizontal verschieben bewegen_um_punkt(Punkt.new(anzahl,0)) end def vertikal_bewegen(anzahl) bewegen_um_punkt(Punkt.new(0,anzahl)) end # Bewege einen Kreis langsam vertikal um # entfernung Bildpunkte def langsam_vertikal_bewegen(entfernung) absolute_entfernung = entfernung if sichtbar? delta = 1 if entfernung < 0 delta = -1 absolute_entfernung = - entfernung end x_delta = 0 y_delta = delta Leinwand.gib_einzige_instanz(). bewege(self,absolute_entfernung,x_delta,y_delta) end @mittelpunkt = @mittelpunkt + Punkt.new(0,entfernung) end def farbe_aendern(neue_farbe) # neue_farbe = neue_farbe.downcase() if neue_farbe == "gruen" @farbe = :green end if neue_farbe == "rot" @farbe = :red end if neue_farbe == "blau" @farbe = :blue end if neue_farbe == "gelb" @farbe = :yellow end if neue_farbe == "weiss" @farbe = :white end if neue_farbe == "schwarz" @farbe = :black end if (sichtbar?) Leinwand.gib_einzige_instanz().farbe_aendern(self) end end def groesse_aendern(neuer_radius) loeschen() @radius = neuer_radius zeichnen() end # Textdarstellung einer Kreisinstanz # für eine lesbare Darstellung def to_s "kreis #@nummer" end # Methode für das Verschieben eines Kreis def bewegen_um_punkt(punkt) @mittelpunkt = @mittelpunkt + punkt if sichtbar? Leinwand.gib_einzige_instanz().verschiebe(self,punkt.x,punkt.y) end end # Ein Kreis wird nur gezeichnet, wenn die Instanz sichtbar ist def zeichnen() if sichtbar?() Leinwand.gib_einzige_instanz().zeichne_kreis(self) end end # Nur sichtbare Kreise werden auf der Leinwand gelöscht def loeschen() if sichtbar? Leinwand.gib_einzige_instanz().loesche(self) end end end
true
eec88cde0b0073db03c55766cbdc584b5a5f2af4
Ruby
ty-doerschuk/phase-0
/week-4/factorial/my_solution.rb
UTF-8
415
3.859375
4
[ "MIT" ]
permissive
# Factorial # I worked on this challenge [by myself, with: ]. # input integer to get factorial number via method # define factorial(number) # assign sum = 1 # use correct loop to count down # sum * number = new sum # number = number - 1 # loop that back through # end method # return sum # Your Solution Below def factorial(number) sum = 1 until number == 0 sum *= number number -= 1 end return sum end
true
4d1a2cd96b5c82863a61db38c3ff96f4ea9ef676
Ruby
upfluence/sensu
/lib/sensu/utilities.rb
UTF-8
2,533
2.9375
3
[ "MIT" ]
permissive
gem "uuidtools", "2.1.5" require "uuidtools" module Sensu module Utilities # Determine if Sensu is being tested, using the process name. # Sensu is being test if the process name is "rspec", # # @return [TrueClass, FalseClass] def testing? File.basename($0) == "rspec" end # Retry a code block until it retures true. The first attempt and # following retries are delayed. # # @param wait [Numeric] time to delay block calls. # @param block [Proc] to call that needs to return true. def retry_until_true(wait=0.5, &block) EM::Timer.new(wait) do unless block.call retry_until_true(wait, &block) end end end # Deep merge two hashes. Nested hashes are deep merged, arrays are # concatenated and duplicate array items are removed. # # @param hash_one [Hash] # @param hash_two [Hash] # @return [Hash] deep merged hash. def deep_merge(hash_one, hash_two) merged = hash_one.dup hash_two.each do |key, value| merged[key] = case when hash_one[key].is_a?(Hash) && value.is_a?(Hash) deep_merge(hash_one[key], value) when hash_one[key].is_a?(Array) && value.is_a?(Array) hash_one[key].concat(value).uniq else value end end merged end # Generate a random universally unique identifier. # # @return [String] random UUID. def random_uuid UUIDTools::UUID.random_create.to_s end # Remove sensitive information from a hash (eg. passwords). By # default, hash values will be redacted for the following keys: # password, passwd, pass, api_key, api_token, access_key, # secret_key, private_key, secret # # @param hash [Hash] to redact sensitive value from. # @param keys [Array] that indicate sensitive values. # @return [Hash] hash with redacted sensitive values. def redact_sensitive(hash, keys=nil) keys ||= %w[ password passwd pass api_key api_token access_key secret_key private_key secret ] hash = hash.dup hash.each do |key, value| if keys.include?(key.to_s) hash[key] = "REDACTED" elsif value.is_a?(Hash) hash[key] = redact_sensitive(value, keys) elsif value.is_a?(Array) hash[key] = value.map do |item| item.is_a?(Hash) ? redact_sensitive(item, keys) : item end end end hash end end end
true
22beef913d65a546b8159e474a5a68688f2b0fba
Ruby
Erawpalassalg/CoursAlgo
/TD11/Exo5.rb
UTF-8
629
3.890625
4
[]
no_license
#encoding: utf-8 =begin fonction Puissance(x, p : Entier) → Entier // La fonction puissance(x,p) renvoie l'entier représentant le nombre x à la pussance p Lexique de Puissance x, p : Entier // paramètres fonctionnels, le nombre renvoyé représente x à la puissance p Algorithme de Puissance Selon p = 0 : renvoyer(1) p > 0 : renvoyer(Puissance(x, p-1)*x) p < 0 : renvoyer(puissance(x, p+1)*x) fSelon =end # Ruby a = 4 b = 4 def puissance(x, p) if p == 1 return x else return puissance(x, p-1)*x end end puts puissance(a, b)
true
d7a57b2e66375405376a5c45d01d1256759112b9
Ruby
WodaKyon/RGSS
/Game Scripts/世紀之卡(Carte-De-Sentinelle)/Scripts/004 - Cache.rb
UTF-8
5,700
2.875
3
[ "Apache-2.0" ]
permissive
#encoding:utf-8 #============================================================================== # ■ Cache #------------------------------------------------------------------------------ # 處理載入圖像,建立/儲保 Bitmap 物件。為加快載入速度和節省內存, # 此模塊將建立的 bitmap 物件保存在內部哈希表中,令程序要再次處理 #  相同的圖像時能快速讀取。 #============================================================================== module Cache #-------------------------------------------------------------------------- # ● 獲取動畫圖像 #-------------------------------------------------------------------------- def self.animation(filename, hue) load_bitmap("Graphics/Animations/", filename, hue) end #-------------------------------------------------------------------------- # ● 獲取戰鬥物件背景(地面)圖像 #-------------------------------------------------------------------------- def self.battleback1(filename) load_bitmap("Graphics/Battlebacks1/", filename) end #-------------------------------------------------------------------------- # ● 獲取戰鬥背景(墻壁)圖像 #-------------------------------------------------------------------------- def self.battleback2(filename) load_bitmap("Graphics/Battlebacks2/", filename) end #-------------------------------------------------------------------------- # ● 獲取戰鬥圖 #-------------------------------------------------------------------------- def self.battler(filename, hue) load_bitmap("Graphics/Battlers/", filename, hue) end #-------------------------------------------------------------------------- # ● 獲取角色行走圖 #-------------------------------------------------------------------------- def self.character(filename) load_bitmap("Graphics/Characters/", filename) end #-------------------------------------------------------------------------- # ● 獲取角色肖像圖 #-------------------------------------------------------------------------- def self.face(filename) load_bitmap("Graphics/Faces/", filename) end #-------------------------------------------------------------------------- # ● 獲取遠景圖 #-------------------------------------------------------------------------- def self.parallax(filename) load_bitmap("Graphics/Parallaxes/", filename) end #-------------------------------------------------------------------------- # ● 獲取“圖片”圖像 #-------------------------------------------------------------------------- def self.picture(filename) load_bitmap("Graphics/Pictures/", filename) end #-------------------------------------------------------------------------- # ● 獲取系統圖像 #-------------------------------------------------------------------------- def self.system(filename) load_bitmap("Graphics/System/", filename) end #-------------------------------------------------------------------------- # ● 獲取圖塊組圖像 #-------------------------------------------------------------------------- def self.tileset(filename) load_bitmap("Graphics/Tilesets/", filename) end #-------------------------------------------------------------------------- # ● 獲取標題圖像(背景) #-------------------------------------------------------------------------- def self.title1(filename) load_bitmap("Graphics/Titles1/", filename) end #-------------------------------------------------------------------------- # ● 獲取標題圖像(外框) #-------------------------------------------------------------------------- def self.title2(filename) load_bitmap("Graphics/Titles2/", filename) end #-------------------------------------------------------------------------- # ● 讀取位圖 #-------------------------------------------------------------------------- def self.load_bitmap(folder_name, filename, hue = 0) @cache ||= {} if filename.empty? empty_bitmap elsif hue == 0 normal_bitmap(folder_name + filename) else hue_changed_bitmap(folder_name + filename, hue) end end #-------------------------------------------------------------------------- # ● 生成空位圖 #-------------------------------------------------------------------------- def self.empty_bitmap Bitmap.new(32, 32) end #-------------------------------------------------------------------------- # ● 生成/獲取普通的位圖 #-------------------------------------------------------------------------- def self.normal_bitmap(path) @cache[path] = Bitmap.new(path) unless include?(path) @cache[path] end #-------------------------------------------------------------------------- # ● 生成/獲取色相變化後的位圖 #-------------------------------------------------------------------------- def self.hue_changed_bitmap(path, hue) key = [path, hue] unless include?(key) @cache[key] = normal_bitmap(path).clone @cache[key].hue_change(hue) end @cache[key] end #-------------------------------------------------------------------------- # ● 檢查緩存是否存在 #-------------------------------------------------------------------------- def self.include?(key) @cache[key] && !@cache[key].disposed? end #-------------------------------------------------------------------------- # ● 清空緩存 #-------------------------------------------------------------------------- def self.clear @cache ||= {} @cache.clear GC.start end end
true
5e234e1e1a09d6c756851250d8911563d28165c8
Ruby
alinemokfa/e16_class_notes
/week_03/day_3/one_to_many_pizza_shop/one_to_many_pizza_end/pizza_shop/db/console.rb
UTF-8
666
2.65625
3
[]
no_license
require('pry-byebug') require_relative('../models/pizza_order') require_relative('../models/customer') PizzaOrder.delete_all() Customer.delete_all() customer1 = Customer.new({'name' => 'Craig Morton'}) customer2 = Customer.new({'name' => 'David Blaine'}) customer1.save() customer2.save() order1 = PizzaOrder.new({ 'customer_id' => customer1.id, 'topping'=> 'Napoli', 'quantity'=> '1' }) order1.save() order2 = PizzaOrder.new({ 'customer_id' => customer1.id, 'topping'=> 'Quattro Formaggi', 'quantity'=> '1' }) order2.save() order3 = PizzaOrder.new({ 'customer_id' => customer2.id, 'topping'=> 'Magic', 'quantity'=> '10' }) order3.save() binding.pry nil
true
03c81e11d9a87231be758524a2999ddc17e8ff15
Ruby
yoyohohoxd/learn_ruby
/03_simon_says/simon_says.rb
UTF-8
913
4.375
4
[]
no_license
#write your code here def echo(string) string end def shout(string) string.upcase end def repeat(string, a = 2) if a <= 2 string + ' ' + string elsif a > 2 repeat_word = string + ' ' full_output = repeat_word * a full_output.delete_suffix(' ') end end def start_of_word(string, a = 1) string[0, a] end def first_word(string) string.split(' ')[0] end def titleize(string) special_words = ['a', 'an', 'and', 'of', 'the', 'over'] fixed_words = [] string.downcase.split.each_with_index do |word, index| # If this isn't the first word, and it's special, use downcase if index > 0 and special_words.include?(word) fixed_words << word # It's either the first word, or not special, so capitalize else fixed_words << word.capitalize end end fixed_words.join(" ") end
true
b41a1dcd1061b4a9c89bcf5143b269fe456f8ac0
Ruby
JFVF/cucumber_022015
/Noemi/Arry_practice.rb
UTF-8
590
3.859375
4
[]
no_license
class My_arry def drawn_arry() puts 'Give me the lenght of the arry?' @var_number = gets.chomp.to_i puts "The leght is #{@var_number}" ary = Array.new Array.new(@var_number) for i in 1.. @var_number puts 'Give me a item to add to arry?' var_item=gets.chomp ary.push var_item end return ary end def print_arry(newarry) puts 'Printing your arry' p newarry puts 'Printing your arry one by one' for i in 0.. @var_number-1 puts newarry[i] end end end noe_arry = My_arry.new newarry= noe_arry.drawn_arry noe_arry.print_arry newarry
true
f70cf70f55320f52b986199447862797cf7549df
Ruby
OskarRamirez/101
/lesson_3/practice_problems_medium_2.rb
UTF-8
744
3.765625
4
[]
no_license
#3 =begin Prints "My string looks like this now: pumpkins" prints "My array looks like this now: ["pumpkin","rutabaga"]" #4 prints "My string looks like this now: pumpkinsrutabaga" prints "My array looks like this now: ["pumpkins"] =end def tricky_method_two(a_string_param, an_array_param) a_string_param << 'rutabaga' an_array_param = ['pumpkins', 'rutabaga'] an_array_param end my_string = "pumpkins" my_array = ["pumpkins"] my_array = tricky_method_two(my_string, my_array) puts "My string looks like this now: #{my_string}" puts "My array looks like this now: #{my_array}" #5 def color_valid(color) color == "blue" || color == "green" ? true : false end def my_favorite_teams(team) team == "Jets" || team == "Mets" end
true
25bf9924527971d59919c5fb14d0362c455c4fd0
Ruby
jroberts235/utils
/diff_env
UTF-8
3,824
2.890625
3
[]
no_license
#!/usr/bin/env ruby require 'colorize' # gem install 'colorize' # accept nil for environment and show all env's if ARGV[0] == nil arg1 = nil else arg1 = ARGV[0] end raise "Knife can't be found at '/usr/bin/knife'".red unless File.exist?('/usr/bin/knife') environment = arg1 mismatches = 0 user_name = `whoami`.chomp knife_path = '/usr/bin/knife' knife_cfg = "/Users/#{user_name}/.chef/knife.rb" repo_dir = "/Users/#{user_name}/chef-repo" lcl_env_dir = "/Users/#{user_name}/chef-repo/environments/" a_srv_lines = Array.new # array of cookbooks and versions from chefserver h_srv_lines = Hash.new # hash of a_lcl_lines = Array.new # array of cookbooks and versions from local files h_lcl_lines = Hash.new # hash of # no environment was specified. show all. if environment == nil puts "Currently, you must supply the Environment to compare." ; exit(1) a = ['prod','dr','ops','stg',] a.each do |env| environment = env get_env_from_chefsrv = "#{knife_path} environment show #{environment} -c #{knife_cfg}" Dir.chdir(repo_dir){ chefsrv_output = %x(#{get_env_from_chefsrv}) } raw_chefsrv_output = raw_output.split(' ') end else # environment was specified ## open the local perception of the environment file ## Dir.chdir(repo_dir){ # execute this in the top of the repo dir s_lcl_lines = "" file = File.open("environments/#{environment}.rb", "rb") # slurp file as binary s_lcl_lines = file.read file.close s_lcl_lines.each_line do |line| # take each line from the strin and put into array if '=' is found line.tr!("\n", '') ; line.tr!('"','') ; line.tr!(',',':') # cleanup the line if line.include?('=') line.lines.map!(&:chomp) a_lcl_lines << (line.split(' ', 2))[1] end end a_lcl_lines.each do |line| # split each element into hash key and value line.tr!(' ', '') # remove whitespaces h_lcl_lines[(line.split('=', 2))[0]] = (line.split('=', 2))[1] end ## get chefserver's perception of environment ## get_env_from_chefsrv = "#{knife_path} environment show #{environment} -c #{knife_cfg}" # cmd to run raw_chefsrv_output = %x(#{get_env_from_chefsrv}) #%x() is basically a syscall # take each line and put into a_chefsrv_output a_chefsrv_output = raw_chefsrv_output.lines.map(&:chomp) # take each line of string and put into an array a_chefsrv_output.each do |line| # find the lines with '=' in them if line.include?('=') a_srv_lines << line # add the line to an array end end a_srv_lines.each do |line| # add each element to a hash key and value line.tr!(' ', '') # remove whitespaces h_srv_lines[(line.split('=', 2))[0]] = ((line.split('=', 2))[1]).tr("\n", '') end } ## comparator ## # for each key in h_lcl_lines check the value of the key by the same name in h_srv_lines h_lcl_lines.each do |cookbook, version| # walk the local hash and compare values with h_srv_lines hash if h_srv_lines[cookbook] != version puts "* ".red + "The #{cookbook.tr(':', '').cyan} cookbook version does not match what is on the chefserver!" + " *".red puts "Maybe someone didn't comit !?!?" puts "Chef => #{cookbook} = #{h_srv_lines[cookbook]}" puts "Local => #{cookbook} = #{version}" mismatches += 1 # found a mismatch end end end puts "* ".green + "In Sync" + " *".green if mismatches == 0 # light is green, trap is clean puts "There was a problem executing your command!".red if $?.exitstatus > 0 # if cmd failed for some reason
true
18e920a7d0c0d1d073817d20f239444ca41721c3
Ruby
Stro21/E9CP1A1
/ejercicio5.rb
UTF-8
692
4.09375
4
[]
no_license
# Class Morseable class Morseable def initialize(number) @number = number end def generate_hash(number) if number >= 0 && number <= 4 hash_minus(number) else hash_point(number) end end def hash_minus(number) h = '-----' return h if number.zero? i = 0 h.each_char do h[i] = '.' break if i == number - 1 i += 1 end h end def hash_point(number) h = '.....' n = number - 5 return h if number == 5 i = 0 h.each_char do h[i] = '-' break if i == n - 1 i += 1 end h end def to_morse generate_hash(@number) end end m = Morseable.new(3) print m.to_morse
true
3cf1ee204603c4209f650f3b6891f3eafdcf6c90
Ruby
shsachdev/ls101
/small_problems/medium_problems/rotation_pt2.rb
UTF-8
507
3.59375
4
[]
no_license
def rotate_rightmost_digits(number, n) if n == 1 return number end number_array = number.to_s.chars deleted_num = number_array.delete_at(-n) number_array << deleted_num number_array.join.to_i end # p rotate_rightmost_digits(735291, 1) == 735291 # p rotate_rightmost_digits(735291, 2) == 735219 # p rotate_rightmost_digits(735291, 3) == 735912 # p rotate_rightmost_digits(735291, 4) == 732915 # p rotate_rightmost_digits(735291, 5) == 752913 # p rotate_rightmost_digits(735291, 6) == 352917
true
2b201bb32626ce18593534bbe6a1361a2691b8da
Ruby
sookoor/ruby-practice
/even_fibonacci_sum.rb
UTF-8
211
3.234375
3
[]
no_license
def even_fibonacci_sum sum, prev, cur if sum < 4000000 if cur % 2 == 0 sum += cur end even_fibonacci_sum sum, cur, prev + cur else return sum end end puts even_fibonacci_sum 0, 1, 2
true
38ec443d9afab097dc8e4ebaecb4c9141e8383a6
Ruby
smile0304/ufuzz
/lib/ufuzz/tokenizer.rb
UTF-8
1,310
3.046875
3
[]
no_license
module UFuzz class Tokenizer attr_accessor :tokens def initialize(str) @tokens = [] @regex = /[@"\/\:=\[\]&,\r\n\|;\*\?\)\(\{\}\\ ]/ prev = '' (0).upto(str.length-1) do |n| if str[n] =~ @regex @tokens << prev unless prev.empty? @tokens << str[n] prev = '' else prev += str[n] end end @tokens << prev if prev if @tokens =~ /(%[0-9a-f][0-9a-f])/i @tokens.map! { |t| t.split(/(%[0-9a-f][0-9a-f])/i) } @tokens.flatten! end @tokens end def fuzz_each_token(testcase, opts = {}, &block) @tokens.each_with_index do |t,i| next if t =~ @regex || t =~ /%[0-9a-f][0-9a-f]/i #|| i < 20 testcase.rewind(t) while(testcase.next?) f = testcase.next fuzz_positions(t, i, f, opts, &block) end end end def to_s @tokens.map { |t| t }.join('') end def fuzz_positions(tok, i, fuzz, opts) Config.instance.encoders.each do |encode| fuzz_val = encode.call(fuzz) ["#{fuzz_val}", "#{tok}#{fuzz_val}", "#{fuzz_val}#{tok}"].each do |f| t = @tokens.dup t[i] = f yield Tokenizer.tok_to_string(t), i, fuzz end end end def self.tok_to_string(tok) tok.map { |t| t }.join('') end end end
true
99f9c7f7dbdfe97d8b8fc4c7fee94d7891a0180a
Ruby
fizzy-fifs/makersbnb
/spec/booking_spec.rb
UTF-8
894
2.59375
3
[]
no_license
require 'booking' require 'user' require 'space' describe Booking do let(:user) {User.create(name: "John" , email: "jman@user.com", password: "password123")} let(:space) {Space.create(name: "10 Makers Lane", description: "Nice house", price_per_night: "10", user_id: user.id) } let(:booking) { Booking.create(start_date: "1/05/2021", end_date: "02/05/2021", user_id: "#{user.id}", space_id: space.id) } describe '.create' do it 'creates a new booking' do user space booking result = DatabaseConnection.query('SELECT * FROM booking;').first expect(result['start_date']).to eq("2021-01-05") expect(booking.start_date).to eq("#{result['start_date']}") expect(booking.end_date).to eq("#{result['end_date']}") expect(booking.user_id).to eq("#{result['user_id']}") expect(booking.space_id).to eq("#{result['space_id']}") end end end
true
aa01f2bee1dae3fe44361eb2045c18623032dfc7
Ruby
chefzyz/BAREALTY
/main.rb
UTF-8
617
2.53125
3
[]
no_license
require 'sinatra' get '/index' do erb :index end get '/contact' do erb :contact end get '/find' do erb :find end get '/sell' do erb :sell end post '/contact' do require 'mandrill' m = Mandrill::API.new message = { :subject=> params[:subject], :from_name=> params[:name], :text=> params[:message] + "Your Phone number is " + params[:tel], :to=>[ { :email=> "elderazeez20@gmail.com", :name=> "Elder Azeez" } ], #:html=>"<html><h1>Hi <strong>message</strong>, how are you?</h1></html>", :from_email=> params[:email] } sending = m.messages.send message puts sending erb :contact end
true
e331607c3fdca0dc6aae76bc09a2ed221852428c
Ruby
aiya000/workspace
/Coder/paiza/Challenge/Rank_C/C016/54.rb
UTF-8
278
3.4375
3
[]
no_license
class String MAP = { "A" => "4", "E" => "3", "G" => "6", "I" => "1", "O" => "0", "S" => "5", "Z" => "2" } def replace_to_leef self.split("").map{|c| _c = MAP[c]; if _c == nil then c else _c end }.join end end puts gets.replace_to_leef
true
3c4f25b03aaf206b4a26b04cd975d91fa8cb4707
Ruby
hectoregm/pingpong
/spec/models/game_spec.rb
UTF-8
1,874
2.625
3
[]
no_license
require 'rails_helper' RSpec.describe Game, type: :model do before do @valid_attributes = { played_at: Time.now, winner: User.create!(email: 'foo@regalii.com', password: 'secret123'), loser: User.create!(email: 'bar@regalii.com', password: 'secret456'), winner_score: 21, loser_score: 19 } end it 'is sane' do expect(Game.new(@valid_attributes)).to be_valid end context do it 'requires a date' do expect(Game.new(@valid_attributes.merge(played_at: nil))).to_not be_valid end it 'requires a winner' do expect(Game.new(@valid_attributes.merge(winner: nil))).to_not be_valid end it 'requires a loser' do expect(Game.new(@valid_attributes.merge(loser: nil))).to_not be_valid end it 'require a score of each player' do expect(Game.new(@valid_attributes.merge(winner_score: -1))).to_not be_valid expect(Game.new(@valid_attributes.merge(loser_score: -1))).to_not be_valid end end context 'Game Points' do it 'max score is 21' do expect(Game.new(@valid_attributes.merge(winner_score: 22))).to_not be_valid end it 'min score is 0' do expect(Game.new(@valid_attributes.merge(winner_score: -1))).to_not be_valid end it 'a victory requires a two point difference' do game = Game.new(@valid_attributes.merge(winner_score: 21, loser_score: 21)) expect(game).to_not be_valid game = Game.new(@valid_attributes.merge(winner_score: 21, loser_score: 20)) expect(game).to_not be_valid game = Game.new(@valid_attributes.merge(winner_score: 21, loser_score: 19)) expect(game).to be_valid game = Game.new(@valid_attributes.merge(winner_score: 21, loser_score: 2)) expect(game).to be_valid end end end
true