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
ad34778728c055470eb5e389531d9dee6bd289ad
Ruby
AbbiAld/anagram
/app/controllers/index_controller.rb
UTF-8
530
3.140625
3
[]
no_license
get '/' do erb :index end post '/' do @word = params[:word] def empty_input?(input) if input.empty? raise Exception.new("Oops! Looks like your didn't enter a word. Please enter a word!") end end begin !empty_input?(@word) redirect "/anagrams/#{@word}" rescue Exception => error @error = error.message erb :index end end get '/anagrams/:word' do @word = params[:word] @anagrams = Word.find_anagrams(@word) if @anagrams.empty? @error = "Sorry! There are no anagrams for that word." end erb :show end
true
268a05d69479dd2d102bd3cadc5e3ac58c4e7db7
Ruby
Zhao-Andy/shine
/db/seeds.rb
UTF-8
1,638
2.75
3
[]
no_license
# Helper method to create a billing address for a customer def create_billing_address(customer_id,state) billing_address = Address.create!( street: Faker::Address.street_address, city: Faker::Address.city, state: state, zipcode: Faker::Address.zip ) CustomersBillingAddress.create!(customer_id: customer_id, address: billing_address) end # Helper method to create a shipping address for a customer def create_shipping_address(customer_id,state,is_primary) shipping_address = Address.create!( street: Faker::Address.street_address, city: Faker::Address.city, state: state, zipcode: Faker::Address.zip ) CustomersShippingAddress.create!(customer_id: customer_id, address: shipping_address, primary: is_primary) end # Cache the number of states so we don't have to query # ecah time through all_states = State.all.to_a # For all customers Customer.find_each do |customer| # Do not recreate addresses if this customer has them next if customer.customers_shipping_address.any? puts "Creating addresses for #{customer.id}..." # Create a billing address for them create_billing_address(customer.id,all_states.sample) # Create a random number of shipping addresses, making # sure we create at least 1 num_shipping_addresses = rand(4) + 1 num_shipping_addresses.times do |i| # Create the shipping address, setting the first one # we create as the "primary" create_shipping_address(customer.id,all_states.sample,i == 0) end end
true
8ca92bcb1fcb5c1e23f26d53ea14346393a83c9d
Ruby
atlochowski/git_test
/Odin_ruby/caesar.rb
UTF-8
342
3.765625
4
[]
no_license
def cipher(strings, num) arr = [] strings.each_char { |n| arr << n.ord} arr.each do |n| if (97..122).include?(n) n > 122 - num ? n = 96 + (num - (122 - n)) : n += num elsif (60..90).include?(n) n > 90 - num ? n = 64 + (num - (90 - n)) : n += num else n end letter = n.chr print letter end end cipher("What a string!", 5)
true
39f02216e7959f9bc9f5004618cdcbfab569744c
Ruby
snoremac/buildlight
/lib/drivers/delcom_904008.rb
UTF-8
1,428
2.71875
3
[]
no_license
require 'usb' class Light VENDOR_ID = 0x0fc5 PRODUCT_ID = 0xb080 INTERFACE_ID = 0 OFF = "\x00" GREEN = "\x01" RED = "\x02" YELLOW = "\x04" def initialize @device = USB.devices.find {|device| device.idVendor == VENDOR_ID && device.idProduct == PRODUCT_ID} raise "Unable to find device" unless @device end def green msg(GREEN) end def yellow msg(YELLOW) end def red msg(RED) end def off msg(OFF) end def close handle.release_interface(INTERFACE_ID) handle.usb_close @handle = nil end private def msg(data) handle.usb_control_msg(0x21, 0x09, 0x0635, 0x000, "\x65\x0C#{data}\xFF\x00\x00\x00\x00", 0) end def handle return @handle if @handle @handle = @device.usb_open begin # ruby-usb bug: the arity of rusb_detach_kernel_driver_np isn't defined correctly, it should only accept a single argument. if USB::DevHandle.instance_method(:usb_detach_kernel_driver_np).arity == 2 @handle.usb_detach_kernel_driver_np(INTERFACE_ID, INTERFACE_ID) else @handle.usb_detach_kernel_driver_np(INTERFACE_ID) end rescue Errno::ENODATA => e # Already detached end @handle.set_configuration(@device.configurations.first) @handle.claim_interface(INTERFACE_ID) @handle end end
true
9554b8b2bd7397e7d2e16fe3e1ffa98a5081cabc
Ruby
jimjh/genie-tangle
/lib/tangle/tty.rb
UTF-8
2,192
2.8125
3
[]
no_license
require 'thread' require 'active_support/core_ext/class/attribute' require 'tangle/ssh' module Tangle # This class is designed to be thread-safe tty factory. During # initialization, the success of the connection is unknown; however, on # failure, the dead terminal is removed from the +TTY.terms+ array. class TTY EXPIRY_TIMER = 15*60 # check every 15 minutes class_attribute :terms, :mutex, :timer_added self.terms = {} # XXX: state should be persisted self.mutex = Mutex.new self.timer_added = false private_class_method :new # @return [SSH::Base] tty def self.create(user_id, opts={}) add_timer unless timer_added cls = (ENV['RACK_ENV'] == 'production') ? SSH::Remote : SSH::Local tty = cls.new owner: user_id, faye_client: faye_client, logger: logger TTY << tty tty.on_close { TTY.delete tty } tty.open opts tty end # Retrieves terminals for given owner and tty id. def self.[](owner, id) mutex.synchronize do terms.has_key?(owner) ? terms[owner][id] : nil end end # Adds a new terminal to the list. Thread-safe. def self.<<(tty) mutex.synchronize do terms[tty.owner] ||= {} terms[tty.owner][tty.object_id] = tty end end # Removes a terminal from the list. Thread-safe. def self.delete(tty) mutex.synchronize do if terms.has_key? tty.owner terms[tty.owner].delete(tty.object_id) terms.delete(tty.owner) if terms[tty.owner].empty? end end end def self.count mutex.synchronize { terms.count } end def self.faye_client Tangle.faye.get_client end private_class_method :faye_client def self.logger Tangle.logger end def self.each terms.each do |_, ttys| ttys.each { |_, tty| yield tty } end end def self.add_timer EM.add_periodic_timer(EXPIRY_TIMER) do self.each do |tty| if tty.expired? logger.info "[tty] tty for #{tty.owner} expired" tty.close end end end self.timer_added = true end end end
true
5eeda72f5c9cb0b2759e162bd91507b5e75adcbf
Ruby
johanneswuerbach/dynamodb-stream-enumerator
/lib/dynamodb/stream/enumerator/shard_reader.rb
UTF-8
759
2.546875
3
[ "MIT" ]
permissive
require "dynamodb/stream/enumerator/version" require "aws-sdk-dynamodbstreams" module Dynamodb module Stream class Enumerator < ::Enumerator class ShardReader def initialize(client, shard_iterator) @client = client @shard_iterator = shard_iterator end def finished? @shard_iterator.nil? end def get_records(limit) # https://docs.aws.amazon.com/sdk-for-ruby/v3/api/Aws/DynamoDBStreams/Client.html#get_records-instance_method resp = @client.get_records({ shard_iterator: @shard_iterator, limit: limit }) @shard_iterator = resp.next_shard_iterator resp.records end end end end end
true
03cd1ae56849762770e747a88fff91b90b1d051a
Ruby
uten0906/myself
/spec/models/user_spec.rb
UTF-8
2,874
2.5625
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do before do @user = FactoryBot.build(:user) end describe "nameのバリデーション確認" do context "半角英数字ではバリデーションされる" do it "1文字目は半角文字、2文字以降半角英数字である" do expect(@user).to be_valid end it "1文字目が数字である" do @user.name = "0test" expect(@user).to be_invalid end it "全角文字が含まれている" do @user.name = "テスト" expect(@user).to be_invalid end end context "空では保存されない" do it "空ではない場合" do expect(@user).to be_valid end it "空の場合" do @user.name = " " expect(@user).to be_invalid end end context "2文字未満では保存されない" do it "2文字未満の場合" do @user.name = "a" expect(@user).to be_invalid end it "2文字以上の場合" do @user.name = "a" * 2 expect(@user).to be_valid end end context "20文字を超えると保存されない" do it "20文字を超える場合" do @user.name = "a" * 21 expect(@user).to be_invalid end it "20文字以内の場合" do @user.name = "a" * 20 expect(@user).to be_valid end end it "一意性である" do duplicate_user = @user.dup duplicate_user.name = @user.name.upcase @user.save! expect(duplicate_user).to be_invalid end end describe "emailのバリデーションの確認" do context "emailが空でない" do it "空でない場合" do expect(@user).to be_valid end it "空の場合" do @user.email = " " expect(@user).to be_invalid end end context "emailのフォーマットの確認" do it "正しいフォーマット" do expect(@user).to be_valid end context "間違ったフォーマット1" do it "間違ったフォーマット" do @user.email = "foo@example@com" expect(@user).to be_invalid end it "間違ったフォーマット2" do @user.email = "foo@example,com" expect(@user).to be_invalid end it "間違ったフォーマット3" do @user.email = "foo@example" expect(@user).to be_invalid end it "間違ったフォーマット4" do @user.email = "foo@example_foo.com" expect(@user).to be_invalid end end end end context "passwordが空でない" do it "空でない場合" do expect(@user).to be_valid end it "passwordが空欄でない" do @user.password_digest = " " expect(@user).to be_invalid end end end
true
e3be30a5bbd83f068bc3d8972441f295024d0a9a
Ruby
Kphillycat/todos
/todo8/deli_spec.rb
UTF-8
560
3.265625
3
[]
no_license
require './deli' describe Deli, "#take_a_number" do my_deli = Deli.new it "should take customer's name and return array with their number and name" do expect(my_deli.take_a_number("KDizzle")).to eq(["1. KDizzle"]) end end describe Deli, "#now_serving" do my_deli = Deli.new my_deli.line = ["1. KDizzle", "2. BobBizzle", "3. FredSizzle"] it "should remove a customer from instance variable array and returns their name" do expect(my_deli.now_serving).to eq("KDizzle") expect(my_deli.line).to eq(["2. BobBizzle", "3. FredSizzle"]) end end
true
e581b1d2ac4a9d287fd4f41c5dce76a4f1fb2f9f
Ruby
Dofassh/airplane-challenge-2
/airport.rb
UTF-8
845
3.8125
4
[]
no_license
require 'weather' class Airport DEFAULT_CAPACITY = 30 def initialize(weather, capacity = DEFAULT_CAPACITY) @weather = weather @capacity = capacity @planes = [] end def land(plane) raise 'Capacity is full : Cannot land plane' if capacity_full raise 'Weather is stormy : Cannot land plane' if stormy? @planes << plane end def take_off(plane) raise 'Weather is stormy : Plane cannot take off' if stormy? #raise 'plane status : has left the station successfully' if at_airport?(plane) plane end def planes end private def capacity_full if @planes.length >= @capacity true else false end end def stormy? @weather.stormy? end def at_airport?(plane) @planes.include?(plane) end end
true
1dabb7732aa79472434dda05aa74109b172e1ef6
Ruby
nomlab/swimmy
/lib/swimmy/service/pollen_service.rb
UTF-8
1,199
2.71875
3
[ "MIT" ]
permissive
# coding: utf-8 require 'date' require 'csv' require 'net/http' module Swimmy module Service class Pollen class CityCodeException < StandardError; end class PollenException < StandardError; end def fetch_info(address, date) begin city_code = Service::CityCode.new.address_to_city_code(address) rescue raise CityCodeException.new end begin url = URI.parse("https://wxtech.weathernews.com/opendata/v1/pollen?") url.query = "citycode=#{city_code}&start=#{date.strftime("%Y%m%d")}&end=#{date.strftime("%Y%m%d")}" res = Net::HTTP.get(url) result = CSV.parse(res, headers: true) rescue raise PollenException.new end # データの提供元にてリザルトコードの扱いが示されていなかったため,正しくデータを取得できているか確認する return nil unless result[0] return Swimmy::Resource::Pollen.new( address, date, result[date.strftime("%H").to_i - 1]["pollen"].to_i) end end # class Pollen end # module Service end # module Swimmy
true
ba65b4dd75d37a3bfe67d0551360144bc5814a40
Ruby
Streetbees/home_network_identity
/test/test_home_network_identity.rb
UTF-8
2,114
2.578125
3
[]
no_license
require 'minitest/autorun' require 'home_network_identity' class HomeNetworkIdentityTest < Minitest::Test def test_country plmn = 60301 home_network_identity = HomeNetworkIdentity.new(plmn: plmn) assert_equal "Algeria", home_network_identity.country end def test_iso_country_code_GG plmn = 23403 home_network_identity = HomeNetworkIdentity.new(plmn: plmn) assert_equal "GG", home_network_identity.iso_country_code end def test_iso_country_code_GB plmn = 23401 home_network_identity = HomeNetworkIdentity.new(plmn: plmn) assert_equal "GB", home_network_identity.iso_country_code end def test_operator plmn = 26801 home_network_identity = HomeNetworkIdentity.new(plmn: plmn) assert_equal "Vodafone Portugal", home_network_identity.operator end def test_raw_by_plmn plmn = 26801 home_network_identity = HomeNetworkIdentity.new(plmn: plmn) assert_equal( [{"plmn"=>"26801", "nibbledPlmn"=>"62F810", "mcc"=>"268", "mnc"=>"01", "region"=>"Europe", "type"=>"National", "countryName"=>"Portugal", "countryCode"=>"PT", "lat"=>"39.5", "long"=>"-8", "brand"=>"Vodafone", "operator"=>"Vodafone Portugal", "status"=>"Operational", "bands"=>"GSM 900 / UMTS 900 / UMTS 2100 / LTE 800 / LTE 1800 / LTE 2600", "notes"=>"formerly Telecel (2001)"}], home_network_identity.raw_by_plmn ) end def test_operator_with_strings plmn = "26801" home_network_identity = HomeNetworkIdentity.new(plmn: plmn) assert_equal "Vodafone Portugal", home_network_identity.operator end def test_mcc_not_found plmn = 268234 home_network_identity = HomeNetworkIdentity.new(plmn: plmn) assert_nil home_network_identity.iso_country_code end def test_operator_with_mcc_mnc_pair_not_found plmn = 268111 home_network_identity = HomeNetworkIdentity.new(plmn: plmn) assert_nil home_network_identity.operator end def test_raw_by_plmn_with_mcc_mnc_pair_not_found plmn = 268111 home_network_identity = HomeNetworkIdentity.new(plmn: plmn) assert_equal [], home_network_identity.raw_by_plmn end end
true
efa6d65a226c149b3070bf1d211a7071480ce4ef
Ruby
christopheleray/learn_ruby_rspec
/02_calculator/calculator.rb
UTF-8
226
3.484375
3
[]
no_license
def add(x, y) return x + y end def subtract(x, y) return x - y end def sum(x) return x.sum end def multiply(x, y) return x * y end def power(x, y) return x ** y end def factorial(x) (1..x).reduce(:*) || 1 end
true
3112ab5b37f1bc43a0c344ad8966a9f63da4054f
Ruby
bfoz/sketch
/test/sketch/builder/repeat.rb
UTF-8
1,195
2.765625
3
[ "BSD-3-Clause" ]
permissive
require 'minitest/autorun' require 'sketch/builder/repeat' describe Sketch::Builder::Repeat do subject { Sketch::Builder::Repeat.new([0,0]) } it 'must simply repeat' do subject.build([0,4], 4) do |step| forward step end.must_equal [[0,1], [0,2], [0,3], [0,4]].map {|a| Point[a] } end it 'must ensure that the end of each repeat block is connected to the base line' do subject.build [0,4], 4 do |step| forward step left 1 end.must_equal [[0,1], [-1,1], [0,1], [0,2], [-1,2], [0,2], [0,3], [-1,3], [0,3], [0,4], [-1,4], [0,4]].map {|a| Point[a] } end it 'must have a first? attribute that is only true for the first repetition' do firsts = [] subject.build [0,4], 4 do |step| firsts.push first? end firsts.must_equal [true, false, false, false] end it 'must have a last? attribute that is only true for the last repetition' do lasts = [] subject.build [0,4], 4 do |step| lasts.push last? end lasts.must_equal [false, false, false, true] end it 'must be first? and last? when repeating only once' do subject.build [0,4], 1 do |step| first?.must_equal true last?.must_equal true end end end
true
326fe73dd00366952fb17af10a5e5c7753e14e29
Ruby
lizwilkins/go_fish_with_Thomas
/lib/game.rb
UTF-8
142
2.609375
3
[]
no_license
class Game def initialize end def over? draw_pool. players.each do |player| player.hand.length draw_pool. end end end
true
9b5d919bc66f375733d86b691843bb32f9008035
Ruby
e46and2/square_array-v-000
/square_array.rb
UTF-8
109
3.515625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array(array) array_squared = [] array.each { |i| array_squared << i ** 2 } array_squared end
true
f86f93c9ecfaf15f72fd8dfb58883985a28aa9c7
Ruby
bwanicur/nattysearch
/app/services/petfinder_service/queries/organization.rb
UTF-8
366
2.5625
3
[]
no_license
module PetfinderService module Queries class Organization def initialize(pf_client, pf_org_id) @client = pf_client @org_id = pf_org_id raise PetfinderService::Queries::Error.new('Petfinder Shelter ID is required') unless @org_id.present? end def run @client.shelter(@org_id) end end end end
true
080aee12116228449e2a5ee2c051ac620dd9f9c5
Ruby
AugustGiles/onitama-project-3-backend
/db/seeds.rb
UTF-8
5,964
2.921875
3
[]
no_license
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) #----------Movement Seeds move1 = new Move(x: 0,y: 1); move2 = new Move(x: 0,y: 2); move3 = new Move(x: 0,y: -1); move4 = new Move(x: 0,y: -2); move5 = new Move(x: 1,y: 0); move6 = new Move(x: 2,y: 0); move7 = new Move(x: -1,y: 0); move8 = new Move(x: -2,y: 0); move9 = new Move(x: 1,y: 1); move10 = new Move(x: 1,y: 2); move11 = new Move(x: 1,y: -1); move12 = new Move(x: 1,y: -2); move13 = new Move(x: 2,y: 1); move14 = new Move(x: 2,y: 2); move15 = new Move(x: 2,y: -1); move16 = new Move(x: 2,y: -2); move17 = new Move(x: -1,y: 1); move18 = new Move(x: -1,y: 2); move19 = new Move(x: -1,y: -1); move20 = new Move(x: -1,y: -2); move21 = new Move(x: -2,y: 1); move22 = new Move(x: -2,y: 2); move23 = new Move(x: -2,y: -1); move24 = new Move(x: -2,y: -2); #---------Cards tiger = new Card(title: "Tiger", quote: "The power of your Art projects instelf like a shadow. Sense your opponent's fear, and pounce with certainty and strength.") tiger.moves << move17 tiger.moves << move3 ox = new Card(title: "Ox", quote: "Pour your strength into the forms of your Art- in its punches, its kicks, in the steady advance of your aggression.") ox.moves << move8 ox.moves << move17 ox.moves << move13 mantis = new Card(title: "Mantis", quote: "Your opponent sees, but does not understand. Distract the watchful, misguide the wary. This is the Art of the Mantis, the Art of the deceptive strike.") mantis.moves << move7 mantis.moves << move9 mantis.moves << move17 eel = new Card(title: "Eel", quote: "If you opponent strikes with fire, counter with water, becoming completely fluid and freeflowing.") eel.moves << move7 eel.moves << move13 eel.moves << move16 frog = new Card(title: "Frog", quote: "Do not fail to learn from the pure voice of an ever-flowing mountian stream spalshing over the rocks. Emulate its flow, mimic its power.") frog.moves << move7 frog.moves << move11 frog.moves << move18 horse = new Card(title: "Horse", quote: "Lose yourself in the rythm of your Art. At times be swift and decisive, at other times measured and taunting.") horse.moves << move12 horse.moves << move8 horse.moves << move17 monkey = new Card(title: "Monkey", qoute: "Without deception you cannot carry out startegy, without strategy you connot control the opponent.") monkey.moves << move7 monkey.moves << move16 monkey.moves << move18 monkey.moves << move9 boar = new Card(title: "Boar", quote: "Watch for opportunity, for it will present itself. Then strike, focussing all your might into a single rush, trampling your opponent's Art under your own.") boar.moves << move12 boar.moves << move8 boar.moves << move13 crane = new Card(title: "Crane", quote: "Make no unnecessary movement, conserving your strength until the time is right to strike. The true Art is a symphony of graceful strikes.") crane.moves << move16 crane.moves << move8 crane.moves << move18 goose = new Card(title: "Goose", quote: "Your robes are your cloak of feathers; spread your wings to hide your intentions. Even then, as your opponent seeks to determine your motive, you shall strike.") goose.moves << move12 goose.moves << move7 goose.moves << move13 goose.moves << move18 rooster = new Card(title: "Rooster", quote: "Do not allow your enemy to rest, but focus your Art to delive quick, sharp strikes whenever he lags.") rooster.moves << move12 rooster.moves << move16 rooster.moves << move13 rooster.moves << move9 rabbit = new Card(title: "Rabbit", quote: "Be near to your opponent, blinding him with your speed. The Art of the Rabbit is the Art of speed.") rabbit.moves << move16 rabbit.moves << move9 rabbit.moves << move14 elephant = new Card(title: "Elephant", quote: "Only the strong may pursue your Art. This is why it is the true Art, the Art that cannot be stopped.") elephant.moves << move12 elephant.moves << move7 elephant.moves << move13 elephant.moves << move9 crab = new Card(title: "Crab", quote: "Move with your opponent's movements, as if you are the never-ceasing tide. When the time is right, he will fall prey to your attack.") crab.moves << move11 crab.moves << move8 crab.moves << move14 dragon = new Card(title: "Dragon", quote: "Be swift as the thunder that peals before you have a chance to cover your ears, fast as the lightining that flashes before you can blink your eyes.") dragon.moves << move16 dragon.moves << move6 dragon.moves << move18 dragon.moves << move10 cobra = new Card(title: "Cobra", quote: "Attack violently when your opponents are not expecting it - show leisure in the beggining, then suddenly attack vigorously.") cobra.moves << move12 cobra.moves << move9 cobra.moves << move18 # ======== P A W N S =========== new Pawn(player_id: 1, type: "student", on_board: true, color: "red", x: 0, y: 0) new Pawn(player_id: 1, type: "student", on_board: true, color: "red", x: 0, y: 1) new Pawn(player_id: 1, type: "sensei", on_board: true, color: "red", x: 0, y: 2) new Pawn(player_id: 1, type: "student", on_board: true, color: "red", x: 0, y: 3) new Pawn(player_id: 1, type: "student", on_board: true, color: "red", x: 0, y: 4) new Pawn(player_id: 2, type: "student", on_board: true, color: "blue", x: 4, y: 0) new Pawn(player_id: 2, type: "student", on_board: true, color: "blue", x: 4, y: 1) new Pawn(player_id: 2, type: "sensei", on_board: true, color: "blue", x: 4, y: 2) new Pawn(player_id: 2, type: "student", on_board: true, color: "blue", x: 4, y: 3) new Pawn(player_id: 2, type: "student", on_board: true, color: "blue", x: 4, y: 4) # ======== P L A Y E R S =========== p1 = new Player p2 = new Player p3 = new Player
true
594ae40affbede1b4b1c2454bab73922251bea1c
Ruby
Patmando73/API_Project
/database_instance_methods.rb
UTF-8
2,255
3.4375
3
[]
no_license
require "active_support" require "active_support/inflector" module DatabaseInstanceMethods # Get the value of a field for a given row. # # field - String of the column name. # # Returns the String value of the cell in the table. def get(field) table_name = self.class.to_s.pluralize.underscore result = CONNECTION.execute("SELECT * FROM #{table_name} WHERE id = #{@id}").first result[field] end def delete table_name = self.class.to_s.pluralize.underscore CONNECTION.execute("DELETE FROM #{table_name} WHERE id = #{@id}") end # This is an instance method that Takes all of the instance variables for an # object and inserts the name of each attribute as a key and the value of that attribute as # the value in a hash. # # This hash is then run through the .join(', ') and used to update data in the database. def save table = self.class.to_s.pluralize.underscore # Uses self.instance_variables to sets instance_variables to the attributes of the object # Without this line there would be no keys to add to the attribute_hash instance_variables = self.instance_variables attribute_hash = {} # Adds the attributes to the attribute_hash as keys # # self.send gets the value of each attribute by using its getter method # # variable.slice takes of the "@" part of the attributes instance_variables.each do |variable| attribute_hash["#{variable.slice(1..-1)}"] = self.send("#{variable.slice(1..-1)}") end individual_instance_variables = [] # Adds the values of the attributes to the values of their corresponding keys # # value.is.a?(string) checks if the value is a string so it can put quotes around it as needed. attribute_hash.each do |key, value| if value.is_a?(String) individual_instance_variables << "#{key} = '#{value}'" else individual_instance_variables << "#{key} = #{value}" end end # Returns a string created by converting each element of the array to a string, separated by a comma and a space for_sql = individual_instance_variables.join(', ') CONNECTION.execute("UPDATE #{table} SET #{for_sql} WHERE id = #{self.id}") return self end end
true
c06ab9e3c4a16b56085719ebba274f229af954e9
Ruby
RobinvdGriend/hangman
/lib/hangman/ai.rb
UTF-8
355
2.640625
3
[ "MIT" ]
permissive
module Hangman module AI DICTIONARY_PATH = "lib/hangman/ai/dictionary.txt" def self.generate_from_dictionary line_count = %x{wc -l #{DICTIONARY_PATH}}.split.first.to_i random_line = rand(line_count) File.open(DICTIONARY_PATH) do |f| (random_line - 1).times { f.gets } f.gets.strip end end end end
true
746d55f1f58c33b8b588377ab9e28ad776e4fb76
Ruby
RubyDaRosess/RuBY-Week2
/exo_07.rb
UTF-8
94
3.09375
3
[]
no_license
print "Choisis un nombre ~> " user_num = gets.to_i 1.upto(user_num) {|user_num| puts user_num}
true
d77b9ef3abf859230c7b9a05a9ffc95735c65198
Ruby
ajn123/market_example
/lib/checkout.rb
UTF-8
1,232
3.421875
3
[]
no_license
class Checkout attr_accessor :item_count attr_accessor :discounts attr_accessor :products def initialize @cart = [] @item_count = Hash.new(0) @discounts = {} @products = {} end def add_discount(product, code, amount, type, options = {}) @discounts[product] = Discount.new(product, code, amount, type, options) end def add_item_to_database(code, cost) @products[code] = cost end def check_for_discount(code) if @discounts.key?(code) return @discounts[code].run_discount(@item_count[code], @item_count) else return 0 end end def scan(item) @item_count[item] += 1 @cart << Product.new(item, @products[item]) end def print_cart sum = 0 puts sprintf("%-20s%5s", "Item", "Price") puts sprintf("%-20s%5s", "----", "-----") @cart.each do |item| sum += item.print_item sum += check_for_discount(item.code) end puts "-" * 25 puts sprintf("%25.2f", sum) sum end end
true
951323870f1c458ce4d013bfc92a970b685468ee
Ruby
MarkFChavez/vehicle_coding_ph-ruby
/lib/vehicle_coding_ph/checker.rb
UTF-8
1,215
2.59375
3
[ "MIT" ]
permissive
module VehicleCodingPh class Checker def self.call(plate_no, datetime = Time.now) return allowed_anywhere if weekend?(datetime) return allowed_anywhere if not coding?(plate_no, datetime) allowed_areas = [] not_allowed_areas = [] hour_of_the_day = datetime.hour VehicleCodingPh.coding_hours_per_area.each do |hash| area = hash[:area] hours = hash[:hours] if hours.empty? || !hours.include?(hour_of_the_day) allowed_areas << area else not_allowed_areas << area end end Response.new(true, allowed_areas, not_allowed_areas) end def self.weekend?(datetime) datetime.saturday? || datetime.sunday? end private_class_method :weekend? def self.coding?(plate, datetime) last_digit = plate[-1] day_today = Date::DAYNAMES[datetime.wday] mapping = VehicleCodingPh.coding_scheme. find { |mapping| mapping[:day] == day_today } mapping[:plates].include?(last_digit) end private_class_method :coding? def self.allowed_anywhere Response.new(false, [:anywhere], []) end private_class_method :allowed_anywhere end end
true
f734728b45071c81a0a9a0f3b52e826e6eac7b6a
Ruby
cremno/mruby-allegro
/llapi/primitives.rb
UTF-8
1,360
3.09375
3
[]
no_license
def al_draw_line(x1, y1, x2, y2, color, thickness) Al.draw_line(x1, y1, x2, y2, color, thickness) end def al_draw_triangle(x1, y1, x2, y2, x3, y3, color, thickness) Al.draw_triangle(x1, y1, x2, y2, x3, y3, color, thickness) end def al_draw_filled_triangle(x1, y1, x2, y2, x3, y3, color) Al.draw_filled_triangle(x1, y1, x2, y2, x3, y3, color) end def al_draw_rectangle(x1, y1, x2, y2, color, thickness) Al.draw_rectangle(x1, y1, x2, y2, color, thickness) end def al_draw_filled_rectangle(x1, y1, x2, y2, color) Al.draw_filled_rectangle(x1, y1, x2, y2, color) end def al_draw_rounded_rectangle(x1, y1, x2, y2, rx, ry, color, thickness) Al.draw_rounded_rectangle(x1, y1, x2, y2, rx, ry, color, thickness) end def al_draw_filled_rounded_rectangle(x1, y1, x2, y2, rx, ry, color) Al.draw_filled_rounded_rectangle(x1, y1, x2, y2, rx, ry, color) end def al_draw_ellipse(cx, cy, rx, ry, color, thickness) Al.draw_ellipse(cx, cy, rx, ry, color, thickness) end def al_draw_filled_ellipse(cx, cy, rx, ry, color) Al.draw_filled_ellipse(cx, cy, rx, ry, color) end def al_draw_circle(cx, cy, r, color, thickness) Al.draw_circle(cx, cy, r, color, thickness) end def al_draw_filled_circle(cx, cy, r, color) Al.draw_filled_circle(cx, cy, r, color) end def al_draw_spline(points, color, thickness) Al.draw_spline(*points, color, thickness) end
true
d6f356ef4573e2787615a4b1970a61bbfa6f58a5
Ruby
TheConductor/Study
/study_plan/ruby_code/lib/remove_duplicates_from_array.rb
UTF-8
819
3.703125
4
[]
no_license
class RemoveDuplicatesFromArray attr_accessor :array def remove_duplicates(array) array_start_size = array.size # used to insure whole array is itterated over items_removed = 0 # used to adjust the index of the for loop to the index of the element that needs to be removed as indexs will not match up with i as items are removed last_item = nil # used to compare the last item to the current item array = array.sort # problem states the array is pre sorted, this is just allows me to pass it unsorted arrays as well. for i in 0..array_start_size adjusted_index = i - items_removed if array[adjusted_index] == last_item array.delete_at(adjusted_index) items_removed += 1 end last_item = array[adjusted_index] end return array end end
true
9b8bdc309923e16d9eb5a4918bf23df04a040cf6
Ruby
reo0306/RubySliver
/lesson/4/4-36.rb
UTF-8
330
2.6875
3
[]
no_license
class Baz1 def public_method1; 1; end public def public_method2; 2; end protected def protected_method1; 1; end def protected_method2; 2; end private def private_method1; 1; end end p Baz1.new.public_method1 p Baz1.new.public_method2 #p Baz1.new.protected_method1 #p Baz1.new.protected_method2 p Baz1.new.private_method1
true
0c0a23348e9d5b17dae6eab9c2472c5b25f4dedc
Ruby
caseyscarborough/github
/lib/github_api_v3/client.rb
UTF-8
6,069
2.84375
3
[ "MIT" ]
permissive
require 'base64' require 'json' require 'github_api_v3/client/commits' require 'github_api_v3/client/contents' require 'github_api_v3/client/events' require 'github_api_v3/client/feeds' require 'github_api_v3/client/gists' require 'github_api_v3/client/gitignore' require 'github_api_v3/client/issues' require 'github_api_v3/client/markdown' require 'github_api_v3/client/milestones' require 'github_api_v3/client/oauth' require 'github_api_v3/client/octocat' require 'github_api_v3/client/orgs' require 'github_api_v3/client/pull_requests' require 'github_api_v3/client/repos' require 'github_api_v3/client/stats' require 'github_api_v3/client/users' module GitHub # The main client for the API. # # @see http://developer.github.com/v3/ class Client include HTTParty # Default base uri for the API functionality. base_uri Default::API_ENDPOINT include GitHub::Client::Commits include GitHub::Client::Contents include GitHub::Client::Events include GitHub::Client::Feeds include GitHub::Client::Gitignore include GitHub::Client::Gists include GitHub::Client::Issues include GitHub::Client::Markdown include GitHub::Client::Milestones include GitHub::Client::OAuth include GitHub::Client::Octocat include GitHub::Client::Orgs include GitHub::Client::PullRequests include GitHub::Client::Repos include GitHub::Client::Stats include GitHub::Client::Users attr_accessor :login, :access_token, :password def initialize(options={}) @login = options[:login] @access_token = options[:access_token] if options[:access_token] @password = options[:password] if options[:password] end private # Perform a get request. # # @return [Hash, Array, String] def get(url, options={}) response = request :get, url, options handle_response(response) response.parsed_response end # Perform a put request. # # @return [Hash, Array, String] def put(url, options={}) response = request :put, url, options handle_response(response) response.parsed_response end # Perform a post request. # # @return [Hash, Array, String] def post(url, options={}) response = request :post, url, options handle_response(response) response.parsed_response end # Perform a patch request. # # @return [Hash, Array, String] def patch(url, options={}) response = request :patch, url, options handle_response(response) response.parsed_response end # Perform a delete request. # # @return [Hash, Array, String] def delete(url, options={}) response = request :delete, url, options handle_response(response) response.parsed_response end # Return a hash with client's login and password. # # @return [Hash] def basic_params @password.nil? ? {} : { :login => @login, :password => @password } end # Return a hash with client's login and access token. # # @return [Hash] def auth_params @login.nil? ? {} : { :login => @login, :access_token => @access_token } end def basic_auth_headers encoded_auth = Base64.encode64("#{@login}:#{@password}") { 'Authorization' => "Basic #{encoded_auth}" } end # Send an HTTP request. # # @param method [Symbol] The request type, such as :get, :put, or :post. # @param url [String] The URL to send the request to. # @param options [Hash] Optional parameters. # @option options [Hash] :params URL parameters. # @option options [Hash] :headers Headers to send with the request. # @option options [Hash] :body Body of the request. # @return [Array, Hash] # @example POST request # request :post, 'http://example.com/users', params: { name: 'Casey' }, body: { example: 'example' } def request(method, url, options={}) params = options[:params] || {} headers = options[:headers] || {} body = options[:body] || {} no_follow = options[:no_follow] || false params.merge!(auth_params) headers.merge!(basic_auth_headers) if @login && @password self.class.send(method, url, :query => params, :body => body.to_json, :headers => headers, :no_follow => no_follow) end # Get a boolean response from an HTTP request. # # @param method [Symbol] The request type, such as :get, :put, or :post. # @param url [String] The URL to send the request to. # @param options [Hash] Optional parameters. # @option options [Hash] :params URL parameters. # @option options [Hash] :headers Headers to send with the request. # @option options [Hash] :body Body of the request. # @return [Boolean] # @example DELETE Request # boolean_request :delete, 'http://example.com/users' def boolean_request(method, url, options={}) response = request(method, url, options) response.code == 204 rescue GitHub::NotFound false end # Handle HTTP responses. # # Raise proper exceptions based on the response code. # # @return [HTTParty::Response] def handle_response(response) case response.code when 400 then raise BadRequest when 401 then raise Unauthorized when 403 if response.body =~ /rate limit/i raise RateLimitExceeded elsif response.body =~ /login attempts/i raise LoginAttemptsExceeded else raise Forbidden end when 404 then raise NotFound when 500 then raise InternalServerError when 502 then raise BadGateway when 503 then raise ServiceUnavailable when 500...600 then raise ServerError, response.code else response end end end end
true
a8fce2092f030d647010e882489323e29a77682f
Ruby
nagatea/nagatea_bot
/lib/cheesecake.rb
UTF-8
1,265
2.9375
3
[]
no_license
require 'open-uri' require 'mechanize' class Cheesecake def initialize @now = Time.now end def get_cheesecake(month = @now.month, day = @now.day) #チズケの閉館時間を取得する unless Date.valid_date?(@now.year, month.to_i, day.to_i) return "#{month}月#{day}日は存在しませんが" end if month.to_i < 10 mon = "0" + month.to_s else mon = month.to_s end url = "https://www.libra.titech.ac.jp/calendar/#{@now.year}#{mon}" agent = Mechanize.new agent.max_history = 1 agent.open_timeout = 30 agent.read_timeout = 60 page = agent.get(url) if page.title == "登録はまだされていません | 東京工業大学附属図書館" return "#{month.to_s}月分はまだ登録されていません" end xpath = "/html/body/div[5]/div/section/div/div/div/div[2]/div[1]/table/tbody/tr[#{day}]/td[3]" times = page.search(xpath).inner_text.gsub(" ", "") xpath = "/html/body/div[5]/div/section/div/div/div/div[2]/div[1]/table/tbody/tr[#{day}]/td[4]" other = page.search(xpath).inner_text.strip if other.empty? others = "" else others = "\n備考:#{other}" end "#{month}月#{day}日は#{times}#{others}" end end
true
05fbd14715aeaf68062908b4b24140ce9984615f
Ruby
sahilda/the-truck-stop-sf
/lib/hipchatResponse.rb
UTF-8
1,160
2.734375
3
[]
no_license
require_relative './truckStopDataPull.rb' require 'json' class HitchatResponse def self.build_response response = {} response['color'] = 'green' response['message'] = TruckStopDataPull.new.get_trucks response['notify'] = 'false' response['message_format'] = 'text' response.to_json end def build_server_response() auth_token = '' client_uri = '' room_id = '' client_post = "/v2/room/#{room_id}/notification?auth_token=#{auth_token}" server_response = {} server_response['uri'] = client_uri server_response['post'] = client_post server_response['message'] = HitchatResponse.build_response server_response end def post_message_to_hipchat() server_response = build_server_response() uri = URI.parse(server_response['uri']) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE request = Net::HTTP::Post.new(server_response['post']) request.add_field('Content-Type', 'application/json') request.body = server_response['message'] response = http.request(request) end end
true
990e8608add96d9b8536270f04fb91dd4c5f93fc
Ruby
collabnix/dockerlabs
/vendor/bundle/ruby/2.6.0/gems/rubocop-0.93.1/lib/rubocop/cop/layout/line_length.rb
UTF-8
8,584
2.84375
3
[ "Apache-2.0", "CC-BY-NC-4.0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# frozen_string_literal: true require 'uri' module RuboCop module Cop module Layout # This cop checks the length of lines in the source code. # The maximum length is configurable. # The tab size is configured in the `IndentationWidth` # of the `Layout/IndentationStyle` cop. # It also ignores a shebang line by default. # # This cop has some autocorrection capabilities. # It can programmatically shorten certain long lines by # inserting line breaks into expressions that can be safely # split across lines. These include arrays, hashes, and # method calls with argument lists. # # If autocorrection is enabled, the following Layout cops # are recommended to further format the broken lines. # (Many of these are enabled by default.) # # * ArgumentAlignment # * BlockAlignment # * BlockDelimiters # * BlockEndNewline # * ClosingParenthesisIndentation # * FirstArgumentIndentation # * FirstArrayElementIndentation # * FirstHashElementIndentation # * FirstParameterIndentation # * HashAlignment # * IndentationWidth # * MultilineArrayLineBreaks # * MultilineBlockLayout # * MultilineHashBraceLayout # * MultilineHashKeyLineBreaks # * MultilineMethodArgumentLineBreaks # * ParameterAlignment # # Together, these cops will pretty print hashes, arrays, # method calls, etc. For example, let's say the max columns # is 25: # # @example # # # bad # {foo: "0000000000", bar: "0000000000", baz: "0000000000"} # # # good # {foo: "0000000000", # bar: "0000000000", baz: "0000000000"} # # # good (with recommended cops enabled) # { # foo: "0000000000", # bar: "0000000000", # baz: "0000000000", # } class LineLength < Cop include CheckLineBreakable include ConfigurableMax include IgnoredPattern include RangeHelp include LineLengthHelp MSG = 'Line is too long. [%<length>d/%<max>d]' def on_block(node) check_for_breakable_block(node) end def on_potential_breakable_node(node) check_for_breakable_node(node) end alias on_array on_potential_breakable_node alias on_hash on_potential_breakable_node alias on_send on_potential_breakable_node def investigate(processed_source) check_for_breakable_semicolons(processed_source) end def investigate_post_walk(processed_source) processed_source.lines.each_with_index do |line, line_index| check_line(line, line_index) end end def autocorrect(range) return if range.nil? lambda do |corrector| corrector.insert_before(range, "\n") end end private def check_for_breakable_node(node) breakable_node = extract_breakable_node(node, max) return if breakable_node.nil? line_index = breakable_node.first_line - 1 range = breakable_node.source_range existing = breakable_range_by_line_index[line_index] return if existing breakable_range_by_line_index[line_index] = range end def check_for_breakable_semicolons(processed_source) tokens = processed_source.tokens.select { |t| t.type == :tSEMI } tokens.reverse_each do |token| range = breakable_range_after_semicolon(token) breakable_range_by_line_index[range.line - 1] = range if range end end def check_for_breakable_block(block_node) return unless block_node.single_line? line_index = block_node.loc.line - 1 range = breakable_block_range(block_node) pos = range.begin_pos + 1 breakable_range_by_line_index[line_index] = range_between(pos, pos + 1) end def breakable_block_range(block_node) if block_node.arguments? && !block_node.lambda? block_node.arguments.loc.end else block_node.loc.begin end end def breakable_range_after_semicolon(semicolon_token) range = semicolon_token.pos end_pos = range.end_pos next_range = range_between(end_pos, end_pos + 1) return nil unless next_range.line == range.line next_char = next_range.source return nil if /[\r\n]/.match?(next_char) return nil if next_char == ';' next_range end def breakable_range_by_line_index @breakable_range_by_line_index ||= {} end def heredocs @heredocs ||= extract_heredocs(processed_source.ast) end def highlight_start(line) # TODO: The max with 0 is a quick fix to avoid crashes when a line # begins with many tabs, but getting a correct highlighting range # when tabs are used for indentation doesn't work currently. [max - indentation_difference(line), 0].max end def check_line(line, line_index) return if line_length(line) <= max return if ignored_line?(line, line_index) if ignore_cop_directives? && directive_on_source_line?(line_index) return check_directive_line(line, line_index) end return check_uri_line(line, line_index) if allow_uri? register_offense( excess_range(nil, line, line_index), line, line_index ) end def ignored_line?(line, line_index) matches_ignored_pattern?(line) || shebang?(line, line_index) || heredocs && line_in_permitted_heredoc?(line_index.succ) end def shebang?(line, line_index) line_index.zero? && line.start_with?('#!') end def register_offense(loc, line, line_index) message = format(MSG, length: line_length(line), max: max) breakable_range = breakable_range_by_line_index[line_index] add_offense(breakable_range, location: loc, message: message) do self.max = line_length(line) end end def excess_range(uri_range, line, line_index) excessive_position = if uri_range && uri_range.begin < max uri_range.end else highlight_start(line) end source_range(processed_source.buffer, line_index + 1, excessive_position...(line_length(line))) end def max cop_config['Max'] end def allow_heredoc? allowed_heredoc end def allowed_heredoc cop_config['AllowHeredoc'] end def extract_heredocs(ast) return [] unless ast ast.each_node(:str, :dstr, :xstr).select(&:heredoc?).map do |node| body = node.location.heredoc_body delimiter = node.location.heredoc_end.source.strip [body.first_line...body.last_line, delimiter] end end def line_in_permitted_heredoc?(line_number) return false unless allowed_heredoc heredocs.any? do |range, delimiter| range.cover?(line_number) && (allowed_heredoc == true || allowed_heredoc.include?(delimiter)) end end def line_in_heredoc?(line_number) heredocs.any? do |range, _delimiter| range.cover?(line_number) end end def check_directive_line(line, line_index) return if line_length_without_directive(line) <= max range = max..(line_length_without_directive(line) - 1) register_offense( source_range( processed_source.buffer, line_index + 1, range ), line, line_index ) end def check_uri_line(line, line_index) uri_range = find_excessive_uri_range(line) return if uri_range && allowed_uri_position?(line, uri_range) register_offense( excess_range(uri_range, line, line_index), line, line_index ) end end end end end
true
e2988146dca2bf8b2d9709f510bb2d889354d45c
Ruby
SlothSimon/HousePricing
/app/models/shops_houses.rb
UTF-8
341
2.53125
3
[]
no_license
require 'csv' class ShopsHouses < ActiveRecord::Base belongs_to :house belongs_to :shop def self.to_csv attributes = %w{id shop_id house_id} CSV.generate(headers: true) do |csv| csv << attributes ShopsHouses.all.each do |col| csv << attributes.map { |attr| col.send(attr) } end end end end
true
3627db67527c3c3d342b5742a18bdbfca6b73862
Ruby
MicaW/lrthw
/chap01/ex3.rb
UTF-8
828
4.5
4
[]
no_license
#Writes string puts "I will now count my chickens:" # Calculates and writes how many hens and roosters puts "Hens #{25.0 + 30.0 / 6.0}" puts "Roosters #{100.0 - 25.0 * 3.0 % 4.0}" #Writes string puts "Now i will count the eggs" #Calculates and writes puts 3.0 + 2.0 + 1.0 - 5.0 + 4.0 % 2.0 - 1.0 / 4.0 + 6.0 #Writes and asks the question, returns a false puts "Is it true that 3 + 2 < 5 - 7?" #Another calculation puts 3.0 + 2.0 < 5.0 - 7.0 #Calculates the number in brackets and returns the answer puts "What is 3.0 + 2.0? #{3.0 + 2.0}" puts "What is 5.0 - 7.0? #{5.0 - 7.0}" #Writes string puts "Oh, that's why it's false." puts "How about some more." #Returns true or false for each question puts "Is it greater? #{5.0 > -2.0}" puts "Is it greater or equal? #{5.0 >= -2.0}" puts "Is it less or equal? #{5.0 <= -2.0}"
true
66549a0581424b2f39203ed315219c506918a1eb
Ruby
Rik280491/programming-univbasics-nds-nds-to-insight-understand-lab-london-web-120919
/lib/nds_explore.rb
UTF-8
416
2.859375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'directors_database' # Call the method directors_database to retrieve the NDS def pretty_print_nds(nds) pp nds end def print_first_directors_movie_titles first_movies = directors_database[0][:movies] inner_index = 0 while inner_index < first_movies.length do titles = first_movies[inner_index][:title] puts titles inner_index += 1 end end
true
11998e3e44569a77aa8fc09350a0cf971d4f9b09
Ruby
peoplesmeat/DecksterRails
/app/helpers/deckster/other_helper.rb
UTF-8
1,287
2.765625
3
[ "MIT" ]
permissive
module Deckster module OtherHelper def color_average *colors_to_avg n = colors_to_avg.count totals = colors_to_avg.reduce({r: 0, b: 0, g: 0}) do |accum, str| p = {} p[:r], p[:g], p[:b] = str.split(/([0-9a-fA-F]{2})/).select { |x| not x.empty? }.map { |s| Integer(s, 16) } accum.merge!(p) { |k, o, n| o + n } end "#{(totals[:r]/n).to_s(16)}#{(totals[:g]/n).to_s(16)}#{(totals[:b]/n).to_s(16)}" end def hashes_to_table hashes, additional_stop_list=nil stop_list = /class|id\z|meta_type_s_m|event_i_m|_version_|tags_s_M#{additional_stop_list}/ html = [] html << '<table><thead>' columns = hashes.collect { |h| h.keys.select { |k| !stop_list.match k } }.flatten.uniq html << '<tr>' html << columns.collect { |c| "<th>#{c.gsub(/_[a-zA-Z]_[a-zA-Z](_[a-zA-Z])?\z/, '').titlecase}</th>" }.join('') html << '</tr>' html << '</thead><tbody>' hashes.each do |hash| "app" html << '<tr>' columns.each do |c| value = hash[c] value = value.join('<br/>') if value.is_a? Array html << "<td>#{value}</td>" end html << '</tr>' end html << '</tbody></table>' html.join('').html_safe end end end
true
31a4e379d201cf7a1c899221aeeb5e7611863e57
Ruby
Emilie-D/Decouverte_Ruby_2
/exo_20.rb
UTF-8
199
3.0625
3
[]
no_license
puts "Salut, bienvenue dans ma super pyramide ! Combien d'étage veux-tu ?" print ">" user_number = gets.chomp.to_i puts "Voici la pyramide :" i = 0 while i < user_number i += 1 puts "#" * i end
true
7628754d4517f9418bd8bb77a60c3351034cb39b
Ruby
coffeencoke/mince
/lib/mince/data_model/timestamps.rb
UTF-8
1,690
2.640625
3
[ "MIT" ]
permissive
module Mince module DataModel require 'active_support/concern' require_relative '../data_model' # = Timestamps # # Timestamps can be mixed into your DataModel classes in order to provide with fields # to store when records are created and updated. # # Example: # require 'mince/data_model' # # Class UserDataModel # include Mince::DataModel # include Mince::DataModel::Timestamps # # data_collection :users # data_fields :username # end # # UserDataModel.add username: 'coffeencoke' # data_model = UserDataModel.find_by_field :username, 'coffeencoke' # data_model.created_at # => todo: returns date time in utc # data_model.updated_at # => todo: returns date time in utc # # Whenever a database persisting message is called for a record, the updated_at # timestamp will be updated. module Timestamps include Mince::DataModel extend ActiveSupport::Concern included do data_fields :created_at, :updated_at end module ClassMethods # :nodoc: def add_timestamps_to_hash(hash) now = Time.now.utc hash.merge!(created_at: now, updated_at: now) end def set_update_timestamp_for(data_collection, id) interface.update_field_with_value(data_collection, id, :updated_at, Time.now.utc) end end def update_timestamps now = Time.now.utc self.created_at = now unless created_at self.updated_at = now end def timestamp_attributes { created_at: created_at, updated_at: updated_at } end end end end
true
180a646deadfee1b3a4e841c0def129c1b9758dc
Ruby
loic-roux-404/playbook-template
/.manala/vg-facade/tools.rb
UTF-8
376
3.0625
3
[ "BSD-3-Clause" ]
permissive
# Ruby complements class ::Hash def deep_merge(second) merger = proc { |key, v1, v2| Hash === v1 && Hash === v2 ? v1.merge(v2, &merger) : v2 } self.merge(second, &merger) end def to_struct Struct.new(*keys.map(&:to_sym)).new(*values.to_struct) end end class ::Array def to_struct map { |value| value.respond_to?(:to_struct) ? value.to_struct : value } end end
true
69f770521d549e68f2fc2a39bd686d6b16f3484c
Ruby
thangngoit/random_japanese_string
/lib/random_japanese_string.rb
UTF-8
885
2.984375
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- require "random_japanese_string/version" require "yaml" class RandomJapaneseString HIRA = YAML.load_file(File.expand_path(File.join('..', 'data', 'hiragana.yml'), __FILE__)) KATA = YAML.load_file(File.expand_path(File.join('..', 'data', 'katakana.yml'), __FILE__)) KANJI = YAML.load_file(File.expand_path(File.join('..', 'data', 'kanji.daily.yml'), __FILE__)) MIX = HIRA*15 + KATA*15 + KANJI def self.hiragana size HIRA.sample(size).join end def self.katakana size KATA.sample(size).join end def self.kanji size KANJI.sample(size).join end def self.generate size MIX.sample(size).join end def hiragana size HIRA.sample(size).join end def katakana size KATA.sample(size).join end def kanji size KANJI.sample(size).join end def generate size MIX.sample(size).join end end
true
45694d01d47e2defc1b2cf9d8ad813ce32b43fea
Ruby
khkhROZALIYakhkh/fat-librarians
/lib/shipping/base.rb
UTF-8
299
2.9375
3
[]
no_license
module Shipping class Base attr_accessor :weight def initialize weight = nil @weight = weight.nil? ? 1 : weight.to_f end def name self.class.name.split('::').last end def cost weight * 0.1 end def days 1 end end end
true
6ccee7be28329264e74bbadd06bb4ab303c2d51e
Ruby
oggy/command_rat
/spec/spec_helper.rb
UTF-8
1,708
2.53125
3
[ "MIT" ]
permissive
require 'spec' require 'command_rat' require 'fileutils' require 'rbconfig' module SpecHelper def self.included(mod) mod.before do @files_to_cleanup = [] end mod.after do @files_to_cleanup.each do |name| FileUtils.rm_f name end end end def temp_dir File.dirname(__FILE__) + '/../tmp' end def clean_up(file_name) @files_to_cleanup << file_name end # # Create a temporary file and return its path. # def generate_file name = nil i = 1 loop do name = "#{temp_dir}/#{i}" break if !File.exist?(name) i += 1 end name = File.expand_path(name) FileUtils.touch name clean_up name name end # # Create a temporary executable with the given source, and return # the path. Any '|'-delimited margin will be stripped first. # # The generated file will be cleaned up in the after hook. # def make_executable(source) source = source.gsub(/^ *\|/, '') name = generate_file open(name, 'w'){|f| f.print(source)} FileUtils.chmod(0755, name) name end # # Prefix the given source string with "#!/bin/sh" and make a # temporary executable out of it. # def make_shell_command(source) make_executable("#!/bin/sh\n" + source) end # # Prefix the given source string with a shebang line that launches # the current ruby interpreter, and make a temporary executable out # of it. # def make_ruby_command(source) ruby = File.join(Config::CONFIG['bindir'], Config::CONFIG['RUBY_INSTALL_NAME']) make_executable("#!#{ruby}\n" + source) end end Spec::Runner.configure do |config| config.include SpecHelper config.mock_with :mocha end
true
6fb77ab32fcca2eca7a7fd5482a316378f574796
Ruby
jpedro-50/ESSBetRuby
/views/game_view.rb
UTF-8
694
2.734375
3
[]
no_license
class GameView def create puts "\n ---- Inserir Jogo ---- \n" puts "Insira os dados do Jogo {Identificador,Equipa1,Equipa2,data,IdentificadorBookie}\n" end def update puts "\n ---- Actualizar Jogo ---- \n" puts "Insira os novos dados do Jogo {Equipa1,Equipa2,data,estado}" end def show(id,team1,team2,date) puts "\n----------------\n" puts "ID => "+id puts "Visitado => "+team1 puts "Visitante => "+team2 puts "Data => "+date end def remove puts "\n ---- Remover Jogo ---- \n" puts "Insira o {identificador} do jogo:" end def search puts "\n ---- Procurar Jogo ---- \n" puts "Insira o {identificador} do jogo:" end end
true
8e7036b22e7e8352c5bb99fa70bdd05f8bed5568
Ruby
vochong/project-euler
/ruby/euler002.rb
UTF-8
148
3.28125
3
[]
no_license
f1 = 1 f2 = 2 sum = 2 while f1 + f2 <= 4000000 do tmp = f2 f2 += f1 f1 = tmp if f2.even? sum += f2 end end puts sum
true
14132c418021f75d6d1e06558c5cb40362c63b90
Ruby
branfull/fte_2103
/lib/event.rb
UTF-8
1,318
3.578125
4
[]
no_license
class Event attr_reader :name, :food_trucks def initialize(name) @name = name @food_trucks = [] end def add_food_truck(food_truck) @food_trucks.push(food_truck) end def food_truck_names @food_trucks.map do |food_truck| food_truck.name end end # refactor if time allows def food_trucks_that_sell(item_in_question) array = [] @food_trucks.each do |food_truck| food_truck.inventory.keys.each do |item| if item == item_in_question array.push(food_truck) end end end array end def list_of_all_food_items array = @food_trucks.map do |truck| truck.inventory.keys end.flatten.uniq end def quantity_of_item(item) @food_trucks.sum do |truck| truck.check_stock(item) end end def total_inventory list_of_all_food_items.inject({}) do |hash, item| hash[item] = {quantity: quantity_of_item(item), food_trucks: food_trucks_that_sell(item)} hash end end def overstocked_items list_of_all_food_items.find_all do |item| food_trucks_that_sell(item).length > 1 && quantity_of_item(item) > 50 end end def sorted_item_list item_names = list_of_all_food_items.map do |item| item.name end item_names.sort end end
true
78715bb104f1dacf6520a681f3d3ffcff2ee3697
Ruby
peterylai/code-challenges
/leetcode/63_unique_paths_2.rb
UTF-8
1,313
4.03125
4
[]
no_license
# Follow up for "Unique Paths": # Now consider if some obstacles are added to the grids. How many unique paths would there be? # An obstacle and empty space is marked as 1 and 0 respectively in the grid. # For example, # There is one obstacle in the middle of a 3x3 grid as illustrated below. # [ # [0,0,0], # [0,1,0], # [0,0,0] # ] # The total number of unique paths is 2. # Note: m and n will be at most 100. ################################################### # @param {Integer[][]} obstacle_grid # @return {Integer} def unique_paths_with_obstacles(obstacle_grid) ObstacleGrid.new(obstacle_grid).unique_paths end class ObstacleGrid attr_reader :grid, :length, :width attr_accessor :memo def initialize(grid) @grid = grid @length = grid.length @width = grid.first.length @memo = {} end def unique_paths unique_paths_at(length, width) end private def unique_paths_at(m, n) return 0 if grid[-length][-width] == 1 return 1 if m == 1 && n == 1 return memo[[n, m]] if memo[[n, m]] down_paths = m <= 1 || grid[-m+1][-n] == 1 ? 0 : unique_paths_at(m - 1, n) memo[[n, m - 1]] = down_paths right_paths = n <= 1 || grid[-m][-n+1] == 1 ? 0 : unique_paths_at(m, n - 1) memo[[n - 1, m]] = right_paths down_paths + right_paths end end
true
a2e50ca90dfcc7eadbbf147c0f4a15b0e00c06d8
Ruby
jhwebbjr/currencyconverter
/cxs_app.rb
UTF-8
1,692
3.25
3
[]
no_license
require 'pry' # => true require_relative 'Currency' # => true us_dollar = Currency.new(1000, "usd") # => #<Currency:0x007fbcff12fac0 @amount=1000, @currency_code="usd"> five_us_dollar = Currency.new(5000, "usd") # => #<Currency:0x007fbcff127938 @amount=5000, @currency_code="usd"> naija_naira = Currency.new(1000, "ngn") # => #<Currency:0x007fbcff1271b8 @amount=1000, @currency_code="ngn"> five_naija_naira = Currency.new(5000, "ngn") # => #<Currency:0x007fbcff126998 @amount=5000, @currency_code="ngn"> haitian_gourde = Currency.new(1000, "htg") # => #<Currency:0x007fbcff1262b8 @amount=1000, @currency_code="htg"> brazilian_real = Currency.new(1000, "brl") # => #<Currency:0x007fbcff125e80 @amount=1000, @currency_code="brl"> ghanian_cedi = Currency.new(1000, "ghs") # => #<Currency:0x007fbcff125ae8 @amount=1000, @currency_code="ghs"> us_dollar == us_dollar # => true us_dollar == naija_naira # => false total = us_dollar + five_us_dollar # => #<Currency:0x007fbcff124e90 @amount=6000, @currency_code="usd"> total.amount # => 6000 total = us_dollar - five_us_dollar # => #<Currency:0x007fbcff124198 @amount=-4000, @currency_code="usd"> total.amount # => -4000 # begin # total = us_dollar + five_naija_naira # rescue DifferentCurrencyCodeError # end # => nil # begin # total = us_dollar - five_naija_naira # rescue DifferentCurrencyCodeError # end # => nil # begin # total = us_dollar * five_us_dollar # => #<Currency:0x007fbcff11f9b8 @amount=5000000.0, @currency_code="usd"> # rescue ExceptionName # # end
true
2d320c8584715b4fc1e61f2398b1e42f2af20ba2
Ruby
douglasnec/school
/app/helpers/students_helper.rb
UTF-8
406
2.78125
3
[]
no_license
module StudentsHelper def values(person) if person.birth.nil? "" else person.birth.strftime('%d/%m/%Y').to_s end end def type_contact(value) case value when 1 ' (Responsible)' when 2 ' (Student)' when 3 ' (Contact)' when 4 ' (Resident)' when 5 ' (Other)' else '' end end end
true
d44b59ea9a5b56ed7764dc0b5b70d4ba5c97bce4
Ruby
lrsdev/dog-admin
/db/seeds.rb
UTF-8
3,486
2.609375
3
[]
no_license
# Basic seeds # Dog Status Values: # 0: Off lead # 1: On lead # 2: No dogs # # Region values: # 0: Southland # 1: Otago # 2: Canterbury # 3: Westland # 4: Marlborough # 5: Nelson # 6: Wellington # 7: Hawke's Bay # 8: New Plymouth # 9: Auckland # # Geolocation Points are Longitude/Latitude ablurb = "If this is in production, update it" Location.create(name: "Allans Beach", category: 0, region: 1, animal_blurb: ablurb, geolocation: "POINT(170.6609251 -45.8464573)", image: open("./db/images/allans.jpg", "r"), active: true, dog_statuses: [DogStatus.new(status: 0, guidelines: "If this is in production, update it")]) Location.create(name: "Brighton Beach", category: 0, region: 1, animal_blurb: ablurb, geolocation: "POINT(170.335150099 -45.9468324)", image: open("./db/images/brighton.jpg", "r"), active: true, dog_statuses: [DogStatus.new(status: 0, guidelines: "If this is in production, update it")]) Location.create(name: "Doctors Point", category: 0, region: 1, animal_blurb: ablurb, geolocation: "POINT(170.6609251 -45.8464573)", image: open("./db/images/doctors.jpg", "r"), active: true, dog_statuses: [DogStatus.new(status: 0, guidelines: "If this is in production, update it")]) Location.create(name: "Long Beach", category: 0, region: 1, animal_blurb: ablurb, geolocation: "POINT(169.26666669 -46.6333333)", image: open("./db/images/long.jpg", "r"), active: true, dog_statuses: [DogStatus.new(status: 0, guidelines: "If this is in production, update it")]) Location.create(name: "St Clair Beach", category: 0, region: 1, animal_blurb: ablurb, geolocation: "POINT(170.4885635 -45.9092631)", image: open("./db/images/stclair.jpg", "r"), active: true, dog_statuses: [DogStatus.new(status: 0, guidelines: "If this is in production, update it")]) Location.create(name: "St Kilda Beach", category: 0, region: 1, animal_blurb: ablurb, geolocation: "POINT(170.5056987 -45.901957)", image: open("./db/images/stkilda.jpg", "r"), active: true, dog_statuses: [DogStatus.new(status: 0, guidelines: "If this is in production, update it")]) Location.create(name: "Tomahawk Beach", category: 0, region: 1, animal_blurb: ablurb, geolocation: "POINT(170.5397840 -45.9064872)", image: open("./db/images/tomahawk.jpg", "r"), active: true, dog_statuses: [DogStatus.new(status: 0, guidelines: "If this is in production, update it")]) Location.create(name: "Tunnel Beach", category: 0, region: 1, animal_blurb: ablurb, geolocation: "POINT(170.45918719 -45.92077530)", image: open("./db/images/tunnel.jpg", "r"), active: true, dog_statuses: [DogStatus.new(status: 0, guidelines: "If this is in production, update it")])
true
086636db77d6fbb9a7529a350117a88945d5feea
Ruby
liuderek97/Day4-Challenges
/category_checker.rb
UTF-8
1,277
3.59375
4
[]
no_license
data = {"chocolate things" => ["chocolate cake", "hot chocolate", "choc"], "liquids" => ["water", "hot chocolate", "cola", "juice"], "lollies" => ["skittles", "M&Ms", "licorice"]} puts "The categories you can choose from are #{data.keys}. Please choose one of the categories" user_choice = gets.chomp if data.has_key?("#{user_choice}") == false user_choice_flag = true #while loop flag condition to execute loop while user_choice_flag puts "Invalid option Please enter one of the following categories" user_choice = gets.chomp if data.has_key?("#{user_choice}") == true user_choice_flag = false end end else puts "Invalid option" while user_choice_flag puts "Invalid option Please enter one of the following categories" user_choice = gets.chomp if data.has_key?("#{user_choice}") == true user_choice_flag = false end end end puts "Please enter the maximum number of characters of the data you want to be shown" max_length = gets.chomp.to_i data.each {|key, value| if user_choice == key data[user_choice].each{|element| if element.length <= max_length puts element end } end }
true
b8fad5399f17d5846664bb00b9e5592a409ffa51
Ruby
seatgeek/shippinglogic
/lib/shippinglogic/fedex/response.rb
UTF-8
2,515
3
3
[ "MIT" ]
permissive
require "shippinglogic/fedex/error" module Shippinglogic class FedEx # Methods relating to receiving a response from FedEx and cleaning it up. module Response SUCCESSFUL_SEVERITIES = ["SUCCESS", "NOTE", "WARNING"] private # Overwriting the request method to clean the response and handle errors. def request(body) response = clean_response(super) if success?(response) response else raise Error.new(body, response) end end # Was the response a success? def success?(response) response.is_a?(Hash) && SUCCESSFUL_SEVERITIES.include?(response[:highest_severity]) end # Cleans the response and returns it in a more 'user friendly' format that is easier # to work with. def clean_response(response) cut_to_the_chase(sanitize_response_keys(response)) end # FedEx likes nested XML tags, because they send quite a bit of them back in responses. # This method just 'cuts to the chase' and get to the heart of the response. def cut_to_the_chase(response) if response.is_a?(Hash) && response.keys.first && response.keys.first.to_s =~ /_reply(_details)?$/ response.values.first else response end end # Recursively sanitizes the response object by clenaing up any hash keys. def sanitize_response_keys(response) if response.is_a?(Hash) response.inject({}) do |r, (key, value)| r[sanitize_response_key(key)] = sanitize_response_keys(value) r end elsif response.is_a?(Array) response.collect { |r| sanitize_response_keys(r) } else response end end # FedEx returns a SOAP response. I just want the plain response without all of the SOAP BS. # It basically turns this: # # {"v3:ServiceInfo" => ...} # # into: # # {:service_info => ...} # # I also did not want to use the underscore method provided by ActiveSupport because I am trying # to avoid using that as a dependency. def sanitize_response_key(key) key.to_s.sub(/^(v[0-9]|ns):/, "").gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').gsub(/([a-z\d])([A-Z])/,'\1_\2').downcase.to_sym end end end end
true
6f3399634afb52ee4016d8fd3a0d86ec6c923e03
Ruby
darthschmoo/fun_with_version_strings
/lib/version_strings/api.rb
UTF-8
1,016
2.765625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module FunWith module VersionStrings # methods that can be called directly upon the module FunWith::VersionStrings module API # if no string is given, the given object is assumed to have a root path and # to have a file "VERSION" immediately underneath that root. That's standard for # my gems. def versionize( obj, version_string = nil ) if obj.respond_to?(:version) warn( "FunWith::VersionStrings (warn): #{obj.to_s[0..100]} already responds to version(). Leaving alone.") return nil end if version_string.nil? if obj.respond_to?(:root) && obj.root.is_a?(FunWith::Files::FilePath) && obj.root("VERSION").file? version_string = obj.root("VERSION").read else raise "No version string specified, and cannot infer version from VERSION file." end end obj.extend( VersionizeExtender ) obj.version( version_string ) end end end end
true
d7d33fec4ff9973b963fda94066e59bc6567bedc
Ruby
rbrother/ReactionSimulator
/ReactionSimulator/Simulate.rb
UTF-8
1,686
3.34375
3
[]
no_license
require 'reaction' class Simulation attr_reader :reagents, :reactions def initialize(*molecules) # list of { :name => 'H2O(l)', :conc => 55.55 } @reagents = molecules.map { |m| [ m[:name], Reagent.new(m[:name],m[:conc]) ] }.to_hash @reactions = Reaction.find_reactions( reagents ) end def report puts "======= Concentrations ========" @reagents.values.map { |r| r.to_s } end def reagent(name) @reagents.fetch(name) end def conc(name) reagent(name).conc end def simulate_equilibrium(verbose = false) # Currently we individually optimise single equilibrium equations one at a time, # then repeat over the set of equations several times until all are converged. # This is clearly not optimal but seems to suffice and converge globally ok for # cases tested so far. A more optimal approach would optimize all independent # variables in one multi-dimensional multi-variable optimisation. TODO: Check 10.times do |n| puts "\n================= ROUND #{n} =================" if verbose @reactions.each { |reaction| reaction.simulate_equilibrium( verbose ) } if @reactions.all? { |r| r.converged? } puts "**** ALL CONVERGED ****" if verbose return true # converged end puts report if verbose end puts "!!!!!!!!!!!!!!!!! FAILS TO CONVERGE !!!!!!!!!!!!!!!!!!!!" if verbose false end def simulate_time(duration) @reactions.each { |reaction| reaction.simulate_time(duration) } end end
true
f4dbc00b307a20161f06cd1879b5cbd81d3dfea3
Ruby
odysseus/wot_ruby
/code_files/tank_group.rb
UTF-8
386
3.046875
3
[]
no_license
require_relative './tank.rb' class TankGroup attr_accessor :group, :db, :name def initialize dict @db = TankStore.db @group = [] dict.each do |k,v| tank = Tank.new(v) tank.db = @db @group.push(tank) end end def self.to_s "TankGroup" end def first @group.first end def each @group.each { |tank| yield tank } end end
true
cb84d2325b1da2b25abf4c1b0249344585547376
Ruby
jpsilva20/collections_practice-online-web-sp-000
/collections_practice.rb
UTF-8
767
3.921875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def sort_array_asc(array) array.sort do |a, b| a <=> b end end def sort_array_desc(array) array.sort do |a, b| -(a <=> b) end end def sort_array_char_count(array) array.sort do |a, b| a.length <=> b.length end end def swap_elements(array) array[1], array[2] = array[2],array[1] array end def reverse_array(array) array.reverse end def kesha_maker(array) array.each do |character| character[2] = "$" end end def find_a(array) array.select do |character| character[0] == "a" end end def sum_array(array) array.inject(0){|sum,x| sum + x } end def add_s(array) array.each_with_index.collect do |word,index| if index != 1 word = word + "s" else word = word end end end
true
2ef364d8461156c5109a71e5f528daa02260cc9d
Ruby
raskhadafi/vesr
/lib/vesr/reference_builder.rb
UTF-8
726
2.546875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require 'vesr/validation_digit_calculator' module VESR class ReferenceBuilder def self.call(customer_id, invoice_id, esr_id) new(customer_id, invoice_id, esr_id).call end attr_reader :customer_id, :invoice_id, :esr_id def initialize(customer_id, invoice_id, esr_id) @customer_id = customer_id @invoice_id = invoice_id @esr_id = esr_id end def call "#{esr_id}#{formatted_customer_id}#{formatted_invoice_id}" end private def formatted_customer_id format "%0#{customer_id_length}i", customer_id end def customer_id_length 19 - esr_id.to_s.length end def formatted_invoice_id format '%07i', invoice_id end end end
true
d6870898790798b76e02919ea70dcac223950bd3
Ruby
SimonDein/launch
/course_101/exercises/easy_3/searching_101.rb
UTF-8
560
4.34375
4
[]
no_license
# Write a program that solicits 6 numbers from the user - # then prints a message that describes whether or not the 6th number appears amongst the first 5 numbers. obtained_numbers = [] # solution 1 5.times do |iteration| puts "=> Enter the #{(iteration + 1)}. number"'' num = gets.chomp.to_i obtained_numbers << num end puts "=> Enter the last number" last_num = gets.chomp.to_i if obtained_numbers.include?(last_num) puts "#{last_num} is in the array: #{obtained_numbers}!" else puts "#{last_num} is not in the array: #{obtained_numbers}!" end
true
03acc392f885fefb9440e0c5110bf50b99ee63b1
Ruby
bureaucratix/array-methods-lab-seattle-web-career-042219
/lib/array_methods.rb
UTF-8
611
3.9375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def using_include(array, element) array.include?(element) end def using_sort(array) array.sort end def using_reverse(array) array.reverse end def using_first(array) array.first end def using_last(array) array.last end def using_size(array) array.length end =begin Determine if an array contains a particular element using the #include? method. Sort an array using the #sort method. Reverse the contents of an array using the #reverse method. Find the first and last elements in an array using the #first and #last methods. Determine the size, or length, of an array using the #size method =end
true
3b7e473513638b2c89e2dda609511265e45961e5
Ruby
rails/rails
/activerecord/lib/active_record/aggregations.rb
UTF-8
14,702
3.75
4
[ "MIT", "Ruby" ]
permissive
# frozen_string_literal: true module ActiveRecord # See ActiveRecord::Aggregations::ClassMethods for documentation module Aggregations def initialize_dup(*) # :nodoc: @aggregation_cache = @aggregation_cache.dup super end def reload(*) # :nodoc: clear_aggregation_cache super end private def clear_aggregation_cache @aggregation_cache.clear if persisted? end def init_internals super @aggregation_cache = {} end # = Active Record \Aggregations # # Active Record implements aggregation through a macro-like class method called #composed_of # for representing attributes as value objects. It expresses relationships like "Account [is] # composed of Money [among other things]" or "Person [is] composed of [an] address". Each call # to the macro adds a description of how the value objects are created from the attributes of # the entity object (when the entity is initialized either as a new object or from finding an # existing object) and how it can be turned back into attributes (when the entity is saved to # the database). # # class Customer < ActiveRecord::Base # composed_of :balance, class_name: "Money", mapping: { balance: :amount } # composed_of :address, mapping: { address_street: :street, address_city: :city } # end # # The customer class now has the following methods to manipulate the value objects: # * <tt>Customer#balance, Customer#balance=(money)</tt> # * <tt>Customer#address, Customer#address=(address)</tt> # # These methods will operate with value objects like the ones described below: # # class Money # include Comparable # attr_reader :amount, :currency # EXCHANGE_RATES = { "USD_TO_DKK" => 6 } # # def initialize(amount, currency = "USD") # @amount, @currency = amount, currency # end # # def exchange_to(other_currency) # exchanged_amount = (amount * EXCHANGE_RATES["#{currency}_TO_#{other_currency}"]).floor # Money.new(exchanged_amount, other_currency) # end # # def ==(other_money) # amount == other_money.amount && currency == other_money.currency # end # # def <=>(other_money) # if currency == other_money.currency # amount <=> other_money.amount # else # amount <=> other_money.exchange_to(currency).amount # end # end # end # # class Address # attr_reader :street, :city # def initialize(street, city) # @street, @city = street, city # end # # def close_to?(other_address) # city == other_address.city # end # # def ==(other_address) # city == other_address.city && street == other_address.street # end # end # # Now it's possible to access attributes from the database through the value objects instead. If # you choose to name the composition the same as the attribute's name, it will be the only way to # access that attribute. That's the case with our +balance+ attribute. You interact with the value # objects just like you would with any other attribute: # # customer.balance = Money.new(20) # sets the Money value object and the attribute # customer.balance # => Money value object # customer.balance.exchange_to("DKK") # => Money.new(120, "DKK") # customer.balance > Money.new(10) # => true # customer.balance == Money.new(20) # => true # customer.balance < Money.new(5) # => false # # Value objects can also be composed of multiple attributes, such as the case of Address. The order # of the mappings will determine the order of the parameters. # # customer.address_street = "Hyancintvej" # customer.address_city = "Copenhagen" # customer.address # => Address.new("Hyancintvej", "Copenhagen") # # customer.address = Address.new("May Street", "Chicago") # customer.address_street # => "May Street" # customer.address_city # => "Chicago" # # == Writing value objects # # Value objects are immutable and interchangeable objects that represent a given value, such as # a Money object representing $5. Two Money objects both representing $5 should be equal (through # methods such as <tt>==</tt> and <tt><=></tt> from Comparable if ranking makes sense). This is # unlike entity objects where equality is determined by identity. An entity class such as Customer can # easily have two different objects that both have an address on Hyancintvej. Entity identity is # determined by object or relational unique identifiers (such as primary keys). Normal # ActiveRecord::Base classes are entity objects. # # It's also important to treat the value objects as immutable. Don't allow the Money object to have # its amount changed after creation. Create a new Money object with the new value instead. The # <tt>Money#exchange_to</tt> method is an example of this. It returns a new value object instead of changing # its own values. Active Record won't persist value objects that have been changed through means # other than the writer method. # # The immutable requirement is enforced by Active Record by freezing any object assigned as a value # object. Attempting to change it afterwards will result in a +RuntimeError+. # # Read more about value objects on http://c2.com/cgi/wiki?ValueObject and on the dangers of not # keeping value objects immutable on http://c2.com/cgi/wiki?ValueObjectsShouldBeImmutable # # == Custom constructors and converters # # By default value objects are initialized by calling the <tt>new</tt> constructor of the value # class passing each of the mapped attributes, in the order specified by the <tt>:mapping</tt> # option, as arguments. If the value class doesn't support this convention then #composed_of allows # a custom constructor to be specified. # # When a new value is assigned to the value object, the default assumption is that the new value # is an instance of the value class. Specifying a custom converter allows the new value to be automatically # converted to an instance of value class if necessary. # # For example, the +NetworkResource+ model has +network_address+ and +cidr_range+ attributes that should be # aggregated using the +NetAddr::CIDR+ value class (https://www.rubydoc.info/gems/netaddr/1.5.0/NetAddr/CIDR). # The constructor for the value class is called +create+ and it expects a CIDR address string as a parameter. # New values can be assigned to the value object using either another +NetAddr::CIDR+ object, a string # or an array. The <tt>:constructor</tt> and <tt>:converter</tt> options can be used to meet # these requirements: # # class NetworkResource < ActiveRecord::Base # composed_of :cidr, # class_name: 'NetAddr::CIDR', # mapping: { network_address: :network, cidr_range: :bits }, # allow_nil: true, # constructor: Proc.new { |network_address, cidr_range| NetAddr::CIDR.create("#{network_address}/#{cidr_range}") }, # converter: Proc.new { |value| NetAddr::CIDR.create(value.is_a?(Array) ? value.join('/') : value) } # end # # # This calls the :constructor # network_resource = NetworkResource.new(network_address: '192.168.0.1', cidr_range: 24) # # # These assignments will both use the :converter # network_resource.cidr = [ '192.168.2.1', 8 ] # network_resource.cidr = '192.168.0.1/24' # # # This assignment won't use the :converter as the value is already an instance of the value class # network_resource.cidr = NetAddr::CIDR.create('192.168.2.1/8') # # # Saving and then reloading will use the :constructor on reload # network_resource.save # network_resource.reload # # == Finding records by a value object # # Once a #composed_of relationship is specified for a model, records can be loaded from the database # by specifying an instance of the value object in the conditions hash. The following example # finds all customers with +address_street+ equal to "May Street" and +address_city+ equal to "Chicago": # # Customer.where(address: Address.new("May Street", "Chicago")) # module ClassMethods # Adds reader and writer methods for manipulating a value object: # <tt>composed_of :address</tt> adds <tt>address</tt> and <tt>address=(new_address)</tt> methods. # # Options are: # * <tt>:class_name</tt> - Specifies the class name of the association. Use it only if that name # can't be inferred from the part id. So <tt>composed_of :address</tt> will by default be linked # to the Address class, but if the real class name is +CompanyAddress+, you'll have to specify it # with this option. # * <tt>:mapping</tt> - Specifies the mapping of entity attributes to attributes of the value # object. Each mapping is represented as a key-value pair where the key is the name of the # entity attribute and the value is the name of the attribute in the value object. The # order in which mappings are defined determines the order in which attributes are sent to the # value class constructor. The mapping can be written as a hash or as an array of pairs. # * <tt>:allow_nil</tt> - Specifies that the value object will not be instantiated when all mapped # attributes are +nil+. Setting the value object to +nil+ has the effect of writing +nil+ to all # mapped attributes. # This defaults to +false+. # * <tt>:constructor</tt> - A symbol specifying the name of the constructor method or a Proc that # is called to initialize the value object. The constructor is passed all of the mapped attributes, # in the order that they are defined in the <tt>:mapping option</tt>, as arguments and uses them # to instantiate a <tt>:class_name</tt> object. # The default is <tt>:new</tt>. # * <tt>:converter</tt> - A symbol specifying the name of a class method of <tt>:class_name</tt> # or a Proc that is called when a new value is assigned to the value object. The converter is # passed the single value that is used in the assignment and is only called if the new value is # not an instance of <tt>:class_name</tt>. If <tt>:allow_nil</tt> is set to true, the converter # can return +nil+ to skip the assignment. # # Option examples: # composed_of :temperature, mapping: { reading: :celsius } # composed_of :balance, class_name: "Money", mapping: { balance: :amount } # composed_of :address, mapping: { address_street: :street, address_city: :city } # composed_of :address, mapping: [ %w(address_street street), %w(address_city city) ] # composed_of :gps_location # composed_of :gps_location, allow_nil: true # composed_of :ip_address, # class_name: 'IPAddr', # mapping: { ip: :to_i }, # constructor: Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) }, # converter: Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) } # def composed_of(part_id, options = {}) options.assert_valid_keys(:class_name, :mapping, :allow_nil, :constructor, :converter) unless self < Aggregations include Aggregations end name = part_id.id2name class_name = options[:class_name] || name.camelize mapping = options[:mapping] || [ name, name ] mapping = [ mapping ] unless mapping.first.is_a?(Array) allow_nil = options[:allow_nil] || false constructor = options[:constructor] || :new converter = options[:converter] reader_method(name, class_name, mapping, allow_nil, constructor) writer_method(name, class_name, mapping, allow_nil, converter) reflection = ActiveRecord::Reflection.create(:composed_of, part_id, nil, options, self) Reflection.add_aggregate_reflection self, part_id, reflection end private def reader_method(name, class_name, mapping, allow_nil, constructor) define_method(name) do if @aggregation_cache[name].nil? && (!allow_nil || mapping.any? { |key, _| !read_attribute(key).nil? }) attrs = mapping.collect { |key, _| read_attribute(key) } object = constructor.respond_to?(:call) ? constructor.call(*attrs) : class_name.constantize.send(constructor, *attrs) @aggregation_cache[name] = object.freeze end @aggregation_cache[name] end end def writer_method(name, class_name, mapping, allow_nil, converter) define_method("#{name}=") do |part| klass = class_name.constantize unless part.is_a?(klass) || converter.nil? || part.nil? part = converter.respond_to?(:call) ? converter.call(part) : klass.send(converter, part) end hash_from_multiparameter_assignment = part.is_a?(Hash) && part.keys.all?(Integer) if hash_from_multiparameter_assignment raise ArgumentError unless part.size == part.each_key.max part = klass.new(*part.sort.map(&:last)) end if part.nil? && allow_nil mapping.each { |key, _| write_attribute(key, nil) } @aggregation_cache[name] = nil else mapping.each { |key, value| write_attribute(key, part.send(value)) } @aggregation_cache[name] = part.dup.freeze end end end end end end
true
9cf4b587bf03b1134d34c62357abab4cdbed87bc
Ruby
kjkkuk/homeworks
/HW_05/Aleksei_Makar/student.rb
UTF-8
784
2.890625
3
[]
no_license
require_relative 'human' require_relative 'authorization' require_relative 'homework' require_relative 'api' require 'uri' require 'net/http' # creates a student and describes his behavior class Student < Human include Authorization def create_homework(source:, title:) Homework.new(homework_source: source, student: self, pr_title: title) end def submit_homework(homework, api) title = homework.pr_title if homework.owner?(self) && api.user_connected?(self) Net::HTTP.post URI('http://www.example.com/'), homework.json, 'Content-Type' => 'application/json' api.add_homework(self, homework) return puts "#{name} successfully sent #{title}" end puts "#{name} could not send #{title}" end end
true
a3f86e6d36d845124990348fa46674b0441122de
Ruby
bataylor976/puppet-samba
/spec/support/augeas.rb
UTF-8
1,180
2.828125
3
[ "MIT" ]
permissive
require "delegate" module Augeas class Change attr_reader :target, :name, :delimiter def initialize(target, name, value = nil, delimiter = "\"") @target = target @name = name @value = value @delimiter = delimiter end def to_s "#{action} #{delimiter}target[. = '#{target}']/#{name}#{delimiter}#{value}" end def hash [target, name, Change].hash end def ==(other) other.is_a?(self.class) && [other.target, other.name] == [target, name] end alias_method :eql?, :== private def action return "set" unless @value.nil? "rm " end def value " #{@value}" if @value end end class ChangeSet def initialize @set = [] end def <<(change) index = @set.index(change) || @set.length @set[index] = change end def to_a changes end def changes @set.map(&:to_s) end end class TargetedChangeSet < DelegateClass(ChangeSet) def initialize(target) @target = target super(ChangeSet.new) end def with(*args) self << Change.new(@target, *args) self end end end
true
a12628f245adcc2585d107bc0f031083ee60b87f
Ruby
GordonNY/collections_practice_vol_2-001-prework-web
/collections_practice.rb
UTF-8
1,111
3.4375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# your code goes here def begins_with_r(arr) arr.all? { |e| e.start_with?("r") } end def contain_a(arr) arr.select { |e| e.include?("a")} end def first_wa(arr) arr.detect { |e| if e.class === "String" e.start_with?("wa") else false end } end def remove_non_strings(arr) arr.reject! {|e| !(e.class === "String")} end def count_elements(arr) new_arr = arr.uniq arr.collect { |x| count = 0 while count < new_arr.count if x[:name] === new_arr[count][:name] new_arr[count][:count] === nil ? new_arr[count][:count] = 1 : new_arr[count][:count] += 1 end count += 1 end } new_arr end def merge_data(keys, data) keys.collect { |x| count = 0 while count < data.count x.merge!(data[count][x[:first_name]]) if data[count].has_key?(x[:first_name]) count += 1 end x } end def find_cool(arr) arr.select { |x| x[:temperature] == "cool"} end def organize_schools(schools) hash = Hash.new schools.each { |k, v| hash.keys.include?(v[:location]) ? hash[v[:location]] << k : hash[v[:location]] = [k] } hash end
true
e886121527a2a2a7348a14f8101e15036e5c60d3
Ruby
sky-uk/mirage
/features/support/command_line.rb
UTF-8
862
2.5625
3
[]
no_license
require 'tempfile' require 'wait_methods' module CommandLine include Mirage::WaitMethods def run command output = Tempfile.new("child") Dir.chdir SCRATCH do process = ChildProcess.build(*("#{command}".split(' '))) process.detach process.io.stdout = output process.io.stderr = output process.start wait_until(:timeout_after => 30) { process.exited? } end File.read(output.path) end def normalise text text.gsub(/[\n]/, ' ').gsub(/\s+/, ' ').strip end def write_to_file file_path, content file_path = "#{SCRATCH}/#{file_path}" unless file_path =~ /^\// FileUtils.rm_rf(file_path) if File.exists?(file_path) FileUtils.mkdir_p(File.dirname(file_path)) File.open("#{file_path}", 'w') do |file| file.write(content) end end end World CommandLine include CommandLine
true
88086c67f77299a5020f311b74ba4cea70b776f2
Ruby
mikeapp/disco
/app/models/resource.rb
UTF-8
2,352
2.5625
3
[]
no_license
require 'net/http' class Resource < ApplicationRecord validates :object_id, presence: true validates :object_type, presence: true def create_event_if_changed response = request(object_id, true) response = request(object_id) if response.code == '405' process_response(response) end private def process_response(response) t = Time.now event_type_str = nil exists = !etag.nil? case response when Net::HTTPSuccess then response_etag = response.header['etag'] unless response_etag response = request(object_id).response raise "Error requesting body for #{object_id}" unless response.code == '200' response_etag = Digest::MD5.hexdigest(response.body) end return if exists and response_etag == etag event_type_str = (exists)? 'Update' : 'Create' self.etag = response_etag when Net::HTTPGone, Net::HTTPNotFound then event_type_str = 'Delete' self.etag = nil self.object_last_update = Time.now else logger.info("Received unexpected response code #{response.code} for #{object_id}") return end self.object_last_update = t event = create_event(event_type_str) save event end def create_event(event_type_str, time = Time.now) raise 'Event type must not be nil' if event_type_str.nil? event_type = ActivityStreamsEventType.find_by_event_type(event_type_str) raise "Unknown event type #{event_type_str}" unless event_type event = ActivityStreamsEvent.new event.object_id = object_id event.object_type = object_type event.event_type = event_type event.end_time = time event.save event end def request(object_uri, head = false, depth = 0) raise 'Too many redirects' if depth > 5 uri = URI.parse(object_uri) http = Net::HTTP.new(uri.host, uri.port) http.use_ssl = (uri.port == 443) response = if head http.head(uri.path).response else http.get(uri.path).response end case response when Net::HTTPSuccess then response when Net::HTTPMethodNotAllowed then response when Net::HTTPGone, Net::HTTPNotFound then response when Net::HTTPRedirection then request(response['location'], head, depth + 1) else response.error! end end end
true
d6497a9443d730e645199a0a98eb49572351cb73
Ruby
MarielJHoepelman/activerecord-tvland-v-000
/app/models/actor.rb
UTF-8
673
3.359375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#* Associate the `Actor` model with the `Character` and `Show` model. An actor should have many characters and many shows through characters.mh #* Write a method in the `Actor` class, `#full_name`, that returns the first and last name of an actor. #* Write a method in the `Actor` class, `#list_roles`, that lists all of the characters that actor has. #An actor has many characters and has many shows through characters. MH class Actor < ActiveRecord::Base has_many :characters has_many :shows, through: :characters def full_name "#{first_name} #{last_name}" end def list_roles characters.map do |c| "#{c.name} - #{c.show.name}" end end end
true
da9423fee58a8b142a40134a23cc1e3009bb1a8a
Ruby
raganwald-deprecated/rewrite
/pkg/rewrite-0.3.0/lib/rewrite/by_example/length_one.rb
UTF-8
1,196
2.90625
3
[ "MIT" ]
permissive
$:.unshift File.dirname(__FILE__) module Rewrite module ByExample # Natches a sequence containing one item. Wraps an entity matcher, # with the wrapped matcher matching the one item. # # Confusing? Consider SymbolEntity.new(:foo). It matches a single # entity, :foo. Whereas LengthOne.new(SymbolEntity.new(:foo)) matches # a sequence of length one where that one thing happens to match :foo. # # This distinction is important because sequences can only consist of # collections of other sequences. So the LengthOnes are leaves of # the sequence trees. class LengthOne < Sequence attr_reader :matcher def initialize(entity_matcher) @matcher = entity_matcher @lambda = lambda { |arr| entity_matcher.unfold(arr.first) } end def unfolders_by_length(length) if length == 1 [ @lambda ] else [] end end def length_range 1..1 end def to_s "<#{matcher.to_s}>" end def fold(enum_of_bindings) matcher.fold(enum_of_bindings) end end end end
true
09844cc9ffa9a6609747e2ec6ea83825b9fbcf14
Ruby
jovelabs/jumpkick
/lib/jumpkick/logger.rb
UTF-8
900
2.515625
3
[ "MIT" ]
permissive
require "logger" class Jumpkick::Logger < ::Logger SEVERITIES = Severity.constants.inject([]) {|arr,c| arr[Severity.const_get(c)] = c; arr} def parse_caller(at) if /^(.+?):(\d+)(?::in `(.*)')?/ =~ at file = Regexp.last_match[1] line = Regexp.last_match[2] method = Regexp.last_match[3] "#{File.basename(file)}:#{line}:#{method} | " else "UNKNOWN_CALLER | " end end def add(severity, message = nil, progname = nil, &block) if @logdev.nil? || (@level > severity) return true end who_called = parse_caller(caller[1]) message = [message, progname, (block && block.call)].delete_if{|i| i == nil}.join(': ') message = "%19s.%-6d | %5s | %5s | %s%s\n" % [Time.now.utc.strftime("%Y-%m-%d %H:%M:%S"), Time.now.usec, Process.pid.to_s, SEVERITIES[severity], who_called, message] @logdev.write(message) true end end
true
70b8c3d4eee29c15852c16c1fc1ffbe34dcd9377
Ruby
tvaroglu/ruby-exercises
/command-query/exercises/lib/children/children.rb
UTF-8
326
3.265625
3
[]
no_license
class Children attr_accessor :children def initialize() @children = Array.new end def <<(child) if child.class == Child children << { :name => child.name, :age => child.age } end end def eldest() return children.max_by do |child| child[:age] end end end
true
1681494b54005dfd96ef7f75cd8e618b72ea2165
Ruby
jcovell/my-first-repository
/more_stuff/regex.rb
UTF-8
1,110
4.21875
4
[]
no_license
# Creating regular expressions starts with the forward slash character (/). Inside two forward slashes you can place any characters you would like to match with the string. We can use the =~ operator to see if we have a match in our regular expression. Let's say we are looking for the letter "b" in a string "powerball". "powerball" =~ /b/ def has_a_b?(string) if string =~ /b/ puts "We have a match!" else puts "No match here." end end has_a_b?("basketball") has_a_b?("football") has_a_b?("hockey") has_a_b?("golf") # boolean_matchdata.rb: On top of the =~ operator, we can use the match method to perform regex comparisons as well. This method returns a MatchData object that describes the match or nil if there is no match. You can use a MatchData object to act as a boolean value in your program. def has_a_b?(string) if /b/.match(string) puts "We have a match!" else puts "No match here." end end has_a_b?("basketball") has_a_b?("football") has_a_b?("hockey") has_a_b?("golf") # If you encounter a string pattern matching problem, remember to look into using regex.
true
160659b18e77809c37fa31d99f99e4180e7d658d
Ruby
kayline/backbone_task_lists
/db/seeds.rb
UTF-8
348
2.71875
3
[]
no_license
first_list = List.new first_list.title = "A Task List" first_list.description = "An example list for playing around" first_list.save task1 = Task.new task1.description = "A thing to do" task2 = Task.new task2.description = "Another thing that needs doing" tasks = [task1,task2] tasks.each do |t| t.save first_list.tasks << t end first_list.save
true
35b2ce5222d49b2fcf7b33d9f1f30e9004f73996
Ruby
ivanbrennan/Rspec-Code-Coverage
/jukebox_spec.rb
UTF-8
2,062
3.015625
3
[]
no_license
require 'simplecov' SimpleCov.start require 'json' require 'rspec' require_relative 'jukebox' require_relative 'song' test_songs = [ "The Phoenix - 1901", "Tokyo Police Club - Wait Up", "Sufjan Stevens - Too Much", "The Naked and the Famous - Young Blood", "(Far From) Home - Tiga", "The Cults - Abducted", "The Phoenix - Consolation Prizes" ] describe "Song" do it "can be initialized" do song = Song.new("Step Right Up") song.should be_an_instance_of(Song) end it "can have a name" do song = Song.new("Hit the Lights") song.name.should eq("Hit the Lights") end end describe "Jukebox" do let(:song_objects) { test_songs. map { |test_song| Song.new(test_song) } } let(:jukebox) { Jukebox.new(song_objects) } let(:instructions) { "Please select help, list, exit, or play." } it "can be initialized" do jukebox.should be_an_instance_of(Jukebox) end it "is on" do jukebox.on?.should eq(true) end it "offers instructions" do jukebox.help.should eq(instructions) end describe "with songs" do it "has songs" do jukebox.songs.should eq(song_objects) end describe "with approved command input" do let(:list_response) { test_songs.each_with_index.map { |test_song, i| "#{i+1} #{test_song}\n" }.join } it "accepts a list command" do jukebox.command("list").should eq(list_response) end it "accepts a help command" do jukebox.command("help").should eq(instructions) end it "accepts an exit command" do jukebox.command("exit") jukebox.on?.should eq(false) end end describe "with play command" do it "plays requested song" do jukebox.command("play Wait Up"). should eq("now playing Wait Up") end end describe "with an invalid command" do it "gives \"invalid command\" message" do jukebox.command("garbage"). should eq("invalid command") end end end end
true
4b1f69170ebaabc85e880fd5a4157b66aef321dd
Ruby
geethh007/July18-22Work
/RubyTesting/Conditions.rb
UTF-8
526
3.78125
4
[]
no_license
#require 'A2' #obj= A2.new #obj.checkNature(-9) require 'A1' obj=A1.new(10,5) s=obj.sub(20,30) puts obj.mul(s,100) r=obj.sum(20,10) t=obj.sub(20,10) puts obj.mul(r,t) obj.table(9) puts"" obj.reverseTable(9) puts "" obj.forLoopTripleDot(4) puts "" obj.forLoopDoubleDot(2) puts"" #approach-1 arr1= Array.new(5) arr2= Array.new(3) arr1=["Hello",23,"Testing", 23.45] arr1[3]=9.44 puts arr1[3] #approach-2 arr2[0]="hello" arr2[1]=20 puts arr2 arr1.each do |i| puts i end
true
36ae2bfe180f85740477953fa290973d9b748035
Ruby
jsoranno/castaway
/lib/castaway/element/text.rb
UTF-8
1,582
2.84375
3
[ "MIT" ]
permissive
require 'castaway/element/base' module Castaway module Element class Text < Element::Base def initialize(production, scene, string) super(production, scene) @string = string @gravity = 'Center' @font = 'TimesNewRoman' @font_size = 24 @background = 'transparent' @kerning = 0 @fill = @stroke = nil attribute(:font_size, 1) { |memo, value| memo * value } attribute(:kerning, -> { @kerning }) { |memo, value| memo + value } end def fill(color) @fill = color self end def stroke(color) @stroke = color self end def background(color) @background = color self end def kerning(kerning) @kerning = kerning self end def gravity(gravity) @gravity = gravity self end def font(font) @font = font self end def font_size(size) @font_size = size self end def _prepare_canvas(t, canvas) canvas.xc @background font_size = @font_size * attributes[:font_size] kerning = attributes[:kerning] canvas.pointsize font_size commands = [ "gravity #{@gravity}", "font '#{@font}'" ] commands << "fill #{@fill}" if @fill commands << "stroke #{@stroke}" if @stroke commands << format('kerning %.1f', kerning) if kerning commands << "text 0,0 '#{@string}'" canvas.draw commands.join(' ') end end end end
true
053b455278ee7d644cd2238e9c253c28c25ad293
Ruby
xoptov/trading-core-ruby
/lib/trading_core/models/trade.rb
UTF-8
1,900
3.171875
3
[]
no_license
require 'rate' module TradingCore module Model module Trade include Rate attr_reader :origin_id, :currency_pair, :type, :created_at TYPE_SELL = :sell TYPE_BUY = :buy # @param origin_id Integer # @param currency_pair CurrencyPair # @param type Symbol # @param price Float # @param volume Float # @param created_at Time def initialize(origin_id, currency_pair, type, price, volume, created_at) @origin_id = origin_id @currency_pair = currency_pair @type = type @price = price @volume = volume @created_at = created_at end # @return String def base_symbol @currency_pair.base_symbol end # @return String def quote_sumbol @currency_pair.quote_symbol end # @param other Trade def ==(other) return @origin_id == other.origin_id if other.instance_of? Trade raise AttributeError 'Unsupported type' end # @param symbol String def symbol?(symbol) @currency_pair.symbol? symbol end # @param type Symbol def type?(type) @type == type end def buy? @type == TYPE_BUY end def sell? @type == TYPE_SELL end # @return Array def supported_types [TYPE_SELL, TYPE_BUY] end # @param type Symbol def support_type?(type) supported_types.index(type) end # @param currency Currency def base_currency?(currency) @currency_pair.base? currency end # @param currency Currency def quote_currency?(currency) @currency_pair.quote? currency end # @param currency Currency def currency?(currency) @currency_pair.currency? currency end end end end
true
7a8060ca2a43c9be492090c78b5b1f4a51ab6972
Ruby
eduardopoleo/ctci
/linked_list/sum_list.rb
UTF-8
1,704
3.5
4
[]
no_license
require_relative './linked_list' def sum_list(head1, head2) # current = head1 # number1 = 0 # multiple = 1 # # while current != nil # number1 += current.id * multiple # multiple *= 10 # current = current.next # end # # current = head2 # number2 = 0 # multiple = 1 # # while current != nil # number2 += current.id * multiple # multiple *= 10 # current = current.next # end # # number = number1 + number2 # previous = nil # # number.to_s.each_char do |c| # node = Node.new(c.to_i) # if !previous # previous = node # next # end # # node.next = previous # previous = node # end # previous ## O(n1 + n2) ## is it possible to calculate this in one go. current1 = head1 current2 = head2 number1 = 0 number2 = 0 previous = nil head = nil extra = 0 sum = 0 loop do id1 = current1 ? current1.id : 0 id2 = current2 ? current2.id : 0 sum = id1 + id2 + extra node_id = sum % 10 extra = sum / 10 node = Node.new(node_id) if previous previous.next = node previous = node else previous = node head = node end sum = 0 current1 = current1 ? current1.next : nil current2 = current2 ? current2.next : nil break if current1.nil? && current2.nil? end head # this is a superior solution # O(N of largest) # Do not rely on transformations end node1 = Node.new(4) node2 = Node.new(3) node3 = Node.new(2) node4 = Node.new(1) node1.next = node2 node2.next = node3 node3.next = node4 node5 = Node.new(3) node6 = Node.new(2) node7 = Node.new(1) node5.next = node6 node6.next = node7 p sum_list(node1, node5)
true
81821901436f5d0158b2e944fac1e7b9b047c1e2
Ruby
sergey-elkin/yandex_dictionary_api
/spec/spec_yandex_dictionary_api.rb
UTF-8
836
2.546875
3
[ "MIT" ]
permissive
require "spec_helper" describe YandexDictionaryApi do before do $interface = YandexDictionaryApi::ApiInterface.new(ENV["API_KEY"]) end it "should return a list of supported languages" do res = $interface.get_langs res.include?("en-en") end it "should return a class contains translation and interpretation of the text" do params = { "lang" => "en-ru", "text" => "time" } res = $interface.lookup(params) res["def"][0]["text"] == "time" end it "should return an array of instances Article class" do params = { "lang" => "en-ru", "text" => "time" } articles = $interface.lookup_arr( params ) articles.each do |article| puts article.text puts article.translations puts article.synonyms puts article.means puts article.examples end true end end
true
82a677152d92cfb4303f783e8492c8ebc3c4ea8c
Ruby
TimotheRuffino/S3_J3_Scraping_to_files
/lib/scrap_mairies.rb
UTF-8
2,744
3.015625
3
[]
no_license
require 'nokogiri' require 'open-uri' require 'google_drive' require 'csv' # require 'pry' #binding.pry class MailMairie attr_accessor :what_db, :mairie_hash def initialize(what_db) @what_db = what_db end def create_hash_of_name_and_mail $annuaire = Nokogiri::HTML(open("http://annuaire-des-mairies.com/val-d-oise.html")) def get_townhall_urls url_mairies = [] url_mairies = $annuaire.css('//table[@class="Style20"]//a').map { |link| link["href"] } url_mairies_full = [] url_mairies.each do |i| url_mairies_full << 'http://annuaire-des-mairies.com/' + i end url_mairies_full end def get_townhall_name names_mairies = [] $annuaire.css('tr > td > p > a').each do |node| names_mairies << node.text end names_mairies end def extract_email_of_url(url) array_emails_mairies = [] url.each do |i| page_cities = Nokogiri::HTML(open(i)) page_cities.xpath('/html/body/div/main/section[2]/div/table/tbody/tr[4]/td[2]').each do |node| array_emails_mairies << node.text end end array_emails_mairies end def name_and_emails_in_hash(names, emails) puts "Veuillez patienter quelques secondes ;-)" @mairie_hash = [] i = 0 names.each do |key| @mairie_hash << {key => emails[i]} i += 1 end return @mairie_hash end name_and_emails_in_hash(get_townhall_name, extract_email_of_url(get_townhall_urls)) end def choose_what_db if @what_db == "json" save_as_JSON elsif @what_db == "google" save_as_spreadsheet else @what_db == "csv" save_as_CSV end end def save_as_JSON File.open("db/mails.json","w") do |f| f.write(@mairie_hash.to_json) end puts "Ok c'est enregistré dans 'db/mails.json'" end def save_as_spreadsheet session = GoogleDrive::Session.from_config("db/config.json") ws = session.spreadsheet_by_key("1xUNL5Q_CTIVcEdxhubjTpfuGN3uU6LUygPR2uTkjpFU").worksheets[0] ws[1, 1] = "Names" ws[1, 2] = "Mails" line = 2 @mairie_hash.each do |i| i.each do |k, v| ws[line, 1] = k line += 1 end end line = 2 @mairie_hash.each do |i| i.each do |k, v| ws[line, 2] = v line += 1 end end ws.save puts "Ok tu peux retrouver la liste ici : https://docs.google.com/spreadsheets/d/1xUNL5Q_CTIVcEdxhubjTpfuGN3uU6LUygPR2uTkjpFU/edit?usp=sharing" end def save_as_CSV line = 1 CSV.open("db/mails.csv", "w") do |csv| @mairie_hash.each do |i| i.each do |k , v| csv << [line, k, v] line += 1 end end end puts "Ok c'est enregistré dans 'db/mails.csv'" end end
true
f1e1b001c265ac9850c392d946b37b01cdb5f1ff
Ruby
unders/eschaton
/slices/google_maps/google/pane.rb
UTF-8
1,477
2.671875
3
[ "MIT" ]
permissive
module Google # Represents a pane that can be added to the map using Map#add_pane. Useful when building your own map controls that # contain html. class Pane < MapObject # ==== Options: # # * +text+ - Optional # * +partial+ - Optional # # * +css_class+, Optional, defaulted to 'pane'. # * +anchor+ - Optional, defaulted to +top_left+ # * +offset+ - Optional, defaulted to [10, 10] def initialize(options = {}) options.default! :var => 'pane', :css_class => 'pane', :anchor => :top_left, :offset => [10, 10] super pane_options = {} pane_options[:id] = self.var.to_s pane_options[:position] = OptionsHelper.to_google_position(options) pane_options[:text] = OptionsHelper.to_content(options) pane_options[:css_class] = options[:css_class].to_s if create_var? google_options = pane_options.to_google_options(:dont_convert => [:position]) self << "#{self.var} = new GooglePane(#{google_options});" end end # Replaces the html of the pane. Works in the same way as JavascriptGenerator#replace_html # # pane.replace_html "This is new html" # pane.replace_html :text => "This is new html" # pane.replace_html :partial => 'new_html' def replace_html(options) text = options.extract(:text) if options.is_a?(Hash) self.script.replace_html self.var, text || options end end end
true
16f767ec821ae2e727a3ac50ab5be695a1d393d6
Ruby
nazwhale/ruby-kickstart
/session3/challenge/2_hashes.rb
UTF-8
679
4.0625
4
[ "MIT" ]
permissive
# Given a nonnegative integer, return a hash whose keys are all the odd nonnegative integers up to it # and each key's value is an array containing all the even non negative integers up to it. # # Examples: # staircase 1 # => {1 => []} # staircase 2 # => {1 => []} # staircase 3 # => {1 => [], 3 => [2]} # staircase 4 # => {1 => [], 3 => [2]} # staircase 5 # => {1 => [], 3 => [2], 5 =>[2, 4]} #given n >= 0 def staircase(n) hash = {} arr = [] r = n until r == 0 arr.unshift(r) r -= 1 end evens = arr.select {|v| v.even?} odds = arr.select {|v| v.odd?} a = 0 until a == odds.length hash[odds[a]] = evens[0...a] a += 1 end hash end
true
dd717a554448ab84fa786a8c7df31d4122978598
Ruby
andrewparrish/citibike_planner_api
/app/services/api_services/citibike_api_service.rb
UTF-8
475
2.78125
3
[]
no_license
require 'uri' require 'net/http' require 'json' class CitibikeApiService BASE_URL = "https://feeds.citibikenyc.com" def initialize(endpoint) @data = nil @endpoint = endpoint @uri = URI(BASE_URL + endpoint) end def perform get_data process_data end private def process_data raise(NotImplementedError, "process_data not implemented for class: #{self.class}") end def get_data @data = JSON.parse(Net::HTTP.get(@uri)) end end
true
2a7f660d46daa4b80b9445a3f222bc96632b6aba
Ruby
grimyoung/chess
/board.rb
UTF-8
14,180
3.1875
3
[]
no_license
module Chess class Board attr_accessor :grid,:white_attack,:black_attack,:white_castled,:black_castled,:enpassant, :enpassant_pawn_pos, :legal_moves #top left is (0,0) bottom right is (7,7), (row,column) def initialize @grid = Array.new(6){Array.new(8)} @grid[0] = back_rank('b', [0,0]) @grid[1] = pawns('b', [1,0]) @grid[6] = pawns('w', [6,0]) @grid[7] = back_rank('w', [7,0]) @white_attack = [] @black_attack = [] @white_castled = false @black_castled = false @enpassant = false @enpassant_pawn_pos = nil @legal_moves = [] end #need to make this pretty def display_grid row_num = 8 grid.each do |row| print row_num.to_s + " " row.each do |square| if square.nil? print " " + "__" + " " else print " " + square.piece + " " end end row_num = row_num - 1 print "\n" end print_bottom puts end def print_bottom print " " * 3 col_letter = "a" 8.times do print col_letter + " " * 3 col_letter = (col_letter.ord + 1).chr end end def inspect grid.each do |row| row.each do |square| if !square.nil? p square print "\n" end end end end #user input is pgn, code logic uses xy (row,col) # def move_piece(start_pgn, end_pgn) a,b = pgn_to_xy(start_pgn) x,y = pgn_to_xy(end_pgn) piece = grid[a][b] color = piece.color if piece.is_a?(King) && (ks_castle_possible?(color) || qs_castle_possible?(color)) castling(color,x,y) end grid[a][b] = nil if piece.is_a?(Pawn) && enpassant enpassant_move(color,x,y) end set_enpassant(piece,x,y,a) if piece.is_a?(Pawn) && (x == 0 || x == 7) piece = get_promotion(color) end grid[x][y] = piece piece.pos = [x,y] if (piece.is_a?(King) || piece.is_a?(Rook)) && piece.has_moved == false piece.has_moved = true end end def set_enpassant(piece,x,y,a) if piece.is_a?(Pawn) && (x-a).abs == 2 self.enpassant = true self.enpassant_pawn_pos = [x,y] elsif self.enpassant == true self.enpassant = false self.enpassant_pawn_pos = nil end end def enpassant_move(color,x,y) n, m = enpassant_pawn_pos if color == "w" if x == (n-1) && y == m grid[n][m] = nil end else if x == (n+1) && y == m grid[n][m] = nil end end end #works since the rook is moved before the king def castling(color,x,y) if color == "w" if x == 7 && y == 6 puts "trigger1" self.move_piece("h1", "f1") elsif x == 7 && y == 2 puts "trigger2" self.move_piece("a1","d1") end @white_castled = true else if x == 0 && y == 6 puts "trigger3" self.move_piece("h8", "f8") elsif x == 0 && y == 2 puts "trigger4" self.move_piece("a8", "d8") end @black_castled = true end end def remove_piece(pgn) x,y = pgn_to_xy(pgn) grid[x][y] = nil end def pgn_to_xy(pgn) column = {'a' => 0,'b' => 1,'c' => 2,'d' => 3,'e' => 4,'f' => 5,'g' => 6,'h' => 7} y = column[pgn[0]] x = (pgn[1].to_i-8).abs return [x,y] end #part of board set up def back_rank(color, pos) rank = [Rook.new(color, pos), Knight.new(color,pos), Bishop.new(color,pos), Queen.new(color,pos), King.new(color,pos), Bishop.new(color,pos), Knight.new(color,pos), Rook.new(color, pos)] col = 0 rank.each do |piece| piece.pos = [pos[0],pos[1]+col] col = col + 1 end return rank end def pawns(color,pos) pawn_rank = [] col = 0 8.times do pawn_rank.push(Pawn.new(color,[pos[0],pos[1]+col])) col = col + 1 end return pawn_rank end #end of board setup def in_bounds?(pos) x,y = pos if x >=0 && x <=7 && y >=0 && y <=7 return true end return false end def square_empty?(pos) x,y = pos if grid[x][y].nil? return true end return false end def friendly_square?(color, pos) if !enemy_square?(color,pos) && !square_empty?(pos) return true end return false end #true if square occupied by opposite color otherwise false def enemy_square?(color,pos) x,y = pos if grid[x][y].nil? return false elsif grid[x][y].color != color return true end return false end def square_attacked?(pos, attacked) if attacked.include?(pos) return true end return false end def attacked_squares grid.each do |row| row.each do |square| if !square.nil? square.moves = square.possible_moves(self) if square.color == "w" if square.piece.is_a?(Pawn) self.white_attack = self.white_attack + square.p_attack else self.white_attack = self.white_attack + square.moves end else if square.piece.is_a?(Pawn) self.black_attack = self.black_attack + square.p_attack else self.black_attack = self.black_attack + square.moves end end end end end end def reset_defended grid.each do |row| row.each do |square| if !square.nil? square.defended = false end end end end def add_castling(color,king_piece) #piece = grid[king_piece[0]][king_piece[1]] piece = king_piece if ks_castle_possible?(color) if color == "w" piece.moves.push([7,6]) else piece.moves.push([0,6]) end end if qs_castle_possible?(color) if color == "w" piece.moves.push([7,2]) else piece.moves.push([0,2]) end end end def add_enpassant(color,enpassant_pos) if enpassant == true a,b = enpassant_pos l_pos = [a,b-1] r_pos = [a,b+1] if color == "w" cap = [a-1,b] if in_bounds?(l_pos) && grid[l_pos[0]][l_pos[1]].is_a?(Pawn) grid[l_pos[0]][l_pos[1]].moves.push(cap) end if in_bounds?(r_pos) && grid[r_pos[0]][r_pos[1]].is_a?(Pawn) grid[r_pos[0]][r_pos[1]].moves.push(cap) end else cap = [a+1, b] if in_bounds?(l_pos) && grid[l_pos[0]][l_pos[1]].is_a?(Pawn) grid[l_pos[0]][l_pos[1]].moves.push(cap) end if in_bounds?(r_pos) && grid[r_pos[0]][r_pos[1]].is_a?(Pawn) grid[r_pos[0]][r_pos[1]].moves.push(cap) end end end end def update_board(turn_color) reset_defended reset_legal_moves attacked_squares king_pos = king_position if turn_color == "w" king_piece = grid[king_pos[0][0]][king_pos[0][1]] king_piece.remove_attack_squares(black_attack) else king_piece = grid[king_pos[1][0]][king_pos[1][1]] king_piece.remove_attack_squares(white_attack) end #if castling is possible add castling moves to king move add_castling(turn_color,king_piece) king_piece.restrict_pinned_pieces(self) #if enpassant is possible add it to pawns on right and left file on the 4th or 5th rank add_enpassant(turn_color,enpassant_pawn_pos) #restrict moves for when king is in check if king_checked?(turn_color) checker = find_checker(turn_color, king_piece.pos) if block_check?(checker) restrict_moves(turn_color, checker.path_to_king) else restrict_moves(turn_color) end end get_legal_moves(turn_color) end #[white king position, black king position] def king_position king_pieces = [nil,nil] grid.each do |row| row.each do |square| if square.is_a?(King) if square.color == "w" king_pieces[0] = square.pos else king_pieces[1] = square.pos end end end end return king_pieces end def king_checked?(color) white_king_pos, black_king_pos = king_position if color == "w" if black_attack.include?(white_king_pos) return true end else if white_attack.include?(black_king_pos) return true end end return false end def find_checker(color, king_pos) checker = [] grid.each do |row| row.each do |square| if !square.nil? && square.color != color if square.moves.include?(king_pos) checker.push(square) end end end end return checker end def block_check?(checker) piece = checker[0] puts piece if checker.length > 2 return false elsif piece.is_a?(Pawn) || piece.is_a?(Knight) return false elsif piece.path_to_king.length > 1 return true end #just in case.. return false end def reset_legal_moves @legal_moves = [] end def get_legal_moves(color) grid.each do |row| row.each do |square| if !square.nil? && square.color == color @legal_moves.push(*square.moves) end end end end def restrict_moves(color, move_array = []) grid.each do |row| row.each do |square| if !square.nil? && square.color == color && !square.is_a?(King) square.moves = square.moves.select{|move| move_array.include?(move)} end end end end def game_over(turn_color) if @legal_moves.length == 0 if king_checked?(turn_color) return :checkmate else return :stalemate end end return false end def stalemate(turn_color) if turn_color == "w" color = "white" else color = "black" end puts "Stalemate! " + color + " has no legal moves" end def checkmate(turn_color) if turn_color == "w" color = "white" else color = "black" end puts "Checkmate! " + color + " has lost by checkmate!" end def ks_castle_possible?(color) white_back_rank = grid[7] black_back_rank = grid[0] if king_checked?(color) return false end if color == "w" if white_castled == false if white_back_rank[4].is_a?(King) && white_back_rank[4].has_moved == false if white_back_rank[7].is_a?(Rook) && white_back_rank[7].has_moved == false if square_empty?([7,5]) && !square_attacked?([7,5],black_attack) && square_empty?([7,6]) && !square_attacked?([7,6],black_attack) return true end end end end else if black_castled == false if black_back_rank[4].is_a?(King) && black_back_rank[4].has_moved == false if black_back_rank[7].is_a?(Rook) && black_back_rank[7].has_moved == false if square_empty?([0,5]) && !square_attacked?([0,5],white_attack) && square_empty?([0,6]) && !square_attacked?([0,6],white_attack) return true end end end end end return false end def qs_castle_possible?(color) white_back_rank = grid[7] black_back_rank = grid[0] if king_checked?(color) return false end if color == "w" if white_castled == false if white_back_rank[4].is_a?(King) && white_back_rank[4].has_moved == false if white_back_rank[0].is_a?(Rook) && white_back_rank[0].has_moved == false if square_empty?([7,1]) && !square_attacked?([7,1],black_attack) && square_empty?([7,2]) && !square_attacked?([7,2],black_attack) && square_empty?([7,3]) && !square_attacked?([7,3],black_attack) return true end end end end else if black_castled == false if black_back_rank[4].is_a?(King) && black_back_rank[4].has_moved == false if black_back_rank[0].is_a?(Rook) && black_back_rank[0].has_moved == false if square_empty?([0,1]) && !square_attacked?([0,1],white_attack) && square_empty?([0,2]) && !square_attacked?([0,2],white_attack) && square_empty?([0,3]) && !square_attacked?([0,3],white_attack) return true end end end end end return false end def get_promotion(color) puts "Pawn Promotion!" puts "What piece do you wish to promote to?" puts "Q R B N" piece = gets.chomp.upcase while !["Q","R","B","N"].include?(piece) puts "Invalid choice" puts "Q R B N" end return create_piece(piece,color) end def create_piece(piece,color) case piece when "Q" return Queen.new(color,nil) when "R" return Rook.new(color,nil) when "B" return Bishop.new(color,nil) when "N" return Knight.new(color,nil) end end def legal_move?(color, start_pgn,end_pgn) a,b = pgn_to_xy(start_pgn) x,y = pgn_to_xy(end_pgn) if square_empty?([a,b]) return false end #grid[x][y] if grid[a][b].color == color && grid[a][b].moves.include?([x,y]) return true end return false end end end
true
f10ee9d5d6eba0069e586bfccd4c58777f99e27b
Ruby
mwunsch/redwood
/test/test_redwood.rb
UTF-8
6,218
2.828125
3
[ "MIT" ]
permissive
require 'helper' class TestRedwood < Test::Unit::TestCase describe 'Node' do test 'has a name' do node = Redwood::Node.new(:test) assert_equal :test, node.name end test 'can be a root element' do node = Redwood::Node.new assert node.root? end test 'add a child' do node = Redwood::Node.new assert node.children.empty? node.add_child(:child) assert_equal :child, node.children.first.name end test 'has children' do node = Redwood::Node.new node.add_child(:child) assert_equal 1, node.children.size end test 'lookup children by named key' do node = Redwood::Node.new child = node.add_child(:child) assert_equal child, node[:child] end test 'has siblings' do node = Redwood::Node.new child = node.add_child(:child) bro = node.add_child(:bro) sis = node.add_child(:sis) assert_equal 2, child.siblings.size assert child.siblings.include?(bro) assert child.siblings.include?(sis) assert !child.siblings.include?(child) end test 'is an only child' do parent_one = Redwood::Node.new parent_two = Redwood::Node.new parent_one.add_child(:one_child) parent_one.add_child(:one_bro) parent_two.add_child(:two_child) assert !parent_one.children.first.only_child? assert parent_two.children.first.only_child? end test 'has ancestors' do node = Redwood::Node.new(:parent) son = node.add_child(:son) daughter = node.add_child(:daughter) grandson = son.add_child(:grandson) greatgrandson = grandson.add_child(:greatgrandson) ancestors = greatgrandson.ancestors assert ancestors.include?(grandson) assert ancestors.include?(son) assert ancestors.include?(node) assert !ancestors.include?(greatgrandson) assert !ancestors.include?(daughter) end test 'has a root' do node = Redwood::Node.new(:parent) son = node.add_child(:son) grandson = son.add_child(:grandson) greatgrandson = grandson.add_child(:greatgrandson) assert_equal node, greatgrandson.root assert_equal node, node.root end test 'has descendants' do node = Redwood::Node.new(:parent) son = node.add_child(:son) daughter = node.add_child(:daughter) grandson = son.add_child(:grandson) granddaughter = daughter.add_child(:granddaughter) greatgrandson = grandson.add_child(:greatgrandson) descendants = node.descendants assert descendants.include?(son) assert descendants.include?(daughter) assert descendants.include?(grandson) assert descendants.include?(granddaughter) assert descendants.include?(greatgrandson) assert !descendants.include?(node) end test 'has a depth' do node = Redwood::Node.new(:parent) son = node.add_child(:son) daughter = node.add_child(:daughter) grandson = son.add_child(:grandson) greatgrandson = grandson.add_child(:greatgrandson) assert_equal 1, node.depth assert_equal daughter.depth, son.depth assert_equal 3, grandson.depth assert_equal 4, greatgrandson.depth end test 'has a height' do node = Redwood::Node.new(:parent) son = node.add_child(:son) daughter = node.add_child(:daughter) grandson = son.add_child(:grandson) greatgrandson = grandson.add_child(:greatgrandson) assert_equal greatgrandson.depth, node.height assert_equal 1, daughter.height assert_equal son.height, (node.height - 1) end test 'has a treeview' do node = Redwood::Node.new(:parent) dog = node.add_child(:dog) puppy = dog.add_child(:puppy) son = node.add_child(:son) daughter = node.add_child(:daughter) grandson = son.add_child(:grandson) assert_respond_to node, :view assert_equal String, node.view.class end test 'is a leaf node' do node = Redwood::Node.new(:parent) child = node.add_child(:child) assert !node.leaf? assert child.leaf? end test 'walks the tree' do node = Redwood::Node.new(:parent) dog = node.add_child(:dog) puppy = dog.add_child(:puppy) son = node.add_child(:son) daughter = node.add_child(:daughter) grandson = son.add_child(:grandson) counter = 0 node.walk {|n| counter += 1 } assert_equal 6, counter end test 'grafts a node' do node = Redwood::Node.new(:parent) dog = Redwood::Node.new(:dog) node.graft dog assert_equal node, dog.parent assert node.children.include?(dog) end test 'add a child with the << method' do node = Redwood::Node.new(:parent) dog = Redwood::Node.new(:dog) node << dog assert_equal node, dog.parent assert node.children.include?(dog) assert !dog.root? assert !node.leaf? end test 'has an optional arbitrary value' do node = Redwood::Node.new(:parent) node.value = "hello world" assert_equal "hello world", node.value end test 'unlinks a node from its parent' do node = Redwood::Node.new(:parent) dog = node.add_child :dog dog.unlink assert node.leaf? assert !node.children.include?(dog) assert dog.root? end test 'prunes its children' do node = Redwood::Node.new(:parent) dog = node.add_child :dog node.prune assert node.children.empty? assert node.leaf? assert !dog.parent end end describe 'FileNode' do test 'scan a directory' do dir = Redwood::FileNode.scandir assert_equal Dir.pwd, dir.name end test 'implements File methods on the Node' do dir = Redwood::FileNode.scandir assert dir.directory? end test 'has a full path' do dir = Redwood::FileNode.scandir('.') assert_equal File.expand_path('.'), dir.path end end end
true
b940a499dcc665c88490dd7543c34f401bd791cc
Ruby
dry-rb/dry-types
/lib/dry/types/constructor/function.rb
UTF-8
6,117
2.875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# frozen_string_literal: true require "concurrent/map" module Dry module Types class Constructor < Nominal # Function is used internally by Constructor types # # @api private class Function # Wrapper for unsafe coercion functions # # @api private class Safe < Function def call(input, &block) @fn.(input, &block) rescue ::NoMethodError, ::TypeError, ::ArgumentError => e CoercionError.handle(e, &block) end end # Coercion via a method call on a known object # # @api private class MethodCall < Function @cache = ::Concurrent::Map.new # Choose or build the base class # # @return [Function] def self.call_class(method, public, safe) @cache.fetch_or_store([method, public, safe]) do if public ::Class.new(PublicCall) do include PublicCall.call_interface(method, safe) define_method(:__to_s__) do "#<PublicCall for :#{method}>" end end elsif safe PrivateCall else PrivateSafeCall end end end # Coercion with a publicly accessible method call # # @api private class PublicCall < MethodCall @interfaces = ::Concurrent::Map.new # Choose or build the interface # # @return [::Module] def self.call_interface(method, safe) @interfaces.fetch_or_store([method, safe]) do ::Module.new do if safe module_eval(<<~RUBY, __FILE__, __LINE__ + 1) def call(input, &block) # def call(input, &block) @target.#{method}(input, &block) # @target.coerve(input, &block) end # end RUBY else module_eval(<<~RUBY, __FILE__, __LINE__ + 1) def call(input, &block) # def call(input, &block) @target.#{method}(input) # @target.coerce(input) rescue ::NoMethodError, ::TypeError, ::ArgumentError => error # rescue ::NoMethodError, ::TypeError, ::ArgumentError => error CoercionError.handle(error, &block) # CoercionError.handle(error, &block) end # end RUBY end end end end end # Coercion via a private method call # # @api private class PrivateCall < MethodCall def call(input, &block) @target.send(@name, input, &block) end end # Coercion via an unsafe private method call # # @api private class PrivateSafeCall < PrivateCall def call(input, &block) @target.send(@name, input) rescue ::NoMethodError, ::TypeError, ::ArgumentError => e CoercionError.handle(e, &block) end end # @api private # # @return [MethodCall] def self.[](fn, safe) public = fn.receiver.respond_to?(fn.name) MethodCall.call_class(fn.name, public, safe).new(fn) end attr_reader :target, :name def initialize(fn) super @target = fn.receiver @name = fn.name end def to_ast [:method, target, name] end end class Wrapper < Function # @return [Object] def call(input, type, &block) @fn.(input, type, &block) rescue ::NoMethodError, ::TypeError, ::ArgumentError => e CoercionError.handle(e, &block) end alias_method :[], :call def arity 2 end end # Choose or build specialized invokation code for a callable # # @param [#call] fn # @return [Function] def self.[](fn) raise ::ArgumentError, "Missing constructor block" if fn.nil? if fn.is_a?(Function) fn elsif fn.respond_to?(:arity) && fn.arity.equal?(2) Wrapper.new(fn) elsif fn.is_a?(::Method) MethodCall[fn, yields_block?(fn)] elsif yields_block?(fn) new(fn) else Safe.new(fn) end end # @return [Boolean] def self.yields_block?(fn) *, (last_arg,) = if fn.respond_to?(:parameters) fn.parameters else fn.method(:call).parameters end last_arg.equal?(:block) end include ::Dry::Equalizer(:fn, immutable: true) attr_reader :fn def initialize(fn) @fn = fn end # @return [Object] def call(input, &block) @fn.(input, &block) end alias_method :[], :call # @return [Integer] def arity 1 end def wrapper? arity.equal?(2) end # @return [Array] def to_ast if fn.is_a?(::Proc) [:id, FnContainer.register(fn)] else [:callable, fn] end end # @return [Function] def >>(other) f = Function[other] Function[-> x, &b { f.(self.(x, &b), &b) }] end # @return [Function] def <<(other) f = Function[other] Function[-> x, &b { self.(f.(x, &b), &b) }] end end end end end
true
509b808bf217c9d7b609959e7d87279824f34f30
Ruby
davgit/samson
/app/models/terminal_executor.rb
UTF-8
1,177
2.921875
3
[ "Apache-2.0" ]
permissive
require 'pty' require 'shellwords' # Executes commands in a fake terminal. The output will be streamed to a # specified IO-like object. # # Example: # # output = StringIO.new # terminal = TerminalExecutor.new(output) # terminal.execute!("echo hello", "echo world") # # output.string #=> "hello\r\nworld\r\n" # class TerminalExecutor attr_reader :pid, :pgid, :output def initialize(output, verbose: false) @output = output @verbose = verbose end def execute!(*commands) commands.map! { |c| "echo » #{c.shellescape}\n#{c}" } if @verbose commands.unshift("set -e") execute_command!(commands.join("\n")) end def stop!(signal) system('kill', "-#{signal}", "-#{pgid}") if pgid end private def execute_command!(command) output, input, @pid = Bundler.with_clean_env do PTY.spawn(command, in: '/dev/null') end @pgid = begin Process.getpgid(pid) rescue Errno::ESRCH nil end begin output.each(56) {|line| @output.write(line) } rescue Errno::EIO # The IO has been closed. end _, status = Process.wait2(pid) input.close return status.success? end end
true
68b02af1983a58eee3875d27bb878950e574ba0f
Ruby
FreddieBoi/Warbands
/app/models/member.rb
UTF-8
1,722
2.734375
3
[]
no_license
# == Schema Information # Schema version: 20110603071110 # # Table name: members # # id :integer not null, primary key # name :string(255) not null # level :integer default(0), not null # experience :integer default(0), not null # health :integer default(100), not null # max_health :integer default(100), not null # combat_value :integer default(0), not null # warband_id :integer # created_at :datetime # updated_at :datetime # class Member < ActiveRecord::Base belongs_to :warband has_many :items validates :name, :presence => true, :length => { :within => 2..20 } after_create :create_starting_items before_save :format_health, :update_xp # Search for Members matching the name of the specified search term def self.search(search) if search where("LOWER (name) LIKE ?", "%#{search.downcase}%") else scoped # Empty scope, like calling 'all' but not performing the query end end def calc_combat_value value = combat_value items.each do |item| value += item.combat_value end value end def equip_if_better?(item) items.each do |i| if item.combat_value > i.combat_value i.destroy item.member = self item.save! return true end end return false end private def create_starting_items t = warband.world.starting_items.sample i = Item.create(:item_template => t, :member => self) end def format_health if self.health < 0 self.health = 0 end end def update_xp while self.experience >= self.max_experience*self.level do self.level += 1 end end end
true
7caac7064e3d3be99f07bb3cc67193fd23bf0185
Ruby
iseitz/Account-validator-Ruby
/lib/user_account_validator.rb
UTF-8
1,068
3.21875
3
[]
no_license
require_relative 'invalid_username' require_relative 'invalid_email' class UserAccountValidator attr_reader :name, :username, :email, :user_hash attr_accessor :errors def initialize ( user_hash ) @user_hash = user_hash @name = user_hash[:name] if !username_invalid? @username = user_hash[:username] else if !email_invalid? @email = user_hash[:email] username_error else email_error username_error end end end # in theory you can also append all the errors (InvalidEmail.new('Invalid email') and InvalidUserName.new('Invalide user name')) # to the array @errors = [ ] and then raise them one by one @errors.each {|error| raise error} def username_invalid? @user_hash[:username].nil? || @user_hash[:username].empty? end def username_error raise InvalidUserName.new('Invalid user name') end def email_invalid? @user_hash[:email].nil? || !@user_hash[:email].include?("@") end def email_error raise InvalidEmail.new('Invalid email') end end
true
91ca0315a2eda563412a0274a1ff9ad2e0bc8c86
Ruby
yantene/rutty
/app/executors/executor_environment/base.rb
UTF-8
1,307
2.71875
3
[]
no_license
module ExecutorEnvironment # ExecutorEnvironment::* がメソッドの共通化のためのモジュール。 # extend して利用する。 module Base # 対応する言語の Docker イメージの id を Redis に格納する際の key # @return [String] key def redis_key %W[ executor_environment #{self::LANGUAGE} #{self::VERSION} image_id ].join("/") end # 対応する言語の Docker イメージの id を Redis から取得する。 # @return [String] Docker イメージの id def image_id Redis.current.get(redis_key).tap do |id| raise "Image not found: #{self}" if id.nil? end end # 対応する言語の Docker イメージの id を Redis に格納する。 # @param [String] id Docker イメージの id def image_id=(id) Redis.current.set(redis_key, id) end # 対応する言語の Docker イメージをビルドし、 # self.image_id にイメージの id を格納する。 # @return [Docker::Image] ビルド後のイメージ def build_image Docker::Image.build_from_dir( self::DOCKERFILE_DIR, buildargs: self::DOCKERFILE_ARGS.to_json, ).tap do |image| self.image_id = image.id end end end end
true
de58fe9ae7f47c77c02ee277d682d41809a4ee63
Ruby
ljwhite/neos
/near_earth_objects_test.rb
UTF-8
1,101
2.65625
3
[]
no_license
require 'minitest/autorun' require 'minitest/pride' require 'pry' require_relative 'near_earth_objects' class NearEarthObjectsTest < Minitest::Test def test_a_date_returns_a_list_of_neos results = NearEarthObjects.call('2019-03-30') assert_equal '(2019 GD4)', results[:astroid_list][0][:name] end def test_api_connection date = "2019-03-30" results = NASAReader.conn(date) assert_equal String, results.class end def test_ability_to_parse_data date = "2019-03-30" results = NearEarthObjects.call(date) assert_equal Hash, results.class assert_equal [:astroid_list, :biggest_astroid, :total_number_of_astroids], results.keys end def test_data_parser_call date = "2019-03-30" response = NASAReader.conn(date) results = DataParser.new(response, date).call assert_equal [:astroid_list, :biggest_astroid, :total_number_of_astroids], results.keys assert_equal Array, results[:astroid_list].class assert_equal Integer, results[:biggest_astroid].class assert_equal Integer, results[:total_number_of_astroids].class end end
true
4a20b2372978eef1c247be9731b188282b216154
Ruby
haruboh/my_send_mail
/app/main.rb
UTF-8
1,874
2.65625
3
[]
no_license
# coding:utf-8 # 相対パスでrequireするために$LOAD_PATHにパスを追加 $LOAD_PATH << File.dirname(__FILE__) require 'yaml' require 'socket' require 'mail' class Send_mail def initialize config = YAML.load_file(CONFIG) @host = Socket.gethostname @dir = config["dir"] @count = config["file_count"].to_i @mail_charset = config["mail"]["charset"] @send_mail = Hash.new @delivary = Hash.new @send_mail[:from] = config["mail"]["from"] @send_mail[:to] = config["mail"]["to"] @send_mail[:subject] = config["mail"]["subject"] @delivary[:address] = config["send_param"]["address"] @delivary[:port] = config["send_param"]["port"].to_i @delivary[:domain] = config["send_param"]["domain"] @delivary[:authentication] = config["send_param"]["authentication"] Dir.chdir(@dir) end def make_and_send_mail mail = Mail.new mail.delivery_method( :smtp, address: @delivary[:address], port: @delivary[:port], domain: @delivary[:domain], authentication: @delivary[:authentication] ) mail.charset = @mail_charset mail.from = @send_mail[:from] mail.subject = @send_mail[:subject] tmp_body = "" tmp_body << "監視ディレクトリ内のファイル数が[#{@count}]を超えました。\n" tmp_body << "発生ホスト => #{@host}\n" tmp_body << "発生ディレクトリ => #{@dir}\n" tmp_body << "このメールは送信専用です。返信はできません。\n" mail.body = "#{tmp_body}" @send_mail[:to].each do |ma| mail.to = ma mail.deliver end end def run if @count < Dir.glob("*").count make_and_send_mail() end end def test make_and_send_mail() end end CONFIG = 'config/config.yml' unless ARGV[0] == "test" Send_mail.new().run else Send_mail.new().test end
true
ae29c91f5eec7fd88fa7a127086ad1f902631f63
Ruby
SBlines/tddblackjack
/deck.rb
UTF-8
1,062
3.46875
3
[]
no_license
# encoding: utf-8 class Deck < Array attr_accessor :cards SUITS = [:clubs, :diamonds, :hearts, :spades] def initialize super SUITS.each do |suit| ace = Card[:value => 11, :suit => suit, :card => "ace"] push(ace) (2..10).each do |n| card = Card[:value => n, :suit => suit, :card => n] push(card) end ["jack", "queen", "king"].each do |n| card = Card[:value => 10, :suit => suit, :card => n] push(card) end end self end class Card < Hash SYMBOLS = { :clubs => "♣", :diamonds => "♦", :hearts => "♥", :spades => "♠" } def soft_ace? self[:card] == 'ace' && self[:value] == 11 end def to_s suit = SYMBOLS[self[:suit]] if self[:card].kind_of?(String) "#{self[:card][0,1].upcase}#{suit} " else "#{self[:card]}#{suit} " end end def inspect to_s end end end
true
678a57b11328aceca06d2f71411b634266138359
Ruby
ChristopherBeltran/playlister-sinatra-v-000
/app/models/song.rb
UTF-8
567
2.703125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song < ActiveRecord::Base belongs_to :artist has_many :song_genres has_many :genres, through: :song_genres def slug title = self.name slug = title.downcase.strip.gsub(' ', '-').gsub(/[^\w-]/, '') slug end def self.find_by_slug(slug) unslug = slug.gsub('-', ' ').gsub(/\S+/, &:capitalize) #unslug = un.slice(0, un.index('(')) Song.all.each do |art| y = art.name x = y.tr('()', '') w = x.tr('.,&','').gsub(/\S+/, &:capitalize) if w == unslug return art end end end end
true
29d2ed2a1893b7fbdeffde598b71cec2fdf05884
Ruby
jacobhamblin/minesweeper
/minesweeper.rb
UTF-8
1,638
4
4
[]
no_license
##TODO ##1. victory? -done ##2. defeat? -done ##3. show a lot if zero -done ##4. identify flag input ##5. make input easier require_relative "board" require_relative "cell" class Minesweeper def initialize puts "\n\n\nWelcome to Minesweeper!" run end def reset puts 'Play again? y/n' input = gets.chomp case input when "y" run else puts "Thanks for playing!" exit end end def run puts "\nInput a number for the desired width of the board." width = get_number puts "Input the desired height for the board!" height = get_number puts "Then, tell us how many mines you want to populate the board." mines = get_number @session = Board.new(mines, width, height) while true if @session.victory? puts "\n" @session.display puts "\nYou've won!" reset end if @session.defeat? puts "\n" @session.reveal_mines @session.display puts "\nA mine!\n\nGame over." reset end @session.display puts "What is the X coordinate of your next move?" x_coord = get_number puts "What is the Y coordinate of your next move?" y_coord = get_number @session.sweep(x_coord-1, y_coord-1) end end def get_number while true input = gets.chomp case input when "exit" exit when /\d*/ if input.to_i == 0 puts "wrong answer >:[" break end return input.to_i else puts "Your input is invalid." end end end end Minesweeper.new
true
ecbda48f94afdd08d16c2bbf6eb452409b1bbc76
Ruby
radu-constantin/small-problems
/easy1/array_average.rb
UTF-8
245
3.3125
3
[]
no_license
def average (array) counter = 0 sum = 0 loop do sum += array[counter] counter += 1 break if counter == array.size end sum / array.size end puts average([1, 5, 87, 45, 8, 8]) == 25 puts average([9, 47, 23, 95, 16, 52]) == 40
true
c9ac5ed338c1c5507c84a1c84c832e7c1b62c57e
Ruby
AmyWeiner/happi_tails
/client.rb
UTF-8
335
3.578125
4
[]
no_license
# This file defines the Client class. A client object must have # a name, a number of children, an age, and a number of pets. class Client attr_reader :name, :num_children, :age, :num_pets def initialize(name, num_children, age, num_pets) @name = name @num_children = num_children @age = age @num_pets = num_pets end end
true
c9e98d589ea7cc76a0a769aec350d3227f4ebbad
Ruby
yoyohashao/enveomics
/Scripts/rbm.rb
UTF-8
4,431
2.78125
3
[ "Artistic-2.0" ]
permissive
#!/usr/bin/env ruby # # @author: Luis M. Rodriguez-R # @update: Aug-25-2015 # @license: artistic license 2.0 # require 'optparse' require 'tmpdir' o = {len:0, id:0, fract:0, score:0, q:false, bin:"", program:"blast+", thr:1, nucl:false} ARGV << "-h" if ARGV.size==0 OptionParser.new do |opts| opts.banner = " Finds the reciprocal best matches between two sets of sequences. Usage: #{$0} [options]" opts.separator "" opts.separator "Mandatory" opts.on("-1", "--seq1 FILE", "Path to the FastA file containing the set 1."){ |v| o[:seq1] = v } opts.on("-2", "--seq2 FILE", "Path to the FastA file containing the set 2."){ |v| o[:seq2] = v } opts.separator "" opts.separator "Search Options" opts.on("-n", "--nucl", "Sequences are assumed to be nucleotides (proteins by default)." ){ |v| o[:nucl] = true } opts.on("-l", "--len INT", "Minimum alignment length (in residues). By default: #{o[:len].to_s}." ){ |v| o[:len] = v.to_i } opts.on("-f", "--fract FLOAT", "Minimum alignment length (as a fraction of the query). If set, " + "requires BLAST+ (see -p). By default: #{o[:fract].to_s}." ){ |v| o[:fract] = v.to_i } opts.on("-i", "--id NUM", "Minimum alignment identity (in %). By default: #{o[:id].to_s}." ){ |v| o[:id] = v.to_f } opts.on("-s", "--score NUM", "Minimum alignment score (in bits). By default: #{o[:score].to_s}." ){ |v| o[:score] = v.to_f } opts.separator "" opts.separator "Software Options" opts.on("-b", "--bin DIR", "Path to the directory containing the binaries of the search program." ){ |v| o[:bin] = v } opts.on("-p", "--program STR", "Search program to be used. One of: blast+ (default), blast." ){ |v| o[:program] = v } opts.on("-t", "--threads INT", "Number of parallel threads to be used. By default: #{o[:thr]}." ){ |v| o[:thr] = v.to_i } opts.separator "" opts.separator "Other Options" opts.on("-q", "--quiet", "Run quietly (no STDERR output)"){ o[:q] = true } opts.on("-h", "--help", "Display this screen") do puts opts exit end opts.separator "" end.parse! abort "-1 is mandatory" if o[:seq1].nil? abort "-2 is mandatory" if o[:seq2].nil? abort "Argument -f/--fract requires -p blast+" if o[:fract]>0 and o[:program]!="blast+" o[:bin] = o[:bin]+"/" if o[:bin].size > 0 Dir.mktmpdir do |dir| $stderr.puts "Temporal directory: #{dir}." unless o[:q] # Create databases. $stderr.puts "Creating databases." unless o[:q] [:seq1, :seq2].each do |seq| case o[:program].downcase when "blast" `"#{o[:bin]}formatdb" -i "#{o[seq]}" -n "#{dir}/#{seq.to_s}" \ -p #{(o[:nucl]?"F":"T")}` when "blast+" `"#{o[:bin]}makeblastdb" -in "#{o[seq]}" -out "#{dir}/#{seq.to_s}" \ -dbtype #{(o[:nucl]?"nucl":"prot")}` else abort "Unsupported program: #{o[:program]}." end end # |seq| # Best-hits. rbh = {} n2 = 0 $stderr.puts " Running comparisons." unless o[:q] [2,1].each do |i| qry_seen = {} q = o[:"seq#{i}"] s = "#{dir}/seq#{i==1?2:1}" $stderr.puts " Query: #{q}." unless o[:q] case o[:program].downcase when "blast" `"#{o[:bin]}blastall" -p #{o[:nucl]?"blastn":"blastp"} -d "#{s}" \ -i "#{q}" -v 1 -b 1 -a #{o[:thr]} -m 8 -o "#{dir}/#{i}.tab"` when "blast+" `"#{o[:bin]}#{o[:nucl]?"blastn":"blastp"}" -db "#{s}" -query "#{q}" \ -max_target_seqs 1 -num_threads #{o[:thr]} -out "#{dir}/#{i}.tab" \ -outfmt "6 qseqid sseqid pident length mismatch gapopen qstart qend \ sstart send evalue bitscore qlen slen"` else abort "Unsupported program: #{o[:program]}." end fh = File.open("#{dir}/#{i}.tab", "r") n = 0 fh.each_line do |ln| ln.chomp! row = ln.split(/\t/) row[12] = "1" if o[:program]!="blast+" if qry_seen[ row[0] ].nil? and row[3].to_i >= o[:len] and row[2].to_f >= o[:id] and row[11].to_f >= o[:score] and row[3].to_f/row[12].to_i >= o[:fract] qry_seen[ row[0] ] = 1 n += 1 if i==2 rbh[ row[0] ] = row[1] else if !rbh[ row[1] ].nil? and rbh[ row[1] ]==row[0] puts ln n2 += 1 end end end end # |ln| fh.close() $stderr.puts " #{n} sequences with hit." unless o[:q] end # |i| $stderr.puts " #{n2} RBMs." unless o[:q] end # |dir|
true
fe23a146ea7251f49c86ef71240eb38b9d9e5c10
Ruby
CarmichaelLucas/rspec-basic
/spec/matchers/comparacao/comparacao_spec.rb
UTF-8
912
2.734375
3
[]
no_license
describe 'Matchers de Comparação' do it '#>' do expect(5).to be > 1 end it '#>=' do expect(5).to be >= 2 expect(5).to be >= 5 end it '#<' do expect(1).to be < 5 end it '#<=' do expect(1).to be <= 5 expect(1).to be <= 1 end it '#be_between inclusive' do expect(5).to be_between(2,7).inclusive expect(2).to be_between(2,7).inclusive expect(7).to be_between(2,7).inclusive end it '#be_between exclusive' do expect(5).to be_between(2,7).exclusive expect(3).to be_between(2,7).exclusive expect(6).to be_between(2,7).exclusive end it '#match' do expect('[email protected]').to match(/..@../) end it '#start_with' do expect('Fulano de Tal').to start_with('Fulano') expect([2,1,3]).to start_with(2) end it '#end_with' do expect('Fulano de Tal').to end_with('Tal') expect([2,3,1]).to end_with(1) end end
true
94e6ccd763d34f5a9203de6cb674e2f93c0aaf61
Ruby
Yuta123456/AtCoder
/Ruby/tmp1/クイズ.rb
UTF-8
73
2.984375
3
[]
no_license
q = gets.chomp.to_i if q == 1 puts "ABC" else puts "chokudai" end
true
3117cf06d862a96268b104b94be25d1c543f2fc5
Ruby
totosha16/Parser
/Old/get_raw.rb
UTF-8
299
2.796875
3
[]
no_license
input = File.open "input.csv", "r" while (line = input.gets) arr=line.strip.split(';') data={:url=>arr[0], :cssP=>arr[1], :xpathP=>arr[2], :cssD=>arr[3], :xpathD=>arr[4], :kP=>arr[5]} data.each do |k,v| data[k]=nil if data[k]=="" end puts data.inspect end input.close gets
true
691d619767d3379fbc8c0249515cbb038aee7ec0
Ruby
veronicacheung/kwk_2017
/Day_4/notes/oo.rb
UTF-8
2,165
3.515625
4
[]
no_license
# chloe = { # :username=>"chloe123" # :password=>"chloeiscool1" # :email=>"[email protected]" # :phone=>"555-555-5555" # :age=>13 # } # class User # attr_reader :username, :password # #this is always initialize # def initialize (username,password) # #the @ sign represents an instance variable # @username=username # @password=password # end # end # def username # @username # end # gianna=User.new("giannayan","fluff") # puts gianna.username class User attr_reader :password,name,email attr_writer :username attr_accessor:username,:password,:email,:age #this is always initialize. MAKE SURE YOU SPELL IT RIGHT def initialize(username, password) #the @ sign represents an instance variable @username=username @password=password end #read the username #reader # def username # @username # end #reader for password # def password # @password # end end #creates a new instance of a user gianna=User.new("giannayan", "fluff","[email protected]","123457") vivian=User.new("vivianp", "vivianiscool","[email protected]","456789") veronicac=User.new("veronicac", "password","[email protected]","23456789") ashlay=User.new("ashlay", "unicorn","[email protected]","098765432") #reading gianna's username puts ashlay.username puts ashlay.password # chloe = { # :username=>"chloe123" # :password=>"chloeiscool1" # :email=>"[email protected]" # :phone=>"555-555-5555" # :age=>13 # } class User # attr_reader :password, :email, :age # attr_writer :username attr_accessor :username, :password, :email, :age #this is always initialize. MAKE SURE YOU SPELL IT RIGHT def initialize(username, password, email, age) #the @ sign represents an instance variable @username=username @password=password @email=email @age=age end #read the username #reader # def username # @username # end #reader for password # def password # @password # end end #creates a new instance of a user gianna=User.new("giannayan", "fluff", "[email protected]", 65) #reading gianna's username puts gianna.username puts gianna.password puts gianna.email puts gianna.age
true
2fd4fc806ae977e94718cc751c6fcaf5f12fbbc4
Ruby
dlove24/yfs
/bin/yfs.rb
UTF-8
2,655
2.59375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env ruby ### Copyright (c) 2013 David Love <[email protected]> ### ### Permission to use, copy, modify, and/or distribute this software for ### any purpose with or without fee is hereby granted, provided that the ### above copyright notice and this permission notice appear in all copies. ### ### THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES ### WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF ### MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ### ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES ### WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ### ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF ### OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ### ### @author David Love ### ### YFS Parser Core. Parses the command line options, and passes control ### to the relevant library. ### # Add lib to load path $LOAD_PATH.unshift(File.expand_path(File.dirname(__FILE__) + '/../lib')) # Make sure we can find the libraries installed by Ruby Gems require "rubygems" # Add core and standard library requires require 'yaml' # Command line parser require 'trollop' # Known sub-commands require 'command/mount' require 'command/mount_all' ### ### Main Loop ### ## ## Set-up the command line parser, and parse the global and sub-command ## options ## # List of known sub-commands SUB_COMMANDS = %w(new-disk mount) # Set-up the global options, and tell Trollop to collect them from the # command line global_opts = Trollop::options do version "yfs 0.1.0 (c) 2013 David Love <[email protected]>" banner <<-EOS Uses the virtual disk facility of the FreeBSD operating systems to fake a virtal network filesystem. EOS stop_on SUB_COMMANDS end # Now work out what the sub-command was, parse both the sub-command # and its own options cmd = ARGV.shift cmd_opts = case cmd when "mount" Trollop::options do opt :all, "Attempt to mount all known sources" end when "new-disk" Trollop::options do opt :size, "Specify the size of the new source" end else Trollop::die "Unknown subcommand" end # Find and sanity check the configuration file, and then hand control over # to the relevant library CONFIGURATION_FILE = "/etc/yfs.conf" if !File.exists?(CONFIGURATION_FILE) then Trollop::die "Unable to read /etc/yfs.conf" exit end case cmd when "mount" if cmd_opts[:all] then Command.mount_all(CONFIGURATION_FILE) else Command.mount(ARGV) end end
true
1f6bfbe5125030cd3fe843c7a5284317420c4a2d
Ruby
xavierloos/codewars
/Ruby/spec/greater_than_spec.rb
UTF-8
747
3.34375
3
[]
no_license
require "greater_than" describe "greater_than" do it "should return a type of number" do expect(greater_than 5, [4,5,6,7]).to be_a_kind_of(Numeric) end it "should raise an error if the first argument is not a valid number or negative" do expect{greater_than "5", [4,5,6,7]}.to raise_error "Invalid number or negative" expect{greater_than 0, [4,5,6,7]}.to raise_error "Invalid number or negative" end it "should raise an error if the sec argument is not an array or empy" do expect{greater_than 5, []}.to raise_error "Invalid argument or empty" expect{greater_than 5, "[]"}.to raise_error "Invalid argument or empty" end it "should return 3" do expect(greater_than 5, [3,4,5,6,7,8]).to eq 3 end end
true
59a02db6ff908a92b3f51724afaf144d28ed05bb
Ruby
darkelv/lessons
/Lesson_3/station.rb
UTF-8
330
3.265625
3
[]
no_license
class Station attr_reader :trains, :station_name def initialize(station_name) @station_name = station_name @trains = [] end def accept_train(train) @trains << train end def send_train(train) trains.delete(train) end def show_trains(type) trains.select{|train| train.type == type} end end
true
02f7ee98348d6429eefdd318eae10453939084eb
Ruby
cybdoom/RoR-events_insider
/app/models/location.rb
UTF-8
2,198
2.734375
3
[]
no_license
# == Schema Information # # Table name: locations # # id :integer not null, primary key # original_address :string # geocoded_address :string # country_code :string(2) # region_code :string # subregion_code :string # city :string # street :string # street_number :string # postcode :string # latitude :float # longitude :float # created_at :datetime not null # updated_at :datetime not null # class Location < ActiveRecord::Base geocoded_by :original_address do |location, results| if geo = results.first logger.debug "geo = #{format_data(geo)}" end end reverse_geocoded_by :latitude, :longitude validates :country_code, length: {is: 2} after_validation :geocode, if: :should_geocode? scope :useful, lambda { where('city IS NOT NULL AND LENGTH(city) > 0 OR region_code IS NOT NULL AND LENGTH(region_code) > 0') } def self.build_from_geoip(result) data = result.data location = self.new location.country_code = data['country_code'] location.region_code = data['region_code'] location.city = data['city'] location.postcode = data['zipcode'] if location.city? location.latitude = data['latitude'] location.longitude = data['longitude'] end location end def coordinates? latitude? && longitude? end def address if original_address? original_address elsif geocoded_address? geocoded_address else address_from_parts end end def address_from_parts parts = [street_number, street, city, region_name] parts.select(&:present?).join(', ') end def useful? region? || city? || coordinates? end def country Country.new(country_code) end def country? country_code? end def usa? country_code == 'US' end def region region? ? country.states[region_code] : nil end def region_name region? ? region['name'] : '' end def region? country_code? && region_code? end private def should_geocode? address.present? && address_changed? end end
true