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
d02602a5729fd6e5f94558ac7ddc9ab6f3de3920
Ruby
dcaba/hashcode-2016
/lib/order.rb
UTF-8
2,212
2.75
3
[]
no_license
LineStatus = Struct.new(:requested,:ongoing,:delivered) class Order attr_reader :id,:delivery_address,:closed_turn def initialize(id, delivery_address) @id = id @delivery_address = delivery_address @items = Hash.new {|hash, key| hash[key] = LineStatus.new(0,0,0)} @closed_turn = nil end def status return "closed" if pending_delivery_qty == 0 return "pending" end def add_items(ptype,quantity) @items[ptype].requested += quantity end def item_picked(ptype,quantity) @items[ptype].ongoing += quantity end def item_delivered(ptype,quantity) @items[ptype].ongoing -= quantity @items[ptype].delivered += quantity if pending_delivery_qty == 0 @closed_turn = $current_turn end end def requested_items() @items.keys end def requested_qty(ptype="all") return @items.values.inject(0) {|sum,line| sum = sum + line.requested} if ptype == "all" return @items[ptype].requested end def ongoing_items return @items.select {|item,line| line.ongoing > 0}.keys end def ongoing_qty(ptype="all") return @items.values.inject(0) {|sum,line| sum = sum + line.ongoing} if ptype == "all" return @items[ptype].ongoing end def delivered_items return @items.select {|item,line| line.delivered > 0}.keys end def delivered_qty(ptype="all") return @items.values.inject(0) {|sum,line| sum = sum + line.delivered} if ptype == "all" return @items[ptype].delivered end def pending_delivery_items return @items.select {|item,line| line.delivered != line.requested}.keys end def pending_delivery_qty(ptype="all") return @items.values.inject(0) {|sum,line| sum = sum + line.requested - line.delivered} if ptype == "all" return requested_qty(ptype) - delivered_qty(ptype) end def pending_pick_items return @items.select {|item,line| line.delivered + line.ongoing != line.requested}.keys end def pending_pick_qty(ptype="all") return @items.values.inject(0) {|sum,line| sum = sum + line.requested - line.delivered - line.ongoing} if ptype == "all" return requested_qty(ptype) - delivered_qty(ptype) - ongoing_qty(ptype) end def score if status == "closed" return (($max_turn-@closed_turn)*100/($max_turn + 0.00)).ceil else return 0 end end end
true
c07b21ea4fff08fce4f75c1a80f2bb947475c603
Ruby
jnskender/Knights-Travails
/Graph.rb
UTF-8
1,667
3.65625
4
[]
no_license
require './Node.rb' require './Game_Board' class Graph attr_accessor :root def initialize @root = nil @board = Game_Board.new end def piece_move(start, finish, piece) @root = Node.new(start) queue = [@root] found_node = nil until queue.empty? || !found_node.nil? current_node = queue.shift piece.moves.each do |move| # for each valid move of piece location = [current_node.location[0] + move[0], current_node.location[1] + move[1]] next unless valid_location?(location) @board.used_positions << location node = Node.new(location) node.parent = current_node current_node.children << node queue << node found_node = node if location == finish break if location == finish end # end do end # end until path = [found_node] loop do #fill path array with parents of finishing nodes break if path[-1] == @root current_node = path[-1] path << current_node.parent end path.reverse! puts "You made it in #{path.size - 1} moves! Here's your path:" path.each {|node| print "#{node.location} \n"} end def valid_location?(location) return false if location[0] > @board.grid_max || location[0] < @board.grid_min|| location[1] > @board.grid_max || location[1] < @board.grid_min || @board.used_positions.include?(location)#infinite loop if you dont track true end end
true
0e4e1a2f9520887ab730cbc0c7c3f7adf3e5a50d
Ruby
CristianRenzoChuraPacsi/ruby
/hashes.rb
UTF-8
837
3.9375
4
[]
no_license
# es una estructura que alamacena datos como un diccionario lo haria # arreglos asociativos # la diferencia es com acceder a los datos de un array # en un hash se busca con su tipo # hash para un tutor # tienen dos partes una clave y un valor # tutor = {"nombre" => "Renzo", "edad" => 23, 20 => "Veinte", [] => "Arreglo"} # #para agrerar es la siguiente # tutor["cursos"] = 20 # tutor.default = ":)"#si no encuentra claves esta sera por default # puts tutor[5] # la ventaja es que podemos acceder de manera mas rapida # a uno de los elementos # las claves son de la izquierda y el valor son la derecha #********************************************* # otra forma de hacer los hash tutor = {nombre: "Renzo", edad: 23, cursos:10} #puts tutor[:edad] tutor.each do |clave,valor| puts "en #{clave} esta guardado #{valor}" end
true
f7da08b93145051a291d3812c1216753dcb30c9c
Ruby
tamu222i/ruby01
/tech-book/7/m-49.rb
UTF-8
262
3.203125
3
[]
no_license
# 以下の実行結果になるようにxに記述するコード t = Time.local(2000,1,1) x # 実行結果 # 2000/01/01 # 1.printf(("%Y/%m/%d),t.year,t.mon,t.day) # 2.printf(("%Y/%m/%d") % t) # 3.print(t.format("%Y/%m/%d")) # 4.print(t.strftime("%Y/%m/%d"))
true
7824b54b7721b8e514d800147672a061d38b2d18
Ruby
t6d/guard-python-unittest
/lib/guard/python_unittest/test_runner.rb
UTF-8
734
2.75
3
[ "MIT" ]
permissive
require 'pathname' class Guard::PythonUnittest::TestRunner attr_reader :directory def initialize(directory) @directory = directory end def run(path = nil) if path execute(convert_path_to_module_name(path)) else execute end end private def command "python" end def command_line_arguments(*args) ["-m", "unittest", *args] end def execute(module_name = "discover") Dir.chdir(directory) { system(command, *command_line_arguments(module_name)) } end def convert_path_to_module_name(path) relative_path = Pathname(path).relative_path_from(Pathname(directory)).to_s relative_path.chomp!(File.extname(path)).gsub!('/', '.') end end
true
81afc06a02414f387e0742c16e1aefb90c3a8991
Ruby
RanSolo/cal
/formattingII.rb
UTF-8
2,676
3.71875
4
[]
no_license
#!/usr/bin/env ruby def conditionals(m,y) if m < 1 || m > 12 raise ArgumentError, "that's not a month dummy" else # calendar_body(m,y) print_header(m, y) end # # def year( y) # one_year = (1..12).to_a # years = (1800..2250) # print years # # if y # end # endprint def month_arg_to_s(m) month_array = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] month_array[m - 1] end def print_header(m, y) header = "#{month_arg_to_s(m)}"+ " " +"#{y}" print header.center(20).rstrip + "\n" + "#{days}" end def days days = "Su Mo Tu We Th Fr Sa" end def individual_day_to_s(m, d) # h represents the first day number from zellers congruencefrom zellers cong h = find_weekday(m, d) days_of_the_week = ['Saturday','Sunday','Monday','Tuesday','Wednesday','Thursday','Friday'] days_of_the_week[h] end def ifleap if @year%4 == 0 && @year%100 == 0 && @year%400 == 0 [31,29,31,30,31,30,31,31,30,31,30,31] else [31,28,31,30,31,30,31,31,30,31,30,31] end end def calendar_body(m, y) # puts find_weekday(m.to_s ,y.to_s) # # m = conditionals(m,y) # # index_of_first_day = [18, 0, 3, 6, 9, 12, 15] # #print index_of_first_day[first_day.to_i] end # months_with_31_days = [nil,1,3,5,7,8,10,12] # months_with_30_days = [4,6,9,11] # # if months_with_31_days.include? month # print long_months(month, year, h) # else # print short_months(month, year, h) # end # def long_months(m,y, h) # days_of_month = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31" # print days_of_month.center(20).rstrip # end # # def short_months(m,y, h) # # days_of_feb =(1...29) # days_of_feb = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 17 18 19 20 21 22 23 24 25 26 27 28" # days_of_feb_leapyear = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 17 18 19 20 21 22 23 24 25 26 27 28 29" # days_of_month = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 17 18 19 20 21 22 23 24 25 26 27 28 29 30" # return days_of_feb if m == 2 # # return days_of_feb_leapyear if # else # days_of_month # # print days_of_month.center(20).rstrip # # end # end # def leap_year(m,y) # when h = 0 days_of_month = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31" # when h = 0 days_of_month = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31" # when h = 0 days_of_month = "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 161 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31" # end # def print_month(m, y) # print_header(m, y), # days end
true
90bcf4e5a9d42eee4ca741e2d3e5fada9ecca1e3
Ruby
alexRai98/c2-module2
/week-1/day-4/find_class.rb
UTF-8
288
3.09375
3
[]
no_license
class Celphone def initialize(color, marca) @color = color @marca= marca @broke = false end def marca @marca end def color @color end end celphone = Celphone.new("back","Lg") puts celphone.marca puts celphone.colo
true
6d3c106a250d6186c4d12ada35ef694d7206f704
Ruby
gabrielclouud/Jogo-da-advinhacao
/teste5.rb
UTF-8
233
3.046875
3
[]
no_license
treze = 13 cinco = 5 puts treze / cinco puts treze % cinco puts treze + cinco puts treze - cinco puts treze * cinco numero = 5 numero += 1 numero -= 2 numero *= 2 numero /= 4 numero *= 13 numero %= 10 puts numero
true
a6fb025971523e911dd608cb1df330675767bca1
Ruby
alex-j-g/rb_101
/lesson_3/medium_1/q02.rb
UTF-8
369
4.5625
5
[]
no_license
#The result of the following statement will be an error: puts "the value of 40 + 2 is " + (40 + 2) #Why is this and what are two possible ways to fix this? #answer: Intergers need to be converted to a string before it can be concatenated to another string. puts "the value of 40 + 2 is " + (40 + 2).to_s #or puts "the value of 40 + 2 is #{40+2}" #with interpolation
true
179c8deb1c3f2ff79f4d64389ea17cc1da49d188
Ruby
Anikram/social_skills
/spec/test_spec.rb
UTF-8
1,002
2.8125
3
[]
no_license
require 'rspec' require 'test.rb' describe 'logic of evaluate_result' do before :each do @test = Test.new(__dir__ + '/fixtures/questions.txt', __dir__ + '/fixtures/results.txt') end context 'when test just started' do it 'returns 6th element of result array' do expect(@test.evaluate_result).to include('3 балла или менее.') result1 = @test.results[6] result2 = @test.evaluate_result expect(result1).to eq result2 end end context 'when all questions asked' do it 'result must include "string"' do responce = @test.print_result expect(responce).to include('30 31 балл. Что скрывать') end end end describe 'initialized values' do before :each do @test = Test.new(__dir__ + '/fixtures/questions.txt', __dir__ + '/fixtures/results.txt') end it 'returns array of content' do @test.results.each do |result| expect(result).to include('баллов').or include('балл') end end end
true
4349490fce611fa309b1dd84131e21b533df68e3
Ruby
BastianErler/Blueliner_Tippspiel
/app/models/tip.rb
UTF-8
861
3.046875
3
[]
no_license
class Tip < ApplicationRecord belongs_to :user belongs_to :game validates :game_id, presence: true validates :user_id, presence: true def evaluate if goals_nil self.price = 1 elsif tip_correct self.price = 0 elsif tendency_correct diff = calculate_diff self.price = [diff * 0.20, 0.80].min else self.price = 1 end save end private def goals_nil (home_goals.nil? && away_goals.nil?) end def tip_correct ((game.home_goals == home_goals) && (game.away_goals == away_goals)) end def tendency_correct ((game.home_goals > game.away_goals) && (home_goals > away_goals)) || ((game.home_goals < game.away_goals) && (home_goals < away_goals)) end def calculate_diff (game.home_goals - home_goals).abs + (game.away_goals - away_goals).abs end end
true
a63ded78130a275f4523adc5e83b6b71e105d3d0
Ruby
7digital/Mint
/src/SevenDigital.Tools.DependencyManager.RakeTasks/test/integration.tests/dependency_conflict_tests.rb
UTF-8
1,636
2.640625
3
[]
no_license
require "test/unit" require File.dirname(__FILE__) + '/../../src/lib/chubby_rain' class DependencyConflictTests < Test::Unit::TestCase def test_that_a_conflict_is_returned instance = ChubbyRain.new(EXE_PATH, WORKING_DIR) conflict = instance.run(COMMAND_REPORT, ASS_NAME) assert_equal(0, conflict.exit_status, "Expected exit status of 0. Message: #{conflict.text}") assert_contains(conflict.text, "Major Revision Conflict") assert_contains(conflict.text, "References: SevenDigital.B") assert_contains(conflict.text, "Reference Version: 1.0.0.0") assert_contains(conflict.text, "Actual Reference Version: 1.5.0.0") end def test_that_there_are_no_conflicts instance = ChubbyRain.new(EXE_PATH, WORKING_DIR) conflict = instance.run(COMMAND_REPORT, NO_CONFLICT_NAME) assert_equal(0, conflict.exit_status, "Expected exit status of 0. Message: #{conflict.text}") assert_not_contains("is referencing assembly",conflict.text) end private def assert_contains(text, what) assert( text.include?(what), "Expected text <#{what}> not found in: <#{text}>" ) end def assert_not_contains(text,what) assert( false == text.include?(what), "Found <#{what}> in: <#{text}>" ) end ANY_PATH_THAT_DOES_NOT_EXIST = 'c:\does-not-exist' EXE_PATH = File.expand_path(File.dirname(__FILE__) + '/../../src/bin/chubbyrain.exe') COMMAND_REPORT = 'conflict' WORKING_DIR = File.expand_path(File.dirname(__FILE__) + '/SampleAssemblies/') ASS_NAME = 'Sevendigital.A.dll' NO_CONFLICT_NAME = 'Sevendigital.B.dll' CHUBBY_BAT_DLL = 'Chubby.Bat.dll' end
true
dd6570eb23d15c6eb3792e7056c27a6ecdfecf73
Ruby
yuping-xiao/practice-ruby
/the8th-chapterF.rb
UTF-8
604
4.03125
4
[]
no_license
puts "計算を始めます" puts "二つの値を入力してください" a=gets.to_i b=gets.to_i puts "計算結果を出力します" puts "a*b=#{a*b}" puts "計算を終了します" puts "続いての計算です" puts "何回繰り返しますか?" input = gets.to_i i = 1 while i <= input do puts "#{i}回目の計算" puts "二つ目の値を入力してください" a = gets.to_i b = gets.to_i puts "a=#{a}" puts "b=#{b}" puts "計算結果を出力します" puts "a+b=#{a+b}" puts "a-b=#{a-b}" puts "a*b=#{a*b}" puts "a/b=#{a/b}" i += 1 end puts "計算を終了します"
true
7408cbeb2b41c618466c292789b405bd2f820916
Ruby
rubenpazch/ruby-algorithms
/books/large_number.rb
UTF-8
133
3
3
[]
no_license
rice_on_square = 1 1024.times do |square| puts "On square #{square + 1} are #{rice_on_square} grain(s)" rice_on_square *= 2 end
true
b9110ed4a32729ffc9158ba63267202352244578
Ruby
richgong/midi-warp
/_archive/shitty_tranpose_ruby/slow_and_shitty.rb
UTF-8
1,287
3.15625
3
[ "MIT" ]
permissive
require 'unimidi' NOTE_ON = 144 NOTE_OFF = 128 puts "Inputs:" UniMIDI::Input.list puts "Outputs:" UniMIDI::Output.list notes = [36, 40, 43, 48, 52, 55, 60, 64, 67] # C E G arpeggios duration = 0.1 output = UniMIDI::Output.use(0) puts "Writing to: #{output.pretty_name}" input = UniMIDI::Input.use(1) TRANSFORM_KEY = { # see Dorian: https://www.youtube.com/watch?v=zKdWSYcApD0 dorian: { # 2 4 5 7 9 11 12 0 => 2, # C 1 => 0, 2 => 4, # D 3 => 0, 4 => 5, # E 5 => 7, # F 6 => 0, 7 => 9, # G 8 => 0, 9 => 11, # A 10 => 0, 11 => 12 # B } } output.open do |output| notes.each do |note| output.puts(NOTE_ON, note, 100) # note on sleep(duration) output.puts(NOTE_OFF, note, 100) # note off message end puts "Reading from: #{input.pretty_name}" input.open do |input| loop do m = input.gets if m.length > 0 data = m[0][:data] type = data[0] note = data[1] vel = data[2] octave = note / 12 key = note % 12 new_key = TRANSFORM_KEY[:dorian][key] || 0 output.puts(type, octave * 12 + new_key, vel) # puts "#{type} note=#{note} #{vel}" end end end end
true
7f87f12830b6e5f9c36b3628dd7c6510c36f7274
Ruby
MattHeard/Five-Hundred
/app/commands/pass_bid.rb
UTF-8
307
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
class PassBid def initialize(game) @game = game end def call game.with_lock { game.events << new_event } end private attr_reader :game def new_event BidPassed.new(player_seat: game_state.current_player_seat) end def game_state CreateGameState.new(game).call end end
true
9f4fa7ae102e1d35605243c61d48157b0ea70e7c
Ruby
anthonynavarre/GildedRose
/lib/gilded_rose/item/event_specific_item.rb
UTF-8
402
2.890625
3
[]
no_license
class EventSpecificItem < Item def age super if expired? @quality = 0 else appreciate end end private def appreciate unless @quality >= MAXIMUM_QUALITY @quality = @quality + appreciation_amount end @quality end def appreciation_amount case when @sell_in < 6 then 3 when @sell_in < 11 then 2 else 1 end end end
true
2e1248af39282c9f1613860b94628751e4ac90dc
Ruby
shawn42/ludum_dare_22
/src/hunger_meter.rb
UTF-8
794
2.90625
3
[]
no_license
class HungerMeterView < ActorView #COLOR = [250,250,255,200] def draw(target,x_off,y_off,z) @screen ||= @stage.resource_manager.load_image 'clock_bg.png' x = @actor.x y = @actor.y @screen.draw x, y, z end end class HungerMeter < Actor has_behavior :layered => {:layer => ZOrder::HudBackground} has_behavior :updatable def setup @label = spawn :label, layer: ZOrder::HudText, font: FONT, size: 30 width = @label.font.text_width "Hunger: " @label.x = self.x+15 @label.y = self.y+20 write_label end def write_label @label.text = "Hunger: #{@hunger}" end def hunger=(hunger) @hunger = hunger.ceil write_label end def subtract(amount) @hunger -= amount @hunger = 0 if @hunger < 0 write_label end end
true
3ab38f05bb9673696b597fbf01e7f09628ffe143
Ruby
sogapalag/contest
/yukicoder/3060.rb
UTF-8
403
3.03125
3
[]
no_license
# coding: utf-8 s=gets.chomp if s=="0" puts 'Nothing' exit elsif s=='3.14159265' puts 'pi' exit elsif s=="1112345678999+X" y="19m19p19s東南西北白發中+Y" if gets.chomp==y puts "九蓮宝燈\nThirteen Orphans" end exit end if s=='All your base are belong to us.' puts [3,4,4,3,6,2,2] exit end if s=='くぁwせdrftgyふじこlp' puts 'さmpぇ' end
true
0431d3b50dc85a92aea55d1880bb08a75f5ed0c2
Ruby
kbronstein/rubytrail
/metaprogramming/flat_scope.rb
UTF-8
387
4.03125
4
[]
no_license
# How to access the variable door_key in: # - the class scope # - the method scope # # #door_key = "Key" # #class FlatScope # Print door_key here # def method # Print door_key here # end #end door_key = "sesame" FlatScope = Class.new do puts "In the class: #{door_key}" define_method :method do puts "In the method: #{door_key}" end end FlatScope.new.method
true
5eb000c0b1e5cd207aadd67bcf578a761c7ffbab
Ruby
ab/dotfiles
/pryrc
UTF-8
587
2.75
3
[]
no_license
# don't use less Pry.config.pager = false # my terminal may resize, damn it Pry.auto_resize! # alias ll => exec ls -l --color def ll _pry_ end # local_methods shows methods that are only available for a given object class Object def local_methods self.methods.sort - self.class.superclass.methods end end Pry::Commands.command 'll', 'Execute ls -l in a shell.' do run ".ls -l --color #{arg_string}" end # quick sample data Myhash = {:foo=>'red', :bar=>'green', :baz=>'blue'} if not defined? Myhash Myarray = ['foo', 'bar', 'baz'] if not defined? Myarray # vim: ft=ruby
true
3d0aeeea1c65c5dafdf92a9102322ef0807aaf42
Ruby
JelF/dynvar
/lib/dynvar/container.rb
UTF-8
738
3.09375
3
[]
no_license
# frozen_string_literal: true class DynVar # @api private # Container for DynVar values, acts as stack class Container # @param default_value generic value def initialize(default_value) self.stack = [default_value] end # pushes new value to use # @param x new value to be used def push(x) stack.push(x) end # pops current value to restore old version def pop stack.pop end # returns current value def head stack[-1] end # @api private # @return [DynVar::Container] new container with current value def fork self.class.new(head) end private # encapsulated storage # @return [Array] attr_accessor :stack end end
true
3202183a0c048e3d9ca233d8f96503184beef951
Ruby
sydneyJ17/calculatorlabproject
/calculator_lab.rb
UTF-8
1,911
4.03125
4
[]
no_license
require 'colorize' # puts "Enter your first number." # number1 = gets.chomp.to_i # puts "Enter your second number." # number2 = gets.chomp.to_i # puts "Enter your function(addition,subtraction,multiplication, or division)." # function1 = gets.chomp # def addition(num_1, num_2) # num_1 + num_2 # end # if function1 == "addition" # puts addition(number1, number2) # end # def subtraction(num_1, num_2) # num_1 - num_2 # end # if function1 == "subtraction" # puts subtraction(number1, number2) # end # def multiplication(num_1, num_2) # num_1 * num_2 # end # if function1 == "multiplication" # puts multiplication(number1, number2) # end # def division(num_1, num_2) # num_1 / num_2 # end # if function1 == "division" # puts division(number1, number2) # end ################################################## puts "How many dogs have you pet on Monday?" dogs1 = gets.chomp.to_i puts "How many dogs have you pet on Tuesday?" dogs2 = gets.chomp.to_i puts "How many dogs have you pet on Wednesday?" dogs3 = gets.chomp.to_i puts "How many dogs have you pet on Thursday?" dogs4 = gets.chomp.to_i puts "How many dogs have you pet on Friday?" dogs5 = gets.chomp.to_i puts "How many dogs have you pet on Saturday?" dogs6 = gets.chomp.to_i puts "How many dogs have you pet on Sunday?" dogs7 = gets.chomp.to_i def dogs_weekly(d1, d2, d3, d4, d5, d6, d7) d1 + d2 + d3 + d4 + d5 + d6 + d7 end total_dogs = dogs_weekly(dogs1, dogs2, dogs3, dogs4, dogs5, dogs6, dogs7) if total_dogs > 10 puts "You have pet #{total_dogs} dogs this week, you've had a FETCHtastic week!!".magenta elsif total_dogs < 10 puts "You have pet #{total_dogs} dogs this week, what a sad life...".red else total_dogs = 10 puts "You have pet #{total_dogs} dogs this week, your week has been average.".cyan end dogs_yearly = total_dogs*52 puts "You will have pet #{dogs_yearly} dogs this year!".green
true
9778318c68e02b8f8606a2763debf0aa373a9f6c
Ruby
mdodd8299/calculatorlab
/unit.rb
UTF-8
715
4.375
4
[]
no_license
#input puts "Hello" while true puts "What would you like to convert to: Fahrenheit or Celsius?" input = gets.chomp #F if input == "Fahrenheit" or input == "fahrenheit" or input == "f" or input == "F" puts "What is your tempurture in Cesius?" c = gets.to_f answer = c*9/5+32 puts "Your conversion is:" puts answer.to_s exit #C elsif input == "Celsius" or input == "C" or input == "celsius" or input == "c" puts "What is your tempurture in Fahrenheit?" c = gets.to_f answer = (c-32)*5/9 puts "Your conversion is:" puts answer.to_s exit else puts "Please make sure that you spelled it correctly." end end
true
6c06f5843c39605dcdb8a4d6ace253fbc609e28e
Ruby
cha63506/typebeast
/vendor/cache/ruby/2.2.0/gems/time-lord-1.0.1/lib/time-lord/period.rb
UTF-8
847
3.28125
3
[ "MIT" ]
permissive
module TimeLord class Period attr_writer :beginning, :ending def initialize(beginning, ending) self.beginning = beginning self.ending = ending end def to_words "#{value} #{unit} #{tense}" end alias_method :in_words, :to_words def difference beginning - ending end alias_method :to_i, :difference def to_time if difference < 0 then @beginning else @ending end end def to_range beginning..ending end def beginning @beginning.to_i end def ending @ending.to_i end private def value Scale.new(absolute).to_value end def unit Scale.new(absolute).to_unit end def absolute difference.abs end def tense if difference < 0 then "ago" else "from now" end end end end
true
a1f6928bf689ad43f84b315a254904db9b480ce4
Ruby
anishaetienne/QuestionMe
/db/seeds.rb
UTF-8
498
2.78125
3
[]
no_license
require 'faker' #Create Questions #5.times do # Question.create!( # questions: Faker::Lorem.sentence, # status: Faker::Lorem.word) #end questions = Question.all #Create Answers 20.times do Answer.create!( question: questions.sample, answers: Faker::Lorem.paragraph) end #30.times do # Tag.create!( # name: Faker::Lorem.word) #end puts "Seed finished!!!" #puts "#{Question.count} questions created" puts "#{Answer.count} answers created" #puts "#{Tag.count} tags created"
true
df8ce4242e78501e463720990c56aae3c0c31a13
Ruby
ferbaco86/Random-Movie-Twitter-Bot
/spec/genres_spec.rb
UTF-8
599
2.75
3
[ "MIT" ]
permissive
require_relative '../lib/genres.rb' describe Genres do let(:genres) { Genres.new(%w[I Want To Watch A Comedy]) } let(:words_array_test) { %w[Comedy] } let(:movies_genre_selected) { Tmdb::Genre.find('Comedy') } describe '#genre' do it 'Returns an array with the elements that are included in words_array and genres_array' do expect(genres.genre).to eql(words_array_test) end end describe '#genre_selected?' do it 'Returns true if the genre list contains the genre in the tweet' do genres.genre expect(genres.genre_selected?).to eql(true) end end end
true
c23a09ea77cd2e8c956d944a304a11e151fbd350
Ruby
dfwheeler394/algorithms-practice
/word_problems/uber/valid_sudoku.rb
UTF-8
1,498
3.90625
4
[]
no_license
# @param {Character[][]} board # @return {Boolean} def is_valid_sudoku(board) SudokuBoard.new(board).valid? end class SudokuBoard def initialize(board) @board = board @size = board.length end def valid? rows_valid? && cols_valid? && squares_valid? end private def rows_valid? @board.each_index do |i| row = [] @board[0].length.times do |j| row << [i, j] end return false unless all_valid?(row) end true end def cols_valid? @board[0].length.times do |j| col = [] @board.each_index do |i| col << [i, j] unless @board[i][j] == '.' end return false unless all_valid?(col) end true end def squares_valid? idxs = (0...@size).step(3).to_a * 2 square_starts = idxs.combination(2).to_a.uniq square_starts.all? { |i, j| valid_square_at?(i, j) } end def valid_square_at?(i, j) square = [] (i..i + 2).each do |n| (j..j + 2).each do |m| square << [n, m] unless @board[n][m] == "." end end all_valid?(square) end def all_valid?(arr) set = Array.new(@size + 1) arr.each do |i, j| el = @board[i][j] next if el == '.' if set[el.to_i] return false else set[el.to_i] = true end end true end end board = [ ".87654321", "2........", "3........", "4........", "5........", "6........", "7........", "8........", "9........"] p is_valid_sudoku(board)
true
7d42d883417880cfbec849be25aa7b8ca92d3149
Ruby
vigneshrajkumar/computation
/DFA/farule.rb
UTF-8
342
3.203125
3
[]
no_license
class FARule < Struct.new(:state, :character, :next_state) # Checks if the given character is applicable to the current state def applies_to?(state, character) self.state == state && self.character == character end def follow next_state end def inspect "#<FARule #{state.inspect}--#{character}-->#{next_state.inspect}>" end end
true
a50902770c11b12d2ab46ed11a03fc15ff82cd21
Ruby
andrewtodd/tbfinancesv1
/app/models/transaction.rb
UTF-8
2,398
2.84375
3
[]
no_license
class Transaction < ActiveRecord::Base include Filterable belongs_to :tennants belongs_to :owners validates_uniqueness_of :name, :scope => [:date, :amount] ## START OF UI FILTER SCOPES scope :category, -> (category) { where category: category } # I'm not sure these notes will be that much help in the future #This is equivalent to the following mysql call: # select * from Transactions where category=category # using scope is just like defining a class with a method. These can be called from concerns, controllers etc # the first use of category is the name of the class. # The second use of category sets the variable 'category' to the value of the paremter being passed to this method when it's called. # the third use of category is the column name in the database. # The final use of category is again the parameter category. #this is the same as writing # def self.category(category) # where ("category = ?", category) the question mark is replaced vy the value of category # end scope :transaction_type, -> (transaction_type) { where transaction_type: transaction_type } # it seems stupid to accept a param (owner) that won't be used but this hack is the only way to enable # us to use this scope with the filter method which is expecting to send one. We could write some code # to give the method more options but that would slow the process down when we can easily just ignore owener scope :owner, -> (owner) { where.not(owner_id: 'NULL') } ## END OF UI FILTER SCOPES scope :tax_year, -> (start_date,end_date) { where("date BETWEEN ? AND ?",start_date,end_date) } scope :business_transactions, -> { where ("owner_id IS NULL") }#used to calculate what owners are owed scope :by_tennant_id, -> (tennant_id) { where tennant_id: tennant_id } def self.search(search) where("name like ?", "%#{search}%") end def self.categories #### CATEGORIES # used to populate the categories drop down categories = [ ['rent','rent'], ['owner','owner'], ['tax','tax'], ['insurance','insurance'], ['repairs','repairs'], ['council','council'], ['tax','tax'], ['utility','utility'], ['mortgage','mortgage'], ['agent','agent'], ['deposit','deposit'], ['uncategorized','uncategorized'] ] return categories end end
true
e8688f2018993fb15b877fd287df2e1d5a01e580
Ruby
BigBadBlue/badges-and-schedules-001-prework-web
/conference_badges.rb
UTF-8
555
3.6875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. def badge_maker(name) return "Hello, my name is #{name}." end def batch_badge_creator(attendees) badges = [] attendees.each do |name| badges.push badge_maker(name) end badges end def assign_rooms(ass) rooms = [] ass.each_with_index do |name, rnum| rooms.push "Hello, #{name}! You'll be assigned to room #{rnum+1}!" end rooms end def printer(speakers) batch_badge_creator(attendees).each do |name| puts name end assign_rooms(speakers).each do |name| puts name end end
true
fa75d46420325356b20981c5bf16128bad8f2504
Ruby
jennifer-yoo/ruby-oo-practice-flatiron-zoo-exercise-nyc01-seng-ft-071320
/lib/Animal.rb
UTF-8
500
3.390625
3
[]
no_license
class Animal attr_accessor :zoo, :species, :nickname attr_reader :weight @@all = [] def initialize(zoo, species, weight, nickname) @zoo = zoo @species = species @weight = weight @nickname = nickname @@all << self end def self.all @@all end def self.find_by_species(arg) self.all.map do |a_instance| if a_instance.species == arg a_instance end end end end
true
e41e158be0b6bc7f800e3c187a0ed1664cdff309
Ruby
TerranceDWilliams1976/debugging-with-pry-v-000
/lib/pry_debugging.rb
UTF-8
58
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
num = 3 def plus_two(num) numbers = num + 2 numbers end
true
2828aa73e877a49e0b4688e71c45d2724b857bef
Ruby
callenb/workpattern
/lib/workpattern/workpattern.rb
UTF-8
8,454
3.296875
3
[ "MIT" ]
permissive
module Workpattern require 'set' require 'tzinfo' # Represents the working and resting periods across a given number of whole # years. Each <tt>Workpattern</tt>has a unique name so it can be easily # identified amongst all the other <tt>Workpattern</tt> objects. # # This and the <tt>Clock</tt> class are the only two that should be # referenced by calling applications when # using this gem. # class Workpattern # Holds collection of <tt>Workpattern</tt> objects @@workpatterns = {} def self.workpatterns @@workpatterns end def workpatterns @@workpatterns end # @!attribute [r] name # Name given to the <tt>Workpattern</tt> # @!attribute [r] base # Starting year # @!attribute [r] span # Number of years # @!attribute [r] from # First date in <tt>Workpattern</tt> # @!attribute [r] to # Last date in <tt>Workpattern</tt> # @!attribute [r] weeks # The <tt>Week</tt> objects that make up this workpattern # attr_reader :name, :base, :span, :from, :to, :weeks # Class for handling persistence in user's own way # def self.persistence_class=(klass) @@persist = klass end def self.persistence? @@persist ||= nil end # Holds local timezone info @@tz = nil # Converts a date like object into utc # def to_utc(date) date.to_time.utc end # Converts a date like object into local time # def to_local(date) date.to_time.getgm end # Retrieves the local timezone def timezone @@tz || @@tz = TZInfo::Timezone.get(Time.now.zone) end # The new <tt>Workpattern</tt> object is created with all working minutes. # # @param [String] name Every workpattern has a unique name # @param [Integer] base Workpattern starts on the 1st January of this year. # @param [Integer] span Workpattern spans this number of years ending on # 31st December. # @raise [NameError] if the given name already exists # def initialize(name = DEFAULT_NAME, base = DEFAULT_BASE_YEAR, span = DEFAULT_SPAN) if workpatterns.key?(name) raise(NameError, "Workpattern '#{name}' already exists and can't be created again") end offset = span < 0 ? span.abs - 1 : 0 @name = name @base = base @span = span @from = Time.gm(@base.abs - offset) @to = Time.gm(@from.year + @span.abs - 1, 12, 31, 23, 59) @weeks = SortedSet.new @weeks << Week.new(@from, @to) workpatterns[@name] = self @week_pattern = WeekPattern.new(self) end def week_pattern @week_pattern end # Deletes all <tt>Workpattern</tt> objects # def self.clear workpatterns.clear end # Returns an Array containing all the <tt>Workpattern</tt> objects # @return [Array] all <tt>Workpattern</tt> objects # def self.to_a workpatterns.to_a end # Returns the specific named <tt>Workpattern</tt> # @param [String] name of the required <tt>Workpattern</tt> # @raise [NameError] if a <tt>Workpattern</tt> of the supplied name does not # exist # def self.get(name) return workpatterns[name] if workpatterns.key?(name) raise(NameError, "Workpattern '#{name}' doesn't exist so can't be retrieved") end # Deletes the specific named <tt>Workpattern</tt> # @param [String] name of the required <tt>Workpattern</tt> # @return [Boolean] true if the named <tt>Workpattern</tt> existed or false # if it doesn't # def self.delete(name) workpatterns.delete(name).nil? ? false : true end # Applys a working or resting pattern to the <tt>Workpattern</tt> object. # # The #resting and #working methods are convenience methods that call # this with the appropriate <tt>:work_type</tt> already set. # # @param [Hash] opts the options used to apply a workpattern # @option opts [Date] :start The first date to apply the pattern. Defaults # to the <tt>start</tt> attribute. # @option opts [Date] :finish The last date to apply the pattern. Defaults # to the <tt>finish</tt> attribute. # @option opts [DAYNAMES] :days The specific day or days the pattern will # apply to.It defaults to <tt>:all</tt> # @option opts [(#hour, #min)] :start_time The first time in the selected # days to apply the pattern. Defaults to <tt>00:00</tt>. # @option opts [(#hour, #min)] :finish_time The last time in the selected # days to apply the pattern. Defaults to <tt>23:59</tt>. # @option opts [(WORK_TYPE || REST_TYPE)] :work_type Either working or resting. # Defaults to working. # @see #working # @see #resting # def workpattern(opts = {}) if self.class.persistence? week_pattern.workpattern(opts, @@persistence) else week_pattern.workpattern(opts) end end # Convenience method that calls <tt>#workpattern</tt> with the # <tt>:work_type</tt> specified as resting. # # @see #workpattern # def resting(args = {}) args[:work_type] = REST_TYPE workpattern(args) end # Convenience method that calls <tt>#workpattern</tt> with the # <tt>:work_type</tt> specified as working. # # @see #workpattern # def working(args = {}) args[:work_type] = WORK_TYPE workpattern(args) end # Calculates the resulting date when the <tt>duration</tt> in minutes # is added to the <tt>start</tt> date. # The <tt>duration</tt> is always in whole minutes and subtracts from # <tt>start</tt> when it is a negative number. # # @param [DateTime] start date to add or subtract minutes # @param [Integer] duration in minutes to add or subtract to date # @return [DateTime] the date when <tt>duration</tt> is added to # <tt>start</tt> # def calc(start, duration) return start if duration == 0 a_day = SAME_DAY utc_start = to_utc(start) while duration != 0 if a_day == PREVIOUS_DAY utc_start -= DAY a_day = SAME_DAY utc_start = Time.gm(utc_start.year, utc_start.month, utc_start.day,LAST_TIME_IN_DAY.hour, LAST_TIME_IN_DAY.min) week = find_weekpattern(utc_start) if week.working?(utc_start) duration += 1 end else week = find_weekpattern(utc_start) end utc_start, duration, a_day = week.calc(utc_start, duration, a_day) end to_local(utc_start) end # Returns true if the given minute is working and false if it is resting. # # @param [DateTime] start DateTime being tested # @return [Boolean] true if working and false if resting # def working?(start) utc_start = to_utc(start) find_weekpattern(utc_start).working?(utc_start) end # Returns number of minutes between two dates # # @param [DateTime] start is the date to start from # @param [DateTime] finish is the date to end with # @return [Integer] number of minutes between the two dates # def diff(start, finish) utc_start = to_utc(start) utc_finish = to_utc(finish) utc_start, utc_finish = utc_finish, utc_start if utc_finish < utc_start minutes = 0 while utc_start != utc_finish week = find_weekpattern(utc_start) r_minutes, utc_start = week.diff(utc_start, utc_finish) minutes += r_minutes end minutes end # Retrieve the correct <tt>Week</tt> pattern for the supplied date. # # If the supplied <tt>date</tt> is outside the span of the # <tt>Workpattern</tt> object then it returns an all working <tt>Week</tt> # object for the calculation. # # @param [DateTime] date whose containing <tt>Week</tt> pattern is required # @return [Week] <tt>Week</tt> object that includes the supplied # <tt>date</tt> in it's range # def find_weekpattern(date) # find the pattern that fits the date # if date < @from result = Week.new(Time.at(0), @from - MINUTE, WORK_TYPE) elsif date > to result = Week.new(@to + MINUTE, Time.new(9999), WORK_TYPE) else date = Time.gm(date.year, date.month, date.day) result = @weeks.find { |week| week.start <= date && week.finish >= date } end result end end end
true
03ac83818d5f790203bb238223a0c9f22681ae83
Ruby
emars/gumroad-sdk
/lib/gumroad/user.rb
UTF-8
471
2.671875
3
[ "MIT" ]
permissive
require 'faraday' require 'json' API_ROOT = 'https://api.gumroad.com/v2/user' module Gumroad class User attr_reader :name, :id, :bio, :email def initialize(attrs) @name = attrs['name'] @id = attrs['id'] @bio = attrs['bio'] @email = attrs['email'] end def self.get response = Faraday.get("#{API_ROOT}", {'access_token' => Gumroad.token}) attrs = JSON.parse(response.body) new(attrs['user']) end end end
true
f9019591e1da3d96bb409a68db5de055cf8d1eaa
Ruby
hasulica/learn_to_program
/ch14-blocks-and-procs/program_logger.rb
UTF-8
323
3.109375
3
[]
no_license
def program_log desc, &block puts 'Beginning "' + desc + '"...' result = block.call puts '..."' + desc + '" finished, returning: ' + result.to_s end program_log 'outer block' do program_log 'some little block' do 5 end program_log 'yet another block' do '!doof iahT ekil I'.reverse end false end
true
539f8d0d31f8979260c7242ec9544eb97e6f0f22
Ruby
cowboy-cod3r/sandbox
/ivv-grid/perf-drb.rb
UTF-8
2,001
2.5625
3
[]
no_license
#!/opt/apps/ruby/ruby/bin/ruby require 'ivv-drb-client' require 'date' require 'json' # How many tests to execute per machine range = 1..1 threads = [] # How many times the test should execute max = 1 max_range = 1..max # Set the hosts file hosts_yml = "humbarger-daily-int-hosts.yml" hosts_yml_loc = File.join(File.dirname(__FILE__),"hosts",hosts_yml) # The nodes that will execute the tests port = "8010" nodes = [ "172.30.13.201", "172.30.13.202", "172.30.13.203", "172.30.13.204", "172.30.13.205", "172.30.13.206", "172.30.13.207", "172.30.13.208", "172.30.13.209", "172.30.13.210", "172.30.13.211", "172.30.13.212", "172.30.13.213", "172.30.13.214", "172.30.13.215", "172.30.13.216", "172.30.13.217", "172.30.13.218", "172.30.13.219", "172.30.13.220" ] features = {} ret_val = {} time_diffs = [] max_range.each do |x| puts "Executing test #{x} of #{max}" start_time = DateTime.now() nodes.each do |node| range.each do |i| threads << Thread.new(i.to_s + node) do |thread| features[Thread.current.object_id] = IVV::Drb::Objects::Features.new(node,port) features[Thread.current.object_id].instantiate() features[Thread.current.object_id].override_hosts(hosts_yml_loc) ret_val[Thread.current.object_id] = features[Thread.current.object_id].execute_ivv("--browser","chrome","--performance") end end end threads.each do |thread| thread.join() end # Calculate Time Difference end_time = DateTime.now() diff = ((start_time - end_time) * 24 * 60 * 60).to_i time_diffs << diff.abs end final = [] ret_val.each do |k,v| final.concat(v) end results = JSON.generate(ret_val) results_file = File.join(File.dirname(__FILE__),"results","results.json") File.open(results_file, 'w') { |file| file.write(results) } avg = time_diffs.inject{ |sum, el| sum + el }.to_f / time_diffs.size puts puts time_diffs.to_json puts puts "Average thread time was '#{avg.to_s}' seconds"
true
bacccce0239158047007acdc75666d1c56496e7f
Ruby
lenadevoto/W1D5
/skeleton/lib/00_tree_node.rb
UTF-8
783
3.578125
4
[]
no_license
class PolyTreeNode attr_accessor :value attr_reader :parent, :children def initialize(value = nil) @value = value @parent = nil @children = [] end # def children # @children.dup # end def parent=(new_parent) return if self.parent == new_parent @parent.children.delete(self) unless @parent.nil? @parent = new_parent @parent.children << self unless @parent.nil? # self end def add_child(new_child) return if self.children.include?(new_child) # self.children << new_child new_child.parent = self end def remove_child(child_node) raise 'Not a child' unless self.children.include?(child_node) child_node.parent = nil end def dfs(target_value) return if target_value == self.value end end
true
7979fe03dbee16604fbb8b49a010c5723198f20d
Ruby
webclinic017/stock_trend_finder
/lib/market_data_utilities/file_utilities.rb
UTF-8
294
2.609375
3
[]
no_license
require 'open-uri' module FileUtilities def download_file(url, local_path, print: true) puts "Downloading #{url} > #{local_path}" if print open(local_path, 'w') do |file| file << open(url).read end end def downloads_folder File.join(Dir.pwd, 'downloads') end end
true
34e7976b33228972499ef2f907c10b90523b92c7
Ruby
chikoski/sqsapi
/lib/sqs/api.rb
UTF-8
1,211
2.578125
3
[]
no_license
require 'sqs' require 'find' class SQS::API @@logger = nil class << self def setup(config_file) load_config(config_file) init_logger load_jar_files end def init_logger @@logger = Logger.new(STDERR) if config.loglevel == "debug" @@logger.level= Logger::DEBUG else @@logger.level = Logger::INFO end end def config return SQS::API::Config.instance end def logger return @@logger end def debug(msg) logger.debug(msg) end def info(msg) logger.info(msg) end def warn(msg) logger.warn(msg) end def error(msg) logger.error(msg) end protected def load_config(file) SQS::API::Config.load(file) end def load_jar_files require 'java' repository = config.m2 repository = File.expand_path(".m2", ENV["HOME"]) unless repository && File.directory?(repository) info("load jar files inside #{repository}") Find.find(repository){|file| if file =~ /\.jar$/ debug("load #{file}") require file end } end end end require 'sqs/api/config'
true
605585fe8c94f1a29155afdd2e1aaabd14c4b9d0
Ruby
Elliot-Cho/interview-assessment-1
/warehouse/app/interactions/customers/quote_pricing.rb
UTF-8
492
2.640625
3
[]
no_license
require 'active_interaction' module Customers # Interaction to quote customers on the pricing of storing their items class QuotePricing < ActiveInteraction::Base object :customer, class: Customer validate :customer_has_items def execute ::CustomerHelper::PriceQuoter.quote_pricing(customer, customer.items) end private # Validation def customer_has_items errors.add(:item, 'customer has no items') unless customer.items.any? end end end
true
4e8c54ec47b9df3b2673afe40a55e49a4f46b2c8
Ruby
lelesrc/rails-marionet
/lib/marionet/slot.rb
UTF-8
519
2.65625
3
[]
no_license
class Marionet::Slot require 'open-uri' require 'hpricot' attr_accessor :url, :html, :name, :header, :body def initialize(url,name) @url = url @name = name begin f = open(url) rescue return false else f.rewind @html = f.readlines.join("\n") doc = Hpricot(@html) @header = doc.search("head").to_s @body = doc.search("body").to_s return true end end def render return "<div class=\"#{self.name}\">#{self.body}</div>" end end
true
3361a6a104c7b178fa12f35ad23f63b40f16c5b9
Ruby
thib123/TPJ
/Notes/Ruby/sample_code/ex0541.rb
UTF-8
106
2.6875
3
[ "MIT" ]
permissive
# Sample code from Programing Ruby, page 307 3.times do print 'hello'.object_id, " " end puts
true
54ba1b2d820597dfcb1326022622a471e8488794
Ruby
haibaer76/st0nk
/config/initializers/load_stonk_config.rb
UTF-8
1,035
3.28125
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
require 'ostruct' # creates a new OpenStruct from the given hash # converts all values which are hashes to OpenStruct recursively # converts all values which are arrays recursively def create_ostruct_from_hash(hash) ret = OpenStruct.new(hash) hash.each do |key, value| if value.is_a?(Hash) ret.send("#{key}=", create_ostruct_from_hash(value)) elsif value.is_a?(Array) ret.send("#{key}=", create_ostruct_array(value)) end end ret end # creates an array from the given array # iterates through all elements # if the element is a hash, create an OpenStruct # if the element is an array, call this function recursively def create_ostruct_array(array) ret = [] array.each do |value| if value.is_a?(Hash) ret << create_ostruct_from_hash(value) elsif value.is_a?(Array) ret << create_ostruct_array(value) else ret << value end end ret end attributes = YAML.load_file("#{RAILS_ROOT}/config/stonk.yml")[RAILS_ENV] STONK_CONFIG = create_ostruct_from_hash(attributes)
true
b567df12fc32639f68ad522e5fc0dbce744a141e
Ruby
arnabs542/Programming-Interview-Questions
/Problems/Ruby/longest_common_subsequence.rb
UTF-8
2,552
4.34375
4
[ "MIT" ]
permissive
# Given two sequences, find the length of the longest subsequence present in both of them. # A subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. # For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. # SOLUTION: # Pseudocode # I) # We will first construct a 2D table from inputs string1 and string2 with a helper function common_subsequence_table; # we will build this table in a bottom up way. # The elements of the table, table[i][j], will contain the length of the longest # common subsequence of string1[0..i-1] and strin2[0..j-1] # The helper function, common_subsequence_table, returns this table # The table will be built using the formula below: # table[i][j] = 0 if i = 0 or j = 0 # table[i][j] = table[i-1][j-1] + 1 if i > 0, j > 0, and string1[i] = string2[j] # table[i][j] = max(table[i, j-1], table[i-1, j]) if i, j > 0 and tring1[i] != string2[j] # II) def longest_common_subsequence(string1, string2) table = common_subsequence_table(string1, string2) result = "" i = string1.length j = string2.length # we start from right bottom corner of table and 1 by 1 we store the common characters (of string1 and string2) into result. while i > 0 && j > 0 # if current character in string1 and string2 are the same, we add it to result if string1[i-1] == string2[j-1] result.insert(0, string1[i-1]) # put current character at begining of result i -= 1 # decrement both i and j j -= 1 # If the 2 characters are not the same, find the largest of 2 elements (left or up) from table and go into that direction elsif table[i-1][j] > table[i][j-1] i -= 1 else j -= 1 end end result end def common_subsequence_table(string1, string2) len1 = string1.length len2 = string2.length table = Array.new(len1+1) {Array.new(len2+1)} i = 0 while i <= len1 j = 0 while j <= len2 if i == 0 || j == 0 table[i][j] = 0 elsif string1[i-1] == string2[j-1] table[i][j] = table[i-1][j-1] + 1 else table[i][j] = maximum(table[i][j-1], table[i-1][j]) end j += 1 end i += 1 end table end def maximum(a, b) a > b ? a : b end p longest_common_subsequence("ABCBDAB", "BDCABC") == "BDAB" p longest_common_subsequence("abc", "d") == "" p longest_common_subsequence("ab", "a") == "a" p longest_common_subsequence("ABCDGH", "AEDFHR") == "ADH" p longest_common_subsequence("AGGTAB", "GXTXAYB") == "GTAB"
true
8b400971e63fdb10d66ddf464cb7a565aaf99272
Ruby
avivrosenberg/dotfiles
/bin.symlink/brew-updated.rb
UTF-8
621
3.046875
3
[]
no_license
# require the Homebrew commands needed require 'cmd/update' require 'cmd/outdated' ### # Just a helper to print bold output def bold(str) console_bold="\e[1m" console_reset="\e[0m" "#{console_bold}#{str}#{console_reset}" end ### # Main function def brew_updated # Update homebrew puts bold "==> Updating homebrew" Homebrew.update # Call homebrew internal function to get number of outdated brews num_outdated = Homebrew.outdated_brews(Formula.installed).length # Print outdated brews if num_outdated > 0 puts bold "==> Outdated brews" Homebrew.outdated end end # do it... brew_updated
true
4a3b6b1f294aabc62b343aed03c066868f8ec23f
Ruby
TimurM/aa_academy
/week2/w2d5 2/arrays_with_rspec/spec/towers_of_hanoi_spec.rb
UTF-8
1,410
3.84375
4
[]
no_license
require 'rspec' require 'towers_of_hanoi.rb' describe Towers do it "creates three arrays representing piles of disks" do expect(Towers.generate_discs.count).to eq(3) end it "create an array where three disks in the first stack" do expect(Towers.generate_stacks.count).to eq(3) end describe 'a towers instance' do subject(:game) { Towers.new } it "initialize stacks for the the game when class loads" do expect(game.stacks).to eq([[3, 2, 1], [], []]) end it "should not win the game" do expect(game.won?).to eq(false) end it "should move disks from one column to user's choice " do expect(game.move(0, 1)).to eq([[3, 2], [1], []]) end it "should return true if the user won the game" do game.move(0,1) game.move(0,2) game.move(1,2) game.move(0,1) game.move(2,0) game.move(2,1) game.move(0,1) expect(game.won?).to eq(true) end end end #Functionality: #Create three array which contain the piles of disks #Create a loop that will ask the user for input #Get the user to tell you the move from where and to where they want to move the disks #check to see if the from place contains disks #check to see if the to place is empty or is greater than the 'new disk' #Check to see if the user won #UI #Display the board #Make sure the arrays contain display correct number of discs
true
670a252056a90ab7c0b4dc18a552b8784ce91360
Ruby
learn-co-students/atl-web-042219
/11-activerecord-associations/app/app_cli.rb
UTF-8
594
3.546875
4
[]
no_license
class AppCLI def run puts "Welcome to the zoo browser" puts "what would you like to do today?" main_menu end def main_menu puts "1 - List our zoos" puts "2 - List our animals" puts "3 - quit" choice = gets.chomp.to_i until choice == 3 case choice when 1 list_zoos when 2 list_animals else puts "That was definitely not one of our choices. Try again." end end end def list_zoos zoos = Zoo.all zoos.each do |zoo| puts "The #{zoo.name} is in #{zoo.location}" end end end
true
4a09d4568e5c9d76a3a54c56e1785bafc5d73036
Ruby
matipacheco/i-dont-know-shit
/models/battle.rb
UTF-8
1,315
3.75
4
[]
no_license
require_relative 'character' require_relative '../mongo_connection' # Game class. It represents the fight between two Character's # The fight logic isnt 100% correct, but you get the idea of it :smirk: class Battle attr_accessor :fighter1, :fighter2, :game_over, :winner def initialize(fighters_json = nil) fighters = fighters_json.nil? ? fighters_from_collection : fighters_from_json(fighters_json) @game_over = !fighters.map(&:alive?).all? @fighter1, @fighter2 = fighters.sort_by(&:dice_roll).reverse end def fighters_from_json(fighters_json) fighters_json.map { |fighter| Character.new.from_json(fighter) } end def fighters_from_collection collection = connect_to_mongo collection.aggregate([{ '$sample' => { 'size' => 2 } }]).map { |fighter| Character.new.from_json(fighter.to_json) } end def attack(fighter1, fighter2) unless fighter1.alive? @game_over = true @winner = fighter2 return end fighter2.hp -= fighter1.str end def fight! attack(@fighter1, @fighter2) unless @game_over attack(@fighter2, @fighter1) unless @game_over end def and_the_winner_is @winner.name + ' WINS!' end def give_em_hell! while !@game_over fight! end return and_the_winner_is end end
true
838822c1cabd8d8907e2c2034ecd210de0de74b8
Ruby
AhmedAliIbrahim/fawry
/lib/fawry/utils.rb
UTF-8
1,009
2.671875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module Fawry module Utils TRUTH_VALUES = [true, 'true', '1', 't'].freeze # Adds keys from fawry API response as methods # on object instance that return the value # of each key # # type => type # referenceNumber => reference_number # merchantRefNumber => merchant_ref_number # expirationTime => expiration_time # statusCode => status_code # statusDescription => status_description # # fawry_res = FawryResponse.new(response) # fawry_res.status_code => 200 # fawry_res.reference_number => 1234567 def enrich_object(fawry_params) fawry_params.each_key do |key| method_name = key.to_s.split(/(?=[A-Z])/).map(&:downcase).join('_') # statusCode => status_code instance_variable_set("@#{method_name}", fawry_params[key]) method_body = proc { instance_variable_get("@#{method_name}") } self.class.public_send(:define_method, method_name, method_body) end end end end
true
7143d3cd19ceac5cd7ca5184a1e92635354451b4
Ruby
AndreySereda/gotoinc-school
/lesson1_ex3.rb
UTF-8
270
3.703125
4
[]
no_license
puts "Введите 3 значения для вычесления среднего арифметического" a = gets.chomp.to_f b = gets.chomp.to_f c = gets.chomp.to_f d = (a + b + c) / 3 puts "Cреднее арифметическое чисел:" + d.to_s
true
3c1fa61c93372fdd3f372c01982e7846ddc9aa70
Ruby
bradq/rubysh
/lib/rubysh/subprocess/pipe_wrapper.rb
UTF-8
2,091
2.765625
3
[ "MIT" ]
permissive
class Rubysh::Subprocess class PipeWrapper begin require 'json' SERIALIZER = JSON rescue LoadError => e if ENV['RUBYSH_ENABLE_YAML'] require 'yaml' SERIALIZER = YAML else raise LoadError.new("Could not import JSON (#{e}). You should either run in an environment with rubygems and JSON, or you can set the RUBYSH_ENABLE_YAML environment variable to allow Rubysh to internally use YAML for communication rather than JSON. This is believed safe, but YAML-parsing of untrusted input is bad, so only do this if you really can't get JSON.") end end attr_accessor :reader, :writer def initialize(reader_cloexec=true, writer_cloexec=true) @reader, @writer = IO.pipe set_reader_cloexec if reader_cloexec set_writer_cloexec if writer_cloexec end def read_only @writer.close end def write_only @reader.close end def close @writer.close @reader.close end def set_reader_cloexec @reader.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) end def set_writer_cloexec @writer.fcntl(Fcntl::F_SETFD, Fcntl::FD_CLOEXEC) end def nonblock [@reader, @writer].each do |fd| fl = fd.fcntl(Fcntl::F_GETFL) fd.fcntl(Fcntl::F_SETFL, fl | Fcntl::O_NONBLOCK) end end def dump_json_and_close(msg) dumped = SERIALIZER.dump(msg) @writer.write(dumped) ensure @writer.close Rubysh.assert(@reader.closed?, "Reader should already be closed") end def load_json_and_close contents = @reader.read return false if contents.length == 0 begin SERIALIZER.load(contents) rescue ArgumentError => e # e.g. ArgumentError: syntax error on line 0, col 2: `' (could # happen if the subprocess was killed while writing a message) raise Rubysh::Error::BaseError.new("Invalid message read from pipe: #{e}") end ensure @reader.close Rubysh.assert(@writer.closed?, "Writer should already be closed") end end end
true
76ef7ab712267c604addc3ba053d73c07315ab5c
Ruby
CDL-Dryad/dryad-app
/lib/stash/repo/submission_result.rb
UTF-8
2,052
2.859375
3
[ "MIT" ]
permissive
require 'logger' module Stash module Repo # Encapsulates a submission result class SubmissionResult attr_reader :resource_id, :request_desc, :message, :error attr_accessor :deferred # @param resource_id [Integer] the ID of the submitted resource # @param request_desc [String, nil] a description of the request that produced this result # @param message [String, nil] an optional log message # @param error [Error, nil] an error indicating a failed result def initialize(resource_id:, request_desc:, message: nil, error: nil) @resource_id = resource_id @request_desc = request_desc @message = message @error = error # for asynchronous processing, gets set if the request is deferred (which is all the time now, but previously # some items were submitted synchronously) @deferred = true end def success? error.nil? end def deferred? @deferred end def log_to(logger) success? ? log_success_to(logger) : log_failure_to(logger) end def self.success(resource_id:, request_desc:, message: nil) SubmissionResult.new(resource_id: resource_id, request_desc: request_desc, message: message) end def self.failure(resource_id:, request_desc:, error: nil) SubmissionResult.new(resource_id: resource_id, request_desc: request_desc, error: error) end protected def log_success_to(logger) msg = "Submission successful for resource #{resource_id}" msg << ': ' << message if message logger.info(msg) end def log_failure_to(logger) msg = "Submission failed for resource #{resource_id}" msg << ': ' << message if message msg << "\n" << error.to_s msg << "\n" << error.full_message if backtrace_str logger.error(msg) end def backtrace_str return unless error.respond_to?(:backtrace) error.full_message end end end end
true
b1e47c510e6890616388be415dbb0a99816b866b
Ruby
JeremyVe/project_tdd_minesweeper
/lib/board.rb
UTF-8
4,989
3.40625
3
[]
no_license
require_relative 'cell' class Board attr_accessor :board, :board_size, :bombs, :count attr_reader :game_over def initialize (board_size = 10, bombs = 9) @count = (board_size ** 2) - bombs @board = {} @board_size = board_size @bombs = bombs @flags_nb = bombs @game_over = false create_board(board_size) end def create_board (board_size) (1..board_size).each do |col| @board[col] = {} end (1..board_size).each do |col| (1..board_size).each do |row| @board[col][row] = Cell.new end end end def create_bombs @bombs.times do |cell| bomb_placed = false until bomb_placed col = rand(1..@board_size) row = rand(1..@board_size) unless select_cell(col, row).state == "B" select_cell(col, row).state = "B" select_cell(col, row).is_bomb = true bomb_placed = true end end end end def create_bomb_indication @board.each do |col_idx, col| col.each do |row_idx, cell| if col_idx > 1 if @board[col_idx-1][row_idx].state == "B" cell.state += 1 unless cell.state == "B" end end if col_idx < @board_size if @board[col_idx+1][row_idx].state == "B" cell.state += 1 unless cell.state == "B" end end if row_idx > 1 if @board[col_idx][row_idx-1].state == "B" cell.state += 1 unless cell.state == "B" end end if row_idx < @board_size if @board[col_idx][row_idx+1].state == "B" cell.state += 1 unless cell.state == "B" end end if col_idx > 1 && row_idx > 1 if @board[col_idx-1][row_idx-1].state == "B" cell.state += 1 unless cell.state == "B" end end if col_idx > 1 && row_idx < @board_size if @board[col_idx-1][row_idx+1].state == "B" cell.state += 1 unless cell.state == "B" end end if col_idx < @board_size && row_idx < @board_size if @board[col_idx+1][row_idx+1].state == "B" cell.state += 1 unless cell.state == "B" end end if col_idx < @board_size && row_idx > 1 if @board[col_idx+1][row_idx-1].state == "B" cell.state += 1 unless cell.state == "B" end end end end end def select_cell(col, row) @board[col][row] end def render_board (reveal = nil) @board_size > 9 ? (print "##|") : (print "#|") @board_size.times {|i| print "#{i+1}|"} puts @board.each do |index, col| index > 9 ? (print "#{index}|") : (print "#{index} |") col.each do |row, cell| if reveal == true print cell.state.to_s + "|" else if cell.flag == true print "F" + "|" elsif cell.reveal == false print "_" + "|" else print cell.state.to_s + "|" end end end puts end puts "count: #{@count}, flags: #{@flags_nb}" end def check_move input if valid_move? input if input[2] == "C" make_move input else if @board[input[0]][input[1]].flag @board[input[0]][input[1]].flag = false @flags_nb += 1 else @board[input[0]][input[1]].flag = true @flags_nb -= 1 end end end end def check_game_over if @count == 0 puts "You Win !" @game_over = true end end def valid_move? input if input[0] == "Q" @game_over = true return false end return true if @board[input[0]][input[1]].reveal == false puts "cannot make this move" end def make_move input if @board[input[0]][input[1]].state == "B" puts "It was a Bomb !" render_board true @game_over = true elsif @board[input[0]][input[1]].state > 0 @board[input[0]][input[1]].reveal = true @count -= 1 else col, row = input[0], input[1] check_around col, row end end def check_around col, row if @board[col][row].state > 0 && @board[col][row].reveal == false @board[col][row].reveal = true @count -= 1 elsif @board[col][row].reveal == false @board[col][row].reveal = true @count -= 1 if col > 1 check_around col-1, row end if col < @board_size check_around col+1, row end if row > 1 check_around col, row-1 end if row < @board_size check_around col, row+1 end if col > 1 && row > 1 check_around col-1, row-1 end if col > 1 && row < @board_size check_around col-1, row+1 end if col < @board_size && row > 1 check_around col+1, row-1 end if col < @board_size && row < @board_size check_around col+1, row+1 end end end end
true
60dc797f1e860428215aa0b66744030792dbd3c3
Ruby
russenoire/LS_core
/rb101/exercises/small_problems/easy_2/008_sum_or_product_extra.rb
UTF-8
291
4.1875
4
[]
no_license
puts ">> Please enter an integer greater than 0:" int_input = gets.chomp.to_i puts ">> Enter 's' to compute the sum, 'p' to compute the product." exp_input = gets.chomp case exp_input when 's' puts (1..int_input).sum when 'p' puts (1..int_input).reduce { |product, n| product * n } end
true
a711a32e8d4d46229cf6b3f934df37d89e339f54
Ruby
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/ruby/bob/ec1d43f13d054e49b577b0b3c9df7ada.rb
UTF-8
407
3.8125
4
[]
no_license
class Bob def hey(phrase) case when is_silent?(phrase) 'Fine. Be that way.' when is_shouting?(phrase) "Woah, chill out!" when is_question?(phrase) 'Sure.' else "Whatever." end end def is_silent?(phrase) phrase.empty? end def is_shouting?(phrase) phrase == phrase.upcase end def is_question?(phrase) phrase.end_with?("?") end end
true
81573bbab38098e5ad44cfbe65643dfc5e028d44
Ruby
Aalto-LeTech/stops
/script/list_course_prereqs.rb
UTF-8
580
2.75
3
[]
no_license
# lists all # scoped courses # with their abstract course code # and their prereq course names # ScopedCourse.all.each do |scoped_course| puts "Scoped: #{scoped_course.localized_description.name}" if scoped_course.abstract_course puts "Abstract: #{scoped_course.abstract_course.code}" else puts "Abstract: NULL" end if scoped_course.prereqs.size > 0 puts "Prereqs:" scoped_course.prereqs.each do |prereq_course| puts " - #{prereq_course.localized_description.name}" end else puts "Prereqs: NONE" end puts "\n\n" end
true
5091d4c568bfc2d033bac2a8a8522a08970855d3
Ruby
MeZKaL/adyen
/lib/adyen/rest/payout.rb
UTF-8
3,251
2.6875
3
[ "MIT" ]
permissive
module Adyen module REST # This module implements the <b>Payout</b> # API calls, and includes a custom response class to make handling the response easier. # https://docs.adyen.com/developers/payout-manual module Payout class Request < Adyen::REST::Request protected def base_path '/pal/servlet/%s/v25/%s' end end class Response < Adyen::REST::Response def success? result_code == SUCCESS end def received? result_code == RECEIVED end def confirmed? response == CONFIRMED end def declined? response == DECLINED end def result_code self[:result_code] end def psp_reference self[:psp_reference] end def response self[:response] end SUCCESS = 'Success'.freeze RECEIVED = '[payout-submit-received]'.freeze CONFIRMED = '[payout-confirm-received]'.freeze DECLINED = '[payout-decline-received]'.freeze private_constant :SUCCESS, :RECEIVED, :CONFIRMED, :DECLINED end # Constructs and issues a Payment.capture API call. def store_payout(attributes = {}) request = store_request('Payout.storeDetail', attributes) execute_request(request) end def submit_payout(attributes = {}) request = store_request('Payout.submit', attributes) execute_request(request) end def submit_and_store_payout(attributes = {}) request = store_request('Payout.storeDetailAndSubmit', attributes) execute_request(request) end def submit_payout_third_party(attributes = {}) request = store_request('Payout.submitThirdParty', attributes) execute_request(request) end def submit_and_store_payout_third_party(attributes = {}) request = store_request('Payout.storeDetailAndSubmitThirdParty', attributes) execute_request(request) end def confirm_payout(attributes = {}) request = review_request('Payout.confirm', attributes) execute_request(request) end def confirm_payout_third_party(attributes = {}) request = review_request('Payout.confirmThirdParty', attributes) execute_request(request) end def decline_payout(attributes = {}) request = review_request('Payout.decline', attributes) execute_request(request) end def decline_payout_third_party(attributes = {}) request = review_request('Payout.declineThirdParty', attributes) execute_request(request) end private # Require you to use a client initialize with payout_store def store_request(action, attributes) Adyen::REST::Payout::Request.new(action, attributes, response_class: Adyen::REST::Payout::Response ) end # Require you to use a client initialize with payout review def review_request(action, attributes) Adyen::REST::Payout::Request.new(action, attributes, response_class: Adyen::REST::Payout::Response ) end end end end
true
a5c97fb09ac36016756ca86566d3d5c2a5a4b185
Ruby
svencu/ruby
/age.rb
UTF-8
449
4
4
[]
no_license
puts "What is your name?" name = gets.chomp puts "What is your age?" age = gets.chomp.to_i puts "What is your gender (m/f)?" gender = gets.chomp if gender == "m" salutation = "Sir" else if gender == "f" salutation = "Madam" else salutation = "genderless" end end date = ((100 - age) + Time.now.year) date = date.to_s puts "Dear #{salutation} #{name}, you will turn a 100 years old in #{date}"
true
bae4f7124853714cd8cc1a93dcb8d78053841090
Ruby
andrewpurcell/lost-cities
/test/lost_cities_test.rb
UTF-8
1,209
2.9375
3
[]
no_license
require_relative 'test_helper' describe LostCities do describe LostCities::DeckBuilder do before do @cards = LostCities::DeckBuilder.build_cards(LostCities::Suit.all, 2..10, 3) end it 'includes the right stuff' do assert_equal 5*12, @cards.count assert_equal 5*3, @cards.count(&:investor?) end end def new_card(suit, value) LostCities::Card.value_card suit, value end describe LostCities::Card do it 'can be compared' do small_card = new_card 'Egypt', 2 big_card = new_card 'Egypt', 6 different_suit = new_card 'Amazon', 6 assert big_card >= small_card assert big_card >= nil refute big_card == different_suit end end describe LostCities::Hand do def new_hand(*args) LostCities::Hand.new args end before do @hand = new_hand(new_card('Egypt', 5), new_card('Egypt', 6), new_card('Amazon', 5)) end let(:other_card) { new_card 'Amazon', 6 } it 'can add and remove cards' do refute @hand.full?, 'Hand should not be full' @hand.add other_card assert_equal 4, @hand.size @hand.remove other_card assert_equal 3, @hand.size end end end
true
61ff90db517df8306bab59e0c09fcef6e09ed4e9
Ruby
HomeBusProjects/homebus-wunderground
/vendor/ruby-homebus/lib/homebus.rb
UTF-8
1,115
2.703125
3
[ "MIT" ]
permissive
require 'net/http' require 'pp' class HomeBus # in order to provision, we contact # HomeBus.local/provision # and POST a json payload of { provision: { mac_address: 'xx:xx:xx:xx:xx:xx' } } # you get back another JSON object # uuid, mqtt_hostname, mqtt_port, mqtt_username, mqtt_password # save this in .env.provision and return it in the mqtt parameter def self.provision(mac_address) uri = URI('http://homebus/provision') request = { provision: { mac_address: mac_address } } req = Net::HTTP::Post.new(uri, 'Content-Type' => 'application/json') req.body = request.to_json res = Net::HTTP.start(uri.hostname, uri.port) do |http| res = http.request(req) return nil unless res.code == "200" answer = JSON.parse res.body, symbolize_names: true mqtt = Hash.new mqtt[:host] = answer[:mqtt_hostname] mqtt[:port] = answer[:mqtt_port] mqtt[:username] = answer[:mqtt_username] mqtt[:password] = answer[:mqtt_password] mqtt[:uuid] = answer[:uuid] return mqtt end return nil end end
true
5f69efdfc673b85b839fcdb2189b30ef4e1d3262
Ruby
fivesenses/cropster
/lib/cropster/response/location.rb
UTF-8
502
2.71875
3
[ "MIT" ]
permissive
## # Converts a Hash object into a Cropster::Response::Location object # module Cropster::Response class Location < Cropster::Response::FormattedResponseItem attr_accessor :name, :street, :zip, :city, :country # @param attributes [Hash] def load_attributes(attributes) return if attributes.nil? @name = attributes[:name] @street = attributes[:street] @zip = attributes[:zip] @city = attributes[:city] @country = attributes[:country] end end end
true
6b520fc28cd9f37dbbe4a2238be7b0dc1db6f784
Ruby
oya3/ruby_tools
/common_modules/signature_stamper.rb
SHIFT_JIS
24,107
2.578125
3
[]
no_license
# coding: cp932 require 'cairo' require 'pango' require 'stringio' require 'win32/clipboard' Encoding.default_external = 'cp932' Encoding.default_internal = 'cp932' # ȂƕiR[h\jɂȂB class SignatureStamper #NX萔 #PI2 = Math::PI*2 # 360xp DEFAULT_SIZE = 200 def initialize( param = nil) @inparam = createInitialParameter() # ftHglݒ setParameter(@inparam,param) @surface = createSignatureImage(@inparam) # q摜 Cairo::ImageSurface 쐬 end # p[^𐶐 def createInitialParameter() param = {} param[:format] = Cairo::FORMAT_ARGB32 param[:size] = DEFAULT_SIZE param[:line_angle] = 20 param[:back_color] = 0xffffffff # param[:font_color] = 0xffff0000 # param[:circle_type] = 'double' # or single param[:rotate_degrees] = 0 # 0-360 #param[:special_mode] = 0 # param[:top_font] = 'HGSeikaishotaiPRO' param[:mid_font] = 'Arial' param[:btm_font] = 'HGSeikaishotaiPRO' param[:top_string] = 'fl' param[:mid_string] = '\'13.10.02' param[:btm_string] = '' param[:tx] = 0 param[:ty] = 0 return param end # p[^ݒ肷 def setParameter(param,args) # w肳ꂽp[^ōXV if ( args ) then args.each do | (key , value ) | param[key] = value end end #param[:size] = 500 # vZXԂKɃ_L[ param[:seed] = Time.new().usec random = nil # w肪΂̒lŃ_L[Ƃ if( param[:special_mode] ) then if( param[:special_mode].to_i != 0 ) then param[:seed] = param[:special_mode].to_i end random = Random.new(param[:seed]) end # calc image size paramter param[:diameter_big] = param[:size] * 80 / 100 # g͑Ŝ80% # c20%sړʕɂƂĂBڂ̂ŁB param[:diameter] = param[:size] * 72 / 100 # g͑Ŝ72% param[:line_size] = param[:diameter] / 45 # ͓̑K param[:date_font_size] = param[:diameter] / 7 # ttHgTCYK param[:font_size] = param[:diameter] / 5 # tHgTCYK param[:width] = param[:size] param[:height] = param[:size] param[:center_x] = param[:width] / 2 param[:center_y] = param[:height] / 2 param[:radius_big] = param[:diameter_big] / 2 # O̔a param[:radius] = param[:diameter] / 2 # ̔a # set background color. param[:back_color_red] = getRed(param[:back_color]) param[:back_color_green] = getGreen(param[:back_color]) param[:back_color_blue] = getBlue(param[:back_color]) param[:back_color_alpha] = getAlpha(param[:back_color]) # set font color. param[:font_color_red] = getRed(param[:font_color]) param[:font_color_green] = getGreen(param[:font_color]) param[:font_color_blue] = getBlue(param[:font_color]) param[:font_color_alpha] = getAlpha(param[:font_color]) # font size ( ͍őPO܂łƂȂƂ܂BjAɌvZƔq炵ȂȂBBBj param[:scale] = param[:size].to_f / DEFAULT_SIZE.to_f param[:top_string_info] = createStringInfo(param[:top_font], param[:top_string], param[:font_color], param[:scale], random) param[:btm_string_info] = createStringInfo(param[:btm_font], param[:btm_string], param[:font_color], param[:scale], random) param[:mid_string_info] = createStringInfo(param[:mid_font], param[:mid_string], param[:font_color], param[:scale], random) #param[:top_string_font_size] = param[:font_size] #param[:mid_string_font_size] = param[:date_font_size] #param[:btm_string_font_size] = param[:font_size] if( random ) then # ꏈFpx+sړl param[:rotate_degrees] = random.rand(30) - 15 # -15 ` 15x param[:tx] = random.rand( param[:center_x]/4) - (param[:center_x]/8) param[:ty] = random.rand( param[:center_y]/4) - (param[:center_y]/8) end param[:random] = random end # \𐶐 def createStringInfo(font, string, font_color,scale,random) # 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 font_size_table = [ 28, 28, 26, 23, 19, 17, 15, 13, 12, 11 ] font_size_table_xoffset = [ 0, 0, 3, 4, 4, 3, 3, 2, 2, 3 ] stringInfo = Hash.new stringInfo[:length] = string.length > 10 ? 10: string.length stringInfo[:font] = font stringInfo[:string] = string stringInfo[:string_yoffset] = Array.new(string.length,0) # [ if( random ) then range = (4 * scale).to_i string.length.to_i.times do |index| stringInfo[:string_yoffset][index] = random.rand(range)-(range/2) end end stringInfo[:font_color_red] = getRed(font_color) stringInfo[:font_color_green] = getGreen(font_color) stringInfo[:font_color_blue] = getBlue(font_color) stringInfo[:font_color_alpha] = getAlpha(font_color) if( stringInfo[:string] =~ /^[ -~-]*$/ ) then # Sp̏ꍇ́A1.7{Ă stringInfo[:font_size] = ((font_size_table[stringInfo[:length]-1] * scale) * 1.7).to_i stringInfo[:xoffset] = ((font_size_table_xoffset[stringInfo[:length]-1] * scale) * 1.0).to_i if( stringInfo[:string] =~ /^[0-9'.,]*$/ ) then # tۂ‚͕\ʒuItZbg͐ݒ肵Ȃ stringInfo[:xoffset] = 0 end else stringInfo[:font_size] = (font_size_table[stringInfo[:length]-1] * scale).to_i stringInfo[:xoffset] = (font_size_table_xoffset[stringInfo[:length]-1] * scale).to_i end return stringInfo end # At@̗vf擾 def getAlpha(argb) return ((argb & 0xff000000) >> 24).to_f / 255.0 end # Ԃ̗vf擾 def getRed(argb) return ((argb & 0x00ff0000) >> 16).to_f / 255.0 end # ΂̗vf擾 def getGreen(argb) return ((argb & 0x0000ff00) >> 8).to_f / 255.0 end # ‚̗vf擾 def getBlue(argb) return (argb & 0x000000ff).to_f / 255.0 end def getPos(angle, radius) x = Math.cos(Math::PI*angle/180) * radius y = Math.sin(Math::PI*angle/180) * radius return x, y end def drawBackground(context, param) # wi context.set_source_rgba( param[:back_color_red], param[:back_color_green], param[:back_color_blue], param[:back_color_alpha] ) # ]lė]ɓhׂĂi[gQ(1.41...)ł͂j context.rectangle(0-param[:center_x], 0-param[:center_y], param[:width]+(param[:center_x]*2), param[:height]+(param[:center_y]*2)) context.fill end # qg` def drawCircle(context, param) # if( param[:circle_type] == 'double' ) then context.set_source_rgba(param[:font_color_red], param[:font_color_green], param[:font_color_blue], param[:font_color_alpha] ) context.move_to( param[:center_x] + param[:radius_big], param[:center_y]) # ~oʒuwiꂪȂƑÖʒu璼`悳 context.arc(param[:center_x], param[:center_y], param[:radius_big], 0, 2 * Math::PI) context.stroke # h end # context.set_source_rgba(param[:font_color_red], param[:font_color_green], param[:font_color_blue], param[:font_color_alpha]) context.move_to( param[:center_x] + param[:radius], param[:center_y]) # ~oʒuwiꂪȂƑÖʒu璼`悳 context.arc(param[:center_x], param[:center_y], param[:radius], 0, 2 * Math::PI) context.stroke # h end # `(m[}) def drawString(context, stringInfo, x, y, type='down') context.set_source_rgba(stringInfo[:font_color_red], stringInfo[:font_color_green], stringInfo[:font_color_blue], stringInfo[:font_color_alpha] ) layout = context.create_pango_layout layout.set_font_description(Pango::FontDescription.new("#{stringInfo[:font]} #{stringInfo[:font_size]}")) layout.text = stringInfo[:string].encode('utf-8') *psize = layout.pixel_size toX = 0 stringInfo[:string].gsub(/[]/){ toX += stringInfo[:xoffset] } # p̏ꍇ̓ʏ sx = x - (psize[0]/2) + ( ((stringInfo[:xoffset] * (stringInfo[:length]-1))) / 2 ) + toX sy = y if( type == 'up' ) then sy -= psize[1] elsif( type == 'center' ) then sy -= (psize[1]/2) end stringInfo[:string].each_char.with_index do |str,index| layout = context.create_pango_layout layout.set_font_description(Pango::FontDescription.new("#{stringInfo[:font]} #{stringInfo[:font_size]}")) layout.text = str.encode('utf-8') *psize = layout.pixel_size context.move_to(sx, sy) sx += psize[0] - stringInfo[:xoffset] str.sub(/[]/){ sx -= stringInfo[:xoffset] } # [] ͂Ɋ񂹂 next if( str =~ /\s/ ) context.show_pango_layout(layout) end end # `(t炵`悷) def drawStringForDate(context, stringInfo, x, y, type='down') context.set_source_rgba(stringInfo[:font_color_red], stringInfo[:font_color_green], stringInfo[:font_color_blue], stringInfo[:font_color_alpha] ) layout = context.create_pango_layout layout.set_font_description(Pango::FontDescription.new("#{stringInfo[:font]} #{stringInfo[:font_size]}")) layout.text = stringInfo[:string].tr("\s","0").encode('utf-8') # Xy[X͐l̔p[ƂĕvZĂ *psize = layout.pixel_size toX = 0 stringInfo[:string].gsub(/[]/){ toX += stringInfo[:xoffset] } # p̏ꍇ̓ʏ sx = x - (psize[0]/2) + ( ((stringInfo[:xoffset] * (stringInfo[:length]-1))) / 2 ) + toX sy = y if( type == 'up' ) then sy -= psize[1] elsif( type == 'center' ) then sy -= (psize[1]/2) end spaceOffset = 0 stringInfo[:string].each_char.with_index do |str,index| layout = context.create_pango_layout layout.set_font_description(Pango::FontDescription.new("#{stringInfo[:font]} #{stringInfo[:font_size]}")) layout.text = str.tr("\s","0").encode('utf-8') # Xy[X͐l̃[ƂĕvZĂ *psize = layout.pixel_size context.move_to(sx, sy + stringInfo[:string_yoffset][index]) nx = psize[0] if( str =~ /\s/ ) then nx = (psize[0]/2) # Xy[XȂړʂ𔼕ɂ spaceOffset += nx # ςݎcێ else sx += spaceOffset # Xy[XłȂȂςݎc𔽉f̈ʒu֖߂ spaceOffset = 0 end sx += nx - stringInfo[:xoffset] str.sub(/[]/){ sx -= stringInfo[:xoffset] } # [] ͂Ɋ񂹂 next if( str =~ /\s/ ) # Xy[X͕`悷KvȂ context.show_pango_layout(layout) end end # # t\ # def drawDate(context, param) # context.set_source_rgba(param[:font_color_red], param[:font_color_green], param[:font_color_blue], param[:font_color_alpha] ) # layout = context.create_pango_layout # layout.set_font_description(Pango::FontDescription.new("#{param[:mid_font]} #{param[:date_font_size]}")) # layout.text = param[:mid_string].encode('utf-8') # *psize = layout.pixel_size # Z^[ʒuop # sx = param[:center_x] - psize[0]/2 # sy = param[:center_y] - psize[1]/2 # # range = (4 * param[:scale]).to_i # param[:mid_string].each_char.with_index do |str,index| # layout = context.create_pango_layout # layout.set_font_description(Pango::FontDescription.new("#{param[:mid_font]} #{param[:date_font_size]}")) # layout.text = str.encode('utf-8') # *psize = layout.pixel_size # context.move_to(sx, sy+param[:random].rand(range)-(range/2)) # {randomĂ͂ȂBBBQxڂdrawDateňႤƂɕ`悵Ă܂BBB # sx += psize[0] # context.show_pango_layout(layout) # end # end # q`悷 def drawSignature( context, param) # ̑ݒ context.set_line_width (param[:line_size]); # q~` drawCircle(context, param) # top, bottom top_sx,top_sy = getPos( -param[:line_angle], param[:radius]) top_ex,top_ey = getPos( 180+param[:line_angle], param[:radius]) btm_sx,btm_sy = getPos( param[:line_angle], param[:radius]) btm_ex,btm_ey = getPos( 180-param[:line_angle], param[:radius]) context.set_source_rgba(param[:font_color_red], param[:font_color_green], param[:font_color_blue], param[:font_color_alpha] ) # top context.move_to(param[:center_x] + top_sx,param[:center_y] + top_sy) context.line_to(param[:center_x] + top_ex,param[:center_y] + top_ey) context.stroke # bottom context.move_to(param[:center_x] + btm_sx,param[:center_y] + btm_sy) context.line_to(param[:center_x] + btm_ex,param[:center_y] + btm_ey) context.stroke # top string drawString(context,param[:top_string_info], param[:center_x], param[:center_y] + top_sy, 'up') # btm string drawString(context,param[:btm_string_info], param[:center_x], param[:center_y] + btm_sy, 'down') # mid string drawStringForDate(context,param[:mid_string_info], param[:center_x], param[:center_y], 'center') #drawDate(context, param) end # ]}gNXݒ def setMatrix( context, param) context.translate( param[:center_x], param[:center_y] ) # ]S_ړ context.rotate( param[:rotate_degrees] * Math::PI / 180 ) # S_] context.translate( -param[:center_x]+param[:tx], -param[:center_y]+param[:ty] ) # ]S_ɖ߂ end # ʑŜH def drawEffect( context, param, random) if( (param[:seed] & 0x1) == 1 ) then #pat = Cairo::LinearPattern.new(0, 0, param[:width], param[:height]) # ォEփtB^H #pat = Cairo::LinearPattern.new(0-param[:center_x], 0-param[:center_y], param[:width]+(param[:center_x]*2), param[:height]+(param[:center_y]*2)) # t߂E܂łjAɓ߂ # #pat = Cairo::LinearPattern.new(param[:center_x]/3, param[:center_y]/3, param[:width], param[:height]) # ォEփtB^H pat = Cairo::LinearPattern.new( random.rand(param[:width]), param[:center_y]/3, random.rand(param[:width]), param[:height]) # ォ牺փtB^ pat.add_color_stop_rgba(0.0, param[:back_color_red], param[:back_color_green], param[:back_color_blue], 0.0) pat.add_color_stop_rgba(1.0, param[:back_color_red], param[:back_color_green], param[:back_color_blue], 0.75) # param[:back_color_alpha]) context.rectangle(0-param[:center_x], 0-param[:center_y], param[:width]+(param[:center_x]*2), param[:height]+(param[:center_y]*2)) context.set_source(pat) context.fill end # x1,y1 = getPos( random.rand(360), param[:center_x]+(param[:center_x]/4)+random.rand(param[:center_x]/3)) x1,y1 = getPos( random.rand(360), param[:radius] + random.rand(param[:radius]) - (param[:radius]/2)) # ǂ𒆐Sɉ~`ɓ߂ pat2 = Cairo::RadialPattern.new( param[:center_x]+x1, param[:center_y]+y1, param[:radius]/5, # ~ param[:center_x]+x1, param[:center_y]+y1, param[:radius]) # 傫~ pat2.add_color_stop_rgba( 0, param[:back_color_red], param[:back_color_green], param[:back_color_blue], 0.6+random.rand(0.4)) # ~ pat2.add_color_stop_rgba( 1, param[:back_color_red], param[:back_color_green], param[:back_color_blue], 0.0) # 傫~ # O[Of[Vŕ`emFꍇ͏LQR[hƉLQR[hւ #pat2.add_color_stop_rgba( 0, 0, 1, 0, 0.6+random.rand(0.4) ) #pat2.add_color_stop_rgba( 1, 0, 1, 0, 0.0) context.rectangle(0-param[:center_x], 0-param[:center_y], param[:width]+(param[:center_x]*2), param[:height]+(param[:center_y]*2)) context.set_source(pat2) context.fill end # qC[W𐶐 def createSignatureImage(param) # ImageSurface 쐬 surface = Cairo::ImageSurface.new(param[:format], param[:width], param[:height]) context = Cairo::Context.new(surface) setMatrix(context, param) drawBackground(context,param) # wi` drawSignature(context,param) # qC[W` # XyV[hȂ摜ɉHB߂ݒ肳Ăꍇ͐삵ȂII # ォ炷ׂĂĕ`悵ĂAt@l͐ZꂽԂŕ`悳ۂB㏑łȂ if( param[:special_mode] ) then random = param[:random] # clone Ƃ΂Ȃŕϐ param = param.clone # p[^Rs[ range = (6 * param[:scale]).to_i param[:center_x] += random.rand(range) - (range/2) param[:center_y] += random.rand(range) - (range/2) param[:font_color_alpha] *= 0.5 param[:top_string_info][:font_color_alpha] *= 0.5 param[:btm_string_info][:font_color_alpha] *= 0.5 param[:mid_string_info][:font_color_alpha] *= 0.5 drawCircle(context,param) drawSignature(context,param) drawEffect(context,param,random) end return surface end def createWindowsBitmap() =begin // 14 byte typedef struct tagBITMAPFILEHEADER { unsigned short bfType; # 'BM' unsigned long bfSize; # t@CTCY unsigned short bfReserved1; # 0 unsigned short bfReserved2; # 0 unsigned long bfOffBits; # t@C擪摜f[^܂ł̃ItZbg } BITMAPFILEHEADER // 40 byte typedef struct tagBITMAPINFOHEADER{ unsigned long biSize; # 40 long biWidth; # 200 long biHeight; # 200 unsigned short biPlanes; # 1 unsigned short biBitCount; # 24 or 32 unsigned long biCompression; # 0: k unsigned long biSizeImage; # 96dpi Ȃ3780, 0 ̏ꍇ long biXPixPerMeter; # 96dpi Ȃ3780, 0 ̏ꍇ long biYPixPerMeter; # 96dpi Ȃ3780, 0 ̏ꍇ unsigned long biClrUsed; # 0 unsigned long biClrImporant; # 0 } BITMAPINFOHEADER; =end data = @surface.data w = @surface.width h = @surface.height # QlTCgF http://www.kk.iij4u.or.jp/~kondo/bmp/#INFOHEADER depath = 4; # ARGB8888=32bit mBITMAPFILEHEADER = { :bfType => 'BM', :bfSize => ((w * h * depath) + 54), # 0x01d4f6, # 120054 # t@CTCY :bfReserved1 => 0, # 0 :bfReserved2 => 0, # 0 :bfOffBits => 0x36, # t@C擪摜f[^܂ł̃ItZbg } # 14 byte mBITMAPINFOHEADER = { :biSize => 0x28, # 40 :biWidth => w, # 200 :biHeight => -h, # 200 :biPlanes => 1, # 1 :biBitCount => 0x20, # 24 or 32 :biCompression => 0, # 0: k :biSizeImage => (w * h * depath), #0x0001d4c0, #120000, # 96dpi Ȃ3780, 0 ̏ꍇ :biXPixPerMeter => 0x00000ec4, #3780, # 96dpi Ȃ3780, 0 ̏ꍇ :biYPixPerMeter => 0x00000ec4, #3780, # 96dpi Ȃ3780, 0 ̏ꍇ :biClrUsed => 0,# 0 :biClrImporant => 0, # 0 } # 40 byte # s!: signed short # S!: unsigned short # i!: signed int # I!: unsigned int # l!: signed long # L!: unsigned long # q!: signed long long # Q!: unsigned long long membuffer = StringIO.new("", 'wb+') #// 14 byte #typedef struct tagBITMAPFILEHEADER { membuffer.write( [mBITMAPFILEHEADER[:bfType]].pack('a2') ) membuffer.write( [mBITMAPFILEHEADER[:bfSize]].pack('L!') ) membuffer.write( [mBITMAPFILEHEADER[:bfReserved1]].pack('S!') ) membuffer.write( [mBITMAPFILEHEADER[:bfReserved2]].pack('S!') ) membuffer.write( [mBITMAPFILEHEADER[:bfOffBits]].pack('L!') ) #// 40 byte #typedef struct tagBITMAPINFOHEADER{ membuffer.write( [mBITMAPINFOHEADER[:biSize]].pack('L!') ) membuffer.write( [mBITMAPINFOHEADER[:biWidth]].pack('l') ) membuffer.write( [mBITMAPINFOHEADER[:biHeight]].pack('l!') ) membuffer.write( [mBITMAPINFOHEADER[:biPlanes]].pack('S!') ) membuffer.write( [mBITMAPINFOHEADER[:biBitCount]].pack('S!') ) membuffer.write( [mBITMAPINFOHEADER[:biCompression]].pack('L!') ) membuffer.write( [mBITMAPINFOHEADER[:biSizeImage]].pack('L!') ) membuffer.write( [mBITMAPINFOHEADER[:biXPixPerMeter]].pack('l!') ) membuffer.write( [mBITMAPINFOHEADER[:biYPixPerMeter]].pack('l!') ) membuffer.write( [mBITMAPINFOHEADER[:biClrUsed]].pack('L!') ) membuffer.write( [mBITMAPINFOHEADER[:biClrImporant]].pack('L!') ) #// image membuffer.write( data ) membuffer.rewind buf = membuffer.read return buf end def export_to_png(fileName) # data = @surface.data # w = @surface.width # h = @surface.height #bitmapImageArray = data.unpack("h*") # ARGB8888 x width x height # data[0,4] = "\xff\x00\x00\x00" # binding.pry # for y in 0..(h-1) do # for x in 0..(w-1) do # buf = data[((y*w)+x)*4,4].unpack("C*") # end # end @surface.write_to_png(fileName) end def getBitmapImage return @surface.data, @surface.width, @surface.height end end
true
003577b63890a5b40e15ebed3e0f38b8a9c0659d
Ruby
kat-onyx/W2D3
/tdd/lib/tdd.rb
UTF-8
785
3.5625
4
[]
no_license
def remove_dups(array) array.uniq end def two_sum(array) result = [] (0..array.length - 1).each do |left| (left + 1..array.length - 1).each do |right| result << [left, right] if array[left] + array[right] == 0 end end result end def my_transpose(array) result = Array.new(3) { Array.new [] } (0..array.length - 1).each do |i| array.each do |arr| result[i] << arr[i] end end result end def stock_picker(prices) days = [] (0..prices.length - 1).each do |first| (first + 1..prices.length - 1).each do |second| greatest_return = 0 if (prices[first] - prices[second]).abs > greatest_return greatest_return = (prices[first] - prices[second]).abs days = [first, second] end end end days end
true
ee4ffed1524d2de97e93f671a9a888f4a2df70c0
Ruby
JeanJoeris/battleship
/lib/game_cell.rb
UTF-8
222
2.71875
3
[]
no_license
class GameCell attr_reader :content def initialize @content = nil @hit = false end def hit? @hit end def hit @hit = true end def add(data) @content = data unless @content end end
true
bb94a17ea7f38d3da318eb98bf6b7bcae60f7d1e
Ruby
cmeiklejohn/wine_dot_com_api_request
/lib/wine_dot_com_api_request.rb
UTF-8
4,189
2.953125
3
[ "MIT" ]
permissive
#!/usr/bin/ruby # WineDotComApiRequest class. # # Provides an interface to access the Wine.com API. # # Author:: Christopher Meiklejohn (cmeik@me.com) # Copyright:: Copyright (c) 2010 Christopher Meiklejohn # License:: Distributes under the terms specified in the MIT-LICENSE file. # # Usage example: #w = WineDotComApiRequest.new(:search => 'mondavi cabernet', # :format => :xml, # :resource => :catalog, # :size => 1, # :offset => 0) # # w.query # # To-do: # * Build a better interface for filters # * Build a better interface for sortBy # * Implement affiliateId # * Implement version, beta currently only supported # * Extract out api key and base url into configuration parameters # # See: http://api.wine.com/wiki/2-catalog-queries require "wine_dot_com_api_request/configuration" require 'net/http' require 'uri' class WineDotComApiRequest public # API key from Wine.com. attr_accessor :api_key # API version number. Available API versions: v1.0, v2.3. attr_accessor :version # API result format. Available API formats: xml, json. attr_accessor :format # API requested resource. Available API resources: catalog, reference, categorymap. attr_accessor :resource # API parameters. attr_accessor :parameters # Base URL of API. attr_accessor :base_url # Affiliate ID for revenue sharing. attr_accessor :affiliate_id # Search offset to start at. attr_accessor :offset # Number of records to return. attr_accessor :size # Search terms. attr_accessor :search # Search filter. Ex. filter=categories(7155+124)+rating(85|100). attr_accessor :filter # Ship to state. Two letter abbrev. Ex. MA. attr_accessor :state # Sort key. Ex. sort=rating|ascending. attr_accessor :sort # In stock. Boolean search value. attr_accessor :instock # Inialize the required parameters, and setup the request defaults. def initialize(options = {}) options.each_pair do |key, value| self.send("#{key}=", value) end end # Return URL that request will be made to. Mainly for debugging purposes. def url api_url end # Execute a search. Returns either raw json or xml. def query(options = {}) options.each_pair do |key, value| self.send("#{key}=", value) end raise 'No API base URL provided.' unless @@base_url raise 'No API key provided.' unless @@api_key raise 'No resource specified.' unless @resource raise 'No format specified.' unless @format return do_get end private # Perform GET request and return results. def do_get Net::HTTP.get(URI.parse(api_url)) end # Generate the url to make the API call to. def api_url "#{@@base_url}/#{format}/#{resource}?apikey=#{@@api_key}#{parameters}" end # parameters overrides attribute reader and returns custom results based on resource type. def parameters url_params = "" if @resource == :catalog url_params += "&" + "offset=#{URI.escape(@offset.to_s)}" if @offset url_params += "&" + "size=#{URI.escape(@size.to_s)}" if @size url_params += "&" + "search=#{URI.escape(@search)}" if @search url_params += "&" + "filter=#{URI.escape(@filter)}" if @filter url_params += "&" + "state=#{URI.escape(@state)}" if @state url_params += "&" + "sort=#{URI.escape(@sort)}" if @sort url_params += "&" + "instock=#{@instock}" if @instock elsif @resource == :categorymap url_params += "&" + "filter=#{URI.escape(@filter)}" if @filter url_params += "&" + "search=#{URI.escape(@search)}" if @search elsif @resource == :reference url_params += "&" + "filter=#{URI.escape(@filter)}" if @filter end return url_params end end
true
293534637e5cc297de27b3513156980209d66332
Ruby
michaelciletti/refactored_projects
/code.rb
UTF-8
345
3.78125
4
[]
no_license
def fizzkata(my_array) my_array.count end def minedminds(my_array) array = [] my_array.each do |num| if num % 15 == 0 array.push("minedminds") elsif num % 3 == 0 array.push("mined") elsif num % 5 == 0 array.push("minds") else array.push(num) end end array.inspect end my_array = [*1..100] puts minedminds(my_array)
true
3be8836987dfa6dad0b14a178e66c1c2f327fd04
Ruby
timsully/learn_ruby_the_hard_way
/ex40.rb
UTF-8
1,726
4.96875
5
[]
no_license
# Creating the class Song class Song # When we call a function down below the initialize # function grabs the values being passed in and # assigns it equal to the variable lyrics def initialize(lyrics) @lyrics = lyrics end # sing_me_a_song then gets the lyrics variable # and iterates through each element in the array # of what was passing in and uses the |line| argument # to pass it into and assign to as it displays the output # with puts line def sing_me_a_song() @lyrics.each { |line| puts line } end # Calling a variable and assigning it a string SWEG = "Super Doper Docher, brah." end # Creating an instance(object) of the Song class # which has an array with 3 elements in the index # which are strings of lyrics I created happy_bday = Song.new(["Happy birthday to you", "I don't want to get sued", "So I'll stop right there"]) bulls_on_parade = Song.new(["They rally around tha family", "With pockets full of shells"]) anotha_one = Song.new(["We are the champions, my friendddddd.", "And we'll keep on fighting til the end. DUN DUN DUN DUNNNNN"]) i_wanna_rock = Song.new(["I WANNA ROCK!","SWEG"]) # Calling the happy_bday variable with the function # we created called sing_me_a_song using the . (dot) # operator which grabs the array and assigns them # equal to the lyrics variable in the initialize function # which has a parameter of lyrics where we pass in our array # so it can be assigned to the lyrics variable happy_bday.sing_me_a_song() bulls_on_parade.sing_me_a_song() anotha_one.sing_me_a_song() i_wanna_rock.sing_me_a_song() # Displaying the output of the varibale SWEG # that is in the class Song, we access it with # the double colons :: puts Song::SWEG
true
dc9fc7a4073562eb2a66b876f65fb633a2e13a78
Ruby
guineveresaenger/Word-Guess
/flower.rb
UTF-8
941
3.875
4
[]
no_license
require 'colorize' class Flower def initialize(buds) @buds = buds end def flower puts case @buds when 7 puts " (@) (@)".colorize(:red) puts "(@)(@)(@)(@)(@)".colorize(:red) when 6 puts " (@)".colorize(:red) puts "(@)(@)(@)(@)(@)".colorize(:red) when 5 puts " (@)".colorize(:red) puts "(@)(@)(@)(@)".colorize(:red) when 4 puts "(@)(@)(@)(@)".colorize(:red) when 3 puts " (@)(@)(@)".colorize(:red) when 2 puts " (@) (@)".colorize(:red) when 1 puts " (@)".colorize(:red) when 0 puts else puts "How did this get messed up!?" end puts ' ,\,\,|,/,/,'.colorize(:green) puts ' _'.colorize(:magenta) + '\|/'.colorize(:green) + '_'.colorize(:magenta) puts ' |_____|'.colorize(:magenta) puts ' | |'.colorize(:magenta) puts " |___|".colorize(:magenta) end end
true
38ba99533cdc2b7c8a855a873aabbdabf4e4f631
Ruby
NativeScript/webkit
/Tools/iExploder/iexploder-1.7.2/tools/lasthit.rb
UTF-8
2,238
2.625
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby # Copyright 2010 Thomas Stromberg - All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # # # lasthit, part of iExploder # # Shows statistics about recent agents that have tested with iExploder. # It takes all or part of an apache logfile via stdin, and outputs a list # of all the agents who tested within that section, what their last test # was, and how many tests they have done. # The usefulness is finding out where a browser crashed. require 'cgi' hostHash = Hash.new if (ARGV[0]) file = File.open(ARGV[0]) else puts "No filename specified, waiting for data via stdin..." file = $stdin end last_index = nil file.readlines.each_with_index { |line, index| # filter out mime hits as they produce a lot of odd user agents next if line =~ /&m=/ if (line =~ /([\w\.]+) - - .*iexploder.cgi\?(.*?)&b=([\w\%-\.+]+)/) host = $1 test_url = $2 agent = $3 if (! hostHash[host]) hostHash[host] = Hash.new end if (! hostHash[host][agent]) hostHash[host][agent] = Hash.new hostHash[host][agent]['total'] = 0 end hostHash[host][agent]['last'] = test_url hostHash[host][agent]['total'] = hostHash[host][agent]['total'] + 1 hostHash[host][agent]['last_line'] = index end last_index = index } printf("%-14.14s | %-25.25s | %6.6s | %7.7s | %s\n", "Host", "Test URL", "Total", "LineAgo", "Agent") puts "-" * 78 hostHash.each_key { |host| hostHash[host].each_key { |agent| next if agent.length < 8 display_agent = CGI::unescape(agent).sub('U; ', '') printf("%-14.14s | %-25.25s | %6.6s | %7.7s | %s\n", host, hostHash[host][agent]['last'], hostHash[host][agent]['total'], hostHash[host][agent]['last_line'] - last_index, display_agent); } }
true
f5a68496c2bb3da77a5c99c1f825040ea9c7c51a
Ruby
Kishanpa3/OakCreekDB
/app/datatables/animal_datatable.rb
UTF-8
885
2.703125
3
[ "MIT" ]
permissive
class AnimalDatatable < ApplicationDatatable private def data animals.map do |animal| [].tap do |column| column << animal.id column << animal.tag column << animal.name column << animal.common_name column << animal.habitat_num end end end def count Animal.count end def total_entries animals.total_entries end def animals @animals ||= fetch_animals end def fetch_animals search_string = [] columns.each do |term| search_string << "lower(CAST(#{term} AS TEXT)) like lower(:search)" end animals = Animal.order("#{sort_column} #{sort_direction}") animals = animals.page(page).per_page(per_page) animals = animals.where(search_string.join(' or '), search: "%#{params[:search][:value]}%") end def columns %w(id tag name common_name habitat_num) end end
true
1f048cf10d4c6721fbe60869051e1da23bd47032
Ruby
albertbahia/wdi_june_2014
/w03/d03/gadi_gottlieb/classwork/fibonacci/lib/fibonacci.rb
UTF-8
399
3.453125
3
[]
no_license
require 'pry' def sum_of_even_fibonaccis(limit) holder = [1, 2] while (holder[-1] + holder[-2]) < limit holder << holder[-1] + holder[-2] # only concerned with the last one, and the second to last one. end # we then add those two numbers together in order to get our Fibonacci numbers return holder.select { |num| num.even?}.reduce(:+) end binding.pry
true
306997de6060081ad88f1d69998e0737c693ac0f
Ruby
ntmbayfield/DevBootcamp-1
/week1/sudoku.rb
UTF-8
4,525
3.875
4
[]
no_license
class Sudoku def initialize(board_string) board_string = board_string.split("") @board = [] 9.times do |row| @board << board_string.shift(9) @board[row].map! do |item| item.to_i end end end def return_row(row) row_arr = [] board[row].each do |item| if item.is_a?(Integer) row_arr << item end end row_arr end def return_column(col) col_arr = [] board.transpose[col].each do |item| if item.is_a?(Integer) col_arr << item end end col_arr end def return_box(starting_x, starting_y) starting_x = (starting_x - (starting_x % 3)) starting_y = (starting_y - (starting_y % 3)) box = [] starting_x.upto(starting_x + 2) do |x| starting_y.upto(starting_y + 2) do |y| box << board[x][y] end end box_arr = [] box.each do |item| if item.is_a?(Integer) box_arr << item end end box_arr end def filled?(row, col) if board[row][col] == 0 board[row][col] = (1..9).to_a false elsif board[row][col].class == Integer true elsif board[row][col].class == Array false end end def solve_cell!(row, col) if filled?(row, col) == false @board[row][col] = @board[row][col] - return_row(row) - return_column(col) - return_box(row, col) end if @board[row][col].class == Array && @board[row][col].length == 1 @board[row][col] = @board[row][col].pop end end def solve! while sudoku_solved? == false 9.times do |row| 9.times do |col| solve_cell!(row, col) end end end end # Returns a string representing the current state of the board # Don't spend too much time on this method; flag someone from staff # if you are. def board @board.each do |row| print row puts "" end end def sudoku_solved?(board) board.flatten(1).each do |cell| return false if cell.class == Array || cell == 0 end true end end ####### NOTES Replace all 0 in the board with an array from (1..9) Then do every permutation of the remaining numbers. First put in the index[0] of every array. if the board is correct then return the board if not then put in add to the next array and test_board 1, 1, 1 1, 2, 2 1, 2, 3 1, 3, 3 2, 1, 1 2, 2, 2 2, 2, 3 2, 3, 3 3, 1, 1 3, 2, 2 3, 2, 3 3, 3, 3 then it has to come back down? [ ] build test_board method This method will add all the numbers in the row, column, and box and make sure it equals 45. def board_correct? # Test row @board.each do |row| row.inject(:+) == 45 end # Test column @board.transpose[col].each do |item| item.inject(:+) == 45 end # Test box end # The file has newlines at the end of each line, so we call # String#chomp to remove them. # board_string = File.readlines('sample.unsolved.txt').first.chomp board_strings = ["105802000090076405200400819019007306762083090000061050007600030430020501600308900", "005030081902850060600004050007402830349760005008300490150087002090000600026049503", "105802000090076405200400819019007306762083090000061050007600030430020501600308900", "005030081902850060600004050007402830349760005008300490150087002090000600026049503", "290500007700000400004738012902003064800050070500067200309004005000080700087005109", "080020000040500320020309046600090004000640501134050700360004002407230600000700450", "608730000200000460000064820080005701900618004031000080860200039050000100100456200", "370000001000700005408061090000010000050090460086002030000000000694005203800149500", ] board_strings2 = ["000689100800000029150000008403000050200005000090240801084700910500000060060410000"] # "030500804504200010008009000790806103000005400050000007800000702000704600610300500", # "096040001100060004504810390007950043030080000405023018010630059059070830003590007", # "000075400000000008080190000300001060000000034000068170204000603900000020530200000", # "300000000050703008000028070700000043000000000003904105400300800100040000968000200", # "302609005500730000000000900000940000000000109000057060008500006000000003019082040"] index = 1 board_strings2.each do |board_string| game = Sudoku.new(board_string) game.solve! puts "Here is solved board number #{index}:" game.board index += 1 end # Remember: this will just fill out what it can and not "guess" # game.solve! # puts "Here is the solved board:" # game.board
true
d2898ae5b5e6e5e419d6a6e6bbe445d086adf81f
Ruby
fameoflight/hirehub
/lib/compile_job.rb
UTF-8
2,811
2.5625
3
[]
no_license
class CompileJob attr_accessor :submission, :solution_dir, :code_path, :exe_path, :compiler_output, :success, :lang def self.perform( submission_id ) job = new submission_id job.prepare_dir submission_id job.compile return job end def initialize( submission_id ) @submission = Submission.find( submission_id ) if @submission.nil? raise 'No such submission' end if @submission.lang == "text" raise 'Not a code submission' end @lang = @submission.lang @submission.update_attributes(:status => ( t 'submission.status.compiling' ) ) end def prepare_dir ( submission_id ) run_dir = Settings['run_dir'] @solution_dir = File.join( run_dir, submission_id.to_s ) if File.exists?(@solution_dir) puts "#{@solution_dir} already exists, deleting ..." FileUtils.rm_rf(@solution_dir) end FileUtils.mkdir_p @solution_dir puts "#{@solution_dir} created" file_ext = Settings[ @lang]['ext'] if file_ext.to_s.length == 0 puts "CompileJob : No Language Extension Found for #{@lang}" @submission.update_attributes(:status => ( t 'submission.status.system_error' ), :judged => true ) return true end @code_path = File.join( @solution_dir, "Solution.#{file_ext}" ) File.open( @code_path , 'w') { |f| f.write(@submission.submission_text) } end def compile self.success = true if Settings[ @lang]['type'] == 'compiled' puts "compiled language" file_ext2 = Settings[ @lang]['binary_ext'] @exe_path = File.join( @solution_dir, "Solution.#{file_ext2}" ) puts "using #{@exe_path} as exe path" cmd_line = Settings[ @lang ]['compile_cmd'] cmd_line = cmd_line % [ @code_path , @exe_path, @solution_dir ] puts "#{cmd_line}" @compiler_output = %x[#{cmd_line}] @compiler_output = @compiler_output.to_s.strip if @compiler_output.length == 0 @compiler_output = ( t 'submission.compiled_success' ) end @submission.update_attributes(:compiler_output => @compiler_output ) unless FileTest.exist?( exe_path ) # Compiler error @submission.update_attributes(:status => ( t 'submission.status.compilation_error' ) , :judged => true ) self.success = false end else cmd_line = Settings[ @lang ]['syntax_cmd'] cmd_line = cmd_line % [ @code_path ] puts "Syntax Check #{cmd_line}" @compiler_output = %x[#{cmd_line}] @compiler_output = @compiler_output.to_s.strip if @compiler_output.length == 0 @compiler_output = ( t 'submission.syntax_check' ) end @submission.update_attributes(:compiler_output => @compiler_output ) end end def link_or_copy(src, des) begin FileUtils.ln_s(src, des) rescue NotImplementedError FileUtils.cp(src,des) end end def t( str ) I18n.t str end end
true
d9e60b0e59b6b32059da2e4d369207c4bc331db0
Ruby
Dale-R-Harrison/RB101
/small_problems/easy4/leap_years.rb
UTF-8
498
4
4
[]
no_license
# orgiginal solution def leap_year?(year) leap_year = false if year % 100 == 0 if year % 400 == 0 leap_year = true end else leap_year = true end end leap_year end puts leap_year?(2016) puts leap_year?(2015) puts leap_year?(2100) puts leap_year?(2400) puts leap_year?(240000) puts leap_year?(240001) puts leap_year?(2000) puts leap_year?(1900) puts leap_year?(1752) puts leap_year?(1700) puts leap_year?(1) puts leap_year?(100) puts leap_year?(400)
true
762f29a574d685f425c6ff9ca9707dac016be7d4
Ruby
acanshul/racing_on_rails
/test/models/events/competitions/dirty_circles_overall_test.rb
UTF-8
1,859
2.53125
3
[ "Ruby", "MIT" ]
permissive
# frozen_string_literal: true require "test_helper" module Competitions # :stopdoc: class DirtyCirclesOverallTest < ActiveSupport::TestCase test "calculate" do series = Series.create!(name: "Dirty Circles") series.children.create!(date: Date.new(2016, 3, 8), name: "Dirty Circles 1") series.children.create!(date: Date.new(2016, 3, 15), name: "Dirty Circles 2") series.children.create!(date: Date.new(2016, 3, 22), name: "Dirty Circles 3") category = Category.create!(name: "Men 1/2/3") series.children.each do |event| event.races.create!(category: category) end winner = FactoryGirl.create(:person, name: "winner") event = series.children.first event.races.first.results.create!(place: "1", person: winner) hot_spot_winner = FactoryGirl.create(:person, name: "hot_spot_winner") event.races.first.results.create!(place: "2", person: hot_spot_winner) hot_spots = event.children.create!(name: "Hot Spots").races.create!(category: category) hot_spot_only = FactoryGirl.create(:person, name: "hot_spot_only") hot_spots.results.create!(place: "1", person: hot_spot_winner) hot_spots.results.create!(place: "2", person: hot_spot_only) DirtyCirclesOverall.calculate! 2016 overall = DirtyCirclesOverall.first results = overall.races.where(category: category).first.results assert_equal 3, results.count assert_equal winner, results[0].person assert_equal "1", results[0].place assert_equal 100, results[0].points assert_equal hot_spot_winner, results[1].person assert_equal "2", results[1].place assert_equal 98, results[1].points assert_equal hot_spot_only, results[2].person assert_equal "3", results[2].place assert_equal 16, results[2].points end end end
true
ca0a9172e3f442b96f3773a12d812fcf6de8063b
Ruby
LauraNgy/Day_2_Lab
/lab_testing_functions_start/ruby_functions_practice.rb
UTF-8
1,286
3.984375
4
[]
no_license
def return_10() return 10 end def add(num1, num2) return num1 + num2 end def subtract(num1, num2) return num1 - num2 end def multiply(num1, num2) return num1 * num2 end def divide(num1, num2) return num1 / num2 end def length_of_string(string) return string.length() end def join_string( string_1, string_2 ) return string_1 + string_2 end def add_string_as_number( string_1, string_2 ) return string_1.to_i() + string_2.to_i() end def number_to_full_month_name(month_number) case month_number when 1 return "January" when 2 return "February" when 3 return "March" when 4 return "April" when 5 return "May" when 6 return "June" when 7 return "July" when 8 return "August" when 9 return "September" when 10 return "October" when 11 return "November" when 12 return "December" else return "Invalid number." end end def number_to_short_month_name(month_number) return number_to_full_month_name(month_number).slice(0,3) end def volume_of_a_cube(side_length) return side_length ** 3 end def volume_of_a_sphere(radius) return ((4*(Math::PI)*(radius**3))/3).round(2) end def convert_fahrenheit_to_celsius(temp_farenheit) return (5*(temp_farenheit.to_f() - 32)/9).round(1) end
true
abfc70bd055722cefca1dec148dd71453347f010
Ruby
SteveVallay/ruby-practice
/chapter3/var1.rb
UTF-8
136
2.9375
3
[]
no_license
person = "Good luck" puts "person's classname is #{person.class}" puts "person 's id is #{person.object_id}" puts "person is : #{person}"
true
4794b559ed7dc7ee178f2e4502bbf4e53250fb0a
Ruby
rheimbuch/rtunesu
/lib/rtunesu/entities/track.rb
UTF-8
1,008
2.578125
3
[ "MIT" ]
permissive
module RTunesU # A Track in iTunes U. # == Attributes # Name # Handle # Kind # TrackNumber # DiscNumber # DurationMilliseconds # AlbumName # ArtistName # GenreName # DownloadURL # Comment class Track < Entity # Tracks can only be found from within their Course. There is currently no way to find a Track separete from its Course in iTunes U. def self.find(handle, course_handle, connection) entity = self.new(:handle => handle) entity.source_xml = Course.find(course_handle, connection).source_xml.at("Handle[text()=#{entity.handle}]..") entity end # Duration in millseconds is the one attribute in plural form that is not a collection def DurationMilliseconds self.value_from_edits_or_store('DurationMilliseconds') end # Duration in millseconds is the one attribute in plural form that is not a collection def DurationMilliseconds=(duration) self.edits['DurationMilliseconds'] = duration end end end
true
e646c6f364082170de67cc9e6356dc08b6a49143
Ruby
profmaad/catmother
/lib/catmother/bytecode_parser.rb
UTF-8
875
2.84375
3
[ "BSD-3-Clause" ]
permissive
module CatMother class BytecodeParser def initialize @opcodes = [] CatMother::Opcode::constants.reject { |c| !(CatMother::Opcode.const_get(c).class == Class) }.map { |c| CatMother::Opcode.const_get(c) }.each do |c| @opcodes[c::OPCODE] = c end end def parse(io, length) disassembly = {} pc = 0 while pc < length opcode = io.readbyte opcode_parser = @opcodes[opcode] unless opcode_parser.nil? result = opcode_parser.new(io, pc) disassembly[pc] = result if result.respond_to? :operands_length pc += (1+result.operands_length) else pc += (1+result.length) end else puts "unknown opcode: #{opcode}" return nil end end return disassembly end end end
true
f98578ad38f87a341065d89a452b750ff035acfb
Ruby
MAshrafM/The_Odin_Project
/11_Data_Structure/KnightMoves/lib/bfs.rb
UTF-8
436
3.109375
3
[]
no_license
# lib/bfs class BFS attr_accessor :way def initialize(source, target) @b = Board.new @way = {} solve(source, target) end def solve(source, target) q = [source] visited = [] until q.empty? pos = q.shift visited << pos jump = @b.cells[pos[0]][pos[1]].link jump.each do |j| q.unshift(j) if j && !visited.include?(j) way[j] = pos unless way.has_key?(j) return if j == target end end end end
true
cae3f2f6d66823b0d68278d5139644d372924c1d
Ruby
lebaongoc/Solar-System
/lib/solar_system.rb
UTF-8
1,180
3.71875
4
[]
no_license
class SolarSystem attr_reader :star_name, :planet def initialize(star_name) @star_name = star_name @planets = [] end def add_planet(planet_instance) @planets << planet_instance end def list_planets conclusion_statement = "Planets orbiting #{star_name}:\n" i = 1 planet_list = "" @planets.each do |planet| planet_list += "#{i}.#{planet.name} \n" i += 1 end return conclusion_statement + planet_list end def find_planet_by_name(planet_name) @planets.find { |planet| planet.name.downcase == planet_name.downcase } end def user_added_planet puts "Please enter new planet's name" planet_name = gets.chomp puts "Please enter new planet's color" planet_color = gets.chomp puts "Please enter new planet's mass in kilograms" planet_mass = gets.chomp.to_i puts "Please enter the distance between this new planet and the sun" planet_distance = gets.chomp.to_i puts "Please enter new planet's fun_fact" fun_fact = gets.chomp user_planet = Planet.new(planet_name.capitalize, planet_color, planet_mass, planet_distance, fun_fact) add_planet(user_planet) end end
true
78630b476e2a6affecc850fb238e2fcdbecbe3fd
Ruby
MalconMouraLima/RubyGame
/nomes.rb
UTF-8
297
3.78125
4
[]
no_license
def le_nome nome = gets.strip puts "Lido #{nome}" nome end def pede_nome puts "Digite seu nome" nome_lido = le_nome puts "Pedido!" nome_lido end def inicio nome = pede_nome puts "Bem vindo #{nome}" puts "Quero conhecer mais alguém" nome2 = pede_nome puts "Olá #{nome2}" end inicio
true
5890342e226bc439e5bf2177b9e61416903925f8
Ruby
malev/efemerides-culturales
/event.rb
UTF-8
825
2.734375
3
[]
no_license
class Event include Mongoid::Document field :month, :type => Integer field :day, :type => Integer field :year, :type => Integer field :content, :type => String def self.search(month, day) if where(:month => month, :day => day).count == 0 parse_and_store(month, day) else generate_hash(month, day) end end def self.parse_and_store(month, day) parser = Parser.new(month, day) output = parser.events_hash output.each do |event| self.create event end output end def self.generate_hash(month, day) output = [] where(:month => month, :day => day).each do |event| output << { :year => event.year, :day => event.day, :month => event.month, :content => event.content } end output end end
true
59468ff55684c2d7b11d898bebe6c94e7397df16
Ruby
thib123/TPJ
/Notes/Ruby/sample_code/ex1021.rb
UTF-8
132
2.84375
3
[ "MIT" ]
permissive
# Sample code from Programing Ruby, page 494 f = File.new("testfile") c = f.getc f.ungetc(c) f.getc
true
a13ca6e1c446a5f586174de4ebb719993d468697
Ruby
exctzo/socks
/create_droplet.rb
UTF-8
2,227
2.90625
3
[]
no_license
#!/usr/bin/env ruby require 'droplet_kit' require 'timeout' puts "" puts "-----------------------------------Server creation-----------------------------------" puts "" puts "Enter the Personal access tokens: " token = gets puts "" puts "--------------------------------------------------------------------------------------" puts "" puts "What region should the server be located in? 1. Amsterdam (Datacenter 2 - Curently not available) 2. Amsterdam (Datacenter 3) 3. Bangalore 4. Frankfurt 5. London 6. New York (Datacenter 1) 7. New York (Datacenter 2 - Curently not available) 8. New York (Datacenter 3) 9. San Francisco (Datacenter 1 - Curently not available) 10. San Francisco (Datacenter 2) 11. Singapore 12. Toronto Please choose the number of your region: " region = gets.chomp case region when "1" region = "ams2" when "2" region = 'ams3' when "3" region = 'blr1' when "4" region = 'fra1' when "5" region = 'lon1' when "6" region = 'nyc1' when "7" region = 'nyc2' when "8" region = 'nyc3' when "9" region = 'sfo1' when "10" region = 'sfo2' when "11" region = 'sgp1' when "12" region = 'tor1' else puts "Input was wrong" end puts "" puts "--------------------------------------------------------------------------------------" puts "" client = DropletKit::Client.new(access_token: token) pub_key = File.read(File.expand_path("~/.ssh/id_rsa.pub")) ssh_key = DropletKit::SSHKey.new( name: 'My SSH Public Key', public_key: pub_key ) client.ssh_keys.create(ssh_key) my_ssh_keys = client.ssh_keys.all.collect {|key| key.fingerprint} droplet = DropletKit::Droplet.new( name: 'shsyea', region: region, size: '512mb', image: 'ubuntu-16-04-x64', ssh_keys: my_ssh_keys ) puts "Exchanging ssh keys." puts "" puts "--------------------------------------------------------------------------------------" client.droplets.create(droplet) puts "" puts "Server has been created!" puts "" puts "--------------------------------------------------------------------------------------" puts ""
true
2f3d84c5ab4cb8fab50eade6d379b1939dcbb966
Ruby
s-steel/monster_shop_2005
/app/models/order.rb
UTF-8
1,416
2.625
3
[]
no_license
class Order < ApplicationRecord validates_presence_of :name, :address, :city, :state, :zip has_many :item_orders has_many :items, through: :item_orders belongs_to :user enum status: %w[pending packaged shipped cancelled] def status_update if (status == 'pending') && item_orders.where('status = 0 OR status = 1').length.zero? update(status: 1) elsif (status == 'packaged') && !item_orders.where('status = 0 OR status = 1').length.zero? update(status: 0) end end def add_item(item, amount = 1) item_orders.create(item: item, price: item.price, quantity: amount) end def grandtotal item_orders.sum('price * quantity') end def item_count item_orders.sum(:quantity) end def date_created created_at.strftime('%m/%d/%Y') end def date_updated updated_at.strftime('%m/%d/%Y') end def cancel_order self.status = 3 end def unfulfill_items item_orders.update_all(status: 'unfulfilled') end def merchant_items(merch_id) items.where(merchant_id: merch_id) end def merchant_item_orders(merch_id) item_orders.joins(:item).where(items: { merchant_id: merch_id }) end def total_sales(merch_id) merchant_items(merch_id).sum('item_orders.quantity * item_orders.price') end def merchant_item_count(merch_id) item_orders.joins(:item).where(items: { merchant_id: merch_id }).sum(:quantity) end end
true
16d89933bbc0ba872b9e2bf4e677741c85588138
Ruby
RumikoAcopa/activerecord-tvshow-onl01-seng-pt-052620
/app/models/show.rb
UTF-8
1,175
2.9375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Show < ActiveRecord::Base def Show::highest_rating Show.maximum(:rating) end def Show::most_popular_show Show.find_by rating: Show.highest_rating #highest_rating: SELECT "shows".* FROM "shows" WHERE (highest_rating = 1) LIMIT ? #highest_rating method as a helper method. end def Show::lowest_rating Show.minimum(:rating) end def Show::least_popular_show Show.find_by rating: Show.lowest_rating #returns the show with the #lowest rating. end def Show::ratings_sum Show.sum(:rating) #returns the sum of all of the ratings. end def Show::popular_shows Show.where("rating > 5") #returns an array of all of the shows #that have a rating greater than 5.#hint: use the where Active Record method. end def Show::shows_by_alphabetical_order Show.order(:name, :asc) #returns an array #of all of the shows sorted by alphabetical order #according to their names. hint: use the order #Active Record method.Client.order(created_at: :asc) end end
true
7d9ed7f0799fd2510ef5b495f4b1e2ddcf3c1cc8
Ruby
smkopp92/UtiliTrak
/spec/features/07user_edits_deletes_bills_spec.rb
UTF-8
1,564
2.53125
3
[]
no_license
# As an authenticated user # I want to edit my utility bills # So that I can update any incorrect information # Acceptance Criteria # [x]I must fill out all the information correctly # [x]I should be redirected to show page after submitting form # [x]Incorrect information should raise an error and refresh page # # As an authenticated user # I want to delete my utility bills # So that my information cannot be accessed # Acceptance Criteria # [x]Each show page should have a delete button # [x]Deleting should prompt the user to confirm deletion # [x]Deleting should return the user to the index page require 'rails_helper' feature 'user may edit and delete their own bills' do before(:each) do @user = FactoryGirl.create(:user) @household = FactoryGirl.create(:household, user_id: @user.id) @bill = FactoryGirl.create(:bill, household_id: @household.id) visit new_user_session_path fill_in 'Email', with: @user.email fill_in 'Password', with: @user.password, match: :prefer_exact click_on 'Log in' end scenario 'user is able to delete bills' do visit households_path find_by_id("house#{@household.id}").click click_on "Delete Bill" expect(page).to_not have_content(@bill.amount) end scenario 'user is able to edit bills they created' do visit households_path find_by_id("house#{@household.id}").click click_on "Edit Bill" fill_in 'Amount', with: "10000000" click_button "Generate Bill" find_by_id("bill#{@bill.id}").click expect(page).to have_content("10000000") end end
true
358a3d3bed176e45b22e8dea28a67dfc75d953f7
Ruby
neurodynamic/p1_rspec_and_regex_breakout
/spec/phone_numbers_spec.rb
UTF-8
849
2.875
3
[]
no_license
require 'rspec' require_relative '../phone_numbers' describe '#standardize_phone_number' do let(:basic_phone_number) { "(555) 555-5555" } let(:invalid_number) { "fjhdskhfdjkshjkdsf" } let(:dash_separated_number) { "555-555-5555" } it "doesn't change an already standardized phone number" do output = standardize_phone_number(basic_phone_number) expect(output).to eq(basic_phone_number) end it "throws an error if there is no valid phone number" do expect { standardize_phone_number(invalid_number) }.to raise_error(InvalidPhoneNumberError) end it "changes XXX-XXX-XXXX numbers to (XXX) XXX-XXXX format" do output = standardize_phone_number(dash_separated_number) expect(output).to eq(basic_phone_number) end it "changes XXX.XXX.XXXX numbers to (XXX) XXX-XXXX format" it "ignores extra numbers" end
true
6bc38654bf1ceae379290d696131bfbf2fa1e0f7
Ruby
jvidalba1/jvidalba_site
/app/models/user.rb
UTF-8
962
2.671875
3
[]
no_license
# == Schema Information # # Table name: users # # id :integer not null, primary key # name :string(255) # email :string(255) # content :string(255) # created_at :datetime not null # updated_at :datetime not null # class User < ActiveRecord::Base attr_accessible :content, :email, :name EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :name, :presence => { :message => " -Debes ingresar un nombre"}, :length => {:maximum => 30, :message => " -Nombre muy largo" } validates :email, :presence => { :message => " -Debes ingresar un email"}, :format => {:with => EMAIL_REGEX, :message => " -Formato de email invalido"} validates :content, :presence => { :message => " -Debes ingresar el mensaje"}, :length => {:within => 10..180, :message => " -El mensaje debe tener de 10 a 180 caracteres"} end
true
6a17ffce190d266503b0dbb708d9abc5fa5b054d
Ruby
ALucking1/recipe_app
/models/recipes.rb
UTF-8
1,670
2.609375
3
[]
no_license
class Recipes attr_reader :rand_rec def brrr_days @rand_rec = [["http://www.bbcgoodfood.com/recipes/3444/saras-chilli-con-carne", "Chilli Con Carne"], ["https://deliciouslyella.com/potato-peanut-curry/", "Potato Peanut Curry"], ["http://www.bbcgoodfood.com/recipes/4807/chunky-minestrone-soup", "Minestrone Soup"]].sample end def not_too_cold_days @rand_rec = [["http://www.bbcgoodfood.com/recipes/144605/tuna-sweet-potato-jackets", "Tuna Sweet Potato Jackets"], ["http://www.bbc.co.uk/food/recipes/sausage_rolls_with_86029", "Sausage Rolls with Caramelised Onions"], ["http://www.bbc.co.uk/food/recipes/pork_belly_with_apples_71757", "Pork Belly with Apple and Sage"]].sample end def mild_days @rand_rec = [["http://www.bbcgoodfood.com/recipes/144605/tuna-sweet-potato-jackets", "Tuna Sweet Potato Jackets"], ["http://www.bbc.co.uk/food/recipes/carrot_and_poppyseed_72665", "Carrot and Poppyseed Salad"], ["http://www.bbc.co.uk/food/recipes/pork_pie_with_chicken_02918", "Pork Pie with Chicken and Apricots"]].sample end def balmy_days @rand_rec = [["http://www.bbc.co.uk/food/recipes/quichelorraine_71987", "Quiche Lorraine"], ["http://www.bbc.co.uk/food/recipes/scottish_cranachan_with_74862", "Scottish Cranachan"], ["http://www.bbc.co.uk/food/recipes/mixed_bean_salad_89055", "Mixed Bean Salad"]].sample end def hot_days @rand_rec = [["http://www.bbc.co.uk/food/recipes/strawberrydiaquiri_86315", "Strawberry Daiquiri"], ["http://www.bbc.co.uk/food/recipes/coconuticecream_86100", "Coconut Icecream"], ["http://www.bbc.co.uk/food/recipes/pistachio_and_rose_ice_66443", "Pistachio and Rose Icecream"]].sample end end
true
a52ab11721383263851b2e1e1cad89d7a2d01096
Ruby
kylehenson/salesengine
/test/merchant_repository_test.rb
UTF-8
4,093
2.984375
3
[]
no_license
require_relative 'test_helper' require_relative '../lib/merchant_repository' require_relative '../lib/sales_engine' class MerchantRepositoryTest < Minitest::Test def test_it_exists assert MerchantRepository end def test_it_holds_seven_merchant_instances merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert merchant_repo.merchants.count == 7 end def test_it_contains_parsed_merchant_objects merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) first = merchant_repo.merchants.first assert_equal "Schroeder-Jerde", first.name end def test_it_can_return_all_merchants merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) all = merchant_repo.all assert_equal 7, all.count assert_equal Merchant, all[0].class end def test_it_can_return_a_random_merchant merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) random = merchant_repo.random assert random assert_equal Merchant, random.class end def test_it_can_find_an_instance_of_merchant_by_id merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert_equal "Willms and Sons", merchant_repo.find_by_id(3).name end def test_it_can_find_an_instance_of_merchant_by_name merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert_equal 2, merchant_repo.find_by_name("Klein, Rempel and Jones").id end def test_it_can_find_an_instance_of_merchant_by_created_at merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert_equal 1, merchant_repo.find_by_created_at("2012-03-27 14:53:59 UTC").id end def test_it_can_find_an_instance_of_merchant_by_updated_at merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert_equal 1, merchant_repo.find_by_updated_at("2012-03-27 14:53:59 UTC").id end def test_it_can_find_all_instances_of_merchant_by_id merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert_equal 2, merchant_repo.find_all_by_id(1).count end def test_it_can_find_all_instances_of_merchant_by_name merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert_equal 2, merchant_repo.find_all_by_name("Williamson Group").count end def test_it_can_find_all_instances_of_merchant_by_created_at merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert_equal 7, merchant_repo.find_all_by_created_at("2012-03-27 14:53:59 UTC").count end def test_it_can_find_all_instances_of_merchant_by_updated_at merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert_equal 6, merchant_repo.find_all_by_updated_at("2012-03-27 14:53:59 UTC").count end def test_it_returns_an_empty_array_if_no_matches_for_find_all_by_x merchant_repo = MerchantRepository.new('./test/support/merchants.csv', nil) assert_equal [], merchant_repo.find_all_by_id(10) end def test_it_can_return_most_revenue engine = SalesEngine.new('./data') assert_equal Array, engine.merchant_repository.most_revenue(5).class assert_equal Merchant, engine.merchant_repository.most_revenue(5).first.class assert_equal "Dicki-Bednar", engine.merchant_repository.most_revenue(5).first.name end def test_it_can_return_most_items engine = SalesEngine.new('./data') assert_equal Array, engine.merchant_repository.most_items(5).class assert_equal Merchant, engine.merchant_repository.most_items(5).first.class first_merch = engine.merchant_repository.most_items(5).first second_merch = engine.merchant_repository.most_items(5)[1] assert first_merch.total_merchant_items > second_merch.total_merchant_items end def test_it_can_return_all_revenues_for_given_date engine = SalesEngine.new('./data') assert_equal BigDecimal, engine.merchant_repository.revenue(Date.parse("2012-03-17")).class assert_equal 2703531, engine.merchant_repository.revenue(Date.parse("2012-03-17")).to_i end end
true
fb3e1b65b07dc607ad4e1f1ef6827c90fcbc3472
Ruby
piotrekkopanski/ads
/app/services/read_notifications_service.rb
UTF-8
643
2.671875
3
[]
no_license
class ReadNotificationsService def self.valid_keys(options) expected_keys_string = ["email", "category", "cost"] expected_keys_symbol = [:email, :category, :cost] if (options.keys - expected_keys_string).empty? or (options.keys - expected_keys_symbol).empty? return true end end public def self.read(x, options = { } ) if valid_keys(options) @notifications = Notification.where(read: false).where(options).first(x) puts @notifications.to_s @notifications.map{ |notification| notification.update_attributes( { read: true } ) } else puts "Wrong options" end end end
true
49152c4d9578ab92240cf77b5358892309d73e7d
Ruby
nullobject/mache
/lib/mache/node.rb
UTF-8
1,353
3.078125
3
[ "MIT" ]
permissive
require 'mache/dsl' module Mache # The {Node} class represents a wrapped HTML page, or fragment. It exposes all # methods from the Mache DSL, and forwards any Capybara API methods to the # {#node} object. # # @abstract class Node include DSL # The underlying Capybara node object wrapped by this instance. # # @return [Capybara::Node] a node object attr_reader :node # Returns a new instance of Node. # # @param node [Capybara::Node] a Capybara node object to wrap def initialize(node:) @node = node end # Tests whether the node is empty. # # @return [Boolean] `true` if the node is empty, `false` otherwise. def empty? node.all('*').length.zero? end # Forwards any Capybara API calls to the node object. if RUBY_VERSION < "3" def method_missing(name, *args, &block) if @node.respond_to?(name) @node.send(name, *args, &block) else super end end else def method_missing(name, *args, **kwargs, &block) if @node.respond_to?(name) @node.send(name, *args, **kwargs, &block) else super end end end # @!visibility private def respond_to_missing?(name, include_private = false) @node.respond_to?(name) || super end end end
true
7a08062d3080e1232000339c3058e8a425ec464d
Ruby
JamManolo/api-dev
/transform-groups.rb
UTF-8
1,576
2.625
3
[]
no_license
# # simple 'include' file for transform tools # def create_group_map(options={}) league_id = options[:league_id] fixtures_xml = options[:xml] group_hash = Hash.new fixtures_xml.xpath("//Match").each do |node| if [16, 17].include? league_id home_team_id = node.xpath("HomeTeam_Id").text away_team_id = node.xpath("AwayTeam_Id").text if group_hash[home_team_id].nil? group_hash[home_team_id] = Array.new group_hash[home_team_id] << home_team_id group_hash[home_team_id] << away_team_id elsif !group_hash[home_team_id].include? away_team_id group_hash[home_team_id] << away_team_id end end end groups = Array.new team_has_group = Hash.new group_hash.each do |k,v| if team_has_group[k].nil? groups << v v.each do |t| team_has_group[t] = true end end end # Group name order hard-coded for 2013 (due to xmlsoccer fixture order) if league_id == 16 group_names = [ 'A', 'D', 'B', 'C', 'H', 'F', 'E', 'G', ] elsif league_id == 17 group_names = [ 'A', 'E', 'F', 'B', 'C', 'D', 'J', 'H', 'I', 'K', 'G', 'L' ] end unsorted_groups = Hash.new groups.each do |group| group_name = group_names.shift unsorted_groups[group_name] = Array.new group.each do |team_id| unsorted_groups[group_name] << team_id group_hash[team_id.to_s] = group_name end end # @groups = Hash.new # unsorted_groups.keys.sort.each do |key| # @groups[key] = unsorted_groups[key] # end group_hash end
true
f044224c6d19ef3191e097ca5ae4a5b1d93a5c7a
Ruby
guilhermepalmeira/linuxfi-loja
/app/models/pedido.rb
UTF-8
1,699
2.765625
3
[]
no_license
class Pedido < ActiveRecord::Base has_many :itens, :dependent => :destroy #um pedido tem vários itens, o :dependent, destroy o item se ele for zero accepts_nested_attributes_for :itens #vai aceitar receber os atributos de forma aninhada #vai atumaticamente criar no seu objeto um metodo "itens_attributes", criadno um array de hashs" #def itens_attributes=(array) after_save :remover_itens_zerados#gancho pra remover do carrinho qdo for zerado belongs_to :usuario, :counter_cache => "pedidos_count" def adicionar_produto(produto, quantidade) if item = self.itens.detect { |i| i.produto == produto } item.update_attributes(:quantidade => quantidade + item.quantidade)#se ja tiver adiciona mais um produto else self.itens.build( :produto_id => produto.id, :quantidade => quantidade )#se nao, cria um novo objeto do tipo item atravez do metodo build end end def preco_total self.itens.to_a.sum( &:preco_total )#metodo to_a convete pra array #self.itens.to_a.sum{ |item| item.preco_total }# a mesma coisa do codigo de cima, o & o substitui end def blank?#pergunta se o objeto ta vazio self.itens.blank? end def quantidade_total self.itens.sum(:quantidade) end def unir(pedido) return if pedido.blank? || self == pedido pedido.itens.each do |item| self.adicionar_produto(item.produto, item.quantidade) end pedido.destroy self.save end protected def remover_itens_zerados itens_a_remover = [] self.itens.each do |item| if item.quantidade.blank? || item.quantidade < 1 itens_a_remover << item end end self.itens.delete( *itens_a_remover ) true end end
true
19a0df3782a3de0fbccdd42201eed261bd421ccf
Ruby
randyjap/project-euler
/15.rb
UTF-8
414
3.515625
4
[]
no_license
# Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. # How many such routes are there through a 20×20 grid? # Answer: 137846528820 grid_size = 20 paths = 1 grid_size.times do |idx| paths *= (2 * grid_size) - idx paths /= idx + 1 end puts paths # real 0m0.613s # user 0m0.112s # sys 0m0.116s
true
4f2838b0a2ef697fbf4ddf5a66c8c8dcb92d64ee
Ruby
kurochan/gaspe-bot
/job/keyword_fav.rb
UTF-8
531
2.625
3
[]
no_license
class KeywordFavJob def call(status) return unless status.text data = [ 'がすぺ', 'ガスペ', '清楚', 'せいそ', 'クソネミ', 'くそねみ', 'ラブライブ', 'スクフェス', 'にっこにっこにー', 'じぇい', 'ジェイ', 'サイゼ', 'ぱんだ', 'パンダ', 'ばし', 'くろ' ] data.each do |str| if status.text.include? str puts "Keyword favorited" TwitterClient.instance.favorite status.id break end end end end
true
9abd13c813722f3ba4f4cfd415c749b64f107b13
Ruby
Finble/learn_to_program
/ch11-reading-and-writing/build_your_own_playlist.rb
UTF-8
319
2.671875
3
[]
no_license
# my incomplete solution below, but got timed out... no rspec tests def music_shuffle filenames File.open 'filenames.m3u', 'w' do |f| all_mp3.each do |mp3| f.write mp3.sort_by{rand} + '\n' #write method returns a string? end end end puts 'Done!' #included shuffle method from earlier exercise
true