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
5c360283eb64f5081bc0e8cc2d73c33561eb4f16
Ruby
arnabs542/Programming-Interview-Questions
/Problems/Ruby/Sorting/merge_2_sorted_lists.rb
UTF-8
1,180
4.09375
4
[ "MIT" ]
permissive
require_relative 'implement_linked_list' # Write a merge_2_sorted_lists function that takes two lists, each of which is sorted in increasing order, # and merges the two together into one list which is in increasing order. # merge_2_sorted_lists should return the new list, which should be made by splicing together the nodes of the first two lists. # For example if the first linked list a is 5->10->15 and the other linked list b is 2->3->20, # then merge_2_sorted_lists should return a pointer to the head node of the merged list 2->3->5->10->15->20. def merge_2_sorted_lists(head_1, head_2) return head_1 if head_2 == nil return head_2 if head_1 == nil result_head = nil if head_1.value < head_2.value result_head = head_1 result_head.next_node = merge_2_sorted_lists(head_1.next_node, head_2) else result_head = head_2 result_head.next_node = merge_2_sorted_lists(head_1, head_2.next_node) end result_head end # TEST DRIVE c = Node.new(15, nil) b = Node.new(10, c) a = Node.new(5, b) g = Node.new(20, nil) f = Node.new(3, g) e = Node.new(2, f) merged = merge_2_sorted_lists(a, e) List.new(merged).each {|node| print node.value, " "} puts
true
c0ff51553e5a2e07d853854913eff2f58ffb24a1
Ruby
randy-darsh/ultra_battleship
/test/board_test.rb
UTF-8
1,128
3.046875
3
[]
no_license
require 'minitest/autorun' require 'minitest/emoji' require './lib/board' class BoardTest < Minitest::Test def setup @b = Board.new end def test_it_exists assert_instance_of Board, @b end def test_it_has_a_grid assert_equal [[' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' '], [' ', ' ', ' ', ' ']], @b.grid end def test_it_prints_out_board assert_nil nil, @b.make_board end def test_it_converts_first_character_to_index assert_equal 0, @b.character_to_index("A1") end def test_it_converts_second_number_to_index assert_equal 2, @b.number_to_index("A3") end def test_it_can_convert_both_to_coordinates assert_equal [1, 3], @b.convert_to_coordinates("B4") end def test_it_can_place_the_first_point_of_the_ship assert_equal "S", @b.place_ship("B4") end def test_it_changes_the_grid @b.place_ship("B4") assert_equal [[" ", " ", " ", " "], [" ", " ", " ", "S"], [" ", " ", " ", " "], [" ", " ", " ", " "]], @b.grid end end
true
ed9011e28585cd1247ecd4d4fe21005312abfa9c
Ruby
adamjkalt/Upcoming_Nintendo_Switch_Games_cli_app
/UpcomingNintendoSwitchGames/lib/UpcomingNintendoSwitchGames/cli.rb
UTF-8
829
3.34375
3
[ "MIT" ]
permissive
class UpcomingNintendoSwitchGames::CLI attr_accessor :name, :release_date, :url, :developer, :genre, :rating, :summary, :games def call list_games menu end def list_games puts "Upcoming Nintendo Switch Games" @games = Game.today @games.each_with_index {|game, index| puts "#{index + 1}. #{game.name} - #{game.release_date}"} end def menu input = nil while input != "exit" puts "Choose the Number Corresponding to the Game of your choice." puts "Enter 'exit' to exit this program" input = gets.strip.downcase if input.to_i > 0 game = @games[input.to_i - 1] the_game = Game.scrape_game(game) puts "#{the_game.name} - #{the_game.release_date} - #{the_game.developer} - #{the_game.genre} - #{the_game.summary}" elsif input == "exit" exit end end end end
true
6662a3c76d2ddd5af01696ae2bbc90899e693520
Ruby
neugierige/prep-work
/coding-test-1/practice-problems/problems/13-capitalize-words.rb
UTF-8
1,256
4.65625
5
[]
no_license
# Write a method that takes in a string of lowercase letters and # spaces, producing a new string that capitalizes the first letter of # each word. # # You'll want to use the `split` and `join` methods. Also, the String # method `upcase`, which converts a string to all upper case will be # helpful. # # Difficulty: medium. def capitalize_words(string) indices = [0] idx = -1 while idx < string.length if string[idx] == " " || idx == -1 string[idx+1] = string[idx+1].to_s.upcase! end idx += 1 end return string end # def capitalize_words(string) # indices = [0] # idx = 0 # while idx < string.length # if string[idx] == " " # indices << idx+1 # end # idx += 1 # end # idx2 = 0 # while idx2 < indices.count # cap_letter = string[indices[idx2]].to_s.upcase! # string[indices[idx2]] = cap_letter # idx2 += 1 # end # return string # end # These are tests to check that your code is working. After writing # your solution, they should all print true. puts( 'capitalize_words("this is a sentence") == "This Is A Sentence": ' + (capitalize_words("this is a sentence") == "This Is A Sentence").to_s ) puts( 'capitalize_words("mike bloomfield") == "Mike Bloomfield": ' + (capitalize_words("mike bloomfield") == "Mike Bloomfield").to_s )
true
1b8f91f0be65d6a302eb93c61e156cf36f808b0e
Ruby
appsignal/appsignal-ruby
/spec/support/helpers/std_streams_helper.rb
UTF-8
2,435
3.09375
3
[ "MIT" ]
permissive
module StdStreamsHelper def std_stream Tempfile.new SecureRandom.uuid end # Capture STDOUT in a variable # # Given tempfiles are rewinded and unlinked after yield, so no cleanup # required. You can read from the stream using `stdout.read`. # # Usage # # out_stream = Tempfile.new # capture_stdout(out_stream) { do_something } def capture_stdout(stdout) original_stdout = $stdout.dup $stdout.reopen stdout yield ensure $stdout.reopen original_stdout stdout.rewind stdout.unlink end # Capture STDOUT and STDERR in variables # # Given tempfiles are rewinded and unlinked after yield, so no cleanup # required. You can read from the stream using `stdout.read`. # # Usage # # out_stream = Tempfile.new # err_stream = Tempfile.new # capture_std_streams(out_stream, err_stream) { do_something } def capture_std_streams(stdout, stderr) original_stdout = $stdout.dup $stdout.reopen stdout original_stderr = $stderr.dup $stderr.reopen stderr yield ensure $stdout.reopen original_stdout $stderr.reopen original_stderr stdout.rewind stdout.unlink stderr.rewind stderr.unlink end # Silence the STDOUT. # # Ignore the STDOUT and don't print it in the test suite's STDOUT. # # If an error is found the output the output is raised as an error, failing # the spec. Warnings and other AppSignal messages are ignored. # # @example # silence { do_something } # # Does nothing # # silence { puts "ERROR!" } # # => Error found in silenced output: # # ERROR! # # @example Ignore certain errors # silence(:allowed => ["my error"]) { puts "my error!" } # # Does nothing # # silence { puts "my error!" } # # => Error found in silenced output: # # my error! def silence(options = {}, &block) stream = Tempfile.new(SecureRandom.uuid) capture_std_streams(stream, stream, &block) ensure output = filter_allowed_errors(stream.read, options.fetch(:allowed, [])) raise "Error found in silenced output:\n#{output}" if output =~ /(ERR|Error|error)/ end def filter_allowed_errors(output, allowed_errors) output.lines.reject do |line| reject = false allowed_errors.each do |error| if line.include?(error) reject = true break end end reject end.join(",") end end
true
66c5d9cba365095a1046cd1a35231866c6d59920
Ruby
StefanoMartin/active-orient
/examples/books.rb
UTF-8
3,702
2.734375
3
[ "MIT" ]
permissive
=begin Books Example There are several Books. And there is a Table with Keywords. These are our Vertex-Classes The Keywords are associated to the books, this is realized via an Edge »has_content« This Example demonstrates how to build a query by using OrientSupport::OrientQuery =end class BooksExample def initialize db, rebuild: true if rebuild print("\n === REBUILD === \n") db.delete_class :Book db.delete_class :Keyword db.delete_class :HAS_CONTENT db.create_vertex_class :Book db.create_vertex_class :Keyword db.create_edge_class :HAS_CONTENT print("\n === PROPERTY === \n") ActiveOrient::Model::Keyword.create_property(:item, type: :string, index: :unique) ActiveOrient::Model::Book.create_property(:title, type: :string, index: :unique) end end def read_samples print("\n === READ SAMPLES === \n") fill_database = ->(sentence, this_book ) do sentence.split(' ').each do |x| this_word = Keyword.update_or_create where: { item: x } this_edge = HC.create_edge from: this_book, to: this_word if this_word.present? end end words = 'Die Geschäfte in der Industrie im wichtigen US-Bundesstaat New York sind im August so schlecht gelaufen wie seit mehr als sechs Jahren nicht mehr Der entsprechende Empire-State-Index fiel überraschend von plus Punkten im Juli auf minus 14,92 Zähler Dies teilte die New Yorker Notenbank Fed heut mit Bei Werten im positiven Bereich signalisiert das Barometer ein Wachstum Ökonomen hatten eigentlich mit einem Anstieg auf 5,0 Punkte gerechnet' this_book = Book.create title: 'first' fill_database[ words, this_book ] words2 = 'Das Bruttoinlandsprodukt BIP in Japan ist im zweiten Quartal mit einer aufs Jahr hochgerechneten Rate von Prozent geschrumpft Zu Jahresbeginn war die nach den USA und China drittgrößte Volkswirtschaft der Welt noch um Prozent gewachsen Der Schwächeanfall wird auch als Rückschlag für Ministerpräsident Shinzo Abe gewertet der das Land mit einem Mix aus billigem Geld und Konjunkturprogramm aus der Flaute bringen will Allerdings wirkte sich die heutige Veröffentlichung auf die Märkten nur wenig aus da Ökonomen mit einem schwächeren zweiten Quartal gerechnet hatten' this_book = Book.create title: 'second' fill_database[ words2, this_book ] end def display_books_with *desired_words print("\n === display_books_with #{desired_words.map{|x| x}} === \n") query = OrientSupport::OrientQuery.new from: Keyword, projection: "expand(in('HAS_CONTENT'))" q = OrientSupport::OrientQuery.new projection: 'expand( $z )' intersects = Array.new desired_words.each_with_index do | word, i | symbol = ( i+97 ).chr # convert 1 -> 'a' query.where = { item: word } q.let << { symbol => query } intersects << "$#{symbol}" end q.let << "$z = Intersect(#{intersects.join(', ')}) " puts "generated Query:" puts q.to_s result = Keyword.query_database q, set_from: false puts "found books: " puts result.map( &:title ).join("; ") puts " -- None -- " if result.empty? end end if $0 == __FILE__ require '../config/boot' ActiveOrient::OrientDB.default_server = { user: 'root', password: 'tretretre' } ActiveOrient::OrientDB.logger.level = Logger::WARN r = ActiveOrient::OrientDB.new database: 'BookTest' b = BooksExample.new r, rebuild: true Book = r.open_class "Book" Keyword = r.open_class "Keyword" HC = r.open_class "HAS_CONTENT" b.read_samples if Keyword.count.zero? b.display_books_with 'Land', 'Quartal' end
true
56b98782355be6ba2d7356cb566b6b6158656fb7
Ruby
AntonFagerberg/BM-Elite-Force
/levels/fly_by.rb
UTF-8
4,286
2.8125
3
[]
no_license
require 'levels/level' require 'backgrounds/space_background' require 'entities/players/monkey_cat' require 'entities/players/mewfinator' require 'entities/players/tommy_gun' require 'entities/players/dunderino' require 'entities/players/doris' require 'entities/players/metal_mack' class FlyBy < Level def initialize(window) super() @window = window @background = SpaceBackground.new(window, Size::WINDOW_HEIGHT) @players = Array.new @players.push Mewfinator.new(window) @players.push TommyGun.new(window) @players.push Dunderino.new(window) @players.push Doris.new(window) @players.push MetalMack.new(window) @players.push MonkeyCat.new(window) @players.each do |player| player.hud = false end @font_80 = Gosu::Font.new(window, 'gfx/wendy.ttf', 80) @font_60 = Gosu::Font.new(window, 'gfx/wendy.ttf', 60) @font_40 = Gosu::Font.new(window, 'gfx/wendy.ttf', 40) @black_pixel = Gosu::Image.new(window, 'gfx/black_pixel.bmp', true) start_position = 0 @players.each do |player| player.x = 65 + (Size::WINDOW_WIDTH / 6) * start_position player.y = Size::WINDOW_HEIGHT - 75 start_position += 1 end @text_y = Size::WINDOW_HEIGHT + 1000 #$music["fly_by"] = Gosu::Song.new(window, "sfx/fly_by.ogg") if !$music.key? "fly_by" #$music["fly_by"].play $frame = 0 end def update #puts $frame @players[0].y -= 5 if $frame > 340 and @players[0].y > 50 and @text_y == Size::WINDOW_HEIGHT + 1000 @players[1].y -= 5 if $frame > 340 and @players[1].y > 125 and @text_y == Size::WINDOW_HEIGHT + 1000 @players[2].y -= 5 if $frame > 510 and @players[2].y > 200 and @text_y == Size::WINDOW_HEIGHT + 1000 @players[3].y -= 5 if $frame > 510 and @players[3].y > 275 and @text_y == Size::WINDOW_HEIGHT + 1000 @players[4].y -= 5 if $frame > 690 and @players[4].y > 350 and @text_y == Size::WINDOW_HEIGHT + 1000 @players[5].y -= 5 if $frame > 690 and @players[5].y > 425 and @text_y == Size::WINDOW_HEIGHT + 1000 if $frame > 1000 and @text_y >= 200 @players.each do |player| player.y -= 5 end @text_y = @players[5].y + Size::WINDOW_HEIGHT / 2 if @players[5].y < Size::WINDOW_HEIGHT - 80 end if $frame == 1150 @players[0].y = Size::WINDOW_HEIGHT + 160 @players[1].y = Size::WINDOW_HEIGHT + 120 @players[2].y = Size::WINDOW_HEIGHT + 60 @players[3].y = Size::WINDOW_HEIGHT + 60 @players[4].y = Size::WINDOW_HEIGHT + 120 @players[5].y = Size::WINDOW_HEIGHT + 160 end if $frame > 1150 @players[0].y = @players[0].y - 7 if @players[0].y > 160 @players[1].y = @players[1].y - 7 if @players[1].y > 120 @players[2].y = @players[2].y - 7 if @players[2].y > 60 @players[3].y = @players[3].y - 7 if @players[3].y > 60 @players[4].y = @players[4].y - 7 if @players[4].y > 120 @players[5].y = @players[5].y - 7 if @players[5].y > 160 end end def draw @font_60.draw('The Mewfinator', @players[0].x + 50, @players[0].y - @players[0].mid_height, 1) if @players[0].y < Size::WINDOW_HEIGHT - 120 and $frame < 1150 @font_60.draw('TommyGun', @players[1].x + 50, @players[1].y - @players[1].mid_height, 1) if @players[1].y < Size::WINDOW_HEIGHT - 120 and $frame < 1150 @font_60.draw('El Dunderino', @players[2].x + 50, @players[2].y - @players[2].mid_height, 1) if @players[2].y < Size::WINDOW_HEIGHT - 120 and $frame < 1150 @font_60.draw('Little Doris', @players[3].x - 320, @players[3].y - @players[3].mid_height, 1) if @players[3].y < Size::WINDOW_HEIGHT - 120 and $frame < 1150 @font_60.draw('metal mack', @players[4].x - 310, @players[4].y - @players[4].mid_height, 1) if @players[4].y < Size::WINDOW_HEIGHT - 120 and $frame < 1150 @font_60.draw('monkeycat', @players[5].x - 280, @players[5].y - @players[5].mid_height, 1) if @players[5].y < Size::WINDOW_HEIGHT - 120 and $frame < 1150 @black_pixel.draw($frame * 15, 0, 10, Size::WINDOW_WIDTH, Size::WINDOW_HEIGHT) @font_80.draw('Bm elite force', 175, @text_y, 1) @font_40.draw('- press enter to start -', 205, @text_y + 100, 1) if $frame / 20 % 5 < 4 @background.draw @players.each { |player| player.draw } end def skip #@click_sound.play @done = true end end
true
76077e72dd59939e8d62700bec30e3858b4d3c84
Ruby
henriquegavabarreto/learn_ruby
/05_book_titles/book.rb
UTF-8
635
3.78125
4
[]
no_license
class Book attr_accessor :title def title lil_word = ["for", "and", "nor", "but", "or", "yet", "so", "in", "the", "of", "a", "an"] new_title = "" words = @title.split(" ") words.each_with_index do |word, index| is_lil_word = false lil_word.each do |con| if word == con && index != 0 is_lil_word = true break else is_lil_word = false end end if is_lil_word new_title += word + " " else new_title += word.capitalize + " " end end new_title = new_title.strip end end
true
997a0f6d1029c927120b70ec772e68010488335a
Ruby
mmarroquin/tdi.1.2014
/Spree/mystore/app/models/crm.rb
UTF-8
4,140
2.578125
3
[]
no_license
class Crm < ActiveRecord::Base require 'rest_client' require 'uri' require 'json' def self.crm(rut, direc) @rut_empresa=rut @input_id=direc #Aca definimos los parametros para acceder a la API # @r guarda la informacion del login. @r="" #usuario... @user='grupo1' #URL's del webservice @wsurl='http://integra.ing.puc.cl/vtigerCRM/webservice.php?operation=' @endpointUrl='http://integra.ing.puc.cl/vtigerCRM/webservice.php?' #Aca se hace el login (challenge y login) #definimos url wb challenge get_challenge_url = @wsurl+'getchallenge&username='+@user #hacemos un GET con el usuario challenge =RestClient.get get_challenge_url #obtenemos el token @token=JSON.parse(challenge.body)['result']['token'] #definimos url login path_login =@wsurl+'login' #transformamos los datos @md5 = Digest::MD5.hexdigest(@token+'Cyz9KPyu0sNNknpm') #hacemos el post login=RestClient.post path_login, 'operation' => 'login', 'username' =>@user, 'accessKey'=>@md5 #obtenemos la informacion @p=JSON.parse(login.body)['result'] if(@p==nil or @p['success']==false) #El caso de que no se pudo realizar el login... @r="NO" @message="Sesion ID: "+"-"+". Login aceptado: "+@r else #El caso de que se realizo el login... @r="YES" @message="Sesion ID: "+JSON.parse(login.body)['result']['sessionName']+". Login aceptado: "+@r end ## #@query="select * from Contacts where lastname='Bautista' and firstname='Emilio';" #Aca ya se tiene una conexion a vTiger y se procede a obtener la empresa con el rut del input. #Se define la query a la tabla de empresas (accounts). @query="select * from Accounts where cf_705='"+@rut_empresa+"';" @queryParam = URI::encode(@query) @sessionId=JSON.parse(login.body)['result']['sessionName'] #use sessionId created at the time of login. @params = 'sessionName='+@sessionId+'&operation=query&query='+@queryParam #describe request must be GET request. path_query = @endpointUrl+@params resultado =RestClient.get path_query @id_empresa=JSON.parse(resultado.body)['result'][0]['id'] @b0=resultado.body @nombre_empresa=JSON.parse(resultado.body)['result'][0]['accountname'] @telefono_empresa=JSON.parse(resultado.body)['result'][0]['phone'] @billing_street_empresa=JSON.parse(resultado.body)['result'][0]['bill_street'] @billing_state_empresa=JSON.parse(resultado.body)['result'][0]['bill_city'] @billing_city_empresa=JSON.parse(resultado.body)['result'][0]['bill_state'] #decode the json encode response from the server. @message=@message+"...."+resultado+"..."+@sessionId+"/n/n/n/n" #Aca se procede a obtener la direccion del empleado de la empresa obtenida #Se define el query para obtener el empleado correspondiente @query="select * from Contacts where account_id="+@id_empresa+" and cf_707='"+@input_id+"';" @queryParam = URI::encode(@query) @sessionId=JSON.parse(login.body)['result']['sessionName'] @b1=login.body #use sessionId created at the time of login. @params = 'sessionName='+@sessionId+'&operation=query&query='+@queryParam #describe request must be GET request. path_query2 = @endpointUrl+@params resultado2 =RestClient.get path_query2 @id_empresa=JSON.parse(resultado2.body)['result'][0]['otherstreet'] #decode the json encode response from the server. @b2=resultado2.body @nombre_empleado=JSON.parse(resultado2.body)['result'][0]['firstname'] @apellido_empleado=JSON.parse(resultado2.body)['result'][0]['lastname'] @telefono_empleado=JSON.parse(resultado2.body)['result'][0]['phone'] @account_id_empleado=JSON.parse(resultado2.body)['result'][0]['account_id'] @street_empleado=JSON.parse(resultado2.body)['result'][0]['otherstreet'] @comuna_empleado=JSON.parse(resultado2.body)['result'][0]['othercity'] @region_empleado=JSON.parse(resultado2.body)['result'][0]['otherstate'] @message2="..."+resultado2+"..."+@sessionId @resultado = @street_empleado + "," + @comuna_empleado + "," + @region_empleado return @resultado end end
true
cb86b61e3118cc55ae1d90bc23a416b45e6dac4d
Ruby
Nadav-Rosenberg/takeaway-challenge
/lib/customer.rb
UTF-8
513
2.984375
3
[]
no_license
class Customer attr_reader :name, :telephone, :order def initialize name, telephone @name = name @telephone = telephone @order end def start_order order_class @order = order_class.new end def look_at_menu order.present_menu end def pick(*options) order.pick_items options end def place_order order.place_order end def confirm_order order.confirm_order end end # class Order # def look_at_menu # end # def pick(*options) # end # end
true
e49421edb792239d723e070b3096579fc9641a08
Ruby
reednj/i2c-oled
/oled-rect.rb
UTF-8
312
2.9375
3
[]
no_license
require './lib/oled' class App def main display = OLEDDisplay.new display.fill_color = OLEDDisplay::COLOR_WHITE w = 16 h = 16 x = -w loop do display.clear_buffer display.fill_rect x, 4, w, h display.write_buffer x += 1 x = -w if x >= display.width end end end App.new.main
true
a5c3b1d266cdb5b180cbb7d0b41598a848aa015e
Ruby
knightjoe2222/Advent-of-Code-2017
/day11.rb
UTF-8
929
3.953125
4
[]
no_license
# Take input in, split and assign to directions input = open("text11.txt").read directions = input.strip.split(',') # I will manipulate x, y and z in accordance to # hexagonal grids as described: https://www.redblobgames.com/grids/hexagons/#distances x = 0 y = 0 z = 0 distances = [] # The increment/decrement rules are described in the article I linked. directions.each do |d| if d == "n" y += 1 z -= 1 elsif d == "s" y -= 1 z += 1 elsif d == "ne" x += 1 z -= 1 elsif d == "sw" x -= 1 z += 1 elsif d == "nw" x -= 1 y += 1 elsif d == "se" x += 1 y -= 1 end # Push the shortest path distance from 'home' to new position distances.push((x.abs + y.abs + z.abs) / 2) end # Part 1 is the distance away at the end of the directions puts "Part 1: #{(x.abs + y.abs + z.abs) / 2}" # Part 2 is the maximum distance away during the directions puts "Part 2: #{dists.max}"
true
5b6bb70b37eaa1d0ce0c21a00282b36ace7b5506
Ruby
AnjaLaube3000/Rentosaurus2.0
/db/seeds.rb
UTF-8
778
2.625
3
[]
no_license
puts "Cleans DB..." Booking.destroy_all Dinosaur.destroy_all User.destroy_all puts "Adds 5 new User records..." 5.times do user = User.create!( name: Faker::FunnyName.name, password: 'valid_password', password_confirmation: 'valid_password', email: Faker::Internet.email ) puts "Adds 2 new Dinosaur records..." 2.times do dino = Dinosaur.create!( name: Faker::FunnyName.name, species: Faker::Games::Pokemon.name, age: rand(1000), gender: Faker::Gender.binary_type, food: Faker::Food.vegetables, habits: Faker::Lorem.words, policy: Faker::Color.color_name, location: Faker::Nation.capital_city, description: Faker::Hacker.say_something_smart, price: rand(1000), user: user ) end end
true
8452bf1932820414f0e32b3f5dfc7c8106207917
Ruby
MikhailMS/TwitterProject
/auto_follow.rb
UTF-8
901
2.640625
3
[]
no_license
require 'timers' def autoFollow @potentialUsers = Hash.new() timers = Timers::Group.new auto_timer = timers.every(7200) file = File.open('lastID.txt', 'r') last = file.read file.close @most_recent = @client.search('Company Name').take(50) first = true newLast = '' @most_recent.each do |tweet| if first newLast = tweet.id first = false end if tweet.id.to_s == last.to_s auto_timer.cancel end @user = @client.status(tweet.id).user if (@potentialUsers[@user] == nil) @potentialUsers[@user] = 0 end @potentialUsers[@user] = @potentialUsers[@user] + 1 if @potentialUsers[@user] == 3 @client.follow(@user) end end file = File.open('lastID.txt', 'w') file.print newLast file.close loop { timers.wait } end
true
0dcf41143e00162ac928c943d0796d272687cd7b
Ruby
lingdudefeiteng/pipette
/bulk/join_bams.rb
UTF-8
1,239
2.515625
3
[]
no_license
#!/usr/bin/env ruby $LOAD_PATH.unshift(File.dirname(__FILE__)) require 'sample_report' bam_dir = ARGV[0] output_dir = File.join(bam_dir, "joined_bams") system("mkdir -p #{output_dir}") sample_report_filename = File.join(bam_dir, "Sample_Report.csv") if !File.exists? sample_report_filename puts "ERROR: no sample report in #{path}" exit(1) end sample_report = SampleReport.new(sample_report_filename) bam_filenames = Dir.glob(File.join(bam_dir, "**", "*.group.reorder.bam")) # bam_filenames = Dir.glob(File.join(bam_dir, "**", "*.rmdup.group.bam")) puts "#{bam_filenames.size} found" samples = {} bam_filenames.each do |bam_filename| fastq_filename = File.basename(File.dirname(bam_filename)) + ".fastq.gz" puts fastq_filename fastq_data = sample_report.data_for(fastq_filename) sample_name = fastq_data["sample name"] puts sample_name samples[sample_name] ||= [] samples[sample_name] << bam_filename end puts "#{samples.keys.size} samples found" samples.each do |name, files| output_filename = File.join(output_dir, name + ".bam") command = "samtools merge #{output_filename} #{files.join(" ")}" puts command system command command = "samtools index #{output_filename}" system command end
true
bf59080e17e08a23b8472bff70c8ff8c1d9d2860
Ruby
univbox/CodeEval
/Ruby/Easy/SELF DESCRIBING NUMBERS/selfdescribeingnumbers.rb
UTF-8
330
3.265625
3
[]
no_license
File.open('in.txt').each_line do |line| num_arr = [0,0,0,0,0,0,0,0,0,0] line.chop! numbers = line.split("") numbers.each do |num| num_arr[num.to_i] += 1 end right = 1 position = 0 numbers.each do |num| if num != num_arr[position.to_i].to_s right = 0 end position += 1 end puts right end
true
28de202370c93f6be28e9c2fea85ac5c34218829
Ruby
t6d/blacksmith
/lib/blacksmith/font_builder.rb
UTF-8
1,162
2.828125
3
[ "MIT" ]
permissive
class Blacksmith::FontBuilder class << self def execute(*args, &block) new(*args, &block).execute end end def initialize(filename = nil, &block) raise "Expects filename or block" unless filename || block raise "Expects either a block or a filename - not both" if filename and block raise "File not found: #{filename}" if filename && !File.exist?(filename) @_instructions = block || File.read(filename) @_attributes = {} @_glyphs = {} end def execute case @_instructions when String instance_eval(@_instructions) when Proc instance_eval(&@_instructions) end font = Blacksmith::Font.new(@_attributes) @_glyphs.each do |filename, attrs| attrs[:scale] ||= font.scale attrs[:offset] ||= font.offset attrs[:source] ||= File.join(font.source, filename) font << Blacksmith::Glyph.new(attrs) end font end def glyph(filename, attrs) @_glyphs[filename] = attrs end def method_missing(name, *args) if args.length == 1 @_attributes[name] = args[0] else super end end end
true
269a5cde2227f9ca59fcf44f14fc2bfa5fdf31ed
Ruby
loveo/ID2222
/2/lib/item_set.rb
UTF-8
1,161
3.421875
3
[]
no_license
# Represents an item set of any size class ItemSet attr_reader :item_ids attr_reader :id, :support def initialize(ids, support=0) @id = ids[0] @item_ids = ids[1 .. -1] @support = support @mutex = Mutex.new end # Checks this item set against a basket # and increases its support if it is present def check_basket(basket) increase_support if in_basket?(basket) end # Returns all item ids in this item set def all_item_ids [id] + item_ids end # Returns true if item_ids are equal and ordered def include_ids?(item_ids) all_item_ids == item_ids end # Returns true if item_ids are equal def same_ids?(item_ids) all_item_ids.sort == item_ids.sort end # String representation of ItemSet def to_s "#{all_item_ids} exists in #{@support} baskets" end private # Returns true if this item sets remaining items occurs in a given basket def in_basket?(basket) @item_ids.all? do |item_id| basket.include?(item_id) end end # Increases the support for this item set def increase_support @mutex.synchronize do @support += 1 end end end
true
61c87dd64af00e201946e6a02f6437f8d8a025ce
Ruby
MIKEALGEE/Homework_day3
/excervise_B.rb
UTF-8
1,596
3.015625
3
[]
no_license
users = { "Jonathan" => { :twitter => "jonnyt", :lottery_numbers => [6, 12, 49, 33, 45, 20], :home_town => "Stirling", :pets => [ { :name => "fluffy", :species => "cat" }, { :name => "fido", :species => "dog" }, { :name => "spike", :species => "dog" } ] }, "Erik" => { :twitter => "eriksf", :lottery_numbers => [18, 34, 8, 11, 24], :home_town => "Linlithgow", :pets => [ { :name => "nemo", :species => "fish" }, { :name => "kevin", :species => "fish" }, { :name => "spike", :species => "dog" }, { :name => "rupert", :species => "parrot" } ] }, "Avril" => { :twitter => "bridgpally", :lottery_numbers => [12, 14, 33, 38, 9, 25], :home_town => "Dunbar", :pets => [ { :name => "monty", :species => "snake" } ] } } p users["Jonathan"][:twitter] #1 p users["Erik"][:home_town]#2 users["Avril"][:pets].select{|a| p a[:species] }#3 eriksnumbers = users["Erik"][:lottery_numbers].sort p eriksnumbers.first #4 users["Avril"][:lottery_numbers].each{|x| p x if x.even?}#5 users["Erik"][:lottery_numbers] << 7 #6 p users["Erik"][:lottery_numbers] #6 users["Erik"].delete(:home_town) #7 users["Erik"][:home_town] = "Edinburgh" #7 p users["Erik"][:home_town] # 7 p users["Erik"][:pets].push(species:"dog", name:"Fluffy")#8 users["Michael"]= {twitter:"MIKEALGEE", lottery_numbers:[1,5,6,8,3,5], home_town:"Edinburgh",pets:{species:"dog", name:"Max"}} #9 p users
true
e06017589db23bfa3afa2b6419b2283c0a130450
Ruby
takafan/hessian2
/test/fiber_concurrency/mysql2_query.rb
UTF-8
659
2.515625
3
[ "MIT" ]
permissive
require 'em-synchrony' require 'em-synchrony/mysql2' require 'em-synchrony/fiber_iterator' require 'yaml' options = YAML.load_file(File.expand_path('../../../spec/database.yml', __FILE__)) puts options.inspect number_of = 10 concurrency = 2 connection_pool_size = 4 results = [] db = EM::Synchrony::ConnectionPool.new(size: connection_pool_size) do Mysql2::EM::Client.new(options) end EM.synchrony do EM::Synchrony::FiberIterator.new(0...number_of, concurrency).each do |i| puts i results << db.query('select sleep(1)').first end puts "results.size #{results.size}" EM.stop end puts results.inspect puts "results.size #{results.size}"
true
2bf3c874c6629f34e07b850b0960729d82fbc968
Ruby
freegeek-pdx/fgdiag
/bin/fake_badblocks
UTF-8
331
2.9375
3
[]
no_license
#!/usr/bin/ruby count = 10 count.times {|i| $stderr.puts "%s: %d / %d" % ['meow' * 20, i+1, count] $stderr.flush sleep 1 } $stderr.puts "meow" * 100 $stdout.puts "bad sector found at sector 10" $stdout.flush while true $stderr.puts "%s: %d / %d" % ['meow' * 20, count + 1, count] $stderr.flush sleep 1 end
true
211cb73a99d61faa8c5cccb563d70f4a6e34e3bc
Ruby
jcreiff/exercism
/ruby/triangle/triangle.rb
UTF-8
347
3.28125
3
[]
no_license
class Triangle def initialize(sides) @sides = sides.sort @valid = @sides[0..1].sum > @sides.last @lengths = sides.uniq.count end [['equilateral?', :==, 1], ['isosceles?', :<=, 2], ['scalene?', :==, 3]].each do |name, operator, number| define_method(name.to_sym) { @valid && @lengths.send(operator, number) } end end
true
1baa166653b60ee1678a2302e9b5f7a9e820e91f
Ruby
ssheehan1210/ruby-reps-101
/reps.rb
UTF-8
3,728
4.875
5
[]
no_license
# write your reps here # makes sure to either `p my_output` or `puts my_output`. # `p _variablename_` prints the full Object # `puts _variablename_` prints the Object.to_s (.toString()) # to run, just `ruby reps.rb` # Round 1: # Write a function lengths that accepts a single parameter as an argument, # namely an array of strings. The function should return an array of numbers. # Each number in the array should be the length of the corresponding string. words = ["hello", "what", "is", "up", "dude"] def lengths(strArr) strArr.map{|word| word.length} end p lengths(words) # Round 2: # Write a Ruby function called transmogrifier. This function should accept three # arguments, which you can assume will be numbers. Your function should return # the "transmogrified" result # The transmogrified result of three numbers is the product (numbers multiplied together) # of the first two numbers, raised to the power (exponentially) of the third number. # For example, the transmogrified result of 5, 3, and 2 is (5 times 3) to the power # of 2 is 225. # Use your function to find the following answers. # transmogrifier(5, 4, 3) # transmogrifier(13, 12, 5) # transmogrifier(42, 13, 7) def transmogrifier(num1, num2, num3) (num1 * num2) ** num3 end p transmogrifier(5, 4, 3) # 8000 p transmogrifier(13, 12, 5) # 92389579776 p transmogrifier(42, 13, 7) # 14466001271480793216 # Round 3: # Write a function called toonify that takes two parameters, accent and sentence. # If accent is the string "daffy", return a modified version of sentence with # all "s" replaced with "th". # If the accent is "elmer", replace all "r" with "w". # Feel free to add your own accents as well! # If the accent is not recognized, just return the sentence as-is. def toonify(accent, sentence) if accent == "daffy" sentenceArr = sentence.split('') sentenceArr.map! do |word| if word == 's' word = 'th' else word = word end end p sentenceArr.join() elsif accent == "elmer" sentenceArr = sentence.split('') sentenceArr.map! do |word| if word == 'r' word = 'w' else word = word end end p sentenceArr.join() else p sentence end end toonify("daffy", "so you smell like sausage") toonify("elmer", "I am hunting rabbits right now") # Round 4: # Write a function wordReverse that accepts a single argument, a string. The method # should return a string with the order of the words reversed. Don't worry about # punctuation. def wordReverse(string) reverseStr = string.reverse stringArr = reverseStr.split(' ') stringArr.map! do |word| word.reverse end p stringArr.join(' ') end wordReverse("Now I know what a TV dinner feels like") # Round 5: # Write a function letterReverse that accepts a single argument, a string. # The function should maintain the order of words in the string but reverse the # letters in each word. Don't worry about punctuation. This will be very similar to # round 4 except you won't need to split them with a space. def letterReverse(string) p string.split.map { |letter| letter.reverse }.join(' ') end letterReverse("Now I know what a TV dinner feels like") letterReverse("Put Hans back on the line") # Round 6: # Write a function longest that accepts a single argument, an array of strings. # The method should return the longest word in the array. In case of a tie, # the method should return either. def longest(stringArray) longestString = '' stringArray.each do |word| if word.length > longestString.length longestString = word end end p longestString end longest(["oh", "good", "grief"]) longest(["Nothing" , "takes", "the", "taste", "out", "of", "peanut", "butter", "quite", "like", "unrequited", "love"])
true
b41389958d4a06f344ecd220b7b69cd03c57197a
Ruby
SchmuhlFace/phase-0-tracks
/ruby/gps2_2.rb
UTF-8
4,947
4.15625
4
[]
no_license
# Release 0 def create_grocery_list(str_items) grocery_list = {} str_items.split(" ").each do |item| grocery_list[item]= 1 end grocery_list end <<<<<<< HEAD def add_item(list, str_item, num) list[str_item] = num list end def update_quantity(list,str_item,new_num) list[str_item] = new_num list end def remove_item(list, str_item_remove) list.delete(str_item_remove) list end def print_list(list) puts "here's your grocery list:" list.each {|item,quantity| puts "*#{item}:#{quantity}"} ======= def add_item(g_l, str_item, num) g_l[str_item] = num g_l end def remove_item(g_l, str_item_remove) g_l.delete(str_item_remove) g_l end def update_quantity(g_l,str_item,new_num) g_l[str_item] = new_num g_l end def print_list(g_l) puts "here's your grocery list:" g_l.each {|item,quantity| puts "*#{item}:#{quantity}"} >>>>>>> 50bc3144704857729ec595682d1258de7ce3d614 end #Driver code my_list = create_grocery_list("apples cereal pizza") my_list = add_item(my_list, "peach", 2) my_list = add_item(my_list, "berry", 2) my_list = add_item(my_list, "lemonade", 2) my_list = add_item(my_list, "tomatoes", 3) my_list = add_item(my_list, "onions", 1) my_list = add_item(my_list, "icecream", 4) p my_list p my_list = remove_item(my_list,"lemonade") p my_list = update_quantity(my_list,"icecream",1) p my_list = print_list(my_list) # Method to create a list # input: string of items separated by spaces (example: "carrots apples cereal pizza") # steps: # create empty data structure to shovel items into # put each item into an hash/array # set default quantity of each item to 1 # print the ugly hash list to the console [using last method "make pretty and print" # output: hash that prints # Method to add an item to a list # input: take in item as parameter # steps: shoveling an item into the array/hash # output: updated hash grocery list # Method to remove an item from the list # input: list hash/collection and the item as parameters # steps: delete a specific item in the list as well as it's quantity # output: new list with the deleted item gone. # Method to update the quantity of an item # input: list hash/collection and the quantity # steps: USe the list hash and key to call up the number which is the value and put a new number in its place # output: updated list with new quantity # Method to print a list and make it look pretty # input: the final list # steps: use the awesome .each method to print out each item and quantity, which will make this look pretty. Add punctuation for added flare. # output: a VERY lovely list of items with quantities so I can go grocery shopping RIGHT ;) #REFLECTION #What I learned about pseudocoding: I don't need to be so stressed about it. I had the chance to practice it on my own and it went well. Daniel suggested I do the first two, and then the rest. this helped tremendously. #Trade offs: hashes and arrays are containers, and important for this exercise. I like that a an array was needed first, and it transitioned nicely into a hash ( even logically so!). #A method returns the last declared variable. I GET this now! I also understand why we need to sometimes use hard returns ( we don't have to in this exercise). #You can pass all kinds of things between methods when you use variables, even other methods (says the text at the top of this exercise). This time I passed my hash via a variable, a string, and an integer. <<<<<<< HEAD #Because I was able to solo pair, I now am really understanding how to make methods "speak" to each other. I went through making "bad code" become good code, and Daniel helped me see the *logical* progression of how this works. I liked being able to think through things by making mistakes and seeing my errors, as well as learning more DRY ways to do things. I'm going to retry this exercise on my own for practice / a refresher before the RUBY test, b/c I found this very helpful. In my last pair, we made an EXTREMLY complicated program that really confused me. This time, I feel MUCH better about the concepts I've learned ( hashes, arrays, how to pass info, etc.) ======= #Because I was able to solo pair, I now am really understanding how to make methods "speak" to each other. I went through making "bad code" become good code, and Daniel helped me see the *logical* progression of how this works. I liked being able to think through things by making mistakes and seeing my errors, as well as learning more DRY ways to do things. I'm going to retry this exercise on my own for practice / a refresher before the RUBY test, b/c I found this very helpful. In my last pair, we made an EXTREMLY complicated program that really confused me. This time, I feel MUCH better about the concepts I've learned ( hashes, arrays, how to pass info, etc.) >>>>>>> 50bc3144704857729ec595682d1258de7ce3d614
true
6d0ecca188712cc6ea6afdb81f2934cd3d493d13
Ruby
daveroberts/script-runner
/backend/app/models/queue_item.rb
UTF-8
4,382
2.5625
3
[]
no_license
require './app/database/database.rb' require 'securerandom' # manages scripts in database class QueueItem def self.columns [:id, :queue_name, :state, :item, :summary, :image_id, :created_at] end def self.add(queue_name, item, options={ summary: nil, image_id: nil }) image_id = options[:image_id] fields = { id: SecureRandom.uuid, queue_name: queue_name, state: 'NEW', item: item.to_json, summary: options[:summary] ? options[:summary].to_json : item.to_json, image_id: options[:image_id], created_at: Time.now } DataMapper.insert("queue_items", fields) end def self.delete(id) DataMapper.delete("queue_items", {id: id}) end def self.requeue(id) DataMapper.update("queue_items", {id: id, state: 'NEW'}) end # Locks the next item ready for processing def self.next(queue_name = nil) item_ids = QueueItem.items_ready_for_processing(queue_name) item_ids.each do |item_id| locked = QueueItem.lock_for_processing(item_id) next if !locked return QueueItem.get(item_id) end return nil end def self.process(queue_item_id) sql = "UPDATE queue_items SET state='DONE', locked_at=NULL WHERE id=? AND locked_at IS NOT NULL" stmt = nil results = nil DB.use do |db| stmt = db.prepare(sql) results = stmt.execute(id) return db.affected_rows end end def self.items_ready_for_processing(queue_name = nil) queue_clause = queue_name ? "AND qi.queue_name = ?" : "" variables = [] variables.push(queue_name) if queue_name sql = " SELECT qi.id FROM queue_items qi INNER JOIN scripts s on s.trigger_queue=TRUE AND s.queue_name=qi.queue_name WHERE qi.state='NEW' #{queue_clause} ORDER BY qi.created_at ASC" ids = DataMapper.raw_select(sql, variables) return ids.map{|row|row[:id]} end def self.by_queue_name(queue_name) sql = " SELECT qi.`id` as qi_id, qi.`queue_name` as qi_queue_name, qi.`state` as qi_state, qi.`summary` as qi_summary, qi.`image_id` as qi_image_id, qi.`created_at` as qi_created_at, s.`id` as s_id, s.name as s_name FROM queue_items qi LEFT JOIN scripts s on qi.queue_name=s.queue_name WHERE qi.queue_name = ? ORDER BY qi.created_at DESC" items = DataMapper.select(sql, { prefix: 'qi', has_many: [ { scripts: { prefix: 's' } } ] }, [queue_name]) items.each do |item| item[:summary] = JSON.parse(item[:summary], symbolize_names: true) end items end def self.get(id) sql = " SELECT #{QueueItem.columns.map{|c|"qi.`#{c}` as qi_#{c}"}.join(",")}, #{Script.columns.map{|c|"s.`#{c}` as s_#{c}"}.join(",")} FROM queue_items qi LEFT JOIN scripts s on qi.queue_name=s.queue_name WHERE qi.id = ? ORDER BY qi.created_at DESC" item = DataMapper.select(sql, { prefix: 'qi', has_one: [ { script: { prefix: 's' } } ] }, [id]).first return nil if !item item[:item] = JSON.parse(item[:item], symbolize_names: true) item[:summary] = JSON.parse(item[:summary], symbolize_names: true) item end def self.names sql =" SELECT qi.queue_name, qi.state, count(qi.id) as total FROM queue_items qi GROUP BY qi.queue_name, qi.state ORDER BY qi.queue_name ASC " rows = DataMapper.raw_select(sql) queues = {} rows.each do |row| queues[row[:queue_name]] = {} if !queues.has_key?(row[:queue_name]) queues[row[:queue_name]][row[:state]] = row[:total] end queues end def self.lock_for_processing(id) sql = "UPDATE queue_items SET state='PROCESSING', locked_at=NOW() WHERE state='NEW' AND id=?" stmt = nil results = nil DB.use do |db| stmt = db.prepare(sql) results = stmt.execute(id) return db.affected_rows end end def self.error_processing(id) sql = "UPDATE queue_items SET state='ERROR', locked_at=NULL WHERE state='PROCESSING' AND id=?" stmt = nil results = nil DB.use do |db| stmt = db.prepare(sql) results = stmt.execute(id) return db.affected_rows end end def self.finish_processing(id) sql = "UPDATE queue_items SET state='DONE', locked_at=NULL WHERE state='PROCESSING' AND id=?" stmt = nil results = nil DB.use do |db| stmt = db.prepare(sql) results = stmt.execute(id) return db.affected_rows end end end
true
2d5c01155d57412f573249d8b6ebf8221f5b111c
Ruby
nkhosla91/ruby-enumerables-reverse-each-word-lab-nyc-web-082619
/reverse_each_word.rb
UTF-8
138
3.609375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def reverse_each_word(string) newarray = string.split(" ") revarray = newarray.collect { |word| word.reverse} revarray.join(" ") end
true
1103f539fe07d85e2af98ca7265371a09c1620df
Ruby
cameronjkelley/the_odin_project
/ruby/tic_tac_toe/tic_tac_toe.rb
UTF-8
2,828
3.828125
4
[]
no_license
module TicTacToe class Player attr_accessor :name, :mark, :moves def initialize(name, mark) @name = name @mark = mark @moves = [] end end class Grid attr_accessor :grid, :cells def initialize @grid = [ ["1", "|", "2", "|", "3"], ["-", "|", "-", "|", "-"], ["4", "|", "5", "|", "6"], ["-", "|", "-", "|", "-"], ["7", "|", "8", "|", "9"] ] @cells = (1..9).to_a end def print_grid @grid.each { |row| puts row.join(" ") } end end class Game @@wins = [[1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 5, 9], [3, 5, 7]] def initialize @game_grid = Grid.new @turns = 9 @player1 = whos_playing(1) @player2 = whos_playing(2) instructions play end def whos_playing(z) mark = "" z == 1 ? mark = "X" : mark = "O" puts "\nPlayer #{z} enter your name: " print ">> " Player.new(gets.chomp, mark) end def instructions puts "\nLet's play Tic Tac Toe!" puts "\nThe grid is set up just like a telephone keypad:" @game_grid.print_grid puts "Just enter 1-9 to put your mark." end def play begin player = whose_turn puts "\nYour turn, #{player.name}." print ">> " cell_played = gets.chomp a_turn(player, cell_played) end until win? || cat? play_again end def win? player = whose_turn @@wins.each do |win| three_in_a_row = 0 player.moves.each do |move| if win.include?(move.to_i) three_in_a_row += 1 end if three_in_a_row == 3 puts "#{player.name} wins! Congratulations!" true end end end @turns -= 1 false end def cat? if @turns == 0 && !win? puts "CAT!" true else false end end def whose_turn @turns % 2 != 0 ? @player1 : @player2 end def a_turn(x, y) if @game_grid.cells.include?(y.to_i) @game_grid.cells.delete(y.to_i) x.moves << y update_grid(y) else puts "That's an invalid move. Please enter the number of an open cell." print ">> " z = gets.chomp a_turn(x, z) end end def update_grid(y) a, b = "", "" case when y == "1" then a, b = 0, 0 when y == "2" then a, b = 0, 2 when y == "3" then a, b = 0, 4 when y == "4" then a, b = 2, 0 when y == "5" then a, b = 2, 2 when y == "6" then a, b = 2, 4 when y == "7" then a, b = 4, 0 when y == "8" then a, b = 4, 2 else a, b = 4, 4 end @game_grid.grid[a][b] = whose_turn.mark @game_grid.print_grid end def play_again puts "Want to play again? Y or N" print ">> " response = gets.chomp.upcase if response == "Y" Game.new.play elsif response == "N" puts "Thanks for playing." else puts "What? Well, thanks for playing." end end end end TicTacToe::Game.new
true
9c3cc4336c91dfd10675d0be305116048bd95ff8
Ruby
micahboyd/shame-bot
/shamebot/bot.rb
UTF-8
1,944
2.84375
3
[]
no_license
module ShameBot class Bot < SlackRubyBot::Bot help do title 'Wall of Shame' desc 'Here are recorded those who have made embarassing blunders' command 'add team' do desc 'Add a team to the Wall of Shame' long_desc 'type "add team "TEAM NAME"" to add a team to the Wall of Shame' end command 'remove team' do desc 'Remove a team from the Wall of Shame' long_desc 'type "remove team "TEAM NAME"" to remove a team from the Wall of Shame' end command 'add user' do desc 'Add user to a team' long_desc 'type "add user \'USER NAME\' to \'TEAM NAME\' to add a user to a team' end command 'remove user' do desc 'Remove user from a team' long_desc 'type "remove user \'USER NAME"" to remove from their respective team' end command 'shame' do desc 'Shame people for their embarrasing blunders' long_desc 'type "shame \'USER NAME\' for reason" to shame to an existing user. Punctuate to beween reasons to add multiple at one time. Shamings cannot be deleted!' end command 'list team shamings' do desc 'List all shamings from a team' long_desc 'type "list team shamings for \'USER NAME\' to see a list for a teams collective shamings' end command 'list user shamings' do desc 'List a users shamings' long_desc 'type "list user shamings for \'USER NAME\' to see a users shamings' end command 'list team rankings' do desc 'Display all teams ranked by their shamings count' long_desc 'type "list team rankings" to see a list of all teams sorted by their shaming count' end command 'list user rankings' do desc 'Display all users ranked by their shamings count' long_desc 'type "list user rankings" to see a list of all users sorted by their shaming count' end end end end
true
ba186e2b99b4ca84eabc06e11067349d442b857a
Ruby
silvstar0/leaderbits-ReactRoR
/lib/organization_monthly_activity_report.rb
UTF-8
2,190
2.53125
3
[]
no_license
# frozen_string_literal: true class OrganizationMonthlyActivityReport include ActionView::Helpers::NumberHelper def initialize(organizations) @organizations = organizations fetch_data end def increment_for_organization(organization) user_ids = organization.users.pluck(:id) was = @two_months_old_logs.count { |_leaderbit_id, user_id| user_ids.include? user_id }.to_f now = @this_month_logs.count { |_leaderbit_id, user_id| user_ids.include? user_id }.to_f result = (now - was) / was.to_f * 100.0 if result.infinite? <<-HTML <font style="cursor: help" title="Numbers are not comparable because past month's value is zero">N/A</font> <div><small style="cursor: help" title="Completed challenges">#{was.to_i} => #{now.to_i}</small></div> HTML elsif result.positive? <<-HTML <font style="color: green">+ #{number_to_percentage result, precision: 0}</font> <div><small style="cursor: help" title="Completed challenges">#{was.to_i} => #{now.to_i}</small></div> HTML elsif result.negative? <<-HTML <font style="color: red">– #{number_to_percentage result.abs, precision: 0}</font> <div><small style="cursor: help" title="Completed challenges">#{was.to_i} => #{now.to_i}</small></div> HTML elsif result.zero? <<-HTML <font style="">=</font> <div><small style="cursor: help" title="Completed challenges">#{was.to_i} => #{now.to_i}</small></div> HTML else <<-HTML <font style="">=</font> <div><small style="cursor: help" title="Completed challenges">#{was.to_i} => #{now.to_i}</small></div> HTML end end private def fetch_data range1 = 2.months.ago..1.month.ago range2 = 1.month.ago..Time.now @two_months_old_logs = LeaderbitLog .completed .where(updated_at: range1) .pluck(:leaderbit_id, :user_id) @this_month_logs = LeaderbitLog .completed .where(updated_at: range2) .pluck(:leaderbit_id, :user_id) end end
true
5f6980164f8b782788a64040a7fb5690d4c0ed7c
Ruby
rfleur01/RB101-109
/Small_Problems/easy_3/oddities.rb
UTF-8
151
3.546875
4
[]
no_license
def oddities(array) odd_elements = [] index = 0 while index < array.size odd_elements << array[index] index += 2 end odd_elements end
true
87db4057ace96e26dbf9a9a083c06b64bb94ee51
Ruby
chiwenchen/awesome_list
/app/services/graphql/response.rb
UTF-8
502
2.609375
3
[]
no_license
module Graphql class Response attr_reader :raw_response def initialize(raw_response) @raw_response = raw_response end def success? errors.blank? end def fail? !success? end # for successful response def json_data JSON.parse(raw_response.data.to_json) end # for failed response def error_sentence errors.messages['data'].to_sentence end private def errors raw_response.errors.all end end end
true
7efaa17221e6d20b7e62fa3e694d2ace181c35b9
Ruby
jesperglad/vikiwar
/app/models/order.rb
UTF-8
14,391
2.609375
3
[]
no_license
class Order < ActiveRecord::Base belongs_to :unit belongs_to :area_element validates_numericality_of :turn # # Order Parser # def Order.next_part the_order_string the_comma_index = the_order_string.index(',') the_return_string = the_order_string.slice!(0, the_comma_index+1) return the_return_string.delete(',').strip() end def Order.parse_unit_order_string gs, the_user_id, the_order_string the_unit_id = Order.next_part(the_order_string).to_i # puts("\t\tthe_unit_id: #{the_unit_id}") the_num_of_orders = Order.next_part(the_order_string).to_i # puts("\t\tthe_num_of_orders: #{the_num_of_orders}") unit = Unit.unit_alive the_unit_id, gs for order_index in 1..the_num_of_orders do the_order_type = Order.next_part(the_order_string) # puts("\t\tthe_order_type: #{the_order_type}") the_from_hex_index = Order.next_part(the_order_string).to_i # puts("\t\tthe_from_hex_index: #{the_from_hex_index}") the_dest_hex_index = Order.next_part(the_order_string).to_i # puts("\t\tthe_dest_hex_index: #{the_dest_hex_index}") if (unit) && (unit.user_id == the_user_id) order = Order.create :order_type => the_order_type, :turn => gs.current_turn_number, :from_hex_index => the_from_hex_index, :dest_hex_index => the_dest_hex_index, :has_been_executed => false unit.orders << order order.unit = unit order.save unit.save # puts(" ** Unit Order Created ** ") end end end def Order.parse_area_element_order_string gs, the_user_id, the_order_string the_area_element_id = Order.next_part(the_order_string).to_i # puts("\t\tthe_area_element_id #{the_area_element_id}") the_num_of_orders =Order.next_part(the_order_string).to_i # puts("\t\tthe_num_of_orders: #{the_num_of_orders}") area_element = gs.area_elements.find :first, :conditions => ["id = ?",the_area_element_id] for order_index in 1..the_num_of_orders do the_order_type = Order.next_part(the_order_string) # puts("\t\tthe_order_type: #{the_order_type}") the_action = Order.next_part(the_order_string) # puts("\t\tthe_action: #{the_action}") if (area_element) && (area_element.user_id == the_user_id) order = Order.create :order_type => the_order_type, :turn => gs.current_turn_number, :action => the_action, :has_been_executed => false area_element.orders << order order.area_element = area_element order.save area_element.save # puts(" ** Area Element Order Created ** ") end end end def heal # print "*** Heal Unit ***\n" self.hist_succeded = true self.hist_from_hex_index = self.from_hex_index self.hist_my_start_healt = self.unit.healt area = self.unit.game_session.region.areas.find :first, :conditions => ["position_index = ?",self.unit.location_hex_index] if self.unit.healt < 9 healt = 0 if self.unit.unit_type.name == "berserker" healt = area.terrain.healing_modifier + Integer((8 - (self.unit.healt + 1)) / 2) elsif self.unit.is_unit_ship? healt = 1 else healt = area.terrain.healing_modifier end if self.unit.healt == 8 && healt > 1 healt = 1 end self.unit.healt += healt self.hist_my_looses = healt end self.has_been_executed = true self.save self.unit.save return true end private def do_move self.hist_from_hex_index = self.unit.location_hex_index self.hist_succeded = true self.unit.location_hex_index = self.dest_hex_index self.unit.save self.has_been_executed = true self.save end def do_move_embak unit_to_embak_on do_move self.action = "embak" self.unit.location_hex_index = -1 unit_to_embak_on.units_in_cargo << self.unit unit_to_embak_on.save self.unit.save self.save end def do_move_disembak do_move self.hist_from_hex_index = self.unit.in_cargo_of.location_hex_index self.unit.in_cargo_of.units_in_cargo.delete(self.unit) self.unit.in_cargo_of.save self.unit.save self.save end public def is_from_hex_ok if self.unit.in_cargo_of return ((self.unit.location_hex_index == -1) && (self.unit.in_cargo_of.location_hex_index == self.from_hex_index)) else return (self.unit.location_hex_index == self.from_hex_index) end end def move if ((self.unit.healt > 0) && (self.is_from_hex_ok)) user = self.unit.user current_game_session = self.unit.game_session area = current_game_session.region.areas.find :first, :conditions => ["position_index = ?",self.dest_hex_index] area_elements_in_area = current_game_session.area_elements.find :all, :conditions => ["location_hex_index = ?",self.dest_hex_index] if area.is_any_units_in_area current_game_session unit_with_cargo_space = area.get_unit_with_cargo_space_in_area current_game_session if unit_with_cargo_space && self.unit.can_embak? && unit_with_cargo_space.room_left_in_cargo? do_move_embak unit_with_cargo_space return true end return false elsif (area_elements_in_area) && (area_elements_in_area.length > 0) area_elements_in_area.each do |ae| if ((ae.area_element_type.name == "city") || (ae.area_element_type.name == "harbor")) && (ae.user != user) && (ae.user != nil) self.hist_from_hex_index = self.dest_hex_index self.save return false elsif ((ae.area_element_type.name == "city") || (ae.area_element_type.name == "harbor")) && (ae.user == nil) self.hist_area_element_user_id = ae.user ae.conqured(user) do_move return true else do_move return true end end elsif (self.unit.in_cargo_of) do_move_disembak return true; else do_move return true; end end self.hist_from_hex_index = self.dest_hex_index self.save return false; end def update_unit_experience the_unit rand_value = 1 + rand(2**(2 + the_unit.experience)); if (rand_value == 1) the_unit.experience +=1 end end def kill_units_in_cargo the_unit, gs if the_unit.units_in_cargo the_unit.units_in_cargo.each do |a_unit_in_cargo| a_unit_in_cargo.healt = 0 a_unit_in_cargo.died_in_turn = gs.current_turn_number a_unit_in_cargo.save end end end def attack_unit gs, def_unit combat_system = CombatSystemVikiwar.new logger print "*** Attack Unit ***\n" print "att_unit: #{self.unit.id}, #{}(str)\n" print "def_unit: #{def_unit.id}\n" att_unit = self.unit self.hist_succeded = true self.hist_from_hex_index = self.dest_hex_index self.hist_other_unit_id = def_unit.id self.hist_my_start_healt = att_unit.healt self.hist_other_unit_start_healt = def_unit.healt combat_system.combat_close att_unit, def_unit, gs.current_turn_number self.hist_my_looses = self.hist_my_start_healt - att_unit.healt self.hist_other_unit_looses = self.hist_other_unit_start_healt - def_unit.healt if def_unit.do_have_heal_order def_unit.orders[0].hist_succeded = false def_unit.orders[0].has_been_executed = true def_unit.orders[0].save end if (def_unit.healt == 0) def_unit.died_in_turn = gs.current_turn_number kill_units_in_cargo(def_unit, gs) area_element_in_hex = AreaElement.get_area_element_at_index self.dest_hex_index, gs if area_element_in_hex self.hist_area_element_user_id = area_element_in_hex.user area_element_in_hex.user = nil; area_element_in_hex.orders.each do |o| o.has_been_executed = true; o.save end area_element_in_hex.save self.hist_other_area_element_id = area_element_in_hex.id end end if (att_unit.healt == 0) att_unit.died_in_turn = gs.current_turn_number kill_units_in_cargo(att_unit, gs) end self.has_been_executed = true self.save update_unit_experience def_unit update_unit_experience att_unit att_unit.save def_unit.save return true end def attack_empty_area_element area_element_in_hex self.hist_area_element_user_id = area_element_in_hex.user area_element_in_hex.user = nil; area_element_in_hex.orders.each do |o| o.has_been_executed = true; o.save end area_element_in_hex.save self.hist_succeded = true self.hist_from_hex_index = self.dest_hex_index self.hist_other_area_element_id = area_element_in_hex.id self.hist_my_start_healt = self.unit.healt self.has_been_executed = true self.save return true end def attack # print "*** Attack ***\n" gs = self.unit.game_session def_unit = gs.units.find :first, :conditions => ["location_hex_index = ? and healt > '0' ", self.dest_hex_index] if ((def_unit) && (self.unit.location_hex_index == self.from_hex_index)) return attack_unit(gs, def_unit) else area_element_in_hex = AreaElement.get_area_element_at_index self.dest_hex_index, gs if area_element_in_hex && area_element_in_hex.user != nil && area_element_in_hex.user != self.unit.user && self.unit.location_hex_index == self.from_hex_index return attack_empty_area_element(area_element_in_hex) else return false end end end def raid the_user = self.unit.user gs = self.unit.game_session ae_in_hex = AreaElement.get_area_element_at_index(self.dest_hex_index, gs) if !ae_in_hex return false end ae_owner_gsus = gs.game_session_user_statuses.find :first, :conditions => ["user_id = ?",ae_in_hex.user.id] current_gsus = gs.game_session_user_statuses.find :first, :conditions => ["user_id = ?",the_user.id] if !ae_owner_gsus || !current_gsus return false end if ae_owner_gsus.resources >= 20 self.hist_my_looses = self.hist_other_unit_looses = 20 ae_owner_gsus.resources -= 20 current_gsus.resources += 20 else self.hist_my_looses = self.hist_other_unit_looses = ae_owner_gsus.resources current_gsus.resources += ae_owner_gsus.resources ae_owner_gsus.resources = 0 end current_gsus.save ae_owner_gsus.save self.hist_succeded = true self.has_been_executed = true self.save return true end def upgrad gs = self.unit.game_session area_element_in_hex = AreaElement.get_area_element_at_index self.dest_hex_index, gs if area_element_in_hex && area_element_in_hex.user != nil && area_element_in_hex.user == self.unit.user && self.unit.location_hex_index == self.from_hex_index if area_element_in_hex.upgrad self.unit_id = self.unit.id self.has_been_executed = true self.hist_succeded = true self.hist_from_hex_index = area_element_in_hex.location_hex_index self.hist_user_id = self.unit.user.id self.hist_unit_type_id = self.unit.unit_type.id self.save return true end end return false end def build current_game_session = self.area_element.game_session user = self.area_element.user gsus = current_game_session.game_session_user_statuses.find :first, :conditions => ["user_id = ?",user.id] area = current_game_session.region.areas.find :first, :conditions => ["position_index = ?",self.area_element.location_hex_index] if area.is_any_units_in_area current_game_session return false else unit_type = UnitType.find :first, :conditions => ["name = ?",self.action] if (unit_type) && (unit_type.level <= current_game_session.level) && (unit_type.resource_cost <= gsus.resources ) gsus.resources -= unit_type.resource_cost gsus.save the_unit = Unit.create( :unit_type => unit_type, :healt => 9, :experience => 1, :location_hex_index => self.area_element.location_hex_index, :game_session => current_game_session, :user => user) self.unit_id = the_unit.id self.has_been_executed = true self.hist_succeded = true self.hist_from_hex_index = self.area_element.location_hex_index self.hist_user_id = user.id self.hist_unit_type_id = unit_type.id self.save return true else return false end end end def execute if (self.unit == nil) && (self.area_element == nil) return false end if (self.unit) self.unit.reload else self.area_element.reload end if ( ((self.unit) && (self.unit.healt > 0)) || (self.area_element) ) if (self.has_been_executed == false) if ((self.unit) && (self.order_type == "move")) return move elsif ((self.unit) && (self.order_type == "attack")) return attack elsif ((self.unit) && (self.order_type == "raid")) return raid elsif ((self.unit) && (self.order_type == "heal")) return heal elsif ((self.unit) && (self.order_type == "upgrad")) return upgrad elsif ((self.area_element) && (self.order_type == "build")) return build end else return false end else return false end end end
true
bbd899e3ce820e01f4ca166028105191dab066be
Ruby
jjwyse/sniktau
/app/services/user_mountains/create_service.rb
UTF-8
940
2.84375
3
[]
no_license
module UserMountains class CreateService def self.execute!(activity:) # Find any Mountains close to the given Activity mountains = activity .locations .map { |location| mountains_within(lat: location.lat, lng: location.lng) } .compact .flatten .uniq # Create the UserMountains mountains.each do |mountain| UserMountain.create!(user: activity.user, activity: activity, mountain: mountain) end end # @!attribute lat - radians # @!attribute lng - radians def self.mountains_within(lat:, lng:, meters: 100) sql = <<-SQL select m.id from mountains m where (acos(sin(#{lat}) * sin(m.lat) + cos(#{lat}) * cos(m.lat) * cos(#{lng} - m.lng)) * 6371000) < #{meters}; SQL entries = ActiveRecord::Base.connection.execute(sql) Mountain.where(id: entries.map { |entry| entry['id']} ).distinct end end end
true
c906a81fac2cd9c63cd596d3b5fe02c52097e97c
Ruby
sarahvoshall/rb101
/easy_3/palindrome_2.rb
UTF-8
378
3.53125
4
[]
no_license
def palindrome?(string) string == string.reverse end def real_palindrome?(string) mod_string = string.downcase.delete(" ").gsub(/[[:punct:]]/, '') palindrome?(mod_string) end p real_palindrome?('madam') p real_palindrome?('Madam') p real_palindrome?("Madam, I'm Adam") p real_palindrome?('356653') p real_palindrome?('356a653') p real_palindrome?('123ab321')
true
6c66c1a0ae4599ccfb194ec8c71ba74c336319d2
Ruby
preiser/ruby-object-initialize-lab-q-000
/lib/dog.rb
UTF-8
275
3.359375
3
[]
no_license
class Dog def initialize(name,breed = "Mut") @name = name @breed = breed end def name @name end def name=(dog_name) @name=(dog_name) end def breed @breed end def breed=(breed_name) @breed=(breed_name) end end
true
e7379a595184d71d651539f59a463840b0f19b3b
Ruby
yazan9/joinshift
/app/controllers/perspectives_controller.rb
UTF-8
1,536
2.546875
3
[]
no_license
require 'DimensionsCalculator' class PerspectivesController < ApplicationController def new @Questions = Question.all @Perspective = Perspective.new end def all @Perspectives = Perspective.all end def create #@Perspective = Perspective.new(perspective_params) @answers = ""; for i in 1..10 @answers << params["question#{i}"] if !params["question#{i}"].nil? end @Perspective = Perspective.new(email: params[:user_email], answers: @answers) if(@answers.length < 10 || params[:user_email].strip == "") flash[:alert] = "Please answer all of the questions below" redirect_to :action => :new and return end begin if @Perspective.save redirect_to :action => 'results', perspective: @answers else flash[:alert] = "Hmm, an unknown error occured, let us work on it and try again in a bit" render :action => 'new' end rescue ActiveRecord::RecordNotUnique flash[:alert] = "The email address you entered has already been taken" redirect_to :action => :new end end def results @Perspective = params[:perspective] @DimensionsCalculator = DimensionsCalculator.new @result = @DimensionsCalculator.calculate(@Perspective) end def perspective_params params.require(:perspectives).permit(:email, :answers) end end
true
fc3c25003c22326c5a30f3f6904ffb518ffe127e
Ruby
xTriad/whiteboard
/app/models/user.rb
UTF-8
3,729
2.609375
3
[]
no_license
class User < ActiveRecord::Base rolify # Setup selected Devise modules devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable # Setup accessible (or protected) attributes for your model attr_accessible :role_ids, :as => :admin attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :university_id has_many :sections_users_roles has_many :sections, :through => :sections_users_roles has_many :roles, :through => :sections_users_roles has_many :attendances belongs_to :university # Caches query results in the has_role? method # Roles_Cache[user_id] = [role_id, role_id ...] # TODO: Use INSTANCE variables to handle all permissions! # Give each user a @role and even @can_do_something # Then we could do current_user.can_do_this or current_user.role can ... # This will allow us to query the database to see their university, section etc. Roles_Cache = {} # Finds the specific section the user is enrolled in by their # user_id and the given course_id def self.find_user_section_by_course_id(user_id, course_id) user = find(:first, :conditions => ['user_id = ?', user_id]) user.sections.find(:first, :conditions => ['course_id = ?', course_id]) end # Returns all sections the professor is currently teaching def self.find_professor_sections(user_id) user = find(:first, :conditions => ['user_id = ?', user_id]) user.sections.find(:all, :conditions => ['role_id = ?', Constants::Role::Professor]) end # Returns all sections the professor is currently teaching in a given course def self.find_professor_sections_in_course(user_id, course_id) user = find(:first, :conditions => ['user_id = ?', user_id]) user.sections.find(:all, :conditions => ['role_id = ? AND course_id = ?', Constants::Role::Professor, course_id]) end # Returns all sections the student is currently enrolled in def self.find_student_sections(user_id) user = find(:first, :conditions => ['user_id = ?', user_id]) user.sections.find(:all, :conditions => ['role_id = ?', Constants::Role::Student]) end def self.find_name_by_user_id(user_id) user = find(:first, :conditions => ['user_id = ?', user_id]) if !user.nil? return user.name else return nil end end def self.find_id_by_email(email) user = find(:first, :conditions => ['email = ?', email]) if !user.nil? return user.id else return nil end end # This method gets called many times on every page view so # it needs to cache as much as possible. def has_role?(role_id) cur_user_id = self.user_id has_role = false # puts "" # Check if we already have the query cached if Roles_Cache.has_key?(cur_user_id) # puts "\t1. Checking cache for role_id = #{role_id} in #{Roles_Cache[cur_user_id].to_s}" if Roles_Cache[cur_user_id].include?(role_id) has_role = true # puts "\t 2. Sucessfully retrieved the role from cache" end else the_users_roles = [] self.roles.uniq.each do |role| the_users_roles << role.role_id end # puts "\t1. Queried database for role_id = #{role_id} and got #{the_users_roles.to_s}" # Store the role array in memory Roles_Cache[cur_user_id] = the_users_roles if the_users_roles.include?(role_id) # puts "\t 2. Successfully retrieved the role from the database" has_role = true end end return has_role end def role_name name = "" Role.all.each do |role| if !role.users.where(:name => self.name).empty? name = role.name end end return name end end
true
fc3a2fe4cc2c05f3d36f76c4d685b7681f8d590b
Ruby
brockboland/daily_file_parse
/parse.rb
UTF-8
1,494
3.375
3
[]
no_license
require 'date' # Get the file (first argument to the script) path = ARGV[0] if (!path || path.empty?) puts "Usage: ruby parse.rb <path to file>" exit # Make sure the file exists elsif (!File.exists?(path)) puts "File does not exist." exit end # Initialize variables date = '' date_logs = {} text_lines = [] # Loop over the lines in the Daily text file File.open(path).each do |line| # Check if the line is a date line if (line =~ /([0-9]{4}\.[0-9]{2}\.[0-9]{2})(.*)/) # Starting a new day: push previous day notes onto the hash of days if (!text_lines.empty?) # Push array of log lines into the hash date_logs[date] = text_lines end # Save the date for the next set of lines. The format is yyyy.mm.dd date = $1 # Reset the array of lines for this day text_lines = [] else # NOT a date line # Escape any quotes so that newlines can be printed in an echo "" later clean_line = line.gsub(/"/, '\"') # Trim whitespace and push it on the running array of lines for today text_lines.push(clean_line.strip) end end # Run the results through the dayone command date_logs.each do |date, lines| # Format the date for Day One. Assume it was written at 10pm d = DateTime.parse(date + ' 10:00 pm'); print_date = d.strftime("%m/%d/%Y %l:%M%p") # dayone formatted # Join the lines for the day input = lines.join("\n").strip; # Execute the command %x{echo "#{input}"|/usr/local/bin/dayone -d="#{date}" new} end
true
d19bb3dc39298ec804aa60b53950ed5808bbb47f
Ruby
hkeefer18/RB101-and-Small-Problems
/small_problems/medium_1/4.rb
UTF-8
754
3.859375
4
[]
no_license
=begin Create an array (1..n).to_a array product ['on'] Create hash from array counter = 2 Iterate through hash. If hash key is a multiple of counter, and value is on, set value to off or if off set value to on. If statement with ternary operator. Counter += 1 Break if counter > n Convert hash back to array Select elements in array with element 1 == 'on' Map over array and take element 0 only =end def toggle(n) hash = ((1..n).to_a).product(['off']).to_h counter = 1 loop do hash.each do |switch, on_off| if switch % counter == 0 on_off == 'on' ? hash[switch] = 'off' : hash[switch] = 'on' end end counter += 1 break if counter > n end hash.select { |_switch, on_off| on_off == 'on' }.keys end
true
d81308d4bd6bada57d7f513c2b72f07c3071f31f
Ruby
bmulvihill/apriori
/lib/apriori/list.rb
UTF-8
659
3.046875
3
[ "MIT" ]
permissive
module Apriori class List attr_reader :sets def self.create_subsets(set) (1).upto(set.size - 1).flat_map { |n| set.combination(n).to_a } end def initialize(sets) @sets = sets end def size return 0 if sets.empty? sets.first.size end def make_candidates if (size + 1) <= 2 sets.flatten.combination(size + 1).to_a else self_join(prune) end end private def self_join(set) set.map{ |a1| set.select{ |a2| a1[0] == a2[0] }.flatten.uniq }.uniq end def prune sets.reject{ |a1| sets.count{ |a2| a1[0] == a2[0] } == 1 } end end end
true
298665f863248ef454531a5efea2f99b8be57535
Ruby
AlejandroFrias/Aerospace-Services
/hmcBuildingService/db/seeds.rb
UTF-8
1,025
2.859375
3
[]
no_license
# Seeds the database from hand inputted data def classes?(b) class_rooms = "SHAN, LAC, PA, ON, GA, BK, KE, JA, SP" !class_rooms[b.code].blank? end def dining_hall?(b) dining_halls = "HOCH" !dining_halls[b.code].blank? end def food?(b) food = "HOCH, SHAN" !food[b.code].blank? end def music?(b) music = "WEST" !music[b.code].blank? end def dorm?(b) !b.name["Dorm"].blank? end building_params = Plist::parse_xml( "db/buildingData.plist" ) building = Tag.create(name: "building") classes = Tag.create(name: "classes") dining_hall = Tag.create(name: "dininghall") food = Tag.create(name: "food") dorm = Tag.create(name: "dorm") music = Tag.create(name: "music") building_params.each do |param| b = Building.create(param) b.tags.concat(building) if classes?(b) b.tags.concat(classes) end if dining_hall?(b) b.tags.concat(dining_hall) end if food?(b) b.tags.concat(food) end if dorm?(b) b.tags.concat(dorm) end if music?(b) b.tags.concat(music) end end
true
ebe8750b6c747ad9aa07fe456d212c8c185ac0e8
Ruby
bureaucratix/oo-counting-sentences-seattle-web-career-042219
/lib/count_sentences.rb
UTF-8
330
3.5
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class String def sentence? self[-1] == '.' end def question? self[-1] == '?' end def exclamation? self[-1] == '!' end def count_sentences punctuation = ['.', '?', '!'] split_string = split(Regexp.union(punctuation)) split_string.delete('') split_string.length end end
true
de31ad89933e84cacc0d89f0bc71c4006f3f542b
Ruby
alicia0408/desafio_2_arreglos
/desafio2.rb
UTF-8
373
3.546875
4
[]
no_license
nombres = ['Violeta', 'Andino', 'Clemente','Javiera', 'Paula', 'Pía', 'Ray'] name1=nombres.select {|x|x.length>5} print name1 puts name2= nombres.map {|x|x.downcase} print name2 puts name3=nombres.select {|x|x if x[0]=="P"} print name3 puts name4=nombres.count {|x|x if x[0]=="A" || x[0]=="B"|| x[0]=="C"} print name4 puts name5=nombres.map {|x|x.length} print name5 puts
true
fa8970dacb3b04f5b322d9c89c82c9378e7d84cb
Ruby
jamespmernin/Ruby-Cars
/cars.rb
UTF-8
1,188
3.84375
4
[]
no_license
class Car attr_accessor :make, :model, :year, :color, :miles def initialize(make, model, year, color) @make = make @model = model @year = year @color = color @miles = 0 end def seen_another_year @miles += 15000 end def details details_string = "This #{year} #{make} #{model} has #{miles} miles on it" if @miles > 50000 details_string += ", and that #{color} paint is really fading" end return details_string end def change_color(color) @color = color ahh_fresh_paint end def ahh_fresh_paint puts "The new #{color} color was a good choice" end end class Truck < Car attr_accessor :make, :model, :year, :color, :miles, :wheels def initialize(make, model, year, color, wheels) super(make, model, year, color) @wheels = wheels end def details return "This #{color} truck has #{wheels} wheels." end end def main my_car = Car.new('Toyota', 'Prius', 2020, 'silver') puts my_car.details for i in 1..4 do my_car.seen_another_year end puts my_car.details my_car.change_color('red') my_truck = Truck.new('Honda', 'Odyssey', 2020, 'black', 18) puts my_truck.details end main
true
2b898f8fa2cc97cb7db6e5ec333413bea87a8adf
Ruby
imkaruna/flatiron-bnb-methods-v-000
/app/models/city.rb
UTF-8
1,595
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class City < ActiveRecord::Base has_many :neighborhoods has_many :listings, :through => :neighborhoods has_many :reservations, :through => :listings extend Statistics::ClassMethods def city_openings(date1, date2) open_listings = self.listings.select do |listing| !listing.reservations.any?{|reservation| (reservation.checkin..reservation.checkout).cover?(Date.parse(date1)..Date.parse(date2))} end end # # def self.highest_ratio_res_to_listings # all_reservations_by_listing_id = Reservation.group(:listing_id).count # # #checks the details of listings for the reservations # city_count={} # all_reservations_by_listing_id.each {|key, value| # the_city = City.find(Neighborhood.find(Listing.find(key).neighborhood_id).city_id) # city_count.has_key?(the_city) ? city_count[the_city]=city_count[the_city]+(value/the_city.listings.count.to_f) : city_count[the_city]=(value/the_city.listings.count.to_f) # } # max_listings_city = city_count.select {|k,v| v == city_count.values.max } # gets the max valued hash-key pair # max_listings_city.keys[0] # since the city is stored as key return the key for the max value # end # # def self.most_res # list = Reservation.group(:listing_id).count # gets the count of the reservations by counting how many reservations belong to each listing_id) and returns a hash # max_res = list.select {|k,v| v == list.values.max } # listing = Listing.find(max_res.keys[0]) # #binding.pry # City.find(Neighborhood.find(listing.neighborhood_id).city_id) # end end
true
2b7bd199bfa84c5e4f373b92e24832f64039c995
Ruby
401ChemistryGenealogy/ChemistryGenealogy
/backend/app/models/supervision.rb
UTF-8
16,410
2.65625
3
[]
no_license
# Model for handling supervisions class Supervision < ActiveRecord::Base belongs_to :degree, :class_name => 'Degree' belongs_to :person, :class_name => 'Person' belongs_to :supervisor, :class_name => 'Person' # Tracks changes has_paper_trail on: [:update], :ignore => [:created_at, :updated_at, :approved, :id]#ignores pointless attributes, only on update # Creates a new supervision. # # @param degree_year [Number] year the degree was awarded # @param degree_type [String] type of degree awarded # @param institution_name [String] institution the degree was awarded # @param person_name [String] name of the person # @param supervisor_name [String] name of the supervisor # @return [Hash{String => String, Number}] created supervision def Supervision.new_supervision(degree_year, degree_type, institution_name, person_name, supervisor_name) degree_id = FindId.degree(degree_year, degree_type, institution_name) person_id = FindId.person(person_name) supervisor_id = FindId.mentor_supervisor(supervisor_name, institution_name) supervision = Supervision.create_with(approved: false) .find_or_create_by(degree_id: degree_id, person_id: person_id, supervisor_id: supervisor_id) return supervision end # Updates the supervisions and degrees that the person has # @note Since the supervisions themselves cannot be edited, this will only update the supervisions connected to a person # # @param id [Number] id of the person # @param name [String] name of the person # @param supervision_array_received [Array<Hash{String => String, Number}>] array of supervisions that the person has def Supervision.update_supervision(id, name, supervision_array_received) # Creates an array of supervision ids that are connected to the person in # the database supervision_array = Array.new supervision_find = Supervision.where(:person_id => id) supervision_find.each do |single| supervision_array.push(single.id) end # Check that supervision_array is not nil unless supervision_array.nil? # Check that the supervision_array_received is not nil unless supervision_array_received.nil? # Create a temporary array to iterate through temp_array_received = Array.new supervision_array_received.each do |supervision| temp_array_received.push(supervision) end # For each supervision in the supervision_array_received, # see if it already exists in the database # If so, then the supervision is present and can be removed from the supervision_array # as well as the supervision_array_received temp_array_received.each do |supervision| if supervision.is_a?(Array) supervision = supervision[0] end if supervision.has_key?("id") supervision_array.delete(supervision["id"]) supervision_array_received.delete(supervision) end end # The results left are ones that were either deleted or new # Check if supervision_array is not empty unless supervision_array.empty? # Check if the supervision_array_received is not empty unless supervision_array_received.empty? # Create a temporary array to iterate through temp_array = Array.new supervision_array.each do |supervision_id| temp_array.push(supervision_id) end # For each of the ids left in the array, update them with a new supervision information temp_array.each do |supervision_id| unless supervision_array_received.empty? new_supervision = supervision_array_received[0] if new_supervision.is_a?(Array) new_supervision = new_supervision[0] end supervisor_id = FindId.person(new_supervision["supervisor"]) degree_id = FindId.degree(new_supervision["year"], new_supervision["type"], new_supervision["institution"]) Supervision.update(supervision_id, supervisor_id: supervisor_id) Supervision.update(supervision_id, degree_id: degree_id) supervision_array.delete(supervision_id) supervision_array_received.delete(new_supervision) end end # If there are any supervisions left in the supervision_array, delete them unless supervision_array.empty? supervision_array.each do |supervision_id| Supervision.delete(supervision_id) end end # If there are any supervisions left in the supervision_array_received, create them unless supervision_array_received.empty? supervision_array_received.each do |supervision| if supervision.is_a?(Array) supervision = supervision[0] end Degree.new_degree(supervision["year"], supervision["type"], supervision["institution"]) Supervision.new_supervision(supervision["year"], supervision["type"], supervision["institution"], name, supervision["supervisor"]) end end # If the supervision_array_received is empty, # then the rest of the supervisions connected to the person are removed from the database else supervision_array.each do |supervision_id| Supervision.delete(supervision_id) end end # If supervision_array is empty, add remaining supervisions to the database else unless supervision_array_received.empty? supervision_array_received.each do |supervision| if supervision.is_a?(Array) supervision = supervision[0] end Degree.new_degree(supervision["year"], supervision["type"], supervision["institution"]) Supervision.new_supervision(supervision["year"], supervision["type"], supervision["institution"], name, supervision["supervisor"]) end end end # If the supervision_array_received is nil (person has no degrees/supervisions) # Then delete all supervisions in the supervision_array else supervision_array.each do |supervision_id| Supervision.delete(supervision_id) end end # If there are no supervisions connected to the person, create new # supervisions and degrees for the person as long as supervision_array_received # is not nil either else unless supervision_array_received.nil? supervision_array_received.each do |supervision| if supervision.is_a?(Array) supervision = supervision[0] end Degree.new_degree(supervision["year"], supervision["type"], supervision["institution"]) Supervision.new_supervision(supervision["year"], supervision["type"], supervision["institution"], name, supervision["supervisor"]) end end end end # Updates the supervisions and degrees that the person has supervised # @note @note This could probably be combined with Supervision.update_supervision # # @param id [Number] id of the person # @param name [String] name of the person # @param supervision_array_received [Array<Hash{String => String, Number}>] array of supervisions that the person has supervised def Supervision.update_superdeg(id, name, supervision_array_received) # Creates an array of supervision ids that are connected to the person in # the database supervision_array = Array.new supervision_find = Supervision.where(:supervisor_id => id) supervision_find.each do |single| supervision_array.push(single.id) end # Check that supervision_array is not nil unless supervision_array.nil? # Check that the supervision_array_received is not nil unless supervision_array_received.nil? # Create a temporary array to iterate through temp_array_received = Array.new supervision_array_received.each do |supervision| temp_array_received.push(supervision) end # For each supervision in the supervision_array_received, # see if it already exists in the database # If so, then the supervision is present and can be removed from the supervision_array # as well as the supervision_array_received temp_array_received.each do |supervision| if supervision.is_a?(Array) supervision = supervision[0] end if supervision.has_key?("id") supervision_array.delete(supervision["id"]) supervision_array_received.delete(supervision) end end # The results left are ones that were either deleted or new # Check if supervision_array is not empty unless supervision_array.empty? # Check if the supervision_array_received is not empty unless supervision_array_received.empty? # Create a temporary array to iterate through temp_array = Array.new supervision_array.each do |supervision_id| temp_array.push(supervision_id) end # For each of the ids left in the array, update them with a new supervision information temp_array.each do |supervision_id| unless supervision_array_received.empty? new_supervision = supervision_array_received[0] if new_supervision.is_a?(Array) new_supervision = new_supervision[0] end supervised_id = FindId.person(new_supervision["superDegNameOfPerson"]) degree_id = FindId.degree(new_supervision["superDegYear"], new_supervision["superDegDegType"], new_supervision["superDegInst"]) Supervision.update(supervision_id, person_id: supervised_id) Supervision.update(supervision_id, degree_id: degree_id) supervision_array.delete(supervision_id) supervision_array_received.delete(new_supervision) end end # If there are any supervisions left in the supervision_array, delete them unless supervision_array.empty? supervision_array.each do |supervision_id| Supervision.delete(supervision_id) end end # If there are any supervisions left in the supervision_array_received, create them unless supervision_array_received.empty? supervision_array_received.each do |supervision| if supervision.is_a?(Array) supervision = supervision[0] end Person.new_person(supervision["superDegNameOfPerson"], supervision["superDegCurrPosition"], supervision["superDegCurrInst"]) Degree.new_degree(supervision["superDegYear"], supervision["superDegDegType"], supervision["superDegInst"]) Supervision.new_supervision(supervision["superDegYear"], supervision["superDegDegType"], supervision["superDegInst"], supervision["superDegNameOfPerson"], name) end end # If the supervision_array_received is empty, # then the rest of the supervisions connected to the person are removed from the database else supervision_array.each do |supervision_id| Supervision.delete(supervision_id) end end # If it is empty, add remaining supervisions to the database else unless supervision_array_received.empty? supervision_array_received.each do |supervision| if supervision.is_a?(Array) supervision = supervision[0] end Person.new_person(supervision["superDegNameOfPerson"], supervision["superDegCurrPosition"], supervision["superDegCurrInst"]) Degree.new_degree(supervision["superDegYear"], supervision["superDegDegType"], supervision["superDegInst"]) Supervision.new_supervision(supervision["superDegYear"], supervision["superDegDegType"], supervision["superDegInst"], supervision["superDegNameOfPerson"], name) end end end # If the supervision_array_received is nil (person has no degrees/supervisions) # Then delete all supervisions in the supervision_array else supervision_array.each do |supervision_id| Supervision.delete(supervision_id) end end # If there are no supervisions connected to the person, create new # supervisions and degrees for the person as long as supervision_array_received # is not nil either else unless supervision_array_received.nil? supervision_array_received.each do |supervision| if supervision.is_a?(Array) supervision = supervision[0] end Person.new_person(supervision["superDegNameOfPerson"], supervision["superDegCurrPosition"], supervision["superDegCurrInst"]) Degree.new_degree(supervision["superDegYear"], supervision["superDegDegType"], supervision["superDegInst"]) Supervision.new_supervision(supervision["superDegYear"], supervision["superDegDegType"], supervision["superDegInst"], supervision["superDegNameOfPerson"], name) end end end end # Makes a serialized supervision with degree information to be sent to the frontend in a JSON format. # @note Could probably take ids off if the frontend isn't using it # # @param supervision [Hash{String => String, Number}] a person's supervision # @return [Hash{String => String, Number}] serialized supervision def serializer_for_supervision(supervision) result = Api::SupervisionSerializer.new(self).serializable_hash degree = Degree.find_by(id: degree_id) result[:year] = degree.year result[:supervisor] = Person.find_by(id: supervision.supervisor_id).name result[:institution] = Institution.find_by(id: degree.institution_id).name result[:type] = degree.degree_type result[:supervised] = Person.find_by(id: supervision.person_id).name result[:degree_id] = degree.id result[:degree_approved] = degree.approved result = result.except(:id, :approved) result[:supervision_id] = supervision.id result[:supervision_approved] = supervision.approved return result end # Handles rendering a supervision in a JSON format. def as_json(options={}) super(:except => [:created_at, :updated_at]) end end
true
6052698ad1c559a92cb2f7677fe16f8dd8f13ff6
Ruby
swistak35/dotfiles
/bin/grafana_send_weight
UTF-8
783
2.828125
3
[]
no_license
#!/usr/bin/env ruby require 'influxdb' class SendWeight InfluxConfigFile = File.join(ENV['HOME'], ".grafana_influxdb") DatabaseName = "carbon" TimeSeries = "weight" def initialize raise InfluxConfigDoesntExist unless File.exists?(InfluxConfigFile) initialize_influxdb end def initialize_influxdb influx_config = File.readlines(InfluxConfigFile).map(&:chomp) @influxdb = InfluxDB::Client.new "carbon", { username: influx_config[0], password: influx_config[1], host: influx_config[2], } end def run(argv) weight = argv[0].to_f raise "WrongWeight" unless (40..120).include?(weight) puts "Weight: #{weight}" @influxdb.write_point(TimeSeries, { weight: weight }) end end SendWeight.new.run(ARGV)
true
82fd965b2d2eb3a0a3b948a234754d2424f947be
Ruby
tae10954/square_array-ruby-apply-000
/square_array.rb
UTF-8
162
3.03125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def square_array(array) # your code here arr = [] array.each do |x| arr.push(x ** 2) end arr #ADVANCED #array.collect{|element| element ** 2} end
true
7125afd9e71ccc1d34fb7f4d17a997d1c7da11a3
Ruby
yamanoie/cherry
/yield.rb
UTF-8
2,755
4.4375
4
[]
no_license
def greeting puts "おはよう" yield yield puts "こんばんは" end greeting do puts "こんにちは" end def greeting puts "おはよう" if block_given? yield end puts "こんばんは" end greeting greeting do puts "こんばんは" end def greeting puts "おはよう" text = yield "hello" puts text puts "こんばんは" end greeting do |text| text * 2 end def greeting puts "おはよう" text = yield "おはよう" puts text puts "こんばんは" end greeting do |text,other| text * 2 + other.inspect end def greeting(&block) puts "おはよう" text = block.call("こんにちは") puts text puts "こんばんは" end greeting do |text| text * 2 end def greeting(&block) puts "おはよう" unless block.nil? text = block.call("こんにちは") puts text end puts "こんばんは" end greeting greeting do |text| text * 2 end def greeting_ja(&block) texts = ["おはよう","こんにちは","こんばんは"] greeting_common(texts,&block) end def greeting_en(&block) texts = ["good morning","hello","good evening"] greeting_common(texts,&block) end def greeting_common(texts,&block) puts texts[0] puts block.call(texts[1]) puts texts[2] end greeting_ja do |text| text * 2 end greeting_en do |text| text.upcase end def greeting(&block) puts "おはよう" text = if block.arity == 1 yield "こんにちは" elsif block.arity == 2 yield "こんに","ちは" end puts text puts "こんばんは" end greeting do |text| text * 2 end greeting do |text_1,text_2| text_1 *2 + text_2 *2 end # Proc hello_proc = Proc.new do "Hello" end hello_proc = Proc.new {"Hello"} puts hello_proc.call add_proc = Proc.new{|a,b|a+b} add_proc.call(10.20) add_proc = Proc.new { |a = 0,b = 0| a + b } add_proc.call add_proc.call(10) add_proc.call(10,20) add_proc.proc {|a,b| a + b } def greeting(&block) puts block.class puts "おはよう" text = block.call("こんにちは") puts text puts "こんばんは" end greeting do |text| text * 2 end repeat_proc = Proc.new{|text| text * 2} greeting(&repeat_proc) def greeting(arrange_proc) puts "おはよう" text = arrange_proc("こんにちは") puts text puts "こんばんは" end repeat_proc = Proc.new{ |text| text * 2 } greeting(repeat_proc) def greeting(proc_1,proc_2,proc_3) puts proc_1.call("おはよう") puts proc_2.call("こんにちは") puts proc_3.call("こんばんは") end shuffle_proc = Proc.new { |text| text.chars.shuffle.join } repeat_proc = Proc.new { |text| text *2 } question_proc = Proc.new{ |text| "#{text}?"} greeting(shuffle_proc,repeat_proc,question_proc) add_proc = Proc { |a,b| a + b } add_proc.call(10,20) add_proc.yield(10,20) add_proc.(10,20) add_proc[10,20]
true
73331314d8bcd934a3e109b67a36b507fd8273f6
Ruby
typhaon/systems_check_2
/test2.rb
UTF-8
201
2.671875
3
[]
no_license
require 'csv' def export_csv(filename) teams = [] CSV.foreach(filename, headers: true) do |row| teams << row.to_hash end teams end teams = export_csv('./public/nfl_data.csv') puts teams
true
1344cca6a97a45f4a6be6626604f31c1f3b39489
Ruby
azheng249/flatiron-bnb-methods-v-000
/app/models/reservation.rb
UTF-8
3,077
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Reservation < ActiveRecord::Base belongs_to :listing belongs_to :guest, :class_name => "User" has_one :review # Validations validates_presence_of :checkin, :checkout # Compares host id with guest id to prevent reserving at own listing validate :not_host? def not_host? listing = Listing.find(self.listing_id) if listing.host_id == self.guest_id errors.add(:listing_id, "You cannot be a guest at your own listing.") end end # Checks to see if any current reservations overlap the given dates validate :available? def available? listing = Listing.find(self.listing_id) # Find reservations from listing that block this reservation, excluding itself if this is an edit # All reservations will block if: # Their checkout dates are after this reservation's checkin date AND # if their checkin dates are before this reservation's checkout date blocking_reservations = listing.reservations.where( "checkout > ? AND checkin < ? AND id != ?", # where statement self.checkin, self.checkout, self.id || 0) # parameters if blocking_reservations.count > 0 errors.add(:guest, "This listing is unavailable on those dates.") end end # Checks that checkout is after the check-in date. # If checkout minus checkin is less than or equal to 0, checkout is the same date or before checkin and invalid. validate :valid_reservation_period? def valid_reservation_period? if self.checkout.is_a?(Date) && self.checkin.is_a?(Date) && (self.checkout.to_date - self.checkin.to_date).to_i <= 0 errors.add(:checkout, "Checkout date needs to be after the check-in date.") end end # Search methods def duration (self.checkout.to_date - self.checkin.to_date).to_i end def total_price self.listing.price * duration end end # Diagram to finding blocking reservations with given dates: # # ______________ As demonstrated on the right, # | | where the empty rectangles # ------------ | are the reservations and # |###########| | the filled rectangles are the blocking reservations: # |###########|_____| # ------------ 1- The blocking reservation's start date is always # before the given ending date. # 2- The blocking reservation's end date is always # _______________ after the give starting date. # | | # | ------------ # | |###########| # |_______|###########| # ------------- # # _______________________ # | | # | ----------- | # | |##########| | # |_____|##########|____| # ------------ # # ___________ # | | # --------------------------- # |##########################| # |##########################| # ---------------------------- #
true
3e32349eb1a01b9a2a0a49fbb77eae9cd7e453fe
Ruby
b-artem/library
/library.rb
UTF-8
1,906
3.296875
3
[]
no_license
$LOAD_PATH << '.' require 'yaml' require 'library_utils.rb' require 'book.rb' require 'author.rb' require 'reader.rb' require 'order.rb' class Library include LibraryUtils attr_accessor :books, :authors, :readers, :orders def initialize(books = nil, authors = nil, readers = nil, orders = nil) @books = books @authors = authors @readers = readers @orders = orders end def loaded? @books && @authors && @readers end def not_loaded puts 'You should load library data using get_data(file) method before using any other methods' exit end def library_ready? return not_loaded unless loaded? return no_orders unless @orders true end def no_orders puts "There are no orders in the library yet. You may create them using generate_orders(orders_amount) method" exit end def get_data(file) begin library = YAML.load_file(file) rescue puts "Couldn't open file #{file}" return end @books = library.books @authors = library.authors @readers = library.readers @orders = library.orders end def save_data(file) puts "Saving library data to file #{file} ..." f = File.new(file, 'w') f.write(to_yaml) f.close rescue => exception puts "Couldn't save data to file. Exception: #{exception}" end def top(entity, top_amount = 1) return unless library_ready? if @orders[0].respond_to?(entity) groupped = @orders.group_by(&entity).sort_by { |_, val| -val.size } groupped.max_by(top_amount) { |_, val| val.size }.to_h.keys else puts "There is no such method #{entity} for Order instance" end end def top_books_readers(top_amount = 1) return unless library_ready? top_books = top(:book, top_amount) orders = @orders.select { |order| top_books.include? order.book } orders.map(&:reader).uniq.count end end
true
9525e08b3c190cba53acab338fe1876d26d5b9a6
Ruby
rumman07/rubyonrails
/ruby_code_sample/classes/candidate.rb
UTF-8
1,080
3.90625
4
[]
no_license
#Hash as initialize argument #Whenever you have a hash that is being passed as the very last argument to the method call you can exclude and omit the curly braces around the hash class Candidate attr_accessor :name, :occupation, :age, :hobby, :birthplace def initialize(name, details = {}) #Assigning the details variable with a defaut value of empty hash defaults = {occupation: "Banker", age: 65, hobby: "Fishing", birthplace: "Kentucky"} defaults.merge!(details) #The merge will override the value in the default hash with the values of details hash that is being passed as an argument to the merge method call @name = name @occupation = defaults[:occupation] @age = defaults[:age] @hobby = defaults[:hobby] @birthplace = defaults[:birthplace] end end #info = {occupation: "Banker", age: 65, hobby: "Fishing", birthplace: "Kentucky"} senator = Candidate.new("Mr. Smith", hoby: "Horror movies", occupation: "Popcorn Vendor") p senator.name p senator.age p senator.occupation p senator.hobby p senator.birthplace
true
03172c6688aef237fda5454c895549dd5af6a799
Ruby
rails/rails
/activerecord/test/cases/type/time_test.rb
UTF-8
1,143
2.8125
3
[ "MIT", "Ruby" ]
permissive
# frozen_string_literal: true require "cases/helper" require "models/topic" module ActiveRecord module Type class TimeTest < ActiveRecord::TestCase def test_default_year_is_correct expected_time = ::Time.utc(2000, 1, 1, 10, 30, 0) topic = Topic.new(bonus_time: { 4 => 10, 5 => 30 }) assert_equal expected_time, topic.bonus_time assert_instance_of ::Time, topic.bonus_time topic.save! assert_equal expected_time, topic.bonus_time assert_instance_of ::Time, topic.bonus_time topic.reload assert_equal expected_time, topic.bonus_time assert_instance_of ::Time, topic.bonus_time end test "serialize_cast_value is equivalent to serialize after cast" do type = Type::Time.new(precision: 1) value = type.cast("1999-12-31T12:34:56.789-10:00") assert_equal type.serialize(value), type.serialize_cast_value(value) assert_instance_of type.serialize(value).class, type.serialize_cast_value(value) assert_instance_of type.serialize(nil).class, type.serialize_cast_value(nil) end end end end
true
7377ad84b341c38bc4faa9a1da4bc235e3288c7d
Ruby
yfcai/paraphernalia
/bin/wctoday
UTF-8
302
2.546875
3
[]
no_license
#!/usr/bin/ruby # estimate how many words you wrote today if ARGV.empty? exec "git diff -M05 -C05 --word-diff=porcelain 'HEAD@{yesterday.23:59}' | grep -e '^+[^+]' | wc -w" else exec "git diff -M05 -C05 --word-diff=porcelain 'HEAD@{yesterday.23:59}' -- #{ARGV[0]} | grep -e '^+[^+]' | wc -w" end
true
d15cb2973e8717206da3ea5771f62e8b0f23e1b0
Ruby
Pawgrammers/Shakespeare-Script-Editor
/script_editor/app/controllers/create_scripts.rb
UTF-8
8,868
2.828125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'nokogiri' # Loop through all available plays and parse XML for each one def createAllScripts() # List of lists that pairs all play names with their Folger's acronyms plays = [["MND", "a_midsummer_nights_dream"], ["AWW", 'alls_well_that_ends_well'], ["Ant", 'antony_and_cleopatra'], ["AYL", 'as_you_like_it'], ["Cor", 'coriolanus'], ["Cym", 'cymbeline'], ["Ham", 'hamlet'], ["1H4", 'henry_iv_part_1'], ["2H4", 'henry_iv_part_2'], ["H5", 'henry_v'], ["1H6",'henry_vi_part_1'], ["2H6", 'henry_vi_part_2'], ["3H6", 'henry_vi_part_3'], ["H8", 'henry_viii'], ["JC", 'julius_caesar'], ["Jn", 'king_john'], ["Lr", 'king_lear'], ["LLL", 'loves_labors_lost'], ["Mac", 'macbeth'], ["MM", 'measure_for_measure'], ["Ado", 'much_ado_about_nothing'], ["Oth", 'othello'], ["Per", 'pericles'], ["R2", 'richard_ii'], ["R3", 'richard_iii'], ["Rom", 'romeo_and_juliet'], ["Shr", 'taming_of_the_shrew'], ["Err", 'the_comedy_of_errors'], ["MV", 'the_merchant_of_venice'], ["Wiv", 'the_merry_wives_of_windsor'], ["Tmp", 'the_tempest'], ["TGV", 'the_two_gentlemen_of_verona'], ["TNK", 'the_two_noble_kinsmen'], ["WT", 'the_winters_tale'], ["Tim", 'timon_of_athens'], ["Tit", 'titus_andronicus'], ["Tro", 'troilus_and_cressida'], ["TN", 'twelfth_night'], ["Ven", 'venus_and_adonis']] index = 1 plays.each do |play| text = createScript(play[0], true) filename = '../../edited_' + play[1] + '.html' File.open(filename, "w") {|f| f.write(text)} puts((index * 100 / plays.length).to_s + '% completed') index = index + 1 end end def createScript(title, flag) # If this was called from the command line or from the controller, # the files for some reason need different paths if flag == true doctitle = "../../FolgerDigitalTexts_XML_Complete/" + title.to_s + ".xml" else doctitle = "FolgerDigitalTexts_XML_Complete/" + title.to_s + ".xml" end doc = Nokogiri::XML(File.open(doctitle)) htmlstring = "" # Create act and scene numbers to update currAct = 1 currScene = 1 currIndex = 1 # DISPLAY ACT NUMBER acts = doc.css('//div1') acts.each do |act| if Nokogiri::XML(act.to_s).css('head').first != nil actname = "Diva" + currAct.to_s actheadname = "a" + currAct.to_s actstring = '<div class="actDiv" id="' + actname + '"><button class="acthead" id="' + actheadname + '" data-cut="false" data-display="true">' + Nokogiri::XML(act.to_s).css("head").first.inner_text + '</button><br></b>' htmlstring << actstring end # DISPLAY SCENE NUMBER currAct = currAct + 1 scenes = Nokogiri::XML(act.to_s).css('//div2') currScene = 1 scenes.each do |scene| if Nokogiri::XML(scene.to_s).css('head').first != nil scenename = "Divs" + currScene.to_s sceneheadname = "s" + currIndex.to_s scenestring = '<div class="sceneDiv" id="'+ scenename + '"><button class="scenehead" id="' + sceneheadname + '" data-cut="false" data-display="true">' + Nokogiri::XML(scene.to_s).css('head').first.inner_text + '</button><br>' htmlstring << scenestring end currScene = currScene + 1 currIndex = currIndex + 1 lines = Nokogiri::XML(scene.to_s).css('//sp') stages = Nokogiri::XML(scene.to_s).css('stage').to_a lines.each do |line| # DISPLAY STAGE DIRECTIONS # Get line id lineN = line.attr("xml:id").to_s.gsub("sp-","").to_i stages.each do |stage| # Get stage direction id stageN = stage.attr('xml:id').to_s.gsub("stg-","").to_i # If there is a stage dir that comes before the line if (stageN < lineN) and (stageN >= lineN-1.0) # display stage direction stagestring = '<br><button class="stage" data-cut="false" data-display="true">' + stage.inner_text + '</button> <br>' htmlstring << stagestring stages.delete(stage) end end # Getting all the info needed for each line speaker = Nokogiri::XML(line.to_s).css('speaker') milestones = Nokogiri::XML(line.to_s).css('milestone') spwords = Nokogiri::XML(line.to_s).css('w','c','pc') # DISPLAY SPEAKER speakerstring = '<br><button class="speaker">' + speaker.inner_text + '</button><br>' htmlstring << speakerstring # DISPLAY LINES milestones.each do |ms| msN = ms.attr("xml:id").to_s.gsub("ftln-","").to_f stages.each do |stage| # Get stage direction id stageN = stage.attr('xml:id').to_s.gsub("stg-","").to_f # If there is a stage dir inside speech if (stageN <= msN) and (stageN >= msN-1.0) # display stage direction stagestring = '<button class="stage inside" data-cut="false" data-display="true">' + stage.inner_text + '</button> <br>' htmlstring << stagestring stages.delete(stage) end end # get line number lineNum = ms.attr("n").to_s.split(".")[2] # get corresps per milestone in array wordIDs = ms.attr("corresp").to_s.split(" ") # remove #s wordIDs = wordIDs.map { |w| w.gsub("#","")} # Search spwords for corresponding w/c/pc # DISPLAY LINE NUMBER if lineNum.to_i % 5 == 0 linenumstring = '<p class="lineNum" id="originalLineNum">' + lineNum.to_s + '</p>' htmlstring << linenumstring end wordIDs.each do |id| spwords.each do |word| if word.attr('xml:id').to_s == id # DISPLAY EACH WORD if (word.inner_text == ".") || (word.inner_text == ",") || (word.inner_text == "?") || (word.inner_text == "!") || (word.inner_text == ";") || (word.inner_text == ":") wordstring = '<button class="punc" data-cut="false" data-display="true" data-lineNum='+lineNum.to_s + '>' + word.inner_text + '</button> ' htmlstring << wordstring else if word.inner_text != "" && word.inner_text != " " wordstring = '<button class="word" data-cut="false" data-display="true" data-lineNum='+lineNum.to_s + '>' + word.inner_text + '</button> ' htmlstring << wordstring end end end end end # BREAK FOR NEW LINE htmlstring << '<br class="newLine" data-lineNum='+lineNum.to_s + '>' stages.each do |stage| # Get stage direction id stageN = stage.attr('xml:id').to_s.gsub("stg-","").to_f # If there is a stage dir inside speech if (stageN >= msN) and (stageN < msN+1.0) # display stage direction stagestring = '<button class="stage inside" data-cut="false" data-display="true">' + stage.inner_text + '</button> <br>' htmlstring << stagestring stages.delete(stage) end end end end # Any last stage direction at the end of the section htmlstring << '<br>' stages.each do |stage| stagestring = '<button class="stage" data-cut="false" data-display="true">' + stage.inner_text + '</button> <br>' htmlstring << stagestring stages.delete(stage) end end htmlstring << '</div>' htmlstring << '<br>' end htmlstring << '</div>' return htmlstring end # Parsing command line arguments, usage: ruby create_scripts.rb all all_flag = ARGV[0] if all_flag == 'all' puts ('Creating all scripts') createAllScripts() end
true
d9c08623838e431e91eed7d1279ec354bf2816c1
Ruby
kou1203/furima-34471
/spec/models/user_spec.rb
UTF-8
5,183
2.6875
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do before do @user = FactoryBot.build(:user) end describe '新規登録' do context '新規登録ができる時' do it 'ニックネーム,メールアドレス,パスワード、パスワード(確認用)、苗字、名前、苗字(振り仮名)、名前(振り仮名)、生年月日があれば登録できる。' do expect(@user).to be_valid end it 'パスワードが6文字以上で半角英数字混合であれば登録できる。' do @user.password = '123456a' @user.password_confirmation = '123456a' expect(@user).to be_valid end end context '新規登録できない時' do it 'ニックネームがないと登録できない' do @user.nickname = '' @user.valid? expect(@user.errors.full_messages).to include "Nickname can't be blank" end it 'メールアドレスが空だと登録できない' do @user.email = '' @user.valid? expect(@user.errors.full_messages).to include "Email can't be blank" end it '同じメールアドレスがあると登録できない' do user_another = FactoryBot.build(:user) user_another.save @user = FactoryBot.build(:user) @user.email = user_another.email @user.valid? expect(@user.errors.full_messages).to include('Email has already been taken') end it 'メールアドレスは、@を含まないと登録できない' do @user.email = 'test.gmail.com' @user.valid? expect(@user.errors.full_messages).to include('Email is invalid') end it 'パスワードがないと登録できない' do @user.password = '' @user.valid? expect(@user.errors.full_messages).to include("Password can't be blank") end it 'パスワードは、6文字以上での入力がないと登録できない' do @user.password = '1234a' @user.valid? expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)") end it 'パスワードは、半角英数字混合での入力がないと登録できない' do @user.password = '123456' @user.password_confirmation = '123456' @user.valid? expect(@user.errors.full_messages).to include("Password is invalid") end it 'パスワード(確認用)は、半角英数字混合での入力がないと登録できない' do @user.password = 'abcdef' @user.password_confirmation = 'abcdef' @user.valid? expect(@user.errors.full_messages).to include("Password is invalid") end it 'パスワードとパスワード(確認用)は、値の一致しないと登録できない' do @user.password = '12345a' @user.password_confirmation = '123456a' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password") end it '苗字が空だと登録できないこと' do @user.last_name = '' @user.valid? expect(@user.errors.full_messages).to include("Last name can't be blank") end it '氏名が空だと登録できないこと' do @user.first_name = '' @user.valid? expect(@user.errors.full_messages).to include("First name can't be blank") end it '苗字が漢字・平仮名・カタカナ以外では登録できないこと' do @user.last_name = 'test' @user.valid? expect(@user.errors.full_messages).to include("Last name is invalid") end it '氏名が漢字・平仮名・カタカナ以外では登録できないこと' do @user.first_name = 'test' @user.valid? expect(@user.errors.full_messages).to include("First name is invalid") end it '苗字カナが空だと登録できないこと' do @user.last_name_kana = '' @user.valid? expect(@user.errors.full_messages).to include("Last name kana can't be blank") end it '氏名カナが空だと登録できないこと' do @user.first_name_kana = '' @user.valid? expect(@user.errors.full_messages).to include("First name kana can't be blank") end it '苗字カナが全角カタカナ以外では登録できないこと' do @user.last_name_kana = 'test' @user.valid? expect(@user.errors.full_messages).to include("Last name kana is invalid") end it '氏名カナが全角カタカナ以外では登録できないこと' do @user.first_name_kana = 'test' @user.valid? expect(@user.errors.full_messages).to include("First name kana is invalid") end it '生年月日が必須がないと登録できない' do @user.birthday = '' @user.valid? expect(@user.errors.full_messages).to include("Birthday can't be blank") end end end end
true
584bc36de9fa8fa1aa9131e94e97816f47b961be
Ruby
pacuum/vtc_payment
/lib/vtc_payment/bank/request.rb
UTF-8
4,836
2.515625
3
[ "MIT" ]
permissive
require "digest" require "cgi" require "date" # terminology # account: the login account used to login VTC website # website_id: You first need to create a business account in vtc website and then register your website. # After the registration you visit the registraion management screen and see the id of your website. It's your website_id # secret_key: when you register you need to decide your secret key. # callback_url # param_extend: see http://sandbox3.vtcebank.vn/Documents/Website_Integrated_en.pdf # # USAGE # req = VtcPayment::Bank::Request.new( account, website_id, SECRET_KEY, callback_url ) # params = { # order_id: 1234, # required # amount: 100000, # VND, required # first_name: , # last_name: , # mobile: , # address1: , # address2: , # city_name: , # country: , # email: , # order_description: , # } # url = req.url(params) module VtcPayment module Bank class Request class << self attr_accessor :production_url # class_attribute end attr_accessor :sandbox def initialize( account, website_id, secret_key, callback_url ) @account = account.to_s @website_id = website_id.to_s @secret_key = secret_key.to_s @callback_url = callback_url.to_s raise "account, website_id, secret_key, callback_url must not be blank." if [ @account, @website_id, @secret_key, @callback_url ].any?{|e| e.to_s.empty? } end def sandbox? # p [ @sandbox, defined?(Rails)] if [email protected]? @sandbox # true or false else (defined? (Rails) && ! Rails.env.production ) end end def base_url # from pdf document sandbox? ? "http://sandbox1.vtcebank.vn/pay.vtc.vn/cong-thanh-toan/checkout.html" : self.class.production_url end # If you want to limit payment type, choose sub classes defined below def screen_method "" # choose from all three methods (VTCPay, Credit, Bank) end class CreditCard < Request def screen_method "PaymentType:Visa;" end %W(Visa Master).each do |card| module_eval <<-EOS class #{card} < CreditCard def screen_method "PaymentType:Visa;Direct:#{card}" end end EOS end end class Bank < Request def screen_method "PaymentType:Bank;" end %W(Vietcombank Techcombank MB Vietinbank Agribank DongABank Oceanbank BIDV SHB VIB MaritimeBank Eximbank ACB HDBank NamABank SaigonBank Sacombank VietABank VPBank TienPhongBank SeaABank PGBank Navibank GPBank BACABANK PHUONGDONG ABBANK LienVietPostBank BVB).each do |bank| module_eval <<-EOS class #{bank} < Bank def screen_method "PaymentType:Bank;Direct:#{bank}" end end EOS end end class VTCPay < Request def screen_method "PaymentType:Bank;" end end module Currency VND = 1 USD = 2 end # notice you need to escapeHTML when you embed this link in your javascript code. def url( params ) raise "amount has to be a positive number" if params[:amount].to_i <= 0 raise "order id can not be blank" if params[:order_id].to_s.empty? data = [ @website_id, Currency::VND, # 1=VND, 2=USD params[:order_id], params[:amount].to_i.to_s, # VND only @account, screen_method(), @secret_key, @callback_url, ].join("-") sign = Digest::SHA256.hexdigest( data ).upcase url = base_url() query = { "website_id": @website_id, "payment_method": Currency::VND, "order_code": params[:order_id], "amount": params[:amount].to_i.to_s, "receiver_acc": @account, "urlreturn": CGI.escape(@callback_url.to_s), "customer_first_name": CGI.escape(params[:first_name].to_s), "customer_last_name": CGI.escape(params[:last_name].to_s), "customer_mobile": CGI.escape(params[:mobile].to_s), "bill_to_address_line1": CGI.escape(params[:address1].to_s), "bill_to_address_line2": CGI.escape(params[:address2].to_s), "city_name": CGI.escape(params[:city_name].to_s), "address_country": CGI.escape(params[:country].to_s), "customer_email": CGI.escape(params[:email].to_s), "order_des": CGI.escape(params[:order_description].to_s), "param_extend": CGI.escape(screen_method()), "sign": sign, } url += "?" url += query.map{|k,v| [k,v].join("=") }.join("&") url end end end end
true
e4f61d72c9b7264949ebafad4afa9923e7e0f7a1
Ruby
azma03/cc_week2_day5_homework
/specs/room_spec.rb
UTF-8
1,502
3.015625
3
[]
no_license
require ("minitest/autorun") require ("minitest/rg") require_relative("../room.rb") require_relative("../song.rb") require_relative("../guest.rb") class RoomTest < Minitest::Test def setup @room = Room.new("Room1", 20) end def test_can_get_room_name assert_equal("Room1", @room.name) end def test_can_get_room_capacity assert_equal(20 , @room.capacity) end def test_can_get_guest_list assert_equal([] , @room.get_guest_list()) end def test_can_get_number_of_guests assert_equal(0, @room.get_number_of_guest()) end def test_add_guest guest = Guest.new("Guest1", 10) @room.add_guest(guest) assert_equal(1,@room.get_number_of_guest()) end def test_remove_guest guest1 = Guest.new("Guest1", 10) guest2 = Guest.new("Guest2", 10) @room.add_guest(guest1) @room.add_guest(guest2) @room.remove_guest(guest2) assert_equal(1,@room.get_number_of_guest()) end def test_can_get_number_of_songs assert_equal(0, @room.get_number_of_songs()) end def test_add_song song = Song.new("Song1", "Artist1") @room.add_song(song) assert_equal(1,@room.get_number_of_songs()) end def test_remove_song song1 = Song.new("Song1", "Artist1") song2 = Song.new("Song2", "Artist2") @room.add_song(song1) @room.add_song(song2) @room.remove_song(song2) assert_equal(1,@room.get_number_of_songs()) end def test_can_update_fee @room.fee = 15 assert_equal(15, @room.fee) end end
true
ab9db2cf208194d0c150dad6e03bcc28e6034350
Ruby
bunmiaj/CodeAcademy
/Web-Development/Ruby/1-Introduction/11.rb
UTF-8
789
4.0625
4
[]
no_license
=begin Multi-Line Comments You can write a comment that spans multiple lines by starting each line with a #, but there's an easier way. If you start with =begin and end with =end, everything between those two expressions will be a comment. Take a look at this example: =begin I'm a comment! I don't need any # symbols. =end =begin rescue Exception => e end Don't put any space between the = sign and the words begin or end. You can do that with math (2 + 5 is the same as 2+5), but in this case, Ruby will get confused. =begin and =end also need to be on lines all by themselves, just as shown above. Instructions Create a multi-line comment in the editor to the right. Make sure =begin and =end are on their own lines! =end =begin comment 1 comment 2 =end
true
c0569f7bfe40e5b1ac38ec66143143851af1fc6c
Ruby
dani8439/well-grounded-rubyist
/sample_code/chapter_six/loops.rb
UTF-8
1,677
4.9375
5
[]
no_license
# loop { puts "Looping forever!"} # loop do # puts "Looping forever!" # end # Controlling the loop: # n = 1 # loop do # n = n + 1 # break if n > 9 # end # => won't be an output, will just execute(loop). # n = 1 # loop do # n = n + 1 # next unless n == 10 # end # => won't be an output, will just execute. # The While Keyword # n = 1 # while n < 11 # puts n # n = n + 1 # end # puts "Done!" # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # Done! n = 1 begin puts n n = n + 1 end while n < 11 puts "Done!" # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # Done! # If you put while at the beginning and if the while condition is false, the code isn't executed n = 10 while n < 10 puts n end # But if you put the while test at the end... n = 10 begin puts n end while n < 10 # 10 is the output. # The until keyword: # The body of the loop (the printing & incrementing of n in this example) is executed repeatedly until condition is true. n = 1 until n > 10 puts n n = n + 1 end # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # The while & until modifiers n = 1 n = n + 1 until n == 10 puts "We've reached 10!" # 1 # 2 # 3 # 4 # 5 # 6 # 7 # 8 # 9 # 10 # We've reached 10! # Could also use while n < 10. The one-line modifier versions of while and until don't behave the same way as # post-positioned while and until you use with a begin/end block. IOW: a = 1 a += 1 until true # won't execute because already true. #But in this case: a = 1 begin a += 1 end until true # The body of the begin/end gets executes once. celsius = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100] puts "Celsius\tFahrenheit" for c in celsius puts "#{c}\t#{Temperature.c2f(c)}" end
true
e28820db9348abef0595a0d94e433a6d6cc62306
Ruby
Roakz/interactive-erd
/mapper.rb
UTF-8
4,538
2.90625
3
[]
no_license
require './lib/data_types.rb' require 'json' class InvalidDataType < StandardError def message "SQL file contains an invalid data type!" end end class Mapper attr_accessor :file, :load_file attr_reader :calculate_top_level, :split_entities, :entities_to_json def initialize(params = {}) @file = params[:file] ? params[:file] : nil @key_map_array = [] end def load_file(file) @file = file end def calculate_top_level return false unless @file unwanted_key_words = ["CREATE", "SCHEMA", "DATABASE"] schema_arr = [] database_arr = [] File.foreach(@file) do |line| if line.include? " CREATE SCHEMA" schema_arr << line.gsub(/\/\*.[^\*\/]*\*\//, '').tr("`", "") end if line.include? "CREATE DATABASE" database_arr << line.gsub(/\/\*.[^\*\/]*\*\//, '').tr("`", "") end next end schema_arr.each_with_index do |line, index| schema_arr[index] = line.split(' ').reject! {|word| unwanted_key_words.include? word }[0].tr(';', '') end unless schema_arr.empty? database_arr.each_with_index do |line, index| database_arr[index] = line.split(' ').reject! {|word| unwanted_key_words.include? word }[0].tr(';', '') end unless database_arr.empty? return {:database => database_arr, :schema => schema_arr} end def split_entities return false unless @file entities = [] entity = "" skip = true File.foreach(@file) do |line| if line.include? "CREATE TABLE" entity = line skip = false end next unless !skip entity += line unless line == entity skip = line.include? ";" skip ? entities << entity : next end entities end def resolve_entity_keys(entity) @return_array = [] entity.each_line do |line| next unless line.include? "KEY" if line.split[0] == "PRIMARY" @extracted_line = line[/\(\W*[a-zA-Z]*\W*(,\W*[a-zA-Z]*\W*)*\)|\)$/] if @extracted_line @extracted_line = @extracted_line.gsub(/[^\w,]/, '') if @extracted_line.split(',').length == 1 @return_array << {:column_name => @extracted_line, :type => "primary"} else @extracted_line.split(',').each {|column| @return_array << {:column_name => column, :type => "primary"}} end end end if line.include? 'FOREIGN' segmented_line = line.split segmented_line.reject! {|word| ["CONSTRAINT", "FOREIGN", "KEY", "REFERENCES"].include? word}.reject!.with_index {|v, i| i == 0} @return_array << { :column_name => segmented_line[0].gsub(/[^\w]/, ''), :type => "foreign", :ref_table => segmented_line[1].gsub(/[^\w]/, ''), :ref_col => segmented_line[2].gsub(/[^\w]/, '') } end end @return_array end def entities_to_json(entities) return_json = {} return_json["top_level"] = calculate_top_level return_json["entities"] = [] entities.each do |entity| entity_name = entity.split(" ")[2].tr('`', '') return_json["entities"] << { "table_name": entity_name, "columns": resolve_columns(entity_name, entity), "keys": resolve_entity_keys(entity) } end return return_json end def resolve_columns_skip?(line) ["DROP TABLE", "USE", "CREATE TABLE", ";", "REFERENCES", "KEY"].each do |skip_value| if line.include? skip_value return true end end return true if ["PRIMARY", "FOREIGN", "--"].include? line.split[0] return false end def validate_data_type!(data_type) [data_type, data_type.upcase, data_type.capitalize].each {|variation| return true if data_types.include? variation} return false end def line_for_data_type(line) @result = line.split[1].gsub(/\([0-9]{1,3}\)?,?[0-9]{0,3}\)|,\z/, '') if validate_data_type!(@result) == false raise InvalidDataType else return @result end end def store_key_mapping_lines(entity, line) return unless line.include? "KEY" @key_map_array << {:entity => entity, :line => line} end def resolve_columns(entity_name, entity) column_array = [] entity.each_line do |line| store_key_mapping_lines(entity_name, line) next if resolve_columns_skip?(line) column = {} column["column_name"] = line.split(" ")[0].tr('`', "") column["data_type"] = line_for_data_type(line) column_array << column end return column_array end end
true
fbe661e0cf65ce6931c79517a846acc92094d0ec
Ruby
szagar/pyzts
/daemons/ibgw2filed/lib/tc2000_entry_filters.rb
UTF-8
1,499
2.625
3
[]
no_license
module Tc2000EntryFilters def pre_buy?(tc,params) puts "Tc2000EntryFilters#pre_buy?=true" true end def descretionary?(tc,params) puts "Tc2000EntryFilters#descretionary?=true" true end def manual?(tc,params) puts "Tc2000EntryFilters#manual?" params[:setup_src][/manual/] end def engulfing_white?(tc,params) puts "Tc2000EntryFilters#engulfing_white?=#{tc.engulfing_white?}" tc.engulfing_white? end def long_bop1?(tc,params) entry_filter = params[:side] == "long" && bop_signal1?(tc) puts "Tc2000EntryFilters#long_bop1?=#{entry_filter}" entry_filter end def long_bop1_rsi1?(tc,params) entry_filter = params[:side] == "long" && bop_signal1?(tc) && rsi_signal2?(tc) puts "Tc2000EntryFilters#long_bop1_rsi1?=#{entry_filter}" entry_filter end def bop1_rsi2?(tc,params) entry_filter = false entry_filter = bop_signal1?(tc) && rsi_signal2?(tc) if params[:side] == "long" entry_filter = !bop_signal1?(tc) && !rsi_signal2?(tc) if params[:side] == "short" puts "Tc2000EntryFilters#bop1_rsi2?=#{entry_filter}" entry_filter end def bop1_rsi1?(tc,params) entry_filter = false entry_filter = bop_signal1?(tc) && rsi_signal1?(tc) if params[:side] == "long" entry_filter = !bop_signal1?(tc) && !rsi_signal1?(tc) if params[:side] == "short" puts "Tc2000EntryFilters#bop1_rsi1?=#{entry_filter}" entry_filter end end
true
a4adcf37ab4dce8ec206831502e9b2489b8c5c9a
Ruby
dantetekanem/rpn-calculator
/lib/tokens/addition_operator_token.rb
UTF-8
169
2.875
3
[]
no_license
class AdditionOperatorToken < OperatorToken def run(operand_1, operand_2) OperandToken.new(operand_1 + operand_2) end def self.expression /^\+/ end end
true
e6a28ec7ca957c772b9d8576762022e1150c35ff
Ruby
jpmermoz/sms_sender
/app/models/sms_gateway.rb
UTF-8
1,020
2.5625
3
[]
no_license
class SmsGateway include Singleton def cmd(param) @port.write("#{param}\r") wait end def connect_to_serialport begin @port = SerialPort.new('/dev/ttyUSB0', 9600) rescue begin @port = SerialPort.new('/dev/ttyUSB1', 9600) rescue @port = SerialPort.new('/dev/ttyUSB2', 9600) end end cmd("AT") cmd("AT+CMGF=1") @debug = true end def send_sms(message) connect_to_serialport cmd("AT+CMGS=\"#{message.number}\"") cmd("#{message.content[0..140]}#{26.chr}\r\r") sleep 3 wait cmd("AT") end def wait buffer = '' while IO.select([@port], [], [], 0.25) chr = @port.getc.chr; print chr if @debug == true buffer += chr end buffer end def close @port.close end def fetch_from_database t = Thread.new do Message.where(sent_at: nil).each do |m| m.update_attribute(:sent_at, Time.now) if m.send_sms.include?("OK") close end end end end
true
b7cca480550fd18a7ea59ecc4bae32cfb84c2799
Ruby
frescoraja/rubymvc
/lib/sqllitedb.rb
UTF-8
989
2.734375
3
[]
no_license
# frozen_string_literal: true require 'sqlite3' # DBConnection provides an interface to connect to and run queries on a DB class DBConnection def self.open(db_file_name) @db = SQLite3::Database.new(db_file_name) @db.results_as_hash = true @db.type_translation = true @db end def self.reset commands = [ "rm '#{@db_file_name}'", "cat '#{@sql_file_name}' | sqlite3 '#{@db_file_name}'" ] commands.each { |command| `#{command}` } DBConnection.open(db_file_name) end def self.instance reset if @db.nil? @db end def self.execute(*args) puts args[0] instance.execute(*args) end def self.execute2(*args) puts args[0] instance.execute2(*args) end def self.last_insert_row_id instance.last_insert_row_id end private attr_reader :db_file_name, :sql_file_name def initialize(db_file_name) @db_file_name = db_file_name @sql_file_name = db_file_name.sub('.db', '.sql') end end
true
0aae7ccedc5688f5ed661944049305313baeb481
Ruby
Loratt/03
/learnrubythehardway(Уроки 1-39)/ex33.rb
UTF-8
355
3.84375
4
[]
no_license
i = 0 numbers = [] puts "Choose number" number = gets.chomp.to_i puts "Choose number of increments " increment = gets.chomp.to_i while i < number puts "At the top i is #{i}" numbers.push(i) i += increment puts "Numbers now: ", numbers puts "At the bottom i is #{i}" end puts "The numbers: " numbers.each {|num| puts num }
true
c1281fc7fd48dce944597da1a124083426de5d71
Ruby
kkznch/learn-ruby-on-ruby
/practice4-8-2.rb
UTF-8
966
3.40625
3
[]
no_license
# coding: utf-8 require "minruby" def evaluate(tree) case tree[0] when 'lit' tree[1] when '+' left = evaluate(tree[1]) right = evaluate(tree[2]) left + right when '-' left = evaluate(tree[1]) right = evaluate(tree[2]) left * right when '*' left = evaluate(tree[1]) right = evaluate(tree[2]) left * right when '**' left = evaluate(tree[1]) right = evaluate(tree[2]) left ** right when '%' left = evaluate(tree[1]) right = evaluate(tree[2]) left % right when '==' left = evaluate(tree[1]) right = evaluate(tree[2]) left == right when '<' left = evaluate(tree[1]) right = evaluate(tree[2]) left < right when '>' left = evaluate(tree[1]) right = evaluate(tree[2]) left > right else left = evaluate(tree[1]) right = evaluate(tree[2]) left / right end end str = gets tree = minruby_parse(str) answer = evaluate(tree) pp(answer)
true
21b05ccfc93a17b56e916ea6e744a6b3d10f5c60
Ruby
alfosco/puppy_love
/app/models/shelter.rb
UTF-8
684
2.703125
3
[]
no_license
class Shelter attr_reader :id, :name, :email, :phone, :city, :state, :zip, :google_map_api_key def initialize(shelter = {}) @id = shelter[:id][:$t] @name = shelter[:name][:$t] @email = shelter[:email][:$t] @phone = shelter[:phone][:$t] @city = shelter[:city][:$t] @state = shelter[:state][:$t] @zip = shelter[:zip][:$t] @google_map_api_key = Figaro.env.google_map_api_key end def self.find_shelter(id) shelter = PetFinderService.find_shelter(id) Shelter.new(shelter) end def remove_spaces_from_name name.tr(" ", "+") end end
true
44b796315f95e08c8a09059fd496ba37a290c50d
Ruby
nathanpena/what-you-know-about-the-gil-is-wrong
/concurrent_ruby.rb
UTF-8
1,586
2.859375
3
[]
no_license
require 'concurrent' require 'benchmark' SYMBOLS = ['MA', 'PCLN', 'ADP', 'V', 'TSS', 'FISV', 'EBAY', 'PAYX', 'WDC', 'SYMC', 'AAPL', 'AMZN', 'KLAC', 'FNFV', 'XLNX', 'MSI', 'ADI', 'VRSN', 'CA', 'YHOO'] def modify_symbols(symbol) symbol += " is a symbol." end def serial_modify_sybmols SYMBOLS.collect do |symbol| modify_symbols(symbol) end end def concurrent_modify_symbols symbols = SYMBOLS.collect do |symbol| Concurrent::Future.execute { modify_symbols(symbol) } end symbols.collect { |symbol| symbol.value } end puts 'Warm up...' p concurrent_modify_symbols puts "\n" Benchmark.bmbm do |bm| bm.report('serial') do serial_modify_sybmols end bm.report('concurrent') do concurrent_modify_symbols end end __END__ Warm up... ["MA is a symbol.", "PCLN is a symbol.", "ADP is a symbol.", "V is a symbol.", "TSS is a symbol.", "FISV is a symbol.", "EBAY is a symbol.", "PAYX is a symbol.", "WDC is a symbol.", "SYMC is a symbol.", "AAPL is a symbol.", "AMZN is a symbol.", "KLAC is a symbol.", "FNFV is a symbol.", "XLNX is a symbol.", "MSI is a symbol.", "ADI is a symbol.", "VRSN is a symbol.", "CA is a symbol.", "YHOO is a symbol."] Rehearsal ---------------------------------------------- serial 0.000000 0.000000 0.000000 ( 0.000011) concurrent 0.000000 0.000000 0.000000 ( 0.001751) ------------------------------------- total: 0.000000sec user system total real serial 0.000000 0.000000 0.000000 ( 0.000021) concurrent 0.000000 0.000000 0.000000 ( 0.001476)
true
fb46e1178a850d41e5b56db3b90c8b06abebb70f
Ruby
srt32/exercism
/fizzbuzz/fizzbuzz.rb
UTF-8
352
3.234375
3
[]
no_license
class Fizzbuzz < Struct.new(:max) MUTATIONS = { 'fizzbuzz' => ->(i) {i % 3 == 0 && i % 5 == 0}, 'fizz' => ->(i) {i % 3 == 0}, 'buzz' => ->(i) {i % 5 == 0} } def fizzle 1.upto(max).map do |i| mutations.find(-> {[i]}) do |k, v| v.call(i) end[0] end end private def mutations MUTATIONS end end
true
5bfda76962660e03eece23192fbcecd0d95339b3
Ruby
co2co2/MarsRover
/marsRover.rb
UTF-8
1,312
4.09375
4
[]
no_license
class Rover def initialize (x, y, dir) @x_coordinate = x @y_coordinate = y @direction = dir end def read_instruction (instruction) @array = instruction.split("") #.split is useful for spliting string into array @array.each do |k| if k == "M" move else turn(k) end end puts "dir = #{@direction}" puts "x coordinate = #{@x_coordinate}" puts "y coordinate = #{@y_coordinate}" end def move case @direction when"N" @y_coordinate +=1 when "S" @y_coordinate -=1 when "E" @x_coordinate +=1 when "W" @x_coordinate -=1 end end def turn(dir) case @direction when "N" if dir == "R" @direction = "E" else @direction = "W" end when "S" if dir == "R" @direction = "W" else @direction = "E" end when "E" if dir == "R" @direction = "S" else @direction = "N" end when "W" if dir == "R" @direction = "N" else @direction = "S" end end end end rov1= Rover.new(1, 2, "N") rov1.read_instruction("LMLMLMLMM") rov2 = Rover.new(3, 3, "E") rov2.read_instruction("MMRMMRMRRM")
true
d2d902546e4120c50f1bb09c9c8757c075f021e3
Ruby
jcmuller/backup_jenkins
/lib/backup_jenkins/backup.rb
UTF-8
4,096
2.5625
3
[ "MIT" ]
permissive
require 'fileutils' module BackupJenkins class Backup include BackupJenkins::Formatter def initialize(config = Config.new) @config = config end def do_backup raise "Backup directory already exists! (#{backup_directory})" if FileTest.directory?(backup_directory) copy_files create_tarball remove_temporary_files remove_old_backups rescue Interrupt puts "Cleaning up..." clean_up end def tarball_filename "#{backup_directory}.tar.bz2" end def list_local_files format_backup_file_data(backup_files) end def clean_up puts "Removing #{backup_directory}" remove_temporary_files puts "Removing #{tarball_filename}" FileUtils.rm_rf(tarball_filename) rescue Errno::ENOENT end private attr_reader :config def backup_directory @backup_directory ||= "#{config.backup.dir_base}/#{config.base_file_name}_#{timestamp}" end def timestamp Time.now.strftime("%Y%m%d_%H%M") end def copy_files create_dir_and_copy(config_file) create_dir_and_copy(plugin_files) create_dir_and_copy(user_content_files) create_dir_and_copy(user_files) create_dir_and_copy(jobs_files) end def create_dir_and_copy(file_names) file_names.each do |file_name| create_dir_and_copy_impl(file_name) end end def create_dir_and_copy_impl(file_name) raise "file '#{file_name}' does not exist" unless FileTest.file?(file_name) new_file_name = new_file_path(file_name) new_file_dir = File.dirname(new_file_name) FileUtils.mkdir_p(new_file_dir, :verbose => config.verbose) FileUtils.cp(file_name, new_file_name, :verbose => config.verbose) end def new_file_path(file_name) "#{backup_directory}/#{file_name.gsub(%r{#{config.jenkins.home}}, "")}".gsub(%r{//}, '/') end def config_file Dir["#{config.jenkins.home}/config.xml"] end def plugin_files plugin_files_jpis + plugin_files_hpis end def plugin_files_jpis Dir["#{config.jenkins.home}/plugins/*.jpi"] + Dir["#{config.jenkins.home}/plugins/*.jpi.pinned"] + Dir["#{config.jenkins.home}/plugins/*.jpi.disabled"] end def plugin_files_hpis Dir["#{config.jenkins.home}/plugins/*.hpi"] + Dir["#{config.jenkins.home}/plugins/*.hpi.pinned"] + Dir["#{config.jenkins.home}/plugins/*.hpi.disabled"] end def user_content_files Dir["#{config.jenkins.home}/userContent/*"] end def user_files find_files('users', 'config.xml') end def jobs_files find_files('jobs', 'config.xml', 'nextBuildNumber') end def find_files(base, *names) `#{find_file_command(base, names)}`.split(%r{#{$/}}) end def find_file_command(base, names) path = File.join(config.jenkins.home, base) names_str = names * " -or -name " "find #{path} -maxdepth 3 -name #{names_str}" end def create_tarball puts "Creating #{tarball_filename}..." if config.verbose Dir.chdir(backup_directory) %x{tar #{tar_options} #{tarball_filename} .} raise "Error creating tarball" unless FileTest.file?(tarball_filename) end def tar_options %w(j c f).tap do |options| options.unshift('v') if config.verbose end.join('') end def remove_old_backups files_to_remove.each do |file| FileUtils.rm(file) end end def files_to_remove glob_of_backup_files - glob_of_backup_files.last(config.backup.backups_to_keep.local) end def glob_of_backup_files Dir["#{config.backup.dir_base}/#{config.base_file_name}_*tar.bz2"] end def backup_files glob_of_backup_files.sort.map do |file| { :key => file.gsub(%r{#{config.backup.dir_base}/}, ''), :content_length => File.size(file) } end end def remove_temporary_files FileUtils.rm_rf(backup_directory, :verbose => config.verbose) end end end
true
e571d1b9e1fd65b40ba6626423dae6c04fc31a27
Ruby
wdoogz/ruby-learning
/learning.rb
UTF-8
1,574
4.25
4
[]
no_license
puts "This is the opposite of a while loop" counter = 1 until counter == 10 puts counter counter += 1 end puts "\n\nThis is a for loop" for i in 1..15 puts i end puts "\n\nThis is a \"loop\" method" i = 0 loop do i += 1 print "#{i}" break if i > 20 end puts "\n\nThis is the loop method with a 'next' key word" i = 40 loop do i -= 1 next if i % 2 != 0 print "#{i}" break if i <=0 end puts "\n\n This is creating an array and iterating through it" array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] array.each do |item| if item**2 % 6 == 0 puts "#{item} squared can be divided by 6" end end puts "\n\n Lets create something silly now..." puts "Give me a string" firstString = gets.chomp puts "Give me one more string Please" secondString = gets.chomp words = firstString.split(" ") words.each do |word| if word == secondString puts "NAME" else puts word end end s = [["ham", "swiss"], ["turkey", "cheddar"], ["roast beef", "gruyere"]] s.each do |x| x.each do |y| puts y end end people = { "Bob" => "Architect", "Steve" => "Analyst", "Arister" => "Jr Analyst" } people.each do |person| puts person[1] end # Function to keep everything neat def test_function puts "Please supply input" text = gets.chomp words = text.split(" ") frequencies = Hash.new(0) words.each do |word| frequencies["#{word}"] += 1 end frequencies = frequencies.sort_by do |k, v| frequencies[k] = v end frequencies.reverse! frequencies.each do |k,v| puts "#{k} #{v.to_s}" end end test_function
true
28484936f4390648a41e2c94961d35bf13a051b5
Ruby
Hinbin/tenjin
/app/services/user/change_user_role.rb
UTF-8
1,450
2.6875
3
[ "MIT" ]
permissive
# frozen_string_literal: true # Adds a role to a user class User::ChangeUserRole < ApplicationService def initialize(user, role, action, subject = nil) @user = user @role = role @action = action @subject = Subject.find(subject) unless subject.blank? end def call return return_error('User not found') unless @user.present? return return_error('Role not found') unless @role.present? return return_error('Action must be "add" or "remove"') unless %i[add remove].include? @action if %w[lesson_author question_author].include?(@role) && @subject.blank? return return_error('Must include a subject with a lesson or quesiton author role') end change_user_role OpenStruct.new(success?: true, user: @user, role: @role, action: @action) end private def return_error(msg) OpenStruct.new(success?: false, user: @user, role: @role, action: @action, errors: msg) end def change_user_role case @action when :add add_user_role when :remove remove_user_role end end def add_user_role if @role == 'school_admin' @user.add_role @role elsif %w[question_author lesson_author].include? @role @user.add_role @role, @subject end end def remove_user_role if @role == 'school_admin' @user.remove_role @role elsif %w[question_author lesson_author].include? @role @user.remove_role @role, @subject end end end
true
37eb38f4348fb63e7927267b2ea3bb0c1a4fb875
Ruby
cassiejdelacruz/course101
/small_problems/easy_set_1/easy1_2.rb
UTF-8
194
3.65625
4
[]
no_license
def is_odd?(integer) integer % 2 == 1 end def is_odd?(number) number.remainder(2) == 1 || number.remainder(2) == -1 end p is_odd?(8) p is_odd?(7) p is_odd?(0) p is_odd?(-4) p is_odd?(-5)
true
f86edace51e57ace7657dfb1e882354c24afcd42
Ruby
aleckyler/voter_sim_folder
/voter_sim_main.rb
UTF-8
3,772
3.875
4
[]
no_license
# main menu file # will contain a case block in which each different option will run a # different method def welcome puts <<-END Welcome to the voting simulator! Have fun! END end def main_menu puts <<-END What would you like to do? (A)Create (B)List (C)Update (D)Vote END end def split_lists(list) end def to_continue puts <<-END Do you want to continue with this set or exit the program? (A)Continue? (B)Exit program? END end def confirm puts <<-END Are you sure you want to perform this action? (A)Yes (B)No END end candidates = [] voters = [] welcome while true # to loop through entire program if user chooses to continue at end # puts main menu and makes sure answer is valid sleep 0.5 main_menu choice = gets.chomp.downcase until (choice == "a" || choice == "b" || choice == "c" || choice == "d") puts "That is not a valid entry." main_menu choice = gets.chomp.downcase end # if user hasn't entered a candidate or voter, they shouldnt try to list, update, or vote if !(choice == "a") && voters == [] && candidates == [] puts "\nYou should probably add a candidate or a voter first..." # if user hasnt included at least one candidate and at least one voter, they cant run a vote elsif choice == "d" && candidates == [] puts "\nYou should probably add a candidate first..." elsif choice == "d" && voters == [] puts "\nYou should probably add a voter first..." # actions based on valid calling of a main menu item else case choice when "a" # create a new person and add them to "candidates" list or "voters" list require './create.rb' new_person = create # p new_person if new_person.is_a? Candidate candidates << new_person puts "\n#{new_person.name}, the #{new_person.party} #{new_person.class} has been added!" # puts candidates # to check that list is updating # puts voters # to check that list is updating else voters << new_person puts "\n#{new_person.name}, the #{new_person.politics} #{new_person.class} has been added!" # puts voters # to check that list is updating end when "c" # run the update function with candidates list and voters list as arguments, # should return both lists back separately require './update.rb' list = update(candidates,voters) when "b" # call the entries in the candidates and voters lists # list = candidates + voters # list.each do |c| # require './classes.rb' # if c.is_a? Candidate # puts "#{c.class}, #{c.name}, #{c.party}" # else # puts "#{c.class}, #{c.name}, #{c.politics}" # end # end list = candidates + voters require './classes.rb' puts "\n" candidates.each do |c| puts "#{c.class}, #{c.name}, #{c.party}" end voters.each do |v| puts "#{v.class}, #{v.name}, #{v.politics}" end when "d" require './vote.rb' pick_vote(candidates,voters) end end # check if user wants to continue with current lists or exit program to_continue continue = gets.chomp.downcase until (continue == "a" || continue == "b") puts "\nThat is not a valid entry." sleep 0.5 to_continue continue = gets.chomp.downcase end if continue == "a" puts "\nThen let's continue." else confirm confirmation = gets.chomp.downcase until (confirmation == "a" || confirmation == "b") puts "\nThat is not a valid entry." sleep 0.5 confirm confirmation = gets.chomp.downcase end if confirmation == "a" break else puts "\nGlad we caught that! Let's continue" end end end
true
41c2d2463f5ce087b54bf0f79b705ad651bc37c3
Ruby
Aldyn306429/Backup
/RubyProjects/ConnectFour/lib/board.rb
UTF-8
2,022
3.515625
4
[]
no_license
# frozen_string_literal: true # Colors for the player pieces class String # colorization def colorize(color_code) "\e[#{color_code}m#{self}\e[0m" end def red colorize(31) end def yellow colorize(33) end def bg_yellow colorize(43) end end # The board of the game class Board attr_accessor :cell attr_accessor :board def initialize @cell = Array.new([['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-'], ['-', '-', '-', '-', '-', '-', '-']]) make_change end def make_change @board = " 1 2 3 4 5 6 7 | #{@cell[0][0]} | #{@cell[0][1]} | #{@cell[0][2]} | #{@cell[0][3]} | #{@cell[0][4]} | #{@cell[0][5]} | #{@cell[0][6]} | | #{@cell[1][0]} | #{@cell[1][1]} | #{@cell[1][2]} | #{@cell[1][3]} | #{@cell[1][4]} | #{@cell[1][5]} | #{@cell[1][6]} | | #{@cell[2][0]} | #{@cell[2][1]} | #{@cell[2][2]} | #{@cell[2][3]} | #{@cell[2][4]} | #{@cell[2][5]} | #{@cell[2][6]} | | #{@cell[3][0]} | #{@cell[3][1]} | #{@cell[3][2]} | #{@cell[3][3]} | #{@cell[3][4]} | #{@cell[3][5]} | #{@cell[3][6]} | | #{@cell[4][0]} | #{@cell[4][1]} | #{@cell[4][2]} | #{@cell[4][3]} | #{@cell[4][4]} | #{@cell[4][5]} | #{@cell[4][6]} | | #{@cell[5][0]} | #{@cell[5][1]} | #{@cell[5][2]} | #{@cell[5][3]} | #{@cell[5][4]} | #{@cell[5][5]} | #{@cell[5][6]} |" end def each_turn(column, icon) 5.downto(0) do |i| if @cell[i][column - 1] == '-' @cell[i][column - 1] = icon break end end make_change end def highlight_path(path) if @cell[path[0][0]][path[0][1]] == "\u25EF".red marker = "\u25EF".red.bg_yellow elsif @cell[path[0][0]][path[0][1]] == "\u25EF".yellow marker = "\u25EF".yellow.bg_yellow end path.each do |mark| @cell[mark[0]][mark[1]] = marker end make_change end end
true
15b86264b340fbd22353463d364c21bdff947df8
Ruby
dtelaroli/google_visualization_test
/app/controllers/chart_controller.rb
UTF-8
1,512
2.59375
3
[]
no_license
class ChartController < ApplicationController def index data_table = GoogleVisualr::DataTable.new data_table.new_column('string' , 'Name') data_table.new_column('number' , 'Salary') data_table.new_column('boolean' , 'Full Time Employee') data_table.add_rows(4) data_table.set_cell(0, 0, 'Mike' ) data_table.set_cell(0, 1, {:v => 10000, :f => '$10,000'}) data_table.set_cell(0, 2, true ) data_table.set_cell(1, 0, 'Jim' ) data_table.set_cell(1, 1, {:v => 8000 , :f => '$8,000' }) data_table.set_cell(1, 2, false ) data_table.set_cell(2, 0, 'Alice' ) data_table.set_cell(2, 1, {:v => 12500, :f => '$12,500'}) data_table.set_cell(2, 2, true ) data_table.set_cell(3, 0, 'Bob' ) data_table.set_cell(3, 1, {:v => 7000 , :f => '$7,000' }) data_table.set_cell(3, 2, true ) opts = { :width => 600, :showRowNumber => true } @table = GoogleVisualr::Interactive::Table.new(data_table, opts) data_table = GoogleVisualr::DataTable.new # Add Column Headers data_table.new_column('string', 'Year' ) data_table.new_column('number', 'Sales') data_table.new_column('number', 'Expenses') # Add Rows and Values data_table.add_rows([ ['2004', 1000, 400], ['2005', 1170, 460], ['2006', 660, 1120], ['2007', 1030, 540] ]) option = { width: 400, height: 240, title: 'Company Performance' } @chart = GoogleVisualr::Interactive::AreaChart.new(data_table, option) end end
true
3675dc2da7c01005f742d6e475f1ef1dfc2a50e2
Ruby
AvraamMavridis/ruby-exercises
/like_this/like_this.rb
UTF-8
387
3.5
4
[]
no_license
def get_text(prefix, plural = "") "#{prefix} like#{plural} this" end def likes(names) case names.size when 0 get_text("no one", "s") when 1 get_text(names[0], "s") when 2 get_text("#{names[0]} and #{names[1]}") when 3 get_text("#{names[0]}, #{names[1]} and #{names[2]}") else get_text("#{names[0]}, #{names[1]} and #{names.size - 2} others") end end
true
e86e6c0e0bdd45e18d04379e1c6baf5551b4f031
Ruby
rodolfopeixoto/problem-ruby-matriz-area-0-1
/lib/matrix.rb
UTF-8
1,711
3.75
4
[]
no_license
require 'byebug' class Matrix def initialize(matrix) @matrix = matrix @submatrix_temporary = [] @maximum_square_size = 0 @previous = 0 @temporary = 0 end def analyze_minimum(index_j) @submatrix_temporary[index_j] = 0 if @submatrix_temporary[index_j].nil? temporary_minimum = [@submatrix_temporary[index_j], @previous].min @submatrix_temporary[index_j] = [temporary_minimum, @submatrix_temporary[index_j]].min + 1 end def analyze_maximum(index_j) [@maximum_square_size, @submatrix_temporary[index_j]].max end def analyze_submatrix(index_i, index_j) if @matrix[index_i][index_j] == 1 analyze_minimum(index_j) @maximum_square_size = analyze_maximum(index_j) else @submatrix_temporary[index_j] = 0 end end def search_submatrix(sub_matrix, index_i) sub_matrix.each_with_index do |value, index_j| @temporary = @submatrix_temporary[index_j].nil? ? 0 : @submatrix_temporary[index_j] analyze_submatrix(index_i, index_j) @previous = @temporary; end end def maximalSquare @matrix.each_with_index do |sub_matrix, index_i| search_submatrix(sub_matrix, index_i) end @maximum_square_size * @maximum_square_size end end matrix = Matrix.new( [ [ 1, 0, 1, 1, 0, 1, 0 ], [ 0, 0, 1, 0, 1, 0, 0 ], [ 1, 1, 1, 0, 1, 0, 0 ], [ 0, 1, 1, 1, 1, 0, 1 ], [ 1, 1, 1, 1, 0, 0, 1 ], [ 0, 1, 1, 1, 0, 0, 0 ] ] ) puts matrix.maximalSquare matrix2 = Matrix.new( [ [ 1, 0, 1, 1, 0, 1, 0 ], [ 0, 0, 1, 1, 1, 0, 0 ], [ 1, 1, 1, 1, 0, 0, 0 ], [ 0, 1, 1, 0, 1, 0, 1 ], [ 1, 1, 0, 0, 0, 0, 1 ], [ 0, 1, 1, 1, 0, 0, 0 ] ] ) puts matrix2.maximalSquare
true
7efaff7ea581936269cda517512a79540d3108c9
Ruby
aryaziai/programming-univbasics-4-square-array-sf-web-091619
/lib/square_array.rb
UTF-8
89
3
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def square_array(array) while squared < array.length puts array**2 sqaured end
true
9f10761d009d4b95cd89aabf3e3e47fc9e7a0229
Ruby
demental/csv2hash
/lib/csv2hash.rb
UTF-8
2,190
2.734375
3
[ "MIT" ]
permissive
require 'csv2hash/version' require 'csv2hash/definition' require 'csv2hash/validator' require 'csv2hash/validator/mapping' require 'csv2hash/validator/collection' require 'csv2hash/parser' require 'csv2hash/parser/mapping' require 'csv2hash/parser/collection' require 'csv2hash/csv_array' require 'csv2hash/data_wrapper' require 'csv2hash/notifier' require 'csv2hash/extra_validator' require 'csv' class Csv2hash attr_accessor :definition, :file_path, :data, :notifier, :exception_mode, :errors, :ignore_blank_line def initialize definition, file_path, exception_mode=true, data_source=nil, ignore_blank_line=false @data_source = data_source self.definition, self.file_path = definition, file_path dynamic_lib_loading 'Parser' self.exception_mode, self.errors = exception_mode, [] dynamic_lib_loading 'Validator' self.notifier = Notifier.new self.ignore_blank_line = ignore_blank_line init_plugins end def init_plugins begin @plugins = [] ::Csv2hash::Plugins.constants.each do |name| @plugins << ::Csv2hash::Plugins.const_get(name).new(self) end rescue; end end def parse load_data_source definition.validate! definition.default! validate_data! Csv2hash::DataWrapper.new.tap do |response| if valid? fill! response.data = data[:data] else response.valid = false response.errors = csv_with_errors notifier.notify response end end end def csv_with_errors @csv_with_errors ||= begin CsvArray.new.tap do |rows| errors.each do |error| rows << error.merge({ value: (data_source[error[:y]][error[:x]] rescue nil) }) end end #.to_csv end end # protected def data_source @data_source ||= CSV.read self.file_path end alias_method :load_data_source, :data_source private def dynamic_lib_loading type case definition.type when Csv2hash::Definition::MAPPING self.extend Module.module_eval("Csv2hash::#{type}::Mapping") when Csv2hash::Definition::COLLECTION self.extend Module.module_eval("Csv2hash::#{type}::Collection") end end end
true
6a8b05342bf73dd9b97740a79b8f0ee728ed7480
Ruby
YizheWill/aA_Homework
/W4D2/Simon/lib/simon.rb
UTF-8
1,022
3.671875
4
[]
no_license
class Simon COLORS = %w(red blue green yellow) attr_accessor :sequence_length, :game_over, :seq def initialize @sequence_length = 1 @game_over = false @seq = [] end def play p "let's play the game" until game_over take_turn end game_over_message reset_game end def take_turn show_sequence unless game_over require_sequence unless game_over round_success_message unless game_over @sequence_length += 1 end def show_sequence add_random_color p @seq sleep 3 system("clear") end def require_sequence p "Please tell me what was on the screen" res = gets.chomp() res = res.split(" ") @game_over = true if res != seq end def add_random_color seq << COLORS.sample end def round_success_message p "Ok congrats, you finished this round" end def game_over_message p "eh-oh pratice makes perfect" end def reset_game @sequence_length = 1 @game_over = false @seq = [] end end
true
92c5ffa1d492eebb8d0f4c7f80cf2192eb978b21
Ruby
cstrynatka/ruby_fundamentals1
/exercise1.rb
UTF-8
1,019
4.21875
4
[]
no_license
puts 2 != 3 puts 2 puts 3 puts 2 != 3 puts 2 puts 3 puts 2 != 3 # puts 2 puts 3 puts 2 != 3 puts "Enter name" name = gets.chomp puts "Your name is #{name}" a = 20 b = 65 puts "The value of a is #{a}." #The value of a is 20 puts "The value of a is #{b}." #The value of a is 65 puts "The value of a plus b is #{a + b}." #The value of a plus b is 85 puts 2 != 3 puts 55.0 * 1.15 #Calculating a tip at a restaurant puts 55.0 * 1.20 #Calculating a really good tip at a restaurant by tipping 20% puts "hello world, here I am" #String to be added to an integer puts "6" #Integer to be added to a string puts "hello world, here I am #{6}" puts 45628 * 7839 puts "45628 * #{7839}" puts (true && false) || (false && true) || !(false && false) myvar = 'myvar is now this string' myvar # myvar is now this string amount = 20 new_amount = amount new_amount #20 amount = "twenty" amount # "twenty" new_amount #20 variable #undefined local variable or method 'variable for main:Object' variable = variable || default value
true
ff64d998a2990443db466ae7d5357b05f45349c6
Ruby
cowlibob/armadillo
/lib/armadillo/project.rb
UTF-8
393
2.71875
3
[]
no_license
require 'armadillo/certificate' require 'inifile' class Project def initialize end def load( project_path ) @data = IniFile::load( project_path ) end def certificates re = /Project#Certificate\d$/ certs = @data.match( re ).collect{ |cert_data| Certificate.new(self, cert_data) } return certs end def version @data['Project']['Version'].to_i end end
true
88561889bec8f18acbfee093f1f75a45a063111b
Ruby
DianaM10/ccc
/room.rb
UTF-8
584
3.171875
3
[]
no_license
class Room attr_reader(:name, :songs, :guests) def initialize(name) @name = name @songs = [] @guests = [] end def check_in_one_guest(a_guest) @guests << a_guest end def add_a_song(a_song) @songs << a_song end # def add_songs_to_room(all_songs) # @songs << all_songs # @songs.flatten! # return @songs.map! { |item| item.artist && item.title } # end def check_in_more_than_one_guest(all_guests) @guests << all_guests @guests.flatten! return @guests.map! { |guest| guest.name} end end
true
9c0e2ff42d3cf90b9c9a1fe3dfad11fe5767a8fc
Ruby
Loris1123/RbScheme
/test/symboltable.rb
UTF-8
1,615
3.03125
3
[ "Beerware" ]
permissive
require_relative "../lang/symboltable" require_relative "../lang/objects" module SymboltableTest def self.test raise "Symboltable should be empty" unless Symboltable.fill_level == 0 Symboltable.get_or_add("foo") raise "Symboltable fill_level should be 1, is #{Symboltable.fill_level}" unless Symboltable.fill_level == 1 Symboltable.get_or_add("foo") raise "Symboltable fill_level should be 1, is #{Symboltable.fill_level}" unless Symboltable.fill_level == 1 Symboltable.get_or_add("bar") raise "Symboltable fill_level should be 2, is #{Symboltable.fill_level}" unless Symboltable.fill_level == 2 Symboltable.reset raise "Symboltable should be empty" unless Symboltable.fill_level == 0 a = Symboltable.get_or_add("foo") b = Symboltable.get_or_add("foo") raise "Symbols should be SchemeSymbol, is #{a.class}" unless a.class == SchemeSymbol raise "Symbols should be the same objects" unless a.object_id == b.object_id # Reshash (1..500).each do |n| Symboltable.get_or_add("Foobar#{n}") end # 501 because I putted one Item before. Attention: there is a reset in between raise "Filllevel should be 501. Is #{Symboltable.fill_level}" unless Symboltable.fill_level == 501 # Use a reference before reshash # get a new b reference after reshash. # Should stillbe the same object_id b = Symboltable.get_or_add("foo") raise "Symbols should be SchemeSymbol, is #{a.class}" unless a.class == SchemeSymbol raise "Symbols should be the same objects" unless a.object_id == b.object_id # Reset to start with a new symboltable after the tests Symboltable.reset end end
true
5144c3144e2462a708f6990287abea0b6e56d837
Ruby
alu0100600643/Practica12
/spec/rspec_p8_spec.rb
UTF-8
3,027
3.25
3
[ "MIT" ]
permissive
#Realizado por Daura Hernández Díaz y Miguel Aurelio García González require "matriz.rb" require "fraccion.rb" describe MatrizDensa do before :each do @matriz = MatrizDensa.densa([[8, 16], [21, 34]]) @matriz2 = MatrizDensa.densa([[1, 2], [3, 4]]) @m1 = MatrizDensa.densa([[Fraccion.new(1, 2), Fraccion.new(3, 4)], [Fraccion.new(3, 4), Fraccion.new(1, 2)]]) @m2 = MatrizDensa.densa([[Fraccion.new(5, 6), Fraccion.new(7, 8)], [Fraccion.new(7, 8), Fraccion.new(5, 6)]]) end it " Primer elemento de la matriz " do @matriz.pos(0, 0).should == 8 end it " Segundo elemento de la matriz " do @matriz.pos(0, 1).should == 16 end it " Tercer elemento de la matriz " do @matriz.pos(1, 0).should == 21 end it " Cuarto elemento de la matriz " do @matriz.pos(1, 1).should == 34 end it "Suma " do ((@matriz + @matriz2).m).should == [[9, 18], [24, 38]] end it "Resta " do ((@matriz - @matriz2).m).should == [[7, 14], [18, 30]] end it "Multiplicacion" do ((@matriz * @matriz2).m).should == [[56, 80], [123, 178]] end it "Fraccion" do ((@m1 + @m2).m).should == [["4/3", "13/8"], ["13/8", "4/3"]] end it "Fraccion" do ((@m1 + @m2).m).should == [["4/3", "13/8"], ["13/8", "4/3"]] end it "Elemento maximo" do @matriz.max.should == 34 end it "Elemento minimo" do @matriz.min.should == 8 end end describe MatrizDispersa do before :each do @m3 = MatrizDispersa.new([1, 2,3], [1, 2, 3], [1, 2, 3]) @m4 = MatrizDispersa.new([1, 2,3], [1, 2, 3], [1, 2, 3]) end it "Primer elemento de la matriz" do (@m3.pos(1, 1)).should == 1 end it "Segundo elemento" do (@m3.pos(2, 2)).should == 2 end it "Suma de matrices" do (@m3 + @m4).valores.should == [2, 4, 6] end it "Resta de matrices" do (@m3 - @m4).valores.should == [0, 0, 0] end it "Valor maximo" do @m3.max.should == 3 end it "Valor minimo" do @m3.min.should == 1 end it "Multiplicacion" do (@m3 * @m4).valores.should == [1, 4, 9] end end describe MatrizDensa do before :each do @m3 = MatrizDispersa.new([0, 1], [0, 1], [1, 2]) @m4 = MatrizDispersa.new([0, 1], [0, 1], [1, 2]) @matriz = MatrizDensa.densa([[8, 16], [21, 34]]) @matriz2 = MatrizDensa.densa([[1, 2], [3, 4]]) @m1 = MatrizDensa.densa([[Fraccion.new(1, 2), Fraccion.new(3, 4)], [Fraccion.new(3, 4), Fraccion.new(1, 2)]]) @m2 = MatrizDensa.densa([[Fraccion.new(5, 6), Fraccion.new(7, 8)], [Fraccion.new(7, 8), Fraccion.new(5, 6)]]) @matden = MatrizDensa.densa([[Fraccion.new(1, 2), 4], [5, 6]]) @matdis = MatrizDispersa.new([1], [1], [Fraccion.new(1, 2)]) end it "Suma de dispersa con densa" do ((@m3 + @matriz).m).should == [[9,16], [21, 36]] end it "Suma de Densa y dispersa" do ((@matriz + @m3).m).should == [[9,16], [21, 36]] end it "Suma con fracciones" do ((@matden + @matdis).m).should == [[Fraccion.new(2,2), 4], [5, "13/2"]] end end
true
1b4636872ad1645d2f31b51d34859dc102b5bf43
Ruby
csbenge/depot_v2_rails3
/app_script/api/api.rb
UTF-8
3,017
2.671875
3
[]
no_license
################################################################################ # Copyright @ 2012,2013 CloudDepot, Inc. # # All Rights Reserved # ################################################################################ #======================================# # API.rb - Cloud Depot API/CLI #======================================# #----------------------------# # init_API() #----------------------------# def init_API() end #----------------------------# # process_CMD() #----------------------------# def process_CMD(argv) case argv[0] when "login" process_Login_CMD(argv) when "depot" process_Depot_CMD(argv) when "package" process_Package_CMD(argv) when "artifact" process_Artifact_CMD(argv) when "instance" process_Instance_CMD(argv) when "credential" process_Credential_CMD(argv) else # Display Help STDOUT.puts "\nUsage: cd_api COMMAND OPTIONS..." STDOUT.puts "" STDOUT.puts "Commands:" STDOUT.puts " login username password" STDOUT.puts " depot [create|destroy|modify] [options]" STDOUT.puts " package [create|destroy|modify] [options]" STDOUT.puts " artifact [create|destroy|modify] [options]" STDOUT.puts " instance [create|destroy|modify] [options]" STDOUT.puts " credential [create|destroy|modify] [options]" end end #----------------------------# # process_Login_CMD() #----------------------------# def process_Login_CMD(argv) if argv[2] STDOUT.puts "login user=" + argv[1] + ", password=" + argv[2] else # Display Help STDOUT.puts "\nUsage: cd_api login USERNAME PASSWORD" end end #----------------------------# # process_Depot_CMD() #----------------------------# def process_Depot_CMD(argv) case argv[1] when "list" process_Depot_List_CMD(argv) else # Display Help STDOUT.puts "\nUsage: cd_api depot COMMAND OPTIONS..." STDOUT.puts "" STDOUT.puts "Commands:" STDOUT.puts " depot create [options]" STDOUT.puts " depot destroy [options]" STDOUT.puts " depot modify [options]" STDOUT.puts " depot list [options]" end end def process_Depot_List_CMD(argv) if argv[2] STDOUT.puts "\nPackages in Depot: " + argv[2] else STDOUT.puts "depot list all" # packages = findAll() STDOUT.puts "<<END>>" end end #----------------------------# # process_Package_CMD() #----------------------------# def process_Package_CMD(argv) STDOUT.puts "package create" end #----------------------------# # process_Artifact_CMD() #----------------------------# def process_Artifact_CMD(argv) STDOUT.puts "package create" end #----------------------------# # process_Instance_CMD() #----------------------------# def process_Instance_CMD(argv) STDOUT.puts "instance create" end ############################## # main ############################## init_API() process_CMD(ARGV)
true
c98bec66c00174dc92c6d2714c68c89da99d5e4e
Ruby
antwolfe/Launch-School
/RB101/Exercises/Small-Problems/Easy1/Repeat_Yourself.rb
UTF-8
550
4.90625
5
[]
no_license
# Write a method that takes two arguments, a string and a positive integer, # and prints the string as many times as the integer indicates. # Problem: # **Rules** # - Method # - Takes two arguments # - Input: a string, a positive integer # - Output: string or multiple strings # - Must output string according to integer arguments # **Examples** # repeat('Hello', 3) --> # Hello # Hello # Hello # **Data Structure** # String # **Algorithm** def repeat(input_str, number) number.times {puts input_str} end repeat('Hello', 3)
true
f5a3372900929724a94c67d8b7b8e282e16fe2b1
Ruby
JasonPKnoll/relational_rails
/spec/features/artists/index_spec.rb
UTF-8
4,852
2.6875
3
[]
no_license
require 'rails_helper' RSpec.describe 'the artists index page' do # => Story 1 # => As a visitor # => When I visit '/artists' # => I see the name of each artist record in the system it 'displays all artists names' do artist = Artist.create!(name: "Povi", description: "From scratch avatar creator", years_experience: 10, comissions_open: false) visit "/artists" #localhost:3000/artist expect(page).to have_content(artist.name) end # => Story 6 # => As a visitor # => When I visit '/artists' # => I see the name of each artist by most recently created it 'displays all artists by most recently created' do povi = Artist.create!(name: "Povi", description: "From scratch avatar creator", years_experience: 10, comissions_open: false) megan = Artist.create!(name: "Megan", description: "3D artists", years_experience: 2, comissions_open: true) srgrafo = Artist.create!(name: "SrGrafo", description: "digital artists", years_experience: 5, comissions_open: false) visit "/artists" expect(page).to have_content(povi.name) expect(page).to have_content(megan.name) expect(page).to have_content(srgrafo.name) expect("Megan").to appear_before("Povi") expect("SrGrafo").to appear_before("Megan") end it 'displays artists index link on all pages' do # => Story 9 # => As a visitor # => When I visit any page # => I see a link at the top of the page that takes me to artists index visit "/" # welcome page expect(page).to have_link("Artist Index") visit "/artworks" expect(page).to have_link("Artist Index") visit "/artists" expect(page).to have_link("Artist Index") visit "/easteregg" expect(page).to have_link("Artist Index") end describe 'can create a new artist' do # Story 11 # As a visitor # When I visit the ARTIST Index page # Then I see a link to create a new ARTIST record, "New ARTIST" # When I click this link # Then I am taken to '/artists/new' where I see a form for a new artist record # When I fill out the form with a new artist's attributes: # And I click the button "Create ARTIST" to submit the form # Then a `POST` request is sent to the '/artists' route, # a new artist record is created, # and I am redirected to the ARTIST Index page where I see the new ARTIST displayed. it 'can link to new artist from artists index' do visit "/artists" click_link "New Artist" expect(page).to have_content("Name") expect(page).to have_content("Description") expect(page).to have_content("Years Experience") expect(page).to have_content("Are Comissions Open?") end it 'can create a new artist' do visit "/artists/new" fill_in "name", with: "Megan" fill_in "description", with: "3D avatar creator" click_button "Create Artist" expect(current_path).to eq("/artists") expect(page).to have_content("Megan") end end it 'can update artists from index page' do # User Story 17, Artist Update From Artist Index Page (x2) # As a visitor # When I visit the artist index page # Next to every artist, I see a link to edit that artist's info # When I click the link # I should be taken to that artists edit page where I can update its information just like in User Story 4 megan = Artist.create!(name: "Meg", description: "3D artists", years_experience: 2, comissions_open: true) srgrafo = Artist.create!(name: "SrGrafo", description: "digital artists", years_experience: 5, comissions_open: false) visit "/artists/" click_link "Edit Meg" fill_in "name", with: "Megan" click_button "Update Artist" expect(current_path).to eq("/artists/#{megan.id}") expect(page).to have_content("Megan") end it "can delete from index" do # User Story 22, Artist Delete From Artist Index Page (x1) # As a visitor # When I visit the artist index page # Next to every artist, I see a link to delete that artist # When I click the link # I am returned to the Artist Index Page where I no longer see that artist megan = Artist.create!(name: "Megan", description: "3D artists", years_experience: 2, comissions_open: true) visit "/artists/" click_link "Delete Megan" expect(page).to_not have_content("Megan") end end
true
8d6f42929d7aa49cc00eb576387d9e9a8fc3eb3e
Ruby
shuhei/webland-scraper
/export.rb
UTF-8
356
2.890625
3
[]
no_license
require 'json' require './database' db = Database.new isFirst = true print '[' db.places.find.each do |place| lat = place['lat'] lng = place['lng'] price = place['price'] next if lat.nil? || lng.nil? || lat == 0 || lng == 0 || price.nil? if isFirst isFirst = false else print ',' end print "#{lat},#{lng},#{price}" end print ']'
true
a100aeac8d7036e4a12b2b81ef338834951de726
Ruby
emanon001/atcoder-ruby
/abc158/b/main.rb
UTF-8
108
2.703125
3
[]
no_license
N, A, B = gets.split.map(&:to_i) c = N / (A + B) rest = N - (A + B) * c ans = A * c + [rest, A].min puts ans
true
43b88a6edb5d17b86a107455cac14d3dd8f78468
Ruby
unheavenlycreature/tic-tac-toe
/tic_tac_toe_manager.rb
UTF-8
2,197
3.984375
4
[]
no_license
# frozen_string_literal: true require_relative 'player' require_relative 'board' # Mediates a game of Tic-Tac-Toe. class TicTacToeManager POSITION_HASH = { UL: [0, 0], UM: [0, 1], UR: [0, 2], ML: [1, 0], MM: [1, 1], MR: [1, 2], BL: [2, 0], BM: [2, 1], BR: [2, 2] }.freeze def play_game @player_one, @player_two = create_players @curr_player = choose_first_player @board = TicTacToeBoard.new @remaining_turns = 9 next_turn until game_over? end private def create_players puts "Player One, you will play as 'X'. What is your name?" player_one = TicTacToePlayer.new(gets.chomp, 'X') puts "Player Two, you will play as 'O'. What is your name?" player_two = TicTacToePlayer.new(gets.chomp, 'O') [player_one, player_two] end def choose_first_player first_player = rand(2).zero? ? @player_one : @player_two puts "Congrats, #{first_player.name}, you're going first!" first_player end def switch_current_player @curr_player = @curr_player == @player_one ? @player_two : @player_one end def game_over? if @remaining_turns > 5 switch_current_player false elsif @board.three_consecutive? @curr_player.sigil puts @board puts "Congrats, #{@curr_player.name}, you win!" true elsif @remaining_turns.zero? puts @board puts 'Looks like a tie!' true else switch_current_player false end end def next_turn puts @board puts "#{@curr_player.name}, please make your move." row, col = get_valid_position @board.add_piece(@curr_player.sigil, row, col) @remaining_turns -= 1 end def get_valid_position position = gets.chomp.upcase.to_sym until valid_position? position puts @board puts "#{@curr_player.name}, that isn't a valid position. Please try again." position = gets.chomp.upcase.to_sym end POSITION_HASH[position] end def valid_position?(position) if POSITION_HASH.keys.include? position row, col = POSITION_HASH[position] @board.space_available?(row, col) else false end end end TicTacToeManager.new.play_game
true
a8ff81d4ebef027690ecd5e8e3738256ea171b47
Ruby
watmin/zombie_battleground-api
/lib/zombie_battleground/api/requests/get_matches_request.rb
UTF-8
3,414
2.609375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'active_record' require 'zombie_battleground/api/validation_helper' require 'zombie_battleground/api/requests/request_helper' module ZombieBattleground class Api class Requests ## # Request validator for GetMatches class GetMatchesRequest include ActiveModel::Validations include ZombieBattleground::Api::ValidationHelper include ZombieBattleground::Api::Requests::RequestHelper ## # @!attribute [r] id # Optionally set the Match's id for filtered querying # # @return [Integer] # # @example # request.id #=> 1 # # @api public attr_accessor :id ## # @!attribute [r] player1_id # Optionally set the Match's player1_id for filtered querying # # @return [String] # # @example # request.player1_id #=> "ZombieSlayer_16601021609396167139295300949176" # # @api public attr_accessor :player1_id ## # @!attribute [r] player2_id # Optionally set the Match's player2_id for filtered querying # # @return [String] # # @example # request.player2_id #=> "ZombieSlayer_16601021609396167139295300949176" # # @api public attr_accessor :player2_id ## # @!attribute [r] status # Optionally set the Match's status for filtered querying # # @return [String] # # @example # request.status #=> "Ended" # # @api public attr_accessor :status ## # @!attribute [r] version # Optionally set the Match's version for filtered querying # # @return [String] # # @example # request.version #=> "v3" # # @api public attr_accessor :version ## # @!attribute [r] winner_id # Optionally set the Match's winner_id for filtered querying # # @return [String] # # @example # request.winner_id #=> "ZombieSlayer_16601021609396167139295300949176" # # @api public attr_accessor :winner_id ## # @!attribute [r] page # Optionally set the page number for filtered querying # # @return [Integer] # # @example # request.page #=> 1 # # @api public attr_accessor :page ## # @!attribute [r] limit # Optionally set the limit for max Matches returned # # @return [Integer] # # @example # request.limit #=> 100 # # @api public attr_accessor :limit validate :id_is_a_non_negative_integer validate :player1_id_is_a_string validate :player2_id_is_a_string validate :status_is_a_string validate :version_is_a_string validate :winner_id_is_a_string validate :page_is_a_non_negative_integer validate :limit_is_a_non_negative_integer ## # The URI for the endpoint # # @return [String] # # @example # request.uri # => "matches" # # @api public def uri 'matches' end end end end end
true
495c4fddb352bcc3e5f3c8cfbcd13101fab55275
Ruby
krekoten/brain_love
/lib/brain_love/parser.rb
UTF-8
991
2.59375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'parslet' module BrainLove class Parser < Parslet::Parser rule(:increment_pointer) { str('>').as(:increment_pointer) } rule(:decrement_pointer) { str('<').as(:decrement_pointer) } rule(:increment_byte) { str('+').as(:increment_byte) } rule(:decrement_byte) { str('-').as(:decrement_byte) } rule(:output_byte) { str('.').as(:output_byte) } rule(:input_byte) { str(',').as(:input_byte) } rule(:jump_forward) { str('[') } rule(:jump_backward) { str(']') } rule :command do increment_pointer | decrement_pointer | increment_byte | decrement_byte | output_byte | input_byte end rule :comment do (command | jump_forward | jump_backward).absnt? >> any.as(:comment) end rule :_loop do (jump_forward >> root >> jump_backward).as(:loop) end rule :root do (comment | command | _loop).repeat.as(:statements) end end end
true
1df00b4ef9f8332b3cc50d94d5722ecfe000e627
Ruby
zpatten/sockit
/lib/sockit/v5/support.rb
UTF-8
2,612
2.71875
3
[ "Apache-2.0" ]
permissive
module Sockit module V5 module Support # 0x00 = request granted # 0x01 = general failure # 0x02 = connection not allowed by ruleset # 0x03 = network unreachable # 0x04 = host unreachable # 0x05 = connection refused by destination host # 0x06 = TTL expired # 0x07 = command not supported / protocol error # 0x08 = address type not supported def build_v5_result_code_message(result_code) message = case result_code when 0x00 then "Request granted" when 0x01 then "General failure" when 0x02 then "Connection not allowed by ruleset" when 0x03 then "Network unreachable" when 0x04 then "Host unreachable" when 0x05 then "Connection refused by destination host" when 0x06 then "TTL expired" when 0x07 then "Command not supported / Protocol error" when 0x08 then "Address type not supported" else "Unknown" end "%s (Code: 0x%02X)" % [message, result_code] rescue "Result Code: #{result_code.inspect}" end # The authentication methods supported are numbered as follows: # 0x00: No authentication # 0x01: GSSAPI[10] # 0x02: Username/Password[11] # 0x03-0x7F: methods assigned by IANA[12] # 0x80-0xFE: methods reserved for private use def build_v5_authentication_method_message(auth_method) message = case auth_method when 0x00 then "No authentication" when 0x01 then "GSSAPI authentication" when 0x02 then "Username/Password authentication" when 0x03..0x7F then "Authentication method assigned by IANA" when 0x80..0xFE then "Authentication method reserved for private use" when 0xFF then "Unsupported authentication" else "Unknown authentication" end "%s (Method: 0x%02X)" % [message, auth_method] rescue "Authentication Method: #{auth_method.inspect}" end # 0x00 = success # any other value = failure, connection must be closed def build_v5_authentication_status_message(auth_status) message = case auth_status when 0x00 then "Authentication success" else "Authentication failure" end "%s (Status: 0x%02X)" % [message, auth_status] rescue "Authentication Status: #{auth_status.inspect}" end end end end
true
355ef540ee67609e27e5e8802e7302259f4a0aa1
Ruby
thesteady/warmup-exercises
/01-99-bottles/beer_example.rb
UTF-8
887
4.375
4
[]
no_license
class Beer def self.verse puts "#{@number} bottles of #{@drink} on the wall, #{@number} bottles of #{@drink}." puts "Take one down and pass it around, #{@number-1} bottles of #{@drink} on the wall." end def self.song printf "How many bottles will you start with?" @number = gets.chomp.to_i printf "What are you drinking?" @drink = gets.chomp while @number > 1 puts verse @number -= 1 end if @number > 1 puts verse @number -= 1 else puts "#{@number} bottles of #{@drink} on the wall, #{@number} bottles of #{@drink}." puts "Take one down and pass it around, no more bottles of beer on the wall." puts "\nNo more bottles of #{@drink} on the wall, no more bottles of #{@drink}." puts "Go to the store and buy some more, #{@number} bottles of #{@drink} on the wall." end end end Beer.song
true
77b3880a7550bb6bc30a679e8df25e8c002b6d41
Ruby
walter-petkanych/lessons
/equation.rb
UTF-8
1,342
3.671875
4
[]
no_license
#вітання puts('Hello, enter a') #отримую значення, конвертую в цифру і присвоюю значення змінній a = gets().chomp().to_f() puts('enter b') b = gets().chomp().to_f() puts('enter c') c = gets().chomp().to_f() #перевіряю що значееня змінної "а" дорівнює "0" і вивожу помилку if(a == 0) puts('ERROR') exit() #TODO після цього треба зупинити програму! end #вираховую значення дискримінанту d = ((b ** 2) - (4 * a * c)) #вивожу значення дискримінанту puts(d) #якщо значення "Д" більше "0" то вираховую оба "Х" if(d > 0) #вираховую "Х1" x1 = ((-b + Math.sqrt(d)) / (2 * a)) #вираховую "Х2" x2 = ((-b - Math.sqrt(d)) / (2 * a)) puts('D = ' + d.to_s()) puts('X1 = ' + x1.to_s()) puts('X2 = ' + x2.to_s()) #якщо значення "Д" дорівнює "0" то вираховую один "Х" elsif(d == 0) x1 = ((-b + 0) / (2 * a)) x2 = ((-b - 0) / (2 * a)) puts('D = ' + d.to_s()) puts('X1 = ' + x1.to_s()) puts('X2 = ' + x2.to_s()) #в інших випадках виводить цей текст else puts('D < 0') end
true