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
23b7f19ade11f7b58f58b6fec4ecd143d1512244
Ruby
nitsujri/confucius-say
/lib/one_offs/process_scrape.rb
UTF-8
2,888
2.8125
3
[]
no_license
class OneOffs class ProcessScrape START_LINE = 0 def process data = gather_data data.drop(START_LINE).each_with_index do |d, i| scrape_data = d.data[:canto_dict] extract_char_data(d) # extract_compounds(scrape_data) break end # process_examples end def process_examples #We want to go over them separately AFTER we've run through all the compounds so it is easier to link. data.each_with_index do |d, i| extract_examples(scrape_data) end end def gather_data ExtraData.all end ############### Extraction Handling ############### def extract_char_data(full_data) orig_word = full_data.storable scrape_data = full_data.data[:canto_dict] unless orig_word.more_info.present? orig_word.build_more_info( part_of_speech: scrape_data[:part_of_speech], stroke_count: scrape_data[:stroke_count].match(/[0-9].*/).to_s, radical: scrape_data[:radical].strip, level: scrape_data[:level], ).save end end def extract_compounds(data) compounds_data = data[:compounds] compounds = compounds_data[:the_compounds] #rebuild compound compounds.each do |compound_data| word = insert_compound(compound_data) #Link the subwords based on their compounds link_compound_subwords(word, compound_data) end end def extract_examples(data) end ################ Main Insert Functions ############### def insert_compound(compound_data) chars_trad = [] chars_simp = [] pinyin = [] compound_data[:chars_trad].each do |char_data| root_char = Word.find_by(chars_trad: char_data[:char_trad]) chars_trad << root_char.chars_trad chars_simp << root_char.chars_simp pinyin << root_char.pinyin end #load data word = Word.where( chars_trad: chars_trad.join, chars_simp: chars_simp.join, ).first_or_create word.update_attributes({ :jyutping => compound_data[:jyutping], :pinyin => pinyin.join(" "), :english => compound_data[:english] }) WordData.where( :word_id => word.id, :usage => compound_data[:usage] ).first_or_create word end def link_compound_subwords(word, compound_data) #find individual chars, create link from compound => subword compound_data[:chars_trad].each do |char_data| subword = Word.find_by(chars_trad: char_data[:char_trad]) word.subword_word_links.create(word_id: subword.id) end end class << self def go #OneOffs::ProcessScrape.go OneOffs::ProcessScrape.new.process end end #self end#process scrape end
true
75f5969e908f6021141f6cd07daa8cee9148ae0e
Ruby
UbuntuEvangelist/therubyracer
/vendor/cache/ruby/2.5.0/gems/powerpack-0.1.2/spec/powerpack/string/remove_prefix_spec.rb
UTF-8
629
2.78125
3
[ "MIT" ]
permissive
require 'spec_helper' describe 'String#remove_prefix' do it 'removes a prefix in a string' do expect('Ladies Night'.remove_prefix('Ladies ')).to eq('Night') end it 'returns the original string if the parameter is not a prefix' do expect('Ladies Night'.remove_prefix('Night')).to eq('Ladies Night') end end describe 'String#remove_prefix!' do it 'removes a prefix in a string' do expect('Ladies Night'.remove_prefix!('Ladies ')).to eq('Night') end it 'returns the original string if the parameter is not a prefix' do expect('Ladies Night'.remove_prefix!('Night')).to eq('Ladies Night') end end
true
fac5f7c600009e6a08fef8329cbe3a89a738a064
Ruby
AugustoPresto/LP-Store
/app/views/sessions_view.rb
UTF-8
359
2.921875
3
[]
no_license
require 'io/console' class SessionsView def ask_for_username puts "What's your username?" print "> " gets.chomp end def ask_for_password puts "What's the password?" print "> " STDIN.noecho(&:gets).chomp end def login_ok puts "Welcome!" end def wrong_credentials puts "Wrong credentials. Try again!" end end
true
aae98d57ac1238a031a33a9d636573941c53cd73
Ruby
sayem/worldfactbook
/spec/worldfactbook/cli_spec.rb
UTF-8
2,081
2.6875
3
[ "MIT" ]
permissive
require File.dirname(__FILE__) + '/../spec_helper' require 'worldfactbook/cli' describe Worldfactbook::CLI, "execute" do describe "help" do before(:each) do @stdout_io = StringIO.new Worldfactbook::CLI.execute(@stdout_io, ['help']) @stdout_io.rewind @stdout = @stdout_io.read end it "should report help commands" do @stdout.should =~ /https:\/\/github.com\/sayem\/worldfactbook\/wiki/ end end describe "country list" do before(:each) do @stdout_io = StringIO.new Worldfactbook::CLI.execute(@stdout_io, ['countries']) @stdout_io.rewind @stdout = @stdout_io.read end it "should report the list of available countries" do @stdout.should =~ /List of available countries/ @stdout.should =~ /jamaica/ end end describe "country lookup" do before(:each) do @stdout_io = StringIO.new Worldfactbook::CLI.execute(@stdout_io, ['united states']) @stdout_io.rewind @stdout = @stdout_io.read end it "should report data" do @stdout.should =~ /Location: North America/ @stdout.should =~ /New York/ @stdout.should =~ /4 July 1776/ @stdout.should =~ /Population/ @stdout.should =~ /English/ @stdout.should =~ /white/ @stdout.should =~ /Protestant/ @stdout.should =~ /0-14 years:/ @stdout.should =~ /age 15 and over can read and write/ @stdout.should =~ /GDP:/ @stdout.should =~ /GDP \(PPP\):/ @stdout.should =~ /GDP growth:/ @stdout.should =~ /GDP sectors:/ @stdout.should =~ /Debt:/ @stdout.should =~ /Unemployment:/ @stdout.should =~ /Inflation:/ @stdout.should =~ /Telephone Users:/ @stdout.should =~ /Mobile Phone Users:/ @stdout.should =~ /Internet Users:/ end end describe "country lookup parameter" do it "should detect parameter" do expect { Worldfactbook::CLI.execute(@stdout_io, ['united states population']) }.should raise_error(Worldfactbook::NoCountryAvailable) end end end
true
01f8cc659a53a2d9ee4734c39899891f3cf488ed
Ruby
zhouqinp/robot
/robot.rb
UTF-8
4,953
3.578125
4
[]
no_license
class Robot def initialize(name) @name = name @x = "NA" @y = "NA" @f = "NA" @ontable = false end # set some arrays for faces @@facelist = ["SOUTH", "NORTH", "EAST", "WEST"] @@facemove = [["SOUTH", 0, -1], ["NORTH", 0, 1], ["EAST", 1, 0], ["WEST", -1, 0]] @@turnlist = ["LEFT", "RIGHT"] @@faceleft = ["EAST", "NORTH", "WEST", "SOUTH", "EAST"] @@faceright = ["EAST", "SOUTH", "WEST", "NORTH", "EAST"] # grant access to private fields attr_accessor :name, :x, :y, :f, :ontable # check whether the robot is on the table, change @ontable, return true/false def isontable? if @x.is_a?(Integer) && @y.is_a?(Integer) && @x.between?(0, 5) && @y.between?(0, 5) && @f.is_a?(String) && @@facelist.include?(@f) @ontable = true else @ontable = false end @ontable end # check the place parameters and check whether the robot is on the table, change @x, @y, @f, @ontable, tolerance to Upper/lowercase def place(numx, numy, facef) #raise "The x, y coordinates are not valid!" if numx.integer? #&& numy.integer? && numx >= 0 && numy >= zero #raise "The face is not valid!" unless facef.is_a?(String) if numx.is_a?(Integer) && numy.is_a?(Integer) && numx.between?(0, 5) && numy.between?(0, 5) && facef.is_a?(String) && @@facelist.include?(facef.upcase) @x = numx @y = numy @f = facef.upcase isontable? puts "The toy is placed." else puts "The coordinates or face is not valid!" end end # check the face and required move, prohibit danger move, check @x+xmove, @y+ymove, change @x, @y def move if @ontable xmove = @@facemove[@@facelist.index(@f)][1] ymove = @@facemove[@@facelist.index(@f)][2] if (@x + xmove).between?(0, 5) && (@y + ymove).between?(0, 5) @x += xmove @y += ymove puts "This move " + @f + " is completed." else puts "WARNING! This move " + @f + " is prohibited!" end else puts "WARNING! This move " + @f + " is prohibited!" end end # turn left or right, change @f def turn(turnLR) if @ontable && turnLR.is_a?(String) && @@turnlist.include?(turnLR.upcase) case turnLR.upcase when @@turnlist[0] # case turn left @f = @@faceleft[@@faceleft.index(@f) + 1] puts "This turn " + turnLR.upcase + " is completed." when @@turnlist[1] # case turn right @f = @@faceright[@@faceright.index(@f) + 1] puts "This turn " + turnLR.upcase + " is completed." else "WARNING! This turn " + turnLR.upcase + " is prohibited!" end else puts "WARNING! This turn " + turnLR.upcase + " is prohibited!" end end # check whether the robot is on the table and report the @x, @y, @f def report if @ontable printf "Output: %d, %d, %s\n", @x, @y, @f printf "REPORT: The robot is now on position(%d, %d) with face to the %s.\n", @x, @y, @f else puts "WARNING! This report is prohibited!" end end # check if a string is an integer with "", return true/false def checkInt(s) /\A[-+]?\d+\z/ === s end # read a local file of command, and create an string[] of commandlines def readFile(filename) # create an string[] of commnadlines commandlines = [] # open file command_file = File.open(filename) #raise "WARNING! The file is not valid!" File.open(filename) do |f| f.each_line do |line| commandlines << line.gsub("\n", "") end end # return an string[] return commandlines rescue SystemCallError => e puts e.class.name puts e.message false else puts "File is loaded." ensure command_file.close if command_file end # execute commandlines one by one def runCommand(commandlines) commandlines.each {|commandline| convertCommand(commandline)} return true rescue SystemCallError => e puts e.class.name puts e.message false end # convert command string to call methods, torlerance to upper/lowercase def convertCommand(commandline) command = commandline.split # command place if command[0].upcase == @@commandlist[0] && command.length == 2 paras = command[1].split(',') # check if paras is valid if checkInt(paras[0]) && checkInt(paras[1]) place(paras[0].to_i, paras[1].to_i, paras[2]) #place parameters else puts "WARNING! The coordinates are not valid!" end # other commands when ontable elsif @ontable && command.length == 1 && command[0].is_a?(String) && @@commandlist.include?(command[0].upcase) case command[0].upcase when @@commandlist[1] #case move move when @@commandlist[2], @@commandlist[3] #case left, right turn(command[0]) when @@commandlist[4] #case report report end else puts "WARNING! The command is not valid!" end end end
true
b801d83870852f11f18dc91a8e12cc0343da8d79
Ruby
antonylao/intro_to_ruby
/exercises/hash_creation_8.rb
UTF-8
103
3.046875
3
[]
no_license
h = {key: "value"} puts h h2 = {:key => "value!"} puts h2 h3 = Hash.new() h3[:key] = "value!!" puts h3
true
36d0b42c953eed9447a963673b193736a4f9f2f3
Ruby
linuxcat/dashBoard
/child_class.rb
UTF-8
394
2.546875
3
[]
no_license
require_relative './parent_class' class ChildClass < ParentClass element :title, "text_locator" element :login, "this is a login" class << self def title? title end end end child = ChildClass.new child.login ChildClass.title? array = "Done signing the test server. Moved it to test_servers/f07329c48c54fef51ff6bf2492d47998_0.4.20.apk".split("to ") puts array[1]
true
9a659fa7999f667090211b922e23bf8cafa78582
Ruby
doahuang/aA-projects
/w2d2/board.rb
UTF-8
2,693
3.4375
3
[]
no_license
require_relative 'piece' class Board def initialize @grid = Array.new(8){ Array.new(8){ NullPiece.instance } } test_piece end def test_piece rook = [ [0,0], [0,7], [7,0], [7,7] ] rook.each do |pos| self[pos] = Rook.new(pos, self, :black) if pos.first == 0 self[pos] = Rook.new(pos, self, :white) if pos.first == 7 end bishop = [ [0,2], [0,5], [7,2], [7,5] ] bishop.each do |pos| self[pos] = Bishop.new(pos, self, :black) if pos.first == 0 self[pos] = Bishop.new(pos, self, :white) if pos.first == 7 end pos = [0,3] self[pos] = Queen.new(pos, self, :black) pos = [7,3] self[pos] = Queen.new(pos, self, :white) pos = [0,1] self[pos] = Knight.new(pos, self, :black) pos = [0,6] self[pos] = Knight.new(pos, self, :black) pos = [7,1] self[pos] = Knight.new(pos, self, :white) pos = [7,6] self[pos] = Knight.new(pos, self, :white) pos = [0,4] self[pos] = King.new(pos, self, :black) pos = [7,4] self[pos] = King.new(pos, self, :white) end def [](pos) x, y = pos grid[x][y] end def []=(pos, value) x, y = pos grid[x][y] = value end def show_grid grid end def move_piece(start_pos, end_pos) if null_piece?(start_pos) raise ArgumentError.new("There is no piece at the start position") end unless valid_move?(start_pos, end_pos) raise ArgumentError.new("Can not move to that position") end update_board(start_pos, end_pos) update_piece(end_pos) end def update_board(start_pos, end_pos) self[end_pos] = self[start_pos] self[start_pos] = NullPiece.instance end def update_piece(pos) self[pos].set_pos(pos) end def null_piece?(pos) self[pos].is_a?(NullPiece) ? true : false end def in_range?(pos) pos.all?{ |coord| coord.between?(0, 7) } end def valid_move?(start_pos, end_pos) curr_piece = self[start_pos] good_moves = curr_piece.moves in_range?(end_pos) && good_moves.include?(end_pos) end # def to_s # puts " " + (0...board.size).to_a.join(" ").colorize(:red) # board.each_with_index do |row, rowno| # puts "#{rowno} ".colorize(:red) + row.map { |piece| piece.is_a?(NullPiece) ? "_" : "X".colorize(:blue) }.join(' ') # end # # Display.new(self) # end # load 'board.rb' # board = Board.new # while true # puts board # puts 'enter your start position' # input1 = gets.chomp.split(',').map(&:to_i) # puts 'enter your end position' # input2 = gets.chomp.split(',').map(&:to_i) # board.move_piece(input1, input2) # system('clear') # end private attr_reader :grid end
true
3e9c124900db127b38ae8b9702cfdd020fe58524
Ruby
Alok255/hackerrank
/practice/algorithms/implementation/encryption/encryption.rb
UTF-8
240
3.125
3
[ "MIT" ]
permissive
input = gets.chomp width = Math.sqrt(input.length).floor height = Math.sqrt(input.length).ceil result = "" for i in 0...height do j = i while j < input.length result += input[j] j += height end result += " " end puts result
true
38fe620bb218abdef4c06e730841cb5c6030760c
Ruby
neonaddict/exception_hunter
/app/presenters/exception_hunter/error_group_presenter.rb
UTF-8
504
2.546875
3
[ "MIT" ]
permissive
module ExceptionHunter class ErrorGroupPresenter delegate_missing_to :error_group def initialize(error_group) @error_group = error_group end def self.wrap_collection(collection) collection.map { |error_group| new(error_group) } end def self.format_occurrence_day(day) day.to_date.strftime('%A, %B %d') end def show_for_day?(day) last_occurrence.in_time_zone.to_date == day.to_date end private attr_reader :error_group end end
true
d044b211754a03b8278737c6ac2121fb968c7d3c
Ruby
kragen/shootout
/website/code/fibo-ruby.code
UTF-8
967
3.015625
3
[ "BSD-3-Clause" ]
permissive
<span class="slc">#!/usr/bin/ruby</span> <span class="slc"># -*- mode: ruby -*-</span> <span class="slc"># $Id: fibo-ruby.code,v 1.12 2006-09-20 05:51:23 bfulgham Exp $</span> <span class="slc"># http://www.bagley.org/~doug/shootout/</span> <span class="kwa">def</span> <span class="kwd">fib</span><span class="sym">(</span>n) <span class="kwa">if</span> n <span class="sym">&lt;</span> <span class="num">2</span> <span class="kwa">then</span> <span class="num">1</span> <span class="kwa">else</span> <span class="kwd">fib</span><span class="sym">(</span>n-2) <span class="sym">+</span> <span class="kwd">fib</span><span class="sym">(</span>n-1) <span class="kwa">end</span> <span class="kwa">end</span> N = <span class="kwd">Integer</span><span class="sym">(</span><span class="kwc">ARGV</span><span class="sym">.</span>shift <span class="sym">||</span> <span class="num">1</span>) puts <span class="kwd">fib</span><span class="sym">(</span>N)
true
beed30aa45c5823153770bfb42e9b9fd1a8ea0ab
Ruby
evanschrager/ember-presentation
/presentation.rb
UTF-8
3,497
2.734375
3
[]
no_license
require 'slide_hero' presentation 'EmberJS-and-Rails-2.0' do slide "EmberJS" do point "A Framework for Creating Ambitious Web Applications" image "fire.gif" note " the web derives its power from the ability to bookmark and share URLs. Ember marries the tools and concepts of native GUI frameworks with support for the feature that makes the web so powerful: the URL." end slide "EmberJS" do image "ember_diagram.png" image "ember_create.png" note "Ember app uses URLs to represent every possible state in your application--In Ember, every route has an associated model-- routes query the model from their model hook, to make it available in the controller and in the template-----Controllers store application state, and they get generated automatically if you dont generate them-----views (unique situations)-----component is reusable code, isolated from other views-----template is the HTML markup, most comparable to VIEWS in Rails-----Helpers = methods you can throw inside handlebars-----COMPONENTS? HELPERS? VIEWS? HELP! -------- creation gets you application namespace, adds event listeners to the document, delegates events to views, renders application template, creates a router" end slide "Rails" do image "rails_diagram.png" end slide "The Run Loop" do image "queues.png" image "run_loop.png" note "Scenarios where you need to understand run loop= AJAX callbacks, DOM update and event callbacks, Websocket callbacks, setTimeout and setInterval callbacks, postMessage and messageChannel event handlers" end slide "Efficiency Example" do image "ember-performance.png" end slide "Ember - Pros and Cons" do point "Pros" note "Angular's (and Ember) unique and innovative features are two-way data bindings, dependency injection, easy-to-test code and extending the HTML dialect by using directives." note "Backbone.js is a lightweight MVC framework. Born in 2010, it quickly grew popular as a lean alternative to heavy, full-featured MVC frameworks such as ExtJS. This resulted in many services adopting it, including Pinterest, Flixster, AirBNB and others." list do point "Ember CLI takes grunt work out of third party add-ons" point "Has its guidance and best practices set by its core team members" point "Won't undergo a complete rewrite like Angular 2.0" end point "Cons" list do point "Helper functions make the two-way data binding much more complicated" point "More difficult to learn than AngularJS" end end slide "Ember Use Cases" do image "joined_image.jpg" note "Scaling for Javascript apps" note "We created an Ember app of our own!" end slide "Intro to Bloggly" do # media "BlogglyDemo.mov", type: video end slide "Snippets" do image "getJSON.png" image "gifscode.png" end slide "Challenges" do point "Learning Curve" point "JSON, Cross-origin resource sharing (CORS)" point "Persisting Blog Posts" point "Moving Parts - Bubbling in the DOM" end slide "The Innovator's Dilemma" do point "Rails - 80%" point "Highly interactive, app-like experiences - 20%" note "successful companies can put too much emphasis on customers' current needs, and fail to adopt new technology or business models that will meet their customers' unstated or future needs." end slide "Questions?" do image "question_mark.jpg" end end
true
c0696b6decddad45bc605a2375003b8066accdd2
Ruby
eychu/dotfiles
/roles/scripts/files/scripts/statparser.rb
UTF-8
1,185
2.875
3
[]
no_license
#!/usr/bin/env ruby # # Filter to convert my text status reports to wikitext. skip = false STDIN.read.strip.split("\n").each do |line| if skip skip = false next end case line # Lines to just drop when /^Status Report \d{2}-\d{2}-\d{4}/ skip = true when /^\s+Line items with quick descriptions./ when /^\s+a\) 'Yellow Flags'/ when /^\s+upcoming work/ when /^\s+b\) 'Red Flags'/ when /^\s+current or almost current work/ when /^\s+c\) etc - other issues that impact you/ when /^\s+in the next week, or in near future/ when /^\s+multi-week project./ when /^\s+a\) Vacations \/ Travel/ when /^\s+be gone$/ when /^\s+b\) On Call - if you're on call soon/ when /^\s+c\) Misc: anything not a & b, such as/ when /^\s+I'm getting 43 root canals/ when /^1.\s+Accomplishments - big thing/ puts '__NOTOC__' puts '==Accomplishments==' when /^2.\s+Difficulties:/ puts '==Difficulties==' when /^3.\s+Upcoming \(projected\) Milestones/ puts '==Upcoming Milestones==' when /^4.\s+Calendar/ puts '==Calendar==' when /\.\s+/ puts line.gsub!(/\.\s+/, '. ') when /^\s*$/ puts '' else puts line end end
true
3c2692063775f9c1da3f4b807efc4457013e3dff
Ruby
JonHalloran/aA-homeworks
/W2D4/Octopus.rb
UTF-8
1,369
3.890625
4
[]
no_license
fish_arr = ['fish', 'fiiish', 'fiiiiish', 'fiiiish', 'fffish', 'ffiiiiisshh', 'fsh', 'fiiiissshhhhhh'] def slug_oct(fish_arr) current_fish = "" found_better = true while found_better found_better = false fish_arr.length.times do |ind| if fish_arr[ind].length > current_fish.length current_fish = fish_arr[ind] found_better = true end end end current_fish end def dom_oct(fish_arr) fish_arr.sort_by { |el| el.length }.last end def clev_oct(fish_arr) current_fish = "" fish_arr.length.times do |ind| current_fish = fish_arr[ind] if current_fish.length < fish_arr[ind].length end current_fish end tile_arr = ["up", "right-up", "right", "right-down", "down", "left-down", "left", "left-up" ] tile_hash = { "up" => 0, "right-up" => 1, "right" => 2, "right-down" => 3, "down" => 4, "left-down" => 5, "left" => 6, "left-up" => 7 } p tile_hash def slow_dance(tile, arr) arr.index(tile) end def fast_dance(tile, tile_hash) p tile_hash tile_hash[tile] end # # p fast_dance("up", tile_hash) # p slow_dance("down", tile_arr) # fish = slug_oct(fish_arr) # p fish # p "slug #{fish}" # # fish = dom_oct(fish_arr) # p "dom_oct #{fish}" # # fish = clev_oct(fish_arr) # p "clev_oct #{fish}"
true
75920d3349e52da322f0cf9f7234ca8293a4ab36
Ruby
PopularDemand/connect-four
/lib/game.rb
UTF-8
1,069
3.734375
4
[]
no_license
# Game # - match draw (when board full) # - win condition # - player turn logic =begin public interface #new - takes attrs{ player_red, player_blue, board } #play - HP - prints welcome - send message game loop private interface #game_loop - =end class Game def initialize(player_x:, player_o:, board:) @player_x = player_x @player_o = player_o @board = board @turn_count = 1 # Odd for red, Even for Blue, at 43 game over @win = false end def play welcome game_loop end private def game_loop @board.render drop = current_player(@turn_count).get_input @board.add_piece(current_player(@turn_count).symbol, drop) check_win end def current_player(count) count % 2 == 0 ? @player_o : @player_x end def welcome puts "Welcome to Connect 4!" puts "To place a piece please type the number of the column (0-6)." puts "Press 'enter' to begin." gets end def check_win @board.four_in_a_row?(player) end end
true
b4390380c031e5df4b7f6719455ef5f73cebf988
Ruby
nidialal/nid-mid
/hw1/part1.rb
UTF-8
694
3.453125
3
[]
no_license
#For those just starting out, one suggested way to work on your code is to have a command window open and a text editor with this #file loaded. Make changes to this file and then run 'ruby part1.rb' at the command line, this will run your program. Once you're #satisfied with your work, save your file and upload it to the checker. def palindrome?(str) # YOUR CODE HERE str1=str.downcase.gsub(/[^a-z]/i,'') str1==str1.reverse end def count_words(str) arr=str.downcase.split(%r{\b}) arr.delete_if{|word| word==" "} word_count={} arr.each do|word| if(word_count[word]==nil) word_count[word]=1 else word_count[word]=word_count[word]+1 end end return word_count end
true
3bdc6f0568b5cdad21d98f21f35de24981f8f95f
Ruby
mollyseith/my-collect-dc-web-071618
/lib/my_collect.rb
UTF-8
118
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def my_collect(array) ret = [] i=0 while i<array.length ret.push yield(array[i]) i += 1 end ret end
true
ee3a8bd67d56d8c4cbc8b3f2122e7bbfac2920f6
Ruby
rhiannoncs/most-anticipated-books-cli-gem
/lib/most_anticipated_books/genre.rb
UTF-8
457
3.234375
3
[ "MIT" ]
permissive
class MostAnticipatedBooks::Genre attr_accessor :name @@all = [] def initialize(name) @name = name @@all << self @books = [] end def self.all @@all end def add_book(book) @books << book end def books @books end def book_count @books.size end def self.genres_with_count all.each_with_index {|genre, index| puts "#{index + 1}. #{genre.name}: #{genre.book_count} Titles"} end end
true
cbd3b9f56f3d3a2634014bdc62982373854914d7
Ruby
bneuman-dev/battleship
/double/volley_results.rb
UTF-8
414
2.859375
3
[]
no_license
require_relative 'coord_translator' module VolleyResultsViewer include CoordTranslator def view_volley_results(results, player) hit_miss = {"H" => "hit", "m" => "miss"} puts "Shots by #{player.name}: " results.each do |result| puts from_coord(result[:coord]) + ": " + hit_miss[result[:result]] puts "Sunk " + result[:sunk] if result[:sunk] end puts "---------------------" puts " " end end
true
ec70c0e3e17266e5db6f98155ac200c271e48f42
Ruby
apalski/prime-ruby-v-000
/prime.rb
UTF-8
392
3.109375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Add code here! def prime?(number) number_array = (1..100).to_a result = 0 result_array = [] if number > 1 number_array.each do |x| result = number % x if result == 0 result_array << result end end if number > 100 result_array << 0 end if result_array.length < 3 true else false end else false end end
true
ea6d5a26cc0634eb0a1a2b1825b4038878589794
Ruby
hdamico/school
/app/models/users/student.rb
UTF-8
658
2.65625
3
[]
no_license
module Users class Student < User has_many :course_students has_many :courses, through: :course_students has_one :challenge def enroll_course(course_id) raise ArgumentError unless courses << Course.find(course_id) end def start_course(course_id) raise ArgumentError unless load_course_student(course_id) @course_student.start end def finish_course(course_id) raise ArgumentError unless load_course_student(course_id) @course_student.finish end private def load_course_student(course_id) @course_student = course_students.find_by(course_id: course_id) end end end
true
c27f560b2987d6be03b220a0adc008f1cfcfb444
Ruby
pharlanne/monday22
/specs/river_spec.rb
UTF-8
346
2.59375
3
[]
no_license
require ("minitest/autorun") require ("minitest/rg") #for green/red test require_relative("../river") require_relative("../fish") class TestRiver < MiniTest::Test def setup fish1=Fish.new("nemo") fish2=Fish.new("moby") fish3=Fish.new("goldie") @fish_group = [fish1, fish2,fish3] @river=River.new(fish_group) end end
true
0ed5990e9caadbcaf8527d179a2bde4fe1695036
Ruby
marclevetin/codewars
/7kyu/money-money-money.rb
UTF-8
1,444
4.0625
4
[]
no_license
# https://www.codewars.com/kata/563f037412e5ada593000114 # Mr. Scrooge has a sum of money 'P' that wants to invest, and he wants to know # how many years 'Y' this sum has to be kept in the bank in order for this sum # of money to amount to 'D'. # # The sum is kept for 'Y' years in the bank where interest 'I' is paid yearly, # and the new sum is re-invested yearly after paying tax 'T' # # Note that the principal is not taxed but only the year's accrued interest # # Example: # # Let P be the Principal = 1000.00 # Let I be the Interest Rate = 0.05 # Let T be the Tax Rate = 0.18 # Let D be the Desired Sum = 1100.00 # # # After 1st Year --> # P = 1041.00 # After 2nd Year --> # P = 1083.86 # After 3rd Year --> # P = 1128.30 # Thus Mr. Scrooge has to wait for 3 years for the initial pricipal to ammount # to the desired sum. # # Your task is to complete the method provided and return the number of years # 'Y' as a whole in order for Mr. Scrooge to get the desired sum. # # Assumptions : Assume that Desired Principal 'D' is always greater than the # initial principal, however it is best to take into consideration that if the # Desired Principal 'D' is equal to Principal 'P' this should return 0 Years. def calculate_years(principal, interest, tax, desired) years = 0 while principal < desired do taxable = (principal * interest) * (1 - tax) principal = principal + taxable years += 1 end years end
true
a587d9b4f66b4a99e24954b505a88d1bff6ae227
Ruby
J-Marriott/codewars
/6kyu/linux_history_4_final.rb
UTF-8
1,329
3.359375
3
[]
no_license
=begin In this kata you should complete a function that take in an string that correspond to s, and an history with the following format: and that should return the most recent command line that start with s, for example with s="more" and the above history it should return more me. If user ask for a s without any know entry for example n=mkdir here, the function should return !mkdir: event not found. =end def bang_start_string(s, history) return "! : event not found" if s == " " array = [] array << history.split(/\s\s\d{1,}\s\s/) array = array.flatten return array[-1].gsub("\n", "") if s == "" (array.length-1).downto(0) {|x| return array[x].gsub("\n", "").strip if array[x][0..s.length-1] == s} "!#{s}: event not found" end history= " 1 cd /pub 2 more beer 3 lost 4 ls 5 touch me 6 chmod 000 me 7 more me 8 history" bang_start_string(s, history) =begin Best solutions on codewars user: Iron Fingers def bang_start_string(s, history) ret = history.scan(/\d\s+(.*)/).flatten.reverse.find{ |cm| cm.start_with?(s) } ret ? ret : "!#{s}: event not found" end user: KSTNR def bang_start_string(s,history) h = history.lines.map{ |e| e.strip.split(' ',2).last }.map{ |e| e.scan(/^#{s}.*/).join }.delete_if(&:empty?).last h.nil? ? "!#{s}: event not found" : h end =end
true
9530228a7614e6c4ead291a4d9d360d881ba2bf9
Ruby
gfabro/ics-bootcamp17
/ch07/deafGrandmaExtended.rb
UTF-8
550
4.21875
4
[]
no_license
#HOW TO PROGRAM WITHOUT break : next puts 'Tell grandma something. You can only end the conversation once you shout "BYE" ' message = '' bye = 0 while bye < 3 message = gets.chomp if message == 'BYE'.chomp bye += 1 #Learned this from another program (Java NetBeans) bye == 3 elsif(message == message.upcase) bye = 0 year = rand(21) + 1930 puts 'NO, NOT SINCE ' + year.to_s + '!' else bye = 0 puts 'HUH?! SPEAK UP, HONNEY!' end end puts 'GOODBYE DEAR!'
true
c497e792f2d4a4b393b05d245664d50d72f1e007
Ruby
seanbehan/sinatra-frank
/lib/sinatra/flash_message.rb
UTF-8
491
2.828125
3
[ "MIT" ]
permissive
# Simple flash messaging in Sinatra # # require 'sinatra/flash_message' # # configure { enable :sessions } # helpers { def flash; @flash ||= FlashMessage.new(session); end } # # get '/' do # flash.message = 'hello world' # end # # <%= flash.message %> # class FlashMessage def initialize(session) @session ||= session end def message=(message) @session[:flash] = message end def message message = @session[:flash] @session[:flash] = nil message end end
true
b51853375211aea2ab9d7f7daf8d4524f554c936
Ruby
nicole7/rails_flashcards
/app/models/guess.rb
UTF-8
442
2.703125
3
[]
no_license
class Guess < ApplicationRecord belongs_to :round belongs_to :card has_one :user, through: :round def self.create_and_check_guess(card, answer, round) Guess.create(correct?: (answer.downcase.chomp == card.answer.downcase), round_id: round.id, card_id: card.id) end def self.get_correct_cards(guesses) correct_cards = [] guesses.each do |guess| correct_cards << guess.card end correct_cards end end
true
7af3211f0c2bdb09a7977cd5eb6d00c80e0efebb
Ruby
mmatney22/best_psych_books
/lib/psych_books/cli.rb
UTF-8
1,802
3.6875
4
[ "MIT" ]
permissive
class PsychBooks::CLI def call puts "\nWelcome to Goodreads Best Psychology Books!\n".green get_books list_books get_user_book end def get_books @books = PsychBooks::Book.all end def list_books puts "------------------------" puts " Greatest Psych Books " puts "------------------------" @books.each.with_index(1) {|book, index| puts "#{index}. #{book.title}".cyan} puts "\nEnter the number of the book to see more information:\n".green end def get_user_book chosen_book = gets.strip.to_i if valid_input?(chosen_book, @books) list_info_for(chosen_book) else puts "\nI'm not quite sure I understand. Please try again.\n".green get_user_book end end def valid_input?(input, data) input.to_i <= data.length && input.to_i > 0 end def list_info_for(chosen_book) book = @books[chosen_book - 1] PsychBooks::Scraper.scrape_book_details(book) puts "\nHere are the details for #{book.title}:\n".green puts "\nAuthor:".yellow.bold + " #{book.author}\n".cyan puts "\nDescription:".yellow.bold + " #{book.description}\n".cyan puts "\nPage count:".yellow.bold + " #{book.page_count}\n".cyan puts "\nRating:".yellow.bold + " #{book.rating}\n".cyan menu end def menu puts "Type 'books' to see the list of books again.".green puts "\nType 'exit' to exit.\n".green input = gets.strip.downcase menu_decision(input) end def menu_decision(input) if input == "books" list_books get_user_book elsif input == "exit" puts "\nThank you for choosing Goodreads! Happy reading!\n".green else puts "\nI'm not quite sure I understand. Please try again.\n".green menu end end end
true
929a8c82ffed918d47151d7f3b88f2456f4c39e5
Ruby
saipat/AA-Daily
/W1D2/memory_game/board.rb
UTF-8
927
3.6875
4
[]
no_license
require_relative 'card' class Board attr_accessor :grid GRIDSIZE = 6 def initialize @grid = Array.new(GRIDSIZE) { Array.new(GRIDSIZE) } @values = ((1..GRIDSIZE*GRIDSIZE/2).to_a * 2).shuffle populate end def reveal(guess_pos) self[guess_pos].reveal self[guess_pos].value end def won? @grid.each do |subarray| subarray.each do |card| return false unless card.face_up end end true end def populate @grid.map! do |subarray| subarray.map! do |el| Card.new(@values.pop) end end end def render @grid.each do |subarray| subarray.each do |card| print card.face_up ? card : ":)" end puts '' end end def [](pos) x,y = pos @grid[x][y] end def []=(pos,value) x,y = pos @grid[x][y] = value end end # if __FILE__ == $0 # a = Board.new # a.populate # a.render # end
true
7ee90291700b934e43b00641091f6fe6a82bbad6
Ruby
jztimm/programming-univbasics-4-simple-looping-lab-nyc01-seng-ft-071320
/lib/simple_loops.rb
UTF-8
608
4.1875
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Write your methods here # ex_arr = ["this", "is", "for", "a", "method"] def loop_message_five_times(message) counter = 0 while counter < 5 do puts message counter += 1 end end def loop_message_n_times(message, n) count = 0 while count < n do puts message count += 1 end end def output_array(array) count = 0 while count < array.length do puts array[count] count += 1 end end def return_string_array(array) counter = 0 new_arr = [] while counter < array.length do new_arr.push(array[counter].to_s) counter += 1 end new_arr end
true
e81956980c759fae006eccbcdbe8d7c0299283f1
Ruby
matiasanaya/toy-robot-simulator
/test/test_pose.rb
UTF-8
3,981
2.890625
3
[ "Unlicense" ]
permissive
require_relative '../lib/toy_robot/pose' require_relative 'test_pose_interface' require_relative 'test_reporter_interface' require 'minitest/autorun' module ToyRobot class PoseTest < MiniTest::Unit::TestCase include PoseInterfaceTest include ReporterInterfaceTest def setup @x, @y = 0, 1 @orientation = Pose::Orientation::EAST @pose = @object = Pose.new( x: @x, y: @y, orientation: @orientation ) end def test_it_can_be_initialized_without_arguments assert Pose.new end def test_that_it_can_mutate mutated_pose_attrs = { x: 5, y: 5, orientation: 'random' } assert_pose mutated_pose_attrs, @pose.mutate!(mutated_pose_attrs) end def test_that_knows_adjacent_when_facing_east adjacent_pose_hash = { x: @x + 1, y: @y, orientation: @orientation } assert_pose adjacent_pose_hash, @pose.adjacent end def test_that_knows_adjacent_when_facing_north orientation = Pose::Orientation::NORTH @pose.instance_variable_set(:@orientation, orientation) adjacent_pose_hash = { x: @x, y: @y + 1, orientation: orientation } assert_pose adjacent_pose_hash, @pose.adjacent end def test_that_knows_adjacent_when_facing_west orientation = Pose::Orientation::WEST @pose.instance_variable_set(:@orientation, orientation) adjacent_pose_hash = { x: @x - 1, y: @y, orientation: orientation } assert_pose adjacent_pose_hash, @pose.adjacent end def test_that_knows_adjacent_when_facing_south orientation = Pose::Orientation::SOUTH @pose.instance_variable_set(:@orientation, orientation) adjacent_pose_hash = { x: @x, y: @y - 1, orientation: orientation } assert_pose adjacent_pose_hash, @pose.adjacent end def test_that_can_rotate_90 clockwise_orientations = [ Pose::Orientation::NORTH, Pose::Orientation::EAST, Pose::Orientation::SOUTH, Pose::Orientation::WEST, Pose::Orientation::NORTH ] clockwise_orientations.each_cons(2) do |initial_orientation, rotated_orientation| @pose.instance_variable_set(:@orientation, initial_orientation) rotated_pose_hash = {x: @x, y: @y, orientation: rotated_orientation} @pose.rotate!(90) assert_pose rotated_pose_hash, @pose end end def test_that_can_rotate_90_counterclockwise counter_clockwise_orientations = [ Pose::Orientation::NORTH, Pose::Orientation::WEST, Pose::Orientation::SOUTH, Pose::Orientation::EAST, Pose::Orientation::NORTH ] counter_clockwise_orientations.each_cons(2) do |initial_orientation, rotated_orientation| @pose.instance_variable_set(:@orientation, initial_orientation) rotated_pose_hash = { x: @x, y: @y, orientation: rotated_orientation } @pose.rotate!(-90) assert_pose rotated_pose_hash, @pose end end def test_that_hash_like_access_to_x_returns_instance_variable_x assert_equal @pose.instance_variable_get(:@x), @pose[:x] end def test_that_hash_like_access_to_y_returns_instance_variable_y assert_equal @pose.instance_variable_get(:@y), @pose[:y] end def test_that_hash_like_access_to_orientation_returns_instance_variable_orientation assert_equal @pose.instance_variable_get(:@orientation), @pose[:orientation] end def assert_pose(expected_pose_hash, actual) assert_equal expected_pose_hash[:x], actual.send(:x), ':x coordinate is different' assert_equal expected_pose_hash[:y], actual.send(:y), ':y coordinate is different' assert_equal expected_pose_hash[:orientation], actual.send(:orientation), ':orientation is different' end end end
true
bbece08b8fbacb719198a6231d0539acd676a006
Ruby
haydenlangelier/phase-0-tracks
/databases/fitness_tracker.rb
UTF-8
3,371
3.859375
4
[]
no_license
# This is my fitness tracker # It will be used for tracking, storing, editing, adding new data on how far you have ran, and how many #calories on each run etc..... #here i require the two gems needed require 'sqlite3' require 'faker' #creating a new fresh datbase db = SQLite3::Database.new("running.db") db.results_as_hash = true #creating the outline for a new table #all distance is in miles #this didn't work at first so i had to look at some other source code #but it's working now! new_table = <<-SQL CREATE TABLE IF NOT EXISTS running( id INTEGER PRIMARY KEY, name VARCHAR(255), address VARCHAR(255), distance INT ) SQL #create an empty table db.execute(new_table) #testing it out to ensure it works! #db.execute("INSERT INTO exercise (name,distance) VALUES ('Hayden',5)") #creating a method for running and including the db, name, and distance ran(miles) def run(db,name,address,distance) db.execute("INSERT INTO running(name,address,distance) VALUES(?,?,?)",[name,address,distance]) end # I commented this out because it kept growing and growing and growing while i was working on it #30.times do # run(db, Faker::Name.name,Faker::Address.street_address,rand(30)) #end #setting up a loop here!!! answer='' puts "What is your name?" username=gets.chomp until answer=="no" #here im going to ask the user for their run information puts "Where did you run?" where=gets.chomp puts "How far did you run(in miles)?" miles=gets.to_i #here i am I am inputingg their information at the end of the list db.execute("INSERT INTO running(name,address,distance) VALUES(?,?,?)",[username,where,miles]) #Here i created a method for calculated the number of calories burned and printed it for the end user to see! def calories_burned(miles_ran) calories=miles_ran*600 puts "You have burned #{calories} calories, congratulations!!!" end calories_burned(miles) puts "Would you like to enter another run? Please enter yes or no." answer=gets.chomp.downcase end # here i am outputting the runs, distance, run number, address etc all_runs = db.execute("SELECT * FROM running") all_runs.each do |runner| puts "#{runner['name']} ran #{runner['distance']} miles on run number #{runner['id']} through #{runner['address']}. " end #here i have created a loop for updating or deleting entries response='' until response=='done' do puts "Now you can update one of your entries if you would like!" puts "Please type update,delete, or done." response=gets.chomp.downcase if response=="update" puts "Which run number would you like to update? Please enter just the number" run_number=gets.to_i puts "What was the correct distance in miles?" correct_distance=gets.to_i puts "What was the correct running location description?" correct_description=gets.chomp db.execute("UPDATE running SET address = ? WHERE id = ?;",[correct_description,run_number]) db.execute("UPDATE running SET distance = ? WHERE id = ?;",[correct_distance,run_number]) db.execute("SELECT * FROM running WHERE id = ?;",[run_number]) else puts "Which run number would you like to delete? Please enter just the number" run_number=gets.to_i db.execute("DELETE FROM running WHERE id = ?;",[run_number]) end end
true
3b2c7fb796b65043ad58150394b1894c5690035b
Ruby
kdiogenes/iron_cache_ruby
/lib/iron_cache/caches.rb
UTF-8
2,742
2.703125
3
[]
no_license
require 'cgi' module IronCache class Caches attr_accessor :client def initialize(client) @client = client end def path(options={}) path = "projects/#{@client.project_id}/caches" if options[:name] path << "/#{CGI::escape(options[:name]).gsub('+', '%20')}" end path end def list(options={}) lst = call_api(:get, '', options) @client.logger.debug lst.inspect lst.map do |cache| @client.logger.debug "cache: " + cache.inspect Cache.new(@client, cache) end end # options: # :name => can specify an alternative queue name def get(options={}) opts = parse_opts(options) opts[:name] ||= @client.cache_name Cache.new(@client, call_api(:get, '', opts)) end def clear(options={}) ResponseBase.new(call_api(:post, '/clear', options)) end def remove(options={}) ResponseBase.new(call_api(:delete, '', options)) end private def parse_opts(options={}) options = options.is_a?(String) ? {:name => options} : options end def call_api(method, ext_path, options={}) pth = path(parse_opts(options)) + ext_path res = @client.send(method, pth) @client.parse_response(res, true) end end class Cache def initialize(client, res) @client = client @data = res end def raw @data end def [](key) raw[key] end def id raw["id"] end def name raw["name"] end # Used if lazy loading def load_cache cache = @client.caches.get(:name => name) # @client.logger.debug "GOT Q: " + cache.inspect @data = cache.raw cache end def reload load_cache end def size case when raw["size"] raw["size"] when @size @size else @size = load_cache.size end end def put(k, v, options={}) @client.items.put(k, v, options.merge(:cache_name => name)) end def get(k, options={}) @client.items.get(k, options.merge(:cache_name => name)) end # Returns the url to this item. It does not actually get the item def url(k, options={}) @client.items.url(k, options.merge(:cache_name => name)) end def delete(k, options={}) @client.items.delete(k, options.merge(:cache_name => name)) end def increment(k, amount=1, options={}) @client.items.increment(k, amount, options.merge(:cache_name => name)) end def clear(options={}) @client.caches.clear(options.merge(:name => name)) end def remove(options={}) @client.caches.remove(options.merge(:name => name)) end end end
true
2f36720935d53a280acb4a102d968071ee1d466e
Ruby
samanthagottlieb/makersbnb
/lib/home.rb
UTF-8
1,037
3.140625
3
[]
no_license
class Home attr_reader :id, :user_id, :name, :description, :price def initialize(id:, user_id:, name:, price:, description: 'Another lovely house') @id = id @user_id = user_id @name = name @description = description @price = price end def self.create(name:, description:, price:, username: 'Guest') result = DatabaseConnection.query("INSERT INTO homes (user_id, name, description, price) VALUES((SELECT id FROM users WHERE username='#{username}'),'#{name}','#{description}',#{price}) RETURNING id, user_id, name, description, price;") Home.new(id: result[0]['id'], user_id: result[0]['user_id'], name: (result[0]['name']), description: (result[0]['description']), price: result[0]['price']) end def self.all result = DatabaseConnection.query('SELECT * FROM homes') result.map do |this| Home.new( name: this['name'], description: this['description'], price: this['price'], id: this['id'], user_id: this['user_id'] ) end end end
true
e1fdb096bee9054d3eca64e9427ec98bad874684
Ruby
akhilsingla97/Dispatchr
/dispatchr-ruby/app/models/store.rb
UTF-8
692
3.265625
3
[]
no_license
require 'haversine.rb' class Store < ApplicationRecord has_many :items, through: :item_stores belongs_to :address validates :address_id, presence: true validates :name, presence: true def self.find_nearest_store(lat, long) store_id = -1 distance = 150 #150 meters within a store Store.all.each do |store| hav_dist = Haversine.distance(lat, long, store.address.latitude, store.address.longitude).to_meters if (hav_dist <= distance) distance = hav_dist store_id = store.id puts("#{store.name} is #{hav_dist} away from you!") end end if (store_id != -1) puts "You are near store #{store_id}" end return store_id end end
true
188dc5ea82117dbde679b82019ad628ecbd0e4f2
Ruby
frodrigueza/kanbantt2
/app/helpers/tasks_helper.rb
UTF-8
2,285
2.6875
3
[]
no_license
module TasksHelper def real_image(real) if real < 8 '0.png' elsif real < 20 'r1.png' elsif real < 33 'r2.png' elsif real < 46 'r3.png' elsif real < 58 'r4.png' elsif real < 71 'r5.png' elsif real < 83 'r6.png' elsif real < 96 'r7.png' else 'r8.png' end end def expected_image(expected) if expected < 8 '0.png' elsif expected < 20 'e1.png' elsif expected < 33 'e2.png' elsif expected < 46 'e3.png' elsif expected < 58 'e4.png' elsif expected < 71 'e5.png' elsif expected < 83 'e6.png' elsif expected < 96 'e7.png' else 'e8.png' end end # entrga lo que falta de manera formateada, se ocupa en la vista del arbol def remaining_days(task) remaining_to_start = task.remaining_to_start remaining_to_end = task.remaining_to_end if task.progress == 100 #terminadas '<span class="glyphicon glyphicon-ok"></span>'.html_safe elsif remaining_to_start >= 0 case remaining_to_start when 0 'Comienza hoy' when 1 'Comienza mañana' else 'Comienza en ' + remaining_to_start.to_s + ' días' end elsif remaining_to_end >= 0 #en progreso case remaining_to_end when 0 'Finaliza hoy' when 1 'Finaliza mañana' else 'Finaliza en ' + remaining_to_end.to_s + ' días' end elsif remaining_to_end < 0 # atrasadas case remaining_to_end when -1 'Atrasada 1 día' else 'Atrasada ' + (remaining_to_end * -1 ).to_s + ' días' end end end def css_task_status_color(task) if task.delayed 'bad' else 'great' end end def urgent_task_title(task) if task.urgent 'Tarea marcada como urgente' else 'Marcar esta tarea como urgente' end end def urgent_task_class(task) if task.urgent 'active' else '' end end def user_assigned_task_title(task) 'Tarea asignada a ' + task.user.f_name end def user_commited_tak_title(task) task.user.f_name + ' se ha comprometido a realizar esta tarea' end end
true
a5f10cc8e066d222970e6108b23e2a8c3efeaba4
Ruby
almihoil/TECH.C
/submit/Sairi7/1011wc.rb
UTF-8
293
3.125
3
[]
no_license
def wc(file) lines = 0 words = 0 chars = 0 file = File.open(file, "r") while line = file.gets lines += 1 chars += line.length wordArray = line.split(/\s+/).reject{|w| w.empty?} words += wordArray.length end put "lines=#{lines} words=#{words} chars=#{chars}" end wc(ARVG[0])
true
8c095f2e9dd316c10fa37661153e760bd51f1da1
Ruby
gdpelican/rainbow_bandit
/lib/rainbow_scraper.rb
UTF-8
2,182
2.5625
3
[]
no_license
require 'open-uri' require 'nokogiri' require './models/color' require './models/url' require 'byebug' require 'screencap' class RainbowScraper def execute exit 0 if Url.find_by(url: random_url) return unless random_url_body puts "Found #{random_url_stylesheet_colors} at #{random_url}" random_url_stylesheet_colors.map do |color| model_for_random_url.colors << Color.find_or_create_by(hex: color) end take_screenshot end private def random_url open('http://www.randomwebsite.com/cgi-bin/random.pl') { |response| @random_url = response.base_uri.to_s } unless @random_url @random_url rescue nil end def model_for_random_url @model_for_random_url ||= Url.create(url: random_url, title: random_url_body.title) end def random_url_body @random_url_body ||= Nokogiri::HTML(open(random_url)) rescue puts "#{random_url} is not scrapeable" end def random_url_stylesheets @random_url_stylesheets ||= random_url_body.search('link').select { |link| link['type'] && link['type'].match(/css/) } end def random_url_style_tags @random_url_style_tags ||= random_url_body.search('style').select { |style| style['type'] && style['type'].match(/css/) } end def random_url_inline_styles @random_url_style_tags ||= random_url_style_tags.map { |style| style.to_s rescue '' } end def random_url_stylesheet_bodies @random_url_stylesheet_bodies ||= random_url_stylesheets.map do |stylesheet| href = stylesheet['href'].match(/^http/) ? stylesheet['href'] : [random_url, stylesheet['href']].join begin open(href).read rescue "" end end.join end def all_styles @all_styles ||= [random_url_stylesheet_bodies, random_url_inline_styles].flatten.join end def random_url_stylesheet_colors @random_url_stylesheet_colors ||= all_styles.scan(/#[A-F0-9]{6}/i).map(&:downcase).uniq end def take_screenshot File.open("public/screencaps/#{model_for_random_url.id}.jpg", "w") do |file| file.write Screencap::Fetcher.new(random_url).fetch(width: 100, height: 100) model_for_random_url.update(screencap: file.path.gsub(/^public/, '')) end end end
true
6767d45779c89d31481398177d55085152ad5291
Ruby
SpringMT/study
/ruby/ruby_doujou/variable2.rb
UTF-8
194
3.015625
3
[]
no_license
class Foo def foofoo @a= 1 end def a @a end def b @b end end class Baa < Foo def baa_a @a end end obj = Foo.new obj.foofoo p obj.a p Foo.new.b p Baa.new.baa_a
true
17b5a5843529f3ae55b80e436edf07d3cf5a9906
Ruby
pelf/advent-of-code-2019
/day12/day12_part2.rb
UTF-8
2,098
3.09375
3
[]
no_license
class Body attr_reader :pos, :vel def initialize(x, y, z) @pos = [x, y, z] @vel = [0, 0, 0] end def energy pot * kin end def to_s # "#{pos}#{vel}" "#{pos[0]}" end private def pot pos[0].abs + pos[1].abs + pos[2].abs end def kin vel[0].abs + vel[1].abs + vel[2].abs end end bodies = File.readlines("input.txt").map do |line| # <x=14, y=2, z=8> line =~ /<x=(-?\d+), y=(-?\d+), z=(-?\d+)>/ Body.new($1.to_i, $2.to_i, $3.to_i) end states = {} i = 0 initial_xs = bodies.map { |b| b.pos[0] } initial_ys = bodies.map { |b| b.pos[1] } initial_zs = bodies.map { |b| b.pos[2] } initial_velx = bodies.map { |b| b.vel[0] } initial_vely = bodies.map { |b| b.vel[1] } initial_velz = bodies.map { |b| b.vel[2] } cycles_found = [false] * 6 loop do i += 1 # gravity step bodies.combination(2).each do |b1, b2| (0..2).each do |axis| if b1.pos[axis] > b2.pos[axis] b1.vel[axis] -= 1 b2.vel[axis] += 1 elsif b2.pos[axis] > b1.pos[axis] b1.vel[axis] += 1 b2.vel[axis] -= 1 end end end # velocity step bodies.each do |body| (0..2).each do |axis| body.pos[axis] += body.vel[axis] end end if bodies.map { |b| b.pos[0] } == initial_xs && !cycles_found[0] cycles_found[0] = i + 1 # positions happen twice at top and bottom of the cycle end if bodies.map { |b| b.pos[1] } == initial_ys && !cycles_found[1] cycles_found[1] = i + 1 # positions happen twice at top and bottom of the cycle end if bodies.map { |b| b.pos[2] } == initial_zs && !cycles_found[2] cycles_found[2] = i + 1 # positions happen twice at top and bottom of the cycle end if bodies.map { |b| b.vel[0] } == initial_velx && !cycles_found[3] cycles_found[3] = i end if bodies.map { |b| b.vel[1] } == initial_vely && !cycles_found[4] cycles_found[4] = i end if bodies.map { |b| b.vel[2] } == initial_velz && !cycles_found[5] cycles_found[5] = i end break if cycles_found.all? end puts "Find the LMC for these numbers: (google it)" p cycles_found.sort
true
47340ff5e572f37cab70bf958fe1e5012a97626e
Ruby
edb-c/ruby-object-attributes-lab-v-000
/lib/person.rb
UTF-8
451
3.4375
3
[]
no_license
class Person #name reads the name of the person from an instance variable @name def name @name end #name=writes the name of the person to an instance variable @name def name=(new_name) @name = new_name end #job reads the job of the person from an instance variable @job def job @job end #job=writes the job of the person to an instance variable @job def job=(new_job) @job = new_job end end
true
50df9ad3c92784eaa00910b14578e099c380531d
Ruby
alanthewelsh/cc-week2-day3-snakeandladders
/specs/die_spec.rb
UTF-8
433
2.859375
3
[]
no_license
require('minitest/autorun') require_relative('../board.rb') require_relative('../player.rb') require_relative('../die.rb') class TestDie < Minitest::Test def test_die_can_produce_number new_dice = Die.new() new_dice_number = new_dice.roll assert_includes((1..6), new_dice_number) end # def test_die_returns_array # # Die.new() # result = dice_roll # assert_includes((1..6), result) # end end
true
0d6c606c38d3091f1e6d5eb69ba74743b2d8de45
Ruby
dallinder/small_problems_ls
/easy_7/5.rb
UTF-8
270
3.65625
4
[]
no_license
def staggered_case(string) chars = string.chars chars.each_with_index do |c, i| if i.even? c.upcase! else c.downcase! end end chars.join('') end puts staggered_case('I Love Launch School!') puts staggered_case('ignore 77 the 444 numbers')
true
0389fe815e887e1922910758d4ed2ddc55f17c3d
Ruby
snrk-m/ruby
/ruby/lesson2.rb
UTF-8
72
2.6875
3
[]
no_license
puts "私の名前は村田です。"+"年齢は"+24.to_s+"歳です。"
true
b56910992ad865e7646864abf1b20005774d443e
Ruby
y-amadatsu/himeshima-mamoru
/app/models/reservation.rb
UTF-8
575
2.53125
3
[]
no_license
# frozen_string_literal: true require 'csv' class Reservation < ApplicationRecord belongs_to :user, class_name: 'User', foreign_key: :imported_user_id, optional: true, inverse_of: :reservation def age (Time.zone.today.strftime('%Y%m%d').to_i - birthday_on.strftime('%Y%m%d').to_i) / 10_000 end # TODO: 編集すること! def self.import(file) CSV.foreach(file.path, headers: true) do |row| book = find_by(id: row['id']) || new book.attributes = row.to_hash.slice(*updatable_attributes) book.save!(validate: false) end end end
true
a9fca059c7d58e20e474f8ae8f6ec467aef20c96
Ruby
DawidGaleziewski/LocalUdemyRuby
/29_equality_with_strings.rb
UTF-8
189
2.890625
3
[]
no_license
a = "Hello" b = "hello" c = "Hello" p a != "zebra" p a == "lion" p a == b p a == c p a != b puts p "Apple" < "Banana" p "hello" < "help" puts p "A" < "a" p true == true p true == false
true
9bad02c9cecb01671c97686031d44b9ce9a559e4
Ruby
IsmaelSANE/learn-to-program
/table-of-contents-revisited.rb
UTF-8
586
3.09375
3
[]
no_license
line_width = 40 contents = ["Table of Contents", "Chapter 1:", "Getting Started", "page 1", "Chapter 2:", "Numbers", "page 9", "Chapter 3:", "Letters", "page 13"] puts '' puts(contents[0].rjust( line_width)) puts '' puts '' puts(contents[1].ljust(line_width/3) + contents[2].ljust(line_width) + contents[3].ljust(line_width/3)) puts(contents[4].ljust(line_width/3) + contents[5].ljust(line_width) + contents[6].ljust(line_width/3)) puts(contents[7].ljust(line_width/3) + contents[8].ljust(line_width) + contents[9].ljust(line_width/3))
true
be68d9d332c3f54310fadff56b93762d66dfb8a6
Ruby
StuartHadfield/robbi-bot
/bot.rb
UTF-8
4,756
2.953125
3
[ "MIT" ]
permissive
require 'sinatra/base' require 'slack-ruby-client' require 'httparty' # This class contains all of the webserver logic for processing incoming requests from Slack. class API < Sinatra::Base # This is the endpoint Slack will post Event data to. post '/events' do # Extract the Event payload from the request and parse the JSON request_data = JSON.parse(request.body.read) # Check the verification token provided with the request to make sure it matches the verification token in # your app's setting to confirm that the request came from Slack. unless SLACK_CONFIG[:slack_verification_token] == request_data['token'] halt 403, "Invalid Slack verification token received: #{request_data['token']}" end case request_data['type'] # When you enter your Events webhook URL into your app's Event Subscription settings, Slack verifies the # URL's authenticity by sending a challenge token to your endpoint, expecting your app to echo it back. # More info: https://api.slack.com/events/url_verification when 'url_verification' request_data['challenge'] when 'event_callback' # Get the Team ID and Event data from the request object team_id = request_data['team_id'] event_data = request_data['event'] # Events have a "type" attribute included in their payload, allowing you to handle different # Event payloads as needed. case event_data['type'] when 'message' # Event handler for messages, including Share Message actions Events.message(team_id, event_data) else # In the event we receive an event we didn't expect, we'll log it and move on. puts "Unexpected event:\n" puts JSON.pretty_generate(request_data) end # Return HTTP status code 200 so Slack knows we've received the Event status 200 end end post '/flat_white' do # test event end end class Events def self.message(team_id, event_data) user_id = event_data['user'] # Don't process messages sent from our bot user unless user_id == $teams[team_id][:bot_user_id] answer = self.assign_message_response(team_id, event_data) # SHARED MESSAGE EVENT # To check for shared messages, we must check for the `attachments` attribute # # and see if it contains an `is_shared` attribute. if event_data['attachments'] && event_data['attachments'].first['is_share'] # We found a shared message user_id = event_data['user'] ts = event_data['attachments'].first['ts'] channel = event_data['channel'] self.send_response(team_id, user_id, channel, ts, answer) else user_id = event_data['user'] channel = event_data['channel'] self.send_response(team_id, user_id, channel, answer) end end end def self.assign_message_response(team_id, event_data) user_name = $teams[team_id]['client'].users_info(user: event_data['user'])['user']['name'] if event_data['text'].downcase =~ /help/i "I see you asked for help! You can ask me for `help` or for a `menu`, but "\ "other than that, I don't really know what I'm capable of just yet, nor "\ "does my creator... check back soon though! :wink:" elsif event_data['text'].downcase =~ /hello/i || event_data['text'].downcase =~ /hi robbi/i "Hello! I'm hearing you loud and clear, over." elsif event_data['text'].downcase =~ /menu/i "I haven't had time to browse the Molten menu thoroughly yet... You're just gonna get a large cap anyway though right?" elsif event_data['text'].downcase =~ /order/i order_config = event_data['text'].split(' ') rescue ['order', 'flat_white'] options = { body: { order: { # your resource menu_item: order_config.last, # your columns/data name: user_name } } } response = HTTParty.post('https://cc63adf0.ngrok.io/orders', options) if response.code == 200 response_body = JSON.parse(response.body) "Molten server says: #{response_body['message']}, id: #{response['order']['id']}, what you ordered: #{response['order']['menu_item']}, ordered for: #{response['order']['name']}" else "Fuck. Order failed." end else "Hey #{user_name}, I'm still growing up and I don't understand English too well.. Please bear with me while I learn!" end end # Send a response to an Event via the Web API. def self.send_response(team_id, user_id, channel, ts = nil, text) $teams[team_id]['client'].chat_postMessage( as_user: 'true', channel: channel, text: text ) end end
true
d0b61b66892d3fa875a9c9be7b4aff2209115cf5
Ruby
lp/cordovan
/lib/cordovan_helpers.rb
UTF-8
1,113
2.90625
3
[ "MIT" ]
permissive
# Author:: lp (mailto:lp@spiralix.org) # Copyright:: 2009 Louis-Philippe Perron - Released under the terms of the MIT license # # :title:Cordovan class Cordovan private def fit_in_grid(style) style[:v_span] = @v_grid if style[:v_span].nil? style[:h_span] = @h_grid if style[:h_span].nil? style[:v_pos] = 1 if style[:v_pos].nil? style[:h_pos] = 1 if style[:h_pos].nil? style[:height] = height_from(style[:v_span]) style[:width] = width_from(style[:h_span]) style[:left] = x_from(style[:h_pos]) style[:top] = y_from(style[:v_pos]) style end def height_from(v_span) return (@height * v_span).to_i if v_span.is_a?(Float) and v_span <= 1.0 (@height.to_f / @v_grid * v_span).to_i end def width_from(h_span) return (@width * h_span).to_i if h_span.is_a?(Float) and h_span <= 1.0 (@width.to_f / @h_grid * h_span).to_i end def x_from(h_pos) return (@width * h_pos).to_i if h_pos.is_a?(Float) and h_pos <= 1.0 (@width.to_f / @h_grid * (h_pos-1)).to_i end def y_from(v_pos) return (@height * v_pos).to_i if v_pos.is_a?(Float) and v_pos <= 1.0 (@height.to_f / @v_grid * (v_pos-1)).to_i end end
true
67950cde6791f9aa31731f600bf9daa7c58ab13b
Ruby
JamesJinPark/mcit-waiver
/app/controllers/courses_controller.rb
UTF-8
3,564
2.640625
3
[]
no_license
# == Schema Information # # Table name: courses # # id :integer not null, primary key # name :string(255) # created_at :datetime not null # updated_at :datetime not null # user_id :integer # email_opt_in :boolean # class CoursesController < ApplicationController # checks that admin is logged in before_filter :check_admin_logged_in!, except: [:show, :index, :subscribe, :unsubscribe] # checks that instructor is logged in before_filter :check_user_logged_in!, only: [:show, :index, :subscribe, :unsubscribe] #trying to make course show page to also include sortable columns helper_method :sort_column, :sort_direction # GET /courses # GET /courses.json def index @courses = Course.all respond_to do |format| format.html # index.html.erb format.json { render json: @courses } end end # GET /courses/1 # GET /courses/1.json def show #@course = Course.find(params[:id]) #trying to make course show page to also include sortable columns @course = Course.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @course } end end # GET /courses/new # GET /courses/new.json def new @course = Course.new respond_to do |format| format.html # new.html.erb format.json { render json: @course } end end # GET /courses/1/edit def edit @course = Course.find(params[:id]) end # POST /courses # POST /courses.json def create @course = Course.new(params[:course]) respond_to do |format| if @course.save format.html { redirect_to @course, notice: 'Course was successfully created.' } format.json { render json: @course, status: :created, location: @course } else format.html { render action: "new" } format.json { render json: @course.errors, status: :unprocessable_entity } end end end # PUT /courses/1 # PUT /courses/1.json def update @course = Course.find(params[:id]) respond_to do |format| if @course.update_attributes(params[:course]) format.html { redirect_to @course, notice: 'Course was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @course.errors, status: :unprocessable_entity } end end end # DELETE /courses/1 # DELETE /courses/1.json def destroy @course = Course.find(params[:id]) @course.destroy respond_to do |format| format.html { redirect_to courses_url } format.json { head :no_content } end end def subscribe @course = Course.find(params[:id]) @course.update_attribute(:email_opt_in, true) redirect_to @course, notice: 'Successfully subscribed to email notifications.' end def unsubscribe @course = Course.find(params[:id]) @course.update_attribute(:email_opt_in, false) redirect_to @course, notice: 'Unsubscribed from email notifications.' end private def check_admin_logged_in! # admin must be logged in authenticate_admin! end def check_user_logged_in! # if admin is not logged in, instructor must be logged in if !admin_signed_in? authenticate_user! end end def sort_column Waiver.column_names.include?(params[:sort]) ? params[:sort] : "created_at" end def sort_direction %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc" end end
true
605b9d71d498b0ac8ba52d0fcf25408587bf28ce
Ruby
MarilenaRoque/CodeChallenges
/full_merge_sort.rb
UTF-8
1,358
3.53125
4
[]
no_license
def merge_sort(array1, array2) idx_1 = 0 idx_2 = 0 sorted_array = [] n = array1.length + array2.length n.times do |count| if array2[idx_2].nil? sorted_array << array1[idx_1] idx_1 +=1 elsif (array1[idx_1].nil? && array2[idx_2]) sorted_array << array2[idx_2] idx_2 +=1 elsif array1[idx_1].split(' ')[0].to_i <= array2[idx_2].split(' ')[0].to_i sorted_array << array1[idx_1] idx_1 +=1 else sorted_array << array2[idx_2] idx_2 +=1 end end sorted_array end def full_merge_method(array) return array if array.length < 2 idx_middle = (array.length/2).floor left = array.slice(0,idx_middle) right = array.slice(idx_middle, array.length - 1) sorted = merge_sort(full_merge_method(left) , full_merge_method(right)) return sorted end def full_merge_sort(array) sorted = full_merge_method(array) sorted = sorted.map do |item| item.split(' ')[1] end end full_merge_sort(["0 ab", "6 cd", "0 ef", "6 gh", "4 ij", "0 ab", "6 cd", "0 ef", "6 gh", "0 ij", "4 that", "3 be", "0 to", "1 be", "5 question", "1 or", "2 not", "4 is", "2 to", "4 the"]) # => ["ab", "ef", "ab", "ef", "ij", "to", "be", "or", "not", "to", "be", "ij", "that", "is", "the", "question", "cd", "gh", "cd", "gh"]
true
6a055dba8596a4f0aab3066ad9f1bbe56591afa1
Ruby
spike886/10pines
/lib/strategy.rb
UTF-8
462
2.8125
3
[]
no_license
class Strategy attr_accessor :system def execute shares shares_to_sell=shares.select do |share| share.purchased && filter_shares_to_sell(share) end shares_to_buy=shares.select do |share| filter_shares_to_buy(share) end shares_to_buy.sort! do |first_share, second_share| sort_shares_to_buy first_share, second_share end @system.sell(shares_to_sell) @system.buy(shares_to_buy) end end
true
025a5679fbdb027164ec703e989d6337a1d25bf8
Ruby
itggot-william-bruun/standard-biblioteket
/lib/average.rb
UTF-8
406
4.28125
4
[]
no_license
# Public: Takes an array and returns a average # # sum - The sum of the array. # i - Iteration agent and number of integers in the array. # avg - The average of the array. # # Examples # # average([1,2,3,4]) # # = > 2,5 # # Returns the average. def average(arr) sum = 0 i = 0 while i < arr.length sum = sum + arr[i] i += 1 end avg = sum.to_f / i return avg end
true
d7215a5dc594212f89c9a2467fd2fffadb9b4cf0
Ruby
simon74/ruby-atm-microcourse
/step1_begin.rb
UTF-8
779
4.375
4
[]
no_license
# Imagine an ATM with ONLY $5 notes. The function accepts a single parameter - amount. # Return false if the amount cannot be given in $5 notes (eg. 23 or 36). # Otherwise, return an array of notes - eg. withdraw(15) would return [5, 5, 5] # TIPS: # Modulus operator (%) gives the remainder. So, 5 % 2 = 1 (five divided by two has a remainder of 1) # Arrays: [] defines an empty array. # Shover operator (<<) adds to an array. Eg: # my_array = [] # my_array << 5 # my_array << 7 # my_array.inspect # (prints out [5, 7]) # # times method: # 3.times { do_something } # will call do_something 3 times! def withdraw(amount) if amount <= 0 # this deals with some of the situations... return false end # ToDo: figure out this bit return [] end require './step1_tests.rb'
true
b8d7a9ed23ad643df4d6f01600415695fbb5fdad
Ruby
alexdean/eight_corner
/lib/eight_corner/quadrant.rb
UTF-8
579
3.171875
3
[ "MIT" ]
permissive
module EightCorner # a Bounds has 4 quadrants. # TODO: singleton instance for each quadrant? # would allow each to return their own angle_range_for. module Quadrant UPPER_LEFT = 0 UPPER_RIGHT = 1 LOWER_RIGHT = 2 LOWER_LEFT = 3 def self.angle_range_for(quad) # the valid range of angles (to the next point) # based on the quadrant the current point is in. { UPPER_LEFT => 30..240, UPPER_RIGHT => 120..330, LOWER_LEFT => 300..(330+180), LOWER_RIGHT => 210..(330+90) }[quad] end end end
true
6032b43bf38ba16669bf324788e29aeb3094f435
Ruby
StephanYu/rock_paper_scissors_gem
/spec/entities/game_spec.rb
UTF-8
1,057
2.890625
3
[ "MIT" ]
permissive
require_relative '../spec_helper.rb' describe RockPapeScis::Game do describe "#play" do it "returns the player's name who chose ROCKS > SCISSORS" do result = RockPapeScis::Game.play(player1 = {name: "John", move: "rock"}, player2 = {name: "Stephan", move: "scissors"}) expect(result).to eq "John" end it "returns the player's name who chose SCISSORS > PAPER" do result = RockPapeScis::Game.play(player1 = {name: "John", move: "scissors"}, player2 = {name: "Stephan", move: "paper"}) expect(result).to eq "John" end it "returns the player's name who chose PAPER > ROCK" do result = RockPapeScis::Game.play(player1 = {name: "John", move: "rock"}, player2 = {name: "Stephan", move: "paper"}) expect(result).to eq "Stephan" end it "returns a tie when both playes choose the same move" do result = RockPapeScis::Game.play(player1 = {name: "John", move: "rock"}, player2 = {name: "Stephan", move: "rock"}) expect(result).to eq "It's a tie. Keep playing" end end end
true
353cc1889776437dcc998ebb8b794be83b5471dd
Ruby
jimmyz/familysearch-api-examples
/ruby/01_read_person_simple.rb
UTF-8
819
2.671875
3
[]
no_license
require 'faraday' require 'json' require 'pp' # For sake of demonstration, we will acquire an access token from # https://sandbox.familysearch.org/platform/ access_token = File.read 'access_token.txt' client = Faraday.new () do |faraday| faraday.response :logger faraday.headers['Accept'] = 'application/x-fs-v1+json,application/x-gedcomx-atom+json,application/json' faraday.authorization('Bearer',access_token) faraday.adapter Faraday.default_adapter # make requests with Net::HTTP end response = client.get "https://sandbox.familysearch.org/platform/tree/persons/KW4V-6T7" gedcomx = JSON.parse response.body pp gedcomx puts "Name: " + gedcomx['persons'][0]['display']['name'] puts "Gender: " + gedcomx['persons'][0]['display']['gender'] puts "Birth Date: " + gedcomx['persons'][0]['display']['birthDate']
true
d089362f7dd8da2c646fdc4fde77caf6667244fa
Ruby
virtusize/build_script
/Buildfile
UTF-8
2,725
2.578125
3
[]
no_license
define HELP_MESSAGE Usage: make [COMMAND] Commands: build Build a Docker image. tag Tag the created image in local repository. push Push the Docker image to Docker Hub, will not push develop or feature-* tags. force-push Push the Docker image to Docker Hub. help Display this help message. Docker tags for git branches: master Git describe (i.e. 5.3.1) and <master> and <latest> for latest develop Branch name: <develop> release Version number of branch with 'release-' prefix (i.e. release-5.3.1) and <release> for latest hotfix Version number of branch with 'hotfix-' prefix (i.e. hotfix-5.3.1) and <hotfix> for latest feature Branch name: <feature-some-name> - will not be pushed to Docker hub, but you can push manually with force-push. endef export HELP_MESSAGE ORG_NAME := virtusize APP_NAME ?= $(shell basename $(CURDIR)) DOCKER_IMAGE_NAME := $(ORG_NAME)/$(APP_NAME) IGNORE_TAGS := feature-% GIT_BRANCH := $(shell git rev-parse --abbrev-ref HEAD) GIT_TAG := $(shell git describe --tags --always) ifeq ($(GIT_BRANCH),master) TAGS := $(GIT_TAG) master latest endif ifeq ($(GIT_BRANCH),develop) TAGS := develop endif ifneq (,$(findstring release,$(GIT_BRANCH))) TAGS := $(subst /,-,$(GIT_BRANCH)) release endif ifneq (,$(findstring hotfix,$(GIT_BRANCH))) TAGS := $(subst /,-,$(GIT_BRANCH)) hotfix endif ifneq (,$(findstring feature,$(GIT_BRANCH))) TAGS := $(subst /,-,$(GIT_BRANCH)) endif LIMITED_TAGS := $(filter-out $(IGNORE_TAGS),$(TAGS)) define log_info echo "\033[0;36m$1\033[0m" endef .PHONY : build test tag push help build: @echo "Organization: $(ORG_NAME)" @echo "Application: $(APP_NAME)" @echo "Branch: $(GIT_BRANCH)" @echo "Tag: $(GIT_TAG)" git status --porcelain @$(call log_info,Building image: $(DOCKER_IMAGE_NAME):$(word 1,$(TAGS))) @docker build -t $(DOCKER_IMAGE_NAME):$(word 1,$(TAGS)) . test: @$(call log_info,Running tests for image: [ $(DOCKER_IMAGE_NAME):$(word 1,$(TAGS)) ]) @docker run -t --net=host $(DOCKER_IMAGE_NAME):$(word 1,$(TAGS)) make test tag: @$(call log_info,Tagging $(DOCKER_IMAGE_NAME):$(word 1,$(TAGS)) with: [ $(foreach t,$(wordlist 2,$(words $(TAGS)),$(TAGS)),$(t) )]) $(foreach t,$(wordlist 2,$(words $(TAGS)),$(TAGS)), docker tag -f $(DOCKER_IMAGE_NAME):$(word 1,$(TAGS)) $(DOCKER_IMAGE_NAME):$(t);) push: tag @$(call log_info,Pushing image: [ $(foreach t,$(LIMITED_TAGS),$(DOCKER_IMAGE_NAME):$(t) )]) $(foreach t,$(LIMITED_TAGS),docker push $(DOCKER_IMAGE_NAME):$(t);) force-push: tag @$(call log_info,Pushing image: [ $(foreach t,$(TAGS),$(DOCKER_IMAGE_NAME):$(t) )]) $(foreach t,$(TAGS),docker push $(DOCKER_IMAGE_NAME):$(t);) help: @echo "$$HELP_MESSAGE"
true
23e28210d4c3d21e0b75575b0e2cdef5c71d0d9b
Ruby
MisterMur/collections_practice_vol_2-nyc-web-career-010719
/collections_practice.rb
UTF-8
809
3.3125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# your code goes here def begins_with_r(tools) tools.each do |i| if i.start_with?('r')==false return false end end true end def contain_a(array) array.select do |i| i.include?('a') end end def first_wa(array) array.each do |i| if i.is_a?(String) && i.start_with?('wa') return i end end end def remove_non_strings(array) array.select do |i| i.is_a?(String) end end def count_elements(array) # array.each do |el| # array.count(el) # end # array.each_with_object(Hash.new(0)) do |hash, item| # # h2[h1[:name]] += 1 # if hash[item] # hash[item] += 1 # else # hash[item] = 0 # end # end # array.uniq.map { |x| [x, array.count(x)] }.to_h h = Hash.new(0) array.each { |l| h[l] += 1 } h.to_a end
true
85fd285fcbced1fd42419831e67787cd3561ed36
Ruby
pygospa/researchr
/vendor/gems/unicode_utils-1.0.0/lib/unicode_utils/each_word.rb
UTF-8
3,106
3.015625
3
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
# -*- encoding: utf-8 -*- require "unicode_utils/read_cdata" module UnicodeUtils # Maps codepoints to integer codes. For the integer code to property # mapping, see #compile_word_break_property in data/compile.rb. WORD_BREAK_MAP = Impl.read_hexdigit_map("word_break_property") # :nodoc: # Split +str+ along word boundaries according to Unicode's Default # Word Boundary Specification, calling the given block with each # word. Returns +str+, or an enumerator if no block is given. # # Example: # # require "unicode_utils/each_word" # UnicodeUtils.each_word("Hello, world!").to_a => ["Hello", ",", " ", "world", "!"] def each_word(str) return enum_for(__method__, str) unless block_given? cs = str.each_codepoint.map { |c| WORD_BREAK_MAP[c] } cs << nil << nil # for negative indices word = String.new.force_encoding(str.encoding) i = 0 str.each_codepoint { |c| word << c if Impl.word_break?(cs, i) && !word.empty? yield word word = String.new.force_encoding(str.encoding) end i += 1 } yield word unless word.empty? str end module_function :each_word module Impl # :nodoc:all def self.word_break?(cs, i) # wb3 cs_i = cs[i] i1 = i + 1 cs_i1 = cs[i1] if cs_i == 0x0 && cs_i1 == 0x1 return false end # wb3a if cs_i == 0x2 || cs_i == 0x0 || cs_i == 0x1 return true end # wb3b if cs_i1 == 0x2 || cs_i1 == 0x0 || cs_i1 == 0x1 return true end # wb5 i0 = i # inline skip_l c = nil loop { c = cs[i0]; break unless c == 0x3 || c == 0x4; i0 -= 1 } ci0 = c if ci0 == 0x6 && cs_i1 == 0x6 return false end # wb6 i2 = i1 + 1 # inline skip_r loop { c = cs[i2]; break unless c == 0x3 || c == 0x4; i2 += 1 } if ci0 == 0x6 && (cs_i1 == 0x7 || cs_i1 == 0x9) && cs[i2] == 0x6 return false end # wb7 i_1 = i0 - 1 # inline skip_l loop { c = cs[i_1]; break unless c == 0x3 || c == 0x4; i_1 -= 1 } if cs[i_1] == 0x6 && (ci0 == 0x7 || ci0 == 0x9) && cs_i1 == 0x6 return false end # wb8 if ci0 == 0xA && cs_i1 == 0xA return false end # wb9 if ci0 == 0x6 && cs_i1 == 0xA return false end # wb10 if ci0 == 0xA && cs_i1 == 0x6 return false end # wb11 if cs[i_1] == 0xA && (ci0 == 0x8 || ci0 == 0x9) && cs_i1 == 0xA return false end # wb12 if ci0 == 0xA && (cs_i1 == 0x8 || cs_i1 == 0x9) && cs[i2] == 0xA return false end # wb13 if ci0 == 0x5 && cs_i1 == 0x5 return false end # wb13a if (ci0 == 0x6 || ci0 == 0xA || ci0 == 0x5 || ci0 == 0xB) && cs_i1 == 0xB return false end # wb13b if ci0 == 0xB && (cs_i1 == 0x6 || cs_i1 == 0xA || cs_i1 == 0x5) return false end # break unless next char is Extend/Format cs_i1 != 0x3 && cs_i1 != 0x4 end end end
true
4d297a9b130662253496386804c717cb1957f480
Ruby
JunaidQ/deadlink
/lib/tasks/manual_broken_llink.rake
UTF-8
640
2.546875
3
[]
no_license
namespace :pick do desc "Pick manual broken link" task :manual_link => :environment do if Rails.env == 'production' root = 'production_url' else root = 'http://localhost:3000' end puts "Enter specific link with compny address ====> /some-link: " u = STDIN.gets.chomp url = root.concat(u) uri = URI.parse(url) puts "===> uri #{uri}" response = nil Net::HTTP.start(uri.host, uri.port) { |http| response = http.head(uri.path.size > 0 ? uri.path : "/") if response.code == "404" puts "broken link" else puts "not broken link" end } end end
true
96e1ced59f8709a6040c0f0fe62c127985ee33f5
Ruby
isakib/prickle
/lib/prickle/capybara/xpath.rb
UTF-8
668
2.578125
3
[]
no_license
require_relative 'xpath/expression' module Prickle module Capybara module XPath def self.for_element_with type, identifier XPath::Element.new(type,identifier).to_s end private class Element def initialize type, identifier @type = type @identifier = identifier end def to_s "//#{@type}[#{identifier}]" end def identifier return @identifier.each_pair.inject([]) do | xpath, (identifier, value) | xpath << XPath::Expression.new(identifier, value).to_s end.join Expression::SEPARATOR end end end end end
true
52bb4913e6579310d59a1465c7b73e3d3e0d703b
Ruby
MrSnickers/FIS
/activities/playlister/playlister_partA/lib/genre_class.rb
UTF-8
319
3.265625
3
[]
no_license
### GENRE CLASS class Genre attr_accessor :name @@genre_array = [] def initialize @@genre_array << self end def self.reset_genres @@genre_array = [] end def songs @songs ||= [] end def artists songs.collect{|song| song.artist}.uniq end def self.all @@genre_array end end
true
bd61352a1f3cb64aecf7df81d20c9150eb46c164
Ruby
joshsarna/interview_cake
/reverse_words.rb
UTF-8
184
3.953125
4
[]
no_license
# Write a method reverse_words!() that takes a message as a string and reverses the order of the words in place. def reverse_words!(message) message.split(" ").reverse.join(" ") end
true
cc46c564ad00ac17559ddc130f11531c06e30399
Ruby
radu-constantin/prep_work
/final_exercises/exercise16.rb
UTF-8
209
3.21875
3
[]
no_license
#delete all words that start with "s" a = ['white snow', 'winter wonderland', 'melting ice', 'slippery sidewalk', 'salted roads', 'white trees'] a.map! do |word| word.split(" ") end a.flatten puts a
true
c68e973313f004011fa10ff751f71786db18c69a
Ruby
bookmate/bm-cancellation
/lib/bm/cancellation.rb
UTF-8
1,489
2.578125
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'bm/cancellation/version' require 'bm/cancellation/interface' require 'bm/cancellation/signal' require 'bm/cancellation/deadline' require 'bm/cancellation/either' module BM # Provides tools for cooperative cancellation and timeouts management. module Cancellation class << self # A cancellation object backed by atomic boolean. Becomes cancelled when an associated {Control} # has done. # # @example Usage # cancellation, control = BM::Cancellation.new # Signal.trap('INT', &control) # # do_work until cancel.cancelled? # # @return [Control] a cancellation and its control handler def new Control.new.freeze end # A cancellation object that expires after certain period of time. # # @example Usage # cancellation = BM::Cancellation.timeout(seconds: seconds) # do_work until cancellation.cancelled? # # @example Joins with another cancellation # cancellation.timeout(seconds: 5).then do |timeout| # do_work until timeout.expired? # end # # @param seconds [Float, Integer] is a number seconds after the timeout will be expired # @param clock [#time] override a time source (non public) # @return [Cancellation] def timeout(seconds:, clock: Deadline::Clock) Deadline.new(seconds_from_now: seconds, clock: clock).freeze end end end end
true
2efb2e53a606487e0d8439bcf4b171d49ecf4834
Ruby
darkripper/Tumble.rb
/lib.rb
UTF-8
2,007
2.640625
3
[]
no_license
require 'rubygems' require 'ruby-multipart-post' require 'active_support' def rename_jpegs_to_jpgs files = Dir['*.jpeg'] files.each do |filename| filerenamed = filename.gsub('.jpeg', '') + '.jpg' File.rename(filename, filerenamed) end end def select_files_to_upload rename_jpegs_to_jpgs files = Dir['*.jpg'] files.delete_if {|file| file.include? '-tumbled' } @selected_files = [] files.each do |file| @selected_files.push(file) end end def select_older_than(older_than) files = Dir['*-tumbled*'] @selected_files = [] files.each do |file| if File.stat(file).mtime < older_than @selected_files.push(file) end end end def delete_already_uploaded select_older_than(7.days.ago) if @selected_files.empty? puts 'No new files to delete' else @selected_files.each do |file| File.delete(file) print '.' end puts '' puts 'Older Files successfuly deleted.' end end def upload_files_to(tumblr) select_files_to_upload if @selected_files.empty? puts 'no new files to upload' else @selected_files.each do |file| @post = Photo.new(file, tumblr) @post.build_request @post.upload end end end class Photo attr_accessor :file, :email, :password, :group def initialize(filename, folder) @file = filename @email = '' @password = '' if folder == 'default' @group = nil else @group = folder + '.tumblr.com' end end def build_request @request = MultiPart::Post.new( 'data' => FileUploadIO.new(@file, 'image/jpg'), 'email' => @email, 'password' => @password, 'type' => 'photo', 'state' => 'queue', 'group' => @group ) end def upload @result = @request.submit('http://www.tumblr.com/api/write') if @result.code == '201' print '.' rename(@file) else puts "#{@file} upload failed" puts "Status: #{@result.code} #{@result.message}" end end def rename(filename) filerenamed = filename.gsub('.jpg', '') + '-tumbled' + '.jpg' File.rename(filename, filerenamed) end end
true
f4907b0b2db440ddc4bb29d39aae147f6a615434
Ruby
relaton/iso-bib-item
/lib/iso_bib_item/iso_document_status.rb
UTF-8
1,742
2.734375
3
[ "MIT", "BSD-2-Clause" ]
permissive
# frozen_string_literal: true require 'iso_bib_item/document_status' require 'iso_bib_item/localized_string' module IsoBibItem # module IsoDocumentStageCodes # PREELIMINARY = '00' # PROPOSAL = '10' # PREPARATORY = '20' # COMMITTE = '30' # ENQUIRY = '40' # APPROVAL = '50' # PUBLICATION = '60' # REVIEW = '90' # WITHDRAWAL = '95' # end # module IsoDocumentSubstageCodes # REGISTRATION = '00' # START_OF_MAIN_ACTION = '20' # COMPLETION_OF_MAIN_ACTION = '60' # REPEAT_AN_EARLIER_PHASE = '92' # REPEAT_CURRENT_PHASE = '92' # ABADON = '98' # PROCEED = '99' # end # ISO Document status. class IsoDocumentStatus < DocumentStatus # @return [String, NilClass] attr_reader :stage # @return [String, NilClass] attr_reader :substage # @return [Integer, NilClass] attr_reader :iteration # @param status [String, NilClass] # @param stage [String, NilClass] # @param substage [String, NilClass] # @param iteration [Integer, NilClass] def initialize(status: nil, stage: nil, substage: nil, iteration: nil) raise ArgumentError, 'status or stage is required' unless status || stage super LocalizedString.new(status) @stage = stage @substage = substage @iteration = iteration end # @param builder [Nkogiri::XML::Builder] def to_xml(builder) if stage.nil? || stage.empty? super else builder.status do builder.stage stage builder.substage substage if substage builder.iteration iteration if iteration end end end end end
true
e57caca5c01a2a74285021ef3acf792d6eef6c9b
Ruby
LifebookerInc/hash_dealer
/spec/lib/path_string_spec.rb
UTF-8
2,104
2.671875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe PathString do it "should match values with a ':' as wildcards" do PathString.new(":test").should == PathString.new("abcdefg") end it "should work on nested hashes and arrays" do PathString.as_sorted_json(:abc => [":1",":2",":3"]).should == PathString.as_sorted_json({:abc => ["1","2","3"]}) a = { "provider[address][address_name]" => ":name", "provider[address][city]" => ":city", "provider[address][state]" => ":state", "provider[address][street_line_1]" => ":street", "provider[address][zip]" => ":zip", "provider[current_step]" => "2", "provider[payment_type_ids]" => [":id"], "provider[statement_of_business]" => ":statement", "provider[url]" => ":url" } b = { "provider[address][address_name]" => "Brady+Rowe", "provider[address][city]" => "New+York", "provider[address][state]" => "NY", "provider[address][street_line_1]" => "708+Kutch+Squares", "provider[address][zip]" => "10024", "provider[current_step]" => "2", "provider[payment_type_ids]" => ["1"], "provider[statement_of_business]" => "Hic+nulla+tempora+voluptatibus+nemo.+Mollitia+qui+deleniti+rerum.+Ut+omnis+adipisci+eos.", "provider[url]" => "http%3A%2F%2Ffoo.com" } PathString.as_sorted_json(a).should == PathString.as_sorted_json(b) end it "should match wildcard paths" do PathString.paths_match?("/a/1/test/2", "/a/:1/test/:2").should be_true end it "should actually sort things with as_sorted_json" do a = [["user_login", {"user_name"=>"username", "user_type"=>"Client", "user_id"=>37, "password"=>"123456", "password_confirmation"=>"123456"}]] b = {:user_login=> {:password=>":password", :password_confirmation=>":password_conf", :user_id=>":id", :user_name=>":username", :user_type=>"Client"}} PathString.as_sorted_json(a).should == PathString.as_sorted_json(b) end end
true
b1f100656d0b2efc4adf0755869d25541cc2aab5
Ruby
ezrashim/blackjack
/spec/blackjack_spec.rb
UTF-8
4,386
3.484375
3
[]
no_license
require_relative "../card" require_relative "../hand" require_relative "../deck" require_relative "../player" require_relative "../dealer" require_relative "../blackjack" RSpec.describe Card do let (:card) { Card.new('♦', 'A') } describe '.new' do it 'creates a card' do expect(card.class).to eq(Card) end end describe '#type' do it 'defines the value into different types' do expect(card.type).to eq("ace") end end end RSpec.describe Deck do let (:deck) { Deck.new } describe '.new' do it 'creates a deck' do expect(deck.cards.size).to eq(52) end end end RSpec.describe Hand do let (:hand_1) {Hand.new} let (:hand_2) {Hand.new} describe '.new' do it 'creates a blank hand ' do expect(hand_1.hand.size).to eq(0) expect(hand_1.score).to eq(0) end end describe '#deal' do it 'deals a number of cards' do hand_1.deal(2) expect(hand_1.hand.size).to eq(2) expect(hand_1.score).to eq(0) hand_2.deal(3) expect(hand_2.hand.size).to eq(3) expect(hand_2.score).to eq(0) end end describe '#calculate_hand' do it 'calculates the score of a hand' do hand_1.deal(2) expect(hand_1.calculate_hand).to be > 1 hand_2.deal(5) expect(hand_2.calculate_hand).to be > 10 end end end RSpec.describe Player do let (:player) {Player.new} describe '.new' do it 'creates a new player' do expect(player.hand.hand).to eq([]) expect(player.hand.score).to eq(0) end end end RSpec.describe Dealer do let (:dealer) {Dealer.new} describe '.new' do it 'creates a new dealer' do expect(dealer.hand.hand).to eq([]) expect(dealer.hand.score).to eq(0) end end end RSpec.describe Blackjack do let (:blackjack) {Blackjack.new} describe '.new' do it 'creates a new blackjack game' do expect(blackjack.player.hand.hand).to eq([]) expect(blackjack.dealer.hand.hand).to eq([]) expect(blackjack.deck.cards.size).to eq(52) end end describe '#deal_player' do it 'deals out a card to player' do blackjack.deal_player expect(blackjack.player.hand.hand.size).to eq(1) end end describe '#deal_dealer' do it 'deals out a card to dealer' do blackjack.deal_dealer expect(blackjack.dealer.hand.hand.size).to eq(1) end end describe '#player_score' do it 'puts out a player score' do blackjack.deal_player blackjack.player.hand.hand[-1].value = 10 blackjack.deal_player blackjack.player.hand.hand[-1].value = 9 expect(blackjack.player_score).to eq(19) end it 'puts out a player score' do blackjack.deal_player blackjack.player.hand.hand[-1].value = "A" blackjack.deal_player blackjack.player.hand.hand[-1].value = "K" expect(blackjack.player_score).to eq(21) end end describe '#dealer_score' do it 'puts out a dealer score' do blackjack.deal_dealer blackjack.dealer.hand.hand[-1].value = 10 blackjack.deal_dealer blackjack.dealer.hand.hand[-1].value = 9 expect(blackjack.dealer_score).to eq(19) end it 'puts out a dealer score' do blackjack.deal_dealer blackjack.dealer.hand.hand[-1].value = "A" blackjack.deal_dealer blackjack.dealer.hand.hand[-1].value = "K" expect(blackjack.dealer_score).to eq(21) end end describe '#result' do it 'shows results' do blackjack.deal_dealer blackjack.dealer.hand.hand[-1].value = 10 blackjack.deal_player blackjack.player.hand.hand[-1].value = "A" expect(blackjack.result).to eq("You win!") end end describe '#play!' do it 'plays the game' do blackjack.play! allow(blackjack.play!).to receive(:gets).and_return("S") expect{blackjack.play!}.to output(" ").to_stdout end end end
true
b57de3dcdbeba81314dc4bc1fa1efbc5c99372a6
Ruby
Besermenji/Table-Reservation
/vendor/bundle/ruby/2.2.0/gems/authority-3.1.0/lib/authority/authorizer.rb
UTF-8
1,698
2.890625
3
[ "MIT" ]
permissive
module Authority class Authorizer # The base Authorizer class, from which all the authorizers in an app will # descend. Provides the authorizer with both class and instance methods # like `updatable_by?(user)`. # Exactly which methods get defined is determined from `config.abilities`; # the class is evaluated after any user-supplied config block is run # in order to make that possible. attr_reader :resource def initialize(resource) @resource = resource end # Whitelisting approach: anything not specified will be forbidden def self.default(adjective, user, options = {}) false end # the instance default method calls the class default method def default(adjective, user, options = {}) user_and_maybe_options = self.class.send(:user_and_maybe_options, user, options) self.class.send(:"#{adjective}_by?", *user_and_maybe_options) end # Each method simply calls the `default` method (instance or class) Authority.adjectives.each do |adjective| class_eval <<-RUBY, __FILE__, __LINE__ + 1 def self.#{adjective}_by?(user, options = {}) default(:#{adjective}, *user_and_maybe_options(user, options)) end def #{adjective}_by?(user, options = {}) user_and_maybe_options = self.class.send(:user_and_maybe_options, user, options) default(:#{adjective}, *user_and_maybe_options) end RUBY end def self.user_and_maybe_options(user, options = {}) [user, options].tap {|args| args.pop if args.last == {}} end private_class_method :user_and_maybe_options end class NoAuthorizerError < StandardError ; end end
true
3d85a227199c20f1406b5cd27fecd9dd9b4e0c3a
Ruby
vanithajayasri/ruby_assignment2_question1
/app/controllers/concerns/foobar.rb
UTF-8
154
2.90625
3
[]
no_license
class Foobar # ENTER CODE FOR Q2 HERE def initialize(k) # instance method @k = k end def bar(y, arr={}) "#{y}#{@k}#{arr[:sat]}" end end
true
67b5f596342e17c6083c0c2797257fed878960ea
Ruby
bsboris/git_reporting
/lib/git_reporting/message_parser.rb
UTF-8
855
2.890625
3
[ "MIT" ]
permissive
require "chronic_duration" module GitReporting class MessageParser attr_reader :input, :regexp def self.parse(*args) new(*args).parse end def initialize(input) @input = input.to_s prefix = GitReporting.configuration.prefix @regexp = /\[\s*#{prefix && prefix + "\s*"}\s*(\d[^\[\]]*)\]/m end def parse message = parse_message time = parse_time [message, time] end private def parse_message input.gsub(regexp, "").strip end def parse_time times = input.scan(regexp) time = if times[0] times[0][0] # we want to take only first time marker else nil end return nil unless time.present? time = "#{time}:00" if time =~ /^\d{1,2}:\d{1,2}$/ ChronicDuration.parse(time, keep_zero: true) end end end
true
733646f9a46518e86d3f65e46e6ae9c713072f82
Ruby
fakebenjay/parrot-ruby-web-0217
/parrot.rb
UTF-8
60
2.734375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def parrot(polly="Squawk!") puts polly return polly end
true
463cfeb8207249dfab337ea3411833c245d7ab99
Ruby
jo-hackson/phase-0-tracks
/ruby/hashes.rb
UTF-8
2,592
4.28125
4
[]
no_license
# first create a hash called "form" to store the information # it is unnecessary to create empty values because the keys will be added anyways form = {} # client name # prompt the user to input client name # capitalize to make sure that it is grammatically correct puts "What is the client's first name?" first_name = gets.chomp.to_s.capitalize! puts "What is the client's last name?" last_name = gets.chomp.to_s.capitalize! form[:full_name] = "#{first_name}" + " " + "#{last_name}" # client age # prompt user to input client's age puts "What is the client's age?" form[:age] = gets.chomp.to_i # number of children # prompt user to input number of children client has puts "How many children does the client have?" form[:children] = gets.chomp.to_i # decor theme # prompt user to input client's decor theme preference puts "What type of decor theme does the client prefer?" form[:decor_theme] = gets.chomp.to_s # budget below $100k # prompt user to select whether client prefers a budget # above or below $50k # if the user does not input either "y" or "n", then # the value returned will be nil and the "Sorry" phrase # will appear puts "Does the client want a budget under $50k? (y/n)" budget_response = gets.chomp.to_s if budget_response == "y" budget = "low" elsif budget_response == "n" budget = "high" else puts "Sorry, did not understand client's budget preference" end form[:budget] = budget puts "This is the information that you have inputted." puts "Client's name: #{form[:full_name]}" puts "Client's age: #{form[:age]}" puts "Number of children: #{form[:children]}" puts "Preferred decor theme: #{form[:decor_theme]}" puts "Budget: #{form[:budget]}" # prompt user if there are any errors # if "none" is inputted, then form will print will values previously entered # if something other than "none" is inputted, then # a prompt will appear asking which key is incorrect # based on the response, that value will be updated puts "Are there any errors? Please type 'yes' or 'none'." correction = gets.chomp if correction != "none" puts "Select which entry is incorrect: client name, age, children, decor theme, or budget." incorrect_entry = gets.chomp.to_sym if incorrect_entry == :budget puts "Please enter 'low' or 'high'" else puts "Please enter the correction for #{incorrect_entry}" end correction = gets.chomp form[incorrect_entry] = correction else end puts "#{form[:full_name]} is #{form[:age]} years old with #{form[:children]} children and likes #{form[:decor_theme]} theme and has a #{form[:budget]} budget."
true
fd18e6dfcf9adc55ad5a033907ec50f9697826e1
Ruby
blake97/phase-0-tracks
/ruby/A.rb
UTF-8
1,571
4.09375
4
[]
no_license
########### Business Methods ########### #reference vowels = "aeiou" consonants = "abcdefghijklmnopqrstuvwxyz".delete("#{vowels}") transformed_array =[] def name_processing (input_name) reverse_name = input_name.split(' ').reverse.join(' ') # <== reverse and break into characters. characters_array = reverse_name.chars end def spy_name_generation(characters_array) #loop through resulting array, determine appropriate reference strand, # create next value. Take care of spaces and end-of-reference string cases. characters_array.map! do |char| if char == ' ' next_char = ' ' elsif char == 'u' next_char = 'a' elsif char == 'z' next_char ='b' elsif consonants.include?(char) next_consonant_ref_index = consonants.index(char)+1 next_char = consonants[next_consonant_ref_index] elsif vowels.include?(char) next_vowel_ref_index = vowels.index(char)+1 next_char = vowels[next_vowel_ref_index] end transformed_array = transformed_array.push(next_char) end spy_name = transformed_array.join('') end ########### Driver Code ########### # get name, downcase, split string into wors, reverse word order, rejoin # words into one string. puts "Enter your name, or enter 'quit' to exit the program" input_name = gets.chomp.downcase loop do puts "Your spy name is #{spy_name}. Enter another name, or type 'quit' and press enter to exit the program." input_name = gets.chomp.downcase break if input_name == 'quit' end puts "Thank you and have a nice day."
true
bc9079dd3e842427a9bf736668b64314f5d6291c
Ruby
uranussg/aA_classwork
/W1D3/nauseating_numbers/phase_1.rb
UTF-8
1,867
3.6875
4
[]
no_license
def strange_sums(arr) count = 0 arr[0..-2].each_with_index do |el, idx| count +=1 if arr[idx + 1..-1].include?(-el) end count end # p strange_sums([2, -3, 3, 4, -2]) # 2 # p strange_sums([42, 3, -1, -42]) # 1 # p strange_sums([-5, 5]) # 1 # p strange_sums([19, 6, -3, -20]) # 0 # p strange_sums([9]) # 0 def pair_product(numbers, product) #new_arr = [] (0...numbers.length).each do |i| (i+1...numbers.length).each do |j| #new_arr << str[i..j] return true if numbers[i]*numbers[j] == product end end false end # p pair_product([4, 2, 5, 8], 16) # true # p pair_product([8, 1, 9, 3], 8) # true # p pair_product([3, 4], 12) # true # p pair_product([3, 4, 6, 2, 5], 12) # true # p pair_product([4, 2, 5, 7], 16) # false # p pair_product([8, 4, 9, 3], 8) # false # p pair_product([3], 12) # false def rampant_repeats(str, hash) new_str = "" str.each_char do |char| if hash.has_key?(char) new_str += char * hash[char] else new_str += char end end new_str end # p rampant_repeats('taco', {'a'=>3, 'c'=>2}) # 'taaacco' # p rampant_repeats('feverish', {'e'=>2, 'f'=>4, 's'=>3}) # 'ffffeeveerisssh' # p rampant_repeats('misispi', {'s'=>2, 'p'=>2}) # 'mississppi' # p rampant_repeats('faarm', {'e'=>3, 'a'=>2}) # 'faaaarm' def perfect_square(num) num.downto(2) do |i| return true if i*i == num end false end p perfect_square(1) # true p perfect_square(4) # true p perfect_square(64) # true p perfect_square(100) # true p perfect_square(169) # true p perfect_square(2) # false p perfect_square(40) # false p perfect_square(32) # false p perfect_square(50) # false
true
6816d6dc74078d75571f4989885c18c5a6d146ac
Ruby
agorf/adventofcode
/2018/04/2.rb
UTF-8
802
2.828125
3
[]
no_license
#!/usr/bin/env ruby require 'time' entries = $stdin.readlines.map { |line| { when: Time.parse(line), id: line[/(?<=#)\d+/], action: line.split(' ').last(2).join(' ') } }.sort_by(&:first) prev_id = nil # Fill-in missing guard ids entries.each do |entry| if entry[:id].nil? entry[:id] = prev_id else prev_id = entry[:id].to_i end end entries.reject! { |entry| entry[:action] == 'begins shift' } sleep_mins_by_guard = Hash.new { |h, k| h[k] = Array.new(60, 0) } entries.each_slice(2) do |asleep, awake| id = asleep[:id] (asleep[:when].min...awake[:when].min).each do |min| sleep_mins_by_guard[id][min] += 1 end end puts sleep_mins_by_guard.map { |id, mins| [id].concat(mins.each_with_index.max.reverse) # id, min, times }.max_by(&:last)[0..1].reduce(:*)
true
ca71a61f3e5582460cde3d95e4cb3000b5e3a5bb
Ruby
mochacaremel/ttt-4-display-board-rb-v-000
/lib/display_board.rb
UTF-8
951
3.953125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def display_board(board) puts " #{board[0]} | #{board[1]} | #{board[2]} " puts "-----------" puts " #{board[3]} | #{board[4]} | #{board[5]} " puts "-----------" puts " #{board[6]} | #{board[7]} | #{board[8]} " end # def display_board # board = [" "," "," "," "," "," "," "," "," "] # (rows[0]).to eq(" | | ") # (rows[1]).to eq("-----------") # (rows[2]).to eq(" | | ") # (rows[3]).to eq("-----------") # (rows[4]).to eq(" | | ") # end # def display_rainbow(color) # puts "R: #{color[0]}, O: #{color[1]}, Y: #{color[2]}, G: #{color[3]}, B: #{color[4]}, I: #{color[5]}, V: #{color[6]}" # end # rows = output.split #{}"{rows[0]}", "{rows[1]}", "{rows[2]}" #{rows[0]}" #{rows[1]}" #{rows[2]}" # display_board(board) {"#rows[0]"} # ```ruby # board = [" "," "," "," "," "," "," "," "," "] # display_board(board) # Define display_board that accepts a board and prints # out the current state.
true
3ac6eab86feec77e21764535700ca083459efd78
Ruby
marcos-x86/AT04_API_test
/MarcosLara/Session_02/Practice_04/customer_id.rb
UTF-8
702
4.125
4
[]
no_license
=begin Write 1 Method called customer_id This Methods - Should receive 2 arguments : name and customer_id - Using short-if expression evaluate the id value according : - Only if ID is greater than 100 print the message “Thanks to be our customer” otherwise only print “Thanks” - Change to uppercase the name Print the text, e.g. : Hi <name_in_uppercase> Your are our customer <ID> <message_according_id> =end def customer_id (name, id) message = id > 100 ? 'Thanks to be our customer' : 'Thanks' puts "Hi #{name.upcase}\nYour are our customer #{id}. #{message}" end #Method call with parenthesis customer_id('Albert', 50) #Method call without parenthesis customer_id 'Nikola', 150
true
3590d5dbf40c54ec878e5683f7f1147cf43743c6
Ruby
gtormiston/ruby-kickstart
/session2/3-challenge/6_array.rb
UTF-8
1,024
4.53125
5
[ "MIT" ]
permissive
# Write a method named prime_chars? which takes array of strings # and returns true if the sum of the characters is prime. # # Remember that a number is prime if the only integers that can divide it with no remainder are 1 and itself. # # Examples of length three # prime_chars? ['abc'] # => true # prime_chars? ['a', 'bc'] # => true # prime_chars? ['ab', 'c'] # => true # prime_chars? ['a', 'b', 'c'] # => true # # Examples of length four # prime_chars? ['abcd'] # => false # prime_chars? ['ab', 'cd'] # => false # prime_chars? ['a', 'bcd'] # => false # prime_chars? ['a', 'b', 'cd'] # => false def prime_chars?(array) length = array.join.length return false if length <= 1 # 0 and 1 aren't primes Math.sqrt(length).to_i.downto(2).each { |x| return false if length % x == 0} #finds the square root of length, #then test each number incrememntally from that number down to 2, to see whether length is divisible by it. true end prime_chars?(['a', 'b', 'c'])
true
729f9294e718fc56c03ab2ac08bf70217e27a2fd
Ruby
DanielHauge/LanguageProject
/Ruby/problem3.rb
UTF-8
420
3.421875
3
[ "MIT" ]
permissive
load 'problem.rb' require 'set' class Problem3 < Problem def initialize(list, exp) @list = list @exp = exp end def Calculate() counter = 0 s1 = Set[] for i in @list if i == counter+1 counter = counter + 1 while (s1.include?(counter+1)) counter = counter + 1 end else s1.add(i) end end return @exp == counter+1 end end
true
c02fad637522d1d91b77f5f9617b1258530c0bf4
Ruby
pacojp/cwalert-disk2
/mrblib/cwalert-disk2.rb
UTF-8
2,541
2.5625
3
[]
no_license
class Checker attr_accessor :verbose, :hostname, :mount_points, :warning_hours, :room_id, :token, :users_to def initialize(config) self.verbose = config["verbose"] || false self.hostname = config["hostname"] || `hostname`.strip self.mount_points = config["mount_points"] self.warning_hours = config["warning-hours"] || [] self.room_id = config["cw"]["room-id"] self.token = config["cw"]["token"] self.users_to = config["cw"]["users-to"] || [] end def logging(st) return if verbose == false puts st if verbose == true || verbose.to_i == 1 end def check logging "start checking!" # only centos, amazonlinux checked! state = :normal mount_points.each do |mp| mount_point = mp["mount_point"] warning = mp["warning"].to_i critical = mp["critical"].to_i logging "checking mount_point #{mount_point}" unless mount_point =~ /\A\// puts "mount_point error #{mount_point}" next end result = `df | grep " #{mount_point}$"`.split(" ")[-2] if result.nil? puts "!mount_point error" elsif result =~ /(\d+)%/ usage = $1.to_i logging "=> usaeg: #{usage} warning: #{warning} critical: #{critical}" usage > warning && state = :warning usage > critical && state = :critical proceed_with_state mount_point, state, usage else puts "disk size chekck format error(not your fault)" end end logging "finish checking!" end def proceed_with_state(mount_point, state, usage) return if state == :normal return if state == :warning && !warning_hours.include?(Time.now.hour) report ";( disk usage #{state}", "#{state}! #{mount_point} disk usage is #{usage}%" end def report(title, message) logging "===> reporting #{title} #{message}" tos = users_to.map{ |u| "[To:#{u}]" }.join("\n") tos += "\n" if tos.size > 0 message = %|[info][title][#{hostname}] #{title}[/title]#{message}[/info]| `curl -s -S -X POST -H "X-ChatWorkToken: #{token}" -k -d "body=#{tos}#{message}" "https://api.chatwork.com/v2/rooms/#{room_id}/messages"` end end def usage puts "Usage: cwalert-disk2 CONFIG_FILE" end def __main__(argv) if argv.size != 2 usage return end case argv[1] when "version" puts "v#{CwalertDisk::VERSION}" else config_file = argv[1] unless File.exist?(config_file) usage return end j = File.read(config_file) Checker.new(JSON.parse(j)).check end end
true
744f2bd58dc034339d072c3495f42bd35eceb9aa
Ruby
Gunn8604/ruby-music-library-cli-onl01-seng-pt-070620
/lib/genre.rb
UTF-8
545
2.78125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Genre extend Concerns::Findable attr_accessor :name, :songs @@all = [] def initialize(name) @name = name @songs = [] save #saving all instances of the genre created end def self.all @@all end def self.destroy_all @@all = [] end def save @@all << self end # def self.create(genre) # self.new(genre) # end def self.create(name) self.new(name) end def songs @songs end def artists self.songs.collect {|song|song.artist}.uniq end end #class end
true
ec6f4520ec1730b489ff211c5a93fb2329d41297
Ruby
kue-ipc/ikamail
/lib/japanese_wrap.rb
UTF-8
7,599
2.875
3
[ "MIT" ]
permissive
# 日本語におけるワードラップや禁則処理を行う # 参考文献 # * JIS X 4051 # * 日本語組版処理の要件 (日本語版) https://www.w3.org/TR/jlreq/ # ワードラップも行うが、JISであることを前提とし、厳密性にはかける。 # 割注始め括弧類や割注終わり括弧類は、それぞれの括弧類に含まれる。 # JIS X 4051 / 日本語組版処理の要件 との違い # * 濁音・半濁音を行頭禁止文字に含める。 # * 合字である「ㇷ゚ U+31F7 U+309A」を考慮しないが、実質行頭禁止になる。 require 'set' module JapaneseWrap module_function # rubocop:disable Style/AccessModifierDeclarations # rubocop: disable Style/PercentLiteralDelimiters # 始め括弧類 OPENING_BRACKETS = %w!‘ “ ( 〔 [ { 〈 《 「 『 【 ⦅ 〘 〖 « 〝!.freeze OPENING_BRACKETS_FULLWIDTH = %w!( [ { ⦅!.freeze OPENING_BRACKETS_HALFWIDTH = %w!「!.freeze # 終わり括弧類 CLOSING_BRACKETS = %w!’ ” ) 〕 ] } 〉 》 」 』 】 ⦆ 〙 〗 » 〟!.freeze CLOSING_BRACKETS_FULLWIDTH = %w!) ] } ⦆!.freeze CLOSING_BRACKETS_HALFWIDTH = %w!」!.freeze # rubocop: enable Style/PercentLiteralDelimiters # ハイフン類 HYPHENS = %w[‐ 〜 ゠ –].freeze # 区切り約物 DIVIDING_PUNCTUATION_MARKS = %w[! ? ‼ ⁇ ⁈ ⁉].freeze DIVIDING_PUNCTUATION_MARKS_FULLWIDTH = %w[! ?].freeze # 中点類 MIDDLE_DOTS = %w[・ : ;].freeze MIDDLE_DOTS_FULLWIDTH = %w[: ;].freeze MIDDLE_DOTS_HALFWIDTH = %w[・].freeze # 句点類 FULL_STOPS = %w[。 .].freeze FULL_STOPS_FULLWIDTH = %w[.].freeze FULL_STOPS_HALFWIDTH = %w[。].freeze # 読点類 COMMAS = %w[、 ,].freeze COMMAS_FULLWIDTH = %w[,].freeze COMMAS_HALFWIDTH = %w[、].freeze # 繰返し記号 ITERATION_MARKS = %w[ヽ ヾ ゝ ゞ 々 〻].freeze # 長音記号 PROLONGED_SOUND_MARK = %w[ー].freeze PROLONGED_SOUND_MARK_HALFWIDTH = %w[ー].freeze # 小書きの仮名 SMALL_KANA = %w[ ぁ ぃ ぅ ぇ ぉ ァ ィ ゥ ェ ォ っ ゃ ゅ ょ ゎ ゕ ゖ ッ ャ ュ ョ ヮ ヵ ヶ ㇰ ㇱ ㇲ ㇳ ㇴ ㇵ ㇶ ㇷ ㇸ ㇹ ㇺ ㇻ ㇼ ㇽ ㇾ ㇿ ].freeze SMALL_KANA_HALFWIDTH = %w[ ァ ィ ゥ ェ ォ ッ ャ ュ ョ ].freeze # ㇷ゚ U+31F7 U+309A # 濁点・半濁点 SOUND_MARKS = (%w[゛ ゜] + ["\u3099", "\u309A"]).freeze SOUND_MARKS_HALFWIDTH = ["\uFF9E", "\uFF9F"].freeze # 分離禁止文字列 INSEPARABLE_STRS = %w[ —— …… ‥‥ 〳〵 〴〵 ].freeze NOT_STARTING_CHARS = Set.new([ *CLOSING_BRACKETS, *CLOSING_BRACKETS_FULLWIDTH, *CLOSING_BRACKETS_HALFWIDTH, *HYPHENS, *DIVIDING_PUNCTUATION_MARKS, *DIVIDING_PUNCTUATION_MARKS_FULLWIDTH, *MIDDLE_DOTS, *MIDDLE_DOTS_FULLWIDTH, *MIDDLE_DOTS_HALFWIDTH, *FULL_STOPS, *FULL_STOPS_FULLWIDTH, *FULL_STOPS_HALFWIDTH, *COMMAS, *COMMAS_FULLWIDTH, *COMMAS_HALFWIDTH, *ITERATION_MARKS, *PROLONGED_SOUND_MARK, *PROLONGED_SOUND_MARK_HALFWIDTH, *SMALL_KANA, *SMALL_KANA_HALFWIDTH, *SOUND_MARKS, *SOUND_MARKS_HALFWIDTH, ]).freeze NOT_ENDING_CHARS = Set.new([ *OPENING_BRACKETS, *OPENING_BRACKETS_FULLWIDTH, *OPENING_BRACKETS_HALFWIDTH, ]).freeze HANGING_CHARS = Set.new([ *FULL_STOPS, *FULL_STOPS_FULLWIDTH, *FULL_STOPS_HALFWIDTH, *COMMAS, *COMMAS_FULLWIDTH, *COMMAS_HALFWIDTH, ]).freeze ASCII_CHARS = Set.new("\u0020".."\u007E").freeze FULLWIDTH_CHARS = Set.new([*("\uFF01".."\uFF60"), *("\uFFE0".."\uFFE6")]) HALFWIDTH_CHARS = Set.new([*("\uFF61".."\uFF9F"), *("\uFFE8".."\uFFEE")]) # 長いテキストを折り返す。 def text_wrap(str, **opts) buff = String.new(encoding: 'UTF-8') str.each_line do |line| each_wrap(line, **opts) do |part| buff << part end end buff end # 折り返しした行をブロックに渡す。ブロックがない場合はEnumeratorを返す。 # == 引数 # str:: 折り返す文字列 # col:: 1行にはいる列の数。つまり、一行の長さ。 # rule:: 折り返しのルール、:none, :force, :word_wrap, :jisx4051 # ambiguous:: Unicodeで幅がAmbiguousとなっている文字(ギリシャ文字)の幅 # hanging:: 句点等のぶら下げを有効にする。 def each_wrap(str, col: 0, rule: :force, ambiguous: 2, hanging: false) return enum_for(__method__, str, col: col, rule: rule, ambiguous: ambiguous, hanging: hanging) unless block_given? return yield str if !col.positive? || rule == :none display_with = Unicode::DisplayWidth.new(ambiguous: ambiguous, emoji: true) remnant = str.dup until remnant.empty? min_ptr = calc_ptr(remnant, col, display_with) ptr = search_breakable(remnant, min_ptr, rule: rule, hanging: hanging) if ptr < remnant.size yield "#{remnant[0, ptr].rstrip}\n" remnant = remnant[ptr, remnant.size - ptr] else yield remnant break end end end # 長さに収まる文字列の位置 def calc_ptr(str, col, display_with) min_ptr = 0 max_ptr = str.size ptr = max_ptr width = display_with.of(str) while min_ptr < max_ptr ptr = col * ptr / width ptr = min_ptr + 1 if ptr <= min_ptr ptr = max_ptr if ptr > max_ptr width = display_with.of(str[0, ptr]) if width > col max_ptr = ptr - 1 else min_ptr = ptr end end min_ptr end # 改行可能な場所を探す。 def search_breakable(str, ptr, rule: :force, hanging: false) case rule when :force ptr when :word_wrap search_breakable_word_wrap(str, ptr) when :jisx4051 search_breakable_jisx4051(str, ptr, hanging: hanging) else logger.error "unknown rule: #{rule}" ptr end end # 英単語のワードラップ def search_breakable_word_wrap(str, ptr, forward: true) # 続きが空白の場合は、空白が終わりまで前進する if forward fw_ptr = search_forward_space(str, ptr) return fw_ptr if fw_ptr end # 続きが非単語かつASCIIではない場合は即座に終了 return ptr if !check_word_char(str[ptr]) && str[ptr] !~ /[[:ascii:]]/ # 単語区切りを見つける cur_ptr = ptr while cur_ptr.positive? # 非単語で終わっていれば終了 return cur_ptr unless check_word_char(str[cur_ptr - 1]) cur_ptr -= 1 end # 区切り場所が見つからない場合は、強制切断 ptr end # JIS X 4051に基づく改行 def search_breakable_jisx4051(str, ptr, hanging: false) ptr += 1 if hanging && HANGING_CHARS.include?(str[ptr]) ptr = search_breakable_word_wrap(str, ptr) cur_ptr = ptr while cur_ptr.positive? if str[cur_ptr] != ' ' cur_ptr = search_breakable_word_wrap(str, cur_ptr, forward: false) if NOT_STARTING_CHARS.exclude?(str[cur_ptr]) && NOT_ENDING_CHARS.exclude?(str[cur_ptr - 1]) return cur_ptr end end cur_ptr -= 1 end ptr end def search_forward_space(str, ptr) return if str[ptr] !~ /\s/ ptr += 1 ptr += 1 while str[ptr] =~ /\s/ ptr end def check_word_char(chr) # ラテン文字のみを対象とする chr =~ /[[:word:]&&[\p{Latin}]]/ # ギリシャ文字、コプト文字、キリル文字のみを対象とする # chr =~ /[[:word:]&&[\p{Latin}\p{Greek}\p{Coptic}\p{Cyrillic}]]/ end end
true
495d65ab18f8a3c926f9290da71a9ee977410c09
Ruby
aQuaYi/computation
/small-step/while.rb
UTF-8
318
2.859375
3
[ "MIT" ]
permissive
# frozen_string_literal: true class While < Struct.new(:condition, :body) def to_s "while (#{condition}) { #{body} }" end def inspect "«#{self}»" end def reducible? true end def reduce(environment) [If.new(condition, Sequence.new(body, self), DoNothing.new), environment] end end
true
87d9b45e6776e196b05dce6127d17a3bcf5fe248
Ruby
andrewsunglaekim/wdi_dc5_instructors
/exercise_bank/rspec/simon_says/lib/simon_says.rb
UTF-8
478
3.953125
4
[]
no_license
class Simon def self.echo(word) word end def self.shout(str) str.upcase end def self.repeat(word, y=2) arr = [] y.times do arr << word end arr.join(' ') end def self.start_of_word(word, y) word[0..y-1] end def self.first_word(str) str.split.first end def self.titleize(str) arr = str.capitalize.split little_word = ['and', 'the', 'over', 'with'] arr.map {|x| little_word.include?(x)? x : x.capitalize}.join(' ') end end
true
fdb189a2133df54d4c27756338b444137f367f70
Ruby
VimIcewind/Code
/ruby/weeks.rb
UTF-8
297
2.8125
3
[]
no_license
#!/usr/bin/ruby $LOAD_PATH << '.' require "support" class Decade include Week no_of_yrs = 10 def no_of_months puts Week::FIRST_DAY number = 10 * 12 puts number end end d1 = Decade.new puts Week::FIRST_DAY Week.weeks_in_month Week.weeks_in_year d1.no_of_months
true
ae5461bf261d55c79a97120a943b1c96231b7e6a
Ruby
Swati24/algorithms
/Old Dynamic Programming/Longest Palindromic Subsequence/prog.rb
UTF-8
740
3.234375
3
[]
no_license
class Prog attr_accessor :string def initialize(string) @string = string end def process matrix = Array.new(string.length){Array.new( string.length )} i = 0 while(i <= string.length) j = 0 while( j <= string.length - 1) if i + j < string.length if i == 0 matrix[i][j] = 1 elsif string[j] == string[j + i] matrix[i][j] = 2 + (matrix[i - 2][j+1] || 0) elsif string[j] != string[j + i] matrix[i][j] = [matrix[i -1][j], matrix[i -1][j+1]].max end end j += 1 end i += 1 end matrix[string.length - 1][0] end def self.run i = Prog.new("AABCDEBAZ") i.process end end
true
cc95d0b32b1154838f87845c56886ca72b794f10
Ruby
natgit8/ttt-10-current-player-v-000
/lib/current_player.rb
UTF-8
658
4.46875
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def turn_count(board) #defining turn_count and giving it a argument of board turn_count = 0 #setting turn_count to 0 to begin our counter board.each do |turn| #going through each index of the array if turn == "X" || turn == "O" #setting our if statement to see if there is an X or O in an index turn_count += 1 #turn_count=turn_count + 1 end end turn_count #calling turn_count end def current_player(board) #defined current_player, passed argument (board) if turn_count(board).even? #calling method turn_count in current_player method. if even return X "X" elsif turn_count(board) % 2 == 1 #if odd return O "O" end end
true
4d375cab14d1f80836cf9b1d21d3e946a3da3df8
Ruby
yuihyama/funcrock
/test/isodd_test.rb
UTF-8
557
2.828125
3
[ "MIT" ]
permissive
require 'minitest/autorun' require './lib/isodd' class IsOddTest < Minitest::Test def test_isodd assert_equal false, isodd(0) assert_equal true, isodd(1) assert_equal false, isodd(2) assert_equal true, isodd(-1) assert_equal false, isodd(-2) assert_raises(NoMethodError) { isodd(1.1) } assert_output("false\n") { p isodd(0) } assert_output("true\n") { puts isodd(1) } assert_output("false\n") { puts isodd(2) } assert_output("true\n") { puts isodd(-1) } assert_output("false\n") { puts isodd(-2) } end end
true
ec81137d340275558f79023367de3a5ae7a0375a
Ruby
karpet/elasticsearch-rails-ha-gem
/spec/temp_db_helper.rb
UTF-8
1,650
2.53125
3
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
require 'tempfile' # stub so we can setup schemas below class Article < ActiveRecord::Base end class TempDBHelper @@_db_file = nil def self.setup if @@_db_file refresh_db end setup_schemas seed_data end def self.quiet ENV['QUIET'] end def self.db_file @@_db_file ||= Tempfile.new('elasticsearch-rails-ha-test.db') end def self.refresh_db quiet or puts "Removing temp db file at #{db_file.path}" db_file.close! db_file.unlink @@_db_file = nil open_connection end def self.open_connection quiet or puts "Opening db connection to #{db_file.path}" ActiveRecord::Base.establish_connection( :adapter => 'sqlite3', :database => db_file.path ) end def self.setup_schemas open_connection Article.connection.create_table :articles do |t| t.string :title t.string :body t.datetime :created_at, :default => 'NOW()' end end def self.seed_data Article.delete_all Article.create! title: 'Test', body: '' Article.create! title: 'Testing Coding', body: '' Article.create! title: 'Coding', body: '' end end TempDBHelper.setup # extend class with ES definitions -- must do this after setup #ActiveRecord::Base.raise_in_transactional_callbacks = true class Article < ActiveRecord::Base include Elasticsearch::Model include Elasticsearch::Model::Callbacks settings index: { number_of_shards: 1, number_of_replicas: 0 } do mapping do indexes :title, type: 'text', analyzer: 'snowball' indexes :body, type: 'text' indexes :created_at, type: 'date' end end end
true
ce62e03d2a7dd7538657f3d12c25bf62b8fb39dc
Ruby
amclain/duet-bootstrap
/bin/duet-bootstrap
UTF-8
6,061
2.59375
3
[ "Apache-2.0" ]
permissive
#! /usr/bin/env ruby # Duet Bootstrap # v1.1.2 # # Website: https://sourceforge.net/projects/duet-bootstrap # # # -- THIS IS A THIRD-PARTY TOOL AND IS NOT AFFILIATED WITH -- # -- THE AMX ORGANIZATION -- # # # This script was designed to run on Ruby v2.0.0-p0 # http://www.ruby-lang.org/en/downloads/ # # OVERVIEW # # This script generates a NetLinx workspace and source code to start # up a Duet module. It is intended to be used when the entire AMX # system has been programmed in Duet. # # This script will generate a workspace and source file in the # working directory. It will also compile the generated source # code if the NetLinx compiler executable is found. # # CONFIGURATION # # If this script was downloaded with the command # gem install duet-bootstrap # then you should be able to execute it with the command # "duet-bootstrap", as long as your Ruby installation has been # added to your system environment variables. # # If you would like to change the default AMX master that will be # used when generating workspaces, open the NetLinx Workspace file # located at template/template.apw. Modify the communication # settings, save the workspace, and close NetLinx Studio. # # EXECUTION # # This script will run on many different operating systems. # # On Windows, the fastest and easiest way to use this script is # through the command line. Open Windows Explorer and browse # to the folder of your compiled Duet .jar file. With no file # selected, hold shift and right-click in the empty space of # the file browser pane, then select "Open command window here" # from the context menu. Alternatively, the command line can # be launched from Start -> Run and typing "cmd" in the box. # # Run this script and pass the Duet module as a parameter in # the file path. Pressing the tab key will auto-complete the # file name. # # Example: >duet-bootstrap My_Duet_File_dr1_0_0.jar # #---------------------------------------------------------------------- # Copyright 2013 Alex McLain # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #---------------------------------------------------------------------- require 'rexml/document' templatePath = File.expand_path '../../lib/duet-bootstrap/template', __FILE__ params = Hash.new # Initialize parameters. params[:projectName] = '' params[:duetModuleName] = '' params[:duetModulePath] = '' # Make sure Duet module file was passed to the script. if ARGV[0].nil? puts 'No Duet module was specified.' exit end params[:duetModulePath] = ARGV[0].strip # Check Duet file extension. unless File.extname(params[:duetModulePath]).downcase == '.jar' puts 'Input file was not a Duet file.' exit end # Parse Duet module name. params[:duetModuleName] = File.basename(params[:duetModulePath], '.jar') params[:projectName] = params[:duetModuleName][/(.*)_dr[0-9]+/, 1].gsub(/_/, ' ') # Import existing AMX workspace template. workspaceTemplate = File.open("#{templatePath}/template.apw", 'r') xml = REXML::Document.new(workspaceTemplate) # Rename the workspace. xml.elements.each('/Workspace/Identifier') do |identifier| identifier.text = params[:projectName] break end # Rename the project. xml.elements.each('/Workspace/Project/Identifier') do |identifier| identifier.text = params[:projectName] break end # Rename the system. xml.elements.each('/Workspace/Project/System/Identifier') do |identifier| identifier.text = params[:projectName] end # Delete all links to files in the workspace's system. The script # will regenerate them. xml.elements.delete_all('/Workspace/Project/System/File') # Add file nodes. xml.elements.each('/Workspace/Project/System') do |e| # Add Duet file. fileElement = e.add_element('File') fileElement.add_attributes('CompileType' => 'None', 'Type' => 'DUET') identifier = fileElement.add_element('Identifier') identifier.text = params[:duetModuleName] filePathName = fileElement.add_element('FilePathName') filePathName.text = params[:duetModulePath] # Add NetLinx file. fileElement = e.add_element('File') fileElement.add_attributes('CompileType' => 'Netlinx', 'Type' => 'MasterSrc') identifier = fileElement.add_element('Identifier') identifier.text = params[:projectName] filePathName = fileElement.add_element('FilePathName') filePathName.text = "#{params[:projectName]}.axs" break end # Save workspace. File.open("#{params[:projectName]}.apw", 'w') do |file| file << xml end # Import NetLinx source code file template. template = File.open("#{templatePath}/template.axs", 'r').read template.gsub!(/%%_PROJECT_NAME_%%/, params[:projectName]) template.gsub!(/%%_MODULE_NAME_%%/, params[:duetModuleName]) # Save source code file. File.open("#{params[:projectName]}.axs", 'w') do |file| file << template end puts 'Generated project.' # Check for NetLinx compiler. compilerPath = 'C:\Program Files (x86)\Common Files\AMXShare\COM\nlrc.exe' canCompile = File.exists?(compilerPath) unless canCompile # Use path for 32-bit O/S and try again. compilerPath = 'C:\Program Files\Common Files\AMXShare\COM\nlrc.exe' canCompile = File.exists?(compilerPath) unless canCompile puts 'NetLinx compiler not found. Can\'t auto-compile.' end end # Execute NetLinx compiler. if canCompile system("\"#{compilerPath}\" \"#{File.absolute_path("#{params[:projectName]}.axs")}\"") end puts 'Done.'
true
fa342da899e2bedb57a891a63f33bc3a5f9e7017
Ruby
AGL745/Launch_School
/Drills/July/vowels_delete.rb
UTF-8
230
3.5
4
[]
no_license
VOWELS = %w(a e i o u).freeze def vowel_remover(words) words.map do |word| chars = word.split('') VOWELS.each { |vowel| chars.delete(vowel) } chars.join('') end end p vowel_remover(%w(green yellow black orange))
true
c2dc4b10c76bd5fc07796870b34b31232475dbd7
Ruby
hermesalexis/ruby
/exception.rb
UTF-8
400
3.859375
4
[]
no_license
class Person attr_reader :name def initialize(name) self.name = name end # nuestro propio método de escritura para name def name=(name) raise ArgumentError, "El nombre no puede ser vacío" if name.nil? @name = name end end p = Person.new("Juan") p.name = "Pedro" # no lanza excepción p.name = nil # lanza ArgumentError p.name = "" # lanza ArgumentError
true
14565c6a1b7493d2f6c8dd4853526976c47cdcbe
Ruby
oreeve/korning
/import.rb
UTF-8
3,633
2.78125
3
[]
no_license
# Use this file to import the sales information into the # the database. require "pg" require 'csv' require 'pry' system 'psql korning < schema.sql' def db_connection begin connection = PG.connect(dbname: "korning") yield(connection) ensure connection.close end end @sales = [] @frequency = [] @employees = [] @customers = [] CSV.foreach("sales.csv", headers: true, header_converters: :symbol) do |row| sale = row.to_hash @sales << sale end @sales.each do |sale| unless @frequency.include?(sale[:invoice_frequency]) @frequency << sale[:invoice_frequency] end unless @employees.include?(sale[:employee]) @employees << sale[:employee] end unless @customers.include?(sale[:customer_and_account_no]) @customers << sale[:customer_and_account_no] end end @frequency.each do |freq| db_connection do |conn| conn.exec_params("INSERT INTO frequency (frequency) VALUES ($1);", [freq]) end end @employee_info = [] @employees.each do |emp| emps = emp.split(" ") employee = {} employee[:name] = emps[0, 2].join(' ') employee[:email] = emps[-1].gsub(/[()]/, '') @employee_info << employee end @employee_info.each do |emp| db_connection do |conn| conn.exec_params("INSERT INTO employee (name, email) VALUES ($1, $2);", [emp[:name], emp[:email]]) end end @customer_info = [] @customers.each do |cust| custs = cust.split(" ") customer = {} customer[:name] = custs[0] customer[:account] = custs[-1].gsub(/[()]/, '') @customer_info << customer end @customer_info.each do |cust| db_connection do |conn| conn.exec_params("INSERT INTO customer (name, account) VALUES ($1, $2);", [cust[:name], cust[:account]]) end end @sales.each do |sale| db_connection do |conn| conn.exec_params("INSERT INTO sales (product, date, amount, units, inv_num) VALUES ($1, $2, $3, $4, $5);", [sale[:product_name], sale[:sale_date], sale[:sale_amount], sale[:units_sold], sale[:invoice_no]]) if sale[:employee].include?("Clancy Wiggum") conn.exec_params("INSERT INTO sales (emp_id) VALUES ($1);", [1]) elsif sale[:employee].include?("Ricky Bobby") conn.exec_params("INSERT INTO sales (emp_id) VALUES ($1);", [2]) elsif sale[:employee].include?("Bob Lob") conn.exec_params("INSERT INTO sales (emp_id) VALUES ($1);", [3]) elsif sale[:employee].include?("Willie Groundskeeper") conn.exec_params("INSERT INTO sales (emp_id) VALUES ($1);", [4]) end if sale[:customer_and_account_no].include?("Motorola") conn.exec_params("INSERT INTO sales (cust_id) VALUES ($1);", [1]) elsif sale[:customer_and_account_no].include?("LG") conn.exec_params("INSERT INTO sales (cust_id) VALUES ($1);", [2]) elsif sale[:customer_and_account_no].include?("HTC") conn.exec_params("INSERT INTO sales (cust_id) VALUES ($1);", [3]) elsif sale[:customer_and_account_no].include?("Nokia") conn.exec_params("INSERT INTO sales (cust_id) VALUES ($1);", [4]) elsif sale[:customer_and_account_no].include?("Samsung") conn.exec_params("INSERT INTO sales (cust_id) VALUES ($1);", [5]) elsif sale[:customer_and_account_no].include?("Apple") conn.exec_params("INSERT INTO sales (cust_id) VALUES ($1);", [6]) end if sale[:invoice_frequency].include?("Monthly") conn.exec_params("INSERT INTO sales (frequency) VALUES ($1);", [1]) elsif sale[:invoice_frequency].include?("Quarterly") conn.exec_params("INSERT INTO sales (frequency) VALUES ($1);", [2]) elsif sale[:invoice_frequency].include?("Once") conn.exec_params("INSERT INTO sales (frequency) VALUES ($1);", [3]) end end end
true
1586649a300024c738b1479af3f972a544156eac
Ruby
MBAPPOU/Projet-Ruby-YvanMBAPPOU
/http.rb
UTF-8
1,625
3.125
3
[]
no_license
module HTTP require 'socket' class Request attr_reader :socket ,:request , :headers, :body def initialize (socket) @socket = socket @headers = Hash.new if socket read end end # lit le socket et retourne la requete et les headers def read # request parsing @request = @socket.gets # On lit sur le socket la 1 ère ligne de la requête begin header = @socket.gets header_name, header_val = header.chomp.split(': ') @headers[header_name] = header_val end until header.chomp.empty? #@headers = headers @body = nil unless @headers["Content-Length"].nil? # on teste si le headers a un content-Length @body = @socket.read(@headers["Content-Length"].to_i) # on lit et on stocke le corps de la requête end [@request, @headers, @body] end def self.cookie? @headers["Cookie"].nil? end def self.cookie if self.cookie? @headers["Cookie"].chomp.split(';')[1].split('=') end end def headers @headers end def path @request.chomp.split(' ')[1] end end class Response attr_reader :code, :code_message , :headers ,:body def initialize @@version = "HTTP/1.1" @headers = Hash.new end def headers @headers end def code= (string) @code = string end def code_message= string @code_message = string end def self.write (string) @body = string end def self.to_s first_line = [@code , @version , @code_message].join(' ') t = [] # parcourir le headers et le mettre au format http @headers.each do |clef,val| t << [clef,val].join(': ') end t.join("\n") @finalresponse = [first_line,t,""].join("\n") end end end
true
8b7e991076da68113617880ebb0f4ee704f2c52e
Ruby
rn0rno/kyopro
/aoj/ruby/01_ALDS/ALDS1_1_C.rb
UTF-8
290
3.640625
4
[]
no_license
#!/usr/bin/env ruby def prime?(x) return true if x == 2 return false if x < 2 || (x % 2).zero? i = 3 while i <= Math.sqrt(x) return false if (x % i).zero? i += 2 end true end n = gets.chomp.to_i cnt = 0 n.times do cnt += 1 if prime?(gets.chomp.to_i) end puts cnt
true
9fd81e554602ebe347d20efab372ceb31231a1b2
Ruby
djpate/email_parser
/lib/email_parser/parsers/email_parser.rb
UTF-8
521
2.921875
3
[]
no_license
module EmailParser module Parsers class EmailParser attr_reader :email_string def initialize email_string @email_string = email_string scanner.scan_until( empty_line_matcher ) end def header @header ||= scanner.pre_match end def body @body ||= scanner.post_match end private def scanner @scanner ||= StringScanner.new( email_string ) end def empty_line_matcher /\n\n/ end end end end
true
bd8f04e9e8d8e7cdc2a8ecf963000904473ef054
Ruby
rgilbert82/Data-Structures
/stack_test.rb
UTF-8
1,160
2.90625
3
[]
no_license
require 'minitest/autorun' require 'minitest/reporters' Minitest::Reporters.use! require_relative 'stack' class StackStructureTest < Minitest::Test def setup @stack = StackStructure.new end def test_initialize assert_equal @stack.data, [] end def test_push @stack.push('hello') assert_equal @stack[0], 'hello' end def test_pop @stack.push('one') @stack.push('goodbye') assert_equal @stack.pop, 'goodbye' assert_equal @stack.size, 1 end def test_unshift_return_value @stack.push('one') assert_equal @stack.unshift('two'), 'two' end def test_unshift @stack.push('one') @stack.unshift('two') assert_equal @stack[0], 'two' assert_equal @stack.length, 2 end def test_shift_return_value @stack.push('one') @stack.push('two') assert_equal @stack.shift, 'one' end def test_shift @stack.push('one') @stack.push('two') @stack.shift assert_equal @stack[0], 'two' assert_equal @stack.size, 1 end def test_init_values @stack2 = StackStructure.new(['one', 'two', 'three']) assert_equal @stack2.data, ['one', 'two', 'three'] end end
true