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
24c7b424617565380fc4ca6f9b3d26bb320f3dc2
Ruby
jmhinric/project_euler
/problem04.rb
UTF-8
886
3.90625
4
[]
no_license
require 'pry' def find_max_palindrome first_set = (100..999).to_a second_set = (100..999).to_a products = [] first_set.each do |num1| second_set.each do |num2| products << num1 * num2 if is_palindrome?(num1 * num2) end end return products.max end def is_palindrome?(number) return number.to_s == number.to_s.reverse end puts find_max_palindrome def max_palindrome(numbers) palindromes = [] numbers.each do |number| if number.to_s == number.to_s.reverse palindromes << number end end return palindromes.max end def product_of_3_digits?(number) three_dig_numbers = (100..999).to_a three_dig_numbers.each do |num| return true if number % num == 0 end return false end # puts max_palindrome(compute_products) test = 998001 while !is_palindrome?(test) || !product_of_3_digits?(test) test -= 1 end puts test
true
0d1a178f3eaa9bf6c49530a1f44b4cb6d01ef28c
Ruby
CodeNeophyte/launch_school_101_lesson3
/Easy_2/question_3.rb
UTF-8
265
3.328125
3
[]
no_license
# throw out the really old people (age 100 or older). ages = { "Herman" => 32, "Lily" => 30, "Grandpa" => 402, "Eddie" => 10 } p ages.reject { |k, v| v > 100 } p ages.select { |k, v| v < 100 } # additional & better solution p ages.keep_if { |_, age| age < 100 }
true
80bf9a653c57f51d0fb6191f7a6e5c6c78f936a4
Ruby
JBoshart/Scrabble
/lib/player.rb
UTF-8
1,061
3.828125
4
[]
no_license
class Player attr_reader :name, :word WIN_CONDITION = 100 def initialize(name) @name = name @words = [] @word_score = 0 end def plays return @words end def play(word) if self.won? == true return false end @word_score = Scoring.score(word) @words << word return @word_score end def total_score tally = 0 @words.each do |word| tally += Scoring.score(word) end return tally end def won? if total_score > WIN_CONDITION return true end return false end def highest_scoring_word words_and_scores = { } most = [] @words.each do |word| words_and_scores[word] = (Scoring.score(word)) end most = words_and_scores.max_by do |key, value| value end return most[0] end def highest_word_score words_and_scores = { } most = [] @words.each do |word| words_and_scores[Scoring.score(word)] = word end most = words_and_scores.max_by do |key, value| key end return most[0] end end
true
5441856c30724b2a388d319805151583b60392b6
Ruby
Madh93/rips
/lib/rips/instructions/jal.rb
UTF-8
427
2.53125
3
[ "MIT" ]
permissive
require "rips/instructions/instruction" module Rips module Instructions class Jal < Instruction attr_reader :variables, :length # @variables: types of instruction's variables # @length: length in bits for each variable def initialize super("jal",Formats::BFormat.new(0b101000)) @variables = [Variables::Address.new] @length = {r1:10, op:6} end end end end
true
742e4788220d44da2dc62828b68f2ab657c80bc6
Ruby
Tapjoy/chore
/lib/chore/hooks.rb
UTF-8
1,093
2.765625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Chore # Abstracts the notion of registering and running hooks during certain points in the lifecycle of chore # processing work. module Hooks # Helper method to look up, and execute hooks based on an event name. # Hooks are assumed to be methods defined on `self` that are of the pattern # hook_name_identifier. ex: before_perform_log def run_hooks_for(event,*args) results = global_hooks_for(event).map { |prc| prc.call(*args) } || [true] results << hooks_for(event).map { |method| send(method,*args) } results = false if results.any? {|r| false == r } results end private def hooks_for(event) @_chore_hooks ||= {} @_chore_hooks[event] ||= candidate_methods.grep(/^#{event}/).sort end # NOTE: Any hook methods defined after this is first referenced (i.e., # after chore begins processing jobs) will not be called. def candidate_methods @_chore_hooks_candidate_methods ||= (self.methods - Object.methods) end def global_hooks_for(event) Chore.hooks_for(event) end end end
true
ac620222419c767ad3b2d7fce49f8356991f4cf4
Ruby
joshado/graylog2-web-interface
/app/models/historic_server_value.rb
UTF-8
384
2.546875
3
[]
no_license
class HistoricServerValue include MongoMapper::Document key :type, String key :created_at, Integer def self.used_memory(minutes) get("used_memory", minutes) end private def self.get(what, minutes) self.all(:conditions => { :type => what }, :order => "$natural DESC", :limit => minutes).collect { |v| [v.created_at*1000, (v.value/1024/1024).to_i] } end end
true
d0f48e17b1deaddb33ad3c300aa56150637a6047
Ruby
DamonClark/introtoruby
/variables/example2a.rb
UTF-8
245
4.21875
4
[]
no_license
puts "How old are you?" age = gets.chomp.to_i puts "In 10 years your will be: " puts age + 10 puts "In 20 years your will be: " puts age + 20 puts "In 30 years your will be: " puts age + 30 puts "In 40 years your will be: " puts age + 40
true
f04724211a02a0862f50b63120beb77b3b138146
Ruby
lostpupil/leetcode-cn
/950.rb
UTF-8
317
3.8125
4
[ "MIT" ]
permissive
# @param {Integer[]} deck # @return {Integer[]} deck = [35, 22, 40, 11, 8, 2, 49, 31, 27, 29] def deck_revealed_increasing(deck) arr = [] deck.sort.reverse.each_with_index do |i, idx| arr << i arr << arr.shift if idx < deck.count - 1 end arr.reverse end p deck_revealed_increasing(deck)
true
8e1545c4d268cef3d192489cd2b6575627344f88
Ruby
ce3po/Projetos_Ruby
/aula01/pessoa.rb
UTF-8
368
3.578125
4
[]
no_license
# encoding: utf-8 class Pessoa attr_accessor :nome, :telefone def initialize(nome, telefone) @nome=nome @telefone=telefone end def relatorio puts "Meu nome é #{@nome} e telefone é #{@telefone}" end end pessoas = [] p1 = Pessoa.new("Fulano", "231") pessoas << p1 p2 = Pessoa.new("abc", "222") pessoas << p2 pessoas.each do |v| puts v.relatorio end
true
d2e5880c510f5ebd498d9698c6a735cdc4b71146
Ruby
skanev/evans
/lib/formatted_code/highlighter.rb
UTF-8
871
2.78125
3
[]
no_license
module FormattedCode class Highlighter def initialize(source, language) @source = source @language = language end def lines @lines ||= begin tokens = lexer.lex(@source) formatter = Rouge::Formatters::HTML.new HTMLLineFormatter.new(formatter).lines_for(tokens).to_a end end private def lexer Rouge::Lexer.find(@language) || Rouge::Lexers::PlainText end end class HTMLLineFormatter < Rouge::Formatter def initialize(formatter, opts={}) @formatter = formatter end def lines_for(tokens) enum_for :stream, tokens end def stream(tokens) token_lines(tokens) do |line| html_line = line.map do |token, value| @formatter.span(token, value) end.join('') yield html_line end end end end
true
1320338f798f8ba203ca54528024c7142a079e70
Ruby
jyllsarta/priconner
/app/models/stage.rb
UTF-8
817
2.890625
3
[]
no_license
# == Schema Information # # Table name: stages # # id :integer not null, primary key # area :integer default(0), not null # location :integer default(0), not null # is_hard :integer default(0), not null # class Stage < ApplicationRecord has_many :drops def name self.is_hard? ? "#{area}-#{location}(H)" : "#{area}-#{location}" end def main_drops drops.where("priority <= 3") end def sub_drops drops.where("priority > 3") end # 一石二鳥 = これらのアイテムを2つ以上このステージで回収できるか? def serving_two_ends?(items) (drops.pluck(:item_id) & items.pluck(:id)).count >= 2 end def self.serving_stages(items) self.includes(:drops).select{|stage| stage.serving_two_ends?(items)} end end
true
804211b408462552cba0dac2ebdc3c4c7b8f9b38
Ruby
quyongqiang/ruby-examples
/meta_test/object_model/methods.rb
UTF-8
364
2.8125
3
[]
no_license
require './my_class.rb' class MySubclass end MyClass.methods.grep /to/ obj = MyClass.new obj.instance_variable_set("@x", 3) p obj.instance_variables MyClass.class MyClass.superclass MyClass.superclass.superclass MySubclass.ancestors obj1 = MySubclass.new p self p "MySubclass ancestors:", MySubclass.ancestors Kernel.private_instance_methods p self
true
7266491af8042846386397f9e2ae24056ae72a61
Ruby
n3m3sis42/tweet-shortener-web-060517
/tweet_shortener.rb
UTF-8
756
3.53125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def words_to_be_substituted { "hello" => "hi", "to" => "2", "two" => "2", "too" => "2", "for" => "4", "four" => "4", "be" => "b", "you" => "u", "at" => "@", "and" => "&" } end def word_substituter(tweet) dictionary = words_to_be_substituted tweet.split(" ").map { |word| dictionary.keys.include?(word.downcase) ? dictionary[word.downcase] : word}.join(" ") end def bulk_tweet_shortener(tweet_array) tweet_array.each{ |tweet| puts word_substituter(tweet)} end def selective_tweet_shortener(tweet) tweet.length > 140 ? word_substituter(tweet) : tweet end def shortened_tweet_truncator(tweet) tweet_short = selective_tweet_shortener(tweet) tweet_short.length < 140 ? tweet_short : "#{tweet_short.slice(0, 137)}..." end
true
c47b357e19cb32284bc238f39995d43cd7ca605c
Ruby
linkyndy/pallets
/lib/pallets/context.rb
UTF-8
357
2.75
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module Pallets # Hash-like class that additionally holds a buffer for all write operations # that occur after initialization class Context < Hash def []=(key, value) buffer[key] = value super end def merge!(other_hash) buffer.merge!(other_hash) super end def buffer @buffer ||= {} end end end
true
030d1247227daa23451ecff0eea97c3694598b94
Ruby
ryuseitaked/RubyonRails
/ruby/lesson3.rb
UTF-8
97
3.125
3
[]
no_license
puts "webcamp".upcase # 「webcamp」という文字列を大文字に変換してください。
true
49adc3969a9cbb3f67b8ef0eca370d168933d1d0
Ruby
Alexander-Blair/ruby-kickstart
/session3/challenge/1_blocks.rb
UTF-8
307
4.1875
4
[ "MIT" ]
permissive
# Write a method, reverse_map, which invokes a block on each of the elements in reverse order, # and returns an array of their results. # # reverse_map(1, 2, 3) { |i| i * 2 } # => [6, 4, 2] def reverse_map(*vals, &block) vals.each.with_index { |val, i| vals[i] = block.call val } vals.reverse end
true
b4ff341d5282f89cd4e47b0238a1f4bb7e56f6c0
Ruby
Meghadandappanavar/ruby_code
/ass4.rb
UTF-8
367
3.234375
3
[]
no_license
numbers=[6,2,1,8,10] puts"#{numbers.sort}" output=[] numbers.each do |num| if num == numbers.sort[0] elsif num == numbers.sort[numbers.length-1] else output.push(num) end end puts"#{output}" sum=0 output.each do |n| sum=sum+n end puts sum =begin elsif num == "#{numbers.min}" else output.push(num) end end puts "#{output}" =end
true
55a79763a549a59f6c2fc5cd65f3a0964c004924
Ruby
ppjk1/chris-pines-learn-to-program
/ch06_bottles.rb
UTF-8
319
3.90625
4
[]
no_license
bottles = 99 while bottles > 0 puts "#{bottles} bottles of beer on the wall," puts "#{bottles} bottles of beer," puts "You take 1 down, pass it around," bottles -= 1 if bottles == 0 puts "No more bottles of beer on the wall." else puts "#{bottles} bottles of beer on the wall." end puts "" end
true
592a9bc27f70bed6d5333701a6fa1de4b5e2269d
Ruby
sbagdat/ruby-challenges
/challenge01/solutions/solution00.rb
UTF-8
2,135
3.265625
3
[ "MIT" ]
permissive
# ------------------------------------------------------------------------------------------| # | TALİMATLAR | # ------------------------------------------------------------------------------------------| # | 0. İlk iş olarak metin dosyasındaki verileri dizilere aktarmalısın: | # | 0.0. `renkler.txt` dosyasındaki satırları `renkler` adında bir diziye aktar. | # | 0.1. `nesneler.txt` dosyasındaki satırları `nesneler` adında bir diziye aktar. | # | 0.2. `sifatlar.txt` dosyasındaki satırları `sifatlar` adında bir diziye aktar. | # | 0.3. `meslekler.txt` dosyasındaki satırları `meslekler` adında bir diziye aktar. | # | 1. Muhteşem takma ad oluşturmak için kullanma gereken formülü şöyle not ettin: | # | 1.0. `renkler` dizisinden rasgele bir eleman seç ve sonuna `rengi` kelimesini ekle. | # | 1.1. `nesneler` dizisinden rasgele bir eleman seç. | # | 1.2. `sifatlar` dizisinden rasgele bir eleman seç. | # | 1.3. `meslekler` dizisinden rasgele bir eleman seç. | # | 1.4. İlk dört adımda seçmiş olduğun metinleri birbirine ekle. | # | 1.5. Her kelimenin ilk harfini büyüt. | # | 2. Über süper muhteşem takma adı ekrana yazdır. | # ------------------------------------------------------------------------------------------- # Senin kodun bu çizgilerin arasına gelecek # ======================== meslekler = File.readlines('meslekler.txt', chomp: true) nesneler = File.readlines('nesneler.txt', chomp: true) renkler = File.readlines('renkler.txt', chomp: true) sifatlar = File.readlines('sifatlar.txt', chomp: true) output = "#{renkler.sample} rengi #{nesneler.sample} #{sifatlar.sample} #{meslekler.sample}" puts output.split.map {|word| word.capitalize(:turkic)}.join(' ') # ========================
true
2734c4cbce54464dbab0b08566c72dcc22299d56
Ruby
sohooo/favbuster
/favbuster.rb
UTF-8
2,038
3.015625
3
[]
no_license
# FavBuster Script ----------- by Sven Sporer 2011 # This script deletes all tweets marked as favorites. # --------------------------------------------------- # Usage: # 1) First, call initial_auth.rb to get the access token and secret. # 2) Create a config.yaml with the following content: # # oauth: # consumer_key: "<consumer key>" # consumer_secret: "<consumer secret>" # access_token: <access token from initial_auth.rb> # access_secret: <access secret from initial_auth.rb> require "rubygems" require "bundler/setup" require "highline/import" require "twitter" # ---------------------------------------------------------------------- # AFTER SUCCESSFUL AUTH # ---------------------------------------------------------------------- CONFIG_FILE = File.expand_path("../config.yaml", __FILE__) CONFIG = YAML::load(File.read(CONFIG_FILE)) Twitter.configure do |config| config.consumer_key = CONFIG['oauth']['consumer_key'] config.consumer_secret = CONFIG['oauth']['consumer_secret'] config.oauth_token = CONFIG['oauth']['access_token'] config.oauth_token_secret = CONFIG['oauth']['access_secret'] end # Just some methods to style (colors, underline links) text. def c(text, style); "<%= color('#{text}', #{style})%> "; end def style(text) styled = "" text.split.each do |phrase| case when phrase.match(/^http/) then styled += c(phrase, "UNDERLINE") when phrase.match(/^@/) then styled += c(phrase, ":yellow") when phrase.match(/^#/) then styled += c(phrase, ":red") else styled += phrase + " " end end styled end # Start cleaning up the favorites list. client = Twitter::Client.new client.favorites.each do |fav| Twitter.favorite_destroy(fav.id) say("<%= color('#{fav.user.screen_name}', :green) %>: #{style(fav.text)}\n") end # Currently, Twitter only allows to delete 20 favs at a time. # We check again in order to call the script again. while client.favorites.size > 0 system("ruby", __FILE__) end
true
b5b2cb1ae2c3d53b336fea9dd3207f09ef629dd9
Ruby
AlexAlt/address_book
/spec/email_spec.rb
UTF-8
1,211
2.890625
3
[]
no_license
require('rspec') require('email') describe(Email) do before() do Email.clear() end describe('#address') do it('returns the address for the email') do test_email = Email.new(:address => "[email protected]", :type => "personal") expect(test_email.address()).to(eq("[email protected]")) end end describe('#type') do it('returns the type of email') do test_email = Email.new(:address => "[email protected]", :type => "personal") expect(test_email.type()).to(eq("personal")) end end describe('.all') do it('initially returns an empty array') do expect(Email.all()).to(eq([])) end end describe('#save') do it('saves a email in the emails array') do test_email = Email.new(:address => "[email protected]", :type => "personal") test_email.save() expect(Email.all()).to(eq([test_email])) end end describe('.clear') do it('clears the array of emails') do Email.clear() expect(Email.all()).to(eq([])) end end describe('#id') do it('returns the id of an email') do test_email = Email.new(:address => "[email protected]", :type => "personal") test_email.save() expect(test_email.id()).to(eq(1)) end end end
true
11fae1e27df93cb1da0ed9bca11e7d038d9e279a
Ruby
joeymariano/patchshair
/db/seeds.rb
UTF-8
1,166
2.765625
3
[]
no_license
# Default Categories bass = Category.create(name: 'Bass') lead = Category.create(name: 'Lead') pad = Category.create(name: 'Pad') percussion = Category.create(name: 'Percussion') arpeggio = Category.create(name: 'Arpeggio') noise = Category.create(name: 'Noise') # Create User 1 and a patch joey = User.create(username: 'joey', password: 'joeyjoey', password_confirmation: 'joeyjoey') patch = Patch.create(name: 'cool', game: '', description: 'awesomely awesome patch', original: true) joey.patches << patch patch.categories << bass # Create User 2 and a patch hoey = User.create(username: 'hoey', password: 'hoeyhoey', password_confirmation: 'hoeyhoey') patch2 = Patch.create(name: 'wow', game: 'Sonic 1', description: 'wowie wow patch', original: false) hoey.patches << patch2 patch2.categories << percussion #Create a lot of patches array = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20] array.each do |i| p = Patch.create(name: "#{i}h", game: '', description: "#{i}h", original: true) hoey.patches << p end array.each do |i| p = Patch.create(name: "#{i}j", game: '', description: "#{i}j", original: true) joey.patches << p end
true
87028df7942c447d7648c98fffd7883a9a478e04
Ruby
superchen14/leetcode
/ruby/034.rb
UTF-8
374
3.53125
4
[]
no_license
# @param {Integer[]} nums # @param {Integer} target # @return {Integer[]} def search_range(nums, target) first_index = nums.index(target) return [-1, -1] if first_index.nil? second_index = first_index while second_index < nums.length && nums[second_index + 1] == target do second_index += 1 end [first_index, second_index] end search_range([1, 2, 2, 3], 4)
true
9890a9e871c601638cf48a9b0beeca86d502ced2
Ruby
cmw/radiant-forum-extension
/lib/forum_tags.rb
UTF-8
7,510
2.8125
3
[]
no_license
module ForumTags include Radiant::Taggable class TagError < StandardError; end desc %{ To enable page commenting, all you have to do is put this in your layout: *Usage:* <pre><code><r:comments:all /></code></pre> In order that pages can still be cached, we show a reply link rather than a form. The sample javascript library included with the forum extension will turn this into a login or comment form as appropriate. } tag 'comments' do |tag| raise TagError, "can't have comments without a page" unless page = tag.locals.page tag.locals.comments = page.posts tag.expand end desc %{ Returns a string in the form "x comments" or "no comments yet". *Usage:* <pre><code><r:comments:summary /></code></pre> } tag 'comments:summary' do |tag| if tag.locals.comments.empty? "no comments yet" elsif tag.locals.comments.size == 1 "one comment" else "#{tag.locals.comments.size} comments" end end tag 'comments:all' do |tag| posts = tag.locals.comments results = [] results << "<h2>Comments</h2>" results << %{<div id="forum">} if posts.empty? results << "<p>None yet.</p>" else posts.each do |post| tag.locals.comment = post results << tag.render('comment') end end results << %{<h3><a href="/pages/#{tag.locals.page.id}/posts/new" class="comment_link">Add a comment</a></h3>} results << "</div>" results end tag 'comment' do |tag| raise TagError, "can't have r:comment without a post" unless post = tag.locals.comment result = [] if tag.double? tag.locals.reader = post.reader result << tag.expand else result << %{ <div class="post" id="#{post.dom_id}>" <div class = "post_header"> <h2> <a href="#{reader_url(post.reader)}" class="main"> <img src="#{post.reader.gravatar_url(:size => 40)}" width="40" height ="40" class="gravatar" /> #{post.reader.name} </a> </h2> <p class="context">#{post.date_html}</p> </div> <div class = "post_body">#{post.body_html}</div> </div> } end result end desc %{ If you would like comments to have the same appearance and inline editing controls as a normal forum page, you'll be serving reader-specific content that isn't cacheable. The best way to do that is to include a remote call after the cached page has been served, but only if the page has comments. It does make the cache a bit redundant, yes, but the plan is to add per-reader fragment caching as well. There are a hundred ways to get the comments - all it takes is a JS or JSON request to /pages/:id/topic - but if you're using the sample mootools-based forum.js, you can just do this: *Usage:* <pre><code> <r:comments:remote /> </code></pre> } tag 'comments:remote' do |tag| if tag.locals.page.has_posts? topic = tag.locals.page.topic %{ <div class="comments"> <a href="/forums/#{topic.forum.id}/topics/#{topic.id}" class="remote_content">Comments</a> </div> } else %{ <div class="comments"> <a href="/pages/#{tag.locals.page.id}/posts/new" class="remote_content">Post a comment</a> </div> } end end desc %{ Returns a string in the form "x comments" or "no comments yet". *Usage:* <pre><code><r:comments:summary /></code></pre> } tag 'comments:summary' do |tag| if tag.locals.comments.empty? "no comments yet" elsif tag.locals.comments.size == 1 "one comment" else "#{tag.locals.comments.size} comments" end end desc %{ Anything between if_comments tags is displayed only - dramatic pause - if there are comments. *Usage:* <pre><code><r:if_comments>...</r:if_comments></code></pre> } tag 'if_comments' do |tag| raise TagError, "can't have if_comments without a page" unless page = tag.locals.page tag.expand if page.posts.any? end desc %{ Anything between unless_comments tags is displayed only if there are no comments. *Usage:* <pre><code><r:unless_comments>...</r:unless_comments></code></pre> } tag 'unless_comments' do |tag| raise TagError, "can't have unless_comments without a page" unless page = tag.locals.page tag.expand if page.posts.any? end desc %{ If you want more control over the display of page comments, you can spell them out: *Usage:* <pre><code><r:comments:each> <h2><r:comment:reader:name /></h2> <p class="date"><r:comment:date /></p> <r:comment:body_html /> </r:comments:each> <r:comment_link /> </code></pre> } tag 'comments:each' do |tag| results = [] tag.locals.comments.each do |post| tag.locals.comment = post results << tag.expand end results end tag 'comment:reader' do |tag| raise TagError, "can't have comment:reader without a comment" unless reader = tag.locals.reader tag.expand end desc %{ The name of the commenter } tag 'comment:reader:name' do |tag| tag.locals.reader.name end desc %{ A gravatar for the commenter } tag 'comment:reader:gravatar' do |tag| tag.locals.reader.gravatar end desc %{ The date of the comment } tag 'comment:date' do |tag| tag.locals.comment.created_at.to_s(:html_date) end desc %{ The time_ago of the comment } tag 'comment:ago' do |tag| time_ago_in_words(tag.locals.comment.created_at) end desc %{ The body of the comment as it was entered (but html-escaped) } tag 'comment:body' do |tag| h(tag.locals.comment.body) end desc %{ The body of the comment rendered into html (and whitelisted, so this ought to be safe) } tag 'comment:body_html' do |tag| tag.locals.comment.body_html end desc %{ A link to the post-a-comment form. Typically you'll use a bit of remote scripting to replace this with a comment or login form depending on whether a reader is detected, but you can just leave the link too. If text is given, the link will be wrapped around it. The default is just "Add a comment". Any supplied attributes are passed through, so you can specify class, id and anything else you like. *Usage:* <pre><code> <r:if_comments> <r:comment_link /> </r:if_comments> <r:unless_comments> <r:comment_link class="how_exciting">Be the first to add a comment!</r:comment_link> </r:unless_comments> </code></pre> } tag 'comment_link' do |tag| raise TagError, "can't have `comment_link' without a page." unless tag.locals.page options = tag.attr.dup attributes = options.inject('') { |s, (k, v)| s << %{#{k.downcase}="#{v}" } }.strip attributes = " #{attributes}" unless attributes.empty? text = tag.double? ? tag.expand : "Add a comment" %{<a href="#{tag.render('comment_url')}"#{attributes}>#{text}</a>} end desc %{ The address for add-a-comment links } tag 'comment_url' do |tag| raise TagError, "can't have `comment_url' without a page." unless tag.locals.page new_page_post_url(tag.locals.page) end end
true
b2d4adf0bbd8709c0da95183dc56cfc9b570a7d5
Ruby
macbury/detox
/app/services/channels/rss/fetch.rb
UTF-8
938
2.609375
3
[]
no_license
module Channels module Rss # Download feed content and update channel information # Return feed source class Fetch < Service use Sanitizer::Full, as: :sanitize use Urls::Normalize, as: :normalize_url use DownloadFeed, as: :download_feed def initialize(channel) @channel = channel end def call channel.name ||= sanitize(feed.title) || sanitize(feed.url) channel.site_url = normalize_url(feed.url) if channel.site_url.blank? channel.description = description channel.save! feed end private attr_reader :channel def feed @feed ||= download_feed( feed_url: channel.source, headers: { 'User-Agent' => channel.user_agent } ) end def description feed.respond_to?(:description) ? sanitize(feed.description) : '' end end end end
true
ed17b61cf539521d3399f7c345fdfb6f63e612de
Ruby
tmattel/blackhawk_api
/lib/blackhawk_api/client/resources/product.rb
UTF-8
3,806
2.578125
3
[ "MIT" ]
permissive
module BlackhawkApi # The Product Management API enables client applications to work with information about individual products. # In functionality that enables selling of cards, you application calls the Product Management Service to # provide customers information about specific products in your catalog. class Product < RESTResource @@resource_url = 'productManagement/v1/product' def initialize(config) super(config) end # This API retrieves product information for the specified product_id. # @param product_id The internal identifier for the product. # @return Retrieves the requested product. # @raise 404 - attempt.to.retrieve.nonexistent.entity - Nonexistent entity def find(product_id) setup_request "#{@@resource_url}/#{product_id}" end # This API retrieves a list of summary information about a subset of the products # matching a given product line ID. # @param productline_id The internal identifier for the product line. # @return Retrieves a list of matching product summary entities and the total number of # entities existing in the system matching the given product line ID. def find_by_productline(productline_id) @request = setup_request "#{@@resource_url}s" @request.query = { productLineId: productline_id } @request end # This API returns a list of product summary information for the given product IDs. # @param ids The Product IDs to be searched. # @return Retrieves a list of matching product summary entities and the total number of # entities existing in the system matching the given product IDs. def find_by_ids(ids) @request = setup_request "#{@@resource_url}s" @request.query = { productIds: ids } @request end # This API returns a list of product summary entities matching the given search keyword. # @param keyword Search keyword. # @param exact_match Flag to exactly match the given criteria, the default is true. # @param case_sensistive Flag to exactly match the case of the given criteria, the default is true. # @return Retrieves a list of matching product summary entities and the total count returned from the query and the request elements specified in the request. def find_by_keyword(keyword, exact_match = true, case_sensistive = true) @request = setup_request "#{@@resource_url}s" @request.query = { keyword: keyword, exactMatch: exact_match, caseSensistive: case_sensistive #, #:sortKey => sortKey, :ascending => ascending, :first => first, :maximum => maximum } @request end # This operation returns a list of summary information about a subset # of the products matching a given product configuration ID. # @param configuration_id The internal identifier for the product configuration. # @return Retrieves a list of ProductSummary entities and the total number of entities # existing in the system matching the given configuration ID. def find_by_configuration(configuration_id) @request = setup_request "#{@@resource_url}s" @request.query = { configurationId: configuration_id } @request end # This operation returns a list of summary information for the subset of products # matching a given provisioning type. # @param provisioning_type PHYSICAL or DIGITAL # @return Retrieves a list of ProductSummary entities and the total number of entities # existing in the system matching the given provisioning type. def find_by_provisioning_type(provisioning_type, index = 1, size = 10) @request = setup_request "#{@@resource_url}s" @request.query = { provisioningType: provisioning_type } @request.take(size).skip(index * size) end end end
true
f96a2db47d04283731b230e3b5d50f8ed05e1767
Ruby
jonpetersen/hvseposapp
/vendor/bundle/ruby/2.5.0/gems/apriori-ruby-0.0.9/spec/lib/apriori/item_set_spec.rb
UTF-8
2,126
2.71875
3
[ "MIT" ]
permissive
describe Apriori::ItemSet do before do data = FactoryGirl.build(:sample_data) @item_set = Apriori::ItemSet.new(data) end context '#mine' do it 'returns all association rules meeting the minimum support and confidence' do expect(@item_set.mine(50,90)).to eql({"Mango=>Keychain"=>100.0, "Onion=>Keychain"=>100.0, "Onion=>Eggs"=>100.0, "Eggs=>Keychain"=>100.0, "Yoyo=>Keychain"=>100.0, "Onion=>Keychain,Eggs"=>100.0, "Onion,Keychain=>Eggs"=>100.0, "Onion,Eggs=>Keychain"=>100.0}) end it 'will allow you to mine the same set multiple times' do @item_set.mine(100,100) expect(@item_set.mine(50,90)).to eql({"Mango=>Keychain"=>100.0, "Onion=>Keychain"=>100.0, "Onion=>Eggs"=>100.0, "Eggs=>Keychain"=>100.0, "Yoyo=>Keychain"=>100.0, "Onion=>Keychain,Eggs"=>100.0, "Onion,Keychain=>Eggs"=>100.0, "Onion,Eggs=>Keychain"=>100.0}) end end context '#confidence' do it 'will return a rule with support and confidence' do set1 = ['Eggs'] set2 = ['Onion', 'Keychain'] expect(@item_set.confidence(set1, set2)).to eql(75.0) end end context '#support' do it 'will return the support of an item' do item = ['Mango'] expect(@item_set.support(item)).to eql((3.to_f/5) * 100) end end context '#create_frequent_item_sets' do it 'creates frequent item sets for a given support' do @set = Apriori::ItemSet.new([['1','2','3'], ['1','2','4'], ['1','4','5']]) expect(@set.create_frequent_item_sets(60).first.sets).to eql([['1'],['2'],['4']]) end end context '#create_association_rules' do it 'creates association rules for all combinations' do @set = Apriori::ItemSet.new([['1','2','3'], ['1','2','4'], ['1','4','5']]) @set.create_frequent_item_sets(60) expect(@set.create_association_rules(60)).to eql({"1=>2"=>66.66666666666666, "2=>1"=>100.0, "1=>4"=>66.66666666666666, "4=>1"=>100.0}) end end context '#count_frequency' do it 'will return the frequency of an item in the data set' do item = ['Mango'] expect(@item_set.count_frequency(item)).to eql(3) end end end
true
4953d018f50da8b68d3724b1b91ba7815e8bef95
Ruby
phoenix12394/fileajob
/lib/tasks/sample_data.rake
UTF-8
1,311
2.515625
3
[]
no_license
require 'faker' namespace :db do desc "Fill database w sample data" task :populate => :environment do Rake::Task['db:reset'].invoke make_users make_locations make_categories make_microposts end end def make_users admin = User.create!(:name => "Admin", :email => "[email protected]", :password => "password", :password_confirmation => "password") admin.toggle!(:admin) 99.times do |n| name = Faker::Internet.user_name email = "example-#{n+1}@watever.com" password = "password" User.create!(:name => name, :email => email, :password => password, :password_confirmation => password) end end def make_microposts User.all(:limit => 6).each do |user| 50.times do |n| user.microposts.create!(:title => Faker::Lorem.sentence(1), :content => Faker::Lorem.paragraphs(3), :location_id => n.modulo(10), :category_id => n.modulo(10), :compensation => 10 + rand(25)) end end end def make_locations 50.times do |n| name = Faker::Address.city Location.create!(:name => name) end end def make_categories 50.times do |n| name = Faker::Company.bs name_array = name.split name = name_array[1].capitalize + " " + name_array[2].capitalize Category.create!(:name => name) end end
true
afc9774136dfd66222959ba5d28a3c5cf36cb824
Ruby
srajiang/app-academy-classwork
/w1/w1d4/perilous_procs/phase_3.rb
UTF-8
6,193
3.578125
4
[]
no_license
def selected_map!(arr, prc1, prc2) arr.map! { |ele| prc1.call(ele) ? prc2.call(ele) : ele } nil end # is_even = Proc.new { |n| n.even? } # is_positive = Proc.new { |n| n > 0 } # square = Proc.new { |n| n * n } # flip_sign = Proc.new { |n| -n } # arr_1 = [8, 5, 10, 4] # p selected_map!(arr_1, is_even, square) # nil # p arr_1 # [64, 5, 100, 16] # arr_2 = [-10, 4, 7, 6, -2, -9] # p selected_map!(arr_2, is_even, flip_sign) # nil # p arr_2 # [10, -4, 7, -6, 2, -9] # arr_3 = [-10, 4, 7, 6, -2, -9] # p selected_map!(arr_3, is_positive, square) # nil # p arr_3 # [-10, 16, 49, 36, -2, -9] # res = prc1.call(val) # acc = prc2.call(res) def chain_map(val, procs) procs.inject(val) {|acc, prc| prc.call(acc)} end # add_5 = Proc.new { |n| n + 5 } # half = Proc.new { |n| n / 2.0 } # square = Proc.new { |n| n * n } # p chain_map(25, [add_5, half]) # 15.0 # p chain_map(25, [half, add_5]) # 17.5 # p chain_map(25, [add_5, half, square]) # 225 # p chain_map(4, [square, half]) # 8 # p chain_map(4, [half, square]) # 4 # { proc => "str", proc2 => "str2"} def proc_suffix(sentence, hash) return_sentense = [] sentence = sentence.split(" ") procs = hash.keys sentence.each do |word| true_procs = true_procs(word, procs) true_procs.each { |proc| word += hash[proc] } return_sentense << word end return_sentense.join(" ") end def true_procs(word, procs) procs.select { |proc| proc.call(word) } end # contains_a = Proc.new { |w| w.include?('a') } # three_letters = Proc.new { |w| w.length == 3 } # four_letters = Proc.new { |w| w.length == 4 } # p proc_suffix('dog cat', # contains_a => 'ly', # three_letters => 'o' # ) # "dogo catlyo" # p proc_suffix('dog cat', # three_letters => 'o', # contains_a => 'ly' # ) # "dogo catoly" # p proc_suffix('wrong glad cat', # contains_a => 'ly', # three_letters => 'o', # four_letters => 'ing' # ) # "wrong gladlying catlyo" # p proc_suffix('food glad rant dog cat', # four_letters => 'ing', # contains_a => 'ly', # three_letters => 'o' # ) # "fooding gladingly rantingly dogo catlyo" def proctition_platinum(words, *procs) hash = Hash.new { |h, k| h[k] = []} words.each do |word| procs.each.with_index do |proc, i| if proc.call(word) hash[i + 1] << word break end end end hash end # is_yelled = Proc.new { |s| s[-1] == '!' } # is_upcase = Proc.new { |s| s.upcase == s } # contains_a = Proc.new { |s| s.downcase.include?('a') } # begins_w = Proc.new { |s| s.downcase[0] == 'w' } # p proctition_platinum(['WHO', 'what', 'when!', 'WHERE!', 'how', 'WHY'], is_yelled, contains_a) # # {1=>["when!", "WHERE!"], 2=>["what"]} # p proctition_platinum(['WHO', 'what', 'when!', 'WHERE!', 'how', 'WHY'], is_yelled, is_upcase, contains_a) # # {1=>["when!", "WHERE!"], 2=>["WHO", "WHY"], 3=>["what"]} # p proctition_platinum(['WHO', 'what', 'when!', 'WHERE!', 'how', 'WHY'], is_upcase, is_yelled, contains_a) # # {1=>["WHO", "WHERE!", "WHY"], 2=>["when!"], 3=>["what"]} # p proctition_platinum(['WHO', 'what', 'when!', 'WHERE!', 'how', 'WHY'], begins_w, is_upcase, is_yelled, contains_a) # # {1=>["WHO", "what", "when!", "WHERE!", "WHY"], 2=>[], 3=>[], 4=>[]} def procipher(sent, procs) sent = sent.split(" ") cipher = [] sent.each do |word| procs.each do |key_proc, value_proc| if key_proc.call(word) cipher << value_proc.call(word) else cipher << word break end end end cipher.join(" ") end # is_yelled = Proc.new { |s| s[-1] == '!' } # is_upcase = Proc.new { |s| s.upcase == s } # contains_a = Proc.new { |s| s.downcase.include?('a') } # make_question = Proc.new { |s| s + '???' } # reverse = Proc.new { |s| s.reverse } # add_smile = Proc.new { |s| s + ':)' } # p procipher('he said what!', # is_yelled => make_question, # contains_a => reverse # ) # "he dias ???!tahw" # p procipher('he said what!', # contains_a => reverse, # is_yelled => make_question # ) # "he dias !tahw???" # p procipher('he said what!', # contains_a => reverse, # is_yelled => add_smile # ) # "he dias !tahw:)" # p procipher('stop that taxi now', # is_upcase => add_smile, # is_yelled => reverse, # contains_a => make_question # ) # "stop that??? taxi??? now" # p procipher('STOP that taxi now!', # is_upcase => add_smile, # is_yelled => reverse, # contains_a => make_question # ) # "STOP:) that??? taxi??? !won" def picky_procipher(sent, procs) sent = sent.split(" ") cipher = [] sent.each do |word| count = 1 procs.each do |key_proc, value_proc| if key_proc.call(word) cipher << value_proc.call(word) break elsif count == procs.length cipher << word break else count += 1 end end end cipher.join(" ") end # is_yelled = Proc.new { |s| s[-1] == '!' } # is_upcase = Proc.new { |s| s.upcase == s } # contains_a = Proc.new { |s| s.downcase.include?('a') } # make_question = Proc.new { |s| s + '???' } # reverse = Proc.new { |s| s.reverse } # add_smile = Proc.new { |s| s + ':)' } # p picky_procipher('he said what!', # is_yelled => make_question, # contains_a => reverse # ) # "he dias what!???" # p picky_procipher('he said what!', # contains_a => reverse, # is_yelled => make_question # ) # "he dias !tahw" # p picky_procipher('he said what!', # contains_a => reverse, # is_yelled => add_smile # ) # "he dias !tahw" # p picky_procipher('stop that taxi now', # is_upcase => add_smile, # is_yelled => reverse, # contains_a => make_question # ) # "stop that??? taxi??? now" # p picky_procipher('STOP that taxi!', # is_upcase => add_smile, # is_yelled => reverse, # contains_a => make_question # ) # "STOP:) that??? !ixat"
true
45782e1b3e9fbdee1cba0df8c95506e4ddda1121
Ruby
xenda/s9-e2
/lib/hang_up/engine.rb
UTF-8
4,886
3.25
3
[]
no_license
require 'rbconfig' module HangUp class Engine include GameTurns include Summonings include GameMessages attr_accessor :deck, :players, :screen, :words, :map PLAYER_NUMBER = 4 FOLLOWERS_PER_GAME = 4 def initialize(deck) @screen = Screen.new shuffle_cards(deck) end def start(filename) display_start_message setup_players create_map(filename) update_initial_position place_followers loop_game end def setup_players @available_types = Player::CHARACTER_TYPES.dup choices = [] PLAYER_NUMBER.times do |i| display_character_types choice = ask_character_types(i) choices << extract_character_type(choice) end create_players(choices) end def loop_game @running = true @current_turn = 0 @deciphered_words = [] @chanted_words = [] trap("SIGINT") do close_game end while @running do @current_turn += 1 @players.each_with_index do |player, index| run_player_turn(player, index) end screen.clear attempt_summon_words attempt_summon_cthulhu destun_followers check_end_game_conditions check_exit_game? end close_game end def check_end_game_conditions if deciphered_all_words display_win_message elsif chanted_all_words display_lost_message end end private def create_map(filename) @map = Map.new(filename, @players) end def place_followers @followers = [] width = @map.rows.size height = @map.columns.size FOLLOWERS_PER_GAME.times do placed = false until placed pos_x = rand(width) pos_y = rand(height) if @map[pos_x, pos_y].empty? @followers << Follower.new @map[pos_x, pos_y].occupant = @followers.last placed = true end end end end def draw_header(player, index) show_current_player(player, index) show_map end def show_map screen.say "" screen.say @map.draw screen.say "" screen.draw_line end def show_actions_for(player) screen.draw do say "Available actions:" player.actions.each_with_index do |action,index| say "#{index+1}: #{action.title}" end end end def characters_list keys = @available_types.keys keys.map.with_index do |type, index| "#{index+1}: #{type.to_s.upcase}: #{@available_types[type]}" end.join("\n") end def display_character_types screen.draw_line screen.say "Choose your character:".upcase screen.say characters_list screen.draw_line end def ask_character_types(i) screen.say "Player #{i+1}, choose your character:" result = screen.ask("Enter the related number") screen.clear result end def show_current_player(player, index) turn = "TURN #{@current_turn}" player_info = "[Player #{index+1}: #{player.character}]" screen.draw_line screen.say "#{turn} #{player_info}\n" screen.say "" red_cards = player.clue_cards(:red) red_message = "Red Cards: #{red_cards}" green_cards = player.clue_cards(:green) green_message = "Green Cards: #{green_cards}" blue_cards = player.clue_cards(:blue) blue_message = "Blue Cards: #{blue_cards}" screen.say "#{red_message} #{blue_message} #{green_message}" screen.draw_line chanted_words = @chanted_words.join(" ") current_words = "#{@chanted_words.size}/#{NEEDED_SUMMONING_WORDS}" screen.say "Chanted words: #{chanted_words} #{current_words}\n" deciphered_words = @deciphered_words.uniq.join(" ") screen.say "Deciphered words: #{deciphered_words}\n" screen.draw_line end def close_game display_exit_message exit end def extract_character_type(choice) symbol = @available_types.keys[choice.to_i-1] @available_types.delete(symbol) symbol end def shuffle_cards(deck) @deck = deck @deck.shuffle_cards end def update_initial_position @players.each do |player| player.update_position(@players, @map) end end def create_players(choices) @players = choices.map do |choice| Player.new(choice, @deck, @map) end end def check_exit_game? exit = screen.ask "Type 'yes' to end or anything to go on." @running = false if exit == "yes" end def destun_followers @followers.each &:wake_up end end end
true
69667ca0b4ffb44bf5692fade95e1746fda22bd1
Ruby
jamiejpace/shy-shadow-4807
/spec/models/garden_spec.rb
UTF-8
1,635
2.515625
3
[]
no_license
require 'rails_helper' RSpec.describe Garden do describe 'relationships' do it { should have_many(:plots) } end describe 'instance methods' do describe '.unique_plants_short_harvest' do before :each do @garden = Garden.create!(name: "Jamie's Garden", organic: true) @plot1 = @garden.plots.create!(number: 1, size: "Large", direction: "West") @plot2 = @garden.plots.create!(number: 2, size: "Small", direction: "East") @plant1 = Plant.create!(name: "Golden Tomato", description: "Medium sun", days_to_harvest: 50) @plant2 = Plant.create!(name: "Special Lettuce", description: "Mostly shade, lots of water", days_to_harvest: 60) @plant3 = Plant.create!(name: "String Beans", description: "Medium sun, rich soil", days_to_harvest: 70) @plant4 = Plant.create!(name: "Blue Watermelon", description: "Full sun, dry soil", days_to_harvest: 150) @plotplant1 = PlotPlant.create!(plant_id: @plant1.id, plot_id: @plot1.id) @plotplant1 = PlotPlant.create!(plant_id: @plant2.id, plot_id: @plot1.id) @plotplant1 = PlotPlant.create!(plant_id: @plant3.id, plot_id: @plot1.id) @plotplant1 = PlotPlant.create!(plant_id: @plant3.id, plot_id: @plot2.id) @plotplant1 = PlotPlant.create!(plant_id: @plant4.id, plot_id: @plot2.id) end it 'find all the unique plants for a garden that have a harvest time less than 100 days and return the plant name' do expect(@garden.unique_plants_short_harvest.length).to eq(3) expect(@garden.unique_plants_short_harvest.first).to eq(@plant1.name) end end end end
true
8f0d4602d97b74d7a43932809a60e4b521681ae1
Ruby
coateds/DevOpsOnWindows
/RubyScripts/BoxClass.rb
UTF-8
519
3.375
3
[]
no_license
class Box attr_accessor :length, :width, :height, :weight, :distance def initialize @@materials_cost = 0.01 #1 cent per square inch @@rate = 0.01 #1 cent per pound per mile end def self.rate= rate @@rate = rate end def self.materials_cost= cost @@materials_cost = cost end def package_cost (@length * @width * 2 + @length * @height *2 + @width * @height *2) * @@materials_cost + @weight * @distance * @@rate end end
true
0d81f2311fe5c5e42fced0005fd6d6324a43ad64
Ruby
janno-p/jannop
/app/models/coin.rb
UTF-8
1,526
2.53125
3
[]
no_license
class Coin < ActiveRecord::Base NOMINAL_VALUES = ['2.00', '1.00', '0.50', '0.20', '0.10', '0.05', '0.02', '0.01'] =begin Coin sizes: 1c - 95px 2c - 110px 5c - 125px 10c - 116px 20c - 130px 50c - 148px 1e - 136px 2e - 150px =end has_attached_file :image, url: '/coins/:id_:style_:basename.:extension', path: "#{Rails.root}/public/coins/:id_:style_:basename.:extension", styles: { normal: '150x150>', collected: { geometry: '150x150>', watermark_path: "#{Rails.root}/public/images/watermark.png", position: 'Center', }, }, default_style: :normal, processors: [:watermark] belongs_to :country validates_attachment_size :image, less_than: 2.megabytes validates :nominal_value, inclusion: { in: NOMINAL_VALUES } validates :type, presence: true validates :country, presence: true private_class_method :new, :allocate def image_url self.image.url self.collected? ? :collected : :normal end def collected? not self.collected_at.nil? end def collect(collected_at, collected_by) if collected_at.nil? then self.collected_at = nil self.collected_by = nil else self.collected_at = collected_at if self.collected_at.nil? self.collected_by = collected_by end end def self.get_latest(n) limit(n).where('collected_at is not null').order('collected_at desc').to_a end def self.wishlist(max_results = nil) limit(max_results).where(collected_at: nil) end end
true
151c969562a2e5831ecbbb742aafc8628ecdefce
Ruby
nmyers93/codewars-ruby
/bits.rb
UTF-8
195
3.65625
4
[]
no_license
def count_bits(n) arr = [] new_num = n while new_num > 0 do arr << new_num % 2 #todo new_num /= 2 end bits = arr.select {|a| a == 1} puts bits.length end count_bits(1234)
true
98e652174f4b4b99453fe21c5ae6b6f5975fc3e8
Ruby
steffenm/activerecord-neo4j-adapter
/lib/neo4j/result.rb
UTF-8
910
2.734375
3
[]
no_license
module Neo4j class Result include Enumerable attr_accessor :columns, :data def initialize(model_columns, model_data) @columns = model_columns @data = model_data end def each(options = {}) case options[:as] when :hash result = [] @data.each do |row| result << @columns.zip(row).map{|column, value| denormalize_column_values(column, value)}\ .inject({}){|hash, injected| hash.merge!(injected)} end result else @data.each do |row| yield row end end end def denormalize_column_values(column, value) return {column => (value == "null" ? nil : value)} if (column != 'properties') # Since Neo4j 1.7M01, map() returns a hash # So no need to gsub on a string output obtained from map() any more value end end # Result end # Neo4j
true
42467cdcf9bbf4635daf68d7f80bd0f8dd8fa6f6
Ruby
ScottDenton/oo-relationships-practice-seattle-web-career-012819
/app/models/CF_projects.rb
UTF-8
765
2.9375
3
[]
no_license
class Project attr_accessor :title, :goal, :amount_remaining, :creator @@all = [] def initialize(title, goal, creator) @title = title @goal = goal @creator = creator @amount_remaining = goal @@all << self end def self.all @@all end def self.no_pledges projects = Project.all.map{|project| project.title} pledges = Pledge.all.map{|pledge| pledge.project.title} projects.reject{|x| pledges.include? x} end def self.above_goal self.all.select{|project| project.amount_remaining < 0}.map{|p| p.title} end def self.most_backers tally =Hash.new(0) Pledge.all.each{|pledge| tally[pledge.project.title] +=1} most_backs = tally.max_by{|k,v| v}[1] tally.select{|k,v| v == most_backs} end end
true
3afd546290d5905abe38a1f58136df4472b45c7b
Ruby
shorrockin/adventofcode2019
/13.rb
UTF-8
1,972
3.390625
3
[]
no_license
# frozen_string_literal: true # https://adventofcode.com/2019/day/13 require 'pry' require './boilerplate' require './intcode' Tile = Struct.new(:x, :y, :id) class Game < Boilerstate attr_accessor :program, :score, :positions, :ball, :paddle def parse(input) @program = Intcode.new(input, reader: @options[:reader]) @positions = {} end def run(&blk) output = [] program.writer = Proc.new do |value| output << value if output.length == 3 x, y, id = output if x == -1 && y == 0 @score = id else tile = Tile.new(x, y, id) @positions[[x, y]] = tile @ball = tile if id == 4 @paddle = tile if id == 3 yield if id == 4 && block_given? end output = [] end end program.run end def stringify str = "SCORE: #{score}\n" sort_x = @positions.values.sort_by(&:x) sort_y = @positions.values.sort_by(&:y) min_x, max_x = [sort_x.first.x, sort_x.last.x] min_y, max_y = [sort_y.first.y, sort_y.last.y] (min_y..max_y).each do |y| (min_x..max_x).each do |x| if (tile = @positions[[x, y]]) str = str + (case tile.id when 0 then ' ' when 1 then '█'.red when 2 then '█'.blue when 3 then '='.bold when 4 then '●'.teal else; ' '; end) end end str = str + "\n" end str end end part 1 do game = Game.new(input) game.run assert_equal(348, game.positions.values.select {|t| t.id == 2 }.length, "game.blocks.length") end part 2 do direction = 0 game = Game.new(input, reader: -> {direction}) game.program.write(0, 2) game.run do puts `clear` puts game.stringify if !game.paddle.nil? && !game.ball.nil? direction = game.ball.x <=> game.paddle.x end end # draw it one more time now that the game has finished puts `clear` puts game.stringify end
true
fa87dca729e7c6395bab861d2664b280f2e5a1a8
Ruby
dylanerichards/tic-tac-toe
/cell.rb
UTF-8
135
2.875
3
[]
no_license
class Cell attr_accessor :value def initialize(value: :blank) @value = value end def blank value == :blank end end
true
e5e5340b082060fe4b625a53d8da2752e5ba5e77
Ruby
evanhughes3/tutorials
/algorithms/ruby/evernote_questions.rb
UTF-8
603
3.828125
4
[ "MIT" ]
permissive
# https://evernote.com/careers/challenge.php # Frequency Counting of Words / Top N words in a document. # Given N terms, your task is to find the k most frequent terms from given N terms. arr = ['Fee', 'Fee', 'Fee', 'Fi', 'Fo', 'Fum', 'Fi', ] def count_of_words(array_of_words, top_number) count_hash = Hash.new(0) return_array = [] array_of_words.each do |word| count_hash[word] += 1 end sorted_nested_arrays = count_hash.sort_by do |word, occurences| occurences end sorted_nested_arrays.reverse[0..(top_number-1)].flatten.each end count_of_words(arr, 2) == ['Fee', 'Fi']
true
3624cabcd6cee2241ea2867b5a409335e07c97af
Ruby
NARKOZ/gitlab
/lib/gitlab/client/tags.rb
UTF-8
3,987
2.625
3
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# frozen_string_literal: true class Gitlab::Client # Defines methods related to tags. # @see https://docs.gitlab.com/ce/api/tags.html module Tags # Gets a list of project repository tags. # # @example # Gitlab.tags(42) # # @param [Integer, String] project The ID or name of a project. # @param [Hash] options A customizable set of options. # @option options [Integer] :page The page number. # @option options [Integer] :per_page The number of results per page. # @return [Array<Gitlab::ObjectifiedHash>] def tags(project, options = {}) get("/projects/#{url_encode project}/repository/tags", query: options) end alias repo_tags tags # Creates a new project repository tag. # # @example # Gitlab.create_tag(42, 'new_tag', 'master') # Gitlab.create_tag(42, 'v1.0', 'master', 'Release 1.0') # # @param [Integer, String] project The ID or name of a project. # @param [String] tag_name The name of the new tag. # @param [String] ref The ref (commit sha, branch name, or another tag) the tag will point to. # @param [String] message Optional message for tag, creates annotated tag if specified. # @param [String] description Optional release notes for tag. # @return [Gitlab::ObjectifiedHash] def create_tag(project, tag_name, ref, message = '', description = nil) post("/projects/#{url_encode project}/repository/tags", body: { tag_name: tag_name, ref: ref, message: message, release_description: description }) end alias repo_create_tag create_tag # Gets information about a repository tag. # # @example # Gitlab.tag(3, 'api') # Gitlab.repo_tag(5, 'master') # # @param [Integer, String] project The ID or name of a project. # @param [String] tag The name of the tag. # @return [Gitlab::ObjectifiedHash] def tag(project, tag) get("/projects/#{url_encode project}/repository/tags/#{url_encode tag}") end alias repo_tag tag # Deletes a repository tag. Requires Gitlab >= 6.8.x # # @example # Gitlab.delete_tag(3, 'api') # Gitlab.repo_delete_tag(5, 'master') # # @param [Integer, String] project The ID or name of a project. # @param [String] tag The name of the tag to delete # @return [Gitlab::ObjectifiedHash] def delete_tag(project, tag) delete("/projects/#{url_encode project}/repository/tags/#{url_encode tag}") end alias repo_delete_tag delete_tag # Adds release notes to an existing repository tag. Requires Gitlab >= 8.2.0 # # @example # Gitlab.create_release(3, '1.0.0', 'This is ready for production') # Gitlab.repo_create_release(5, '1.0.0', 'This is ready for production') # # @param [Integer, String] project The ID or name of a project. # @param [String] tag The name of the new tag. # @param [String] description Release notes with markdown support # @return [Gitlab::ObjectifiedHash] def create_release(project, tag, description) post("/projects/#{url_encode project}/repository/tags/#{url_encode tag}/release", body: { description: description }) end alias repo_create_release create_release # Updates the release notes of a given release. Requires Gitlab >= 8.2.0 # # @example # Gitlab.update_release(3, '1.0.0', 'This is even more ready for production') # Gitlab.repo_update_release(5, '1.0.0', 'This is even more ready for production') # # @param [Integer, String] project The ID or name of a project. # @param [String] tag The name of the new tag. # @param [String] description Release notes with markdown support # @return [Gitlab::ObjectifiedHash] def update_release(project, tag, description) put("/projects/#{url_encode project}/repository/tags/#{url_encode tag}/release", body: { description: description }) end alias repo_update_release update_release end end
true
391e3b7337838442bfc664f465ae1a70c7dac1fa
Ruby
Podenniy/falconmotors
/db/migrate/20131002205209_combine_items_in_cart.rb
UTF-8
1,115
2.515625
3
[]
no_license
class CombineItemsInCart < ActiveRecord::Migration def up #замена нескольких записей для одного и тогоже # товара в корзине одной записью Cart.all.each do |cart| #подсчет колличества каждогго товара sums = cart.line_items.group(:spare_part_id).sum(:quantity) sums.each do |spare_part_id, quantity| if quantity > 1 #удаление отдельных записей cart.line_items.where(spare_part_id: spare_part_id).delete_all cart.line_items.create(spare_part_id: spare_part_id, quantity: quantity) end end end end def down #разбиение записей с quantity>1 на несколкозаписей LineItem.where("quantity>1").each do |line_item| line_item.quantity.times do LineItem.create cart_id: line_item.cart_id, spare_part_id: line_item.spare_part_id, quantity:1 end #удаление исходной записи line_item.destroy end end end
true
767dd7f07e589a95808d9b456479f5cc337180a0
Ruby
christopher-hague/rspec-student-testing
/student.rb
UTF-8
852
3.234375
3
[]
no_license
class Student attr_accessor :true_pal, :clique, :intelligence attr_reader :name, :teacher, :homeroom @@all = [] def initialize(student_info) @name = student_info[:name] @true_pal = student_info[:true_pal] @clique = student_info[:clique] @teacher = student_info[:teacher] @homeroom = student_info[:homeroom] @intelligence = student_info[:intelligence] @@all << self end def now_friends self.true_pal = true unless self.true_pal end def had_fight self.true_pal = false if self.true_pal end def self.list_nerds @@all.select { |student| student.intelligence >= 9 } end def self.list_friends @@all.select { |student| student.true_pal } end def self.list_classmates(homeroom) @@all.select { |student| student.homeroom === homeroom } end def self.all @@all end end
true
48494f636e3fbeb9b152b444e403e72367d49d5b
Ruby
srinjoychakravarty/final_hospital_app
/app/models/doctor.rb
UTF-8
1,853
2.609375
3
[]
no_license
class Doctor < ActiveRecord::Base attr_accessible :email, :first_name, :gender, :last_name, :phone, :specialization has_many :appointments has_many :patients ,:through => :appointments before_save :format_phone validates :email, :first_name, :gender, :last_name, :phone, :specialization, :presence => true validates_format_of :email, :with => /^[\w]([^@\s,;]+)@(([\w-]+\.)+(com|edu|org|net|gov|mil|biz|info|qa))$/i, :message => "is not a valid format" validates_format_of :phone, :with => /^(\+?\d{11}|\+?\d{3}?[-.]?\d{4}[-.]?\d{4})$/, :message => "should be 11 digits (country code needed) delimited with dashes only" GENDERS = [['Male'], ['Female']] Specialization = [['Audiologist'], ['Allergist'], ['Andrologist'], ['Anesthesiologist'], ['Cardiologist'], ['Dentist'], ['Dermatologist'], ['Emergency Doctor'], ['Endocrinologist'], ['ENT Specialist'], ['Epidemiologist'], ['Family Practician'], ['Gastroenterologist'], ['Geneticist'], ['Gynecologist'], ['Hematologist'], ['Hepatologist'], ['Immunologist'], ['Infectious Disease Specialist'], ['Internist'], ['Internal Medicine Specialist'], ['Microbiologist'], ['Neonatologist'], ['Nephrologist'], ['Neurologist'], ['Neurosurgeon'], ['Obstetrician'], ['Oncologist'], ['Ophthalmologist'], ['Orthopedic Surgeon'], ['Perinatologist'], ['Paleopathologist'], ['Parasitologist'], ['Pathologist'], ['Pediatrician'], ['Physiologist'], ['Physiatrist'], ['Plastic Surgeon'], ['Podiatrists'], ['Psychiatrist'], ['Pulmonologist'], ['Radiologists'], ['Rheumatologsist'], ['Surgeon'], ['Urologist'], ['Veterinarian']] scope :alphabetical, order('last_name, first_name') def proper_name first_name+" "+last_name end def name last_name+", "+first_name end private def format_phone phone = self.phone.to_s phone.gsub!(/[^0-9]/, "") self.phone = phone end end
true
9fc8184c38f3da5f5971555f5295c18ee2f8590d
Ruby
sylantyev/adam
/src/app/helpers/asset_data_store.rb
UTF-8
839
2.890625
3
[]
no_license
# Copyright:: (c) Kubris & Autotelik Media Ltd 2008 # Author :: Tom Statter # Date :: Nov 2008 # License:: MIT ? # Store actual data against an Asset's structure, for creating populated output and conversions # TODO - Create iterator directly over @value_map class AssetDataStore attr_accessor :value_map def initialize( asset ) raise TypeError, "Can only store data for object of type Asset" unless asset.is_a?(Asset) @asset_id = asset.id @value_map = {} end def clear() @value_map = {} end def add(composer, value) @value_map[composer.id] ||= [] @value_map[composer.id] << value end # Assume same size array for each key def data_size puts @value_map.values.flatten.size (@value_map.values.flatten.size / @value_map.size) end def size @value_map.size end end
true
cc99e9e086294abc34124ed2d40fe3ea436c5af5
Ruby
mrrusof/algorithms
/corner-to-corner-matrix-traversal/main.rb
UTF-8
897
3.953125
4
[]
no_license
#!/usr/bin/env ruby =begin Given a square matrix of integers, find the maximum sum of elements on the way from the top-left cell to the bottom-right cell. From a given cell, you may only move to the cell to the right or the cell below. Example. The answer for the following matrix is 29. 1 2 3 4 5 6 7 8 9 =end def traverse m n = m.length - 1 (0..n).each do |i| (0..n).each do |j| u = if i > 0 then m[i-1][j] else 0 end l = if j > 0 then m[i][j-1] else 0 end m[i][j] = [u, l].max + m[i][j] end end return m[-1][-1] end [ [[[1,2,3],[4,5,6],[7,8,9]], 29], [[[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]], 73], [[[1,2,3,4],[5,6,7,50],[9,10,11,12],[13,14,15,16]], 97], [[[10,-4,3],[5,2,6],[-1,7,9]], 33] ].each do |m, exp| act = traverse m if exp == act print 'PASS' else print 'FAIL' end puts " traverse [#{m[0]}, ...] = #{act}" end
true
e54d623b760fee013f281532785ef7e290101d79
Ruby
97-Jeffrey/ar-exercises
/exercises/exercise_6.rb
UTF-8
731
3.21875
3
[]
no_license
require_relative '../setup' require_relative './exercise_1' require_relative './exercise_2' require_relative './exercise_3' require_relative './exercise_4' require_relative './exercise_5' puts "Exercise 6" puts "----------" # Your code goes here ... @store1.employees.create(first_name: "Khurram", last_name: "Virani", hourly_rate: 60) @store1.employees.create(first_name: "Jeffrey", last_name: "Shao", hourly_rate: 100) @store1.employees.create(first_name: "sereneany", last_name: "fnsdk", hourly_rate: 30) @store2.employees.create(first_name: "abukrbm", last_name: "Vrcnia", hourly_rate: 50) @store2.employees.create(first_name: "Cindy", last_name: "wang", hourly_rate: 80) puts "there's #{@store1.employees.count} in store1"
true
ac00852d4eaecbfe5afa343b126aa711fc4a9d0f
Ruby
polyfox/moon-packages
/lib/moon/packages/path_finding/__astar.rb
UTF-8
5,306
2.71875
3
[ "MIT" ]
permissive
__END__ module PathFinding module AStar # Initializes Astar for a map and an actor def self.init(map, actor) self.map = map self.actor = actor self.move_cache = {} end # The default heuristic for A*, tries to come close to the straight path def self.heuristic_closer_path(sx, sy, cx, cy, tx, ty) #if util.is_hex? # h = core.fov.distance(cx, cy, tx, ty) #else # Chebyshev distance h = math.max(math.abs(tx - cx), math.abs(ty - cy)) #end # tie-breaker rule for straighter paths dx1 = cx - tx dy1 = cy - ty dx2 = sx - tx dy2 = sy - ty h + 0.01*math.abs(dx1*dy2 - dx2*dy1) end # The a simple heuristic for A*, using distance def self.heuristicDistance(sx, sy, cx, cy, tx, ty) core.fov.distance(cx, cy, tx, ty) end def self.to_single(x, y) x + y * self.map.w end def self.to_double(c) y = math.floor(c / self.map.w) return c - y * self.map.w, y end def self.createPath(came_from, cur) if not came_from[cur] then return end rpath, path = {}, {} while came_from[cur] do x, y = self.to_double(cur) rpath[rpath.size+1] = {x=x,y=y} cur = came_from[cur] end for i = rpath, 1, -1 do path[#path+1] = rpath[i] end return path end # Compute path from sx/sy to tx/ty # @param sx the start coord # @param sy the start coord # @param tx the end coord # @param ty the end coord # @param use_has_seen if true the astar wont consider non-has_seen grids # @param add_check a def that checks each x/y coordinate and returns true if the coord is valid # @return either nil if no path or a list of nodes in the form { {x=...,y=...}, {x=...,y=...}, ..., {x=tx,y=ty}} def self.calc(sx, sy, tx, ty, use_has_seen, heuristic, add_check, forbid_diagonals) heur = heuristic or self.heuristic_closer_path w, h = self.map.w, self.map.h start = self.to_single(sx, sy) stop = self.to_single(tx, ty) open = {[start]=true} closed = {} g_score = {[start] = 0} h_score = {[start] = heur(self, sx, sy, sx, sy, tx, ty)} f_score = {[start] = heur(self, sx, sy, sx, sy, tx, ty)} came_from = {} cache = self.map._fovcache.path_caches[self.actor.getPathString()] checkPos if cache then if not (self.map.isBound(tx, ty) and ((use_has_seen and not self.map.has_seens(tx, ty)) or not cache.get(tx, ty))) then print("Astar fail. destination unreachable") return nil end checkPos = def(node, nx, ny) nnode = self.to_single(nx, ny) if not closed[nnode] and self.map.isBound(nx, ny) and ((use_has_seen and not self.map.has_seens(nx, ny)) or not cache.get(nx, ny)) and (not add_check or add_check(nx, ny)) then tent_g_score = g_score[node] + 1 # we can adjust here for difficult passable terrain tent_is_better = false if not open[nnode] then open[nnode] = true; tent_is_better = true elseif tent_g_score < g_score[nnode] then tent_is_better = true end if tent_is_better then came_from[nnode] = node g_score[nnode] = tent_g_score h_score[nnode] = heur(self, sx, sy, tx, ty, nx, ny) f_score[nnode] = g_score[nnode] + h_score[nnode] end end end else if not (self.map.isBound(tx, ty) and ((use_has_seen and not self.map.has_seens(tx, ty)) or not self.map.checkEntity(tx, ty, Map.TERRAIN, "block_move", self.actor, nil, true))) then print("Astar fail. destination unreachable") return nil end checkPos = def(node, nx, ny) nnode = self.to_single(nx, ny) if not closed[nnode] and self.map.isBound(nx, ny) and ((use_has_seen and not self.map.has_seens(nx, ny)) or not self.map.checkEntity(nx, ny, Map.TERRAIN, "block_move", self.actor, nil, true)) and (not add_check or add_check(nx, ny)) then tent_g_score = g_score[node] + 1 # we can adjust here for difficult passable terrain tent_is_better = false if not open[nnode] then open[nnode] = true; tent_is_better = true elseif tent_g_score < g_score[nnode] then tent_is_better = true end if tent_is_better then came_from[nnode] = node g_score[nnode] = tent_g_score h_score[nnode] = heur(self, sx, sy, tx, ty, nx, ny) f_score[nnode] = g_score[nnode] + h_score[nnode] end end end end while next(open) do # Find lowest of f_score node, lowest = nil, 999999999999999 n, _ = next(open) while n do if f_score[n] < lowest then node = n; lowest = f_score[n] end n, _ = next(open, n) end if node == stop then return self.createPath(came_from, stop) end open[node] = nil closed[node] = true x, y = self.to_double(node) # Check sides for _, coord in pairs(util.adjacentCoords(x, y, forbid_diagonals)) do checkPos(node, coord[1], coord[2]) end end end end end
true
822685396d9020011c45a96730f144f4e59f1e91
Ruby
garimaj2108/phase-0-tracks
/ruby/santa.rb
UTF-8
2,276
4.1875
4
[]
no_license
# Declared a Santa class class Santa attr_reader :age, :ethnicity attr_accessor :gender # Instance method speak greets for holidays! def speak puts "Ho, ho, ho! Haaaappy holidays!" end # This instance method takes a cookie type as parameter def eat_milk_and_cookies(cookie_type) puts "That was a good #{cookie_type} cookie!" end # Ruby special method initialize def initialize(gender,ethnicity) @gender = gender @ethnicity = ethnicity @reindeer_ranking = ["Rudolph", "Dasher", "Dancer", "Prancer", "Vixen", "Comet", "Cupid", "Donner", "Blitzen"] @age = rand(140) puts "Initializing a #{@gender} Santa instance" end # This method increases age by 1 def celebrate_birthday @age = @age + 1 puts "Now Santa's age is #{@age}" end # This method is deleting def get_mad_at(reindeer_name) i = 0 while i < @reindeer_ranking.length if reindeer_name == @reindeer_ranking[i] @reindeer_ranking.delete(@reindeer_ranking[i]) @reindeer_ranking << reindeer_name end i += 1 end puts "Now the reindeer ranking is #{ @reindeer_ranking}" end =begin # getter method def age @age end #getter method def ethnicity @ethnicity end #getter method def gender @gender end # setter method def gender=(new_gender) @gender = new_gender end =end end #santas = [] # Array of example genders example_genders = ["agender", "female", "male", "bigender", "gender fluid", "N/A"] # Array of example ethnicities example_ethnicities = ["black", "Latino", "white", "Japanese-African", "prefer not to say", "Mystical Creature (unicorn)", "N/A"] # Iterate 100 times 100.times do # Create a new instance of class Santa new_santa = Santa.new(example_genders.sample, example_ethnicities.sample) # santas << new_santa - had declared an array earlier # set gender to unknown if meets condition if example_genders == "N/A" new_santa.gender = "unknown" puts "Now the gender is #{new_santa.gender}" end # Driver code new_santa.speak new_santa.eat_milk_and_cookies("Macadamia nut") puts"Santa is currently #{new_santa.age} years old." puts" Santa's ethnicity is #{new_santa.ethnicity}" new_santa.celebrate_birthday new_santa.get_mad_at("Dancer") end
true
00a4c67862a523fa7fe82a7708c1d149d40ebc3b
Ruby
jjromeo/practice-directory
/directory.rb
UTF-8
4,169
3.9375
4
[]
no_license
@students = [] # an empty array accesible to all methods @check @name @cohort @hobby @dob @cob def input_students puts "Please enter the names of the students" puts "To finish, just hit return twice" @name = STDIN.gets.slice(0..-2) # while the name is not empty, repeat this code while [email protected]? do puts "What cohort is #{@name} in?" @cohort = STDIN.gets.slice(0..-2) @cohort = "August" if @cohort.empty? puts "What is #{@name}'s Hobby" @hobby = STDIN.gets.slice(0..-2) puts "When was #{@name} born (dd/mm/yyyy)?" @dob = STDIN.gets.slice(0..-2) puts "Which country was #{@name} born in?" @cob = STDIN.gets.slice(0..-2) #check that the student was entered correctly puts "You entered: #{@name} | Hobby: #{@hobby} | Date of birth: #{@dob} | Country of birth: #{@cob}\n Is this correct? y/n" @check = STDIN.gets.chomp.downcase until @check == "y" || @check == "n" do puts "Sorry, please answer y or n. You entered: #{@name} | Hobby: #{@hobby} | Date of birth: #{@dob} | Country of birth: #{@cob}\n Is this correct? y/n" @check = STDIN.gets.chomp.downcase end if @check == "y" @students << {name: @name, cohort: @cohort.to_sym, hobby: @hobby, dob: @dob, cob: @cob} puts "now we have #{@students.length} students" else puts "please enter the student's details again" end #get another name from the user puts "enter student name" @name = STDIN.gets.slice(0..-2) end # return array of students @students end # and then print them def print_header puts "The students of my cohort at Makers Academy" puts "-----------------" end def show_students print_header prints_student_details end def interactive_menu loop do #1. print the menu and ask the user what to do print_menu #2. read the input and save it into a variable process(STDIN.gets.chomp) #3. do what the user has asked end end def print_menu puts "1. Input the students" puts "2. Show the students" puts "3. Save the list to students.csv" puts "4. Load the list from students.csv" puts "9. Exit" #9 because we'll be adding more items end def process(selection) case selection when "1" # input the students input_students when "2" # show the students show_students when "3" save_students when "4" load_students when "9" exit # this will cause the program to terminate else puts "I don't know what you meant, try again" end end def cohorts @students.map { |mapitem| mapitem[:cohort]}.uniq end def prints_student_details if [email protected]? #lists the cohort cohorts.each do |cohort| print "\nThe #{cohort} cohort\n\n" #lists the students in that cohort @students.select {|x| x[:cohort] == cohort}.each_with_index do |student, i| print "#{i + 1}. #{student[:name]}. Their hobby is #{student[:hobby]} and they were born on the #{student[:dob]} in #{student[:cob]}.\n" end end if @students.length > 1 puts "Overall, we have #{@students.length} great students \n\n" else puts "Overall, we have #{@students.length} great student \n\n" end else puts "The student directory is currently empty" end end def save_students #open the file for writing file = File.open("students.csv", "w") @students.each do |student| student_data = [student[:name], student[:cohort], student[:hobby], student[:dob], student[:cob]] csv_line = student_data.join(",") file.puts csv_line end file.close end def load_students(filename = "students.csv") file = File.open(filename, "r") file.readlines.each do |line| @name, @cohort, @hobby, @dob, @cob = line.chomp.split(',') @students << {name: @name, cohort: @cohort.to_sym, hobby: @hobby, dob: @dob, cob: @cob} end file.close end def try_load_students filename = ARGV.first # first argument from the command line return if filename.nil? # get out of the method if it isn't given if File.exists?(filename) #if it exists load_students(filename) puts "Loaded #{@students.length} from #{filename}" else # if it doesn't exist puts "Sorry, #{filename} doesn't exist" exit #quit the program end end #nothing happens until we call the methods try_load_students interactive_menu
true
e56714cfe1833437d02a554aa3e2d4c49b6f0189
Ruby
jeremyevans/erubi
/lib/erubi/capture_end.rb
UTF-8
2,603
2.890625
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'erubi' module Erubi # An engine class that supports capturing blocks via the <tt><%|=</tt> and <tt><%|==</tt> tags, # explicitly ending the captures using <tt><%|</tt> end <tt>%></tt> blocks. class CaptureEndEngine < Engine # Initializes the engine. Accepts the same arguments as ::Erubi::Engine, and these # additional options: # :escape_capture :: Whether to make <tt><%|=</tt> escape by default, and <tt><%|==</tt> not escape by default, # defaults to the same value as :escape. # :yield_returns_buffer :: Whether to have <tt><%|</tt> tags insert the buffer as an expression, so that # <tt><%| end %></tt> tags will have the buffer be the last expression inside # the block, and therefore have the buffer be returned by the yield # expression. Normally the buffer will be returned anyway, but there # are cases where the last expression will not be the buffer, # and therefore a different object will be returned. def initialize(input, properties={}) properties = Hash[properties] escape = properties.fetch(:escape){properties.fetch(:escape_html, false)} @escape_capture = properties.fetch(:escape_capture, escape) @yield_returns_buffer = properties.fetch(:yield_returns_buffer, false) @bufval = properties[:bufval] ||= '::String.new' @bufstack = '__erubi_stack' properties[:regexp] ||= /<%(\|?={1,2}|-|\#|%|\|)?(.*?)([-=])?%>([ \t]*\r?\n)?/m super end private # Handle the <%|= and <%|== tags def handle(indicator, code, tailch, rspace, lspace) case indicator when '|=', '|==' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace escape_capture = !((indicator == '|=') ^ @escape_capture) terminate_expression @src << "begin; (#{@bufstack} ||= []) << #{@bufvar}; #{@bufvar} = #{@bufval}; #{@bufstack}.last << #{@escapefunc if escape_capture}((" << code @buffer_on_stack = false add_text(rspace) if rspace when '|' rspace = nil if tailch && !tailch.empty? add_text(lspace) if lspace if @yield_returns_buffer terminate_expression @src << " #{@bufvar}; " end @src << code << ")).to_s; ensure; #{@bufvar} = #{@bufstack}.pop; end;" @buffer_on_stack = false add_text(rspace) if rspace else super end end end end
true
0893f7195d012e82d0dfa10dc16e7d11416cb39c
Ruby
Tubbz-alt/WADRC-BCP-Scripts
/bin/tensor_transpose.rb
UTF-8
1,089
2.578125
3
[]
no_license
#!/usr/bin/env ruby $:.unshift File.join(File.dirname(__FILE__),'..','lib') require 'optparse' require 'tensor' def run! # Parse CLI Options and Spec File options = parse_options # Create a DTI Preprocessing Flow Task and run it. tensor = Tensor.new(options[:tensor_file]) tensor.to_fsl_txt(options[:output_file]) end def parse_options options = Hash.new parser = OptionParser.new do |opts| opts.banner = "Usage: #{File.basename(__FILE__)} [options] input_tensor output_transposed_tensor" # opts.on('-t', '--tensor TENSOR_FILE', "Tensor File.") do |tensor_file| # options[:tensor_file] = tensor_file # end opts.on_tail('-h', '--help', "Show this message") { puts(parser); exit } opts.on_tail("Example: #{File.basename(__FILE__)} 40_direction.txt 40_direction_transposed.txt") end parser.parse!(ARGV) options[:tensor_file] = ARGV[0] options[:output_file] = ARGV[1] unless ARGV.size == 2 puts(parser); exit end return options end if File.basename(__FILE__) == File.basename($0) run! end
true
81aac4152e18151fe9d5a610c7a415e776bb21d2
Ruby
platanus/linedump-gem
/lib/linedump/stream_wrapper.rb
UTF-8
999
2.984375
3
[ "MIT" ]
permissive
module Linedump class StreamWrapper MAX_LENGTH = 2048 attr_reader :stream def initialize(_stream, _block) @stream = _stream @block = _block @buffer = [] @eof = false end def eof? @eof end def process_lines begin loop do chunk = @stream.read_nonblock(MAX_LENGTH) process_chunk chunk end rescue IO::WaitReadable # nothing, just stop looping rescue EOFError, IOError @eof = true rescue Exception => exc puts "Error in stream consumer: #{exc.class}" # TODO: not sure where to send this error @eof = true end end private def process_chunk(_chunk) index = _chunk.index $/ unless index.nil? head = _chunk[0..index-1] tail = _chunk[index+1..-1] @block.call(@buffer.join + head) @buffer.clear process_chunk tail else @buffer << _chunk end end end end
true
5064adf27f7ff0dc745101f4ce6ad86900e76385
Ruby
acltc/vg_tools
/lib/helper_tools/checking_methods.rb
UTF-8
307
3.109375
3
[ "MIT" ]
permissive
module CheckingMethods def moved_to_a_valid_square? %w{▒ ╔ ═ ╗ ╝ ╚ ║}.none? { |character| current_square_on_map.include?(character) } end def win? current_square_on_map == target end private def current_square_on_map map[current_square[0]][current_square[1]] end end
true
342eebab3b89714b92c2759f962c5eae75571b74
Ruby
zlschatz/phase-0
/week-5/pad-array/my_solution.rb
UTF-8
4,158
4.25
4
[ "MIT" ]
permissive
# Pad an Array # I worked on this challenge [by myself, with: Amaar] # I spent [2 hours with Amaar, 1 hour solo, 1 hour office hours] hours on this challenge. # Complete each step below according to the challenge directions and # include it in this file. Also make sure everything that isn't code # is commented in the file. #Coditions #minimum size <= length of the array should return array #pad([1,2,3], 3) should return [1,2,3] #array length < min_size, pad should return a new array, padded with final value to meet the min requirement #pad should always return a new object #pad! should modify the original array # 0. Pseudocode # What is the input? #Array, min_size (non-negative integer), optional argument of what the array should be padded with # What is the output? (i.e. What should the code return?) #IF condition 1 is TRUE, the original array will be returned #IF condition 2 is TRUE, the original array with the padded value up to the min number of elements # What are the steps needed to solve the problem? #Define methods to abide by conditions 1 and 2 #create a condtion that accepts two arguments and returns the first if the second is <= array.length #create a second condition that runs if array.length is less than min_size then returns the first argument plus the value as many times as neccesary to meet min_size # 1. Initial Solution =begin def pad!(array, min_size, value = nil) #destructive if array.length >= min_size return array else (min_size - array.length).times do |i| array.push(value) end return array end end def pad(array, min_size, value = nil) #non-destructive new_array = array.clone if array.length >= min_size return new_array else (min_size - array.length).times do |i| new_array.push(value) end return new_array end end =end # 3. Refactored Solution def pad(array, min_size, value = nil) #non-destructive new_array = array.clone if array.length < min_size (min_size - array.length).times {new_array.push(value)} end return new_array end def pad!(array, min_size, value = nil) #destructive if array.length < min_size (min_size - array.length).times {array.push(value)} end return array end # 4. Reflection =begin Were you successful in breaking the problem down into small steps? We were able to break the problem down into steps and address the various conditions. We verbally communicated the goals of the challenge, and translated that into pseudocode. Once you had written your pseudocode, were you able to easily translate it into code? What difficulties and successes did you have? At first we were off to a strong start, successfully navigating through our pseudocode. We encountered issues when trying to push the value back into the array. We struggled with this for quite some time before deciding to take a break from coding and revisit the issue later on. Was your initial solution successful at passing the tests? If so, why do you think that is? If not, what were the errors you encountered and what did you do to resolve them? At first, it was not. We were not using the proper method to iterate through the array. After spending a few hours on the challenge, I joined an office hours session to learn more about iteration. This was very helpful to complete the challenge. When you refactored, did you find any existing methods in Ruby to clean up your code? The refactoring was primarily eliminating redundancies and condensing lines. This included removing the 'do' statement with {}. How readable is your solution? Did you and your pair choose descriptive variable names? I think it's very readable! The new_array variable should make sense to anyone reading through the code. What is the difference between destructive and non-destructive methods in your own words? Destructive methods are ways of warning others that the code being run will result in changed arguments. In this challenge, the destructive (pad!) returned the changed array. The non-destructive (pad) was defined to return new_array so that we know the original array is not being changed. =end
true
83e5b234c2ffbe8daf2bfecfccef06579e0a79d7
Ruby
ramblex/euler
/euler-9.rb
UTF-8
457
3.796875
4
[]
no_license
# # A Pythagorean triplet is a set of three natural numbers, a b c, for which, # a2 + b2 = c2 # For example, 32 + 42 = 9 + 16 = 25 = 52. # There exists exactly one Pythagorean triplet for which a + b + c = 1000.Find the # product abc. # a = 500 while a > 0 b = 500 while b > 0 c = Math.sqrt((a*a) + (b*b)) if c == c.floor and (a + b + c) == 1000 puts "MATCH: #{a} #{b} #{c}" puts a * b * c end b -= 1 end a -= 1 end
true
b3bcd252db4a498bea52f38d31ac431a0c8edc97
Ruby
nesquena/tokyo_cabinet_examples
/examples/table2.rb
UTF-8
285
2.515625
3
[]
no_license
require 'rubygems' require 'rufus/tokyo' t = Rufus::Tokyo::Table.new('../data/table2.tct') t['bob'] = { 'num' => '12' } t['frank'] = { 'num' => '20' } t['george'] = { 'num' => '5' } p t.query { |q| q.add_condition 'num', :numge, '12' q.order_by 'word' q.limit 5 } t.close
true
64bac4ea7343843c78cccc93f76980619883d708
Ruby
fedetaglia/wdi_sydney_3
/students/federico_tagliabue/w1d3/subway.rb
UTF-8
2,892
3.0625
3
[]
no_license
lines = Hash.new lines["N"] = ["times square", "34th", "28th", "23rd", "union square", "8th"] lines["L"] = ["8th", "6th", "union square", "3rd", "1st"] lines["6"] = ["grand central", "33rd", "28th", "23rd", "union square", "astor", "place"] # I ASSUME THERE IS ONLY ONE INTERSECTION ! intersections = (lines["N"] & lines["L"] & lines["6"]).each {|i| i} intersection = intersections[0] create thi def header puts "\e[H\e[2J" # clear screen puts "Federico's Subway App" puts end def footer puts puts "see you the next time!" puts end def check_line (lines, line) until lines.keys.include? line puts "insert a valid line" line = gets.chomp.capitalize end return line end def check_station (lines, licreate thine, station) until lines[line].include? station.downcase puts "insert a valid station" station = gets.chomp.downcase end return station end def find_station (lines, line1, station1, line2, station2) index1 = lines[line1].index(station1) index2 = lines[line1].index(station2) actual_station_index = index1 trip_length = (index2 - index1).abs stations = [] if index2 <= index1 while (actual_station_index > index2) do stations << lines[line2][actual_station_index] actual_station_index -= 1 end else while (actual_statiocreate thin_index < index2 ) do stations << lines[line2][actual_station_index] actual_station_index += 1 end end return stations end def print_result (trip) trip.each {|key,value| puts "Line : #{key}" value.each {|v| puts " #{v}"} } end exit = 0 until exit == "n" do header # input for line and station puts "which is your starting line? N - L - 6" input = gets.chomp.capitalize start_line = check_line(lines, input) puts "which is your starting station?" lines[start_line].each {|staz| puts " #{staz}"} input = gets.chomp.downcase start_station = check_station(lines, start_line, input) puts "which is your final line? N - L - 6" input = gets.chomp.capitalize finish_line = check_line(lines, input) puts "which is your final station?" lines[finish_line].each {|staz| puts " #{staz}"} input = gets.chomp.downcase finish_station = check_station(lines, finish_line, input) trip = {} # Hash with the final result of the program : list of line - station stations = [] # check if the final station is on the same line than the start one if start_line == finish_line trip[start_line] = find_station(lines, start_line, start_station, finish_line, finish_station) else # else means that the start line is different than the finish line trip[start_line] = find_station(lines, start_line, start_station, start_line, intersection) trip[finish_line] = find_station(lines, finish_line, intersection, finish_line, finish_station) end print_result(trip) puts "Do you want to check another trip? Y - N" exit = gets.chomp.downcase end footer
true
3dec71763fe99fd35b2a20da6ce907ecb47b8bad
Ruby
r-cochran/mtg-bot
/searchTO.rb
UTF-8
177
2.609375
3
[ "MIT" ]
permissive
class SearchTO attr_accessor :name, :set def needs_help? @name == "help" end def show_sets? @name == "set list" end def has_set? [email protected]? && @set != "" end end
true
4496832a6d4d9010f6f9e351af4244f361791489
Ruby
NNWaller/oo-kickstarter-cb-000
/lib/project.rb
UTF-8
440
3.21875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Project attr_accessor :title, :backers def initialize(title) @title = title @backers = [ ] end #The add_backer method accepts a Backer as an argument and stores it in a backers array #We are also telling the backer to add the Project instance to the @backed_projects #array that is located in the Backer class. def add_backer(backer) @backers << backer backer.backed_projects << self end end
true
cb36238011448dcfe59774968ecfb53b6a150a9d
Ruby
cgregs32/leetcode_algo
/ruby/grading_students.rb
UTF-8
255
3.4375
3
[]
no_license
def gradingStudents(grades) return grades.map do |grade| next grade if grade < 38 next grade if (grade % 5) < 3 rounded = grade.round(-1) rounded > grade ? rounded : rounded + 5 end end grades = [73,67,38,33] p gradingStudents(grades)
true
1a38ee3f934e5e6b0069f8e09dc2176b91570bdd
Ruby
Leandro-b-03/teelogger
/lib/teelogger/filters/assignment.rb
UTF-8
1,109
2.65625
3
[ "MITNFA" ]
permissive
# # TeeLogger # https://github.com/spriteCloud/teelogger # # Copyright (c) 2014,2015 spriteCloud B.V. and other TeeLogger contributors. # All rights reserved. # require 'teelogger/filter' module TeeLogger module Filter ## # The Assignment filter takes strings of the form <prefix><word>=<value> and # obfuscates the value. class Assignment < FilterBase FILTER_TYPES = [String] WINDOW_SIZE = 1 def initialize(*args) super(*args) # We create more complex matches out of the filter words passed. @matches = [] run_data[:words].each do |word| @matches << /(-{0,2}#{word} *[=:] *)(.*)/i end end def process(*args) # Note that due to the window size of one, args is only an element long. args.each do |arg| @matches.each do |match| # Modify the matching arguments in place arg.gsub!(match, "\1#{::TeeLogger::Filter::REDACTED_WORD}") end end return args end end # class Assignment end # module Filter end # module TeeLogger
true
02ebe21cddeeaf573cfee59aa17b231cb17aab10
Ruby
karashchuk/LessonRuby_01
/lesson_01_methods.rb
UTF-8
2,385
3.640625
4
[]
no_license
#Для класса Fixnum: # Метод, увеличивающий число на единицу puts 11.next puts 11.succ # Метод проверяющий является ли число нулём puts 0.zero? # Метод возвращающий модуль числа puts -12.abs # #Для класса Float: # Метод, округляющий вещественное число вниз до целой части puts 15.6.to_i # Метод, возвращающий результат деления 2-х чисел в виде массива с целой частью и остатком от деления print 11.divmod 5 print "\n" #Для класса String: # Метод, приводящий все символы в строке к нижнему регистру puts "Hello, WORLD!".downcase # Метод, возвращающий следующий символ за текущим (согласно кодам ASCII) puts "a".next + 'd'.succ # Метод изменяющий текущий объект строки, путём удаления предшествующих и завершающих пробельных символов puts " Hello ".strip #Для класса Array: # # Метод, удаляющий все встречающиеся элементы в массиве равные заданному a = [ "a", "b", "b", "b", "c" ] a.delete("b") print a print "\n" # Метод, возвращающий текущий массив с элементами в случайном порядке ss = [1,2,3,4,5,6,7,8,9] print ss.sample(ss.count) puts "\n" # Метод, превращающий массив в строку путём объединения его элементов a = [ "a", "b", "b", "b", "c" ] puts a.join # #Для класса Hash: # # Метод, проверяющий наличие заданного ключа в хэше hh = {sky:'blue',tree:'green',cloud:'white',snow:'white',floor:'brown'} print hh.has_key?(:sky) # Метод, объединяющий 2 объекта хэшей h2 ={wall:'yellow'} print "\n" print hh.merge(h2) print "\n" #Для класса Range: # # Метод, возвращающий максимальное значение диапазона puts ('1'..'g').max
true
fd89b9770129febddd0c41ad0aadd39546009196
Ruby
gearlles/gitlab-changelog-generator
/gitlab_client.rb
UTF-8
1,886
2.625
3
[ "MIT" ]
permissive
require 'gitlab' class GitlabClient attr_accessor :project_name def initialize(endpoint, private_token, project_name) Gitlab.endpoint = endpoint Gitlab.private_token = private_token @project_name = project_name projects = nil begin projects = Gitlab.project_search(project_name) if projects.nil? or projects.count == 0 raise ArgumentError, 'Project not found.' else @project = projects[0] end rescue => ex puts ex.message end end def generate_changelog() tags = Gitlab.tags(@project.id) mrs = Gitlab.merge_requests(@project.id) closed_issues = Gitlab.issues(@project.id, {state: 'closed'}) tags.each_with_index do |current_tag, i| previously_tag = tags[i + 1].nil? ? NIL : tags[i + 1] current_tag_date = DateTime.parse(current_tag.commit.committed_date) puts "#{current_tag.name} (#{current_tag_date.strftime("%F")})" if previously_tag != NIL previously_tag_date = DateTime.parse(previously_tag.commit.committed_date) full_changelog = "#{@project.web_url}/compare/#{previously_tag.name}...#{current_tag.name}" puts "Full changelog: #{full_changelog}" puts 'Merge requests' mrs.each_with_index do |mr, i| mr_date = DateTime.parse(mr.updated_at) if mr_date > previously_tag_date and mr_date < current_tag_date puts "\##{mr.iid}: #{mr.title} (@#{mr.author.username})" end end puts 'Closed issues' closed_issues.each_with_index do |closed_issue, i| closed_issue_date = DateTime.parse(closed_issue.updated_at) if closed_issue_date > previously_tag_date and closed_issue_date < current_tag_date puts "\##{mr.iid}: #{mr.title} (@#{mr.assignee.username})" end end puts '' end end end end
true
5b3d8342bf50b1a1f569e3d3dd202900b882c266
Ruby
jcoglan/advent-of-code
/2016/18/solution.rb
UTF-8
552
2.984375
3
[]
no_license
input_path = File.expand_path('../input.txt', __FILE__) rows = File.read(input_path).strip.lines PATTERNS = ['^^.', '.^^', '^..', '..^'] def new_row(row) cells = row.size.times.map do |i| window = [i-1, i, i+1].map { |j| j < 0 ? '.' : (row[j] || '.') }.join('') PATTERNS.include?(window) ? '^' : '.' end cells.join('') end until rows.size == 400000 rows << new_row(rows.last) end p rows.inject(0) { |s, r| s + r.scan('.').size } __END__ ... ..^ 1 .^. .^^ 1 ^.. 1 ^.^ ^^. 1 ^^^
true
f2915f07291cc4dd1136c2d8a407b749ec463162
Ruby
GalacticPlastic/ironhack
/Week1/Day2/PP_EmployeePayroll/lib/salaried_employee.rb
UTF-8
340
2.890625
3
[]
no_license
class SalariedEmployee < Employee include SalariedPay attr_accessor(:salary) def initialize(name, email, salary) @name = name @email = email @salary = salary end def calculate_salary gross_weekly_pay # => gross_weekly_pay calls: @salary / 52.0 net_weekly_pay = gross_weekly_pay * 0.82 #returns the net weekly pay end end
true
d1522cee0e1def47284803f268cd25250c1d3ee6
Ruby
pgcosta/battleship-game
/spec/player_spec.rb
UTF-8
373
2.796875
3
[]
no_license
require_relative '../boat' require_relative '../board' require_relative '../player' describe Player do it "should calculate the health of all the boats" do player = Player.new board = Board.new boat1 = Boat.new(3) boat2 = Boat.new(3) board.boats = [boat1, boat2] player.board = board expect(player.calculate_player_health).to eq(6) end end
true
39fe045f1fd3c7f206db9246e77a78f4554ced54
Ruby
filipebarcos/metaprogramming-talk
/method_calls/include.rb
UTF-8
212
3.296875
3
[]
no_license
module MyModule def my_method "my_method called on MyModule" end end class MyClass include MyModule def my_method "my method called on MyClass" end end my_class = MyClass.new puts my_class.my_method
true
e9393630e6570035c7131afa021d7795154f686a
Ruby
riekure/ruby-book
/caption8/product_2.rb
UTF-8
743
3.65625
4
[]
no_license
# ログ出力用のメソッドを提供するモジュール module Loggable def log(text) puts "[LOG] #{text}" end end class Product # Loggableモジュールのメソッドを特異メソッド(クラスメソッド)としてミックスインする extend Loggable def self.create_products(names) # logメソッドをクラスメソッド内で呼び出す # (つまりlogメソッド自体もクラスメソッドになっている) log 'create_products is called.' end end # クラスメソッド経由でlogメソッドが呼び出される Product.create_products([]) # Productクラスのクラスメソッドとして直接呼び出すことも可能 Product.log('Hello.')
true
0b8387b84746ef33bb9bc03836c07b448c1800b7
Ruby
ipoval/mongo-ruby-driver
/lib/mongo/cursor.rb
UTF-8
6,443
2.640625
3
[ "Apache-2.0" ]
permissive
# Copyright (C) 2009-2014 MongoDB, Inc. # # 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. module Mongo # Client-side representation of an iterator over a query result set on # the server. # # A +Cursor+ is not created directly by a user. Rather, +CollectionView+ # creates a +Cursor+ in an Enumerable module method. # # @example Get an array of 5 users named Emily. # users.find({:name => 'Emily'}).limit(5).to_a # # @example Call a block on each user doc. # users.find.each { |doc| puts doc } # # @note The +Cursor+ API is semipublic. # @api semipublic class Cursor # Creates a +Cursor+ object. # # @param view [ CollectionView ] The +CollectionView+ defining the query. def initialize(view, response) @view = view @collection = @view.collection @client = @collection.client process_response(response) end # Get a human-readable string representation of +Cursor+. # # @return [String] A string representation of a +Cursor+ instance. def inspect "<Mongo::Cursor:0x#{object_id} @view=#{@view.inspect}>" end # Iterate through documents returned from the query. # # @yieldparam [Hash] Each matching document. def each yield fetch_doc until done? end private # Process the response returned from the server either from # the initial query or from the get more operation. # # @params [ Object ] The response from the operation. def process_response(response) @server = response.server @cache = (@cache || []) + response.docs @returned = (@returned || 0) + @cache.length @cursor_id = response.cursor_id end # Whether we have iterated through all documents in the cache and retrieved # all results from the server. # # @return [true, false] If there are neither docs left in the cache # or on the server for this query. def done? @cache.empty? && exhausted? end # Get the next doc in the result set. # # If the cache is empty, request more docs from the server. # # Check if the doc is an error doc before returning. # # @return [Hash] The next doc in the result set. def fetch_doc request_docs if @cache.empty? doc = @cache.shift doc unless error?(doc) end # Close the cursor on the server. # # If there is neither a server set or if the cursor is already closed, # return nil. Otherwise, send a kill cursor command. def close return nil if @server.nil? || closed? kill_cursors end # Request documents from the server. # # Close the cursor on the server if all docs have been retreived. def request_docs send_get_more close if exhausted? end # Build the +GetMore+ message using the cursor id and number of documents # to return. # # @return [Hash] The +GetMore+ operation spec. def get_more_spec { :to_return => to_return, :cursor_id => @cursor_id, :db_name => @collection.database.name, :coll_name => @collection.name } end def get_more_op Mongo::Operation::Read::GetMore.new(get_more_spec) end # Send a +GetMore+ message to a server to get another batch of results. # # @todo: define exceptions def send_get_more raise Exception, 'No server set' unless @server context = @server.context response = get_more_op.execute(context) process_response(response) end # Build a +KillCursors+ message using this cursor's id. # # @return [KillCursors] The +KillCursors+ message. def kill_cursors_op Mongo::Operation::KillCursors.new({ :cursor_ids => [@cursor_id] }) end # Send a +KillCursors+ message to the server and set the cursor id to 0. def kill_cursors context = @server.context kill_cursors_op.execute(context) @cursor_id = 0 end # Check whether the document returned is an error document. # # @return [true, false] Whether the document is an error document. # @todo: method on response? def error?(doc) # @todo implement this false end # Delta between the number of documents retrieved and the documents # requested. # # @return [Integer] Delta between the number of documents retrieved # and the documents requested. def remaining_limit limit - @returned end # The number of documents to return in each batch from the server. # # @return [Integer] The number of documents to return in each batch from # the server. def batch_size @view.batch_size && @view.batch_size > 0 ? @view.batch_size : limit end # Whether a limit should be specified. # # @return [true, false] Whether a limit should be specified. def use_limit? limited? && batch_size >= remaining_limit end # The number of documents to return in the next batch. # # @return [Integer] The number of documents to return in the next batch. def to_return use_limit? ? remaining_limit : batch_size end # Whether this query has a limit. # # @return [true, false] Whether this query has a limit. def limited? limit > 0 if limit end # Whether the cursor has been closed on the server. # # @return [true, false] Whether the cursor has been closed on the server. def closed? @cursor_id == 0 end # Whether all query results have been retrieved from the server. # # @return [true, false] Whether all results have been retrieved from # the server. def exhausted? return true if closed? limited? && (@returned >= limit) end # The limit setting on the +CollectionView+. # # @return [Integer, nil] Either the limit setting on +CollectionView+ or nil. def limit @view.limit end end end
true
6c8c63fde1884288c64c86d6f92e910c9b511fb1
Ruby
mattduboismatt/sound-persistence
/app/models/user.rb
UTF-8
546
2.78125
3
[]
no_license
class User include ApplicationHelper attr_reader :first_name, :last_name, :gender, :favorite_color, :date_of_birth def initialize(user_params) @first_name = user_params.fetch(:first_name,nil) @last_name = user_params.fetch(:last_name,nil) @gender = user_params.fetch(:gender,nil) @favorite_color = user_params.fetch(:favorite_color,nil) @date_of_birth = date_to_str(user_params.fetch(:date_of_birth,nil)) end def render "#{@last_name} #{@first_name} #{@gender} #{@favorite_color} #{date_of_birth}" end end
true
aa7dc9e9ba61304e383d67ddf056c948c15209b4
Ruby
emiliodacosta/w1d3
/recursion.rb
UTF-8
1,708
3.796875
4
[]
no_license
require 'byebug' def range(min, max) return [] if max <= min rec = range(min+1, max) rec.unshift(min) end def sum_rec(array) return array.first if array.length == 1 array.first + sum_rec(array[1..-1]) end def sum_iter(array) sum = 0 array.each do |num| sum += num end sum end def exp(b, n) return b if n == 1 return 1 if n == 0 b * exp(b, n - 1) end def exp2(b, n) return b if n == 1 return 1 if n == 0 if n.even? evenoper = exp2(b, n/2) evenoper * evenoper else oddoper = exp2(b, (n-1) / 2) b * oddoper * oddoper end end class Array def deep_dup arr = [] self.each do |el| if el.is_a?(Array) arr.push(el.deep_dup) else arr << el end end arr end def subsets return [[]] if self.empty? rec = self[0...-1].subsets rec + rec.map { |set| set + [self.last] } end def permutations return [self] if self.length <= 1 first_el = self.shift new_self = self.permutations result = [] new_self.each do |n_self| (0..n_self.length).times do result << n_self.unshift(first_el) end end end def permutitions return self if self.length == 1 final = [] n = self.length (0...n).each do |i| final << self.rotate(i) end if self.length >2 (0...n).each do |i| final << self.reverse.rotate(i) end end final end end def fibs_it(n) array = [0, 1] (n-2).times do |i| array << array[i] + array[i+1] end array end def fibs_c(n) return [] if n <= 0 return [0] if n == 1 return [0,1] if n == 2 prev_fibs = fibs_c(n-1) prev_fibs << (prev_fibs[-1] + prev_fibs[-2]) end
true
8a52016a38d78e7bf3c329544c4b8d59a0d9eaeb
Ruby
aslamz/appium
/lib/support/helpers/file_helpers.rb
UTF-8
1,496
3.0625
3
[ "Apache-2.0" ]
permissive
module Appium module Helpers # # File/FileUtils wrapper methods # # File.exist? def exist? *args File.exist? *args end # File.exists? def exists? *args File.exists? *args end # File.dirname def dirname *args File.dirname *args end # File.basename def basename *args File.basename *args end # File.basename path, '.*' # # Basename with ext removed # # File.basename('/a/b/c.txt', '.*') # => "c" def basename_no_ext path File.basename path, '.*' end # File.extname(path).downcase def extname *args File.extname(*args).downcase end # File.expand_path def expand_path *args File.expand_path *args end # File.file? def file? *args File.file? *args end # File.directory? def directory? *args File.directory? *args end # FileUtils.mkdir_p def mkdir_p *args FileUtils.mkdir_p *args end # FileUtils.rm_rf def rm_rf *args FileUtils.rm_rf *args end # FileUtils.copy def copy *args FileUtils.copy *args end # FileUtils.copy_entry def copy_entry *args FileUtils.copy_entry *args end # File.expand_path File.join # # Always expand path after joining or the paths may not be valid. # Deleting an unexpanded path will fail for example. def join *paths File.expand_path File.join(*paths) end end end
true
294192b1bbd7f1baef60e84f2a57c29c0ba5089b
Ruby
anaerobeth/Bravo-exercises
/test_scores.rb
UTF-8
875
3.484375
3
[]
no_license
require 'CSV' total_above_90 = 0 total_above_80 = 0 total_above_70 = 0 total_less_70= 0 above_90 = [] above_80 = [] above_70 = [] less_70 = [] # test_scores.csv is found in # https://gist.github.com/anaerobeth/ec82e261f98fc8da4105 CSV.foreach('test_scores.csv', headers: true) do |row| score = row[1].to_f if score >= 90 above_90 << row[0] total_above_90 += 1 elsif score >= 80 above_80 << row[0] total_above_80 += 1 elsif score >= 70 above_70 << row[0] total_above_70 += 1 else less_70 << row[0] total_less_70 += 1 end end puts ">= 90: #{total_above_90}" puts ">= 80: #{total_above_80}" puts ">= 70: #{total_above_70}" puts " < 70: #{total_less_70}" puts '' puts "=== >= 90 ===" puts above_90 puts '' puts "=== >= 80 ===" puts above_80 puts '' puts "=== >= 70 ===" puts above_70 puts '' puts "=== < 70 ===" puts less_70
true
d990e4876d463ff8d6d4c9d4f640147bf361a254
Ruby
rejennarate/short_stories
/catmethod.rb
UTF-8
1,276
4.1875
4
[]
no_license
# cat method @maji = 0 @tristan = 0 def cat question while true puts question reply = gets.chomp.downcase if reply == "a" @tristan = @tristan + 1 break elsif reply == "b" @maji = @maji + 1 break elsif reply == "c" break else puts "please select 'a' or 'b'." end #break end end puts "this is a program for identifying cats." puts "the cats in question are tristan and maji." puts "please answer each question to the best of your ability." cat "is the cat a) kind of orangey in color; b) sort of tabby-like?" cat "does the cat make a sound like: a) a dying animal; b) a dying animal underwater?" cat "is the cat afraid of sneezes? a) yes; b) no" cat "does the cat only like you if you feed it? a) yes; b) no; c) what are you talking about, all cats only like you if you feed them" cat "does the cat like to pick fights with his cat brother? a) no; b) yes" cat "has the cat previously killed and brought home a bat? a) no; b) yes" puts "it appears the cat you are describing is:" if @maji > @tristan puts "maji" elsif @maji < @tristan puts "tristan" elsif @maji == @tristan puts "you don't appear to be describing any particular cat. perhaps you should work on your cat observation skills." else puts "how did you break this?" end
true
2ad8d3463df952cbecb3c27b1f94cb7b52e70fc9
Ruby
WilfriedDeluche/erp_project
/app/helpers/companies_helper.rb
UTF-8
311
2.765625
3
[]
no_license
module CompaniesHelper def contact_name(company) chaine = "" chaine += "#{company.contact_first_name.capitalize} " unless company.contact_first_name.nil? # otherwise error in case attr is nil chaine += company.contact_last_name.upcase unless company.contact_last_name.nil? chaine end end
true
c05068727e86bb0cce1a1d87099998a959a67047
Ruby
dapengli2005/clock-api
/app/models/clock_entry.rb
UTF-8
763
2.546875
3
[]
no_license
class ClockEntry < ApplicationRecord belongs_to :user ALLOWED_ACTION_TYPES = %w(IN OUT) DATETIME_GRACE_PERIOD = 5.minutes # in case user's clock is not synced (not likely, but just in case) validates :action_type, inclusion: { in: ALLOWED_ACTION_TYPES, message: "%{value} is not supported, must be one of #{ALLOWED_ACTION_TYPES}" } validates :datetime, presence: true validate :datetime_not_in_future, if: -> { datetime } scope :by_date_desc, -> { order(datetime: :desc) } def self.next_action(prev_action) prev_action == 'IN' ? 'OUT' : 'IN' end private def datetime_not_in_future if datetime > DateTime.now + DATETIME_GRACE_PERIOD errors.add(:datetime, 'cannot be in the future') end end end
true
22c408445749122b0211c3ba6f1a493a7b35c500
Ruby
ronwoch/classwork
/ruby/last.rb
UTF-8
745
2.90625
3
[]
no_license
#!/usr/bin/ruby #========================================================================================= # Ronald Wochner # Wed May 24 11:34:12 PDT 2017 # Version 1 # Simple ruby script to explore control statements #========================================================================================= data = `last`.split("\n") users = [] hosts = [] data.each do |l| if l == "" next elsif l.start_with? "reboot" next elsif l.start_with? "wtmp" next else l.rstrip! users << l[0,8].rstrip hosts << l[17,16].rstrip.lstrip end end users.uniq! hosts.uniq! until users.empty? print "User: %s\n" % users.pop end while not hosts.empty? print "Host: %s\n" % hosts.pop end
true
5c8a20ef1a2b86507fe62f41f3c2faaffaaf1251
Ruby
cyberarm/ftc_skystone_game
/lib/game_objects/robot.rb
UTF-8
1,605
2.9375
3
[]
no_license
module Game class Robot < Game::GameObject def setup @image = Gosu::Image.new(GAME_ROOT_PATH + "/assets/robot.png") @position += (@image.width / 2) / 2 @angle = 90.0 end def update super forward if Gosu.button_down?(Gosu::KB_UP) || Gosu.button_down?(Gosu::KB_W) backward if Gosu.button_down?(Gosu::KB_DOWN) || Gosu.button_down?(Gosu::KB_S) turn_left if Gosu.button_down?(Gosu::KB_LEFT) turn_right if Gosu.button_down?(Gosu::KB_RIGHT) strife_left if Gosu.button_down?(Gosu::KB_A) strife_right if Gosu.button_down?(Gosu::KB_D) end def forward @velocity.y -= Math.cos(@angle * Math::PI / 180) * relative_speed @velocity.x += Math.sin(@angle * Math::PI / 180) * relative_speed end def backward @velocity.y += Math.cos(@angle * Math::PI / 180) * relative_speed @velocity.x -= Math.sin(@angle * Math::PI / 180) * relative_speed end def strife_left @velocity.y -= Math.sin(@angle * Math::PI / 180) * relative_speed @velocity.x -= Math.cos(@angle * Math::PI / 180) * relative_speed end def strife_right @velocity.y += Math.sin(@angle * Math::PI / 180) * relative_speed @velocity.x += Math.cos(@angle * Math::PI / 180) * relative_speed end def turn_left @velocity.z -= @turn_speed * window.dt end def turn_right @velocity.z += @turn_speed * window.dt end def relative_speed @speed * window.dt end def game_width 18.0 # inches end def game_height 18.0 # inches end end end
true
70b294f6b5c24bcc8d59c2547b34455b60102c7a
Ruby
yangchuanosaurus/rubymonk
/2 - Ruby Primer - Ascent/8 - Finding and Fixing Bugs/logging.rb
UTF-8
2,226
3.765625
4
[]
no_license
# Logging require 'logger' # The caller method returns the stack trace as an array # which is pretty convenient if you want to programmatically introspect it. def c puts "I'm in C. You know who called me?" puts caller end def b c end def a b end a # debug < info < warn < error < fatal < unknown. logger = Logger.new($stdout) # You can set the severity level of logging by assigning the level like so: logger.level = Logger::WARN logger.warn("This is a wraning") logger.info("This is an info") puts # logger.level = Logger::UNKNOWN logger.debug("(UNKNOWN) This a debug message") logger.unknown("(UNKNOWN) Something unknown. Oh, mystery and suspense!") logger.error("(UNKNOWN) Error! Run! Panic!") logger.warn("(UNKNOWN) This is a warning.") logger.level = Logger::INFO logger.debug("(INFO) This a debug message") logger.unknown("(INFO) Something unknown. Oh, mystery and suspense!") logger.error("(INFO) Error! Run! Panic!") logger.warn("(INFO) This is a warning.") puts logger.level = Logger::DEBUG # lowest severity. will print all logs. logger.formatter = lambda do |severity, datetime, progname, msg| "#{datetime} - #{severity}: #{msg}\n" end logger.warn "A warning" logger.info "An info" # Exercise class Order def initialize(order_items, customer) @logger = Logger.new(STDOUT) @logger.level = Logger::INFO @order_items = order_items @customer = customer @state = :new @logger.info("create #{@state} by #{@customer}") end def procure(vendor) if @state == :new @vendor = vendor @state = :procured @logger.info("#{@vendor} procure #{@state}") end end def pack if @state == :procured @state = :packed @logger.info("pack #{@state}") else @logger.error("error when pack #{@state}") end end def ship(address) if @state == :packed @state = :shipped @shipping_address = address @logger.info("ship to #{@shipping_address} #{@state}") else @logger.error("error when ship to #{@shipping_address} #{@state}") end end end order = Order.new(["mouse", "keyboard"], "Asta") order.procure("Awesome Supplier") order.pack order.ship("The Restaurant, End of the Universe")
true
b0fa1f2e8416883c4334bf6e5a5897fe8616e73e
Ruby
albahri/TrashTrack
/app/api_client.rb
UTF-8
841
3.078125
3
[]
no_license
require './lib/api.rb' require 'nokogiri' # CRUD example with an api def list_posts(api_object) puts "Current Post:" doc = Nokogiri::XML.parse api_object.read contents= doc.xpath('posts/post/content').collect {|e| e.text } puts contents.join(", ") puts "" end api = Api.new list_posts(api) # Create puts "Creating someone post..." api.create "Thuy Linh", 3, "Imagepath", "Upper Churctown Road" list_posts(api) # Read one and do nothing with it api.read 1 # Read all and get valid IDs doc = Nokogiri::XML.parse api.read ids = doc.xpath('posts/post/id').collect {|e| e.text } # Update last record puts "Updating last record ..." api.update ids.last, "Hanaa", 3, "Imagepath", "Upper Churctown Road" list_posts(api) # Delete puts "deleting last record ..." api.delete ids.last list_posts(api)
true
17c52b11b98387c21cbd0fb34f828bbe1ad0069b
Ruby
stebbie/learnruby
/ex5.rb
UTF-8
481
3.640625
4
[]
no_license
my_name = 'Zed A. Shaw' my_age = 35 inches = 74 my_weight = 180 my_eyes = 'blue' my_teeth = 'white' my_hair = 'brown' my_height = inches * 2.54 puts "Let's talk about #{my_name}." puts "He's #{my_height} inches tall" puts "He's #{my_weight} pounds heavy" puts "Actually that's not too heavy" puts "He's got #{my_eyes} eyes and #{my_hair} hair" puts "His teeth are usually #{my_teeth}" puts "If I add #{my_age}, #{my_height}, and #{my_weight} I get #{my_age + my_height + my_weight}."
true
dba9e07db763b07f95c3144e1db7ecc387bfb57b
Ruby
bhabig/ruby-intro-to-hashes-lab-v-000
/intro_to_ruby_hashes_lab.rb
UTF-8
1,946
3.015625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' def new_hash {} end def actor actor = {name: "Dwayne The Rock Johnson"} end def monopoly monopoly = {} monopoly[:railroads]= {} monopoly end def monopoly_with_second_tier monopoly = {} monopoly[:railroads]= {} monopoly[:railroads][:pieces]= 4 monopoly[:railroads][:names]= {} monopoly[:railroads][:rent_in_dollars]= {} monopoly end def monopoly_with_third_tier monopoly = {} monopoly[:railroads]={} monopoly[:railroads][:pieces]=4 monopoly[:railroads][:names]={} monopoly[:railroads][:rent_in_dollars]={} monopoly[:railroads][:rent_in_dollars][:one_piece_owned]=25 monopoly[:railroads][:rent_in_dollars][:two_pieces_owned]=50 monopoly[:railroads][:rent_in_dollars][:three_pieces_owned]=100 monopoly[:railroads][:rent_in_dollars][:four_pieces_owned]=200 monopoly[:railroads][:names][:reading_railroad]={} monopoly[:railroads][:names][:pennsylvania_railroad]={} monopoly[:railroads][:names][:b_and_o_railroad]={} monopoly[:railroads][:names][:shortline]={} monopoly end def monopoly_with_fourth_tier monopoly = {} monopoly[:railroads]={} monopoly[:railroads][:pieces]=4 monopoly[:railroads][:names]={} monopoly[:railroads][:rent_in_dollars]={} monopoly[:railroads][:rent_in_dollars][:one_piece_owned]=25 monopoly[:railroads][:rent_in_dollars][:two_pieces_owned]=50 monopoly[:railroads][:rent_in_dollars][:three_pieces_owned]=100 monopoly[:railroads][:rent_in_dollars][:four_pieces_owned]=200 monopoly[:railroads][:names][:reading_railroad]={} monopoly[:railroads][:names][:pennsylvania_railroad]={} monopoly[:railroads][:names][:b_and_o_railroad]={} monopoly[:railroads][:names][:shortline]={} monopoly[:railroads][:names][:reading_railroad]["mortgage_value"]= "$100" monopoly[:railroads][:names][:pennsylvania_railroad]["mortgage_value"]= "$200" monopoly[:railroads][:names][:b_and_o_railroad]["mortgage_value"]= "$400" monopoly[:railroads][:names][:shortline]["mortgage_value"]= "$800" monopoly end
true
fc0de8f434230a9d87943819e070fccedda880f6
Ruby
tobykurien/adventofcode2018
/1/1.rb
UTF-8
251
2.84375
3
[ "MIT" ]
permissive
d = [] f = File.open('data.txt') f.each_line{|line| d << line.to_i} puts d.sum() acc = 0 dup = nil seen = {0=>true} while not dup d.each do |v| i = v + acc acc += v if seen[i] dup = i puts dup return end seen[i] = true end end
true
bc796fec71a8739ee5a7acef31ac6a39f02d9656
Ruby
MollieS/noughtsandcrosses
/spec/board_spec.rb
UTF-8
1,631
3.515625
4
[]
no_license
require 'board' describe Board do context 'positions' do it 'shows the rows' do expect(subject.rows).to eq([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) end it 'shows the columns' do expect(subject.columns).to eq([[1, 4, 7], [2, 5, 8], [3, 6, 9]]) end it 'shows the diagonals' do expect(subject.diagonals).to eq([[1, 5, 9], [7, 5, 3]]) end it 'shows all winning positions' do expect(subject.winning_rows).to eq(subject.rows + subject.columns + subject.diagonals) end it 'returns all free spaces' do expect(subject.available_spaces).to eq((1..9).to_a) end end context 'playing' do it 'puts a mark on the board' do subject.place_mark(1, 'X') expect(subject.grid[0]).to eq 'X' end it 'initializes with an empty grid' do expect(subject).to be_clear end it 'knows when someone has won' do won_game expect(subject.won_by?('X')).to be true end it 'empties the tile' do subject.place_mark(5, 'X') subject.clear_space(5) expect(subject).to be_clear end it 'returns false for a taken space' do subject.place_mark(5, 'X') expect(subject.place_mark(5, 'O')).to be false end it 'returns false for a move out of bounds' do expect(subject.place_mark(10, 'X')).to be false end end def won_game subject.place_mark(1, 'X') subject.place_mark(2, 'O') subject.place_mark(3, 'X') subject.place_mark(4, 'O') subject.place_mark(5, 'X') subject.place_mark(6, 'O') subject.place_mark(7, 'X') subject.place_mark(8, 'O') end end
true
f82982060c9729ae1fcc6f859d9554f915403fa4
Ruby
shipp11/winning-ticket
/winningticket_test.rb
UTF-8
1,007
2.921875
3
[]
no_license
require "minitest/autorun" require_relative "winningticket.rb" class Testwinningticket < Minitest::Test def test_assert_1_is_1 assert_equal(1, 1) end def test_assert_that_there_is_an_array_for_winning_numbers winners = [1234, 4567, 6789] my_ticket = 1234 assert_equal(Array, winning_nums(winners, my_ticket)) end def test_assert_that_my_ticket_is_4_digits winners = [1234, 4567, 6789] my_ticket = 1234 assert_equal(4, my_ticket_length(winners, my_ticket)) end def test_assert_that_my_ticket_is_in_winners_array winners = [1234, 4567, 6789] my_ticket = 1234 assert_equal("winner", ticket_search(winners, my_ticket)) end def test_assert_that_is_a_array_for_so_close_number so_close = [1134, 4557, 6889] my_ticket = 2134 assert_equal("so close", ticket_search(so_close, my_ticket)) end def test_assert_that_is_a_array_for_losing_number losing_number = [4321, 7654, 9876] my_ticket = 1234 assert_equal("loser", ticket_search(losing_number, my_ticket)) end end
true
8c9713f9bf7d04182f2fa6124d36d9428f797114
Ruby
thib123/TPJ
/Notes/Ruby/sample_code/ex0466.rb
UTF-8
1,397
3.015625
3
[ "MIT" ]
permissive
# Sample code from Programing Ruby, page 250 require 'tk' class GifViewer def initialize(filelist) setup_viewer(filelist) end def run Tk.mainloop end def setup_viewer(filelist) @root = TkRoot.new {title 'Scroll List'} frame = TkFrame.new(@root) image_w = TkPhotoImage.new TkLabel.new(frame) do image image_w pack 'side'=>'right' end list_w = TkListbox.new(frame) do selectmode 'single' pack 'side' => 'left' end list_w.bind("ButtonRelease-1") do busy do filename = list_w.get(*list_w.curselection) tmp_img = TkPhotoImage.new { file filename } scale = tmp_img.height / 100 scale = 1 if scale < 1 image_w.copy(tmp_img, 'subsample' => [scale, scale]) image_w.pack end end filelist.each do |name| list_w.insert('end', name) # Insert each file name into the list end scroll_bar = TkScrollbar.new(frame) do command {|*args| list_w.yview *args } pack 'side' => 'left', 'fill' => 'y' end list_w.yscrollcommand {|first,last| scroll_bar.set(first,last) } frame.pack end # Run a block with a 'wait' cursor def busy @root.cursor "watch" # Set a watch cursor yield ensure @root.cursor "" # Back to original end end viewer = GifViewer.new(Dir["screenshots/gifs/*.gif"]) viewer.run
true
f676854882328aea86eb7fe463792e7f34997703
Ruby
Lixxmint/thinknetica
/Lesson_2/mounth.rb
UTF-8
606
3.71875
4
[]
no_license
=begin 1. Сделать хеш, содеращий месяцы и количество дней в месяце. В цикле выводить те месяцы, у которых количество дней ровно 30 =end mounth = {:January => 31, :February => 28, :March => 31, :April => 30, :May => 31, :June => 30, :July => 31, :August => 31, :September => 30, :October => 31, :November => 30, :December => 31 } puts "Список месяцев в которых 31 день:" mounth.each do |m, d| if(d == 30) puts "#{m} - #{d}" end end
true
217d4857547fefd48904ad8a71bd885fcf27a4d2
Ruby
mikecurran/launchschool
/101/lesson_4/twenty-one.rb
UTF-8
5,342
3.65625
4
[]
no_license
#!/usr/bin/env ruby DEALER_LIMIT = 17 GAME_LIMIT = 21 WINNING_SCORE = 5 SUITS = %w(Hearts Diamonds Spades Clubs).freeze VALUES = %w(2 3 4 5 6 7 8 9 10 Jack Queen King Ace).freeze def prompt(msg) puts "=> #{msg}" end def clear_screen system('clear') || system('cls') end def initialize_deck VALUES.product(SUITS).shuffle end def get_cards(deck, num = nil) num.nil? ? deck.shift : deck.shift(num) end def join_cards(cards) cards = cards.map { |card, suit| "#{card} of #{suit}" } cards[-1] = "and #{cards.last}" if cards.size > 1 cards.size == 2 ? cards.join(' ') : cards.join(', ') end def initial_total(cards) values = cards.map { |card| card[0] } aces = sum = 0 values.each do |value| sum += if value == 'Ace' then 11 elsif value.to_i == 0 then 10 # J, Q, K else value.to_i end end values.each { |value| aces += 1 if value == 'Ace' } ace_adjustment(sum, aces) end def running_total(card, sum, aces) value = card[0] sum += if value == 'Ace' then 11 elsif value.to_i == 0 then 10 # J, Q, K else value.to_i end aces += 1 if value == 'Ace' ace_adjustment(sum, aces) end def ace_adjustment(sum, aces) while sum > GAME_LIMIT && aces > 0 sum -= 10 aces -= 1 end [sum, aces] end def detect_result(dealer_total, player_total) if player_total > GAME_LIMIT then :player_busted elsif dealer_total > GAME_LIMIT then :dealer_busted elsif dealer_total < player_total then :player elsif dealer_total > player_total then :dealer else :tie end end def display_result(dealer_total, player_total) result = detect_result(dealer_total, player_total) case result when :player_busted then prompt 'You busted! Dealer wins this round!' when :dealer_busted then prompt 'Dealer busted! You win this round!' when :player then prompt 'You win this round!' when :dealer then prompt 'Dealer wins this round!' when :tie then prompt "It's a tie!" end end def track_score(result, score) if result == :player || result == :dealer_busted score[:player] += 1 elsif result == :dealer || result == :player_busted score[:dealer] += 1 else score[:tie] += 1 end end def display_score(score) prompt "The score is Player: [#{score[:player]}], " \ "Dealer: [#{score[:dealer]}], " \ "Ties: [#{score[:tie]}]" end def show_round_results(dealer_cards, dealer_total, player_cards, player_total) puts '==============' prompt "Dealer has #{join_cards(dealer_cards)}, " \ "for a total of: #{dealer_total}" prompt "Player has #{join_cards(player_cards)}, " \ "for a total of: #{player_total}" puts '==============' display_result(dealer_total, player_total) end def display_game_winner(final_score) final_score.each do |player, score| if score == WINNING_SCORE && player == :player prompt 'You won the game!' elsif score == WINNING_SCORE && player == :dealer prompt 'The dealer won the game!' end end end def busted?(total) total > GAME_LIMIT end def play_again? loop do answer = gets.chomp.downcase return true if %w(y yes).include?(answer) return false if %w(n no).include?(answer) prompt "Please enter 'y' or 'n'" end end loop do score = { player: 0, dealer: 0, tie: 0 } clear_screen loop do deck = initialize_deck dealer_cards = get_cards(deck, 2) player_cards = get_cards(deck, 2) dealer_total, dealer_aces = initial_total(dealer_cards) player_total, player_aces = initial_total(player_cards) display_score(score) prompt "Dealer has: #{dealer_cards[0][0]} " \ "of #{dealer_cards[0][1]} and unknown card" prompt "You have: #{join_cards(player_cards)}, " \ "for a total of #{player_total}" loop do break if busted?(player_total) player_turn = nil loop do prompt 'Would you like to (h)it or (s)tay?' player_turn = gets.chomp.downcase break if %w(h s).include?(player_turn) prompt "Sorry, must enter 'h' or 's'." end if player_turn == 'h' player_cards << get_cards(deck) player_total, player_aces = running_total(player_cards.last, player_total, player_aces) prompt 'You chose to hit!' prompt "Your cards are now: #{join_cards(player_cards)}" prompt "Your total is now: #{player_total}" end break if player_turn == 's' end unless busted?(player_total) prompt "Dealer's turn..." until dealer_total >= DEALER_LIMIT prompt 'Dealer hits!' dealer_cards << get_cards(deck) dealer_total, dealer_aces = running_total(dealer_cards.last, dealer_total, dealer_aces) prompt "Dealer's cards are now: #{join_cards(dealer_cards)}" end end result = detect_result(dealer_total, player_total) track_score(result, score) show_round_results(dealer_cards, dealer_total, player_cards, player_total) prompt 'Press enter to continue...' gets clear_screen break display_game_winner(score) if score.value?(WINNING_SCORE) end prompt 'Do you want to play again? (y or n)' break unless play_again? end prompt 'Thank you for playing Twenty-One. Good bye!'
true
4eeca3ef0cd5009b1423223bbba6bbc9aaf40636
Ruby
asilvadev/QA-automacao-RockLov
/api/spec/scenarios/session_post_spec.rb
UTF-8
1,838
2.578125
3
[ "MIT" ]
permissive
describe "POST /session" do context "login com sucesso" do before(:all) do payload = { email: "[email protected]", password: "pwd123", } @result = Sessions.new.login(payload) end it "validar status code" do expect(@result.code).to eql 200 end it "validar id do usuario" do expect(@result.parsed_response["_id"].length).to eql 24 end end exemples = [ { title: "Wrong Password", payload: { email: "[email protected]", password: "1pwd123" }, code: 401, error: "Unauthorized", }, { title: "Wrong Email", payload: { email: "[email protected]", password: "1pwd123" }, code: 401, error: "Unauthorized", }, { title: "Blank Email input", payload: { email: "", password: "1pwd123" }, code: 412, error: "required email", }, { title: "Undefined Email", payload: { password: "1pwd123" }, code: 412, error: "required email", }, { title: "Blank Password input", payload: { email: "temp", password: "" }, code: 412, error: "required password", }, { title: "Undefined Password", payload: { email: "temp" }, code: 412, error: "required password", }, ] # puts exemples.to_json #gerar estrutura em json para converter em yml # exemples = YAML.load(File.read(Dir.pwd + "/spec/fixtures/login.yml", symbolize_names: true)) exemples.each do |e| context "#{e[:title]}" do before(:all) do @result = Sessions.new.login(e[:payload]) end it "validar status code #{e[:code]}" do expect(@result.code).to eql e[:code] end it "validar error #{e[:error]}" do expect(@result.parsed_response["error"]).to eql e[:error] end end end end
true
c68aa95b291e92c924292db40153da7cd2cf7c5b
Ruby
simonjamain/designexporter-plugin-businesscard
/main
UTF-8
3,803
2.546875
3
[]
no_license
#!/usr/bin/env ruby # encoding: utf-8 require 'nokogiri' require 'csv' require 'yaml' require 'fileutils' require 'shellwords' ACCEPTED_FONTS_EXTENSIONS = %w( .ttf .otf ) ACCEPTED_CONFIGFILE_EXTENSIONS = %w( .yml ) SOURCES_EXTENSION = 'svg' def isValidFontFile?(fontFile) ACCEPTED_FONTS_EXTENSIONS.include? File.extname(fontFile).downcase end def isValidConfigFile?(configFile) ACCEPTED_CONFIGFILE_EXTENSIONS.include? File.extname(configFile).downcase end def isAnterior?(oldFile, newFile) File.mtime(oldFile) < File.mtime(newFile) end # récupérer les arguments indentitiesFile = ARGV[0].to_s sourcesFolder = ARGV[1].to_s outFolder = ARGV[2].to_s # localiser tout les fichiers yml cardsToCompute = [] Dir.foreach(sourcesFolder) do |node| node = File.join sourcesFolder, node if File.file?(node) && isValidConfigFile?(node) configuration = YAML.load File.read(node) sourceFileName = "#{node.chomp( File.extname(node) )}.#{SOURCES_EXTENSION}" unless configuration['businessCardLayersSetups'].nil? || !File.readable?(sourceFileName) cardsToCompute << {:sourceFileName => sourceFileName, :layersSetups => configuration['businessCardLayersSetups']} end end end # envoyer la sauce cardsToCompute.each do |cardToCompute| svgSource = Nokogiri::XML(File.read(cardToCompute[:sourceFileName])) #load configuration files identities = CSV.read(indentitiesFile, headers:true) # 2 COMPUTING #compute each identities identities.each do |identity| svgToEdit = svgSource.clone puts "IDENTITY: #{identity['identityName']}" #change all provided (in csv) and needed fields (in svg) identity.each do |fieldName, fieldContent| #don't process the field containing the identity name unless fieldName == 'identityName' then svgToEdit.xpath('//svg:text[@inkscape:label="' + fieldName + '"]').each do |textTag| puts "'#{fieldName}' content: #{textTag.xpath('./svg:tspan')[0].content} , class: #{textTag.xpath('//svg:tspan')[0].content.class}" textTag.xpath('./svg:tspan')[0].content = fieldContent puts "#{svgToEdit.xpath('//svg:text[@inkscape:label="' + fieldName + '"]/svg:tspan')[0].content}\n\n" end end end #export a version for each layer setup cardToCompute[:layersSetups].each do |layerSetName, layerSet| exportFolderName = File.join outFolder, identity['identityName'] exportFileName = "#{identity['identityName']}_#{layerSetName}" exportFullpath = "#{exportFolderName}/#{exportFileName}" # check if export is needed begin next if isAnterior? cardToCompute[:sourceFileName], "#{exportFullpath}.pdf" rescue end svgLayerSetToEdit = svgToEdit.clone svgAllLayers = svgLayerSetToEdit.xpath('//svg:g[@inkscape:groupmode="layer"]') svgAllLayers.each do |svgLayer| svgCurrentLayerName = svgLayer.attributes['label'].value if layerSet.include? svgCurrentLayerName svgLayer.attributes['style'].value = 'display:inline' #force layer display else svgLayer.remove # not so sure end end #now that only desired layers has been kept, produce the "filtered" svg file FileUtils.mkpath(exportFolderName) #save modified svg File.write("#{exportFullpath}.svg", svgLayerSetToEdit.to_xml) #convert svg to pdf print "#{exportFullpath}.pdf produced.\n" if system "inkscape -C --export-pdf=#{exportFullpath.shellescape}.pdf --export-text-to-path --export-dpi=300 --without-gui #{exportFullpath.shellescape}.svg" #remove modified svg File.delete("#{exportFullpath}.svg") end end end
true
fa03e4e89a2bfc8a4739137124bdb925035ca39c
Ruby
IamNorma/whats-in-my-food
/app/facades/search_facade.rb
UTF-8
180
2.640625
3
[]
no_license
class SearchFacade def fetch_food_data(food) response = FoodService.new.search(food) response[:foods].map do |food_data| Food.new(food_data) end end end
true
76c6c18ae460fe7f7f1aefcf85bb3c15bcae394a
Ruby
Steveo00/launchschool
/ruby_basics/methods/exercise_10.rb
UTF-8
277
3.890625
4
[]
no_license
def name(arr) arr.sample end def activity(arr) arr.sample end def sentence(word1, word2) "#{word1} went #{word2} today!" end names = ['Dave', 'Sally', 'George', 'Jessica'] activities = ['walking', 'running', 'cycling'] puts sentence(name(names), activity(activities))
true
cd2c2a94c53def903adda4e15300cd497b30a210
Ruby
AlexRoadsign/Ruby_basics1-2
/lib/01_hello.rb
UTF-8
75
2.90625
3
[]
no_license
def say_hello (prefix = "Bonjour") puts "#{prefix}" end return say_hello
true
0f8c7873320275dcf33ab23bd2df31cc878f2b06
Ruby
spetluri/ruby-class-variables-and-class-methods-lab-v-000
/lib/song.rb
UTF-8
821
3.390625
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Song attr_accessor :name, :artist, :genre @@count = 0 @@genres = [] @@artists = [] def initialize(name,artist,genre) @name = name @artist = artist @genre = genre @@count += 1 @@genres << genre @@artists << artist end def self.count # => 30 @@count end def self.artists # => ["Jay-Z", "Drake", "Beyonce"] @@artists.uniq end def self.genres # => ["Rap", "Pop"] @@genres.uniq end def self.genre_count # => {"rap" => 5, "rock" => 1, "country" => 3} genres = {} @@genres.each {|k| genres.key?(k) ? genres[k] += 1 : genres[k] = 1 } genres end def self.artist_count # => {"Beyonce" => 17, "Jay-Z" => 40} artists = {} @@artists.each {|k| artists.key?(k) ? artists[k] += 1 : artists[k] = 1 } artists end end
true
72401e772f449be3698057a5b180453239df5b64
Ruby
tranngocsam/turbine
/spec/turbine/graph_spec.rb
UTF-8
3,770
3.015625
3
[]
no_license
require 'spec_helper' describe 'Turbine::Graph' do let(:graph) { Turbine::Graph.new } let(:node) { Turbine::Node.new(:jay) } let(:other) { Turbine::Node.new(:gloria) } describe 'adding a new node' do context 'when the graph is empty' do before { graph.add(node) } it 'should add the node' do expect(graph.node(:jay)).to eql(node) end it 'should be included in the "nodes" enumerable' do expect(graph.nodes).to include(node) end end # when the graph is empty context 'when another non-conflicting node exists' do before do graph.add(other) graph.add(node) end it 'should add the node' do expect(graph.node(:jay)).to eql(node) end it 'should retain the other node' do expect(graph.node(:gloria)).to eql(other) end it 'should be included in the "nodes" enumerable' do expect(graph.nodes).to include(node) end it 'should include the other node in the "nodes" enumerable' do expect(graph.nodes).to include(other) end it 'should draw an edge between them' do expect(graph.node(:jay).connect_to(other)).to be_an Turbine::Edge end end # when another non-conflicting node exists context 'when the key conflicts with an existing node' do before { graph.add(node) } it 'should raise a DuplicateNodeError' do expect(->{ graph.add(Turbine::Node.new(:jay)) }).to raise_error( Turbine::DuplicateNodeError, /Graph already has a node with the key/) end end # when the key conflicts with an existing node end # adding a new node describe 'removing a node' do context 'when the node is not a member of the graph' do it 'raises NoSuchNodeError' do expect { graph.delete(Turbine::Node.new(:nope)) }. to raise_error(Turbine::NoSuchNodeError, /:nope/) end end # when the node is not a member of the graph context 'when the node is a member of the graph' do before :each do graph.add(node) graph.add(other) end let!(:edge_one) { node.connect_to(other, :spouse) } let!(:edge_two) { other.connect_to(node, :spouse) } let!(:result) { graph.delete(node) } it 'returns the removed node' do expect(result).to eql(node) end it 'removes the node from the graph' do expect(graph.nodes).to_not include(node) end it 'removes outward edges from the removed node' do expect(node.out_edges).to_not include(edge_one) end it 'removes inward edges from the removed node' do expect(node.in_edges).to_not include(edge_two) end it 'removes outward edges from surviving nodes' do expect(other.out_edges).to_not include(edge_two) end it 'removes inward edges from surviving nodes' do expect(other.in_edges).to_not include(edge_one) end end end # removing a node describe '#inspect' do before do graph.add(node) graph.add(other) node.connect_to(other, :test) end it 'should show the number of nodes' do expect(graph.inspect).to include('2 nodes') end it 'should show the number of edges' do expect(graph.inspect).to include('1 edges') end end # inspect describe '#tsort' do it 'returns an array when doing an unfiltered sort' do expect(graph.tsort).to be_an(Array) end it 'returns an array when doing a by-label sort' do expect(graph.tsort(:spouse)).to be_an(Array) end it 'returns an array when doing a filtered sort' do expect(graph.tsort { |*| true }).to be_an(Array) end end # tsort end # Turbine::Graph
true
e4a49eb765cd8076251a505221b5612957a429f7
Ruby
ajamarco/programming-univbasics-nds-nds-to-insight-raw-brackets-lab-london-web-010620
/lib/nds_extract.rb
UTF-8
539
2.671875
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
$LOAD_PATH.unshift(File.dirname(__FILE__)) require 'directors_database' def directors_totals(nds) pp nds result = { } puts nds.length nds.length.times do |index| #puts nds[index].length result[nds[index][:name]] = 0 puts "MOVIES BY #{nds[index][:name]}" nds[index][:movies].length.times do |movies_index| puts nds[index][:movies][movies_index][:worldwide_gross] result[nds[index][:name]] += nds[index][:movies][movies_index][:worldwide_gross] end puts "\n\n" end result end
true
c52c0a226e7a5d51c6692398dbfd9a4c658c50f4
Ruby
opal/opal
/stdlib/json.rb
UTF-8
3,627
3.03125
3
[ "MIT" ]
permissive
# backtick_javascript: true module JSON class JSONError < StandardError end class ParserError < JSONError end %x{ var $hasOwn = Opal.hasOwnProperty; function $parse(source) { try { return JSON.parse(source); } catch (e) { #{raise JSON::ParserError, `e.message`}; } }; function to_opal(value, options) { var klass, arr, hash, i, ii, k; switch (typeof value) { case 'string': return value; case 'number': return value; case 'boolean': return !!value; case 'undefined': return nil; case 'object': if (!value) return nil; if (value.$$is_array) { arr = #{`Opal.hash_get(options, 'array_class')`.new}; for (i = 0, ii = value.length; i < ii; i++) { #{`arr`.push(`to_opal(value[i], options)`)}; } return arr; } else { hash = #{`Opal.hash_get(options, 'object_class')`.new}; for (k in value) { if ($hasOwn.call(value, k)) { #{`hash`[`k`] = `to_opal(value[k], options)`}; } } if (!Opal.hash_get(options, 'parse') && (klass = #{`hash`[JSON.create_id]}) != nil) { return #{::Object.const_get(`klass`).json_create(`hash`)}; } else { return hash; } } } }; } class << self attr_accessor :create_id end self.create_id = :json_class def self.[](value, options = {}) if String === value parse(value, options) else generate(value, options) end end def self.parse(source, options = {}) from_object(`$parse(source)`, options.merge(parse: true)) end def self.parse!(source, options = {}) parse(source, options) end def self.load(source, options = {}) from_object(`$parse(source)`, options) end # Raw js object => opal object def self.from_object(js_object, options = {}) options[:object_class] ||= Hash options[:array_class] ||= Array `to_opal(js_object, options)` end def self.generate(obj, options = {}) obj.to_json(options) end def self.dump(obj, io = nil, limit = nil) string = generate(obj) if io io = io.to_io if io.responds_to? :to_io io.write string io else string end end end class Object def to_json to_s.to_json end end # BUG: Enumerable must come before Array, otherwise it overrides #to_json # this is due to how modules are implemented. module Enumerable def to_json to_a.to_json end end class Array def to_json %x{ var result = []; for (var i = 0, length = #{self}.length; i < length; i++) { result.push(#{`self[i]`.to_json}); } return '[' + result.join(',') + ']'; } end end class Boolean def to_json `(self == true) ? 'true' : 'false'` end end class Hash def to_json %x{ var result = []; Opal.hash_each(self, false, function(key, value) { result.push(#{`key`.to_s.to_json} + ':' + #{`value`.to_json}); return [false, false]; }); return '{' + result.join(',') + '}'; } end end class NilClass def to_json 'null' end end class Numeric def to_json `self.toString()` end end class String def to_json `JSON.stringify(self)` end end class Time def to_json strftime('%FT%T%z').to_json end end class Date def to_json to_s.to_json end def as_json to_s end end
true
2cca1c0d6236fa1b8ccdc106f2fa2591f8a41503
Ruby
Mattieuga/CodeNow-May2014
/yasminenassar and jessi67/calc.rb
UTF-8
627
3.5625
4
[]
no_license
begin puts "First number?" user1 = gets.to_i puts "Second number?" user2=gets.to_i puts "Operation?" op= gets.chomp if op== "+" puts "#{user1} + #{user2} = #{user1 + user2}" elsif op== "-" puts "#{user1} - #{user2} = #{user1 - user2}" elsif op== "*" puts "#{user1} * #{user2} = #{user1 * user2}" elsif op== "/" puts "#{user1} / #{user2} = #{user1 / user2}" elsif op== "%" puts "#{user1} % #{user2} = #{user1 % user2}" elsif op== "^" puts "#{user1} ^ #{user2} = #{user1 ** user2}" else puts "cannot compute" end puts "press any key to continue" input= gets.chomp puts puts puts end while input != "done"
true
8bb55b5a7ab8c8396d7bf6e7a8012f51464a71ba
Ruby
ondrejfuhrer/rocket-library
/app/models/rental.rb
UTF-8
1,506
2.65625
3
[ "MIT" ]
permissive
class Rental < ActiveRecord::Base validates_with RentalValidator, on: :create state_machine initial: :active do event :return do transition any => :returned end before_transition any => :returned do |rental| rental.returned_at = Time.now end after_transition any => :returned do |rental| # @type [Rental] rental rental.book.release rental.watch_lists.active.each do |w| UserMailer.watchlist(w.user, rental).deliver_now end end end belongs_to :user belongs_to :book has_many :watch_lists default_scope { order('returned_at DESC') } scope :active, -> { with_state(:active) } scope :returned, -> { with_state(:returned) } after_create do book.rent book.rentals.each do |rental| rental.watch_lists.each do |w| if w.active? if w.user == user w.fulfill w.save! else UserMailer.watchlist_unfulfilled(w.user, self).deliver_now end end end end end # Returns a rental time in human readable format. If the rental is still active, the value shows for how long it is rented until now, # if the rental is already returned it shows the difference between created time and return time # # === Return # @return [String] # def rental_time from_date = (self.returned? ? self.returned_at : Time.current).utc TimeDifference.between(from_date, self.created_at.utc, true).in_general.humanize end end
true
9fa6e8cbf60604fb62a25c8a9ff4a6c1517d2878
Ruby
netoconcon/batch-503-live-code
/acronymize.rb
UTF-8
384
3.421875
3
[]
no_license
def acronymize(sentence) sentence_array = sentence.split(" ") acronym = "" sentence_array.each do |word| acronym += word[0].upcase end return acronym end puts acronymize("Frequently Asked Question") # == "FAQ" # ["Frequently", "Asked", "Question"] puts acronymize("") # == "" puts acronymize("AWAY FROM KEYBOARD") #== "AFK" puts acronymize("what the fuck") # == "WTF"
true