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
8eb3e26e20bc18da8f7be25b4a2cd02c116b670c
Ruby
hildjj/magic_reveal
/spec/magic_reveal/slide_renderer_spec.rb
UTF-8
3,883
2.75
3
[ "MIT" ]
permissive
require 'spec_helper' require 'magic_reveal/slide_renderer' require 'tmpdir' describe MagicReveal::SlideRenderer do describe '.header' do context 'when no slides have been shown' do before { subject.has_shown_slides = false } it 'starts with <section>' do expect(subject.header('text', 1)).to match(/\A<section>/) end end context 'when slides have been shown' do before { subject.has_shown_slides = true } it 'starts with </section><section>' do expect(subject.header('text', 1)).to match(%r{\A</section>\s*<section>}) end end it 'ends with <h?>text</h?>' do txt = "text#{rand 99}" lvl = rand(6) expect(subject.header(txt, lvl)).to match(%r{<h#{lvl}>#{txt}</h#{lvl}>\Z}) end end describe '.doc_header' do it 'should generate an HTML comment' do expect(subject.doc_header) .to match(/\A<!--\s.*\s-->\Z/) end it 'should set has_shown_slides to false' do subject.has_shown_slides = true subject.doc_header expect(subject.has_shown_slides).to be_false end end describe '.doc_footer' do context 'when slides have been shown' do before { subject.has_shown_slides = true } it 'emits a </section>' do expect(subject.doc_footer).to eq('</section>') end end context 'when no slides have been shown' do before { subject.has_shown_slides = false } it 'emits an empty string' do expect(subject.doc_footer).to eq('') end end end describe '.block_code' do let(:code) { "code = #{rand 99};" } context 'with language' do let(:language) { "lang#{rand 99}" } it 'has the pre class set to the language' do expect(subject.block_code(code, language)) .to match(/\A\s*<pre class="#{language}">/) end end context 'without language' do it 'has pre without class' do expect(subject.block_code(code, nil)) .to match(/\A\s*<pre>/) end end it 'wraps the text in a <code> tag' do text = "#{rand 99} text #{rand 99}" expect(subject.block_code(text, nil)) .to match(%r{<code>#{Regexp.quote text}</code>}) end it 'escapes the code text' do CGI.should_receive(:escapeHTML).and_return('text') subject.block_code('whatever', nil) end it 'ends with </pre>' do expect(subject.block_code('whatever', nil)) .to match(%r{</pre>\s*\Z}) end it 'has no space between <pre> and <code>' do expect(subject.block_code('whatever', nil)) .to match(/<pre[^>]*><code>/) end it 'has no space between </pre> and </code>' do expect(subject.block_code('whatever', nil)) .to match(%r{</code></pre>}) end it "doesn't add whitespace after code and before </code>" do expect(subject.block_code('mouse', nil)).to match(%r{mouse</code>}) end end describe 'prepare_code' do context 'with @@source = filename' do around do |example| Dir.mktmpdir do |dir| @tmpdir = Pathname.new dir example.run end end let(:filename) { @tmpdir + "file#{rand 99}" } it 'loads the contents from filename' do text = "#{rand 99} bottles of beer" filename.open('w') { |f| f.write text } expect(subject.prepare_code "@@source = #{filename}").to eq(text) end end context 'without @@source' do it 'returns the text' do text = "#{rand 99} luft balloons." expect(subject.prepare_code text).to eq(text) end it 'strips leading whitespace' do expect(subject.prepare_code " \t\nmouse") .to eq('mouse') end it 'strips trailing whitespace' do expect(subject.prepare_code "mouse\n\t ") .to eq('mouse') end end end end
true
c2e5cad7751e794b1953e9a0329b1fed7deea0eb
Ruby
NAKKA-K/learn-metapro-ruby
/blocks/instance_eval.rb
UTF-8
239
3.46875
3
[]
no_license
class MyClass def initialize @v = 1 end end obj = MyClass.new v = 2 # objインスタンスのスコープでコードを書ける obj.instance_eval do p self #=> #<MyClass:0x00007fb03d18c0c8 @v=1> p @v #=> 1 p v #=> 2 end
true
b27ad40e9011d6ad390e717168a7888ae037ca4d
Ruby
banthaherder/number-to-words
/lib/number_words.rb
UTF-8
796
3.484375
3
[]
no_license
class Integer def number_words # Partial list of required numbers ones = {0 => "zero", 1 => "one", 2 => "two", 3 => "three", 4 => "four", 6 => "six", 7 => "seven"} tens = {2 => "twenty ", 7 => "seventy ", 8 => "eighty "} # List of denomination names denoms = {1 => " hundred ", 2 => " thousand ", 3 => " million ", 4 => " billion ", 5 => " trillion "} # Splits a number into an array of string numbers (ex. 1234 -> "1","2","3","4") input_nums = self.to_s.split("") # Empty array num_array = [] # Loops through array of presplit input numbers to reconvert to integer for n in input_nums num_array.push(n.to_i) end num_of_places = (num_array.length / 3).ceil grouped_array for i in num_array.length num end end end
true
4fa7e79b1bdc6e9d75346a17895928a62f5e9cb0
Ruby
hisaacdelr/VideoStoreAPI
/test/models/movie_test.rb
UTF-8
1,688
2.765625
3
[]
no_license
require "test_helper" describe Movie do let (:movie) {Movie.new} let (:one) {movies(:one)} let (:two) {movies(:two)} it "must have a title to be vaild" do one.valid?.must_equal true one.title = nil one.valid?.must_equal false end it "must have a overview to be vaild" do one.valid?.must_equal true one.overview = nil one.valid?.must_equal false end it "must have a release date to be vaild" do one.valid?.must_equal true one.release_date = nil one.valid?.must_equal false end it "must have a release date with a valid date in YYYY-MM-DD format" do one.valid?.must_equal true one.release_date = "cow" one.valid?.must_equal false one.release_date = "2017-02-50" one.valid?.must_equal false end it "must have an inventory to be vaild" do one.valid?.must_equal true one.inventory = nil one.valid?.must_equal false end it "must have an integer in inventory to be vaild" do one.valid?.must_equal true one.inventory = "zero" one.valid?.must_equal false end it "inventory must be greater than or equal to zero to be vaild" do one.valid?.must_equal true one.inventory = -1 one.valid?.must_equal false end describe "available_inventory" do let(:movie){movies(:two)} let(:customer1){customers(:one)} let(:customer2){customers(:two)} it "decreases a movie's available inventory with a new rental" do starting_inventory = movie.available_inventory Rental.create(customer: customer1, movie: movie) Rental.create(customer: customer2, movie: movie) movie.available_inventory.must_equal starting_inventory - 2 end end end
true
99767a4110a0648a0abfe7fba224a6b3e1da72ae
Ruby
cjolokai/launchschool
/lesson_2/pseudo.rb
UTF-8
875
4.375
4
[]
no_license
#1. a method that returns the sum of two integers # START # GET one integer from user # GET another integer from user # RETRIEVE the sum of both integers # END #2 a method that takes an array of strings, and # returns a string that is all those strings # concatenated together # START # Given an array of strings called "Strings" # TAKE each string within the "Strings" array and combined together # RETURN the combined strings #3 a method that takes an array of integers, # and returns a new array with every other element # START # Given an array of integers # Given enpty array # Assign each integer and index # Go over the array and return the odd numbered integers and # push them into the blank array # End # arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # n_arr = [] # arr.each_with_index do |num, idx| # if idx % 2 == 0 # n_arr << num # end # end # p n_arr
true
008184359a235bc995c88813b529c4fc689db798
Ruby
urbantumbleweed/urbantumbleweed
/w01/d03/Joshua_Lieberman/Homework/subway2.rb
UTF-8
1,377
3.359375
3
[]
no_license
n = ['ts', '34th', '28th-n', '23rd-n', 'us'] l = ['8th', '6th', 'us', '3rd', '1st'] s = ['gc', '33rd', '28th-s', '23rd-s', 'us'] mta = {} mta[:n] = n mta[:l] = l mta[:s] = s def subway(subway_hash) n = ['ts', '34th', '28th-n', '23rd-n', 'us'] l = ['8th', '6th', 'us', '3rd', '1st'] s = ['gc', '33rd', '28th-s', '23rd-s', 'us'] mta = subway_hash puts "What line would you like to ride on?" line = gets.chomp.downcase puts mta[line.to_sym] puts "" puts "Where are you getting on?" on = gets.chomp.downcase puts "" puts "Where are you getting off?" off = gets.chomp.downcase distance = (line.index(on).to_i - line.index(off).to_i).abs if off != "us" puts "" puts "Your trip will be #{distance} stops" else puts "" transfer(distance, mta) end end def transfer(distance, subway_hash) mta = subway_hash puts "Do you wish to transfer at Union Square? (y/n)" trans_ans = gets.chomp.downcase if trans_ans == "n" puts "Your trip will be #{distance} stops" else puts "test test #{distance} test test" puts "Which line are you transferring to?" line = gets.chomp.downcase puts mta[line.to_sym] puts "Where are you getting off?" trans_off = gets.chomp.downcase trans_distance = (line.index(trans_off).to_i - line.index("us").to_i).abs distance = distance + trans_distance puts "Your trip will be #{distance} stops" end end subway(mta)
true
98abe59d66c72c6a7cfc684e676c9b7ff0468b4f
Ruby
rosariovalech/PruebaRuby2
/Ejercicio1.rb
UTF-8
85
3.046875
3
[]
no_license
class T def method1() puts "funciona" end end t = T.new t.method1()
true
c1e58fa4e850e529617d5da431ec0b83923504e5
Ruby
HoorayForZoidberg/tylerknottgregson
/finder.rb
UTF-8
2,119
3.671875
4
[]
no_license
# frozen_string_literal: true def check_snippet(snippet, target_sentence_array) # order words last to first (because snippets are found using the last word) # memoize the index marking the last word (start with snippet length) upper_boundary = snippet.length count = 0 # for each word, find the highest matching index of occurence that is strictly # lower than the memoized value, replace it with *** word ***, and keep count target_sentence_array.reverse.each do |word| matches = snippet[0...upper_boundary].each_index.select { |i| snippet[i].include?(word) } unless matches.empty? snippet[matches.last] = "#{snippet[matches.last].upcase}" upper_boundary = matches.last count += 1 end end # compare count to target_sentence_array count # if they match, return the snippet_arr.join # else, return nil count == target_sentence_array.length ? snippet.join(' ') : nil end puts "Type all your sentences, then type \"go\"\n" sentences = [] answer = gets.chomp!.downcase while answer != "go" sentences << answer answer = gets.chomp!.downcase end # get text, remove punctation text = File.read('greatexpectations.txt') .gsub(/([^\s\w’-])/, '') .gsub(/\-/, ' ') .downcase .split(' ') success = 0 sentences.each do |target_sentence| # turn sentence into array target_sentence_array = target_sentence.split(' ') # start search using last word (less likely to be common) search_word = target_sentence_array.last # find index of each occurence of last word indices = text.each_index.select { |i| text[i].include?(search_word) } # for each last word indices.each do |i| # collect 300 words before snippet = text[i - 300..i] # check if the passage contains all words in the proper order checked_snippet = check_snippet(snippet, target_sentence_array) unless checked_snippet.nil? puts "\nall words found for #{target_sentence}: \n #{checked_snippet}" success += 1 end end end success.positive? ? puts("\nfound in #{success} instances") : puts('sorry, no luck')
true
73f0cd723661ac6aaa6cee7ab1c4a492ce38c813
Ruby
haggen/mobility
/lib/mobility/configuration.rb
UTF-8
1,300
2.59375
3
[ "MIT" ]
permissive
module Mobility =begin Stores shared Mobility configuration referenced by all backends. =end class Configuration # Alias for mobility_accessor (defaults to +translates+) # @return [Symbol] attr_accessor :accessor_method # Name of query scope/dataset method (defaults to +i18n+) # @return [Symbol] attr_accessor :query_method # Default fallbacks instance # @return [I18n::Locale::Fallbacks] def default_fallbacks(fallbacks = {}) @default_fallbacks.call(fallbacks) end attr_writer :default_fallbacks # Default backend to use (can be symbol or actual backend class) # @return [Symbol,Class] attr_accessor :default_backend # Returns set of default accessor locles to use (defaults to # +I18n.available_locales+) # @return [Array<Symbol>] def default_accessor_locales if @default_accessor_locales.is_a?(Proc) @default_accessor_locales.call else @default_accessor_locales end end attr_writer :default_accessor_locales def initialize @accessor_method = :translates @query_method = :i18n @default_fallbacks = lambda { |fallbacks| I18n::Locale::Fallbacks.new(fallbacks) } @default_accessor_locales = lambda { I18n.available_locales } end end end
true
4a38f3206cfef1bc20ac1c3f814d6ef95755606a
Ruby
fbonetti/great_lakes_data
/app/services/data_importer.rb
UTF-8
1,752
2.84375
3
[]
no_license
require 'open-uri' class DataImporter def self.import(station, year) # Alpena has a different path for some reason if station.id == 6 station_id = 'c6' else station_id = station.id.to_s.rjust(2, '0') end uri = URI::HTTP.build( host: 'www.glerl.noaa.gov', path: "/metdata/#{station.slug}/archive/#{station.slug}#{year}.#{station_id}t.txt" ) open(uri) do |file| inserts = file.map { |row| convert_row_to_sql_insert(row) }.compact insert_readings(inserts) end end private def self.convert_row_to_sql_insert(row) return nil if row.include?("ID") || row.include?("AirTemp") data = row.split(" ") station_id = data[0] year = data[1] day_of_year = data[2] utc_time = data[3] air_temp = data[4] wind_speed = data[5] wind_gust = data[6] wind_direction = data[7] timestamp = DateTime.strptime([year, day_of_year, utc_time].join(' '), "%Y %j %H%M").to_s values = { station_id: station_id, timestamp: timestamp, air_temp: air_temp, wind_speed: wind_speed, wind_gust: wind_gust, wind_direction: wind_direction } return nil if wind_speed.to_f < 0 || wind_gust.to_f < 0 || wind_direction.to_i < 0 sql = "(:station_id, :timestamp, :air_temp, :wind_speed, :wind_gust, :wind_direction)" sanitize(sql, values) end def self.insert_readings(inserts) ActiveRecord::Base.connection.execute(" INSERT INTO readings (station_id, timestamp, air_temp, wind_speed, wind_gust, wind_direction) VALUES #{inserts.join(', ')} ON CONFLICT DO NOTHING ") end def self.sanitize(sql, values = {}) ActiveRecord::Base.send(:sanitize_sql, [sql, values], '') end end
true
22ae860063f96fec2aaaa11ace9fd31ed1a4d3cb
Ruby
erickcsh/TicTacToe
/spec/tic_tac_toe/input_spec.rb
UTF-8
6,226
2.578125
3
[]
no_license
require 'tic_tac_toe' require 'constants' require 'boards' describe TicTacToe::Input, ".input_name" do let(:display) { double(:display).as_null_object } subject { described_class.instance } before do allow(TicTacToe::Display).to receive(:instance) { display } allow(subject).to receive(:input_line) end after do subject.input_name(player_number: 0) end it "displays enter player name message" do expect(display).to receive(:display_msg_ask_for_player_name) end it "reads player name" do expect(subject).to receive(:input_line) end end describe TicTacToe::Input, ".input_replay" do let(:display) { double(:display).as_null_object } subject { described_class.instance } before do allow(TicTacToe::Display).to receive(:instance) { display } allow(subject).to receive(:input_line) { 'n' } end after do subject.input_replay end it "displays replay message" do expect(display).to receive(:display_msg_replay) end it "reads replay answer" do expect(subject).to receive(:input_line) end end describe TicTacToe::Input, ".input_mode" do let(:display) { double(:display).as_null_object } subject { described_class.instance } before do allow(TicTacToe::Display).to receive(:instance) { display } end after do subject.input_mode end context "when valid mode is selected" do before do allow(subject).to receive(:input_line).and_return(A_VALID_MODE) end it "does not display error message" do expect(display).not_to receive(:display_error_msg_mode) end end context "when invalid mode is selected" do before do allow(subject).to receive(:input_line).and_return(AN_INVALID_MODE, A_VALID_MODE) end it "displays error message" do expect(display).to receive(:display_error_msg_mode) end end end describe TicTacToe::Input, ".input_player_action" do let(:display) { double(:display).as_null_object } let(:checker) { double(:checker).as_null_object } let(:board) { double(:board).as_null_object } let(:player_1) { Boards.player_1 } subject { described_class.instance } before do allow(TicTacToe::Display).to receive(:instance) { display } allow(Kernel).to receive(:rand) { 0 } allow(subject).to receive(:input_line) end context "when asks for a position" do let(:cell) { double(:cell, position:'quit') } before do allow(board).to receive(:get_empty_positions) { [cell, cell, cell] } end context "when player is a computer" do after do subject.input_player_action(computer, board) end let(:computer) { TicTacToe::Player.new(A_COMPUTER_NAME, computer: true) } it "displays computer thinking message" do expect(display).to receive(:display_msg_computer_thinking) end it "selects random position" do expect(subject).to receive(:input_validation).with(cell.position, board).and_call_original end end context "when player is not a computer" do after do subject.input_player_action(player_1, board) end it "displays select position message" do allow(subject).to receive(:input_line) { 'quit' } expect(display).to receive(:display_msg_select_position) end it "reads player's input" do expect(subject).to receive(:input_line) { 'quit' } end end end context "when player types an input" do after do subject.input_player_action(player_1, board) end context "when input is invalid" do shared_examples "re-ask position" do it "asks for input again" do expect(subject).to receive(:select_position).twice.with(player_1, board) end end context "when input is not a valid position" do before do allow(subject).to receive(:select_position).and_return(INVALID_INPUT_POSITION, 'quit') end it "displays not valid input error message" do expect(display).to receive(:display_msg_not_valid_input) end it_behaves_like "re-ask position" end context "when input is not an empty position" do before do allow(subject).to receive(:select_position).and_return(A_POSITION_STRING, 'quit') allow(board).to receive(:position_empty?) { false } end it "displays not empty position error message" do expect(display).to receive(:display_msg_not_empty_position) end it_behaves_like "re-ask position" end end context "when input is valid" do shared_examples "valid input" do it "does not show error messagges" do expect(display).not_to receive(:display_msg_not_valid_input) expect(display).not_to receive(:display_msg_not_empty_position) end end context "when input is a special option" do context "when input is 'quit'" do before do allow(subject).to receive(:select_position) { 'quit' } end it_behaves_like "valid input" it "does not ask for input again" do expect(subject).to receive(:select_position).once.with(player_1, board) end end context "when input is 'reset'" do before do allow(subject).to receive(:select_position).and_return('reset' , 'quit') end it_behaves_like "valid input" end context "when input is 'help'" do before do allow(subject).to receive(:select_position).and_return('help', 'quit') allow(display).to receive(:display_gameplay_instructions) end it_behaves_like "valid input" end end context "when input is a position" do before do allow(subject).to receive(:select_position).and_return(A_POSITION_STRING, 'quit') end it_behaves_like "valid input" end end end end describe TicTacToe::Input, "#input_line" do it "reads the input and chops the \\n" do allow(STDIN).to receive(:gets).and_return(AN_INPUT + "\n") expect(described_class.instance.input_line).to eq(AN_INPUT) end end
true
1708863f357c6cc03b150a4cfeffbb38cdc3f858
Ruby
ScoRay72/awsum
/lib/awsum/s3.rb
UTF-8
9,206
2.859375
3
[ "MIT" ]
permissive
require 'awsum' require 'awsum/s3/bucket' require 'awsum/s3/object' require 'awsum/s3/headers' module Awsum # Handles all interaction with Amazon S3 # #-- # TODO: Change this to S3 # ==Getting Started # Create an Awsum::Ec2 object and begin calling methods on it. # require 'rubygems' # require 'awsum' # ec2 = Awsum::Ec2.new('your access id', 'your secret key') # images = ec2.my_images # ... # # All calls to EC2 can be done directly in this class, or through a more # object oriented way through the various returned classes # # ==Examples # ec2.image('ami-ABCDEF').run # # ec2.instance('i-123456789').volumes.each do |vol| # vol.create_snapsot # end # # ec2.regions.each do |region| # region.use # images.each do |img| # puts "#{img.id} - #{region.name}" # end # end # end # # ==Errors # All methods will raise an Awsum::Error if an error is returned from Amazon # # ==Missing Methods # If you need any of this functionality, please consider getting involved # and help complete this library. class S3 include Awsum::Requestable # Create an new S3 instance # # The access_key and secret_key are both required to do any meaningful work. # # If you want to get these keys from environment variables, you can do that # in your code as follows: # s3 = Awsum::S3.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']) def initialize(access_key = nil, secret_key = nil) @access_key = access_key @secret_key = secret_key end # List all the Bucket(s) def buckets response = send_s3_request parser = Awsum::S3::BucketParser.new(self) parser.parse(response.body) end def bucket(name) Bucket.new(self, name) end # Create a new Bucket # # ===Parameters # * <tt>bucket_name</tt> - The name of the new bucket # * <tt>location</tt> <i>(optional)</i> - Can be <tt>:default</tt>, <tt>:us</tt> or <tt>:eu</tt> def create_bucket(bucket_name, location = :default) raise ArgumentError.new('Bucket name cannot be in an ip address style') if bucket_name =~ /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/ raise ArgumentError.new('Bucket name can only have lowercase letters, numbers, periods (.), underscores (_) and dashes (-)') unless bucket_name =~ /^[\w\d][-a-z\d._]+[a-z\d._]$/ raise ArgumentError.new('Bucket name cannot contain a dash (-) next to a period (.)') if bucket_name =~ /\.-|-\./ raise ArgumentError.new('Bucket name must be between 3 and 63 characters') if bucket_name.size < 3 || bucket_name.size > 63 data = nil if location == :eu data = '<CreateBucketConfiguration><LocationConstraint>EU</LocationConstraint></CreateBucketConfiguration>' end response = send_s3_request('PUT', :bucket => bucket_name, :data => data) response.is_a?(Net::HTTPSuccess) end def delete_bucket(bucket_name) response = send_s3_request('DELETE', :bucket => bucket_name) response.is_a?(Net::HTTPSuccess) end # List the Key(s) of a Bucket # # ===Parameters # * <tt>bucket_name</tt> - The name of the bucket to search for keys # ====Options # * <tt>:prefix</tt> - Limits the response to keys which begin with the indicated prefix. You can use prefixes to separate a bucket into different sets of keys in a way similar to how a file system uses folders. # * <tt>:marker</tt> - Indicates where in the bucket to begin listing. The list will only include keys that occur lexicographically after marker. This is convenient for pagination: To get the next page of results use the last key of the current page as the marker. # * <tt>:max_keys</tt> - The maximum number of keys you'd like to see in the response body. The server might return fewer than this many keys, but will not return more. # * <tt>:delimeter</tt> - Causes keys that contain the same string between the prefix and the first occurrence of the delimiter to be rolled up into a single result element in the CommonPrefixes collection. These rolled-up keys are not returned elsewhere in the response. def keys(bucket_name, options = {}) paramters = {} paramters['prefix'] = options[:prefix] if options[:prefix] paramters['marker'] = options[:marker] if options[:marker] paramters['max_keys'] = options[:max_keys] if options[:max_keys] paramters['prefix'] = options[:prefix] if options[:prefix] response = send_s3_request('GET', :bucket => bucket_name, :paramters => paramters) parser = Awsum::S3::ObjectParser.new(self) parser.parse(response.body) end # Create a new Object in the specified Bucket # # ===Parameters # * <tt>bucket_name</tt> - The name of the Bucket in which to store the Key # * <tt>key</tt> - The name/path of the Key to store # * <tt>data</tt> - The data to be stored in this Object # * <tt>headers</tt> - Standard HTTP headers to be sent along # * <tt>meta_headers</tt> - Meta headers to be stored along with the key # * <tt>acl</tt> - A canned access policy, can be one of <tt>:private</tt>, <tt>:public_read</tt>, <tt>:public_read_write</tt> or <tt>:authenticated_read</tt> def create_object(bucket_name, key, data, headers = {}, meta_headers = {}, acl = :private) headers = headers.dup meta_headers.each do |k,v| headers[k =~ /^x-amz-meta-/i ? k : "x-amz-meta-#{k}"] = v end headers['x-amz-acl'] = acl.to_s.gsub(/_/, '-') response = send_s3_request('PUT', :bucket => bucket_name, :key => key, :headers => headers, :data => data) response.is_a?(Net::HTTPSuccess) end # Retrieve the headers for this Object # # All header methods map directly to the Net::HTTPHeader module def object_headers(bucket_name, key) response = send_s3_request('HEAD', :bucket => bucket_name, :key => key) Headers.new(response) end # Retrieve the data stored for the specified Object # # You can get the data as a single call or add a block to retrieve the data in chunks # ==Examples # data = s3.object_data('test-bucket', 'key') # # or # # s3.object_data('test-bucket', 'key') do |chunk| # # handle chunk # puts chunk # end def object_data(bucket_name, key, &block) send_s3_request('GET', :bucket => bucket_name, :key => key) do |response| if block_given? response.read_body &block return true else return response.body end end end # Deletes an Object from a Bucket def delete_object(bucket_name, key) response = send_s3_request('DELETE', :bucket => bucket_name, :key => key) response.is_a?(Net::HTTPSuccess) end # Copy the contents of an Object to another key and/or bucket # # ===Parameters # * <tt>source_bucket_name</tt> - The name of the Bucket from which to copy # * <tt>source_key</tt> - The name of the Key from which to copy # * <tt>destination_bucket_name</tt> - The name of the Bucket to which to copy (Can be nil if copying within the same bucket, or updating header data of existing Key) # * <tt>destination_key</tt> - The name of the Key to which to copy (Can be nil if copying to a new bucket with same key, or updating header data of existing Key) # * <tt>headers</tt> - If not nil, the headers are replaced with this information # * <tt>meta_headers</tt> - If not nil, the meta headers are replaced with this information # #-- # TODO: Need to handle copy-if-... headers def copy_object(source_bucket_name, source_key, destination_bucket_name = nil, destination_key= nil, headers = nil, meta_headers = nil) raise ArgumentError.new('You must include one of destination_bucket_name, destination_key or headers to be replaced') if destination_bucket_name.nil? && destination_key.nil? && headers.nil? && meta_headers.nil? headers = { 'x-amz-copy-source' => "/#{source_bucket_name}/#{source_key}", 'x-amz-metadata-directive' => (((destination_bucket_name.nil? && destination_key.nil?) || !(headers.nil? || meta_headers.nil?)) ? 'REPLACE' : 'COPY') }.merge(headers||{}) meta_headers.each do |k,v| headers[k =~ /^x-amz-meta-/i ? k : "x-amz-meta-#{k}"] = v end unless meta_headers.nil? destination_bucket_name ||= source_bucket_name destination_key ||= source_key response = send_s3_request('PUT', :bucket => destination_bucket_name, :key => destination_key, :headers => headers, :data => nil) if response.is_a?(Net::HTTPSuccess) #Check for delayed error (See http://docs.amazonwebservices.com/AmazonS3/2006-03-01/RESTObjectCOPY.html#RESTObjectCOPY_Response) response_body = response.body if response_body =~ /<Error>/i raise Awsum::Error.new(response) else true end end end #private #The host to make all requests against def host @host ||= 's3.amazonaws.com' end def host=(host) @host = host end end end
true
4a3d9db963fefb8498aee802f34f4920ca37235f
Ruby
sol-vin/pixesoteric
/p_thread.rb
UTF-8
3,845
3.453125
3
[]
no_license
require_relative './memory_wheel' # Single thread for an instruction reader and executor. class PThread # parent of the thread, should be a machine attr_reader :parent # 2d array of instructions, is of type Instructions attr_reader :position_x, :position_y # direction of travel attr_reader :direction # memory wheel attr_reader :memory_wheel # stages for mathematical operations attr_accessor :stage_1, :stage_2 # is the thread paused? attr_reader :paused # how many more cycles should the thread pause for attr_reader :paused_counter # has the thread ended? attr_reader :ended # the identity of the thread, given by the parent machine attr_reader :id # clockwise list of instructions DIRECTIONS = [:up, :right, :down, :left] def initialize(parent, position_x, position_y, direction) @parent = parent @position_x = position_x @position_y = position_y @direction = direction @paused = false @paused_counter = 0 @ended = false @id = parent.make_id reset end # resets memory def reset @memory_wheel = MemoryWheel.new @stage_1 = 0 @stage_2 = 0 end def clone thread = PThread.new(parent, position_x, position_y, direction) thread.instance_variable_set('@memory_wheel', memory_wheel.clone) thread end # runs a single instruction and moves def run_one_instruction if paused @paused_counter -= 1 parent.log.debug "^ T#{id} C:#{parent.cycles} is paused for #{@paused_counter} cycles" if @paused_counter <= 0 parent.log.debug "^ T#{id} is unpaused" unpause end return end instruction = parent.instructions.get_instruction(position_x, position_y) parent.log.info "T#{id} C:#{parent.cycles} Running #{instruction.class} @ #{position_x}, #{position_y} CV: #{instruction.color_value.to_s 16}" instruction.run(self, instruction.color_value) parent.log.debug '^ Thread state:' parent.log.debug "^ mw:#{memory_wheel.to_s}" parent.log.debug "^ s_1:#{stage_1}" parent.log.debug "^ s_2:#{stage_2}" parent.log.debug "^ d:#{direction}" parent.log.debug '^ Machine state:' parent.log.debug "^ static: #{parent.memory}" parent.log.debug "^ output: #{parent.output}" parent.log.debug "^ input: #{parent.input}" #move unless we called here recently. move 1 unless instruction.class == Call end # change the direction def change_direction(direction) throw ArgumentError.new unless DIRECTIONS.include? direction @direction = direction end # turns the thread left def turn_right index = DIRECTIONS.index(direction) + 1 index = 0 if index >= DIRECTIONS.length change_direction(DIRECTIONS[index]) end # turns the thread right def turn_left index = DIRECTIONS.index(direction) - 1 index = DIRECTIONS.length-1 if index < 0 change_direction(DIRECTIONS[index]) end # reverses the thread def reverse turn_left turn_left end # moves the instruction cursor amount units in a direction def move(amount) case direction when :up @position_y -= amount when :down @position_y += amount when :left @position_x -= amount when :right @position_x += amount else throw ArgumentError.new end end # jumps to a relative position def jump(x, y) @position_x += x @position_y += y end # pauses the thread for a certain amount of cycles def pause(cycles) @paused = true @paused_counter = cycles end # unpause the thread def unpause @paused = false @paused_counter = 0 end # kill the thread def kill @ended = true end alias_method :paused?, :paused alias_method :ended?, :ended alias_method :killed?, :ended end
true
a18abd604a046b5959a7c8e84be304273e89d9da
Ruby
JRRHarper/class_project1
/danger_pets.rb
UTF-8
335
2.84375
3
[]
no_license
class DangerPets attr_reader :name, :species, :price, :danger_level def initialize( name, species, price, danger_level) @name = name @species = species @price = price @danger_level = danger_level end # def danger_test # for pet in @pets # for key, value in pet # return key if value > # end end
true
166f5831da4b94d3cb24e6b1b8bbe728e4f7bbc1
Ruby
adamliesko/sng-histogram
/lib/tasks/computing.rake
UTF-8
1,278
2.703125
3
[ "MIT" ]
permissive
namespace :computing do task :compute_histograms => :environment do Artist.find_each do |artist| color_counts = Hash.new { |hash, key| hash[key] = 0 } global_histogram = Hash.new { |hash, key| hash[key] = 0 } artist.records.each do |record| record.histogram.each do |color, value| if value > 0 color_counts[color] += 1 global_histogram[color] += value end end end global_histogram.each do |color, value| if color_counts[color] != 0 avg = value / color_counts[color] sum = 0 global_histogram.each_value { |v| sum+= v } puts "avg #{avg}" puts "sum #{sum}" global_histogram[color] = avg.to_f / sum * 100 end end era = Era.new(artist_id: artist.id, date_from: nil, date_to: nil, histogram: global_histogram.map { |k, v| {"color" => k, "value" => v} }) if era.save puts era else puts "Error on:\n artist:#{artist.name}\n - #{record.id}" end end end task :dominant_color => :environment do Artist.find_each do |artist| artist.dominant_color=artist.compute_dominant_color puts artist.dominant_color artist.save end end end
true
76c24a9c5349848ca702c7bab84673f9c237acf3
Ruby
miguelnietoa/ruby-basics
/13-HashesII/merge_method_to_combine_hashes.rb
UTF-8
479
3.59375
4
[]
no_license
market = {garloc: "3 cloves", tomatoes: "5 batches", milk: "10 galons"} kitchen = {bread: "2 loaves", yogurt: "20 cans", milk: "100 galons"} # If there are keys in common, .merge will preserve ones of second hash p market.merge(kitchen) p kitchen.merge(market) # Bang method is available: .merge! # --- def custom_merge(hash1, hash2) output = hash1.dup hash2.each { |key, value| output[key] = value } output end puts p custom_merge(market, kitchen) p market p kitchen
true
84604ca550c35136621a073bc6521ecc668ff063
Ruby
Barendan/IH_exercises
/Week2/Monday/TodoList/lib/todo_list.rb
UTF-8
528
3
3
[]
no_license
class TodoList attr_reader :tasks attr_reader :user def initialize(user) @tasks = [] @user = user end def add_task(new_task) @tasks.push(new_task) end def delete_task(task_id) @tasks.delete_if do |task| task.id == task_id end end def find_task_by_id(task_id) @tasks.find { |task| task.id == task_id } end def sort_by_created sorted_time = @tasks.sort { | task1, task2 | task1.created_at <=> task2.created_at } end end
true
aad8161a008c6275637a6eff824fc80cab3f09f3
Ruby
carlhuda/thor
/spec/parser/option_spec.rb
UTF-8
5,881
2.78125
3
[ "MIT" ]
permissive
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') require 'thor/parser' describe Thor::Option do def parse(key, value) Thor::Option.parse(key, value) end def option(name, description=nil, required=false, type=nil, default=nil, banner=nil, group=nil, aliases=[]) @option ||= Thor::Option.new(name, description, required, type, default, banner, group, aliases) end describe "#parse" do describe "with value as a symbol" do describe "and symbol is a valid type" do it "has type equals to the symbol" do parse(:foo, :string).type.must == :string parse(:foo, :numeric).type.must == :numeric end it "has not default value" do parse(:foo, :string).default.must be_nil parse(:foo, :numeric).default.must be_nil end end describe "equals to :required" do it "has type equals to :string" do parse(:foo, :required).type.must == :string end it "has no default value" do parse(:foo, :required).default.must be_nil end end describe "equals to :optional" do it "has type equals to :boolean" do capture(:stderr){ parse(:foo, :optional).type.must == :boolean } end it "has no default value" do capture(:stderr){ parse(:foo, :optional).default.must be_nil } end end describe "and symbol is not a reserved key" do it "has type equals to :string" do parse(:foo, :bar).type.must == :string end it "has no default value" do parse(:foo, :bar).default.must be_nil end end end describe "with value as hash" do it "has default type :hash" do parse(:foo, :a => :b).type.must == :hash end it "has default value equals to the hash" do parse(:foo, :a => :b).default.must == { :a => :b } end end describe "with value as array" do it "has default type :array" do parse(:foo, [:a, :b]).type.must == :array end it "has default value equals to the array" do parse(:foo, [:a, :b]).default.must == [:a, :b] end end describe "with value as string" do it "has default type :string" do parse(:foo, "bar").type.must == :string end it "has default value equals to the string" do parse(:foo, "bar").default.must == "bar" end end describe "with value as numeric" do it "has default type :numeric" do parse(:foo, 2.0).type.must == :numeric end it "has default value equals to the numeric" do parse(:foo, 2.0).default.must == 2.0 end end describe "with value as boolean" do it "has default type :boolean" do parse(:foo, true).type.must == :boolean parse(:foo, false).type.must == :boolean end it "has default value equals to the boolean" do parse(:foo, true).default.must == true parse(:foo, false).default.must == false end end describe "with key as a symbol" do it "sets the name equals to the key" do parse(:foo, true).name.must == "foo" end end describe "with key as an array" do it "sets the first items in the array to the name" do parse([:foo, :bar, :baz], true).name.must == "foo" end it "sets all other items as aliases" do parse([:foo, :bar, :baz], true).aliases.must == [:bar, :baz] end end end it "returns the switch name" do option("foo").switch_name.must == "--foo" option("--foo").switch_name.must == "--foo" end it "returns the human name" do option("foo").human_name.must == "foo" option("--foo").human_name.must == "foo" end it "converts underscores to dashes" do option("foo_bar").switch_name.must == "--foo-bar" end it "can be required and have default values" do option = option("foo", nil, true, :string, "bar") option.default.must == "bar" option.must be_required end it "cannot be required and have type boolean" do lambda { option("foo", nil, true, :boolean) }.must raise_error(ArgumentError, "An option cannot be boolean and required.") end it "allows type predicates" do parse(:foo, :string).must be_string parse(:foo, :boolean).must be_boolean parse(:foo, :numeric).must be_numeric end it "raises an error on method missing" do lambda { parse(:foo, :string).unknown? }.must raise_error(NoMethodError) end describe "#usage" do it "returns usage for string types" do parse(:foo, :string).usage.must == "[--foo=FOO]" end it "returns usage for numeric types" do parse(:foo, :numeric).usage.must == "[--foo=N]" end it "returns usage for array types" do parse(:foo, :array).usage.must == "[--foo=one two three]" end it "returns usage for hash types" do parse(:foo, :hash).usage.must == "[--foo=key:value]" end it "returns usage for boolean types" do parse(:foo, :boolean).usage.must == "[--foo]" end it "uses padding when no aliases is given" do parse(:foo, :boolean).usage(4).must == " [--foo]" end it "uses banner when supplied" do option(:foo, nil, false, :string, nil, "BAR").usage.must == "[--foo=BAR]" end it "checkes when banner is an empty string" do option(:foo, nil, false, :string, nil, "").usage.must == "[--foo]" end describe "with required values" do it "does not show the usage between brackets" do parse(:foo, :required).usage.must == "--foo=FOO" end end describe "with aliases" do it "does not show the usage between brackets" do parse([:foo, "-f", "-b"], :required).usage.must == "-f, -b, --foo=FOO" end end end end
true
915af428332a37a931bb8e89571aecc8ba5d8bca
Ruby
rajeshvyas2005/react-on-rails-tutorial
/lib/ruby_syntax/table_loop.rb
UTF-8
128
3
3
[]
no_license
#!/bin/ruby n = gets.strip.to_i (1..10).each_with_index do | country, index | puts "#{n} x #{index+1} = #{n*(index+1)}" end
true
9d04fd6db4cdc00fc438b10a50796320783b4cba
Ruby
dmagliola/maze_experiment
/app/models/maze_cell.rb
UTF-8
876
3.90625
4
[]
no_license
class MazeCell attr_accessor :coords attr_accessor :visited attr_accessor :neighbours attr_accessor :walls def initialize(x, y, maze_size) @coords = [x, y] @visited = false # Initialize the neighbors @neighbours = [] @neighbours << left unless x <= 0 @neighbours << up unless y <= 0 @neighbours << right unless x >= maze_size - 1 @neighbours << down unless y >= maze_size - 1 # Start with walls in every direction @walls = @neighbours.dup end def accessible_neighbours @neighbours - @walls end def can_walk?(direction) accessible_neighbours.include?(self.send(direction)) end def up [@coords.first, @coords.last - 1] end def down [@coords.first, @coords.last + 1] end def left [@coords.first - 1, @coords.last] end def right [@coords.first + 1, @coords.last] end end
true
617fae2915dd4ea79d03e87b4fdec628bab2d026
Ruby
ttscott2/programming_foundations
/lesson_3/easy1.rb
UTF-8
478
3.875
4
[]
no_license
#Question 1 # the code will print out the original numbers array. The uniq method is not destructive. # Question 2 # != is "not equals" # used before a variable, ! means "not"; used after a variable, it usually indicates a destructive method. # Question 5 range = (10..100) range_array = range.to_a if range_array.include?(42) puts "42 is in the range" end # Question 9 flintstones = { "Fred": 0, "Wilma": 1, "Barney": 2, "Betty": 3, "BamBam": 4, "Pebbles": 5 }
true
d8b2bf50ba21bf7e2fed423e4e85607a274e05c3
Ruby
rsupak/tc-challenges
/DoubleLinkedList/double_linked_list/lib/double_linked_list.rb
UTF-8
1,433
3.671875
4
[]
no_license
# Node class for Double Linked List class Link attr_accessor :key, :val, :nxt, :prev def initialize(key = nil, val = nil, nxt = nil, prev = nil) @key, @val, @nxt, @prev = key, val, nxt, prev end def to_s "#{@key}, #{@val}" end end # Main Class class DoubleLinkedList attr_accessor :head, :tail, :length include Enumerable def initialize @head = Link.new(0) @tail = @head @length = 0 end # sets item value at the index(key) def []=(key, value) current = @head until current.key == key @tail = @tail.nil? ? current.nxt : current current.nxt = current.nxt.nil? ? Link.new(current.key + 1, nil, nil, current) : current.nxt current = current.nxt end @tail = current if current.nxt.nil? current.val = value @length += 1 end # returns the value from the list at the given index def [](i) each_with_index { |link, j| return link if i == j } nil end # returns the value of the first item in the list def first @head.val end # returns the value of the last item in the list def last @tail.val end # iterates over each item in the list def each current = @head until current.nil? yield current.val current = current.nxt end end end # test block if $PROGRAM_NAME == __FILE__ list = DoubleLinkedList.new list[0] = 1 list[1] = 2 list[2] = 3 list.each { |link| puts link } end
true
a8dd57a13b776af9eab9dd73cf6e90772a44108d
Ruby
bexfinken/phase-0-tracks
/ruby/classy house/house.rb
UTF-8
520
3.203125
3
[]
no_license
# # Build a house out of classes # HOUSE CLASS (A HOUSE IS MADE OF ROOMS, ROOMS OUT OF ITEMS) # Attributes: # - rooms (a collection of Room instances) # Methods: # - getter for rooms # - add_room (only allows up to 10 rooms) # - square_footage (adds up the house's square footage and returns it as an integer) # - total_value (adds up value of items in all rooms) # - to_s override # We are going to combine objects in different ways # Each class is going to get its own file (more professionally typical)
true
b796ab1c9a9bbb19cf31a6d9ea9426723396e3bb
Ruby
codacy20/RubyExercism
/rna-transcription/rna_transcription.rb
UTF-8
662
3.0625
3
[ "MIT" ]
permissive
class Complement def self.of_dna(item = '') arr2 = ['G', 'C', 'T', 'A'] answer = [] unless item == '' count = item.length for i in 0...count if arr2.include?(item[i]) case item[i] when 'G' answer[i] = 'C' when 'C' answer[i] = 'G' when 'T' answer[i] = 'A' when 'A' answer[i] = 'U' end else return '' end end end return answer.join('') end end module BookKeeping VERSION = 4 # Where the version number matches the one in the test. end
true
a2429492f38c2a0c9c98d15f76060bfbe6d1de89
Ruby
jakef203/RB101-ProgrammingFoundations
/Exercises/Easy5/bannerizer.rb
UTF-8
2,447
3.71875
4
[]
no_license
# def print_in_box(string) # length = string.length # print_horizontal_border(length) # print_inside_blank_line(length) # puts "| #{string} |" # print_inside_blank_line(length) # print_horizontal_border(length) # end # def print_horizontal_border(length) # puts "+#{'-' * (length + 2)}+" # end # def print_inside_blank_line(length) # puts "|#{' ' * (length + 2)}|" # end ## Their solution, much easier to read # def print_in_box(message) # horizontal_rule = "+#{'-' * (message.size + 2)}+" # empty_line = "|#{' ' * (message.size + 2)}|" # puts horizontal_rule # puts empty_line # puts "| #{message} |" # puts empty_line # puts horizontal_rule # end # require 'pry' def print_in_box(message, column_width) # if message.length > 76 #truncated message if # message = message[0..75] # end horizontal_rule = "+#{'-' * (column_width-2)}+" blank_line = "|#{' ' * (column_width-2)}|" message_lines = [] message_remaining = message message_width = column_width - 4 loop do if message_remaining.length <= (message_width) message_lines << message_remaining # binding.pry break elsif message_remaining[message_width-1] == ' ' message_lines << message_remaining[0..(message_width-1)] message_remaining = message_remaining[message_width..-1] # binding.pry elsif message_remaining[message_width] == ' ' message_lines << message_remaining[0..message_width-1] message_remaining = message_remaining[message_width+1..-1] else i = message_width - 2 loop do break if message_remaining[i] == ' ' i -= 1 end message_lines << message_remaining[0..i] message_remaining = message_remaining[i+1..-1] # binding.pry end end puts horizontal_rule puts blank_line message_lines.each { |line| puts "| #{line.ljust(message_width, ' ')} |" } puts blank_line puts horizontal_rule end # print_in_box('To boldly go where no one has gone before.') # print_in_box('') print_in_box("0123456789 0123456789 0123456789 0123456789 0123456789 0123456 0123456789" + " Hot dog sandwiches are the best thing ever man, I mean yeah I don't know a lot" + "of stuff but in the end you can't really be too sure about what's going on around town" + "and why we do what we do, it's just pure chaos. I don't know man.", 80) # puts " 01234567890123456789 "
true
6d70cdd84d19a65a1b29c60b9656157e674b9378
Ruby
ericovinicosta/pdti-ruby-respostas-exercicio04
/resposta06.rb
UTF-8
798
3.546875
4
[]
no_license
=begin Faça um Programa que peça as quatro notas de 10 alunos, calcule e armazene num vetor a média de cada aluno, imprima o número de alunos com média maior ou igual a 7.0. =end dados_alunos = [] (1..10).each do |i| print "Informe o nome do aluno #{i}: " nome = gets.chomp notas = [] #solicitaçao de notas (1..4).each do |j| print "Informa a #{j} nota: " notas << gets.to_f end media = notas.sum / notas.length aluno = { "nome" => nome, "notas" => notas, "media" => media } dados_alunos << aluno end aluno_aprovados = [] dados_alunos.each do |aluno| aluno.each do | key, value | if (key == "media" and value >= 7.0) aluno_aprovados << aluno end end end puts aluno_aprovados puts "Foram aprovados #{aluno_aprovados.length}"
true
3ac225adf389df8296c35fed17877629b1834b08
Ruby
ismcodes/nwrun
/app/models/event_manager.rb
UTF-8
392
2.578125
3
[]
no_license
class EventManager < ActiveRecord::Base belongs_to :runner before_create :zero_all def zero_all self.mean = self.stdev = self.number_races = 0 end def update_stats race_time self.mean = (self.mean * self.number_races + race_time) / (self.number_races + 1).to_f #puts "#{self.mean} #{race_time} #{self.number_races}" self.number_races += 1 save #??? end end
true
488b0c6f0591c02f0ff05af4e1890fc418adc02f
Ruby
kirizawa/webtrends_api_parser
/lib/wt_api_extract.rb
UTF-8
796
2.5625
3
[]
no_license
require 'net/http' require 'net/https' def query(account, username, password, query) # puts account # puts username # puts password # puts query hostname = "ws.webtrends.com" https = Net::HTTP.new(hostname, Net::HTTP.https_default_port) https.use_ssl = true https.ca_file = "/usr/share/curl/curl-ca-bundle.crt" resp = https.start { |http| request = Net::HTTP::Get.new("/v2/ReportService/" + query) request.basic_auth account + '\\' + username, password res = http.request(request) case res when Net::HTTPSuccess, Net::HTTPRedirection return res.body else res.error! end } end
true
972cc260e756094d6ede53e7661d24933d1b2f75
Ruby
stephan-dev/MVC_THP_Next_s01
/app/models/item.rb
UTF-8
741
2.859375
3
[]
no_license
# frozen_string_literal: true # == Schema Information # # Table name: items # # id :bigint(8) not null, primary key # original_price :float not null # has_discount :boolean default(FALSE) # discount_percentage :integer default(0) # created_at :datetime not null # updated_at :datetime not null # class Item < ApplicationRecord def price return original_price unless has_discount # calculate discount without setting discount_percentage to float (original_price * (100 - discount_percentage )) / 100 end def self.average_price sum = 0 Item.all.map{ |item| sum += item.price } sum / Item.count end end
true
23fbdff7062ff4abdbbf5511bfd06eee5577ded8
Ruby
dallinder/ls_small_pbs_round2
/easy_5/1.rb
UTF-8
108
3.109375
3
[]
no_license
def ascii_value(string) string.chars.map { |char| char.ord }.inject(:+) end p ascii_value('Four score')
true
34240a984de66d60b66485de6dbeaf80cda8a169
Ruby
eriksk/kawaii
/lib/kawaii/physics_manager.rb
UTF-8
968
2.84375
3
[ "MIT" ]
permissive
require 'chipmunk' module Kawaii class PhysicsManager attr_accessor :space, :entities SUBSTEPS = 10 def initialize @space = CP::Space.new @space.gravity = CP::Vec2.new(0, 5) @entities = [] end def add_static_physics_entity entity if entity.class == PhysicsEntity @entities.push entity entity.add_static_to_space @space else raise WrongTypeError, "Only PhysicsEntity and derivatives are accepted" end end def add_physics_entity entity if entity.class == PhysicsEntity @entities.push entity entity.add_to_space @space else raise WrongTypeError, "Only PhysicsEntity and derivatives are accepted" end end def remove_physics_entity entity @entities.delete entity entity.remove_from_space @space end def update dt SUBSTEPS.times do @space.step(dt / 1000.0) @entities.each do |entity| entity.body.reset_forces end end end end end
true
04807846c87e28aa5c87a1f7a6e95abc81883232
Ruby
shiryu92/metafuzz
/src/word_fuzzbot/debug_server.rb
UTF-8
1,394
2.5625
3
[]
no_license
require File.dirname(__FILE__) + '/../core/connector' require File.dirname(__FILE__) + '/conn_cdb' require 'rubygems' require 'msgpack/rpc' require 'trollop' OPTS=Trollop::options do opt :port, "Port to listen on, default 8888", :type=>:integer, :default=>8888 opt :debug, "Debug output", :type=>:boolean end class DebugServer COMPONENT="MsgpackDebugServer" VERSION="1.5.0" def start_debugger( *args ) @debugger_conn=Connector.new( CONN_CDB, *args ) warn "#{COMPONENT}:#{VERSION}: Started #{@debugger_conn.debugger_pid} for #{args[0]['pid']}" if OPTS[:debug] true end def close_debugger @debugger_conn.close if @debugger_conn warn "#{COMPONENT}:#{VERSION}: Closing #{@debugger_conn.debugger_pid rescue "<no debugger>"}" if OPTS[:debug] true end def shim( meth, *args ) warn "#{COMPONENT}:#{VERSION}: Shimming #{meth}" if OPTS[:debug] @debugger_conn.send( meth, *args ) end def destroy begin warn "#{COMPONENT}:#{VERSION}: Received destroy. Exiting." if OPTS[:debug] close_debugger rescue nil rescue puts $! ensure Process.exit! end end end server=MessagePack::RPC::Server.new server.listen('127.0.0.1', OPTS[:port], DebugServer.new) server.run
true
cf877700f7e0448735c09e1d983bc06a2c07171a
Ruby
genericlady/design_patterns
/chapter01_strategy/interface/ruby/duck_sim/lib/fly_with_wings.rb
UTF-8
62
2.65625
3
[]
no_license
class FlyWithWings def fly puts "I'm flying!" end end
true
a8783df0723ab0cf9f9f25fbe141a1981f17be96
Ruby
craigem/LearnRubyTheHardWay
/ex19.rb
UTF-8
2,276
4.4375
4
[]
no_license
# Defines the function cheese_and_crackers def cheese_and_crackers(cheese_count, boxes_of_crackers) # Prints the text and the value ot cheese_count to STDOUT puts "You have #{cheese_count} cheeses!" # Prints the text and the value ot boxes_of_crackers to STDOUT puts "You have #{boxes_of_crackers} boxes of crackers!" # Prints the text STDOUT puts "Man that's enough for a party!" # Prints the text STDOUT puts "Get a blanket.\n" end # Prints the text STDOUT puts 'We can just give the function numbers directly:' # Calls the named function and sets two argument values cheese_and_crackers(20, 30) # Prints the text STDOUT puts 'OR, we can use variables from our script:' # Set the value of the varialble amount_of_cheese = 10 # Set the value of the varialble amount_of_crackers = 50 # Calls the function and uses the variables set earlier as arguments cheese_and_crackers(amount_of_cheese, amount_of_crackers) # Prints the text STDOUT puts 'We can even do the math inside too:' # Calls the function and sets the arguments to the value of the equations cheese_and_crackers(10 + 20, 5 + 6) # Prints the text STDOUT puts 'And we can combine the two, variables and math:' # Calls the function and sets the arguments to the value of the equations cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000) # 3 Write at least one more function of your own design, and run it 10 different # ways. def my_own_design(pants, style, reggies) puts "\nIt appears you #{pants} wearing pants. Good on you!" puts "They look like #{style}. Nice work. You carry it off." puts "Oh, you #{reggies} wearing reggies. That's possibly too much \ information." puts "You're going to stop traffic." end puts "\n1. Calling it directly:" my_own_design('are', 'footy shorts', 'are not') puts "\n2. Adding Stings:" my_own_design('are' + ' ' + 'not', 'naked', 'are' + ' ' + 'not') puts "\n3. Using Variables:" pants = 'are' style = "fisherman's pants" reggies = 'are not' my_own_design(pants, style, reggies) puts "\n4. Calling for input:" print 'Are you wearin pants?: ' pants = $stdin.gets.chomp print 'What style of pants?: ' style = $stdin.gets.chomp print 'Are you wearing reggies?: ' reggies = $stdin.gets.chomp my_own_design(pants, style, reggies)
true
a719509b36f4bbd8684a57d6cceee20a01294674
Ruby
bcasadei/hangman
/hangman.rb
UTF-8
4,356
3.734375
4
[]
no_license
require 'yaml' # Word class defines a random word for the game. class Word def random contents = File.open('5desk.txt', 'r').read array = contents.split.select { |word| word.size > 4 && word.size < 13 } array.sample(1).join.downcase end end # Player class defines player's information class Player attr_reader :name def initialize choose_name end def choose_name loop do puts "What's your name?" @name = gets.chomp.strip break unless name.empty? puts "Sorry that's not a valid choice." end end end # Game class defines the game's functionality class Game def initialize @word = Word.new.random.chars @player = Player.new @missed_letters = [] @correct_letters = [] end def display_welcome_message puts "\nHi #{@player.name}, Welcome to Hangman!" end def start display_intro loop do display_save_message guess display_word display_missed_letters display_winner if winner? break if winner? || loser? end end def display_intro display_welcome_message display_load_message display_word check_score end def guess player_guess clear check_guess end def clear system 'clear' end def display_word result = @word.map do |char| if @correct_letters.include?(char) char else '_' end end puts "Your word has #{@word.size} letters. Good luck!\n" puts result.join(' ') end def display_missed_letters puts "\nMissed Letters: #{@missed_letters.join(', ')}" end def check_score case @missed_letters.size when 1 puts "Your head is on the hangman's noose!" when 2 puts "Your body is on the hangman's noose!" when 3 puts "Your right arm is on the hangman's noose!" when 4 puts "Your left arm is on the hangman's noose!" when 5 puts "Your right leg is on the hangman's noose!" when 6 puts "Game over! The word was #{@word.join}." else puts "The hangman is ready for you #{@player.name}!" end end def player_guess loop do puts "\nChoose a letter!" @guess = gets.chomp.downcase break unless @guess.empty? || @guess.size > 1 || @guess =~ /[0-9\s]/ puts "Sorry that's not a valid choice." end end def check_guess if @correct_letters.include?(@guess) || @missed_letters.include?(@guess) puts "You've already guessed (#{@guess})." elsif @word.include?(@guess) @word.each { |char| @correct_letters << char if char == @guess } puts 'Correct!' else @missed_letters << @guess puts 'Sorry, that letter is not in the word.' end end def display_winner puts "Congratulations #{@player.name}, you won! You are free to go." end def winner? return true if @correct_letters.size == @word.size end def loser? return true if @missed_letters.size == 6 end def display_save_message loop do puts 'Would you like to save your game? (y/n)' answer = gets.chomp.downcase if answer.include?('y') save break elsif answer.include?('n') break else puts "That's an invalid choice please enter (y/n)." end end end def save file_name = "#{@player.name}.yaml" data = { 'word' => @word, 'player' => @player, 'missed_letters' => @missed_letters, 'correct_letters' => @correct_letters } File.open(file_name, 'w') do |file| file.write(data.to_yaml) end puts 'Your game has been saved.' end def display_load_message loop do break unless File.exist?("#{@player.name}.yaml") puts 'Would you like load your previous game? (y/n)' answer = gets.chomp.downcase if answer.include?('y') clear load display_missed_letters break elsif answer.include?('n') break else puts "That's an invalid choice please enter (y/n)." end end end def load file_name = "#{@player.name}.yaml" File.open(file_name, 'r') do |file| data = YAML.load file data.keys.each do |key| instance_variable_set("@#{key}", data[key]) end end puts 'Your previous game has been loaded!' end end Game.new.start
true
07827422f611de134f854617ce64fbd22182cac1
Ruby
KarlHarnois/task_cli
/lib/task_cli/deserializers/task_deserializer.rb
UTF-8
277
2.625
3
[ "MIT" ]
permissive
require 'json' require_relative '../models/task' class TaskCli class TaskDeserializer def initialize(json) @json = JSON.parse(json) end def to_item Task.new(@json) end def to_list @json.map { |json| Task.new(json) } end end end
true
f8f3a9da0890a850e40c40b3c4c1ac52baea88e1
Ruby
pharaonick/ls_101
/ex/easy8/middle_char.rb
UTF-8
634
4.34375
4
[]
no_license
# input: non-empty str # output: return middle char if str odd length, middle 2 if even # -- 1 char, return that char def center_of(str) if str.length.odd? str[str.length / 2] else str[str.length / 2 - 1, 2] # this sets length of 2 char from position end end # might be better to set length variable but w/e # can use String#slice rather than [] # can also make use of the fact that with odd-sized strings, the result of # size/2 and (size-1)/2 will be the same... center_of('I love ruby') == 'e' center_of('Launch School') == ' ' center_of('Launch') == 'un' center_of('Launchschool') == 'hs' center_of('x') == 'x'
true
29187505443b3b3fb90043222e367bbb3252fe0e
Ruby
wainhudec88/escuchat
/vendor/plugins/attr_encrypted/lib/huberry/attr_encrypted/default_encryptor.rb
UTF-8
834
2.53125
3
[ "MIT" ]
permissive
module Huberry module AttrEncrypted class DefaultEncryptor require 'openssl' def self.encrypt(value, key, options = {}) crypt 'encrypt', value, key, options end def self.decrypt(value, key, options = {}) crypt 'decrypt', value, key, options end protected def self.crypt(method, value, key, options = {}) silence_warnings do algorithm = options[:algorithm] || default_algorithm c = OpenSSL::Cipher.module_eval("#{algorithm}.new") method == 'encrypt' ? c.encrypt : c.decrypt c.pkcs5_keyivgen(key) res = c.update(value) res << c.final rescue '' end end def self.default_algorithm 'BF' end end end end
true
dfc3754eda628c37d794b6de54b6838730a39eab
Ruby
pitosalas/ruby_inheritance_demo
/example1.rb
UTF-8
623
3.75
4
[]
no_license
require 'pry-byebug' # Represent game characters that can move: People and Cars # Using a @type variable (an immedaite smell!) class Character attr_reader :location, :velocity, :type def initialize(args) @type = args[:type] @velocity = args[:starting_v] end def passengers if @type == :car 4 end end def to_s if @type == :person "[person]" elsif @type == :car "[car]" else error "Invalid type" end end end person = Character.new(type: :person, starting_v: 0) puts person car = Character.new(type: :car, starting_v: 0) puts car puts car.passengers
true
8f2d58452b87fa16ddc0a75e283d736f4db96630
Ruby
alwikah/chronoTime
/app/models/item.rb
UTF-8
826
2.859375
3
[]
no_license
class Item < ActiveRecord::Base attr_accessible :label, :payment_type, :payment_unit, :time validates :time, :presence => true before_validation :setup def setup self.time = 0 if(self.time.nil?) end def self.clean_all_items unless Item.count > 10000 Item.all.each do |item| unless item.save puts "We erase item with id=#{item.id}" item.delete # If there is a problem : we erase ! end end end end def secondes_to_string s, m, h = self.time, 0, 0 if s>59 s = s%60 m = (self.time - (s))/60 if m>59 h = (m-(m%60))/60 m = m%60 end end "#{simple_display(h)}:#{simple_display(m)}:#{simple_display(s)}" end def simple_display(t) if t>10 t else "0#{t}" end end end
true
af6c68bf4652a7dce7c155d24031046dd60ef78a
Ruby
bRRRITSCOLD/openweatherrough
/lib/owm/classes/response.rb
UTF-8
277
2.953125
3
[]
no_license
module OWM class Response attr_accessor :response, :response_body, :weather def initialize res @response = res end def response_body @response_body = @response.body end def weather @weather = Weather.new JSON.parse(response_body) end end end
true
41789e61807ef10d082b583a9536392600244b7e
Ruby
dmyers3/launch_school_101
/Exercises/Easy6/reversed_arrays.rb
UTF-8
409
3.65625
4
[]
no_license
def reverse!(arr) arr_copy = arr.dup arr_size = arr.size arr.map! do |element| arr_size -= 1 arr_copy[arr_size] end end def reverse(arr) arr_copy = arr.dup arr_size = arr.size arr.map do |element| arr_size -= 1 arr_copy[arr_size] end end # list = %w(a b c d e) # result = reverse!(list) # p result # p list list2 = %w(a b c d e) result2 = reverse(list2) p result2 p list2
true
de13e38e0026008c4a9ac776ecc03189f4f92246
Ruby
crawsible/advent-2019
/01/spec/fuel_counter_spec.rb
UTF-8
1,220
2.78125
3
[]
no_license
require 'fuel_counter' RSpec.describe FuelCounter do describe "#required_fuel_for_modules" do context "with one module weight" do it "returns its required fuel amount without factoring fuel weight" do expect(FuelCounter.new([9]).required_fuel_for_modules).to eq(1) expect(FuelCounter.new([33]).required_fuel_for_modules).to eq(9) expect(FuelCounter.new([105]).required_fuel_for_modules).to eq(33) end end context "with multiple module weights" do it "returns the sum of the required fuel amounts without factoring fuel weight" do expect(FuelCounter.new([9, 33, 105]).required_fuel_for_modules).to eq(43) end end end describe "#required_fuel" do context "with one module weight" do it "returns its required fuel amount" do expect(FuelCounter.new([9]).required_fuel).to eq(1) expect(FuelCounter.new([33]).required_fuel).to eq(10) expect(FuelCounter.new([105]).required_fuel).to eq(43) end end context "with multiple module weights" do it "returns the sum of the required fuel amounts" do expect(FuelCounter.new([9, 33, 105]).required_fuel).to eq(54) end end end end
true
d07bcd0db6cb0ad1197c051ab305efc582b74e45
Ruby
co2co2/nov29ordinal_indicator
/Untitled.rb
UTF-8
275
4.0625
4
[]
no_license
def ordinal_indicator(number) n = number.to_s.split('') if n[-1] == "1" puts "#{number}st" elsif n[-1] == "2" puts "#{number}nd" elsif n[-1] == "3" puts "#{number}rd" else puts "#{number}th" end end puts ordinal_indicator(12)
true
a4858f2f15c187e20501a8735e1f674f433a0323
Ruby
sagutierrez10/routes-controllers
/practice/app/controllers/hello_controller.rb
UTF-8
743
2.609375
3
[]
no_license
class HelloController < ApplicationController def index render :text => "Hello Coding Dojo!" end def say render :text => "Saying hello!" end def sayname render :text => "Saying Hello Joe" end def saynamem if params[:name] == 'michael' redirect_to '/say/hello/joe' end end def local render :text => 'What do you want me to say???' end def times if session[:visits] == nil session[:visits] = 0 end session[:visits]+= 1 render :text => "You have visited thir url #{session[:visits]} times" end def restart session.clear render :text => 'session is clear' end end
true
c316063af58f57ffc362f07c3c970ac6bde3cbd5
Ruby
DenisColoma/Semaine03_J01_Ruby_spec
/lib/00_hello.rb
UTF-8
95
3.34375
3
[]
no_license
def hello return "Hello!" end name = gets.chomp def greet(name) return "Hello, #{name}!" end
true
b633c173a5be2e744eadda768359ace2051a29b9
Ruby
akoltun/form_obj
/test/form/persistence_test.rb
UTF-8
4,260
2.921875
3
[ "MIT" ]
permissive
require "test_helper" class FormPersistenceTest < Minitest::Test class Team < FormObj::Form attribute :name attribute :cars, array: true, primary_key: :code do attribute :code attribute :driver end attribute :colour do attribute :rgb end end class DefaultTeam < FormObj::Form attribute :name, default: 'Ferrari' attribute :cars, array: true, default: [{code: '1'}, {code: '2'}], primary_key: :code do attribute :code attribute :driver end attribute :colour do attribute :rgb, default: 0xFFFFFF end end def test_that_form_is_not_persisted_after_initialization_without_initial_parameters team = Team.new refute(team.persisted?) refute(team.colour.persisted?) assert(team.cars.persisted?) end def test_that_form_is_not_persisted_after_initialization_with_initial_parameters team = Team.new(name: 'Ferrari') refute(team.persisted?) refute(team.colour.persisted?) assert(team.cars.persisted?) end def test_that_form_is_not_persisted_after_initialization_with_initial_parameters_for_nested_form team = Team.new(colour: { rgb: 0xFFFFFF } ) refute(team.persisted?) refute(team.colour.persisted?) assert(team.cars.persisted?) end def test_that_form_is_not_persisted_after_initialization_with_initial_parameters_for_empty_nested_array team = Team.new(cars: []) refute(team.persisted?) refute(team.colour.persisted?) assert(team.cars.persisted?) end def test_that_form_is_not_persisted_after_initialization_with_initial_parameters_for_non_empty_nested_array team = Team.new(cars: [{code: '1'}, {code: '2'}]) refute(team.persisted?) refute(team.colour.persisted?) refute(team.cars.persisted?) refute(team.cars[0].persisted?) refute(team.cars[1].persisted?) end def test_that_form_is_not_persisted_after_initialization_with_default_values team = DefaultTeam.new refute(team.persisted?) refute(team.colour.persisted?) refute(team.cars.persisted?) refute(team.cars[0].persisted?) refute(team.cars[1].persisted?) end def test_that_mark_as_persisted_returns_object_itself team = Team.new assert_same(team, team.mark_as_persisted) end def test_that_form_becomes_persisted_after_marking_as_persisted team = DefaultTeam.new.mark_as_persisted assert(team.persisted?) assert(team.colour.persisted?) assert(team.cars.persisted?) assert(team.cars[0].persisted?) assert(team.cars[1].persisted?) end def test_that_persisted_form_remains_persisted_after_updating_attribute team = DefaultTeam.new.mark_as_persisted team.name = 'McLaren' assert(team.persisted?) assert(team.colour.persisted?) assert(team.cars.persisted?) assert(team.cars[0].persisted?) assert(team.cars[1].persisted?) end def test_that_persisted_form_remains_persisted_after_updating_nested_attribute team = DefaultTeam.new.mark_as_persisted team.colour.rgb = 0xFFFFFF assert(team.persisted?) assert(team.colour.persisted?) assert(team.cars.persisted?) assert(team.cars[0].persisted?) assert(team.cars[1].persisted?) end def test_that_persisted_form_remains_persisted_after_updating_attribute_of_element_in_the_array team = DefaultTeam.new.mark_as_persisted team.cars[0].driver = 'Ascari' assert(team.persisted?) assert(team.colour.persisted?) assert(team.cars.persisted?) assert(team.cars[0].persisted?) assert(team.cars[1].persisted?) end def test_that_persisted_form_remains_persisted_after_adding_element_to_array team = DefaultTeam.new.mark_as_persisted team.cars.build assert(team.persisted?) assert(team.colour.persisted?) refute(team.cars.persisted?) assert(team.cars[0].persisted?) assert(team.cars[1].persisted?) refute(team.cars[2].persisted?) end def test_that_persisted_form_remains_persisted_after_marking_element_for_destruction team = DefaultTeam.new.mark_as_persisted team.cars[1].mark_for_destruction assert(team.persisted?) assert(team.colour.persisted?) assert(team.cars.persisted?) assert(team.cars[0].persisted?) assert(team.cars[1].persisted?) end end
true
6de573a52e0f0f539f0dbe9378ece38ba9ab147d
Ruby
Azzamobeid/Azzam_The_Bank
/Thebank/the_bank.rb
UTF-8
3,855
3.625
4
[]
no_license
require_relative 'bank_classes' @customers = [] @accounts = [] def welcome_screen @current_customer = "" puts "Welcome to Azzam's Bank" puts "Please choose for Menu" puts "_-_-_-_-_-_-_-_-_-_-_-_" puts "1. Customer sign-in" puts "2. New customer registration " choice = gets.chomp.to_i case choice when 1 then sign_in #method 1 when 2 then sign_up("","")#method 2 end end #method 1 def sign_in print "Please enter you name" name = gets.chomp print "Please enter you location" location = gets.chomp if @customers.empty? puts "no customer found with that information" sign_up(name, location) end customer_exists = false @customers.each do |customer| #represents each item in the array if name == customer.name && location == customer.location @current_customer = customer customer_exists = true end end if customer_exists account_menu else puts "Does not exsit" puts "1. try again?" puts "2. sign Up" choice = gets.chomp.to_i case choice when 1 then sign_in #recurrsive method calls itself when 2 then sign_up(name, location) end end end def sign_up(name, location)#method 2 if name == "" && location == "" print "what is your name?" name = gets.chomp print " what is your location?" location = gets.chomp end @current_customer = Customer.new(name, location) @customers.push(@current_customer) puts "Thank you for registration" account_menu end def account_menu puts "Account Menu" puts "_-_-_-_-_-_-_" puts "1. Create an Account" puts "2. View Account" puts "3. Sign Out" choice = gets.chomp.to_i case choice when 1 then creat_account when 2 then view_account when 3 puts "Thank you" welcome_screen else puts "Invalid selection." account_menu end end def creat_account print "How much will your first deposite be? $" amount = gets.chomp.to_i print "What type of account will you be opening? " acct_type = gets.chomp new_acct = Account.new(@current_customer, amount, (@accounts.length+1), acct_type) @accounts.push(new_acct) puts "Account successfully created!" account_menu end def view_account @current_customer = "" print "Which account (type) do you want to view?" type = gets.chomp account_exists = false @accounts.each do |account| if @current_customer == account.customer && type == account.acct_type.downcase @current_customer = accounts account_exists = true end end if account_exists current_account_actoins else puts "Try again." view_account end end def current_account_actoins puts "choose from the following:" puts "_-_-_-_-_-_-_-_-_-_-_-_-_-_" puts "1. Balacce check" puts "2. Make a deposite" puts "3. Make a withdrawal" puts "4. Return to Account Menu" puts " 5. Sign out" choice = gets.chomp.to_i case choice when 1 puts "current balance is $#{'%0.2'%(@current_account.balance)}" current_account_actoins when 2 @current_account.deposite current_account_actoins when 3 @current_account.withdrawal current_account_actoins when 4 then view_account when 5 then welcome_screen else puts "Invalid Selection." current_account_actoins end end welcome_screen
true
4273d5f121e39e672e258cc763e0c6ecf06cd689
Ruby
WHomer/mod1-midmod
/test/student_test.rb
UTF-8
711
3.046875
3
[]
no_license
require 'minitest/autorun' require './lib/student' class TestStudent < MiniTest::Test def setup @morgan = Student.new({name: "Morgan", age: 21}) end def test_it_exists assert_instance_of Student, @morgan end def test_it_has_a_name assert_equal "Morgan", @morgan.name end def test_it_has_a_age assert_equal 21, @morgan.age end def test_it_has_empty_scores assert_equal [], @morgan.scores end def test_it_can_log_scores @morgan.log_score(89) @morgan.log_score(78) assert_equal [89, 78], @morgan.scores end def test_it_can_average_all_scores @morgan.log_score(89) @morgan.log_score(78) assert_equal 83.5, @morgan.grade end end
true
c668aacd99e469a061265f8c9cc1920613d655c3
Ruby
Anthony-Mendola/pokemon-scraper-v-000
/lib/pokemon.rb
UTF-8
799
3.09375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Pokemon attr_accessor :id, :name, :type, :hp, :db DATABASE_CONNECTION = SQLite3::Database.new('db/pokemon.db') def initialize(attributes) attributes.each {|attribute, value| self.send(("#{attribute}="), value)} end def self.save(name, type, db) sql = File.read("db/schema_migration.sql") db.execute_batch(sql) db.execute(" INSERT INTO pokemon (name, type) VALUES (?,?) ", name, type) end def self.find(id, db) sql = File.read("db/schema_migration.sql") db.execute_batch(sql) attributes = db.execute("SELECT * FROM pokemon WHERE id = (?)", id).flatten Pokemon.new(id: attributes[0], name: attributes[1], type: attributes[2], hp: attributes[3]) end def alter_hp(new_hp, db) db.execute("UPDATE pokemon SET hp = #{new_hp} WHERE id =#{id}") end end
true
2c49b713e20a513bdaf5762de9822e75fb90a455
Ruby
fenkod/todos
/spec/todo/todo_spec.rb
UTF-8
2,235
2.875
3
[]
no_license
require 'spec_helper' class Login < SitePrism::Section element :username_input, "input#username" element :password_input, "input#password" element :submit_button, "input[value='Login']" def login_with(username, password) username_input.set(username) password_input.set(password) submit_button.click end end class TodoForm < SitePrism::Section element :todo_input, "input[name='text']" element :todo_submit, "input[type='submit']" def add_todo(text) todo_input.set(text) todo_submit.click end end class TodoList < SitePrism::Section elements :items, "li" end class ToDo < SitePrism::Section section :form, TodoForm, "form" section :list, TodoList, "ul" end class CoolStuffApp < SitePrism::Page set_url "http://localhost:9292" section :login, Login, ".login" section :todo, ToDo, "#todo-app" end describe "login page" do let(:app) { CoolStuffApp.new } let(:login) { app.login } before { app.load } it "has a username input" do expect(login).to have_username_input end it "has a password input" do expect(login).to have_password_input end it "has a submit button" do expect(login).to have_submit_button end it "displays a validation error with invalid credentials" do login.login_with("bad@example.com", "bad-password") expect(app).to have_login expect(login).to have_content "Invalid" end it "displays the todo section when logged in with valid credentials" do login.login_with("test@example.com", "password") expect(app).not_to have_login expect(app).to have_todo end end describe "adding todos" do let(:app) { CoolStuffApp.new } before { app.load app.login.login_with("test@example.com", "password") } it "adds a todo to the list" do app.todo.form.add_todo("Wake Up") expect(app.todo).to have_list expect(app.todo.list.items.first).to have_content "Wake Up" end it "adds multiple todos to the list" do items = ["Wake Up", "Get out of Bed", "Drag a Comb Across My Head"] items.each do |item| app.todo.form.add_todo(item) end items.each_with_index do |item, index| expect(app.todo.list.items[index].text).to eql item end expect(app.todo.list.items.first.text).to eql items[0] expect(app.todo.list.items.last.text).to eql items[-1] end end
true
dd49b95a82b3715bb311b75dd076c068f7374549
Ruby
Lojistic/NwsAlerts-gem
/lib/nws/api/alerts/alert.rb
UTF-8
1,852
2.796875
3
[ "MIT" ]
permissive
# The Alert class encapsulates all of the important information for a given weather alert module Nws module Api module Alerts class Alert attr_reader :nws_id, :onset, :expires, :message_type, :severity, :certainty, :urgency, :instruction, :geometry def self.from_api_response(client, parsed_response, alerts = nil) alerts ||= AlertSet.new return alerts unless parsed_response['features'] parsed_response['features'].each do |alert_data| alerts << self.new(alert_data) end if parsed_response['pagination'] && parsed_response['pagination']['next'] next_uri = URI.parse(parsed_response['pagination']['next']) next_path = next_uri.to_s.gsub("#{next_uri.scheme}://#{next_uri.host}", '') self.from_api_response(client, client.fetch_raw_alerts(path: next_path), alerts) end return alerts end def initialize(data) if data['geometry'] @geometry = data['geometry']['coordinates'].first end properties = data['properties'] @nws_id = properties['id'] @onset = properties['onset'] @expires = properties['expires'] @message_type = properties['messageType'] @severity = properties['severity'] @certainty = properties['certainty'] @urgency = properties['urgency'] @instruction = properties['instruction'] end def attributes hsh = {} # Give back a hash of attributes suitable for persistance to a DB, for instance. instance_variables.map(&:to_s).map{|iv| iv.gsub('@', '')}.map{|att| hsh[att.to_sym] = self.send(att.to_sym)} hsh end end end end end
true
345d28e5f8727c0698a7bafe86a010fe6538a5d6
Ruby
mk10305/rubyonrails_bootcamp
/intro_to_ruby_web_dev/precourse/1_Basics/3.rb
UTF-8
150
2.984375
3
[]
no_license
movies = {:Snow_White => 1937, :Cinderalla => 1950, :Jungle_Book=> 1967} puts movies[:Snow_White] puts movies [:Cinderalla] puts movies[:Jungle_Book]
true
d3a0acbeb2c86dd717db2f8b67bf3ab051bdbc4b
Ruby
Flameeyes/attic
/try/10_attic_tryouts.rb
UTF-8
944
2.78125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
group "Attic" library :attic, "lib" tryouts "Basics" do drill "can extend Attic", true do class ::Worker extend Attic def kind() :true end end # 1.9 # 1.8 Worker.methods.member?(:attic) || Worker.methods.member?('attic') end drill "can't include Attic raises exception", :exception, RuntimeError do class ::Worker include Attic end end drill "can define attic attribute", true do Worker.attic :size w = Worker.new #w.attic :size stash :instance_methods, Worker.instance_methods(false) stash :metamethods, Worker.methods.sort w.respond_to? :size end drill "can access attic attributes explicitly", 2 do w = Worker.new w.attic_variable_set :size, 2 w.attic_variable_get :size end drill "won't define a method if on already exists", :true do Worker.attic :kind a = Worker.new a.kind end end
true
8272ddaf1643420d3285f43f9604370ec7e188d0
Ruby
tbae2/odin_project_ruby
/ceaser_cipher.rb
UTF-8
1,271
3.90625
4
[]
no_license
def ceaser_cipher(userentry, shift) #how to create ceaser_cipher index pulled from an example, taking notes as decoding what someone has done #for learning purposes #the a to z ranges produce a - Z to_a places i into an array. concat appends A-Z caps array #to preexisting array alphabet_index = ('a'..'z').to_a.concat(('A'..'Z').to_a) word_output = "" # do = create a loop , |i| = each char output userentry.each_char do |i| #! at the beginning implies char doesn't exist in index include (look ahead and then check #to see if #it's included in the index. accounts for spaces and extra chars ? checks to see if the char is in the alphabet_index if !alphabet_index.include?(i) #appends the character if not in the alphabet word_ouput += i else #takes alphabet index array, and targets [] where the i char = and then subtracts the desired #position to hit the roper char. then adds it to the array word_output += alphabet_index[alphabet_index.index(i.downcase) - shift] end end #return the built word_output downcase all chars, return first char caps return word_output.downcase.capitalize end puts ceaser_cipher("hello world who is out there?", 2)
true
455ef49899f35b258e8dffe0cb3ba261f648badf
Ruby
mgmilton/black_thursday
/test/item_test.rb
UTF-8
417
2.6875
3
[]
no_license
require './test/test_helper' require './lib/item' class ItemTest < MiniTest::Test def setup @item = Item.new({ :name => "Pencil", :description => "You can use it to write things", :unit_price => BigDecimal.new(1099), :created_at => Time.now, :updated_at => Time.now}) end def test_unit_price_to_dollars assert_equal 10.99, @item.unit_price_to_dollars end end
true
0b7744fe1680b792f9f7fad8ccb89771be118b5f
Ruby
h0tl33t/Gradebook
/test/models/enrollment_test.rb
UTF-8
2,060
2.625
3
[]
no_license
require 'test_helper' class EnrollmentTest < ActiveSupport::TestCase setup do @enrollment = Enrollment.first end teardown do @enrollment = nil end test 'invalid without a student' do enrollment = FactoryGirl.build(:enrollment, student: nil) refute enrollment.valid?, 'Not validating presence of a student.' end test 'invalid without a course' do enrollment = FactoryGirl.build(:enrollment, course: nil) refute enrollment.valid?, 'Not validating presence of a course.' end test 'invalid without a grade' do enrollment = FactoryGirl.build(:enrollment, grade: nil) refute enrollment.valid?, 'Not validating presence of a grade.' end test 'belongs to a student' do enrollment = FactoryGirl.create(:enrollment) assert_respond_to(enrollment, :student, "Enrollment 'belongs_to student' association not configured correctly.") end test 'belongs to a course' do enrollment = FactoryGirl.create(:enrollment) assert_respond_to(enrollment, :course, "Enrollment 'belongs_to course' association not configured correctly.") end test 'a student cannot have more than one enrollment for a given course' do enrollment = FactoryGirl.create(:enrollment) assert_raise(ActiveRecord::RecordInvalid) {FactoryGirl.create(:enrollment, student: enrollment.student, course: enrollment.course)} end test 'float grade invalid if not between 0.0 and 4.0' do enrollment = FactoryGirl.build(:enrollment, grade: 4.2) refute enrollment.valid?, 'Not validating float grade range.' end test 'letter grade valid between 0.0 and 4.0' do enrollment = FactoryGirl.build(:enrollment, grade: '2.7') assert enrollment.valid?, 'Not accepting valid letter grades.' end test 'scope with courses for a given semester' do semester = @enrollment.course.semester assert_equal Enrollment.includes(:course).where(courses: {semester_id: semester.id}), Enrollment.with_courses_for_semester(semester), 'Not scoping courses for a given semester.' end end
true
c50e3fa76abee746b481df44d30469b1913a0d63
Ruby
kristianmandrup/partializer
/lib/partializer/collection.rb
UTF-8
2,212
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
class Partializer class Collection include Enumerable include Partializer::PathHelper attr_reader :hashie, :name, :ns, :action def initialize name, *items hash = items.extract_options! partials << partial_keys(items) self.name = name.to_s @hashie = Hashie::Mash.new resolve(hash) unless hash.empty? set_names unless hashie.nil? end def each &block partials.each {|partial| yield partial } end def partials @partials ||= Partializer::Partials.new end def path [ns, action, name.gsub('.', '/')].compact.join('/') end alias_method :to_partial_path, :path def set_context ns, action @ns, @action = [ns, action] partials.list.each {|p| p.send :set_context, ns, action } end protected def name= name @name = name partials.list.each do |p| p.path = name end end def set_names hashie.keys.each do |key| if key.kind_of?(String) h = hashie.send(key) if h.kind_of? Partializer::Collection h.send :name=, "#{name}.#{key}" h.set_names unless h.hashie.nil? end end end end def resolve hash hash.inject({}) do |res, pair| key = pair.first item = pair.last key = key.to_s.sub(/^_/, '').to_sym value = resolve_value key, item res[key.to_s.sub(/^_/, '').to_sym] = value res end end def resolve_value key, item case item when Partializer::Collection item.hashie ? item.send(key) : item when Symbol, String Partializer::Collection.new('noname', item) when Hash item.values.first else raise ArgumentError, "cant resolve: #{item.inspect}" end end def partial_keys *args args.flatten.map do |item| case item when Hash item.keys.map(&:to_sym) when String, Symbol item.to_s.sub(/^_/, '').to_sym end end.flatten.compact.uniq end def method_missing meth_name, *args, &block hashie.send(meth_name) end end end
true
ea63927437189005d3135a213bdd69d9b317b9a5
Ruby
ralzate/FES2
/app/decorators/user_decorator.rb
UTF-8
283
2.5625
3
[]
no_license
module UserDecorator def select_genero [['Masculino', 1], ['Femenino', 2]] end def label_generos if select_genero.flatten.include?(genero.to_i) select_genero.each { |nombre, id| return nombre if genero.to_i == id } end end end
true
85b82abb98d13ebbd2b15031e1dac0a8ebafebe1
Ruby
gegerlan/Gentle-Love-Quest
/Source/Scripts/Scene_End.rb
UTF-8
4,914
2.59375
3
[]
no_license
#============================================================================== # ** Scene_End #------------------------------------------------------------------------------ # This class performs game end screen processing. #============================================================================== class Scene_End < Scene_Base #-------------------------------------------------------------------------- # * Start processing #-------------------------------------------------------------------------- def start super create_menu_background create_command_window end #-------------------------------------------------------------------------- # * Post-Start Processing #-------------------------------------------------------------------------- def post_start super open_command_window end #-------------------------------------------------------------------------- # * Pre-termination Processing #-------------------------------------------------------------------------- def pre_terminate super close_command_window end #-------------------------------------------------------------------------- # * Termination Processing #-------------------------------------------------------------------------- def terminate super dispose_command_window dispose_menu_background end #-------------------------------------------------------------------------- # * Return to Original Screen #-------------------------------------------------------------------------- def return_scene $scene = Scene_Menu.new(5) end #-------------------------------------------------------------------------- # * Frame Update #-------------------------------------------------------------------------- def update super update_menu_background @command_window.update if Input.trigger?(Input::B) Sound.play_cancel return_scene elsif Input.trigger?(Input::C) case @command_window.index when 0 # to title command_to_title when 1 # shutdown command_shutdown when 2 # quit command_cancel end end end #-------------------------------------------------------------------------- # * Update Background for Menu Screen #-------------------------------------------------------------------------- def update_menu_background super @menuback_sprite.tone.set(0, 0, 0, 128) end #-------------------------------------------------------------------------- # * Create Command Window #-------------------------------------------------------------------------- def create_command_window s1 = Vocab::to_title s2 = Vocab::shutdown s3 = Vocab::cancel @command_window = Window_Command.new(172, [s1, s2, s3]) @command_window.x = (544 - @command_window.width) / 2 @command_window.y = (416 - @command_window.height) / 2 @command_window.openness = 0 end #-------------------------------------------------------------------------- # * Dispose of Command Window #-------------------------------------------------------------------------- def dispose_command_window @command_window.dispose end #-------------------------------------------------------------------------- # * Open Command Window #-------------------------------------------------------------------------- def open_command_window @command_window.open begin @command_window.update Graphics.update end until @command_window.openness == 255 end #-------------------------------------------------------------------------- # * Close Command Window #-------------------------------------------------------------------------- def close_command_window @command_window.close begin @command_window.update Graphics.update end until @command_window.openness == 0 end #-------------------------------------------------------------------------- # * Process When Choosing [To Title] Command #-------------------------------------------------------------------------- def command_to_title Sound.play_decision RPG::BGM.fade(800) RPG::BGS.fade(800) RPG::ME.fade(800) $scene = Scene_Title.new close_command_window Graphics.fadeout(60) end #-------------------------------------------------------------------------- # * Process When Choosing [Shutdown] Command #-------------------------------------------------------------------------- def command_shutdown Sound.play_decision RPG::BGM.fade(800) RPG::BGS.fade(800) RPG::ME.fade(800) $scene = nil end #-------------------------------------------------------------------------- # * Process When Choosing [Cancel] Command #-------------------------------------------------------------------------- def command_cancel Sound.play_decision return_scene end end
true
54f111efacd571d3e77020c0b5e2b26c2ed91261
Ruby
carolyny/launchschool
/Backend/101/Exercises/bonus.rb
UTF-8
205
3.375
3
[]
no_license
def calculate_bonus(salary, yesno) if yesno == true salary/2 else 0 end end puts calculate_bonus(2800, true) == 1400 puts calculate_bonus(1000, false) == 0 puts calculate_bonus(50000, true) == 25000
true
20ce21c4e80cdf90b998d90c1e1ac6c7046412c5
Ruby
dam5s/somanyfeeds
/app/models/feed/blog.rb
UTF-8
1,078
2.90625
3
[ "MIT" ]
permissive
require 'open-uri' require 'nokogiri' class Feed::Blog < Feed def self.default new(name: 'My Blog', info: 'your blog url') end def url=(info) if info new_url = info.normalize_url new_url.insert(0, 'http://') unless info.match /^http/ if doc = Nokogiri(open new_url) rescue nil feed = new_url if doc.css('rss').present? || doc.css('feed').present? unless feed links = doc.css('link[rel=alternate]') rss = links.find{|l| l['type'] =~ /rss/ }['href'] rescue nil atom = links.find{|l| l['type'] =~ /atom/}['href'] rescue nil feed = append_host( rss || atom, new_url ) end write_attribute :url, feed end # if doc end # if info end private def append_host( feed, base_url ) return feed if feed.blank? || feed.match(/^http/) host = if feed.match(%r[^/]) # absolute path base_url.match( %r[^(http://[^/]+)/] )[1] else # relative path base_url.match( %r[^(http://.+/)[^/]*$] )[1] end host + feed end end
true
6a9f8bf1522b612f4f0e4afb63a9febc5ecf4865
Ruby
jk1dd/night_writer
/lib/file_writer.rb
UTF-8
223
3.1875
3
[]
no_license
class FileWriter def write_braille (string) write_file = File.open(ARGV[1], 'w+') write_file.write(string) write_file.close puts "Created file #{ARGV[1]} containing #{string.length} characters." end end
true
c8c5f414f4f2f549409b2f56183e1a860e50e29b
Ruby
nilbus/teaspoon
/lib/teaspoon/utility.rb
UTF-8
696
3.0625
3
[ "BSD-3-Clause", "MIT" ]
permissive
module Teaspoon module Utility # Cross-platform way of finding an executable in the $PATH. # http://stackoverflow.com/questions/2108727/which-in-ruby-checking-if-program-exists-in-path-from-ruby # # @example # which('ruby') #=> /usr/bin/ruby # # @param cmd [String] the executable to find # @return [String, nil] the path to the executable # def which(cmd) exts = ENV['PATHEXT'] ? ENV['PATHEXT'].split(';') : [''] ENV['PATH'].split(File::PATH_SEPARATOR).each do |path| exts.each do |ext| exe = "#{ path }/#{ cmd }#{ ext }" return exe if File.executable?(exe) end end nil end end end
true
ea3ddae5d80f93fc3ebebcff6909863ff1810dfb
Ruby
AaronC81/parlour
/lib/parlour/options.rb
UTF-8
2,489
3.203125
3
[ "MIT" ]
permissive
# typed: true module Parlour # A set of immutable formatting options. class Options extend T::Sig sig { params(break_params: Integer, tab_size: Integer, sort_namespaces: T::Boolean).void } # Creates a new set of formatting options. # # @example Create Options with +break_params+ of +4+ and +tab_size+ of +2+. # Parlour::Options.new(break_params: 4, tab_size: 2) # # @param break_params [Integer] If there are at least this many parameters in a # signature, then it is broken onto separate lines. # @param tab_size [Integer] The number of spaces to use per indent. # @param sort_namespaces [Boolean] Whether to sort all items within a # namespace alphabetically. # @return [void] def initialize(break_params:, tab_size:, sort_namespaces:) @break_params = break_params @tab_size = tab_size @sort_namespaces = sort_namespaces end sig { returns(Integer) } # If there are at least this many parameters in a signature, then it # is broken onto separate lines. # # # With break_params: 5 # sig { params(name: String, age: Integer, hobbies: T::Array(String), country: Symbol).void } # # # With break_params: 4 # sig do # params( # name: String, # age: Integer, # hobbies: T::Array(String), # country: Symbol # ).void # end # # @return [Integer] attr_reader :break_params sig { returns(Integer) } # The number of spaces to use per indent. # @return [Integer] attr_reader :tab_size sig { returns(T::Boolean) } # Whether to sort all items within a namespace alphabetically. # Items which are typically grouped together, such as "include" or # "extend" calls, will remain grouped together when sorted. # If true, items are sorted by their name when the RBI is generated. # If false, items are generated in the order they are added to the # namespace. # @return [Boolean] attr_reader :sort_namespaces sig { params(level: Integer, str: String).returns(String) } # Returns a string indented to the given indent level, according to the # set {tab_size}. # # @param level [Integer] The indent level, as an integer. 0 is totally unindented. # @param str [String] The string to indent. # @return [String] The indented string. def indented(level, str) " " * (level * tab_size) + str end end end
true
434ba02a56534f6f2be45ed0c791d5d3739c0394
Ruby
DanielaCarvajal/ruby-collaborating-objects-lab-v-000
/lib/mp3_file.rb
UTF-8
190
3.046875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class MP3File attr_reader :artist, :song, :genre def initialize(file) @artist = file.split(" - ")[0] @song = file.split(" - ")[1] @genre = file.split(" - ")[2] end end
true
01eee193fe3a4a68becc0e70eee0d2b4affe05c1
Ruby
fabianp5060/bwtoolkit
/src/bwhelpers/confluence_helpers.rb
UTF-8
1,815
2.734375
3
[]
no_license
require 'net/http' require 'uri' class CDKConfluence def initialize(config_data) c = $bw.get_app_config(config_data) @url = c[:confluence_url] @user = c[:confluence_user] @pass = c[:confluence_pass] end def fetch(uri_part, limit=10) raise ArgumentError, 'too many HTTP redirects' if limit == 0 response = get_confluence_response(uri_part) case response when Net::HTTPSuccess then response when Net::HTTPRedirection then # puts "#{response.code}: #{response.message} to #{response['location']}" location = response['location'] warn "redirected to #{location}" fetch(location, limit - 1) else response.body end return response end def get_confluence_response(uri_part) response = nil uri = URI(uri_part) puts "URI HOSTNAME: #{uri.hostname}" Net::HTTP.start(uri.hostname,use_ssl: uri.scheme == 'https') do |http| request = Net::HTTP::Get.new(uri.request_uri) request.basic_auth $user,$pass response = http.request request # puts response # puts "MY BODY:\n #{response.body}" end return response end def create_new_child_page_w_content(post_body) response = nil uri = URI(@url+"content/") header = {'Content-Type' => 'application/json'} Net::HTTP.start(uri.hostname,use_ssl: uri.scheme == 'https') do |http| request = Net::HTTP::Post.new(uri.request_uri, header) request.body = post_body.to_json request.basic_auth @user,@pass response = http.request request end return response end # Take Array of Hashes and create an HTML formatted table def create_confluence_table_html(data) xm = Builder::XmlMarkup.new(:indent => 2) xm.table { xm.tr { data[0].keys.each { |key| xm.th(key)}} data.each { |row| xm.tr { row.values.each { |value| xm.td(value)}}} } return "#{xm}" end end
true
b2dd75f2c78d4ca4c7f504447f8c5b1461ed1f89
Ruby
dominictarr/practice
/class_herd/old/class_conductor2.rb
UTF-8
2,366
3.109375
3
[]
no_license
#class conductor using symbol shadowing #~ #two ways to reconfigure: #~ #1. #~ #replace (X,Y) #~ #means: always use Y in the place of X globally. #~ #2. #~ #for(A).replace(B,C) #~ #means: A now uses C instead of B #~ #3. #~ #[for(A)].replace(B,C).when {test is true}... #~ #could monkey patch Class instead of going For(x) might be a better idea not to though. #~ #implemention approch: #~ #1. hook X.new to return a new Y #~ #1.2. or reassign :X to point to Y? #~ #2. C shadow B on A. #~ #3. B' shadow B on A, hook B'.new to eval test and return C.new if it passes, else super. #stacking. #for(A).replace(B,for(C).replace(X,Y)) #means in A, use a C (which uses Y instead of X) instead of B #will need a terminator: #for(A).replace(B,for(C).replace(X,Y).do).do #or to reverse the syntax #replace(B,replace(X,Y).on(C)).on(A) #thats slightly more confusion. #if for(A) returns A.dup, and the replace modify that... #then, when things are stacked, it will work automagicially. #to use the configuration: call new on the top level dup. #probably best to avoid calling replace() globally. #~ #how might a test framework use this? #~ #For(Test).replace(StandardSubject, NewSubject) #~ #by duplicating Test, could create a list of all Test combinations. #~ #this would also allow a elegant configuration definition #~ [AppleTree #for class AppleTree #~ [Apple : Pear]#replace Apple with Pear #~ [Roots : Pipes, {test}] #use rockets for roots when test is true. #~ [Trunk : [ModularTrunk #~ [Stem : Stem1] #~ [Branch: Branch3]]] #~ ] #~ #since we've made settings for ModularTrunk under Trunk, that applies only in that situation. #~ #implement this my shadowing AppleTree.trunk with ModularTrunk.dup #~ what about application composition? (with reference to tests?) #~ it will be like the above, but will say 'passes(Test1,Test2,Test3)' #~ what about tests which refur to more than one class? #~ can use this to detect which classes are compatable - they can pass the test when used together... #~ this must be what they mean by *integration tests*... module ClassHerd class ClassHerd::ClassConductor2 attr_accessor :klass def self.for(x) ClassConductor2.new(x) end @klass def initialize(x) @klass = x.dup end def replace(x,y) @klass.const_set(x, y) self end def create (*args,&block) @klass.new(*args,&block) end end end
true
0b4906dcf350afa0a2e4f210b3e087d7df6e9ac8
Ruby
andhapp/rb_tnetstring
/lib/rb_tnetstring/encoder/integer_encoder.rb
UTF-8
213
2.640625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module RbTNetstring class IntegerEncoder < Encoder def initialize(obj) @obj = obj end def encode int_string = @obj.to_s "#{int_string.length}:#{int_string}#" end end end
true
9b86d18c96ed52d47b4fa87d72f800ce0caa4bf1
Ruby
hyperturing/chess
/lib/game.rb
UTF-8
1,591
3.78125
4
[]
no_license
require './board.rb' require './player.rb' class Game attr_reader :board, :players, :winner def initialize(player1: 'Ashley', player2: 'Ashley-2.0') instructions @board = Board.new @players = { white: Player.new(name: player1), black: Player.new(name: player2) } @board.display_board end def instructions puts "Welcome to Chess ^.^ ^.^\n\n" puts 'Instructions:' puts '========================' puts 'To make a move when prompted:' puts 'Enter the chess notation of the move you wish to make' puts '(Ex: King at "a1" moving to "b2" is: Ka1-b2)' puts '=======NOTATION========' puts 'Pawn: p' puts 'Bishop: B' puts 'Rook: R' puts 'Knight: N' puts 'Queen: Q' puts 'King: K' end def play turn until over? if won? @winner == :black || @winner == :white puts "\nCongratulations #{@players[winner].name}! You won!!\n\n" elsif stalemate? puts 'Cats Game!' end end def turn current_player = @board.current_player user_input = @players[@board.current_player].move until @board.valid_move?(user_input) puts "Invalid move #{@board.hint(user_input)}" user_input = @players[@board.current_player].move end @board.update(move: user_input) @winner = current_player if won? @board.display_board @board.next_player end def over? !@board.legal_moves? end def checkmate? over? && @board.check? end def won? over? && board.checkmate? end def stalemate? over? && !board.checkmate? end end
true
3e4145a623c4493933d9207bf4d0a0a6ba3071ab
Ruby
ajessen-thp/exercice_ruby
/exo_13.rb
UTF-8
120
3.296875
3
[]
no_license
puts "Qu'elle est ton année de naissance ?" year = gets.chomp.to_i i = year while i != 2017 do i = i + 1 puts i end
true
e66d4ee55dfe9c5618189b9c218f6fa12f242c5c
Ruby
CDRH/african_poetics
/config/initializers/data.rb
UTF-8
514
2.5625
3
[]
no_license
# this file collects the country and region information # for display on the map pages yml_path = File.join(Rails.root, "config", "data", "countries.yml") begin COUNTRIES = YAML.load_file(yml_path)["countries"] # TODO remove or alter this when we are no longer supporting originally # proof of concept map codes = {} COUNTRIES.each do |country, info| codes[country] = info["code"] end COUNTRY_CODES = codes rescue => e puts "something went wrong loading the countries.yml file: #{e}" end
true
367eb75f1dfe6c21271a003eac405cdd07c2dab6
Ruby
mattcameron/WDI-MELB-2_Homework
/Matt Cameron/classwork/7-tdd/tdd/phone/phone.rb
UTF-8
376
3.6875
4
[]
no_license
class Phone def initialize(number) @number = number.tr('(). -', '') end def number @number[0] = '' if @number[0..1] == "11" && @number.length == 11 @number = "0000000000" if @number.length == 11 || @number.length == 9 @number end def area_code @number[0..2] end def to_s @number.insert(0, '(') @number.insert(4, ') ') @number.insert(9, '-') end end
true
c5f5d3e59e0f41699818c546626d96fb5d820b64
Ruby
aherrmann20/Week_1_Project
/rehearse-app.rb
UTF-8
3,202
2.65625
3
[]
no_license
require "sinatra" get '/' do erb :home end get "/songs/:song" do |song| random_number = rand(3) if random_number == 0 redirect("https://www.youtube.com/watch?v=dQw4w9WgXcQ") end @songs = { breaking_free: { movie: "High School Musical", lyrics: "http://www.lyricsmode.com/lyrics/h/high_school_musical/breaking_free.html", youtube_link: "O6fpbBoIrXI" }, can_i_have_this_dance: { :movie => "High School Musical 3", :lyrics => "http://www.metrolyrics.com/can-i-have-this-dance-lyrics-vanessa-hudgens.html", :youtube_link => "fCa8pxUtN1s" }, can_you_feel_the_love_tonight: { :movie => "The Lion King", :lyrics => "http://www.azlyrics.com/lyrics/eltonjohn/canyoufeelthelovetonight.html", :youtube_link => "aF4CWCXirZ8" }, for_the_first_time_in_forever: { :movie => "Frozen", :lyrics => "http://www.azlyrics.com/lyrics/idinamenzel/forthefirsttimeinforever.html", :youtube_link => "EgMN0Cfh-aQ" }, i_see_the_light: { :movie => "Tangled", :lyrics => "http://www.azlyrics.com/lyrics/mandymoore/iseethelight.html", :youtube_link => "j5iFxpkz40o" }, if_i_didnt_have_you: { :movie => "Monsters, Inc.", :lyrics => "https://www.justsomelyrics.com/676419/monsters,-inc-if-i-didn't-have-you-lyrics.html", :youtube_link => "MRhnWA84qwc" }, if_i_never_knew_you: { :movie => "Pocahontas", :lyrics => "http://www.lyricsmode.com/lyrics/p/pocahontas/if_i_never_knew_you.html", :youtube_link => "KiuBw_kj1-U" }, love_is_an_open_door: { :movie => "Frozen", :lyrics => "http://www.metrolyrics.com/love-is-an-open-door-lyrics-kristen-bell.html", :youtube_link => "nPImqZo0D74" }, love_will_find_a_way: { :movie => "The Lion King II: Simba's Pride", :lyrics => "http://www.metrolyrics.com/love-will-find-a-way-lyrics-lion-king.html", :youtube_link => "5XhufW7-c_k" }, we_are_one: { :movie => "The Lion King II: Simba's Pride", :lyrics => "http://www.lionking.org/lyrics/RTPR/WeAreOne.html", :youtube_link => "glDGAo9SIqs" }, a_whole_new_world: { :movie => "Aladdin", :lyrics => "http://www.metrolyrics.com/a-whole-new-world-lyrics-aladdin.html", :youtube_link => "kl4hJ4j48s" }, you_are_the_music_in_me: { :movie => "High School Musical 2", :lyrics => "http://www.metrolyrics.com/you-are-the-music-in-me-lyrics-vanessa-hudgens.html", :youtube_link => "cxznbn-BLXs" } } song_name = params["song"] song_key = song_name.to_sym @song_movie = @songs[song_key][:movie] @song_lyrics = @songs[song_key][:lyrics] @song_link = @songs[song_key][:youtube_link] song_name_array = song_name.split('_') capitalized_song_array = [] song_name_array.each do |word| capitalized_song_array << word.capitalize end @displayed_song_name = capitalized_song_array.join(' ') erb :song end get "/songs" do @songs = ["Breaking Free", "Can I Have This Dance", "Can You Feel the Love Tonight", "For the first Time in Forever", "I See the Light", "If I Didnt Have You", "If I Never Knew You", "Love is an Open Door", "Love Will Find a Way", "We Are One", "A Whole New World", "You are the Music in Me"] erb :song_index end
true
ae53da1507bb9f734da67352c55aedb79307c160
Ruby
Alex2Yang/prepcourse_ruby_exercises
/tla_ruby_workbook/easy_quiz_2/ex9.rb
UTF-8
152
3.421875
3
[]
no_license
# Using array#map!, shorten each of these names to just 3 characters: # # flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles) # flintstones.map! { |i| i[0..2]}
true
e68611096bb2e7b89a6bc27b2fcba8ee97274050
Ruby
Velfolt/fyb
/lib/fyb/client.rb
UTF-8
2,215
2.828125
3
[ "MIT" ]
permissive
module Fyb # Client class containing all the methods needed to buy and sell btc. class Client # Returns the current ask price. def ask BigDecimal Fyb.public.ticker.perform.parse['ask'], 2 end # Returns the current bid price. def bid BigDecimal Fyb.public.ticker.perform.parse['bid'], 2 end # Returns a couple of the last asks and bids. def orderbook Fyb.public.orderbook.perform.parse end # Returns trades. # # Fyb.trades # Fyb.trades Time.now.to_i # # * +tid+ tradeid to begin history from def trades(tid = nil) params = { since: tid } unless tid.nil? params ||= {} plain_orders = Fyb.public.trades(params).perform.parse return [] if plain_orders.empty? plain_orders.map do |data| Order.new data['amount'], data['price'], :undefined, data['tid'] end end # Returns true if the authorization key and signature was correct. def test data = Fyb.private.test.perform.parse data['msg'] == 'success' end # Creates and performs a buy order. # # Returns the order. def buy!(qty, price) order = Fyb::Order.new qty, price, :buy order.perform end # Creates and performs a sell order. # # Returns the order. def sell!(qty, price) order = Fyb::Order.new qty, price, :sell order.perform end # Returns your currenct balance and the currency you have configured. def balance wallet = Fyb.private.getaccinfo.perform.parse btc_label = 'btcBal' money_label = Fyb::Configuration.currency.to_s + 'Bal' btc = BigDecimal.new wallet[btc_label] real_money = BigDecimal.new wallet[money_label] { :btc => btc, Fyb::Configuration.currency => real_money } end # Returns your order history. def order_history(limit = 10) plain_orders = Fyb.private.getorderhistory(limit: limit).perform.parse error = plain_orders['error'] fail Exception, error unless error == 0 plain_orders['orders'].map do |data| Order.new data['qty'], data['price'], data['type'] == 'B' ? :buy : :sell, data['ticket'] end end end end
true
8b51c28c584f88e2a11b5fdf92fa8149acc8edbd
Ruby
isabella232/statue
/lib/statue/backends/udp.rb
UTF-8
812
2.5625
3
[ "MIT" ]
permissive
require 'socket' module Statue class UDPBackend attr_reader :host, :port def self.from_uri(uri) uri = URI(uri) new(host: uri.host, port: uri.port) end def initialize(host:, port:) @host = host @port = port end def collect_metric(metric) if metric.sample_rate == 1 || rand < metric.sample_rate send_to_socket metric.to_s end end alias :<< :collect_metric private def socket Thread.current[:statue_socket] ||= begin socket = UDPSocket.new(Addrinfo.ip(host).afamily) socket.connect(host, port) socket end end def send_to_socket(message) Statue.debug(message) socket.send(message, 0) rescue => e Statue.error("#{e.class} #{e}") nil end end end
true
f21199b78877641b23aa37ef3753f2d4eb29624a
Ruby
showwin/AtCoder
/agc001/A.rb
UTF-8
190
2.96875
3
[]
no_license
n = gets.to_i c = gets.split("").map{|str| str.to_i } cnt = [] 1.upto(4) do |ans| cnt[ans-1]=0 n.times do |i| cnt[ans-1] += 1 if ans == c[i] end end print "#{cnt.max} #{cnt.min}\n"
true
db5ad3e93336ba8c56a310d79c30a29837cb364f
Ruby
firehose-codemasters/codemasters_chess
/app/models/game.rb
UTF-8
2,457
2.6875
3
[]
no_license
class Game < ApplicationRecord belongs_to :white_player, class_name: 'User' belongs_to :black_player, class_name: 'User' validates :name, presence: true has_many :pieces # Need to communicate that each game has this validates :result, inclusion: { in: %w(in_progress white_win black_win draw), message: '%{value} is not a valid result' } validates :white_player, presence: true validates :black_player, presence: true # Game rules of chess def set_pieces # white pieces (1..8).each do |index| Pawn.create(game_id: id, x_position: index, y_position: 2, color: 'white', active: true) end Rook.create(game_id: id, x_position: 1, y_position: 1, color: 'white', active: true) Knight.create(game_id: id, x_position: 2, y_position: 1, color: 'white', active: true) Bishop.create(game_id: id, x_position: 3, y_position: 1, color: 'white', active: true) Queen.create(game_id: id, x_position: 4, y_position: 1, color: 'white', active: true) King.create(game_id: id, x_position: 5, y_position: 1, color: 'white', active: true) Bishop.create(game_id: id, x_position: 6, y_position: 1, color: 'white', active: true) Knight.create(game_id: id, x_position: 7, y_position: 1, color: 'white', active: true) Rook.create(game_id: id, x_position: 8, y_position: 1, color: 'white', active: true) # black pieces (1..8).each do |index| Pawn.create(game_id: id, x_position: index, y_position: 7, color: 'black', active: true) end Rook.create(game_id: id, x_position: 1, y_position: 8, color: 'black', active: true) Knight.create(game_id: id, x_position: 2, y_position: 8, color: 'black', active: true) Bishop.create(game_id: id, x_position: 3, y_position: 8, color: 'black', active: true) Queen.create(game_id: id, x_position: 4, y_position: 8, color: 'black', active: true) King.create(game_id: id, x_position: 5, y_position: 8, color: 'black', active: true) Bishop.create(game_id: id, x_position: 6, y_position: 8, color: 'black', active: true) Knight.create(game_id: id, x_position: 7, y_position: 8, color: 'black', active: true) Rook.create(game_id: id, x_position: 8, y_position: 8, color: 'black', active: true) end def next_turn cc_stager = current_color rc_stager = resting_color update(current_color: rc_stager) update(resting_color: cc_stager) end end
true
ada5927760588e07cb577e8f0b33fab7eee8ece6
Ruby
bschwartz10/def_method
/lib/player.rb
UTF-8
468
3.421875
3
[]
no_license
class Player attr_reader :player, :last_name, :first_name, :gender, :favorite_color, :date_of_birth def initialize(player) @player = player @last_name = player[0] @first_name = player[1] @gender = formatted_gender @favorite_color = player[3] @date_of_birth = formatted_date_of_birth end def formatted_date_of_birth player[4].tr('-', '/') end def formatted_gender player[2].start_with?('M') ? 'Male' : 'Female' end end
true
b9de71b2c0e1fda8c88f2f571efce77c35ca2c5b
Ruby
jpietrzyk/kwh-api
/app/services/get_cached_request_service.rb
UTF-8
975
2.875
3
[]
no_license
require 'redis' require 'json' # This is first layer cache writter. It saves request url as a key, and # parsed and validated result as a value, so when request is in cache # we don't need parse raw xml, and validate responsed data class GetCachedRequestService def initialize(request:) @redis = Redis.new @request = request @data = nil end def call parse_data Result.new(status: :success, data: data, message: data ? 'Request found. SUCCESS' : 'Request not found. SUCCESS') rescue StandardError => e Result.new(status: :failure, data: request, message: "Getting from cache failed: #{e.message} See the errors for more information", errors: [e]) end private attr_accessor :request, :redis, :data def parse_data @data = JSON.parse(redis.get(request)) end def clear_cache! redis.keys.each { |k| redis.del k } end end
true
638309ffa6c80432b1a8249e0f942322eda1caeb
Ruby
somcode/Leap-years
/lib/leap_year.rb
UTF-8
89
2.84375
3
[ "MIT" ]
permissive
def leap_year?(year) (year % 400).zero? || (year % 4).zero? && !(year % 100).zero? end
true
1e815f45b2f26364a3759972a7b73f6e0e3805b1
Ruby
kelvinjhwong/ruby-exercises
/ruby-small-problems/03_easy_3/03_10.rb
UTF-8
542
4.0625
4
[]
no_license
# Does not work for numbers with leading 0s require 'pry' def palindromic_number?(number) number = number.to_s binding.pry while number.start_with? '0' number = number[1..-1] end number == number.reverse end puts palindromic_number?(034543) == true puts palindromic_number?(00123210) == false puts palindromic_number?(00022) == true puts palindromic_number?(05) == true puts palindromic_number?(34543) == true puts palindromic_number?(123210) == false puts palindromic_number?(22) == true puts palindromic_number?(5) == true
true
f1e8998330e56851785aa2d4b4223266d0a034c7
Ruby
konung/rubytoolbox
/app/models/search.rb
UTF-8
327
2.59375
3
[ "MIT" ]
permissive
# frozen_string_literal: true class Search attr_accessor :query private :query= def initialize(query) self.query = query.presence&.strip end def query? query.present? end def projects @projects ||= Project.search(query) end def categories @categories ||= Category.search(query) end end
true
afb15e8202bfa3a7188b71d4d1950fff733fee68
Ruby
amyfranz/ruby-metaprogramming-mass-assignment-lab-london-web-012720
/lib/person.rb
UTF-8
722
2.875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Person attr_accessor :name, :birthday, :hair_color, :eye_color, :height, :weight, :handed, :complexion, :t_shirt_size, :wrist_size, :glove_size, :pant_length, :pant_width @@all = [] def initialize(*args) @name = args[0][:name] @birthday = args[0][:birthday] @hair_color = args[0][:hair_color] @eye_color = args[0][:eye_color] @height = args[0][:height] @weight = args[0][:weight] @handed = args[0][:handed] @complexion = args[0][:complexion] @t_shirt_size = args[0][:t_shirt_size] @wrist_size = args[0][:wrist_size] @glove_size = args[0][:glove_size] @pant_length = args[0][:pant_length] @pant_width = args[0][:pant_width] @@all << self end end
true
2f06ab5e05425f26c580d1c0d5ac60f697ee4a42
Ruby
Umnums/ttt-7-valid-move-online-web-sp-000
/lib/valid_move.rb
UTF-8
500
3.5
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def position_taken?(board,index) if (board[index] == "" || board[index] == " " || board[index] == nil) return false else puts "true" return true end end def valid_move?(board, index) if (index >= 0 && index <= 8 && !position_taken?(board,index)) puts "true" return true else puts "false" return false end end board = ["","",""] valid_move?(board, 2) # re-define your #position_taken? method here, so that you can use it in the #valid_move? method above.
true
b3a073aae78a06e2524c323f2c13c8d39b81ac57
Ruby
mofahmy/clio
/scripts/scrape_cfps.rb
UTF-8
3,456
2.921875
3
[ "CC0-1.0" ]
permissive
#!/usr/bin/ruby require 'rubygems' require 'nokogiri' require 'open-uri' require 'sqlite3' $script_dir = File.dirname(__FILE__) # Read in categories names from a text file (one per line) def load_categories(file) categories = IO.readlines(file) categories.each do |cat| cat.strip! end return categories end # Return the id of a category in the database given its name def get_category_id(category) db = SQLite3::Database.new "#{$script_dir}/cfps.db" category_id = db.get_first_value("select id from category where name = ?", [category]) return category_id end # Return the name of a category in the database given its id def get_category_name(category_id) db = SQLite3::Database.new "#{$script_dir}/cfps.db" category = db.get_first_value("select name from category where id = ?", [category_id]) return categor end # Fetch the HTML containing list of CFPs for a category def scrape_cfp_list(category) category_encoded = category.sub(' ','%20') content = '' page = 1 until (content =~ /Expired/) uri = "http://www.wikicfp.com/cfp/call?conference=#{category_encoded}&page=#{page}" body = (Nokogiri::HTML(open(uri))).to_s content << body page += 1 end content = content.split(/Expired/).first return content end # Extract links for each individual CFP (from HTML containing list of CFPs) def scrape_cfp_links(content) page = Nokogiri::HTML(content) event_links = Array.new links = page.css("a") links.each do |a| if a["href"].include? "showcfp" event_links.push "http://wikicfp.com#{a["href"]}" end end return event_links end # Scrapes info about a particular CFP and stores it in the database def scrape_and_store_cfp_info(category_id, link) uri = link page = Nokogiri::HTML(open(uri)) event = page.css('title').text headers = Array.new data = Array.new # Get Table Headers page.xpath('//tr/th').each do |e| headers.push(e.text.to_s) end # Get Table Data page.xpath('//tr/th/following-sibling::*').each do |d| data.push(d.text.strip) end hash = Hash[headers.zip(data)] event_name = event[/(.*?):/,1].strip event_full_name = (event[/:(.*)/,1] || event_name).strip event_date = (hash["When"] || "N/A") event_location = (hash["Where"] || "N/A") abstract_due = (hash["Abstract Registration Due"] || "N/A") submission_due = (hash["Submission Deadline"] || "N/A") notification_due = (hash["Notification Due"] || "N/A") final_due = (hash["Final Version Due"] || "N/A") official_link = (page.to_s[/Link:\s*<a\shref="(.*?)"/,1] || "N/A").strip wikicfp_link = uri db = SQLite3::Database.new "#{$script_dir}/cfps.db" db.execute("INSERT INTO event (id, category_id, name, full_name, date, location, abstract_due, submission_due, notification_due, final_due, wikicfp_link, official_link) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", [nil, category_id, event_name, event_full_name, event_date, event_location, abstract_due, submission_due, notification_due, final_due, wikicfp_link, official_link]) end # Main puts "Script dir: #{$script_dir}\n" categories = load_categories("#{$script_dir}/categories_full.txt") categories.each do |cat| puts "Processing category: #{cat}\n" category_id = get_category_id(cat) content = scrape_cfp_list(cat) links = scrape_cfp_links(content) links.each do |link| scrape_and_store_cfp_info(category_id, link) end end
true
cfb5789a9f43df8fd850833f1d42a78bf467afee
Ruby
CFWLoader/LeetCode
/Problem557/Solution.rb
UTF-8
644
3.5
4
[]
no_license
# @param {String} s # @return {String} def reverse_words(s) ret_val = '' end_idx = -1 back_idx = 0 iter_idx = 0 iter_end = s.size while iter_idx != iter_end if s[iter_idx] == ' ' back_idx = iter_idx - 1 while back_idx > end_idx ret_val << s[back_idx] back_idx -= 1 end ret_val << s[iter_idx] end_idx = iter_idx end iter_idx += 1 end back_idx = iter_idx - 1 while back_idx > end_idx ret_val << s[back_idx] back_idx -= 1 end ret_val end if $0 == __FILE__ testCase = 'Let\'s take LeetCode contest' p reverse_words testCase end
true
69d02a951df3c2fbbfefa53251143b5dd65fa818
Ruby
ucarion/moho
/lib/moho/lang.rb
UTF-8
1,459
2.796875
3
[ "MIT" ]
permissive
module Moho module Lang class Environment < Struct.new(:bindings, :parent) def [](name) bindings.fetch(name) { parent[name] } end def self.global Stdlib.env end end class Expression < Struct.new(:value) end class List < Expression def eval(env = Environment.global) operator, *arguments = self.value case operator.value when 'quote' value[1] when 'if' pred, conseq, alt = arguments[0], arguments[1], arguments[2] if pred.eval(env) conseq else alt end.eval(env) when 'lambda' params_list, body = value[1], value[2] formal_parameters = params_list.value.map(&:value) Proc.new do |args| bindings = Hash[formal_parameters.zip(args)] body.eval(Environment.new(bindings, env)) end else evaled_arguments = arguments.map { |exp| exp.eval(env) } operator.eval(env).call(evaled_arguments) end end end class LiteralExpression < Expression def eval(env = Environment.global) value end end class Bool < LiteralExpression end class Int < LiteralExpression end class String < LiteralExpression end class Symbol < Expression def eval(env = Environment.global) env[value] end end end end
true
feda140fbc54f9a0fa8957aab4013602a30d929c
Ruby
hawkenritter/phase-0-tracks
/ruby/puppy_methods.rb
UTF-8
888
4.09375
4
[]
no_license
#class Puppy# # def fetch(toy) # puts "I brought back the #{toy}!" # toy # end# # def rollover # puts "*rollover*" # end# # def speak(integer) # puts "Woof! " * integer # end # def dog_years(human_years) # dog_age = 7 * human_years # puts "is " + dog_age.to_s + " years old" # end # def shake # puts "*reaches paw out to shake*" # end # def initialize # puts "initialize new puppy instance..." # end #end #fluffy = Puppy.new #fluffy.fetch("beer") #fluffy.rollover #fluffy.speak(5) #fluffy.dog_years(5) #fluffy.shake class Hooper def initialize #name #@name = name #puts "Go #{@name}!" end def shoot puts "Shoot the ball!" end def pass puts "Pass to the open man!" end end player_array = [] 50.times do player = Hooper.new player_array << player end p player_array player_array.each do |i| i.shoot i.pass end
true
2038ab95fb42e01151fd0f8e9dc5bfec3d8979e0
Ruby
SlevinMcGuigan/SMG
/library/test/tc_book_in_stock.rb
UTF-8
1,444
3.359375
3
[]
no_license
require 'test/unit' require 'lib/book_in_stock' class TcBookInStock < Test::Unit::TestCase def test_isbn_is_initialized_correctly book = BookInStock.new("1234",23) assert_equal("1234",book.isbn) end def test_price_is_initialized_correctly book = BookInStock.new("1234",23) assert_equal(23,book.price) end def test_price_may_not_be_initialized_with_a_string_value assert_raise( TypeError ) do BookInStock.new("TypeError expected","abcd") end end def test_price_may_not_be_initialized_with_zero_arguments assert_raise( ArgumentError) do BookInStock.new() end end def test_price_may_not_be_initialized_with_one_argument assert_raise( ArgumentError ) do BookInStock.new("ArgumentError expected") end end def test_price_may_not_be_initialized_with_three_arguments assert_raise( ArgumentError ) do BookInStock.new("ArgumentError expected",1234,"blub") end end def test_price_can_be_changed book = BookInStock.new("1234",23) book.price = book.price + 10 assert_equal(33,book.price) end def test_isbn_can_not_be_changed book = BookInStock.new("1234",23) assert_raise( NoMethodError ) do book.isbn = "2345" end end def test_to_s_prints_enriched_information book = BookInStock.new("1234",23) assert_equal("ISBN: '1234', price: '23.00'",book.to_s) end end
true
4bf1cee6da5fcba1e6d37aac345b3284ae746921
Ruby
JayZonday/oo-cash-register-web-112017
/lib/cash_register.rb
UTF-8
1,200
3.28125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class CashRegister attr_accessor :discount, :total, :items def initialize(discount=0) @total = 0 @discount = discount @items = [] end def add_item(title, price, quantity = 1) @last_total = total @total += price * quantity quantity.times do @items << title end end def apply_discount if discount > 0 @total = @total *(100-discount)/100 "After the discount, the total comes to $#{@total}." else "There is no discount to apply." end end def void_last_transaction @total = @last_total end end # class CashRegister # attr_accessor :total # def initialize(discount = 0) # @total = 0 # @discount = discount # @items = [] # @last_total = 0 # end # def total # @total # end # def discount # @discount # end # def add_item(title, price, quantity = 1) # @last_total = @total # @total += price * quantity # quantity.times do # @items << title # end # end # def apply_discount # if @discount > 0 # @total = @total*(100-@discount)/100 # "After the discount, the total comes to $#{@total}." # else # "There is no discount to apply." # end # end # def items # @items # end # def void_last_transaction # @total = @last_total # end # end
true
0e095e38ded8854aa1a4b03909e6561caa476726
Ruby
kimpalita/ironhack_week_01_02
/ex_unit_test/spec/conway_game2_spec.rb
UTF-8
1,552
2.703125
3
[]
no_license
require_relative '../conway_game2.rb' require 'pry' RSpec.describe "" do before :each do @grid_cells = [{x: 1, y: 1}, {x: 1, y: 2}, {x: 1, y: 3}, {x: 2, y: 1}, {x: 2, y: 2}, {x: 2, y: 3}, {x: 3, y: 1}, {x: 3, y: 2}, {x: 3, y: 3}] end let(:first_seeds) do instance_double("Seed Generation Grid", :seed_positions => [{x: 2, y: 2}, {x: 2, y: 1}, {x: 2, y: 3}]) end let(:gen_one){GenerationOne.new([{x: 2, y: 2}, {x: 2, y: 1}, {x: 2, y: 3}])} let(:gen_two){GenerationOne.new(gen_one.next_gen_cells)} #------------------------------------------------ it "show empty array for live cells in first generation" do expect(gen_one.live_cells).to match_array([]) end it "show live cells in the first generation" do gen_one.cells_states(@grid_cells) expect(gen_one.live_cells).to match_array([{x: 2, y: 1}, {x: 2, y: 2}, {x: 2, y: 3}]) end it "show dead cells in the first generation" do gen_one.cells_states(@grid_cells) expect(gen_one.dead_cells).to match_array([{:x=>1, :y=>1}, {:x=>1, :y=>2}, {:x=>1, :y=>3}, {:x=>3, :y=>1}, {:x=>3, :y=>2}, {:x=>3, :y=>3}]) end it "show cells that will survive the next generation" do gen_one.cells_states(@grid_cells) gen_one.sort_survivors expect(gen_one.next_gen_cells).to match_array([{x: 1, y: 2}, {x: 2, y: 2}, {x: 3, y: 2}]) end it "show live cells in the new generation" do gen_one.cells_states(@grid_cells) gen_one.sort_survivors gen_two.cells_states(@grid_cells) expect(gen_two.live_cells).to match_array([{x: 1, y: 2}, {x: 2, y: 2}, {x: 3, y: 2}]) end end
true
90a1c59c583881c302c6a980c09c5e60e0333ccb
Ruby
tylerb33/ruby-lists
/planets.rb
UTF-8
1,440
4.0625
4
[]
no_license
planet_list = ["Mercury", "Mars"] #Use push() to add Jupiter and Saturn at the end of the array. planet_list.push("Jupiter", "Saturn") # puts planet_list #Use the concat() method to add another array of the last two planets in our solar system to the end of the array. planet_list.concat(["Uranus", "Neptune"]) #Use insert() to add Earth, and Venus in the correct order. planet_list.insert(1, "Venus", "Earth") #Use << ("shovel operator") to add Pluto to the end of the array. planet_list << "Pluto" # puts planet_list # Now that all the planets are in the array, slice the array in order to get the rocky planets into a new list called rocky_planets. rocky_planets = Array.new rocky_planets = planet_list.slice(0, 4) puts rocky_planets #Being good amateur astronomers, we know that Pluto is now a dwarf planet, so use the pop operation to remove it from the end of planet_list. planet_list.pop puts planet_list #Create another array containing arrays where each array will hold the name of a spacecraft that we have launched, and the names of the planet(s) that it has visited, or landed on. (e.g. ['Cassini', 'Saturn']). spacecraft_facts = [['Cassini', 'Saturn'],['Juno', 'Jupiter'],['Curiosity', 'Mars'],['Voyager 2', 'Uranus'],['Pioneer 10', 'Jupiter']] print spacecraft_facts #Iterate over your array of planets, and inside that loop, iterate over the array of arrays. Print, for each planet, which satellites have visited.
true
c720872039757059d85824173483fd22dffe9a32
Ruby
bertrandk/botr
/lib/botr/videos/video_tag.rb
UTF-8
1,666
2.84375
3
[ "MIT" ]
permissive
module BOTR # The BOTR::VideoTag class contains calls for manipulating video tags. # # Tags are essentially labels that can be used for the classification of # videos. class VideoTag < BOTR::Object class << self attr_reader :last_status # Return a list of video tags. # # @param [Hash] options search parameters # # @option options [String] search case-insensitive search in the # name tag field # @option options [String] order_by specifies parameters by which # returned result should be ordered; ":asc" and ":desc" can be # appended accordingly # @option options [Integer] result_limit specifies maximum number of # tags to return; default is 50 and maximum result limit is 1000 # @option options [Integer] result_offset specifies how many tags # should be skipped at the beginning of the result set; default is # 0 # # @return [Array] a list of tag objects matching the search # criteria def list(**options) json = get_request(options.merge(:method => 'list')) res = JSON.parse(json.body) if json.status == 200 results = process_list_response(res) else raise "HTTP Error #{json.status}: #{json.body}" end return results end def all list({}) end private def process_list_response(body) res = [] body["tags"].each do |tag| res << new(tag) end return res end end attr_reader :name ,:videos def initialize(params = {}) params.each do |key, val| param = "@#{key.to_s}" next unless methods.include? key.to_sym instance_variable_set(param, val) end end end end
true
37599c0c46c05171900a4b7d4e9ad9267dfe911e
Ruby
ekene966/hackerrank
/ruby/compare_the_triplets.rb
UTF-8
512
3.59375
4
[ "MIT" ]
permissive
# Triplet Comparator class TripletComparator def self.scores(a_triplet, b_triplet) "#{a_score(a_triplet, b_triplet)} #{b_score(a_triplet, b_triplet)}" end def self.a_score(a_triplet, b_triplet) a_triplet.zip(b_triplet).count { |a, b| a > b } end def self.b_score(a_triplet, b_triplet) a_triplet.zip(b_triplet).count { |a, b| a < b } end end a_triplet = gets.strip.split(' ').map(&:to_i) b_triplet = gets.strip.split(' ').map(&:to_i) puts TripletComparator.scores(a_triplet, b_triplet)
true
e1d65a3dfefdf12c79e4cdf8973a20376a73573f
Ruby
remyaub/ruby
/exo_21.rb
UTF-8
352
3.21875
3
[]
no_license
puts " Salut, bienvenue dans ma super pyramide ! Combien d'étages veux-tu ?" print " > " userFloor = gets.to_i v = 0 diez = "#" space = " " if userFloor <= 25 puts "Let's go bro" loop do break if v == userFloor (userFloor - 1 - v).times do print space end puts diez diez += "#" v += 1 end else puts "Take it easy bro..." end
true
55dd91d3d44ecddeedb37847cf9139f2cd8236a1
Ruby
stefanp227/Athlon-task
/spec/deck_spec.rb
UTF-8
650
3.109375
3
[]
no_license
require_relative '../deck' require_relative '../card' require_relative 'spec_helper' describe Deck, "#count" do context "testing deck functionalities" do it "checks the size of the deck" do deck = Deck.new expect(deck.count).to eql 52 end end end describe Deck, "#draw" do context "testing deck functionalities" do it "tests draw function" do deck = Deck.new deck.draw(5) expect(deck.count).to eql 47 end end end describe Deck, "#shuffle!" do context "testing deck functionalities" do it "tests the shuffle! function" do deck = Deck.new deck2 = deck.shuffle! expect(deck == deck2).to eql false end end end
true
c345c5e682c971fca8c450e243796cad6c7c6948
Ruby
pooja-yadav-ctrl/Ror-training
/ruby monk/cubes.rb
UTF-8
97
3.546875
4
[]
no_license
def sum_of_cubes(a, b) (a..b).inject(0) { |sum, x| sum += (x*x*x)} end puts sum_of_cubes(1,3)
true
c132af22fa6b92481a36c3a0d09e664f04618638
Ruby
ducc/dablang
/src/compiler/nodes/node_reference_member.rb
UTF-8
391
2.65625
3
[ "MIT" ]
permissive
require_relative 'node_reference.rb' class DabNodeReferenceMember < DabNodeReference def initialize(base, name) super() insert(base) @name = name end def base children[0] end def name @name end def compiled DabNodePropertyGet.new(base.compiled, @name) end def formatted_source(options) base.formatted_source(options) + '.' + name end end
true