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
36c762969f07b7840956baa2761decdb621a8d4a
Ruby
snovity/konstructor
/spec/gem_conflicts/contracts_spec.rb
UTF-8
3,438
2.734375
3
[ "MIT" ]
permissive
require 'spec_helper' require_relative '../shared' describe "Konstructor with contracts.ruby" do before :all do require 'konstructor' end # Contracts seem not to work with any kind of class metaprogramming, # so have to define regular classes context "when contract is for method" do before :all do class TestContractsOne include Contracts::Core include Contracts::Builtin attr_reader :zero, :one, :two, :three def initialize @zero = 0 end konstructor def alpha(one, two) @one, @two = one, two end Contract Num => Bool def betta(three) @three = three true end end end let(:klass) { TestContractsOne } include_examples "one custom constructor" context "call contracted method" do let(:instance) { klass.alpha(111, 222) } subject { instance.betta(value) } context "with number" do let(:value) { 333 } specify do expect(subject).to eq true expect_instance_state nil, 111, 222, 333 end end context "with string" do let(:value) { 'not a number' } specify do expect_to_raise ParamContractError expect_instance_state nil, 111, 222, nil end end end end context "when contract is for konstructor after konstructor keyword" do before :all do class TestContractsTwo include Contracts::Core include Contracts::Builtin attr_reader :zero, :one, :two, :three def initialize @zero = 0 end konstructor def alpha(one, two) @one, @two = one, two end konstructor Contract Num => TestContractsTwo def betta(three) @three = three end end end let(:klass) { TestContractsTwo } include_examples "two custom constructors" context "call contracted method" do let(:instance) { klass.betta(value) } subject { instance } context "with number" do let(:value) { 333 } specify { expect_instance_state nil, nil, nil, 333 } end context "with string" do let(:value) { 'not a number' } specify do expect_to_raise ParamContractError end end end end context "when contract is for konstructor before konstructor keyword" do before :all do class TestContractsThree include Contracts::Core include Contracts::Builtin attr_reader :zero, :one, :two, :three def initialize @zero = 0 end konstructor def alpha(one, two) @one, @two = one, two end Contract Num => TestContractsThree konstructor def betta(three) @three = three end end end let(:klass) { TestContractsThree } include_examples "two custom constructors" context "call contracted method" do let(:instance) { klass.betta(value) } subject { instance } context "with number" do let(:value) { 333 } specify { expect_instance_state nil, nil, nil, 333 } end context "with string" do let(:value) { 'not a number' } specify do expect_to_raise ParamContractError end end end end end
true
bc0663015d1a58f1bb1ffe23c364d42b9d8fe1f4
Ruby
ahorner/advent-of-code
/lib/2019/13.rb
UTF-8
951
3.09375
3
[]
no_license
require_relative "./shared/intcode" TILES = [".", "|", "#", "_", "o"].freeze def render(tiles) screen = Hash.new(0) score = 0 tiles.each_slice(3) do |x, y, value| if x == -1 && y == 0 score = value else screen[[x, y]] = value end end [screen, score] end cabinet = Computer.new(INTCODE) screen, = render(cabinet.run) solve!("The total number of blocks is:", screen.values.count { |tile| tile == TILES.index("#") }) playable = INTCODE.dup playable[0] = 2 cabinet = Computer.new(playable) final_score = loop do ball, = screen.detect { |_coords, tile| tile == TILES.index("o") } paddle, = screen.detect { |_coords, tile| tile == TILES.index("_") } joystick = ball[0] <=> paddle[0] updates, score = render(cabinet.run(inputs: [joystick])) screen.merge!(updates) break score if screen.values.none? { |tile| tile == TILES.index("#") } end solve!("The score after breaking all blocks is:", final_score)
true
2923522cfc7bfb247e23f4ed0e0b13da0f404133
Ruby
andreybakanovsky/homeworks-2021
/HW04/aleksandr_serikov/lib/person.rb
UTF-8
383
3.0625
3
[]
no_license
# frozen_string_literal: true # Person class Person attr_reader :name, :surname, :notifications def initialize(name, surname) @name = name @surname = surname @notifications = [] end def add_notification(notification) notifications << notification end def mark_as_read! notifications.clear end def full_name "#{name} #{surname}" end end
true
d0205a63d7e9cf1d73baf2a8b56be868fa3db777
Ruby
zdennis/strac
/vendor/plugins/presentation_object/vendor/behaviors/test/tasks_test/test/user_test.rb
UTF-8
838
3.015625
3
[ "MIT" ]
permissive
require 'test/unit' here = File.expand_path(File.dirname(__FILE__)) require "#{here}/../../../lib/behaviors" require "#{here}/../lib/user" class UserTest < Test::Unit::TestCase extend Behaviors def setup @user = User.new('edith',18) end context 'when constructing' do should 'set name and age accessors' do assert_equal 'edith', @user.name assert_equal 18, @user.age end end context 'given a constructed instance' do should 'be an adult if age is 18' do assert @user.adult?, 'should be an adult' end end should 'allow name to be changed' do assert_equal 'edith', @user.name @user.name = 'bonnie' assert_equal 'bonnie', @user.name end should 'allow age to be changed' do assert_equal 18, @user.age @user.age = 30 assert_equal 30, @user.age end end
true
808a85892db391bc0957fc0c772ea53183ebbf85
Ruby
ccsalespro/ams_new
/app/algorithm/interchange_cost.rb
UTF-8
229
3.03125
3
[]
no_license
class InterchangeCost def initialize(inttableitems) @inttableitems = inttableitems end def calculate_cost @costs = 0 @inttableitems.each do |item| @costs += item.costs end @costs end end
true
c7fde18bdf8a6ebcc177c965f1483fc99fb4f772
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/raindrops/520c15c7e31c4309ac042d93612ab972.rb
UTF-8
360
3.625
4
[]
no_license
class Raindrops def initialize @str = "" end def Raindrops.convert num if divisible?(num, 3) @str << "Pling" elsif divisible?(num, 5) @str << "Plang" elsif divisible?(num, 7) @str << "Plong" else return num.to_s end return @str end def Raindrops.divisible?(num, i) num % i == 0 end end
true
cac77a9a9ac7e1798c62376c43f7ce9a5de7bdd3
Ruby
Jendnice/ruby-inheritance-lab-online-web-ft-090919
/bin/time_for_school
UTF-8
996
3.515625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#!/usr/bin/env ruby require_relative "../lib/user.rb" require_relative "../lib/teacher.rb" require_relative "../lib/student.rb" jim = User.new jim.first_name = "Jim" jim.last_name = "Johnson" steve = Student.new steve.first_name = "Steve" steve.last_name = "Jobs" nora = Student.new nora.first_name = "Nora" nora.last_name = "Jones" avi = Teacher.new avi.first_name = "Avi" avi.last_name = "Flombaum" some_knowledge = avi.teach more_knowledge = avi.teach different_knowledge = avi.teach steve.learn(some_knowledge) steve.learn(more_knowledge) nora.learn(more_knowledge) nora.learn(different_knowledge) puts "Steve just learned this important knowledge: '#{steve.knowledge.first}' from Avi" puts "And learned this: '#{steve.knowledge.last}' from Avi" puts "Nora just learned, '#{nora.knowledge.first} from Avi." puts "And Nora learned this: '#{nora.knowledge.last}'." steve.knowledge.each do |knowledge| puts knowledge end nora.knowledge.each do |knowledge| puts knowledge end
true
1d00b2599c06dbd14ad43474e47fd9154fe79e3f
Ruby
codyduval/dork
/spec/lib/dork_spec.rb
UTF-8
9,049
3.0625
3
[]
no_license
require "spec_helper" require "dork" module Dork describe Node do it "can add a child" do root = Node.new(:root) child = Node.new(:child) root.add(child) expect(root.children).to include(child) end it "can add a child via a block" do root = Node.new(:root) do Node.new(:child) end expect(root.children.count).to eq(1) child = root.children.first expect(child.parent).to eq(root) expect(root.children).to include(child) end it "can add a 2 siblings via a block" do root = Node.new(:root) do [Node.new(:first_child), Node.new(:second_child)] end expect(root.children.count).to eq(2) child = root.children.first child2 = root.children.last expect(child.parent).to eq(root) expect(child.name).to eq(:first_child) expect(child2.name).to eq(:second_child) end it "can add grandchildren via a block" do root = Node.new(:root) do Node.new(:child) do Node.new(:grandchild) end end grandchild = root.children.first.children.first expect(grandchild.name).to eq(:grandchild) end it "can chain calls to add children" do root = Node.new(:root) child = Node.new(:child) second_child = Node.new(:second_child) root.add(child).add(second_child) expect(root.children).to include(child, second_child) end it "can find a decendant by name" do root = Node.new(:root) do Node.new(:child) do Node.new(:grandchild) do Node.new(:greatgrandchild) end end end greatgrandchild = root.find(:greatgrandchild) expect(greatgrandchild.name).to eq(:greatgrandchild) end it "can find a decendant on another branch by name" do root = Node.new(:root) do Node.new(:child) do Node.new(:grandchild) do Node.new(:greatgrandchild) end end end sibling = Node.new(:sibling) sibling.add(Node.new(:grandsibling)) root.add(sibling) sibling_found = root.find(:sibling) expect(sibling_found).to eq(sibling) grandsibling = root.find(:grandsibling) expect(grandsibling.name).to eq(:grandsibling) end it "can return its immediate children" do root = Node.new(:root) child = Node.new(:child) grandchild = Node.new(:grandchild) child.add(grandchild) root.add(child) expect(root.children).to eq([child]) end it "can list all its descendants" do root = Node.new(:root) do Node.new(:child) do Node.new(:grandchild) end end sibling = Node.new(:sibling) root.add(sibling) expect(root.descendants.count).to eq(3) expect(root.descendants).to include(sibling) end it "can find the root" do root = Node.new(:root) child = Node.new(:child) grandchild = Node.new(:grandchild) child.add(grandchild) root.add(child) expect(grandchild.root).to eq(root) end it "knows who its parent is" do root = Node.new(:root) child = Node.new(:child) grandchild = Node.new(:grandchild) child.add(grandchild) root.add(child) expect(grandchild.parent).to eq(child) end it "can tell if it has a node" do root = Node.new(:root) child = Node.new(:child) grandchild = Node.new(:grandchild) child.add(grandchild) root.add(child) expect(child.has(:grandchild)).to be(true) end end describe World do it "can be an empty world" do world = World.new(:world) expect(world).to be_instance_of(World) end end describe Room do before(:each) do @world = World.new(:world) @kitchen = Room.new(:kitchen) @den = Room.new(:den) @world.add(@kitchen).add(@den) end it "can be a room called 'kitchen' in the world" do world = World.new(:world) do Room.new(:kitchen) end expect(world.children.last.name).to eq(:kitchen) end it "finds a script by a key" do script = Script.new(:unlock_door) script.script_keys = ["open door with key", "use key on door"] @den.add(script) script_text1 = script.script_keys.first script_text2 = script.script_keys.last expect(@den.has_script?(script_text1)).to eq(script) expect(@den.has_script?(script_text2)).to eq(script) end it "can have exits to other rooms" do @kitchen.exit_north = @den @den.exit_south = @kitchen expect(@kitchen.exit_north.name).to eq(:den) end end describe Item do it "can be an item called 'spoon' in kitchen " do world = World.new(:world) do Room.new(:kitchen) do Item.new(:spoon) end end spoon = world.children.last.children.last expect(spoon.name).to eq(:spoon) end it "cant be seen if it is in something closed" do box = Item.new(:box) box.open = false thing_in_box = Item.new(:hidden_thing) thing_in_box.visible = true box.add(thing_in_box) expect(thing_in_box.is_visible).to eq(false) end end describe Script do before(:each) do @player = Player.new(:cody) @room = Room.new(:den) @box = Item.new(:box) @key = Item.new(:key) @player.add(@key) @script = Script.new(:key_box) @room.add(@script).add(@player).add(@box) end it "can execute commands" do @script.conditions = [ "parent.name == :den", "root.player.has(:key)", "parent.has(:box)" ] expect(@script.conditions_met?).to be(true) end it "does something when successful" do @box.can_open = false @script.actions = ["root.find(:box).can_open = true"] @script.is_successful expect(@box.can_open).to be(true) end it "returns a message when it doesn't work" do end end describe Player do before(:each) do @player = Player.new(:cody) @world = World.new(:world) @room = Room.new(:kitchen) @item = Item.new(:spoon) @script = Script.new(:locked_box) end it "can be a player called 'cody' in kitchen " do @room.add(@player) @world.add(@room) expect(@room.children).to include(@player) end it "can move an item from kitchen to player" do @room.add(@player).add(@item) @world.add(@room) expect(@room.children).to include(@item) @player.get(:spoon) expect(@player.children).to include(@item) expect(@room.children).to_not include(@item) expect(@item.parent).to eq(@player) end it "can move a direction if room has that exit" do another_room = Room.new(:den) @room.exit_east = :den @room.add(@player) @world.add(@room) @world.add(another_room) @player.go("east") expect(@player.parent.name).to eq(:den) end it "cannnot move a direction if room does not has that exit" do another_room = Room.new(:den) @room.exit_east = :den @room.add(@player) @world.add(@room) @world.add(another_room) @player.go("west") expect(@player.parent.name).to eq(:kitchen) end it "can return its inventory" do @room.add(@player) @room.add(@item) @world.add(@room) @player.get(@item.name) expect(@player.inventory).to include(@item.description) end it "can take a two word string command" do @room.add(@player) @room.add(@item) @world.add(@room) @player.command("go north") expect(@player.parent).to equal(@room) end it "can execute a script with a command" do @script.script_keys = ["unlock box with key", "use key on box"] @room.add(@script).add(@player) @player.command("unlock box with key") end it "can pickup an item in the same room" do @item.can_take = true @room.add(@player) @room.add(@item) @world.add(@room) @player.pickup(@item.name) expect(@item.parent).to equal(@player) end it "can look and get a description of a room" do @room.add(@player) @room.add(@item) @world.add(@room) @room.description = "This is a room" expect(@player.look(@room.name)).to include("This is a room") end it "can't pickup an item it can't see" do @item.can_take = true closed_box = Item.new(:closed_box) closed_box.open = false @room.add(@player) closed_box.add(@item) @world.add(@room).add(closed_box) @player.pickup(@item.name) expect(@item.parent).to equal(closed_box) end it "doesnt break if it doesnt know command" do @room.add(@player) @room.add(@item) @world.add(@room) @player.command("blurb up") expect(@player.parent).to equal(@room) end end end
true
20c325bb027071e5e9112154313ac142c7a1ce39
Ruby
kopchak/OOP_Library
/order.rb
UTF-8
172
3.015625
3
[]
no_license
class Order attr_accessor :book, :reader, :date def initialize(book, reader) @book, @reader, @date = book, reader, Time.now.strftime("%H:%M:%S %d-%m-%Y") end end
true
b424daa6969bf6a982487beb0bd01b7d208d515f
Ruby
billbell73/phototo
/app/models/tag.rb
UTF-8
544
2.515625
3
[]
no_license
class Tag < ActiveRecord::Base has_and_belongs_to_many :photos validates :content, length: {minimum: 2} def self.create_tags_for!(tag_list, photo) tag_list.split(' ').each do |tag_content| slug = tag_content.gsub('#', '').downcase photo.tags << find_or_create_by!(content: tag_content, slug: slug) end end def tag_names '' end def to_param slug end # def tag_names=(tags_string, photo) # tags_string.split(' ').each do |tag| # photo.tags << self.create(content: tag) # end # end end
true
a860b19ec2bb3e0e79c424f2dd39c8345a8bd764
Ruby
RubyCamp/rc2018sp_g5
/practice15/Scene/senser/senser_all.rb
UTF-8
338
2.8125
3
[]
no_license
class Senser_all def initialize(board) @board = board end def draw data = @board.analog_read(0) #p data end def light_now_getter @board.analog_read(0) end def distance_value_getter #距離センサの値を読む @board.analog_read(4) #距離センサーはA3に挿す end end
true
89974a94e7eaee7945304655d7ca8a1a32d1c55f
Ruby
DouglasAllen/code-The_Book_of_Ruby
/code/ch08/method_call.rb
UTF-8
188
3.375
3
[]
no_license
# ch08 The Book of Ruby - http://www.sapphiresteel.com def nochange(x) x end num = 10 puts("num.object_id=#{num.object_id}") num = nochange(num) puts("num.object_id=#{num.object_id}")
true
c90366e3196969d69e81a1da318441d7a7edbbf0
Ruby
reedlaw/ruby-mmo
/players/jbttn.rb
UTF-8
1,316
3.1875
3
[]
no_license
module Jbttn def move if stats[:health] >= 100 && !am_i_leading? attack else [:rest] end end def to_s "Jbttn" end private def everyone Game.world[:players].select{ |p| p.alive } end def leaders everyone.sort!{ |a,b| a.stats[:experience] <=> b.stats[:experience] } everyone.take(5) end def opponents Game.world[:players].select{ |p| p != self && p.alive } end def attack weakling = weakest strongling = strongest random_dying = dying_opponents.shuffle.first if random_dying [:attack, random_dying] else [:attack, weakest] end end def weakest sorted = opponents.sort_by { |p| p.stats[:health] } sorted.first end def strongest opponents.max { |a,b| a.stats[:experience] <=> b.stats[:experience] } end def weaker_than?(opponent) stats[:health] < opponent.stats[:health] end def stronger_than?(opponent) stats[:health] > opponent.stats[:health] end def dying?(player) player.stats[:health] < 20 end def dying_opponents opponents.find_all { |p| dying?(p) } end def am_i_leading? in_lead = leaders in_lead.include?(self) end end
true
178a676f101594fb0fb0836476d7f82840bdcae9
Ruby
KajiMaster/personal
/deck_v01.rb
UTF-8
2,748
3.25
3
[]
no_license
class Card SUITS = %w(Spades Hearts Clubs Diamonds) RANKS = %W(A K Q J 10 9 8 7 6 5 4 3 2) attr_accessor :suit, :rank def initialize(id) self.suit = SUITS[id % 4] self.rank = RANKS[id % 13] end end class Deck attr_accessor :cards def initialize @cards = (0..51).to_a.shuffle.collect { |id| Card.new(id) } end def to_s "[#{@cards.join(", ")}]" end def draw(*num) @cards.pop(*num) end end # class Hand # attr_accessor :hands # # def initialize # self.hands = in_play[0..6] # # end # end # class Player # attr_accessor :hands # # def intialize(n) # self.hands = Array.new # n.times { self.hands << Deck.draw } # end # end d1 = Deck.new hand = # d1.cards.each { |card| in_play.push ("#{card.rank} of #{card.suit}") } d1.cards.each_with_index { |card, index| puts card } #player1 = Player.new hand = cards.draw(7) puts hand.join(", ") ## Displays each card one by one #d1.cards.select{ |num| puts "#{num.rank} of #{card.suit}" } #puts "#{cards.rank} of #{cards.suit}" ######################## ##### ######## ##### OUTPUT ######## ##### ######## ######################## #### #<Card:0x00000000b0db00> #### #<Card:0x00000000b0dad8> #### #<Card:0x00000000b0dab0> #### #<Card:0x00000000b0da88> #### #<Card:0x00000000b0da60> #### #<Card:0x00000000b0da38> #### #<Card:0x00000000b0da10> #### #<Card:0x00000000b0d9e8> #### #<Card:0x00000000b0d9c0> #### #<Card:0x00000000b0d998> #### #<Card:0x00000000b0d970> #### #<Card:0x00000000b0d948> #### #<Card:0x00000000b0d920> #### #<Card:0x00000000b0d8f8> #### #<Card:0x00000000b0d8d0> #### #<Card:0x00000000b0d8a8> #### #<Card:0x00000000b0d880> #### #<Card:0x00000000b0d858> #### #<Card:0x00000000b0d830> #### #<Card:0x00000000b0d808> #### #<Card:0x00000000b0d7e0> #### #<Card:0x00000000b0d7b8> #### #<Card:0x00000000b0d790> #### #<Card:0x00000000b0d768> #### #<Card:0x00000000b0d740> #### #<Card:0x00000000b0d718> #### #<Card:0x00000000b0d6f0> #### #<Card:0x00000000b0d6c8> #### #<Card:0x00000000b0d6a0> #### #<Card:0x00000000b0d678> #### #<Card:0x00000000b0d650> #### #<Card:0x00000000b0d628> #### #<Card:0x00000000b0d600> #### #<Card:0x00000000b0d5d8> #### #<Card:0x00000000b0d5b0> #### #<Card:0x00000000b0d588> #### #<Card:0x00000000b0d560> #### #<Card:0x00000000b0d538> #### #<Card:0x00000000b0d510> #### #<Card:0x00000000b0d4e8> #### #<Card:0x00000000b0d4c0> #### #<Card:0x00000000b0d498> #### #<Card:0x00000000b0d470> #### #<Card:0x00000000b0d448> #### #<Card:0x00000000b0d420> #### #<Card:0x00000000b0d3f8> #### #<Card:0x00000000b0d3d0> #### #<Card:0x00000000b0d3a8> #### #<Card:0x00000000b0d380> #### #<Card:0x00000000b0d358> #### #<Card:0x00000000b0d330> #### #<Card:0x00000000b0d308>
true
8f19446a46ff63ebefe3db107c581e0f5ea41f24
Ruby
DanielDo92/houzie
/app/models/bills/parking.rb
UTF-8
221
2.546875
3
[]
no_license
module Bills class Parking < Base PRICE_PER_VEHICLE = 100_000 def unit_count room.vehicle_count end def calculate_total self.total_price = unit_count * PRICE_PER_VEHICLE end end end
true
a49f4278865ca884ad3a9d13edb5146e78c471ae
Ruby
osmszk/dla_team14
/devide_test_train.rb
UTF-8
1,092
2.765625
3
[]
no_license
require 'fileutils' #ももくろに戻すときはtrue is_momokuro = false talents = is_momokuro ? ['kanako','shiori','ayaka','momoka','reni'] : ['takemoto','taniai','suzuki'] ext = is_momokuro ? 'jpg' : 'png' train_image_dir = './data/train/' test_image_dir = './data/test/' #以下、学習データとテストデータにわける RATIO_TRAIN_DATA = 0.7 talents.each do |dir| FileUtils.mkdir_p(train_image_dir+dir) unless FileTest.exist?(train_image_dir+dir) FileUtils.mkdir_p(test_image_dir+dir) unless FileTest.exist?(test_image_dir+dir) sum = Dir.glob("./image_momo/cropped_images_#{dir}/*.#{ext}").count puts "sum of #{dir}:#{sum.to_s}" Dir.glob("./image_momo/cropped_images_#{dir}/*.#{ext}").each_with_index do |src, index| percent = index.to_f/sum.to_f if percent < RATIO_TRAIN_DATA FileUtils.cp(src, train_image_dir+dir+"/") else FileUtils.cp(src, test_image_dir+dir+"/") end end puts "train:" puts Dir.glob("./#{train_image_dir+dir}/*.#{ext}").count puts "test:" puts Dir.glob("./#{test_image_dir+dir}/*.#{ext}").count end
true
375c1112a5da073753f84bf19e42099c141e4ad4
Ruby
elDante/eoat
/lib/eoat/cache/memcached_cache.rb
UTF-8
2,460
2.625
3
[ "MIT" ]
permissive
module EOAT module Cache # Memcached cache handler. Used `gem memcache` # Default use standard connection parameters. # @author Ivan Kotov {mailto:i.s.kotov.ws e-mail} # @example Set Memcached as a cache storage, with default Memcached `address` and `port` # EOAT.cache = EOAT::Cache::MemcachedCache.new # @example Set Redis as a cache storage, with connect to custom server:port and not set key prefix # EOAT.cache = EOAT::Cache::MemcachedCache.new('10.0.1.1:11212', '') class MemcachedCache require 'yaml' # @param [String] server the connection string `<ip-address>:<port>` # @param [String] prefix the prefix for keys def initialize(server='localhost:11211', prefix='eoat') require 'memcache' @backend = Memcache.new(:server => server, :namespace => prefix, :segment_large_values => true) end # Get object from cache # @param [String] host the request host string # @param [String] uri the query string # @return [Object, NilClass] the instance of result class # or nil if key not does not exist def get(host, uri) # Set key as md5 string key = EOAT::Cache.md5hash(host + uri) response = @backend.get(key) if response if EOAT::Cache.md5hash(response) == @backend.get(key + '_hash') return YAML::load(response) else @backend.delete(key) @backend.delete(key + '_hash') end end false end # Save instance of result class. # @param [String] host the request host string # @param [String] uri the query string # @param [Object] content the result class instance def save(host, uri, content) # Calculate TTL in seconds expire = (content.cached_until - content.request_time).to_i # If TTL > EOAT.max_ttl set EOAT.max_tt as expire expire = expire > EOAT.max_ttl ? EOAT.max_ttl : expire # If 0 or a negative value, it does not save. if expire > 0 # Set key as md5 string key = EOAT::Cache.md5hash(host + uri) yaml = content.to_yaml @backend.set( key, yaml, :expiry => expire ) @backend.set( key + '_hash', EOAT::Cache.md5hash(yaml), :expiry => expire ) end end end end end
true
fb7fc70c841eee6922a9cd8f40e3578c1283a267
Ruby
rokoroku/partyrecruit
/app/helpers/parties_helper.rb
UTF-8
448
2.59375
3
[]
no_license
# coding: UTF-8 module PartiesHelper def category_list ['취미', '운동', '식사', '스터디', '공연', '영화', '봉사', '기타'] end def print_remaining_time(ended_at) unless ended_at.nil? remaining = (ended_at - Time.now)/60 + 0.5 if remaining >= 60 (remaining/60).to_i.to_s << "시간 " << (remaining%60).to_i.to_s << "분" else remaining.to_i.to_s << "분" end end end end
true
b7984b407bd7f359c2fc02bffe622acda9dfc337
Ruby
christaylor19/citylines
/api/test/unit/models/lines.rb
UTF-8
2,524
2.515625
3
[ "MIT" ]
permissive
require File.expand_path '../../../test_config', __FILE__ describe Line do before do @city = City.new(name: 'Some city', start_year: 2017, url_name: 'city', country: 'Argentina') @city.coords = Sequel.lit("ST_GeomFromText('POINT(-71.064544 42.28787)',4326)") @city.save @system = System.create(city_id: @city.id) @line = Line.create(city_id: @city.id, system_id: @system.id, name: 'Test line', url_name: 'test-line', color: '#e6e6e6') end it "should set the right url_name" do assert_equal 'test-line', @line.url_name @line.name = " A New Name / Blah " @line.save @line.generate_url_name assert_equal "#{@line.id}-a-new-name---blah", @line.url_name end it "should return the right values" do assert_equal "#e6e6e6", @line.color end it "should backup the line properly" do assert_equal 0, LineBackup.count @line.backup! assert_equal 1, LineBackup.count backup = LineBackup.first assert_equal @line.id, backup.original_id assert_equal @line.city_id, backup.city_id assert_equal @line.name, backup.name assert_equal @line.url_name, backup.url_name assert_equal @line.color, backup.color assert_equal @line.system_id, backup.system_id end describe "add/remove to/from features" do before do @feature = Section.create(city_id: @city.id) end it "should be added to the feature" do assert 0, @feature.lines.count @line.add_to_feature(@feature) assert 1, @feature.lines.count assert @line, @feature.lines.first end it "should be removed from the feature" do @line.add_to_feature(@feature) assert 1, @feature.lines.count @line.remove_from_feature(@feature) assert 0, @feature.lines.count end end describe "transport modes" do it "should return the right transport mode info" do line = Line.create(city_id: @city.id, name: 'Test', transport_mode_id: 4) assert_equal TransportMode[4], line.transport_mode assert_equal TransportMode[4].width, line.width assert_equal TransportMode[4].min_width, line.min_width end it "should return the default transport mode if it's not set" do line = Line.create(city_id: @city.id, name: 'Test') assert_equal TransportMode[0], line.transport_mode assert_equal TransportMode[0].width, line.width assert_equal TransportMode[0].min_width, line.min_width end end end
true
fa9eb9ec9d86fcccf7a23a01b47e79e6128f947d
Ruby
cajun/resume
/lib/resume.rb
UTF-8
5,027
3.03125
3
[ "MIT" ]
permissive
require 'rubygems' require 'facets/ansicode' module Resume def self.included(base) base.extend(ANSICode) base.extend(ClassMethods) (base.methods - Object.methods).each do |method| base.send(method, Array.new) if method =~ /=$/ end base.contact_info = Hash.new base.width = 80 # default width end module ClassMethods attr_accessor :contact_info, :schools, :jobs, :applications, :technologies, :practices, :width, :story_text def my_name self.to_s.gsub(/([A-Z]+)([A-Z][a-z])/,'\1 \2').gsub(/([a-z\d])([A-Z])/,'\1 \2') end def contact(opts = {}) if(email = opts[:email]) self.contact_info[:email] = email.is_a?(Array) ? email.to_email : (raise Exception.new('Please use an array to define your email address')) end if(phone = opts[:phone]) self.contact_info[:phone] = phone.is_a?(Array) ? phone.to_phone : (raise Exception.new('Please use an array to define your phone number')) end end def story(story) self.story_text = story.join(" ") end # attended "XYZU", :in => "Basket Weaving", :with => "PHD", :graduated => "1999" def attended(school, opts = {}) self.schools << {:name => school, :curriculum => opts[:in], :degree => opts[:with], :graduated => opts[:graduated]} end # worked :at => "Acme, Inc.", :description => "bored out of skull", :position => "Monkey", :tenure => 2008 def worked(opts = {}) self.jobs << {:company => opts[:at], :project => opts[:project], :description => opts[:description], :position => opts[:position], :tenure => opts[:tenure]} end {"built" => "applications", "using" => "technologies", "practicing" => "practices"}.each do |name, accessor| class_eval <<-EOV def #{name}(args) self.#{accessor} = self.#{accessor} + (args.is_a?(Array) ? args : [args]) end EOV end def line(width = @width) "-".center(width, "-") end def pretty_print(out = $>, width = @width) print(my_name, out, width, :center) print_contact(out, width) print(line, out, width) print(line, out, width) if print_schools(out, width) print(line, out, width) if print_jobs(out, width) print(line, out, width) if print_array(applications, "Sites", out, width) print(line, out, width) if print_array(technologies, "Technologies", out, width) print(line, out, width) if print_array(practices, "Practices", out, width) print(story_text, out, width) out << "\n" end def has_contact_info? !contact_info[:email].nil? or !contact_info[:phone].nil? end def has_story? self.story_text and !self.story_text.empty? end %w(schools jobs applications technologies practices story_).each do |name| class_eval <<-EOV def has_#{name}? self.#{name} and !self.#{name}.empty? end EOV end def print_contact(out = "", width = @width) row = "" row << contact_info[:email] if contact_info[:email] row << " " if contact_info[:email] and contact_info[:phone] row << contact_info[:phone] if contact_info[:phone] print(row, out, width, :center) end def print_schools(out = "", width = @width) schools.collect { |s| row = "" row << "Attended #{s[:name]}" if s[:name] row << " #{s[:curriculum]}" if s[:curriculum] row << " for #{s[:degree]}" if s[:degree] row << "; Graduated #{s[:graduated]}" if s[:graduated] print(row, out, width, :right) }.join("\n") end def print_jobs(out = "", width = @width) jobs.collect { |j| row = "" row << "Worked at #{j[:company]}" if j[:company] row << " as a #{j[:position]}" if j[:position] row << " (#{j[:tenure]})" if j[:tenure] row << "\n On #{j[:project]}" if j[:project] result = print(row, out, width, :right) result += "\n " + print(j[:description], out, width) if j[:description] }.join("\n\n") end def print_array(array, title = "", out = "", width = @width) unless(array.empty?) print(title, out, width, :right) print(array.join(" - "), out, width) end end def print(str, out, width, justify = :left) if(str.length > width) i = str.rindex(' ', width) print(str[0, i], out, width, justify) + ' ' +print(str[i+1, str.length], out, width, justify) elsif(!str.empty?) line = str.justify(width, justify) out << "\n#{line}" line.strip end end end end class String def justify(width, justify) case justify when :center: center(width) when :left: ljust(width) when :right: rjust(width) end end end class Array def to_email "#{self.first}@#{self[1,size].join('.')}" end def to_phone(delimiter = ".") self.join(delimiter) end end
true
161c65c82e7b65ecc37f2f38c919e4938813db6a
Ruby
Manfred/Four
/test/support/collector.rb
UTF-8
309
3.34375
3
[ "MIT" ]
permissive
class Collector attr_accessor :_written def initialize self._written = [] end def puts(*args) args.each { |line| write(line.end_with?("\n") ? line : line + "\n") } end def write(*args) self._written << args end def flush # noop end def to_s _written.join end end
true
e2b41fe69edfa49530da85d59507184d482952aa
Ruby
Bw00d/ruby_tic_tac_toe
/spec/tic_tac_toe_spec.rb
UTF-8
2,772
3.28125
3
[]
no_license
require 'space' require 'board' require 'player' require 'game' require 'rspec' describe Space do describe '#initialize' do it 'initializes a new instance of Space' do test_space = Space.new(0, 0) test_space.should be_an_instance_of Space end end describe '#mark_by' do it 'lets a player mark a space' do test_space = Space.new(1,2) test_player = Player.new('X') test_space.mark_by(test_player) test_space.marked_by.should eq test_player end end end describe Board do describe '#initialize' do it 'initializes a new instance of Board' do test_board = Board.new test_board.should be_an_instance_of Board end it 'creates 9 instances of Space' do test_board = Board.new test_board.spaces.count.should eq 9 end it 'has each Space hold the proper coordintates' do test_board = Board.new test_board.spaces[8].x_coordinate.should eq 2 test_board.spaces[8].y_coordinate.should eq 2 end end describe '#row' do it 'returns an array of Spaces corresponding to the certain row' do test_board = Board.new test_board.row(0).count.should eq 3 end end describe '#column' do it 'returns an array of Spaces corresponding to the certain column' do test_board = Board.new test_board.column(0).count.should eq 3 end end describe '#check_win' do it 'returns false if a player does not have 3 in a row' do test_board = Board.new test_player = Player.new('X') test_board.check_win(test_player).should eq false end it 'returns true if a player has three in a row' do test_board = Board.new test_player = Player.new('X') test_board.spaces[0].mark_by(test_player) test_board.spaces[4].mark_by(test_player) test_board.spaces[8].mark_by(test_player) test_board.check_win(test_player).should eq true end end end describe Player do describe '#initialize' do it 'should initialize an instance of Player' do test_player = Player.new('X') test_player.should be_an_instance_of Player end it 'initializes player with a value' do test_player = Player.new('X') test_player.value.should eq 'X' end end end describe Game do describe '#initialize' do it 'initializes an instance of Game' do test_game = Game.new test_game.should be_an_instance_of Game end it 'should create a board' do test_game = Game.new test_game.board.should be_an_instance_of Board end it 'creates two players with the values of X and O' do test_game = Game.new test_game.player_one.value.should eq 'X' test_game.player_two.value.should eq 'O' end end end
true
e82150a2c6ea1f4f93fcbbbe5966d6881eacac35
Ruby
clio/slow_query_exporter
/lib/slow_query_exporter/query_parser.rb
UTF-8
484
2.609375
3
[ "MIT" ]
permissive
module SlowQueryExporter class QueryParser def initialize(logger) @buffer = "" @logger = logger @parsed = [] reset! end def reset! @query = SlowQuery.new end def parse_line(line) @query.parse_line(line) if @query.done? @parsed << @query @query = SlowQuery.new end rescue => e @logger.error(e.message) reset! end def pop_finished_query @parsed.pop end end end
true
74c990490fb6317f7d015d3e3e89ffbb61e3207a
Ruby
tommchenry/drem-tem-ruby-racer
/view.rb
UTF-8
522
3.53125
4
[]
no_license
require_relative 'game' require_relative 'car' require_relative 'reset_screen' class View def get_input gets.chomp end def race_starter puts "READY..." sleep 1 puts "SET..." sleep 1 puts "GO!" sleep 1 end def pretty_board(arr_of_cars, track_length) arr_of_cars.each do |car| track = Array.new(track_length, " |") track[car.position] = car.name print track.join + "\n" end end def end_game(winning_car) puts "#{winning_car.name} WINS!" end end
true
c5939633f06c49ac0914d9fee0f2c33f551d6733
Ruby
janewysoki/Page-Of-Reason
/app/models/book.rb
UTF-8
724
2.65625
3
[ "MIT" ]
permissive
class Book < ApplicationRecord belongs_to :author belongs_to :user has_many :reviews has_many :users, through: :reviews accepts_nested_attributes_for :author validates :title, presence: true validates :author, presence: true validate :no_duplicates scope :alphabetize, -> { order(:title) } def author_attributes=(attributes) self.author = Author.find_or_create_by(attributes) if !attributes['name'].empty? self.author end def no_duplicates book = Book.find_by(title: title, author_id: author_id) if !!book && book != self errors.add(:title, 'has already been added for that author') end end def title_and_author "#{title} - #{author.name}" end end
true
e15ad132f087a55dfd8c9e96619fe6f7917c73b9
Ruby
corneliusellen/http
/lib/game.rb
UTF-8
729
3.4375
3
[]
no_license
class Game attr_accessor :number_of_guesses, :user_guess, :high_or_low, :secret_number def initialize @secret_number = rand(0..5) @number_of_guesses = 0 @user_guess = nil @high_or_low = nil end def assign_user_guess(request) @number_of_guesses += 1 @user_guess = request.user_guess end def check_high_or_low if @user_guess < @secret_number @high_or_low = "was too low!" elsif @user_guess > @secret_number @high_or_low = "was too high!" elsif @user_guess == @secret_number @high_or_low = "is correct!!!" end end def guess_checker(request) assign_user_guess(request) check_high_or_low end end
true
9e4d63d688fb4cf5b3598097f1ff64e1bbba8d19
Ruby
Illianthe/ProjectEuler
/lib/utility.rb
UTF-8
608
3.859375
4
[]
no_license
module Utility # Checks if a number is prime via trial division def is_prime?(n) (2..Math.sqrt(n).floor).each do |i| return false if n % i == 0 end true end # Returns an array of all the proper divisors of n def proper_divisors(n) divisors = [] (1..Math.sqrt(n).floor).each do |i| if n % i == 0 divisors << i if (i > 1) and (n / i != i) divisors << n / i end end end divisors end def factorial(n) product = 1 1.upto(n) do |i| product *= i end product end end
true
3500a012bc14d6d3c9caa2435ff0883d094dc38d
Ruby
chestercun/common
/lib/utility/file_utility.rb
UTF-8
677
3.203125
3
[]
no_license
module FileUtility def cat_file(fn) line_arr(fn).each do |line| p line end end def line_arr(fn) # call private file = open(fn) # build line array tmp = [] file.each do |line| next if line =~ /\A\n\Z/ line.sub! /\n$/, '' tmp.push(line) end tmp end def file_to_a(fn) file = open(fn) tmp = [] file.each do |line| line.sub! /\n$/, '' values = line.split(/\s+/) tmp.push(values) end tmp end private def open(fn) begin file = File.new(fn,'r') # if File.exists?(fn) return file rescue => e p "#{e} Exception Caught." end end end
true
c9021694765e12da7c3c28d1a0fd6f0141a28e16
Ruby
MyReplayLive/schedule-scrape
/lib/schedule-scraper.rb
UTF-8
1,177
2.65625
3
[ "MIT" ]
permissive
require 'nibbler' require 'open-uri' require 'csv' require 'uri' require 'nokogiri' require "schedule-scraper/version" require "schedule-scraper/config" require "schedule-scraper/event" require "schedule-scraper/schedule" require "schedule-scraper/pointstreak/event" require "schedule-scraper/pointstreak/schedule" require "schedule-scraper/ezleagues/event" require "schedule-scraper/ezleagues/schedule" module ScheduleScraper def self.fetch(type_or_url, url = nil) type = url ? type_or_url : type_from_url(type_or_url) url = url || type_or_url raise UnsupportedSchedule unless supported_schedules.include?(type.to_sym) raise InvalidURL unless valid_url?(url) type_class(type).fetch(url) end def self.type_from_url(url) Config.types.each do |key, klass| return key if /#{key}/ =~ url end end def self.type_class(type) Config.types[type] end def self.supported_schedules Config.types.keys end def self.valid_url?(url) uri = URI.parse(url) uri.kind_of?(URI::HTTP) rescue URI::InvalidURIError false end class UnsupportedSchedule < StandardError; end class InvalidURL < StandardError; end end
true
e27439816387f641b1677b1f6e3f7e3944399076
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/rna-transcription/49019e2c4ee14f789ea0db69b3b6fac3.rb
UTF-8
301
2.9375
3
[]
no_license
class Complement RNA = { 'G' => 'C', 'C' => 'G', 'T' => 'A', 'A' => 'U' } DNA = { 'C' => 'G', 'G' => 'C', 'A' => 'T', 'U' => 'A' } def self.of_dna(dna) dna.each_char.inject('') { |a, e| a << RNA[e] } end def self.of_rna(rna) rna.each_char.inject('') { |a, e| a << DNA[e] } end end
true
0319c94700030fd44da001df02d75ca2afd5b610
Ruby
claudiobm/base_app
/lib/slugify.rb
UTF-8
809
2.703125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require "string_helper" module Slugify LIST_FIELD = [:name, :title] def slugify(word, unique = true) slug = "" slug = word.slugfy if unique i = 1 if self.id while self.class.where(['slug = ? AND id <> ?', slug, self.id]).count > 0 do slug = ("#{i}-#{slug}}") i = i + 1 end else while self.class.where(['slug = ?', slug]).count > 0 do slug = ("#{i}-#{slug}") i = i + 1 end end end slug end def create_slug unless @slugify.blank? self.slug = slugify(@slugify) else LIST_FIELD.each do |field| if(self.respond_to? field) self.slug = slugify(eval("self.#{field}.to_s.slugfy") ) if self.slug.blank? break end end end end end
true
af7df44aa93bdbb41eb6f47c389487177c3ce2f3
Ruby
dare1010/rl1
/4wk/1ea_dog.rb
UTF-8
529
4.03125
4
[]
no_license
# http://pastebin.com/tSzvcDC0 class Dog attr_reader :name, :tricks def method_missing(name, *args, &block) if @tricks.has_key?(name) puts "#{@tricks[name]}" else puts "I don't know such tricks. Teach me!" end end def initialize(name) @name = name @tricks = {} end def bark end def eat end def chase_chat end def teach_trick(trick, &block) @tricks[trick] = block.call end end d = Dog.new('Leo') d.teach_trick(:dance) do "#{d.name} is dancing!" end d.dance
true
f43778a94be53e6f629b4e85987b89c151a62483
Ruby
shawn42/free-radicals
/src/electron.rb
UTF-8
2,252
2.890625
3
[]
no_license
class ElectronView < ActorView def draw(target, x_off, y_off, z) target.draw_circle @actor.x,@actor.y, @actor.radius, [40,225,25,255], z target.draw_circle @actor.x,@actor.y, @actor.radius+3, [20,255,20,155], z end end class Electron < Actor has_behaviors :updatable, :audible, :layered => 2 attr_accessor :radius, :nucleus, :shell, :force def setup @nucleus = @opts[:nucleus] self.shell = @opts[:shell] @speed = 90 @radius = 3 @force = Ftor.new 0, 0 end def shell=(new_shell) @speed_deg = 90+rand(90) @shell = new_shell end def free(force) @force = Ftor.new(self.x-@nucleus.x, self.y-@nucleus.y) @force.m = force.m*0.1 @nucleus = nil @shell = nil play_sound :electron_freed end def update(time) if @nucleus.nil? dir_vec = @force * @speed * (time/1000.0) self.x += dir_vec.x self.y += dir_vec.y # hardcode the borders for now if self.x <= 0 play_sound :electron_freed @force *= 0.6 self.x = -self.x @force = Ftor.new(-@force.x,@force.y) elsif self.x >= 1024 play_sound :electron_freed @force *= 0.6 self.x -= self.x-1024 @force = Ftor.new(-@force.x,@force.y) elsif self.y <= 0 play_sound :electron_freed @force *= 0.6 self.y = -self.y @force = Ftor.new(@force.x,-@force.y) elsif self.y >= 800 play_sound :electron_freed @force *= 0.6 self.y -= self.y-800 @force = Ftor.new(@force.x,-@force.y) end else # follow shell movement_deg = @speed_deg * (time/1000.0) dx = self.x-@nucleus.x dy = self.y-@nucleus.y rads = Math.atan(dy.to_f/dx) if dx < 0 rads += Math::PI end movement_rads = deg_to_rads movement_deg rads = movement_rads+rads ex = @nucleus.shell_distance * @shell * Math.cos(rads) ey = @nucleus.shell_distance * @shell * Math.sin(rads) self.x = ex+@nucleus.x self.y = ey+@nucleus.y end end def deg_to_rads(deg) deg * Math::PI / 180.0 end def rads_to_degs(rads) rads * 180.0 / Math::PI end end
true
7215fda527dc30f16fd80dc056f31c663b767b12
Ruby
jcreiff/exercism
/ruby/queen-attack/queen_attack.rb
UTF-8
598
3.8125
4
[]
no_license
class Queens attr_reader :white, :black def initialize(white: [], black: []) [white, black].each do |position| raise ArgumentError, 'Invalid position' unless valid?(position) end @white = white @black = black end def attack? same_row? || same_column? || same_diagonal? end private def valid?(square) square.all? { (0..7).cover?(_1) } end def same_row? white.first == black.first end def same_column? white.last == black.last end def same_diagonal? (white.first - black.first).abs == (white.last - black.last).abs end end
true
2e96a39548281b41e0368787fb6aaac03d57dc5d
Ruby
bay-qa/linkedin_script
/linkdin.rb
UTF-8
2,312
3.125
3
[]
no_license
require 'capybara/dsl' require 'selenium-webdriver' require 'pry' Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new(app, browser: :chrome) end Capybara.javascript_driver = :chrome Capybara.configure do |config| config.default_max_wait_time = 10 # seconds config.default_driver = :selenium end class Linkdin include Capybara::DSL def scroll_to_bottom page.execute_script('window.scrollTo(0,100000)') end def login(email, password) find('#login-email').set(email) find('#login-password').set(password) find('#login-submit').click end def my_network find('#mynetwork-tab-icon').click end def visit_site(url) visit url end def people_may_know within find('.mn-pymk-list__cards') do all('.mn-person-info__card-details', :minimum => 3) end end def qas?(string) # key words to search for: # if user has: "sqa" or "test engineer" or "quality assurance" or "software qa" or "qa engineer" # u can add more ey word to the regex...syntax: |\b<key words>\b regex = /quality|\btest engineer\b|\bquality assurance\b|\bsoftware qa\b|\bqa engineer\b|\bqa\b|software test/ if regex.match(string.downcase) return true else false end end def get_testers qas = [] people_may_know.each do |user| if qas?(user.text) qas << user puts user.text end end qas end def connect_testers begin get_testers.each do |qa| qa.find(:xpath, '..').find('span', :text => "Connect").click puts "User connected: #{qa.text}" end puts "TOTAL connected users: #{get_testers.size}" rescue Selenium::WebDriver::Error::StaleElementReferenceError puts '-----------------------------' end end end linkdin = Linkdin.new linkdin.visit_site("https://www.linkedin.com") # login to the web site: email, password = ENV['email'], ENV['password'] linkdin.login(email, password) # go to my network: linkdin.my_network number_of_scrolls = 0 while number_of_scrolls < 10 #number of iterations = 5, change it if you want more. linkdin.connect_testers number_of_scrolls += 1 linkdin.scroll_to_bottom end # how ro run: # email=<my_email> password=<my_password> ruby linkdin.rb # let me know if any issues.
true
6d1a96bacfdc8d8a8a0a096ace97ba74886ef41a
Ruby
TriciaAI/ruby-challenges
/symbols.rb
UTF-8
302
3.671875
4
[]
no_license
hash1 = {name: "Baby Jaguar", description: "cracked eye", description2: "worn fur"} hash2 = {name: "Jaguar", description: "biggest", description2: "looks new" } hash3 = {name: "Jaggy", description: "smallest", description2: "floppy head" } winner = hash1[:name] puts "The most-loved jaguar is #{winner}!"
true
b78ea2176d7e6495a296d5e1ac163e617f62a3e0
Ruby
technolingo/gimchi
/lib/gimchi.rb
UTF-8
10,062
3.453125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
#!/usr/bin/env ruby # encoding: UTF-8 # Junegunn Choi (junegunn.c@gmail.com) require 'yaml' require 'set' require 'gimchi/char' require 'gimchi/pronouncer' class Gimchi class << self attr_reader :chosungs, :jungsungs, :jongsungs def Char ch Gimchi::Char.new(ch) end # Decompose a Korean character into 3 components # @param [String] ch Korean character # @return [Array] def decompose ch Gimchi::Char.new(ch).to_a end # Compose 3 elements into a Korean character String # @param [String] chosung # @param [String] jungsung # @param [String] jongsung # @return [String] def compose chosung, jungsung = nil, jongsung = nil if chosung.nil? && jungsung.nil? "" elsif chosung && jungsung n1, n2, n3 = n1 = chosungs.index(chosung) || 0 n2 = jungsungs.index(jungsung) || 0 n3 = ([nil] + jongsungs).index(jongsung) || 0 [ 0xAC00 + n1 * (21 * 28) + n2 * 28 + n3 ].pack('U') else chosung || jungsung end end # @param [String] ch # @return [Boolean] def chosung? ch @chosung_set.include? ch end # @param [String] ch # @return [Boolean] def jungsung? ch @jungsung_set.include? ch end # @param [String] ch # @return [Boolean] def jongsung? ch @jongsung_set.include? ch end # Checks if the given character is a korean character. # @param [String] ch A string of size 1 def korean_char? ch raise ArgumentError.new('Lengthy input') if str_length(ch) > 1 complete_korean_char?(ch) || @all.include?(ch) end alias kchar? korean_char? # Checks if the given character is a "complete" korean character. # "Complete" Korean character must have chosung and jungsung, with optional jongsung. # @param [String] ch A string of size 1 def complete_korean_char? ch raise ArgumentError.new('Lengthy input') if str_length(ch) > 1 # Range of Korean chracters in Unicode 2.0: AC00(가) ~ D7A3(힣) ch.unpack('U').all? { | c | c >= 0xAC00 && c <= 0xD7A3 } end # @deprecated # @private def kchar ch Gimchi::Char.new(ch) end # Reads numeric expressions in Korean way. # @param [String, Number] str Numeric type or String containing numeric expressions # @return [String] Output string def read_number str str.to_s.gsub(/(([+-]\s*)?[0-9,]*,*[0-9]+(\.[0-9]+(e[+-][0-9]+)?)?)(\s*.)?/) { read_number_sub($1, $5) } end # Returns the pronunciation of the given string containing Korean characters. # Takes optional options hash. # # @param [String] Input string # @param [Hash] options Options # @option options [Boolean] each_char Each character of the string is pronounced respectively. # @option options [Boolean] slur Strings separated by whitespaces are processed again as if they were contiguous. # @option options [Boolean] number Numberic parts of the string is also pronounced in Korean. # @option options [Array] except Allows you to skip certain transformations. # @return [String] Output string def pronounce str, options = {} options = { :each_char => false, :slur => false, :number => true, :except => [], :debug => false }.merge options str = read_number(str) if options[:number] result, transforms = @pronouncer.send :pronounce!, str, options if options[:debug] return result, transforms else return result end end # Returns the romanization (alphabetical notation) of the given Korean string. # http://en.wikipedia.org/wiki/Korean_romanization # @param [String] str Input Korean string # @param [Hash] options Options # @option options [Boolean] as_pronounced If true, #pronounce is internally called before romanize # @option options [Boolean] number Whether to read numeric expressions in the string # @option options [Boolean] slur Same as :slur in #pronounce # @return [String] Output string in Roman Alphabet # @see Korean#pronounce def romanize str, options = {} options = { :as_pronounced => true, :number => true, :slur => false }.merge options rdata = @config[:romanization] post_subs = rdata[:post_substitution] rdata = [rdata[:chosung], rdata[:jungsung], rdata[:jongsung]] str = pronounce str, :each_char => !options[:as_pronounced], :number => options[:number], :slur => options[:slur], # 제1항 [붙임 1] ‘ㅢ’는 ‘ㅣ’로 소리 나더라도 ‘ui’로 적는다. :except => %w[rule_5_3] dash = rdata[0]["ㅇ"] romanization = "" romanize_chunk = lambda do |chunk| chunk.each_char.map { |ch| Gimchi::Char.new(ch) rescue ch }.each do |kc| kc.to_a.each_with_index do |comp, idx| next if comp.nil? comp = rdata[idx][comp] || comp comp = comp[1..-1] if comp[0, 1] == dash && (romanization.empty? || romanization[-1, 1] =~ /\s/) romanization += comp end end return post_subs.keys.inject(romanization) { | output, pattern | output.gsub(pattern, post_subs[pattern]) } end k_chunk = "" str.each_char do | c | if korean_char? c k_chunk += c else unless k_chunk.empty? romanization = romanize_chunk.call k_chunk k_chunk = "" end romanization += c end end romanization = romanize_chunk.call k_chunk unless k_chunk.empty? romanization end private CONFIG_FILE_PATH = File.expand_path('../../config/default.yml', __FILE__) def str_length str str.length end def read_number_sub num, next_char nconfig = @config[:number] if num == '0' return nconfig[:digits].first end num = num.gsub(',', '') next_char = next_char.to_s is_float = num.match(/[\.e]/) != nil # Alternative notation for integers with proper suffix alt = false if is_float == false && nconfig[:alt_notation][:when_suffix].keys.include?(next_char.strip) max = nconfig[:alt_notation][:when_suffix][next_char.strip][:max] if max.nil? || num.to_i <= max alt = true end end # Sign sign = [] negative = false if num =~ /^-/ num = num.sub(/^-\s*/, '') sign << nconfig[:negative] negative = true elsif num =~ /^\+/ num = num.sub(/^\+\s*/, '') sign << nconfig[:positive] end if is_float below = nconfig[:decimal_point] below = nconfig[:digits][0] + below if num.to_f < 1 if md = num.match(/(.*)e(.*)/) dp = md[1].index('.') num = md[1].tr '.', '' exp = md[2].to_i dp += exp if dp > num.length num = num.ljust(dp, '0') num = num.sub(/^0+([1-9])/, "\\1") below = "" elsif dp < 0 num = '0.' + '0' * (-dp) + num else num[dp, 1] = '.' + num[dp, 1] end end num.sub(/.*\./, '').each_char do | char | below += nconfig[:digits][char.to_i] end if num.include? '.' num = num.sub(/\..*/, '') else below = "" end tokens = [] unit_idx = -1 num = num.to_i while num > 0 v = num % 10000 unit_idx += 1 if v > 0 if alt == false || unit_idx >= 1 str = "" # Cannot use hash as they're unordered in 1.8 [[1000, '천'], [100, '백'], [10, '십']].each do | arr | u, sub_unit = arr str += (nconfig[:digits][v/u] if v/u != 1).to_s + sub_unit + ' ' if v / u > 0 v %= u end str += nconfig[:digits][v] if v > 0 raise RangeError, "number too large" unless nconfig[:units][unit_idx] tokens << str.sub(/ $/, '') + nconfig[:units][unit_idx] else str = "" tenfolds = nconfig[:alt_notation][:tenfolds] digits = nconfig[:alt_notation][:digits] alt_post_subs = nconfig[:alt_notation][:post_substitution] # Likewise. [[1000, '천'], [100, '백']].each do |u, sub_unit| str += (nconfig[:digits][v/u] if v/u != 1).to_s + sub_unit + ' ' if v / u > 0 v %= u end str += tenfolds[(v / 10) - 1] if v / 10 > 0 v %= 10 str += digits[v] if v > 0 alt_post_subs.each do |p, s| str.gsub!(p, s) end if alt tokens << str.sub(/ $/, '') + nconfig[:units][unit_idx] end end num /= 10000 end tokens += sign unless sign.empty? ret = tokens.reverse.join(' ') + below + next_char nconfig[:post_substitution].each do |p, s| ret.gsub!(p, s) end ret end # @private def setup symbolize_keys = lambda do |val| case val when Hash {}.tap do |h| val.each do |k, v| k = k.gsub(' ', '_').to_sym if k =~ /[a-z0-9 ]/ h[k] = symbolize_keys.call v end end when Array val.map { |v| symbolize_keys.call v } else val end end @config = symbolize_keys.call YAML.load(File.read CONFIG_FILE_PATH) [ @config[:romanization][:post_substitution], @config[:number][:post_substitution], @config[:number][:alt_notation][:post_substitution] ].each do |r| r.keys.each do |k| r[Regexp.compile k.to_s] = r.delete k end end @config.freeze @pronouncer = Gimchi::Pronouncer.send :new, @config[:pronouncer], @config[:structure] @chosungs = @config[:structure][:chosung] @jungsungs = @config[:structure][:jungsung] @jongsungs = @config[:structure][:jongsung] @chosung_set = Set[*@chosungs] @jungsung_set = Set[*@jungsungs] @jongsung_set = Set[*@jongsungs] @all = @chosung_set + @jungsung_set + @jongsung_set end end private def initialize raise NoMethodError, "Gimchi is a singleton class" end end#Gimchi require 'gimchi/patch_1.8' Gimchi.send :setup
true
8845e429364ccd4f6efbe09644a03c9bc85bafe7
Ruby
Boltmade/Phonepad-Chess
/knight.rb
UTF-8
375
3.09375
3
[]
no_license
class Knight < ChessPiece def is_move_legal?(board, x, y) # Knight moves in L or stays in its place return super && ( (board.current_x == x) && (board.current_y == y) || ((board.current_x - x).abs == 1) && ((board.current_y - y).abs == 2) || ((board.current_x - x).abs == 2) && ((board.current_y - y).abs == 1)) end end
true
23173d11ea0628287a22cf8069960abfd5e18c88
Ruby
okeeffe/playboard
/app/models/user.rb
UTF-8
1,919
2.765625
3
[]
no_license
class User < ActiveRecord::Base # Establishes the relationship between Users and Plays, and that if a User is deleted, their Plays are too. has_many :plays, :dependent => :destroy # All the validations for a User. validates :first_name, :presence => true, :length => {:minimum => 1} validates :last_name, :presence => true, :length => {:minimum => 1} validates :team, :presence => true, :length => {:minimum => 1} validates :username, :presence => true, :uniqueness => true, :length => {:minimum => 4} validates :email, :presence => true, :uniqueness => true, :email => true validates :password, :confirmation => true, :length => {:minimum => 4} attr_accessor :password_confirmation attr_reader :password validate :password_must_be_present # Return the user if they login with the right details def User.authenticate(username, password) if user = find_by_username(username) if user.hashed_password == encrypt_password(password, user.salt) user end end end # Encrypt the user's passsword, adding the arbitrary 'wibble' string for some extra security. def User.encrypt_password(password, salt) Digest::SHA2.hexdigest(password + "wibble" + salt) end # Method to save the password as an encrypted version of itself # (overrides the standard setter created by attr_accessor above) # 'password' is a virtual attribute. def password=(password) @password = password if password.present? generate_salt self.hashed_password = self.class.encrypt_password(password, salt) end end private # Checks if the hashed password is present def password_must_be_present errors.add(:password, "can't be blank") unless hashed_password.present? end # Generate the salt for the hashed password def generate_salt self.salt = self.object_id.to_s + rand.to_s end end
true
87855d277f9a5530f44c0d04d8af75343b28e5d2
Ruby
wilkosz/domain_com_au
/lib/domain_com_au/client.rb
UTF-8
422
2.515625
3
[ "MIT" ]
permissive
require 'domain_com_au/http_client' require 'domain_com_au/domain_listing' class Client def initialize(client_id, client_secret) @http_client = HttpClient.new(client_id, client_secret) end def get_token @http_client.auth_token end def search_listings(type, params={}) DomainListing.index(@http_client, type, params) end def show_listing(id) DomainListing.show(@http_client, id) end end
true
4192235d3ed7eaadfcb528ad5d68759ae7e2b9aa
Ruby
Khomyachok5/equation
/app/controllers/equations_controller.rb
UTF-8
2,966
3.21875
3
[]
no_license
class EquationsController < ApplicationController require 'csv' require 'equation_solver' def main_page end def handle_input @status = [] @total_pairs = [] if params[:a_value] || params[:b_value] || params[:c_value] a = params[:a_value] b = params[:b_value] c = params[:c_value] if handle_form(a, b, c) else return (flash.alert = "One of the requirements for building parabola was not satisfied. Please review the requirements and rectify input values: \nThe value of \"a\" parameter can\'t be nill. \n Input values must be numbers."; redirect_to root_path) end elsif params[:file] file = params[:file].read if !handle_csv(file) return (flash.alert = "Invalid CSV file"; redirect_to root_path) else @array = handle_csv(file) end if !add_values(@array) return (flash.alert = "An empty file was submitted. Please submit a file with valid values"; redirect_to root_path) end if count_values(@array) @no_common_chart = 1 end if !array_slice(@array) return (flash.alert = "Values in the CSV file are split into pairs of three digits where each one corresponds to \"a\", \"b\" and \"c\" parameter to the function. The value of \"a\" parameter can\'t be nill. Please change it to a different digit"; redirect_to root_path) end render template: "equations/calculate" else return (flash.alert = "Neither the values for the form nor CSV file were submitted. Please, fill in the form or supply a CSV file with values"; redirect_to root_path) end end private def handle_form(a, b, c) @status = [] @total_pairs = [] result = EquationSolver.calculate(a, b, c, @status) if result != false @total_pairs << result else return false end @no_common_chart = 1 render template: "equations/calculate" end def handle_csv(file) if !EquationSolver.check_file_validity(file) false else CSV.parse(file).first end end def add_values(array) count = @array.count if count == 0 false elsif count % 3 != 0 (3 - (count % 3)).times do array << 0 end flash.notice = "The number of values supplied in the CSV file was not divisible by 3, so we added #{3 - (count % 3)} additional elements to be able to build the parabola. The arguments supplied now look as follows: #{@array}" array else array end end def count_values(array) if array.count == 3 true else false end end def array_slice(array) @total_pairs = [] @array_split = @array.each_slice(3).each_with_index do |pair, i| result = EquationSolver.calculate(pair[0], pair[1], pair[2], @status) if result != false @total_pairs << result elsif result == false return false end end @total_pairs end end
true
2ec4e118d89ec5f9bec5d6241d5846f0eb9251e7
Ruby
hermine-dm/scrapping
/lib/townhall.rb
UTF-8
1,437
3.265625
3
[]
no_license
require 'rubygems' require 'nokogiri' require 'open-uri' =begin def finding_the_page(ville) townhall_url = Nokogiri::HTML(open("https://www.annuaire-des-mairies.com/95/#{ville}.html")) return townhall_url end =end def get_townhall_email(townhall_url) begin #ne sert à rien il n'y avait pas d'erreur haha page = Nokogiri::HTML(open("#{townhall_url}")) email = page.xpath('//section[2]//tr[4]/td[2]/text()') #// saute le chemin au milieu rescue => e email = "n/a" end return email end def get_towhall_city() page = Nokogiri::HTML(open("http://annuaire-des-mairies.com/val-d-oise.html")) array_of_city = page.xpath('//*[@class="lientxt"]/text()') return array_of_city end def get_townhall_urls(array) arr_wo_space = array.map{|city| city.to_s.tr(' ','-')} array_of_urls = arr_wo_space.map{|city_wo|"https://www.annuaire-des-mairies.com/95/#{city_wo.downcase}.html"} return array_of_urls end def creat_final_array(arr_city,arr_email) arr_final = [] for i in 0...arr_city.size arr_final << {arr_city[i].to_s => arr_email[i].to_s} #ne pas mettre des crochets autour sinon ca fait un array end return arr_final end def perform() array_of_city = get_towhall_city() array_of_urls = get_townhall_urls(array_of_city) array_of_email = array_of_urls.map{|urls| urls = get_townhall_email(urls)} arr_final = creat_final_array(array_of_city,array_of_email) puts arr_final return arr_final end perform()
true
49637cdd5cc2e06f6c5b0a8943b717636edf2207
Ruby
nguyennhan09cntt/4room.vn
/app/models/user.rb
UTF-8
1,148
2.59375
3
[]
no_license
require 'digest/sha1' class User < ApplicationRecord self.table_name = "user" before_create :encrypt_password after_create :clear_password validates :user_name, :presence => {message: "is required" }, :length => { in: 4..20, message: "from 4 to 20 charters"}, uniqueness: true validates :password, :presence => true, length: { in: 6..20, message: "from 6 to 20 charters"}, :on => :create def encrypt_password if password.present? self.salt = Digest::SHA1.hexdigest("abcdefghk#{Time.now}") self.password = Digest::SHA1.hexdigest("#{salt}#{password}") end end def clear_password self.password = nil end def self.authenticate(username="", login_password="") user = User.find_by_user_name(username) if user && user.match_password(login_password) return user else return false end end def match_password(login_password="") return password == Digest::SHA1.hexdigest("#{salt}#{login_password}") end def self.koala(auth) access_token = auth['token'] Koala.config.api_version = "v2.10" facebook = Koala::Facebook::API.new(access_token) facebook.get_object("me?fields=name,picture,birthday,email") end end
true
fa4459887e2b8e04dc6c108b2bccdffe08f3a64d
Ruby
benhutton/facebooker2
/lib/facebooker2.rb
UTF-8
1,938
2.59375
3
[ "MIT" ]
permissive
# Provides rails helpers for interfacing with Facebook's OpenGraph Javascript # API, http://developers.facebook.com/docs/reference/javascript/. require "mogli" require "facebooker2/rails/controller" require "facebooker2/rails/helpers/facebook_connect" require "facebooker2/rails/helpers/javascript" require "facebooker2/rails/helpers/request_forms" require "facebooker2/rails/helpers/user" require "facebooker2/rails/helpers" require "facebooker2/not_configured" module Facebooker2 # provide cached access to configuration class << self attr_accessor :api_key, :secret, :app_id end # provide cached access to the configured application secret def self.secret @secret || raise_unconfigured_exception end # provide cached access to the configured app_id def self.app_id @app_id || raise_unconfigured_exception end # when configuration is missing, raise exception def self.raise_unconfigured_exception raise NotConfigured.new("No configuration provided for Facebooker2. Either set the app_id and secret or call Facebooker2.load_facebook_yaml in an initializer") end # load configuration from hash def self.configuration=(hash) self.api_key = hash[:api_key] self.secret = hash[:secret] self.app_id = hash[:app_id] end # read configuration from yaml config file def self.load_facebook_yaml config = YAML.load(ERB.new(File.read(File.join(::Rails.root,"config","facebook.yml"))).result)[::Rails.env] raise NotConfigured.new("Unable to load configuration for #{::Rails.env} from facebook.yml. Is it set up?") if config.nil? self.configuration = config.with_indifferent_access end # flexible access to facebook_id of user from several possible object types def self.cast_to_facebook_id(object) if object.kind_of?(Mogli::Profile) object.id elsif object.respond_to?(:facebook_id) object.facebook_id else object end end end
true
b081d4f2bfb97d61071a29cb224f4d8d09aa0742
Ruby
Thermatix/dynamised-rb
/lib/dynamised/node.rb
UTF-8
946
2.90625
3
[ "MIT" ]
permissive
module Dynamised class Node include Enumerable attr_accessor :childs,:init, :data, :ident,:siblings def initialize(init={},ident=nil) @ident = ident @childs = {} @sibilngs = {} @init = init.clone @data = init.clone end def each(&block) block.call(self) @childs.map do |key,child| child.each(&block) end end def <=>(other_node) @data <=> other_node.data end def [](*keys) return self if @childs.empty? [*keys.flatten].inject(self) do |node,ident| node.find {|n| n.ident == ident} end end def new_child(ident,&block) child = self.class.new(@init,ident) child.siblings = self.childs child.tap(&block) if block_given? @childs[ident] = child end def pretty_print(pp) self.each {|node| pp.text(node.ident || "" );puts "\n";pp.pp_hash node.data} end end end
true
de9f52943d7f7d59a32d95672b73acd1dc863cec
Ruby
malachispencer/codewars
/ruby/6kyu/ranking-nba-teams.rb
UTF-8
4,760
3.671875
4
[]
no_license
=begin Codewars. 28/05/20. 'Ranking NBA teams'. 6kyu. We are given a string of the results of NBA games, separated by commas, and another string, an NBA team. Here we create a method which provides a breakdown of that team's results/stats for example "Boston Celtics:W=4;D=0;L=0;Scored=403;Conceded=350;Points=12". Here is the solution I developed to solve the challenge. 1) We define our method nba_results_ms, which takes a r, a string of results and t, an NBA team as its arguments. 2) We handle our first error check, if t is an empty string, we return an empty string. 3) Each game is separated by a comma and now we need to extract all the games our input team features in. So that we don't need to use split and reject or select, we call tr on r and replace all commas with newlines, so now every game is on a different line, then we call the scan method. 4) In our regex, ^ asserts the start of the line, .* is 0 or more characters, followed by our input team #{t}, followed by a space, followed by 0 or more characters .* until the end of the line $. This returns an array of every line/game our input team features in, which we call tr for team results. 5) Placing the space after #{t} is important, because without it, for example, we'd match Bostin Celtics if our input was Boston Celt. 6) If our array of games is empty, we return that our input team didn't play. 7) Only integers are accepted as a valid score, so if tr contains a float, matched by our regex \d+\.\d+, we return another error message. 8) Now we need to separate the team and score within each game, so we map! over tr, then for each game we call the scan method to turn the string into an array of 2 strings, with each string contain the team and its score. 9) In our regex, ^ asserts the start of the string, followed by 1 or more characters (the team name), followed by a space \s, followed by a set of digits \d+ just before a space we don't capture (?=\s). This first half of our regex will capture the first team and score in the string. We then have an or operator and capture the second team and score in the string. In this part of the regex, \w captures the first word of the second team, .+ captures the rest of the team name including any spaces, \s captures the space after the team name and then \d+ captures the score (which for the second team is at the end of the string $). 10) Now we have an array of arrays where each sub-array holds team 1 and its score as the first element, and team 2 and its score as the second element, both are strings. 11) To make our lives easier, we want our input team to always be in the first position of every sub-array, so we map! over both elements of each sub-array and if a contains our input team, we make a the first element and b the second element, if not, b contains our input team so we make b the first element and a the second element. 12) Now our array of games is sorted so that our input team is always the first team in the sub-array. 13) We then initialize a counter hash, where we are going to store the wins, draws, losses, total scored and total conceded for our input team. 14) Using each, we iterate over both teams in each game. We create a variable as where using string slicing we grab the last set of digits from the team in the first position of the sub-array i.e. the score of our input team, we convert this to an integer. We do the same for the opposition team and store this in a variable bs. 15) For each game, if our input team's score (as) is higher than the opposition's score (bs), we increment wins in our hash by 1, if they are equal, we increment draws by 1, if as has a lower score than bs, we increment losses by 1. The score key of our hash is increment by every score of our input team, and the conceded key is incremented by every score of the opposition team. 16) Now we have our stats, using string interpolation we return them in the specified format. Points is simply the number of wins multiplied by 3, added to the total amount of draws. =end def nba_results_ms(r,t) return "" if t.empty? tr = r.tr(",", "\n").scan(/^.*#{t}\s.*$/) return "#{t}:This team didn't play!" if tr.empty? return "Error(float number):#{tr.join}" if tr.join.match(/\d+\.\d+/) tr.map! {|g| g.scan(/^.+\s\d+(?=\s)|\w.+\s\d+$/)}.map! {|a,b| a.match(/#{t}/) ? [a,b] : [b,a]} h = {"W"=>0, "D"=>0, "L"=>0, "S"=>0, "C"=>0} tr.each do |a,b| as = a[/\d+$/].to_i bs = b[/\d+$/].to_i h["W"] += 1 if as > bs h["D"] += 1 if as == bs h["L"] += 1 if as < bs h["S"] += as h["C"] += bs end "#{t}:W=#{h["W"]};D=#{h["D"]};L=#{h["L"]};Scored=#{h["S"]};Conceded=#{h["C"]};Points=#{h["W"] * 3 + h["D"]}" end
true
12d92a9b644407557ea6b4a313c21232029b9f17
Ruby
mbraga24/ruby-oo-fundamentals-object-attributes-lab-nyc04-seng-ft-041920
/lib/dog.rb
UTF-8
310
3.578125
4
[]
no_license
class Dog # SETTERS def name=(dog_name) @name = dog_name end def breed=(dog_breed) @breed = dog_breed end # GETTERS def name @name end def breed @breed end end laika = Dog.new laika.name = "Laika" laika.breed = "Mixed" puts laika.name puts laika.breed
true
1dcef8b2da3bcf4429eec9e7ff58fce190d0589c
Ruby
sue445/cure-mastodon-bots
/lib/on_air_bot.rb
UTF-8
1,136
2.734375
3
[ "MIT" ]
permissive
require_relative "bot" require_relative "program_manager" class OnAirBot < Bot DELAY_MINUTES = 10 RANGE_MINUTES = 30 def initialize super(ENV["MASTODON_URL"], ENV["ACCESS_TOKEN_ON_AIR"]) end def perform on_air_programs = current_programs if on_air_programs.empty? puts "Doesn't found on air programs" return end ProgramManager.each_with_same_story_number(on_air_programs) do |program, ch_names| message = generate_message(program, ch_names) post_message(message) end end private def current_programs current_time = Time.current min = current_time.min - (current_time.min % 10) start_at = current_time.change(min:, sec: 0) + DELAY_MINUTES.minutes end_at = start_at + RANGE_MINUTES.minutes ProgramManager.search(start_at:, end_at:, squeeze: true) end def generate_message(program, ch_names) message = program.format(ch_names) message << "\nこのあとすぐ!\n" message.strip end end if $PROGRAM_NAME == __FILE__ Bundler.require(:default, :development) Dotenv.load OnAirBot.new.perform end
true
ba3ae312455f61aeeed5d58b50cbcf6f94f939fe
Ruby
niklaslong/epicodus-lessons
/Ruby/train/spec/train_spec.rb
UTF-8
2,122
2.734375
3
[]
no_license
require 'unit_helper_spec' describe 'Train' do describe '.all' do it 'Will return an empty array for the all method' do expect(Train.all).to eq [] end end describe '.save' do it 'It will save a train to the trains table' do name = "test train" train_uuid = Train.save(name) expect(Train.all[0]["id"]).to eq train_uuid end end describe '.find' do it 'returns a train based on id' do name = "test train" train_uuid = Train.save(name) expect(Train.find(train_uuid)["name"]).to eq "test train" end end describe '.edit' do it "will allow a user to edit a train" do name = "test train" train_uuid = Train.save(name) Train.edit("Burf", train_uuid) expect(Train.all[0]["name"]).to eq "Burf" end end describe '.delete' do it "will allow a user to delete a train" do name = "test train" train_uuid = Train.save(name) Train.delete(train_uuid) expect(Train.all).to eq [] end end describe '.train_cities' do it "will list all of the cities of a specific train" do name = "test train" train_uuid = Train.save(name) expect(Train.train_cities(train_uuid)).to eq [] end end describe '.add_train_cities' do it "will add cities to the join table with a specific train id" do city_uuid_a = [] time_a = [] city_name = "Portland" city_uuid = City.save(city_name) city_time = "12:00 PM" city_name2 = "Seattle" city_time2 = "2:00 PM" city_uuid2 = City.save(city_name2) time_a.push(city_time, city_time2) city_uuid_a.push(city_uuid, city_uuid2) name = "test train" train_uuid = Train.save(name) Train.add_train_cities(train_uuid, city_uuid_a, time_a) expect(Train.train_cities(train_uuid)[0]["city_id"]).to eq city_uuid expect(Train.train_cities(train_uuid)[1]["city_id"]).to eq city_uuid2 expect(Train.train_cities(train_uuid)[0]["stop_time"]).to eq "12:00:00" expect(Train.train_cities(train_uuid)[1]["stop_time"]).to eq "14:00:00" end end end
true
ba77ee4e9939ba95004baa637d91e15e263eed8d
Ruby
IamElaya/contact-list.v4
/app/actions.rb
UTF-8
614
2.515625
3
[]
no_license
# Homepage (Root path) get '/' do erb :index end get '/contacts' do contacts = Contact.all # contacts = contacts.where("name ILIKE ?", params[:name]) if params[:name].present? contacts.to_json end post '/contacts' do firstname = params[:firstname] lastname = params[:lastname] email = params[:email] results = {result: false} contact = Contact.new(firstname: firstname, lastname: lastname, email: email) if contact.save results[:result] = true results[:id] = contact.id end results.to_json end get '/contacts/:id' do contact = Contact.find(params[:id]) contact.to_json end
true
c65096c0651bf6edd98650690ffb8d7fcd93dc4c
Ruby
dachrisch/extreme_startup
/lib/extreme_startup/question_factory.rb
UTF-8
9,949
3.40625
3
[]
no_license
require 'set' require 'prime' # TODO: This really should be somewhere better # but I don't know how to best set up the require's for that class Array def pick_one self[Kernel.rand(self.length)] end end module ExtremeStartup class Question class << self def generate_uuid @uuid_generator ||= UUID.new @uuid_generator.generate.to_s[0..7] end end def ask(player) url = player.url + '?q=' + URI.escape(self.to_s) puts "GET: " + url begin response = get(url) if (response.success?) then self.answer = response.to_s else @problem = "error_response" end rescue => exception puts exception @problem = "no_answer" end end def get(url) HTTParty.get(url) end def result if @answer && self.answered_correctly? "correct" elsif @answer "wrong" else @problem end end def score case result when "correct" then points when "wrong" then penalty when "error_response" then -5 when "no_answer" then -20 else puts "!!!!! result #{result} in score" end end def delay_before_next case result when "correct" then 5 when "wrong" then 10 else 20 end end def display_result "\tquestion: #{self.to_s}\n\tanswer: #{answer}\n\tresult: #{result}" end def id @id ||= Question.generate_uuid end def to_s "#{id}: #{as_text}" end def answer=(answer) @answer = answer end def answer @answer && @answer.downcase.strip end def answered_correctly?(answer = answer) correct_answer.to_s.downcase.strip == answer end def points 10 end def penalty - points / 10 end end class BinaryMathsQuestion < Question def initialize(player, *numbers) if numbers.any? @n1, @n2 = *numbers else @n1, @n2 = rand(20), rand(20) end end end class TernaryMathsQuestion < Question def initialize(player, *numbers) if numbers.any? @n1, @n2, @n3 = *numbers else @n1, @n2, @n3 = rand(20), rand(20), rand(20) end end end class SelectFromListOfNumbersQuestion < Question def initialize(player, *numbers) if numbers.any? @numbers = *numbers else size = rand(2) @numbers = random_numbers[0..size].concat(candidate_numbers.shuffle[0..size]).shuffle end end def random_numbers randoms = Set.new loop do randoms << rand(1000) return randoms.to_a if randoms.size >= 5 end end def correct_answer @numbers.select do |x| should_be_selected(x) end.join(', ') end end class MaximumQuestion < SelectFromListOfNumbersQuestion def as_text "which of the following numbers is the largest: " + @numbers.join(', ') end def points 40 end private def should_be_selected(x) x == @numbers.max end def candidate_numbers (1..100).to_a end end class AdditionQuestion < BinaryMathsQuestion def as_text "what is #{@n1} plus #{@n2}" end private def correct_answer @n1 + @n2 end end class SubtractionQuestion < BinaryMathsQuestion def as_text "what is #{@n1} minus #{@n2}" end private def correct_answer @n1 - @n2 end end class MultiplicationQuestion < BinaryMathsQuestion def as_text "what is #{@n1} multiplied by #{@n2}" end private def correct_answer @n1 * @n2 end end class AdditionAdditionQuestion < TernaryMathsQuestion def as_text "what is #{@n1} plus #{@n2} plus #{@n3}" end def points 30 end private def correct_answer @n1 + @n2 + @n3 end end class AdditionMultiplicationQuestion < TernaryMathsQuestion def as_text "what is #{@n1} plus #{@n2} multiplied by #{@n3}" end def points 60 end private def correct_answer @n1 + @n2 * @n3 end end class MultiplicationAdditionQuestion < TernaryMathsQuestion def as_text "what is #{@n1} multiplied by #{@n2} plus #{@n3}" end def points 50 end private def correct_answer @n1 * @n2 + @n3 end end class PowerQuestion < BinaryMathsQuestion def as_text "what is #{@n1} to the power of #{@n2}" end def points 20 end private def correct_answer @n1 ** @n2 end end class SquareCubeQuestion < SelectFromListOfNumbersQuestion def as_text "which of the following numbers is both a square and a cube: " + @numbers.join(', ') end def points 60 end private def should_be_selected(x) is_square(x) and is_cube(x) end def candidate_numbers square_cubes = (1..100).map { |x| x ** 3 }.select{ |x| is_square(x) } squares = (1..50).map { |x| x ** 2 } square_cubes.concat(squares) end def is_square(x) (x % Math.sqrt(x)) == 0 end def is_cube(x) (x % Math.cbrt(x)) == 0 end end class PrimesQuestion < SelectFromListOfNumbersQuestion def as_text "which of the following numbers are primes: " + @numbers.join(', ') end def points 60 end private def should_be_selected(x) Prime.prime? x end def candidate_numbers Prime.take(100) end end class FibonacciQuestion < BinaryMathsQuestion def as_text n = @n1 + 4 "what is the #{n}th number in the Fibonacci sequence" end def points 50 end private def correct_answer n = @n1 + 4 root5 = Math.sqrt(5) phi = 0.5 + root5/2 Integer(0.5 + phi**n/root5) end end class GeneralKnowledgeQuestion < Question class << self def question_bank [ ["what is the twitter id of the organizer of this dojo", "jhannes"], ["who is the Prime Minister of Great Britain", "David Cameron"], ["which city is the Eiffel tower in", "Paris"], ["what currency did Spain use before the Euro", "peseta"], ["what colour is a banana", "yellow"], ["who played James Bond in the film Dr No", "Sean Connery"] ] end end def initialize question = GeneralKnowledgeQuestion.question_bank.pick_one @question = question[0] @answer = question[1] end def as_text @question end def correct_answer @answer end end class ConversationalQuestion < Question def initialize(player, spawn_rate = 80) @session = get_session(player, spawn_rate) end def get(url) @session.get(url) end def answer=(answer) @answer = answer @session.add_answer(answer) end def answered_correctly? @session.answered_correctly? end def as_text @question ||= @session.question end def correct_answer @session.correct_answer end def points @session.points end def penalty @session.penalty end def self.sessions @sessions ||= {} end def get_session(player, spawn_rate) sessions = (self.class.sessions[player] ||= []) sessions.reject! { |session| session.dead? } sessions << create_session if spawn?(sessions, spawn_rate) self.class.sessions[player].pick_one end def spawn?(sessions, spawn_rate) sessions.empty? || (rand(100) < spawn_rate) end end class Conversation def get(url) response = HTTParty.get(url, :headers => headers) return response unless response.success? @cookie = response.headers['set-cookie'] || @cookie return response end def headers @cookie ? { "cookie" => @cookie } : {} end def answered_correctly? @answer && correct_answer.strip.to_s == @answer.strip.to_s end def score answered_correctly? ? points : penalty end def points 10 end def penalty - points / 10 end end class RememberMeConversation < Conversation def initialize @name = %w(abe bob chuck dick evan fred george hob ivan jim pete ric).pick_one @attempts = 0 end def add_answer(answer) @answer = answer @attempts += 1 end def dead? !answered_correctly? || @attempts > 10 end def question if answered_correctly? return "what is my name" else return "my name is #{@name}. what is my name" end end def correct_answer @name end def points 30 # + @attempts * 10 end end class RememberMeQuestion < ConversationalQuestion def create_session RememberMeConversation.new end end class QuestionFactory attr_reader :round def initialize @round = 1 @question_types = [ #RememberMeQuestion, #ExtremeStartup::Questions::WebshopQuestion, AdditionQuestion, MaximumQuestion, MultiplicationQuestion, SquareCubeQuestion, GeneralKnowledgeQuestion, PrimesQuestion, SubtractionQuestion, FibonacciQuestion, PowerQuestion, AdditionAdditionQuestion, AdditionMultiplicationQuestion, MultiplicationAdditionQuestion ] end def next_question(player) available_question_types = @question_types[0..(@round * 2 - 1)] available_question_types.pick_one.new(player) end def advance_round @round += 1 end end end
true
2f219ec7fb08dd479141e26110a2ed18d30b694d
Ruby
abak-press/apress-sources
/lib/apress/sources/object_id_extractor.rb
UTF-8
1,713
3.109375
3
[ "MIT" ]
permissive
module Apress module Sources # Extract id from params where exists object key # # @example: # Apress::Sources::ObjectIdExtractor.new(:user).call(object: {user_id: 1}) # => 1 # # @api public # # @since 0.2.0 class ObjectIdExtractor attr_reader :object_name # Create new extractor # # @param [Symbol] object_name (:user, :company) # # @return [Apress::Sources::ObjectIdExtractor] def initialize(object_name) @object_name = object_name end # @param [Hash] params # @option params [String, Numeric, Proc, Object, Hash] :object # # @example String # ObjectIdExtractor.new(:user).call(object: '1') # # @example Hash # ObjectIdExtractor.new(:user).call(object: {user: 1}) # ObjectIdExtractor.new(:user).call(object: {user_id: User.new}) # ObjectIdExtractor.new(:user).call(object: {user_id: ->{ 1 }}) # # @return [Integer] # # @raise ArgumentError if can`t extract id from params def call(params = {}) object = params.fetch(:object) object = object[object_name] || object["#{object_name}_id".to_sym] if object.is_a?(Hash) case object when Numeric object when String object.to_i else if object && object.respond_to?(:id) object.id elsif object.respond_to?(:call) object.call else raise ArgumentError.new( "#{object_name} instance or Numeric/String/Proc #{object_name} id expected!', #{params.inspect}" ) end end end end end end
true
afca3dac1d831d37e4aa2af6c7f3e94888454fa1
Ruby
maximkoo/ruby-repo
/Ruby Stuff/Ruby Lecture/3. Blocks/080.rb
UTF-8
146
3.046875
3
[]
no_license
def m6(&block1) puts block1.class.name block1.call yield end; pp=Proc.new do puts "Proc executed as a block" end m6(&pp)
true
b7f07980d50011faa56bb0d5809678a010a93206
Ruby
BeRMaNyA/minesweeper-api
/app/models/time_entry.rb
UTF-8
376
2.515625
3
[]
no_license
# frozen_string_literal: true class TimeEntry include Mongoid::Document field :start_time, type: Time field :end_time, type: Time field :duration, type: Float embedded_in :game def finish self.end_time = Time.now.utc self.duration = (end_time - start_time).round(2) end def duration super || (Time.now.utc - start_time).round(2) end end
true
39bc32eb0b96f89274c06de8c941dacb85f7ed63
Ruby
baumanj/matasano_crypto_challenges
/103_single-byte_xor_cipher.rb
UTF-8
3,909
2.96875
3
[]
no_license
# Single-byte XOR cipher # The hex encoded string: # 1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736 # ... has been XOR'd against a single character. Find the key, decrypt the message. # You can do this by hand. But don't: write code to do it for you. # How? Devise some method for "scoring" a piece of English HEX_PLAINTEXT. Character frequency is a good metric. Evaluate each output and choose the one with the best score. # Achievement Unlocked # You now have our permission to make "ETAOIN SHRDLU" jokes on Twitter. if __FILE__ == $0 puts `rspec -f documentation #{__FILE__}` end require "rspec" require "securerandom" require "./type_conversion" require "./bit_manipulation" require "./natural_language_processing" require "./crypto" module SingleByteXORCipher HEX_CIPHERTEXT ||= "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736" # found first with brute force + visually scanning output (c.f. master 80d4fb4) HEX_PLAINTEXT ||= "436f6f6b696e67204d432773206c696b65206120706f756e64206f66206261636f6e" PLAINTEXT ||= "Cooking MC's like a pound of bacon" KEY ||= "58" end describe :decrypt do it "returns the plaintext when the proper key is applied" do expect(decrypt(SingleByteXORCipher::HEX_CIPHERTEXT, hex_key: SingleByteXORCipher::KEY)).to eq(SingleByteXORCipher::HEX_PLAINTEXT) expect(decrypt("00", hex_key: "00")).to eq("00") expect(decrypt("f00f", hex_key: "ff")).to eq("0ff0") end it "requires two args, one of them named 'key'" do expect { decrypt() }.to raise_error(ArgumentError) expect { decrypt(SingleByteXORCipher::HEX_CIPHERTEXT) }.to raise_error(ArgumentError) expect { decrypt(SingleByteXORCipher::HEX_CIPHERTEXT, hex_key: SecureRandom.hex(1)) }.to_not raise_error end it "requires key to be one hex byte" do expect { decrypt(SingleByteXORCipher::HEX_CIPHERTEXT, hex_key: SecureRandom.hex(1)[0]) }.to raise_error(ArgumentError) long_hex_key = SecureRandom.hex(100) 3.upto(long_hex_key.length - 1) do |num_hex_digits| expect { decrypt(SingleByteXORCipher::HEX_CIPHERTEXT, hex_key: long_hex_key[0, num_hex_digits]) }.to raise_error(ArgumentError) end expect { decrypt("beef", hex_key: "cake") }.to raise_error(ArgumentError) expect { decrypt("dead", hex_key: "b0d") }.to raise_error(ArgumentError) expect { decrypt("dead", hex_key: "kk") }.to raise_error(ArgumentError) end it "requires the hex ciphertext to be full hex bytes" do expect(decrypt(SecureRandom.hex(0), hex_key: SecureRandom.hex(1))).to eq("") random_hex = SecureRandom.hex(SecureRandom.random_number(100)) expect { decrypt(random_hex, hex_key: SecureRandom.hex(1)) }.to_not raise_error expect { decrypt(random_hex[1..-1], hex_key: SecureRandom.hex(1)) }.to raise_error(ArgumentError) end end describe :find_key do TOP_ENGLISH_CHARS_BY_FREQ.each do |strategy, top_chars| context "when using top characters determined from #{strategy}" do let(:plaintext) do ciphertext = hex_to_raw(SingleByteXORCipher::HEX_CIPHERTEXT) key = find_key(ciphertext, top_chars) plaintext = hex_to_raw(decrypt(SingleByteXORCipher::HEX_CIPHERTEXT, hex_key: raw_to_hex(key))) end it "finds a key that decrypts #{SingleByteXORCipher::HEX_CIPHERTEXT} to mostly words in the dict file" do expect(valid_word_pct(plaintext)).to be > 50 end it "finds a key that decrypts #{SingleByteXORCipher::HEX_CIPHERTEXT} to all printing characters" do expect(plaintext.scan(/[^[:print:][:space:]]/)).to be_empty end end end end def decrypt(hex_ciphertext, hex_key:) fail ArgumentError, "key must be one full hex byte" if hex_key.length != 2 key = hex_to_raw(hex_key) ciphertext = hex_to_raw(hex_ciphertext) repeated_key = key * (ciphertext.length / key.length) raw_to_hex(xor(ciphertext, repeated_key)) end
true
86319e716d98b9a29aaadb10cd559cebf44a98e4
Ruby
nathaliesantana/cocktail_recipes
/lib/cocktail_recipes/cli.rb
UTF-8
1,327
3.59375
4
[ "MIT" ]
permissive
class CocktailRecipes::Cli def welcome CocktailRecipes::Scraper.new("https://www.foodandwine.com/cocktail-recipes").scrape puts "Hi, Welcome to Reinvented Classic Cocktails" main_menu end def main_menu puts "Here is a list of all of our cocktails:" display_cocktails_list puts "Type the number of the cocktail you would like to learn." input = gets.strip.to_i if (1..CocktailRecipes::Recipes.all.length).include?(input) puts CocktailRecipes::Recipes.all[input-1].name.upcase puts "" puts "Ingredients" puts CocktailRecipes::Recipes.all[input-1].ingredients puts "" puts "Instructions" puts CocktailRecipes::Recipes.all[input-1].instructions puts "" menu_options else invalid end end def menu_options puts "Would you like to see another recipe?" puts "Type (Yes or No) " input = gets.strip.downcase input == "yes" ? main_menu : good_bye end def good_bye puts "Thank you for your visit." puts "You're welcome to come back anytime!" end def invalid puts "Im sorry. This is not an option." puts "Please try againg." main_menu end def display_cocktails_list CocktailRecipes::Recipes.all.each.with_index do |c, i| puts "#{i+1}. #{c.name}" end end end
true
4f0f27a78bbf74684d46cd55718192d393067a1d
Ruby
danisbubblesdad/Introduction_to_Ruby_and_Web_Development
/Lesson_2/OOP_Workbook/easy/Quiz_1/e6.rb
UTF-8
348
3.703125
4
[]
no_license
# 6 - What could we add to the class below to access the instance variable # @volume? class Cube attr_reader :volume #if we add an attr_reader we can access the #instance variable. We could also add a method #that returns the variable. def initialize(volume) @volume = volume end end
true
a81bd5631d8a25f53b370eb23bf5bc988efc7659
Ruby
MasoodGit/rubytdddemo
/spec/testunit.rb
UTF-8
716
2.640625
3
[]
no_license
gem 'minitest' require 'minitest/autorun' require '../lib/string_calc' class TestTheCalc< MiniTest::Test def test_add_emptystring_returnsdefaultvalue result = StringCalculator.new.add("") assert_equal 0,result end end describe StringCalculator do describe "adding" do describe "empty string" do it "changes the state of the system" do result = StringCalculator.new.add("") result.must_equal 0 end it "Calls a logger" do result = StringCalculator.new.add("") result.must_equal 0 end it "returns default value" do result = StringCalculator.new.add("") result.must_equal 0 end end end end
true
719e0d6801beb70d1455a699aa8bd8a81a449f33
Ruby
mabid/EpisodeCalendar3
/app/helpers/followings_helper.rb
UTF-8
726
2.859375
3
[]
no_license
module FollowingsHelper def print_unwatched(count) if count > 0 "<em class=\"green\">#{count} unwatched episodes</em>" else "<em>#{count} unwatched episodes</em>" end end def wasted_in_words(to) time_hash = Time.diff(Time.now, Time.now + to.minutes) wasted = [] months = time_hash[:month] days = time_hash[:day] hours = time_hash[:hour] wasted << pluralize(months.to_i, "month") if months > 0 wasted << pluralize(days.to_i, "day") if days > 0 wasted << pluralize(hours.to_i, "hour") if hours > 0 unless hours.to_i == 0 wasted.to_sentence(:last_word_connector => " and ") else pluralize(time_hash[:minute].to_i, "minute") end end end
true
0457ff2b8c103e46353abd2d9b70d9937690f5b4
Ruby
saintprug/rubytalks.org
/spec/support/request_helpers.rb
UTF-8
2,337
2.53125
3
[]
no_license
# frozen_string_literal: true module RequestHelpers APP = Hanami.app class Request def initialize(method, path, options) @path, @query_string = path.split('?', 2) @method = method @body = options[:body] @headers = options[:headers] || {} end def env default_env.tap do |env| env['PATH_INFO'] = @path env['REQUEST_METHOD'] = @method env['QUERY_STRING'] = @query_string env['rack.input'] = StringIO.new(@body) if @body @headers.each do |key, value| rack_name = key.upcase.tr('-', '_') rack_name = "HTTP_#{rack_name}" unless rack_name == 'CONTENT_TYPE' env[rack_name] = value end end end def default_env { 'SCRIPT_NAME' => '', 'SERVER_NAME' => 'localhost', 'SERVER_PORT' => '800613', 'rack.version' => [1, 3], 'rack.url_scheme' => 'http', 'rack.input' => StringIO.new, 'rack.errors' => StringIO.new, 'rack.multithread' => false, 'rack.multiprocess' => false, 'rack.run_once' => false, 'rack.hijack?' => false } end end def default_headers { 'Content-Type' => 'application/json' } end def do_request(verb, path, options) create_request(verb, path, options).then { |request| perform_request(request) } end def perform_request(request) @response = APP.call(request.env) @response.close end def create_request(verb, path, options) Request.new(verb, path, options) end def response @response end def response_status response.status end def response_headers response.headers end def response_body response.body[0] end def response_hash @response_hash ||= JSON.parse(response_body) end def response_data response_hash.fetch('data') end def get(path, options = {}) do_request('GET', path, options) end def post(path, options = {}) do_request('POST', path, options) end def patch(path, options = {}) do_request('PATCH', path, options) end def put(path, options = {}) do_request('PUT', path, options) end def options(path, options = {}) do_request('OPTIONS', path, options) end def delete(path, options = {}) do_request('DELETE', path, options) end end
true
22fe150c3dac920bb1bcfba8966487499a6083be
Ruby
haotianwang/CanvUs
/test/unit/bitmap_test.rb
UTF-8
2,676
2.734375
3
[]
no_license
require 'test_helper' class BitmapTest < ActiveSupport::TestCase # Empties the test Bitmap database and adds some test data. def setup Bitmap.destroy_all Bitmap.create(bitmap: 'bitmap_0', canvas_id: 0) Bitmap.create(bitmap: 'bitmap_1', canvas_id: 1) Bitmap.create(bitmap: 'bitmap_2', canvas_id: 2) end # Test that the correct validations are enforced on Bitmap record creation. def testValidations numBitmaps = Bitmap.all.count Bitmap.create() assert_equal(numBitmaps, Bitmap.all.count, "A Bitmap record without a canvas_id was incorrectly stored") end # Tests that empty bitmaps, which represent blank canvases, are properly stored. def testStoreEmptyBitmap numBitmaps = Bitmap.all.count Bitmap.storeBitmap('', DateTime.new(1991, 9, 19), 3) assert_equal(numBitmaps+1, Bitmap.all.count, "Empty bitmap was not stored") Bitmap.last.destroy end # Tests that nonempty bitmaps are properly stored. def testStoreNonemptyBitmap numBitmaps = Bitmap.all.count Bitmap.storeBitmap('bitmap_3', DateTime.new(1990, 4, 19), 3) assert_equal(numBitmaps+1, Bitmap.all.count, "Nonempty bitmap was not stored") Bitmap.last.destroy end # Tests that a bitmap with a duplicate canvas_id is properly stored. def testStoreBitmapDupCanvas numBitmaps = Bitmap.all.count Bitmap.storeBitmap('bitmap_3', DateTime.new(1992, 5, 19), 0) assert_equal(numBitmaps+1, Bitmap.all.count, "Bitmap was not stored") Bitmap.last.destroy end # Tests that getting a bitmap with a nonexistent canvas_id will return an empty string, # which represents a blank canvas. def testGetBitmapFailure bitmapGot = Bitmap.getBitmap(3) assert(bitmapGot.nil?, "Bitmap incorrectly retrieved") end # Tests that getBitmap will return only the latest bitmap for a particular canvas_id. def testGetBitmap Bitmap.create(bitmap: 'bitmap_3', canvas_id: 0) bitmapGot = Bitmap.getBitmap(0) assert_equal('bitmap_3', bitmapGot[:bitmap], "Bitmap incorrectly retrieved") Bitmap.last.destroy end # Tests the deletion of the oldest bitmap def testDeleteBitmap Bitmap.create(bitmap: 'bitmap_4', canvas_id: 5) Bitmap.create(bitmap: 'bitmap_5', canvas_id: 5) Bitmap.create(bitmap: 'bitmap_6', canvas_id: 5) Bitmap.create(bitmap: 'bitmap_7', canvas_id: 5) oldestBitmap = Bitmap.where("canvas_id = ?", 5).order("created_at ASC").first deletedBitmap = Bitmap.deleteBitmap(5) assert_equal(oldestBitmap, deletedBitmap, "Wrong bitmap deleted; was not the oldest one") end # Empties the test Bitmap database once again. def teardown Bitmap.destroy_all end end
true
d2788458ea9815c9444c4064845fbc86e41764ff
Ruby
tomclose/norrington_app
/app.rb
UTF-8
698
3.015625
3
[]
no_license
require 'sinatra' require 'csv' data = CSV.read('./data/norrington_over_years.csv', :col_sep => "\t") headings = data.first values = data[1..-1] values_as_hashes = values.map {|v| Hash[headings.zip(v)] } get '/' do @name = 'tom' erb :index end get '/year/:year' do | year | allowed_years = %w( 2006 2007 2008 2009 2010 2011 2012) if allowed_years.include?(year) score_column_name = "#{year} Score" @data = values_as_hashes.map do |h| [h['Name'], h['Type'], h[score_column_name]] end @data.reject! {|h| h[2].nil?} @data.sort_by! {|h| h[2] }.reverse! @year = year erb :year_ranking else @year = year erb :missing_year end end
true
ffaf12320bf58ef6c2ab57ed421cce2f8354be41
Ruby
mitio/rubocop
/lib/rubocop/cop/style/braces_around_hash_parameters.rb
UTF-8
1,952
2.703125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# encoding: utf-8 module Rubocop module Cop module Style # This cop checks for braces in method calls with hash parameters. class BracesAroundHashParameters < Cop def on_send(node) _receiver, method_name, *args = *node # Discard attr writer methods. return if method_name.to_s.end_with?('=') # Discard operator methods. return if OPERATOR_METHODS.include?(method_name) # We care only for the last argument. arg = args.last return unless non_empty_hash?(arg) if style == :no_braces && has_braces?(arg) && !all_hashes?(args) add_offence(arg, :expression, 'Redundant curly braces around a hash parameter.') elsif style == :braces && !has_braces?(arg) add_offence(arg, :expression, 'Missing curly braces around a hash parameter.') end end def autocorrect(node) @corrections << lambda do |corrector| if style == :no_braces corrector.remove(node.loc.begin) corrector.remove(node.loc.end) elsif style == :braces corrector.insert_before(node.loc.expression, '{') corrector.insert_after(node.loc.expression, '}') end end end private def non_empty_hash?(arg) arg && arg.type == :hash && arg.children.any? end def has_braces?(arg) !arg.loc.begin.nil? end def all_hashes?(args) args.length > 1 && args.all? { |a| a.type == :hash } end def style case cop_config['EnforcedStyle'] when 'braces' then :braces when 'no_braces' then :no_braces else fail 'Unknown style selected!' end end end end end end
true
208833063dec4808f04e61ce5359d09460437b4d
Ruby
tzinfo/tzinfo
/lib/tzinfo/format1/timezone_definer.rb
UTF-8
3,279
2.703125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# encoding: UTF-8 # frozen_string_literal: true module TZInfo module Format1 # Instances of {Format1::TimezoneDefiner} are yielded to TZInfo::Data # format 1 modules by {TimezoneDefinition} to allow the offsets and # transitions of the time zone to be specified. # # @private class TimezoneDefiner < Format2::TimezoneDefiner #:nodoc: undef_method :subsequent_rules # Defines an offset. # # @param id [Symbol] an arbitrary value used identify the offset in # subsequent calls to transition. It must be unique. # @param utc_offset [Integer] the base offset from UTC of the zone in # seconds. This does not include daylight savings time. # @param std_offset [Integer] the daylight savings offset from the base # offset in seconds. Typically either 0 or 3600. # @param abbreviation [Symbol] an abbreviation for the offset, for # example, `:EST` or `:EDT`. # @raise [ArgumentError] if another offset has already been defined with # the given id. def offset(id, utc_offset, std_offset, abbreviation) super(id, utc_offset, std_offset, abbreviation.to_s) end # Defines a transition to a given offset. # # Transitions must be defined in increasing time order. # # @param year [Integer] the UTC year in which the transition occurs. Used # in earlier versions of TZInfo, but now ignored. # @param month [Integer] the UTC month in which the transition occurs. # Used in earlier versions of TZInfo, but now ignored. # @param offset_id [Symbol] references the id of a previously defined # offset (see #offset). # @param timestamp_value [Integer] the time the transition occurs as an # Integer number of seconds since 1970-01-01 00:00:00 UTC ignoring leap # seconds (i.e. each day is treated as if it were 86,400 seconds long). # @param datetime_numerator [Integer] the time of the transition as the # numerator of the `Rational` returned by `DateTime#ajd`. Used in # earlier versions of TZInfo, but now ignored. # @param datetime_denominator [Integer] the time of the transition as the # denominator of the `Rational` returned by `DateTime#ajd`. Used in # earlier versions of TZInfo, but now ignored. # @raise [ArgumentError] if `offset_id` does not reference a defined # offset. # @raise [ArgumentError] if `timestamp_value` is not greater than the # `timestamp_value` of the previously defined transition. # @raise [ArgumentError] if `datetime_numerator` is specified, but # `datetime_denominator` is not. In older versions of TZInfo, it was # possible to define a transition with the `DateTime` numerator as the # 4th parameter and the denominator as the 5th parameter. This style of # definition is not used in released versions of TZInfo::Data. def transition(year, month, offset_id, timestamp_value, datetime_numerator = nil, datetime_denominator = nil) raise ArgumentError, 'DateTime-only transitions are not supported' if datetime_numerator && !datetime_denominator super(offset_id, timestamp_value) end end end end
true
86176b097154e6f120ec492fb5b5493f40373bee
Ruby
Garrett-Bodley/countdown-to-midnight
/countdown.rb
UTF-8
625
4.1875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def countdown(time) # loop function while time in seconds is greater than 0 while time > 0 # output a string of the amount of seconds left puts "#{time} SECOND(S)!" # decrement time time -= 1 end # return HAPPY NEW YEAR! "HAPPY NEW YEAR!" end def countdown_with_sleep(time) # loop function while time in seconds is greater than 0 while time > 0 # output a string of the amount of seconds left puts "#{time} SECOND(S)!" # sleep for one second sleep (1) # decrement time time -= 1 end # return HAPPY NEW YEAR! "HAPPY NEW YEAR!" end
true
05f1bedd53075e84813306e4c9f44798a72cbe43
Ruby
cclazarou/phase-0-tracks
/ruby/vampires.rb
UTF-8
2,461
4.21875
4
[]
no_license
require 'date' #VARIABLES conclusion = "Results inconclusive" current_year = Date.today.year #need to check if today is last day of year is_last_day_of_year = Date.today.year != Date.today.next_day.year age_is_right = nil allergy = nil # SURVEY puts "How many employees will be processed?" number_of_employees = gets.chomp.to_i for i in 1..number_of_employees puts "What is your name?" name = gets.chomp puts "How old are you?" age = gets.chomp puts "What year were you born?" birth_year_from_survey = gets.chomp.to_i puts "Our company cafeteria serves garlic bread. Should we order some for you (y or n)?" garlic_order = gets.chomp puts "Would you like to enroll in the company's health insurance (y or n)?" health_insurance = gets.chomp puts "Please tell us what allergies you have. If you have multiple allergies, type one allergy, hit enter/return, then type the next allergy, etc. Please type 'done' when you are finished." allergy = gets.chomp # continue asking for allergies while allergy != "done" puts "Next allergy:" allergy = gets.chomp if allergy == "sunshine" conclusion = "Probably a vampire" break end end #AGE CHECK #calculate birth year according to age recieved in survey birth_year_from_age = current_year - age.to_i #if staff member is surveyed before birthday, allow for leeway in stated birth year (1 year earlier) birth_year_from_age_allowance = birth_year_from_age-1 if is_last_day_of_year if birth_year_from_age == birth_year_from_survey age_is_right = true else age_is_right = false end else if (birth_year_from_age == birth_year_from_survey) || (birth_year_from_survey == birth_year_from_age_allowance) age_is_right = true else age_is_right = false end end #CONDITIONS if age_is_right && (garlic_order == "y" || health_insurance == "y") conclusion = "Probably not a vampire" end if !age_is_right && (garlic_order == "n" || health_insurance == "n") conclusion = "Probably a vampire" end if !age_is_right && garlic_order == "n" && health_insurance == "n" conclusion = "Almost certainly a vampire" end if name == "Drake Cula" || name == "Tu Fang" conclusion = "Definitely a vampire" end puts conclusion #end number of employees FOR loop end puts "Actually, never mind! What do these questions have to do with anything? Let's all be friends."
true
bc75db413ef8dfb01147662a366b0eacf0b84f3c
Ruby
osifoanosike/basicruby
/6/lib/vehicle.rb
UTF-8
297
3.53125
4
[]
no_license
class Vehicle def initialize(name, price) @name = name @price = price end def show_content puts "\n#{self.class} Details \nName: #{@name} \nPrice: #{@price}\nDealer: #{@dealer}" end def change_price(new_price) @price = new_price end end #trying yo split things up
true
639f7a4c06f6e33e84069c7a71b6d69803a68d31
Ruby
Mk-Etlinger/SQL-bear-organizer-lab-v-000
/lib/sql_queries.rb
UTF-8
1,012
3.078125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def selects_all_female_bears_return_name_and_age "SELECT name, age FROM bears WHERE gender = 'F';" end def selects_all_bears_names_and_orders_in_alphabetical_order "SELECT name FROM bears ORDER BY name ASC;" end def selects_all_bears_names_and_ages_that_are_alive_and_order_youngest_to_oldest "SELECT name, age FROM bears WHERE alive = 1 ORDER BY age ASC;" end def selects_oldest_bear_and_returns_name_and_age "SELECT name, MAX(age) FROM bears LIMIT 1;" end def select_youngest_bear_and_returns_name_and_age "SELECT name, MIN(age) FROM bears LIMIT 1;" end def selects_most_prominent_color_and_returns_with_count "SELECT color, COUNT(color) AS most_prominent_color FROM bears GROUP BY color ORDER BY most_prominent_color DESC LIMIT 1;" end def counts_number_of_bears_with_goofy_temperaments "SELECT COUNT(temperament) FROM bears WHERE temperament = 'goofy'" end def selects_bear_that_killed_Tim "SELECT * FROM bears WHERE temperament = 'aggressive' LIMIT 1" end
true
1e03020a131d0b47590fc2d0518ce13f2567c5d2
Ruby
swatkns785/car-listings
/spec/features/manufacturers/user_adds_manufacturer_spec.rb
UTF-8
1,841
2.90625
3
[]
no_license
require "rails_helper" feature "a user adds a manufacturer to database", %q( As a car salesperson I want to record a car manufacturer So that I can keep track of the types of cars found in the lot [x] I must specify a manufacturer name and country. [x] If I do not specify the required information, I am presented with errors. [x] If I specify the required information, the manufacturer is recorded and I am redirected to the index of manufacturers. ) do context "user meets all positive acceptance criteria" do scenario "user successfully adds a manufacturer" do manufacturer = FactoryGirl.create(:manufacturer) visit root_path expect(page).to have_link "Add Manufacturer" click_link "Add Manufacturer" expect(page).to have_content "Fill in the form below to add a manufacturer!" fill_in "Manufacturer Name", with: manufacturer.name fill_in "Country of Origin", with: manufacturer.country click_button "Submit" expect(page).to have_content "You have successfully added a manufacturer to the database." expect(page).to have_content "All of the Manufacturers" expect(page).to have_content manufacturer.name end end context "user makes mistakes while trying to add manufacturer to database" do scenario "user does not add manufacturer name correctly" do visit new_manufacturer_path fill_in "Manufacturer Name", with: "" fill_in "Country of Origin", with: "USA" click_button "Submit" expect(page).to have_content "Name is too short (minimum is 3 characters)" end scenario "user leaves fields blank" do visit new_manufacturer_path click_button "Submit" expect(page).to have_content "Name can't be blank" expect(page).to have_content "Country can't be blank" end end end
true
c75ed2585ed349da986c7899022e543426a7e5c9
Ruby
samfader/tilesets-api-cli-ruby
/lib/job.rb
UTF-8
2,071
2.703125
3
[]
no_license
require 'tty-prompt' require 'dotenv/load' require 'http' class Job @prompt = TTY::Prompt.new(enable_color: true) def self.list_all puts "Working..." result = @prompt.collect do key(:tileset_id).ask("Enter the tileset ID:", help: "The ID is composed of your username followed by a period and the tileset\'s unique name") key(:stage).select("Query for jobs at a specific processing stage:", %w(all processing queued success failed)) end puts "Working..." if result[:stage] = "all" allJobs = HTTP.get("#{ENV['BASE_URL']}/#{result[:tileset_id]}/jobs", :params => {:access_token => ENV['ACCESS_TOKEN']}) else allJobs = HTTP.get("#{ENV['BASE_URL']}/#{result[:tileset_id]}/jobs", :params => {:stage => result[:stage], :access_token => ENV['ACCESS_TOKEN']}) end ## Tilesets API returns 201 when successfully deleted if allJobs.code != 200 puts "Uh oh! You're hitting a #{allJobs.status} error. Look into the docs, then try running this script again. Here's the full response: \n #{allJobs.body.to_s}" else puts "Success! Here are the details you seek: \n #{allJobs.body.to_s}" end Index.restart end def self.retrieve_single puts "Working..." result = @prompt.collect do key(:tileset_id).ask('Enter the tileset ID:', help: "The ID is composed of your username followed by a period and the tileset\'s unique name") key(:job_id).ask('Enter the ID for the job belonging to the tileset whose status you want to check:') end puts "Working..." singleJobStatus = HTTP.get("#{ENV['BASE_URL']}/#{result[:tileset_id]}/jobs/#{result[:job_id]}", :params => {:access_token => ENV['ACCESS_TOKEN']}) if singleJobStatus.code != 200 puts "Uh oh! You're hitting a #{singleJobStatus.status} error. Look into the docs, then try running this script again. Here's the full response: \n #{singleJobStatus.body.to_s}" else puts "Success! Here are the details you seek: \n #{singleJobStatus.body.to_s}" end Index.restart end end
true
cbfc5c666c7c7846643567d15829f248857b6a8e
Ruby
ginason/ruby_fundamentals2
/exercise8.rb
UTF-8
456
3.921875
4
[]
no_license
# sum_of_expense=0 # total_expenses=[] # while true # price=gets.to_f # total_expenses.push(price) # sum_of_expense += price # puts "total expense is #{total_expenses} and sum is #{sum_of_expense}" # end def add(numbers) puts "numbers is #{numbers}" total_expenses=0 numbers.each do |i| puts "i is #{i}" total_expenses += i end puts "total expenses is #{total_expenses}" end amounts = [250, 7.95, 30.95, 16.50] puts add(amounts)
true
2c06cd0047dade6d2855032784344832beacde37
Ruby
armanbalani/app-academy-repo
/Week 4/W4D4/octupus-problems.rb
UTF-8
1,502
3.703125
4
[]
no_license
fish = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh'] def sluggish_octopus(array) array.find do |ele| array.all? do |ele2| ele.length >= ele2.length end end end def dominant_octopus(array) merge_sort(array).last end def clever_octopus(array) array.inject do |acc, ele| if acc.length >= ele.length acc else ele end end end def merge_sort(array) return array if array.length <= 1 mid_point = array.length/2 left = merge_sort(array.slice(0...mid_point)) right = merge_sort(array.slice(mid_point...array.length)) sorted_array = merge(left, right) end def merge(left_side, right_side) sorted = [] until left_side.empty? || right_side.empty? if left_side[0].length < right_side[0].length sorted.push(left_side.shift) else sorted.push(right_side.shift) end end sorted + left_side + right_side end tiles_array = ["up", "right-up", "right", "right-down", "down", "left-down", "left", "left-up" ] def slow_dance(direction, array) array.each.with_index do |ele, idx| return idx if ele == direction end end def create_hash(array) hash = {} array.each.with_index do |ele, idx| hash[ele] = idx end hash end dance_hash = create_hash(tiles_array) def fast_dance(direction, hash) hash[direction] end p fast_dance("left-up", dance_hash)
true
e918d4a4d0f5ce3499d7b27e276d704305e0e5d1
Ruby
mamarjan/bioruby-gff3-plugin
/lib/bio/output/gfffastawriter.rb
UTF-8
649
2.71875
3
[ "MIT" ]
permissive
module Bio module GFFbrowser class FastaWriter def initialize translate, validate @do_translate = translate @do_validate = validate end def put id, seq puts '>'+id put_seq id, seq end private def put_seq id, seq if @do_translate or @do_validate ntseq = Bio::Sequence::NA.new(seq) aaseq = ntseq.translate puts aaseq if @do_translate if @do_validate raise 'Validation problem of '+id if aaseq.count('*') > 1 end return if @do_translate end puts seq end end end end
true
c188b98b78166864c75013d4009713a677f0c71f
Ruby
klavinslab/protocols_aquarium_1_0
/mutagenesis_workflow/020_run_gel.rb
UTF-8
3,377
2.65625
3
[]
no_license
needs "aqualib/lib/standard" class Protocol include Standard def debug false end def arguments { stripwell_ids: [], gels_ids: [], volume: 50 # The volume of PCR fragment to load in µL } end def main stripwells = input[:stripwell_ids].collect { |i| collection_from i } gels = input[:gels_ids].collect { |i| collection_from i } volume = input[:volume] || 20 take stripwells + gels, interactive: true ladder = choose_sample "1 kb Ladder" dye = choose_object "Gel Loading Dye Blue (6X)" show { title "Set up the power supply" note "In the gel room, obtain a power supply and set it to 100 V and with a 40 minute timer." note "Attach the electrodes of an appropriate gel box lid from A7.525 to the power supply." image "gel_power_settings" } show { title "Set up the gel box(s)." check "Remove the casting tray(s) (with gel(s)) and place it(them) on the bench." check "Using the graduated cylinder at A5.305, fill the gel box(s) with 200 mL of 1X TAE from J2 at A5.500. TAE should just cover the center of the gel box(s)." check "With the gel box(s) electrodes facing away from you, place the casting tray(s) (with gel(s)) back in the gel box(s). The top lane(s) should be on your left, as the DNA will move to the right." check "Using the graduated cylinder, add 50 mL of 1X TAE from J2 at A5.500 so that the surface of the gel is covered." check "Remove the comb(s) and place them in the appropriate box(s) in A7.325." check "Put the graduated cylinder back at A5.305." image "gel_fill_TAE_to_line" } show { title "Add loading dye" note "Add #{volume / 5.0} µL of loading dye to each (used) well of the stripwells" stripwells.each do |sw| bullet "Stripwell #{sw.id}, wells #{sw.non_empty_string}" end } show { title "Load DNA ladder" gels.each do |gel| check "Using a 100 µL pipetter, pipet 10 µL of ladder (containing loading dye) from tube #{ladder} into wells 1 (top-left) and 7 (bottom left) of gel #{gel}." end image "gel_begin_loading" } gels.each do |gel| gel.set 0, 0, ladder gel.set 1, 0, ladder end transfer( stripwells, gels ) { title "Using a 100 µL pipetter, pipet #{volume} µL of each PCR result into the indicated gel lane." note "Make sure each stripwell has the leftmost well labeled with an 'A'. This well contains the first sample. The well to its right contains the second sample, etc." image "gel_begin_loading" } show { title "Start electrophoresis" note "Carefully attach the gel box lid(s) to the gel box(es), being careful not to bump the samples out of the wells. Attach the red electrode to the red terminal of the power supply, and the black electrode to the neighboring black terminal. Hit the start button on the gel boxes - usually a small running person icon." note "Make sure the power supply is not erroring (no E* messages) and that there are bubbles emerging from the platinum wires in the bottom corners of the gel box." image "gel_check_for_bubbles" } release stripwells, interactive: true release gels + [ ladder, dye ], interactive: true return input end end
true
f74adf104d26bd6d5015f458e7e8d7962245ba8f
Ruby
PianoFF/ruby-boating-school-london-web-102819
/tools/console.rb
UTF-8
1,219
2.890625
3
[]
no_license
require_relative '../config/environment.rb' def reload load 'config/environment.rb' end spongebob = Student.new("Spongebob") patrick = Student.new("Patrick") cindy = Student.new("Cindy") puff= Instructor.new("Ms.Puff") krabs= Instructor.new("Mr.Krabs") sb = Student.find_student('Spongebob') # puts "student should be spongebob: #{sb}" no_crashing = cindy.add_boating_test("Don't Crash 101", "passed", puff) power_steering_pass = cindy.add_boating_test("Power Steering 201", "passed", krabs) no_crashing = spongebob.add_boating_test("Don't Crash 101", "pending", puff) # puts "new test has been added: #{no_crashing}" power_steering_failure = patrick.add_boating_test("Power Steering 202", "failed", puff) # puts "if failed, present #{power_steering_failure}" power_steering_pass = spongebob.add_boating_test("Power Steering 201", "passed", krabs) # puts "Has spongebob passed? #{power_steering_pass}" # Insert code here to run before hitting the binding.pry # This is a convenient place to define variables and/or set up new object instances, # so they will be available to test and play around with in your console binding.pry p "endofpry"#leave this here to ensure binding.pry isn't the last line
true
d171709fd41fb1060551c944f546be92c999cca6
Ruby
noahschultz/dealesque
/app/values/cart.rb
UTF-8
348
2.671875
3
[]
no_license
class Cart attr_accessor :id, :hmac, :encoded_hmac, :purchase_url def initialize(attributes = {}) raise ArgumentError.new("Missing attributes") unless attributes {id: "", hmac: "", encoded_hmac: "", purchase_url: ""}.each do |property, default_value| send("#{property}=", attributes[property] || default_value) end end end
true
9f2049d6d28c56e74e7177dc45413ea736f678d2
Ruby
Jun-lo/tokinagara
/re.0428.rb
UTF-8
682
3.78125
4
[]
no_license
#-*- coding: utf-8 -*- #キーボードから次々と整数値を読み込んで、負でない値の合計値と平均を求めるプログラム # 読み込んだ負の整数値の数の個数は平均を求める際の分母から除外する puts "整数を加算します" print "何個加算しますか?" input = gets n = input.to_i sum = 0 count = 0 for i in 0..(n - 1) print "整数:" input = gets y = input.to_i if (y < 0) puts "負の数は加算しません。" end sum += y count += 1 end puts "合計は#{sum}です。" if (count != 0) print "平均は#{sum / count}です。" end #0以下の場合加算しない処理がわからない
true
8f301f26af0fd5bfb576ffdf391c639243b1edde
Ruby
derbya/Hackerrank_Projects
/30 Days of Code/Day 3: Intro to Conditional Statements/ruby.rb
UTF-8
535
3.53125
4
[]
no_license
#!/bin/ruby require 'json' require 'stringio' #I was playing around with procs to see what I could do. A lot of this in not needed. N = gets.to_i lessThanSix = proc {|x| (2..5).each do |n| if n == x puts "Not Weird" end end } moreThanSix = proc {|x| (6..20).each do |n| if n == x puts "Weird" end end } lessThanTwenty = proc {|x| x >= 6 ? moreThanSix.(x) : lessThanSix.(x)} iseven = proc {|x| x > 20 ? (puts "Not Weird") : lessThanTwenty.(x)} if N.odd? then puts "Weird" else iseven.(N) end
true
e4c3fbb2a8f0e2c777557c627d18064fdffb83b0
Ruby
jasonliz85/PartnerManage
/app/models/bridge.rb
UTF-8
9,439
2.625
3
[]
no_license
class Bridge < ActiveRecord::Base has_event_calendar #validations validates_presence_of :start_at, :end_at, :name validates :start_at, :uniqueness => true #scopes #relationships #callbacks #functions def update_bridge!() #checks whether bridge has been updated (added new shifts) since it was created if self.update_needed? and not self.bridge_table.nil? #do update algorithm print "Update Needed?: " puts self.update_needed self. return true end return false end def get_bridge_info() #returns the bridge table and bridge stats column in the database if self.bridge_table.nil? or self.bridge_stats.nil? return [false, false] else return [JSON.parse(self.bridge_table), JSON.parse(self.bridge_stats) ] end end def self.find_bridge_on(date) #finds the bridge on the given date return find_bridge_on_date_range(date, date).first end def self.find_bridge_on_date_range(date_from, date_to) #finds the bridge on the given date range bridges = where("start_at > ? AND start_at < ?", date_from.beginning_of_day(), date_to.end_of_day()) return bridges end def self.get_partner_object_from_shift(shifts_working) #simply returns the partner linked to each shift (i.e. shift.partner) partners = [] shifts_working.each {|shift| partners << shift.partner } return partners end def self.create_bridge!(date, break_slots) b_table, b_stats = create_bridge_table_and_stats(date, break_slots) self.create(:name => "Bridge", :start_at => date.beginning_of_day(), :end_at => date.end_of_day(), :bridge_table => b_table.to_json, :bridge_stats => b_stats.to_json, :color => '#3366FF' ) return [b_table, b_stats] end def self.create_bridge_table_and_stats(date, break_slots) #this function creates the bridge table format for the bridge page. #Each row has one competency and several partners, representing a row in the bridge table table = {} stats = {} competencies = Competency.find_all_by_priority(2).map {|f| f.name} important_competencies = Competency.find_all_by_priority(1).map {|f| f.name }#['Sasu','Task Team'] shifts_working, shifts_not_working, shift_types = Shift.find_all_partners_who_are_working_on_date(date) stats['shift_types'] = shift_types if not shifts_working.empty? #partners = get_partner_object_from_shift(shifts_working) #partners_not_working = get_partner_object_from_shift(shifts_not_working) stats['partners_working'] = shifts_working.map{|shift| extract_partner_and_shift_info(shift)} stats['partners_not_working'] = shifts_not_working.map{|shift| extract_partner_and_shift_info(shift)} stats['total_working'] = shifts_working.count #1.find managers and separate table['Manager'] = {} managers, partners_left_shifts = find_all_managers_from(shifts_working) stats['total_managers'] = managers.count table['Manager'] = sort_partners_into_breaks(managers, break_slots) stats['competencies'] = {} #2.find important sections and separate [in Audio and TV: Sasu and Task Team] important_competencies.each do |competency| table[competency] = {} partners, partners_left_shifts = find_all_partners_with_competency(partners_left_shifts, competency) stats['competencies'][competency] = partners.count table[competency] = sort_partners_into_breaks(partners, break_slots) end #3.Sort all other partners sorted_partners_with_competences = sort_partners_into_competencies(partners_left_shifts, competencies, important_competencies) sorted_partners_with_competences.each_pair do |competency, partners| stats['competencies'][competency] = partners.count table[competency] = sort_partners_into_breaks(partners, break_slots) end end return [table, stats] #combine results #bridge_row = bridge_row_manager + bridge_row + bridge_row_sasu + bridge_row_task end protected class Array #functions (shuffle and shuffle!) which will shuffle randomly an array def shuffle sort_by { rand } end def shuffle! self.replace shuffle end end def self.extract_partner_and_shift_info(shift) return {'start_at' => shift.start_at.to_s, 'end_at' => shift.end_at.to_s, 'shift_type'=> shift.shift_type, 'first_name'=> shift.partner.first_name, 'last_name' => shift.partner.last_name, 'partner_id'=> shift.partner.id, 'is_manager'=> shift.partner.is_manager } end def self.find_all_managers_from(partners_shift) #this function simply finds all the is_manager fields from the partner(s) object managers = [] non_managers =[] partners_shift.each do |shift| shift.partner.is_manager ? managers << extract_partner_and_shift_info(shift): non_managers << shift end return [managers, non_managers] end def self.find_all_partners_with_competency(partners_shift, competency) #this function finds all the partners who match the input competency partners_competent = [] partners_not_competent = [] partners_shift.each do |shift| shift.partner.is_competent_at(competency) ? partners_competent << extract_partner_and_shift_info(shift): partners_not_competent << shift end return [partners_competent, partners_not_competent] end def self.sort_partners_into_competencies(partners_shift, sections, excluded_sections) #this function sorts and groups a list of partners into a hash of competencies (section) #i.e. fits partners into a section #warning, potential problem if partner.competencies != sections #initialise variables grouped_partners = {} sections.each do |section| grouped_partners[section] = [] end #first, find all partners without a competency - add these later partners_with_no_competency = [] partners_shift.each do |shift| if shift.partner.competencies.empty? partners_with_no_competency << shift partners_shift.delete(shift) end end #now whilst partner list is not empty, loop through each competency #and allocate a partner to this competency checked_sections = [] repeat = true while not partners_shift.empty? #shuffle competencies sections.shuffle! while repeat #find section with lowest number of partners, if more than one with the lowest #then between these lowest numbers choose it at rand lowest_sections = [] set = 0 grouped_partners.each_pair do |section, list_of_partners| if checked_sections.include?(section) next #skip elsif set == 0 set = 1 lowest_sections << section next elsif list_of_partners.count < grouped_partners[lowest_sections.first].count lowest_sections.clear() lowest_sections << section elsif list_of_partners.count == grouped_partners[lowest_sections.first].count lowest_sections << section end end if lowest_sections.count > 1 current_section = lowest_sections[rand(lowest_sections.length)] else current_section = lowest_sections.first end #once section chosen, allocate a partner to it's list #to do this, loop through the partners list and find a partner with a competency that matches #its section partners_shift.shuffle! partners_shift.each do |shift| #skip partners who have only one competency and belong to excluded sections (such as Sasu and Task Team) if shift.partner.competencies.count == 1 and excluded_sections.include?(shift.partner.competencies.first.name) partners_shift.delete(shift) next end shift.partner.competencies.each do |partner_competency| if excluded_sections.include?(partner_competency.name) next #skip elsif not sections.include?(partner_competency.name) #this case must not happen, as it can potentially cause an infinite loop return [] elsif partner_competency.name == current_section grouped_partners[current_section] << extract_partner_and_shift_info(shift)#partner.to_json #{ :start_at => shift.start_at, :end_at => shift.end_at, :shift_type => shift.shift_type, } partners_shift.delete(shift) repeat = false break end end if shift == partners_shift.last checked_sections << current_section end end if checked_sections.length == grouped_partners.length repeat = false end end checked_sections.clear() repeat = true end #now deal with partners without competencies #partners_with_no_competency?? return grouped_partners end def self.sort_partners_into_breaks(partners, break_slots) #this function sorts the given partner objects into the break slots #more intelligence in allocating a break slot is needed slots = {} shuffled_partners = partners.shuffle! for break_no in 1..break_slots do slots[break_no] = [] shuffled_partners.each do |partner| if slots[break_no].empty? slots[break_no] << partner shuffled_partners.delete(partner) end end end return slots end end # == Schema Information # # Table name: bridges # # id :integer not null, primary key # name :string(255) # start_at :datetime # end_at :datetime # color :string(255) # created_at :datetime # updated_at :datetime # bridge_table :text # bridge_stats :text # update_needed :boolean default(FALSE) #
true
9f9619b009b95360937ebfa5a105efc3fd5d9836
Ruby
henkm/leisureking
/lib/leisureking/authentication.rb
UTF-8
1,102
2.59375
3
[ "MIT" ]
permissive
module LeisureKing::Authentication require 'digest' require 'jwt' require 'base64' require 'openssl' # The communication layer implements all the methods available in the LeisureKing API class << self attr_accessor :token # Set's the default value's to nil and false # @return [Hash] conguration options def init! @defaults = { :@token => nil, } end def get_token body = { apikey: LeisureKing::Config.api_key, secret: LeisureKing::Config.api_secret } result = LeisureKing::API.send_request("authenticate", body) if result["status"] && result["status"] == "OK" self.token = result["data"]["token"] end return result end # Parses the current API key and checks if the 'exp' attribute # represents a date in the future. def has_valid_api_key return self.token != nil && api_key_valid_until > Time.now end def api_key_valid_until decoded_token = JWT.decode self.token, nil, false Time.at(decoded_token.first["exp"]) end end init! end
true
6ab8dacc746f9aea6d0f0d6ffa98d2bf808ae1d0
Ruby
nateberkopec/Marks-Fake-Facts
/server.rb
UTF-8
960
2.90625
3
[]
no_license
require './initializer' class Mark def generate_fact candidate = gabbler if (110..140) === candidate.length && good_grammar?(candidate) return candidate else generate_tweet end end def initialize(dict_location = 'dictionaries/hot.txt') @dict_location = dict_location end def gabbler unless @gabbler @gabbler = Gabbler.new(:depth => 3) @gabbler.learn(File.read(@dict_location)) end @gabbler end private def good_grammar?(string) grammar_checker = Mechanize.new { |agent| agent.user_agent_alias = 'Mac Safari' } page = grammar_checker.get('http://www.link.cs.cmu.edu/link/submit-sentence-4.html') sentence_form = page.forms.first sentence_form.fields.first.value = string result = grammar_checker.submit(sentence_form) linkages = result.search('pre').last.content return true unless linkages['No linkages found'] || linkages['Found 1 linkage'] end end
true
36dd58bf7621078d271f6d322b873955b0e2aaae
Ruby
juliesof/wdi_1_ruby_lab_apartments
/lib/tenant.rb
UTF-8
835
3.28125
3
[]
no_license
require 'pry' class Tenant attr_reader :first_name, :age, :credit_score attr_accessor :last_name def initialize(first_name:, last_name:, age:, credit_score:) @first_name = first_name @last_name = last_name @full_name = last_name + ', ' + first_name @age = age @credit_score = credit_score end def credit_rating#(credit_score:)already have thiss avail #returns the string in credit_rating case credit_score when credit_score >= 760 credit_rating = 'Excellent' when credit_score >= 725 credit_rating = 'Great' when credit_score >= 660 credit_rating = 'Good' when credit_score >= 560 credit_rating = 'Mediocre' else #NEEDS else rather than ending in while bc then the else defaults to nil credit_rating = 'Bad' end end end
true
18006cb754c8e6f4f581dd46790b986ff4fe55b7
Ruby
emdurr/devpoint-casino
/craps_win.rb
UTF-8
4,563
3.5
4
[]
no_license
require 'pry' require_relative 'user_input.rb' require_relative 'dice_images.rb' require_relative 'dice_roll.rb' class CrapsWin attr_accessor :player, :game def initialize#(player, game) @player = player @game = game @available_bets = ['Pass Line', "Don't Pass Line", 'Place Bet, Place Bet to Lose, Buy Bet, or Lay Bet', 'Field', 'Any 7', 'Any Craps', 'Snake Eyes', 'Twelve Craps', 'Hard Bet', 'Three Craps', 'Six Five', 'Horn Bet'] @bets = ['Place Bet', 'Place Bet to Lose', 'Buy Bet', 'Lay Bet'] @bet_potential = [] @bet_placed = [] @dice_options = [{'total' => 2, 'saying' => 'Aces!'}, {'total' => 3, 'saying' => 'Ace deuce!'}, {'total' => 4, 'saying' => 'Four!'}, {'total' => 5, 'saying' => 'Fever!'}, {'total' => 6, 'saying' => 'She-hix!'}, {'total' => 7, 'saying' => 'Seven!'}, {'total' => 8, 'saying' => 'Eight!'}, {'total' => 9, 'saying' => 'Centerfield nine!'}, {'total' => 10, 'saying' => 'Tennessee!'}, {'total' => 11, 'saying' => 'Yo-leven!'}, {'total' => 12, 'saying' => 'Full Boat!'} ] end def first_bet counter = 1 puts "Choose your bet:" @available_bets.each do |list| puts "#{counter}. #{list}" counter += 1 end @user_input = UserInput.new(@player, @game) user_input_a = @user_input.gather.to_i bet_poss = @available_bets[user_input_a -1] if @available_bets.include?(bet_poss) if bet_poss == 'Place Bet, Place Bet to Lose, Buy Bet, or Lay Bet' place_bet elsif bet_poss == 'Hard Bet' hard_bet else puts "Bet placed on #{bet_poss}!" end else puts "Invalid selection! Please try again!" first_bet end @bet_potential << bet_poss bet_amount end def place_bet options = [4, 5, 6, 8, 9, 10] puts "Which bet type would you like to place?" puts @bets.join(", ") user_input_1 = gets.strip if @bets.include? user_input_1 puts "Which number would you like to place your bet on?" puts options.join(" ") user_input = gets.to_i if options.include? user_input puts "Bet placed on #{user_input}" else puts "Invalid selection! Please try again." place_bet end else puts "Invalid selection! Please try again." place_bet end bet_placed_1 = user_input_1 + ' ' + user_input.to_s @bet_potential << bet_placed_1 bet_amount end def hard_bet options = [4, 6, 8, 10] puts "Which number do you bet will be rolled hard?" user_input_2 = gets.to_i if options.include? user_input_2 puts "Bet placed on Hard #{user_input_2}" else puts "Invalid selection! Please try again" hard_bet end hard_bet_placed = 'Hard ' + user_input_2.to_s @bet_potential << hard_bet_placed end def bet_amount puts "How much will you be betting on #{@bet_potential.last}?" user_input = UserInput.new(@player, @game) user_input_a = @user_input.gather.to_i puts "You're betting #{user_input_a} on #{@bet_potential.last}." puts "Is that correct? y/n" user_input_3 = gets.strip.downcase if user_input_3 == 'y' @bet_placed << {bet: @bet_potential.last, betamount: user_input_a} puts "Excellent!" again elsif user_input_3 == 'n' puts "Alright...Let's try this again..." bet_amount else puts "Invalid Selection. Try again." bet_amount end end def again puts "Would you like to place another bet? y/n" user_input_4 = gets.strip.downcase if user_input_4 == 'y' first_bet elsif user_input_4 == 'n' puts "Perfect! Choose your dice!!" choose = DiceImages.new choose.dice_sample rolling else puts "You're not very good at this, are you? Try again :/" again end end def rolling pics = DiceImages.new puts "Dice out!" puts puts " **** Rolling ****" puts roll_the_dice = Dice.new roll_the_dice.roll binding.pry puts pics.dice_arr.sample sleep 0.5 puts pics.dice_arr.sample sleep 0.5 puts pics.dice_arr.sample sleep 0.5 puts puts puts puts pics.dice_arr[roll_the_dice.die1 - 1] puts pics.dice_arr[roll_the_dice.die2 - 1] puts roll_the_dice.show_dice @total = roll_the_dice.sum_total puts "#{@dice_options[@total - 2]['saying']}" puts # bet_resolution end end lets_begin = CrapsWin.new#(player, game) lets_begin.first_bet
true
0e7ef68126d9e0ed2b12c230b8ae2f870590a72e
Ruby
dchopson/guitar_builder
/app/models/order.rb
UTF-8
3,093
2.53125
3
[]
no_license
class Order < ActiveRecord::Base belongs_to :user has_many :guitars, dependent: :destroy accepts_nested_attributes_for :guitars i18n_scope = [:models, :order] STATUSES = { complete: I18n.t('statuses.complete', scope: i18n_scope), in_progress: I18n.t('statuses.in_progress', scope: i18n_scope), pending: I18n.t('statuses.pending', scope: i18n_scope) } scope :pending, -> { where(status: STATUSES[:pending]) } scope :in_progress, -> { where(status: STATUSES[:in_progress]) } scope :created_today, -> { where(created_at: Date.today) } after_initialize :set_completion_date before_create :set_status, :set_number validate :price_matches_options def self.method_missing(method, *args) order_const = Order.const_get(method.upcase) return order_const unless order_const.is_a?(Hash) order_const.map{|_,v| v} end # @return [String] concatentation of first and last names def name "#{last_name}, #{first_name}" end # @return [Boolean] is the order paid for? def paid? purchased_at.present? end # @return [Integer] the price converted from dollars to cents def price_in_cents price * 100 end # Sets the token value. Retrieves additional buyer attributes from the gateway # and sets them as well # @param token [String] the token received from PayPal def express_token=(token) write_attribute(:express_token, token) if token.present? details = EXPRESS_GATEWAY.details_for(token) self.express_payer_id = details.payer_id params = details.params.with_indifferent_access # self.email = params[:payer] self.first_name = params[:first_name] self.last_name = params[:last_name] self.telephone = params[:phone] self.address = "#{params[:street1]}\n"\ "#{"#{params[:street2]}\n" if params[:street2]}"\ "#{params[:city_name]}, #{params[:state_or_province]} #{params[:postal_code]}\n"\ "#{params[:country_name]}" end end # Completes the purchase on the PayPal side # @return [Boolean] was the purchase successful? def purchase! response = process_purchase update_attribute(:purchased_at, DateTime.now) if response.success? response.success? end private def set_completion_date if self.new_record? wait_time = Order.pending.count + Order.in_progress.count + 15 self.completion_date = Date.today + wait_time.days end end def set_status self.status = STATUSES[:pending] end def set_number random = SecureRandom.urlsafe_base64(6) random.gsub('-', 'a') random.gsub('_', '9') self.number = random.upcase end # TODO assumes 1 guitar per order def price_matches_options unless guitars.all? {|g| g.total_of_selected == price} errors.add(:price, 'does not match selected options') end end def process_purchase EXPRESS_GATEWAY.purchase(price_in_cents, express_purchase_options) end def express_purchase_options { # :ip => ip_address, :token => express_token, :payer_id => express_payer_id } end end
true
8fb2f69a01eaee5943ac80eccf81e3e2dff3dd85
Ruby
naveed-ahmad/productivity-scripts
/git/commit-msg
UTF-8
933
3.078125
3
[]
no_license
#!/usr/bin/env ruby # # Script for appending the pivotal id of a story to the commits # Branches must begin with st{pivotal_story_id}_description_here # # Reads the pivotal story from the branch name and appends it to the # commit messages. Supports the following formats # # Examples: # st{#pivotal_id}_commit_description_here # hotfix/st{#pivotal_id}_commit_description_here # feature/st{#pivotal_id}_commit_description_here # # Sohaib Talaat Bhatti -- sohaibbbhatti@gmail.com # sohaibbbhatti.wordpress.org branch_name = `git branch`[/\* (.+)/] story_subset = branch_name[/\* ((feature\/)|(hotfix\/)){0,1}st(\d+)/] pivotal_story_id = "[##{story_subset[/\d+/]}]" if story_subset message_file = ARGV[0] message = File.read(message_file) message = if pivotal_story_id message.empty? ? message : [pivotal_story_id, message].join(' ') else message end File.open(message_file, 'w') { |f| f.write message }
true
7aa87189035fae3a1367bc594e0c2f4be57232ae
Ruby
Elizabeth-Roche/phase-0
/week-6/die-2/my_solution.rb
UTF-8
1,889
4.46875
4
[ "MIT" ]
permissive
# Die Class 2: Arbitrary Symbols # I worked on this challenge [by myself, with: ]. # I spent [#] hours on this challenge. # Pseudocode # Input: an array of strings # Output: a random string from the input array # Steps: raise an argumenterror if labels size is less than one #create method sides that returns the size of sides #create a method that returns a random string of the labels_array when called # Initial Solution # class Die # def initialize(labels) # raise ArgumentError.new("dice must have 1 or more strings") if labels.length < 1 # @labels = labels # end # def sides # return @labels.length # end # def roll # return @labels.sample # end # end # Refactored Solution class Die def initialize(labels) @labels = labels raise ArgumentError.new("dice must have 1 or more strings") if @labels.empty? end def sides return @labels.length end def roll return @labels.sample end end # Reflection #What were the main differences between this die class and the last one you created in terms of implementation? Did you need to change much logic to get this to work? #This was very similar to the logic used in the last die class challenge. The big difference was that the contents of the array were strings rather than integers. #What does this exercise teach you about making code that is easily changeable or modifiable? #This challenge showed the importance of creating code that is easy to modify. #What new methods did you learn when working on this challenge, if any? #I used sample in this code! At first, I wanted to use rand but quickly realized that it was not an approproate choice. Sample was used to grab a random element of the array. #What concepts about classes were you able to solidify in this challenge? #I have a better understanding of instance variables after working through this challenge.
true
97269ba0a0e57fb8d815bd7f2f70a29ab2206bb9
Ruby
kmorcinek/apihack
/app/domain/int_matcher.rb
UTF-8
124
2.578125
3
[ "MIT" ]
permissive
class IntMatcher def ===(other) other.kind_of?(Integer) end def as_json(options={}) "[an integer]" end end
true
d0b59885a6c5114f2f2c4d09827c923ea16f6628
Ruby
jukinner/Coding-Practice-Codewars-Codility-Hackerrank-etc.-
/User_class_with_block.rb
UTF-8
1,362
4
4
[]
no_license
# Build a User Class that Can Be Passed a Block to Set Its Values # In this Ruby coding exercise your knowledge of blocks will be tested. The requirement is to build a User class that can be created and passed a block to set its values in addition to the traditional process for setting an object's data. # Summary # Build a User Class that Can Be Passed a Block to Set Its Values. # Exercise Description # In order to properly pass this coding exercise you'll need to create a Ruby User class that is flexible enough to take a block along with the traditional data setting process.. # Examples # user = User.new do |u| # u.name = "Jordan" # u.email = "test@test.com" # end # user.name # 'Jordan' # user.email # 'test@test.com' # Should work, along with: # user = User.new # user.name = "Jordan" # user.email = "test@test.com" # user.name # 'Jordan' # user.email # 'test@test.com' require 'rspec' describe 'Block User' do it 'Allows a user to be created with a block of values' do user = User.new do |u| u.name = "Jordan" u.email = "test@test.com" end expect(user.name).to eq('Jordan') expect(user.email).to eq('test@test.com') end it 'Allows a user to be created witout default values' do user = User.new user.name = "Jordan" user.email = "test@test.com" expect(user.name).to eq('Jordan') expect(user.email).to eq('test@test.com') end end
true
b57f08c7c87f7afa3b63e6b24332f7db53f67ff0
Ruby
menge101/merkle
/lib/merkle_tree.rb
UTF-8
4,228
3.5625
4
[]
no_license
# frozen_string_literal: true require 'ruby-xxhash' # Implementation of a Merkle tree # This implementation is for exploring the details of the data structure # It is not meant to be a servicable production library # A non-cryptographically secure library is used for creating the hashes # it has the benefit of being extremely fast, at the expense of security # which is just fine for non-production use. # # @author Nathan Menge # @attr_reader [Integer] root The root of the Merkle tree # @attr_reader [Array] leaves An array containing all of the leaf nodes of the tree class MerkleTree attr_reader :root, :leaves DEFAULT_HASH_METHOD = XXhash.method(:xxh64) # Constructor # @param [Array] leaves Takes an optional Array of values to add to the tree # @return [Integer, nil] Returns the value of the root node def initialize(leaves = [], hash_method: DEFAULT_HASH_METHOD) @leaves = leaves @history = {} @partners = {} @hash_method = hash_method @root = build(@leaves) end # Adds values to the tree # @param [Array, #to_s] *values Can take any number of #to_s-able objects either as arguments and/or as an array # @return [Integer, nil] Returns the root node value def add(*values) keys = values.flatten.map do |value| key = create_hash(value) @history[value] = key end @leaves.concat(keys) @root = build(@leaves) end # Finds the path from value to root in a built Merkle tree # @param [#to_s] value A value to start from # @return [Array] Returns an array of hashes that represent the complementary values to reach the root def path(value) result = create_hash(value) tree_path = [] until result == @root raise(ArgumentError, 'Value is not part of this tree') unless @partners.key?(result) partner = @partners[result] tree_path << partner result = self.class.hash_parents(result, partner) end tree_path end private # Builds the merkle tree by joining keys and hashing them # @param [Array] leaves Takes an array of Integers(hash strings) that represent all the leaves to the tree # @return [Integer, nil] Returns the root key def build(leaves) return nil if leaves.empty? branches = leaves.dup branches << hash_parents(*branches.slice!(0, 2)) until branches.length == 1 branches.first end # Creates a key from a value # @param [#to_s] value Takes a value to hash to a key # @return [Integer] Returns a hashed value def create_hash(value) value = value.to_s unless value.respond_to?(:downcase) key = self.class.create_hash(value, hash_method: @hash_method) @history[value] = key end # Creates a key from parent keys # @param [Array, #to_s] *parents Takes either an Array and/or any number of arguments of to_s-able values # @return [Integer] Returns a hashed value def hash_parents(*parents) @partners[parents.first] = parents.last @partners[parents.last] = parents.first create_hash(self.class.parent_hash_string(parents)) end # This method handles the actual hashing of values # @param [#to_s] value A value to hash # @param [#call] hash_method A method to use to create a hash def self.create_hash(value, hash_method: DEFAULT_HASH_METHOD) hash_method.call(value.to_s) end def self.hash_parents(*parents, hash_method: DEFAULT_HASH_METHOD) create_hash(parent_hash_string(parents), hash_method: hash_method) end def self.parent_hash_string(*parents) parents.flatten.map(&:to_s).sort.join('') end # This method will verify that a given value and path to root, actually reaches the root node # @param [#to_s] value Value for which inclusion in the tree will be verified # @param [Array] path An array of complementary hash values that should lead to the root node # @param [#to_s] root Root value to verify inclusion of the value param along the given path # @return [true, false] Returns a boolean value true for value is part of root, false for not def self.verify(value, path, root, hash_method: DEFAULT_HASH_METHOD) root == path.reduce(create_hash(value, hash_method: hash_method)) do |acc, node| hash_parents(acc, node, hash_method: hash_method) end end end
true
d3e2f28c5c07439f5505108b1f1d337d958c5bf2
Ruby
DouglasDDo/Data-Structures-and-Algorithms
/data_structures/heaps/ruby/binary_heap_arr_rep.rb
UTF-8
4,665
3.828125
4
[]
no_license
# Objective: Implement a min/max heap using an array-representation of nodes # Defaults to min heap; Pass in a > b proc for max heap class Heap attr_reader :nodes def initialize(opts = {}) @comparator = opts.fetch(:comparator, Proc.new {|a,b| a < b}) @nodes = Heap.build_heap!(opts.fetch(:nodes, Array.new), @comparator) end def peek @nodes.first end def empty? @nodes.empty? end def size @nodes.size end # def insert(new_node) @nodes << new_node heapify_up @nodes end alias :push :insert # Default: Remove and return root # With args: Remove and return node at given index def extract(current_idx = 0) # Cover the empty case return nil if empty? # Account for negative indexes current_idx = current_idx < 0 ? size + current_idx : current_idx raise ArgumentError, "The index provided is out of bounds." if current_idx >= size # Cover the easy case of just one el return @nodes.shift if size == 1 # Assign extracted node to a var for returning # Pop off the last leaf node and assign its value to current index node extracted_node, @nodes[current_idx] = @nodes[current_idx], @nodes.pop Heap.heapify_down!(current_idx, @nodes, @comparator) # Return the extracted node extracted_node end alias :shift :extract # TODO: Implement later def update_at(index, value) end # Join two heaps to form a valid new heap but preserve the original two def self.merge(heap_1, heap_2, comparator = Proc.new {|a,b| a < b}) all_nodes = heap_1.nodes.dup.concat(heap_2.nodes) Heap.new(nodes: all_nodes, comparator: comparator) end protected # Defaults to last index but can use input for updating node def heapify_up(current_idx = size - 1) # Account for negative indexes current_idx = current_idx < 0 ? size + current_idx : current_idx raise ArgumentError, "The index provided is out of bounds." if current_idx >= size while current_idx > 0 # Formula for parent index of any child node: P(i) = ((i + 1) / 2) - 1 # parent_idx = ((current_idx + 1) / 2).floor - 1 parent_idx = ((current_idx + 1) / 2) - 1 # Based on outcome of yielding comparator if @comparator.yield(@nodes[current_idx], @nodes[parent_idx]) # Swap the positions @nodes[current_idx], @nodes[parent_idx] = @nodes[parent_idx], @nodes[current_idx] # Set current index to previous parent index so that the process # can continue and check with the parent node current_idx = parent_idx else # Break out of the loop if comparator yields false break end end end # NOTE: I made this a class method because I wanted to use the same logic # in the Heap.build_heap! method without having to repeat myself def self.heapify_down!(current_idx, arr, comparator) loop do # Formula for left child index of any node: L(i) = ((i + 1) * 2) - 1 left_idx = ((current_idx + 1) * 2) - 1 # Formula for right child index of any node: R(i) = L(i) + 1 right_idx = left_idx + 1 # Assign left index as the default next node next_idx = left_idx # Exit loop if left index is out of bounds break if left_idx >= arr.size # If there is a valid right index, we need to compare it with the left index if right_idx < arr.size # If max & right node > left node OR # If min & right node < left node # Assign right index to next index next_idx = right_idx if comparator.yield(arr[right_idx], arr[left_idx]) end # Before any swap # If max & current > next OR # If min & current < next # Exit loop break if comparator.yield(arr[current_idx], arr[next_idx]) # Swap current and next arr[next_idx], arr[current_idx] = arr[current_idx], arr[next_idx] # Set current to next and loop back current_idx = next_idx end end def self.build_heap!(arr, comparator = Proc.new {|a,b| a < b}) raise ArgumentError, "The argument given must be an Array" unless arr.is_a?(Array) return arr if arr.size <= 1 # Heapify down, moving up in the heap, starting at the last parent (arr.size/2).downto(0) do |i| current_idx = i Heap.heapify_down!(current_idx, arr, comparator) end arr end end min = {nodes: [1,2,3,4,9,5,10,14,6]} max = {nodes: [6, 14, 10, 5, 9, 4, 3, 2, 1], comparator: Proc.new {|a,b| a > b}} unsorted = {nodes: [5,4,2,7,8,1]} maxHeap = Heap.new(max) minHeap = Heap.new(min) randomMinHeap = Heap.new(unsorted) p maxHeap.nodes maxHeap.update_at(1,2) p randomMinHeap.nodes
true
6b54567a5814a137ca7184b93c973339f974d3da
Ruby
ElliotOlbright/sweater_weather
/app/POROS/forecast.rb
UTF-8
305
3.171875
3
[]
no_license
class Forecast attr_reader :daily, :hourly, :current, :id def initialize(current_weather, five_day_weather, hourly_weather) @id = nil @current = current_weather @daily = five_day_weather @hourly = hourly_weather end end
true
0282dd2f7947f9c0f579a24c17a806cd00436861
Ruby
Himuravidal/E9CP1A1
/Ejercicio06.rb
UTF-8
469
3.234375
3
[]
no_license
class Product attr_reader :name, :tallas def initialize(name, *tallas) @name = name @tallas = tallas.map(& :to_i) end def average @tallas.inject(& :+) / @tallas.size.to_f end end products_list = [] data = [] File.open('catalogo.txt', 'r') { |file| data = file.readlines } data.each do |prod| ls = prod.split(', ') products_list << Product.new(*ls) end products_list.each do |product| puts product.name puts product.average end
true
c13ca6920ee935ec52c41e5467f186d79b58adac
Ruby
cradle/todoist
/todoist.rb
UTF-8
441
2.5625
3
[]
no_license
#!/usr/bin/ruby1.8 require 'rubygems' require 'json' require 'net/http' class Todoist def initialize(token) @token = token end def projects get_action('getProjects') end def labels get_action('getLabels') end private def get_action(action) JSON.parse(Net::HTTP.get(base_uri(action))) end def base_uri(action, params = nil) URI.parse("http://todoist.com/API/#{action}?token=#{@token}") end end
true
ace48f9cd8c9d0c8d4a9a1719f2bd278f495f4d1
Ruby
tomoasleep/yoda
/lib/yoda/server/server_controller/progress_reporter.rb
UTF-8
2,695
2.609375
3
[ "MIT" ]
permissive
module Yoda class Server class ServerController class ProgressReporter # @param [String, Integer, nil] attr_reader :work_done_token # @param [String, Integer, nil] attr_reader :partial_result_token # @param [Notifier] attr_reader :notifier # @param [Array] attr_reader :results class << self # @param work_done_token [String] # @param title [String] # @yield [reporter] # @yieldparam reporter [ProgressReporter] def in_workdone_progress(work_done_token:, title:, notifier:, &block) in_partial_result_progress( work_done_token: work_done_token, partial_result_token: nil, notifier: notifier, title: title, &block ) end # @param work_done_token [String] # @param partial_result_token [String, nil] # @param title [String] # @yield [reporter] # @yieldparam reporter [ProgressReporter] def in_partial_result_progress(work_done_token:, partial_result_token:, notifier:, title:) reporter = ProgressReporter.new( work_done_token: work_done_token, partial_result_token: partial_result_token, notifier: notifier, ) reporter.send_begin(title: title) yield reporter reporter.results ensure reporter.send_end end end # @param work_done_token [String, Integer, nil] # @param partial_result_token [String, Integer, nil] # @param notifier [Notifier] def initialize(work_done_token:, partial_result_token:, notifier:) @work_done_token = work_done_token @partial_result_token = partial_result_token @notifier = notifier @results = [] end def send_begin(**kwargs) if work_done_token notifier.work_done_progress_begin(token: work_done_token, **kwargs) end end def send_end(**kwargs) if work_done_token notifier.work_done_progress_end(token: work_done_token, **kwargs) end end def report(**kwargs) if work_done_token notifier.work_done_progress_report(token: work_done_token, **kwargs) end end def send_result(value) if partial_result_token notifier.partial_result(token: partial_result_token, value: value) else results.push(value) end end end end end end
true
7d2893216773ffae1e54da85d2bea90bf76de282
Ruby
mjc/genealogy
/spec/genealogy/model_settings_spec.rb
UTF-8
4,181
2.515625
3
[ "MIT" ]
permissive
require 'spec_helper' module ModelSettingsSpec extend GenealogyTestModel describe "*** Model and table settings ***" do before(:each) do ModelSettingsSpec.define_test_model_class(has_parents_opts) end describe 'model with options :father_column => "padre", :mother_column => "madre", :current_spouse => true, :current_spouse_column => "partner", :sex_column => "gender"' do let(:has_parents_opts) { {:father_column => "padre", :mother_column => "madre", :current_spouse => true, :current_spouse_column => "partner", :sex_column => "gender"} } {:father_column => "padre", :mother_column => "madre", :current_spouse_column => "partner", :sex_column => "gender"} .each do |attr,col_name| it "should have #{col_name} as #{attr} attribute" do TestModel.send(attr).should == col_name end it "should have db column named #{col_name}" do TestModel.column_names.should include(col_name) end end it "should have 'M' as sex_male_value" do TestModel.sex_male_value.should == 'M' end it "should have 'F' as sex_female_value" do TestModel.sex_female_value.should == 'F' end end describe 'model with options: :current_spouse => true' do let(:has_parents_opts) { {:current_spouse => true} } it "should have current_spouse_column class attribute" do TestModel.current_spouse_column.should == 'current_spouse_id' end it "should have db column named spouse_id" do TestModel.column_names.should include("current_spouse_id") end it "has current_spouse_enabled class attribute true" do TestModel.current_spouse_enabled.should be true end end describe 'model with options: :perform_validation => false' do let(:has_parents_opts) { {:perform_validation => false} } it "has perform_validation class attribute false" do TestModel.perform_validation.should be false end end describe 'model without options: defaults' do let(:has_parents_opts) { {} } [:father, :mother].each do |parent| it "should have #{parent}_id as #{parent} column" do TestModel.send("#{parent}_column").should == "#{parent}_id" end it "should have db column #{parent}_id" do TestModel.column_names.should include("#{parent}_id") end end it "has perform_validation class attribute true" do TestModel.perform_validation.should be true end it "should not have db column named spouse_id" do TestModel.column_names.should_not include("current_spouse_id") end it "has current_spouse_enabled class attribute false" do TestModel.current_spouse_enabled.should be false end it "should not have a current_spouse_column class attribute" do expect { TestModel.current_spouse_column }.to raise_error(NoMethodError) end end describe 'model with options: :sex_column => "gender", :sex_values => [1,2]' do let(:has_parents_opts) { {:sex_column => "gender", :sex_values => [1,2]} } it "has gender as sex column" do TestModel.sex_column.should == 'gender' end it "has an array as sex values" do TestModel.sex_values.should be_a_kind_of(Array) end it "has 1 as male sex value" do TestModel.sex_male_value == 1 end it "has 2 as female sex value" do TestModel.sex_female_value == 1 end end end describe "model and table settings with wrong options" do context "has_parents_opts: {:foo => 'bar' }" do let(:has_parents_opts) { {:foo => "bar" } } specify { expect { ModelSettingsSpec.define_test_model_class(has_parents_opts) }.to raise_error Genealogy::WrongOptionException } end context "has_parents_opts: {:foo => 'bar' }" do let(:has_parents_opts) { {:sex_column => "gender", :sex_values => [1,2,3]} } specify { expect { ModelSettingsSpec.define_test_model_class(has_parents_opts) }.to raise_error Genealogy::WrongOptionException } end end end
true
3eef60e44ebc465d71cb184cb46ed1090b2b593b
Ruby
MefazM/md-server-v2
/lib/battle/entity/spells/stun_spell.rb
UTF-8
401
2.6875
3
[]
no_license
module Battle class StunSpell def initialize(time) @time = time @finish_at = time + Time.now.to_f @complited = false end def reset! @finish_at = @time + Time.now.to_f end def ready?(time) @complited = @finish_at < time end def complited? @complited end def mutate yield('set_freeze', !@complited) end end end
true
805a7fce1386970d9a13ac6ad3513127ddff6ec4
Ruby
Sheddyka07/learn-co-sandbox
/scraper.rb
UTF-8
326
2.734375
3
[]
no_license
require 'nokogiri' require 'open-uri' html = open("https://web.archive.org/web/20160227204808/http://flatironschool.com/team") doc = Nokogiri::HTML(html) instructors = doc.css("#instructors .team-holder .person-box") instructors.each do |instructor| puts "Flatiron School <3 " + instructor.css("h2").text end
true
3957e20e98f76ea80ac59359405a4424d7a17c56
Ruby
SJeannie/oo-banking-houston-web-071618
/lib/bank_account.rb
UTF-8
1,128
3.484375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' require_relative "transfer" class BankAccount attr_reader :name attr_accessor :balance, :status @@all_accounts = [] def initialize(name) @name = name @balance = 1000 @status = "open" @valid = true @@all_accounts << self end def deposit(amount) @balance += amount end def display_balance p "Your balance is $#{self.balance}." end def valid? if @balance <= 0 || @status == "closed" @valid = false else @valid = true end end def close_account self.status = "closed" end # def self.valid?(sender, receiver) # if sender.valid? == true && receiver.valid? == true # Transfer.valid = true # end # end # def self.execute_transaction(sender, receiver, amount) # if Transfer.valid == true && Transfer.status != "complete" # sender.balance -= amount # receiver.balance += amount # Transfer.status = "complete" # end # # if sender.valid? == false # puts "Transaction rejected. Please check your account balance." # Transfer.status = "rejected" # end # end end
true
336c9a9fdf2747ba6b37b8a878d5f7cca2fad6b1
Ruby
johnlinatoc/countdown-to-midnight-chicago-web-051319
/countdown.rb
UTF-8
260
3.609375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
#write your code here def countdown(input) while input>0 puts "#{input} SECOND(S)!" input-=1 end "HAPPY NEW YEAR!" end def countdown_with_sleep(input) while input>0 puts "#{input} SECOND(S)!" input-=1 sleep 1 end "HAPPY NEW YEAR!" end
true
a39564ac2c07582fd61c89fa672b2704d0ef05c9
Ruby
kernelsmith/workbook
/test/test_table.rb
UTF-8
4,945
2.921875
3
[ "MIT", "GPL-3.0-only", "LGPL-2.0-or-later", "GPL-2.0-only", "Ruby" ]
permissive
# frozen_string_literal: true require File.join(File.dirname(__FILE__), "helper") class TestTable < Minitest::Test def test_initialize t = Workbook::Table.new assert_equal(t, []) c = Workbook::Cell.new("celllll") t = Workbook::Table.new [[c]] assert_equal([[c]], t) end def test_header t = Workbook::Table.new assert_nil(t.header) t = Workbook::Table.new [[1]] assert_equal(t.header, [1]) assert_equal(t.header.class, Workbook::Row) end def test_new_row t = Workbook::Table.new assert_equal(t.count, 0) r = t.new_row [1, 2, 3, 4] assert_equal(r, [1, 2, 3, 4]) assert_equal(r.class, Workbook::Row) assert_equal(1, t.count) r = t.new_row assert_equal(r.empty?, true) assert_equal(r.class, Workbook::Row) assert_equal(2, t.count) assert_equal(r, t.last) r << 2 assert_equal(t.last.empty?, false) end def test_append_row t = Workbook::Table.new row = t.new_row(["a", "b"]) assert_equal(row, t.header) row = Workbook::Row.new([1, 2]) assert_nil(row.table) t.push(row) assert_equal(t, row.table) row = Workbook::Row.new([3, 4]) assert_nil(row.table) t << row assert_equal(t, row.table) t = Workbook::Table.new t << [1, 2, 3, 4] assert_equal(Workbook::Row, t.first.class) end def test_sheet t = Workbook::Table.new s = t.sheet assert_equal(t, s.table) assert_equal(t.sheet, s) end def test_name t = Workbook::Table.new t.name = "test naam" assert_equal("test naam", t.name) end def test_delete_all w = Workbook::Book.new [["a", "b"], [1, 2], [3, 4]] t = w.sheet.table t.delete_all assert_equal(Workbook::Table, t.class) assert_equal(0, t.count) end def test_clone w = Workbook::Book.new [["a", "b"], [1, 2], [3, 4]] t = w.sheet.table assert_equal(3, t[2][:a]) t2 = t.clone t2[2][:a] = 5 assert_equal(3, t[2][:a]) assert_equal(5, t2[2][:a]) end def test_clone_custom_header w = Workbook::Book.new [[nil, nil], ["a", "b"], [1, 2], [3, 4]] t = w.sheet.table t.header = t[1] assert_equal(3, t[3][:a]) t2 = t.clone t2[3][:a] = 5 assert_equal(3, t[3][:a]) assert_equal(5, t2[3][:a]) end def test_spreadsheet_style_cell_addressing w = Workbook::Book.new [[nil, nil], ["a", "b"], [1, 2], [3, 4]] t = w.sheet.table assert_nil(t["A1"].value) assert_nil(t["B1"].value) assert_equal("a", t["A2"].value) assert_equal("b", t["B2"].value) assert_equal(1, t["A3"].value) assert_equal(2, t["B3"].value) assert_equal(3, t["A4"].value) assert_equal(4, t["B4"].value) end def test_multirowselect_through_collections w = Workbook::Book.new [["a", "b"], [1, 2], [3, 4]] t = w.sheet.table assert_equal(Workbook::Table, t[0..2].class) assert_equal(2, t[0..2][1][1]) end def test_table w = Workbook::Book.new [[nil, nil], ["a", "b"], [1, 2], [3, 4]] t = w.sheet.table w2 = Workbook::Book.new w2.sheet.table = t[2..3] assert_equal("1,2\n3,4\n", w2.sheet.table.to_csv) end def test_array_style_assignment w = Workbook::Book.new [["a", "b"], [1, 2], [3, 4]] t = w.sheet.table r = t[1].clone assert_nil(r.table) t[2] = r assert_equal(t, r.table) end def test_delete_at w = Workbook::Book.new [["a", "b"], [1, 2], [3, 4]] t = w.sheet.table t.delete_at 2 assert_equal(1, t.last.first.value) end def test_trim! t = Workbook::Table.new t << [1, 2, 3] t << [1, 2, nil, nil] t.trim! assert_equal("1,2,3\n1,2,\n", t.to_csv) t = Workbook::Table.new t << [1, 2, 3] t << [nil] t << [1, 2, nil, nil] t << [nil, nil, nil, nil] t << [nil, nil, nil, nil] t.trim! assert_equal("1,2,3\n,,\n1,2,\n", t.to_csv) end def test_performance table = Workbook::Table.new headers = 100.times.collect { |a| "header#{a}" } first_row = 100.times.collect { |a| Time.now } table << headers.shuffle table << first_row 1000.times do |times| row = table[1].clone table << row headers.each do |a| row[a.to_sym] = Time.now end end last_line = table.count - 1 delta_start = table[12][0].value - table[2][0].value delta_end = table[last_line][0].value - table[last_line - 10][0].value average_run_time = (delta_start + delta_end / 20) if (delta_end - delta_start) > average_run_time puts "Performance issue" end end def test_columns table = Workbook::Table.new([[]]) assert_equal(table.columns, []) table = Workbook::Table.new([[:a, :b], [1, 2]]) assert_equal(table.columns.count, 2) end def test_dimensions table = Workbook::Table.new([[]]) assert_equal([0, 1], table.dimensions) table = Workbook::Table.new([[:a, :b], [1, 2, 3, 4]]) assert_equal([4, 2], table.dimensions) end end
true