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
f6561467f630b68486ada0af593df41aa4c6e98b
Ruby
martinpoljak/rb.rotate
/lib/rb.rotate/hook.rb
UTF-8
2,895
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# encoding: utf-8 require "yaml" module RbRotate ## # Represents hook. # class Hook ## # Holds name of the hook. # @name ## # Holds data of the hook. # @data ## # Holds arguments of the hook. # @arguments ## # Hold variables for the hook. # @variables ## # Constructor. # def initialize(name, arguments = nil, variables = { }) @name = name @arguments = self.parse_arguments(arguments) @variables = variables end ## # Parses "arguments line". # def parse_arguments(string) if not string.nil? string.split(":") else [] end end ## # Runs hook. # def run! # Gets commans command = self.command.dup # Adds arguments self.expand_arguments(command) # Adds variables self.expand_variables(command) # Runs it pipe = ::File.popen(command) pipe.eof? # ask for EOF causes waiting for terminating the pipe process result = pipe.read pipe.close() # Parses and returns result return self.parse_result(result) end ## # Expands arguments. # def expand_arguments(command) @arguments.each_index do |i| arg = arguments[i] command.gsub! "%" << i.to_s, '"' << arg << '"' end end ## # Expands variables. # def expand_variables(command) @variables.each_pair do |name, value| command.gsub! "%" << name, '"' << value << '"' end end ## # Parses result. # def parse_result(result) if result.strip.empty? return { } end result = YAML.load(result) if not result.kind_of? Hash result = { } log "Warning: result of hook '" << @name.to_s << "' wasn't YAML collection. Ignored." end return result end ## # Gets command. # def command command = Configuration::get.hooks[@name] if command.nil? raise Exception::new("Invalid hook: " << @name.to_s) end end end end
true
07091074b9ad48a490b0ecfaaae29234ad0c5741
Ruby
corokun/kapeka
/lib/kapeka.rb
UTF-8
315
2.875
3
[ "MIT" ]
permissive
require "kapeka/version" module Kapeka # Your code goes here... def self.fpb(x, y) if x == 0 return y elsif y == 0 return x else self.fpb(y, x%y) end end def self.kpk(x, y) (x*y)/self.fpb(x,y) end end class Fixnum def kpkthis(a) Kapeka.kpk(self, a) end end
true
37e59ca2f79da48fb62e2e00a12c08ed01109b2d
Ruby
SalMac86/ttt-8-turn-ruby-intro-000
/lib/display_board.rb
UTF-8
169
2.609375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def display_board blank = " " row = blank + "|" + blank + "|" + blank puts row puts "-----------" puts row puts "-----------" puts row end display_board
true
f5a9120ac7370d12727e989debfba75c36dcc512
Ruby
anuragsx/payrolls
/app/models/incometax/underground_tax_formula.rb
UTF-8
310
2.640625
3
[]
no_license
class UndergroundTaxFormula < TaxFormula THRESHOLD = 800 def employee_tds EmployeeTaxDetail.for_employee(employee).last end def eligible_for_employee? !!employee_tds end def calculate if eligible_for_employee? return amount - [amount,THRESHOLD].min end amount end end
true
49924b65638e8981c0d8f7ad42748723d95e40e0
Ruby
sebaplawner/pdep-ruby-hitbug
/biblioteca.rb
UTF-8
1,000
2.875
3
[]
no_license
require './contenido' class Biblioteca def initialize tamanioIndividual @biblioteca = [] @tamanioIndividual = tamanioIndividual end def contiene contenido @biblioteca.include? contenido end def superaTamanioIndividual contenido contenido.tamanio > @tamanioIndividual end def rebalsa contenido self.tamanio + contenido.tamanio > 500 * @tamanioIndividual end def tamanio @biblioteca.inject(0) { |suma, item| suma + item.tamanio } end def subir contenido raise 'El archivo no se pudo subir' if not contenido.sePuedeSubir self @biblioteca << contenido contenido.modificar end def buscarPorNombre nombre @biblioteca.select{ |item| item.nombre.include? nombre } end def actividadReciente @biblioteca.sort_by{ |item| item.ultimaModificacion }[0..4].map{ |item| item.nombre } end def removerRotos @biblioteca.reject! { |item| item.roto self } end def eliminar contenido @biblioteca.delete contenido end end
true
3fdc447a8e1ae07829b074d1eca6b1ff57bc71b6
Ruby
GCHwee/The_Well_Grounded_Rubyist
/modules/mixing_into_class/stack.rb
UTF-8
411
3.296875
3
[]
no_license
# relative вказує місцеположення відносно файла require_relative 'modules/stacklike' puts class Stack include Stacklike end s = Stack.new s.add_to_stack("item_1") s.add_to_stack("item_2") s.add_to_stack("item_3") puts "Object currently on the stack:" puts s.stack taken = s.take_from_stack puts "Removed this object:" puts taken puts "Now on stack:" puts s.stack puts
true
c8b6ffce0572a0cd7fbee1a2e5e35d2945dd1223
Ruby
fierytortilla/week04_day02_lab_hw
/sinatra_calc/sinatra_calc_start/controller.rb
UTF-8
877
2.734375
3
[]
no_license
require('sinatra') require('sinatra/contrib/all') require_relative('models/calculator') also_reload('./models/*') # get('/add/:num1/:num2') do # return "The add result is #{Calculator.add(params[:num1].to_i, params[:num2].to_i)}" # end get('/root/:num1/:num2') do return "The nth root (where n equals #{params[:num2]}) is #{Calculator.root(params[:num1].to_i(), params[:num2].to_i())}" end #we must tell the controller where to render the calculation variable to. note that the desired location must have the same name as the .erb file we, which is result.erb get('/subtract/:num1/:num2') do @calculation = "#{params[:num1].to_i - params[:num2].to_i}" erb(:result) end get('/add/:num1/:num2') do @calculation = "#{Calculator.add(params[:num1].to_i, params[:num2].to_i)}" erb(:result) end get("/") do erb(:home) end get("/about_us") do erb(:about_us) end
true
e98093fe9f8d91159b6db022759f68deb5b70597
Ruby
lucianboatright/Ruby_Notes_examples
/Ruby_Makers_quiz.rb
UTF-8
43,268
4.375
4
[]
no_license
######## CHAPTER 10 Working # class Todo # def initialize(todo) # @todo = todo # end # def text # @todo # end # end # class TodoList # def initialize # @todo_list = [] # end # def add(todo) # @todo_list.push(todo) # end # def print # @todo_list.each do |word| # word = word.text # puts "* #{word}" # end # end # end # class Todo # def initialize(todo) # @todo = todo # This sets your instance variable @todo to whatever you passing, you will probably want to add a check to make sure you only accept strings # end # def text # @todo # The text method is returning whatever the @todo variable is, in this case since you are passing a string, it is returning a string # end # end # class TodoList # def initialize # @todo_list = [] # When you are initializing your TodoList you are creating an array called @todo_list # end # def add(todo) # @todo_list << Todo.new(todo) # When you call this method you are adding a new instance of your Todo class # end # def print # # Here you are iterating through your array @todo_list, which we established earlier is an array of your Todo Class variables # @todo_list.each do |x| # Pro tip, try to stay away from using names like 'x' or 'y' use more descriptive names # # Your 'x' variable here is one of your Todo classes instances # puts "* #{x.text}" # As defined in your Todo class, you will need to call the text method to retrieve the text you stored in your class # end # end # end ############################# ############################# ##### CHAPTER 9 ######### WORKING and pass test # def random_card # cards = ["two", "three", "four", "five", "six", "seven", # "eight", "nine", "ten", # "jack", "queen", "king", "ace"] # cards[rand(13)] # end # def move # run = true # while run == true # puts "Would you like to 'hit' or 'stick'" # input = gets.chomp # if input == "hit" # run = false # elsif input == "stick" # run = false # else # run = true # end # end # return input # end # def score(hand) # points = 0 # card_values = { # "two" => 2, "three" => 3, "four" => 4, "five" => 5, "six" => 6, # "seven" => 7, "eight" => 8, "nine" => 9, "ten" => 10, "jack" => 10, # "queen" => 10, "king" => 10, "ace" => 11 # } # hand.each do |card| # points += card_values[card].to_i # end # return points # end # def run_game # hand = [] # play = true # while play == true # if move() == "stick" # if score(hand) > 21 # puts "You busted with: #{score(hand)}" # else # puts "You scored: #{score(hand)}" # end # play = false # else # hand.push(random_card) # puts "Score so far: #{score(hand)}" # end # end # end ############################# ###### WORKING BUT NO RUN_GAME ########## # hand = [] # points = 0 # play = true # def random_card # cards = ["two", "three", "four", "five", "six", "seven", # "eight", "nine", "ten", # "jack", "queen", "king", "ace"] # cards[rand(13)] # end # def move(hand,points,play) # # while play == true # puts "Would you like to 'hit' or 'stick'" # choice = gets.chomp # if choice == "stick" # if score(points,hand).to_i > 21 # puts "You busted with: #{score(points,hand)}" # play = false # else # puts "You scored: #{score(points,hand)}" # play = false # end # elsif choice == "hit" # hand.push(random_card) # puts score(points,hand) # # end # end # end # def score(points, hand) # card_values = { # "two" => 2,"three" => 3,"four" => 4,"five" => 5,"six" => 6, # "seven" => 7,"eight" => 8,"nine" => 9,"ten" => 10, "jack" => 10, # "queen" => 10,"king" => 10, "ace" => 11 # } # hand.each do |card| # points += card_values[card].to_i # end # return points # end # # def run_game(play) # # while play == true # # random_card # # move(hand,points,play) # # end # # end # run_game(play) # # move(hand,points,play) ############################# ############################# ######### CHAPTER 8 ###### Version of Group names devided into group number # puts "Please enter how many groups" # group_num = gets.chomp.to_i # counter = 0 # names = [] # while true # puts "Enter name" # name = gets.chomp # if name == "stop" # break # else # names.push(name) # end # end # puts names # count = 0 # length = 0 # empty_table = Array.new(group_num){Array.new()} # print empty_table # names.each do |item| # count = 0 # while true # if count < selection # empty_table[count].push(item) # count += 1 # else count == selection # count = 0 # end # end # end ############################# # selection.times{Array.new} # groups = [] # while true # if counter < selection # names.each do |item| # groups[selection].push(item) # counter += 1 # end # elsif counter >= selection # counter = 0 # end # end ############################# # people = [ # { "name" => "Mary", "sport" => "squash", "fruit" => "blackberry" }, # { "name" => "Lauren", "sport" => "squash", "fruit" => "orange" }, # { "name" => "Isla", "sport" => "weightlifting", "fruit" => "banana" }, # { "name" => "Sam", "sport" => "cycling", "fruit" => "orange" }, # { "name" => "Govind", "sport" => "squash", "fruit" => "banana" }, # { "name" => "Awad", "sport" => "weightlifting", "fruit" => "kiwi" }, # { "name" => "Will", "sport" => "cycling", "fruit" => "blackberry" } # ] # sort_by_groups = {} # puts "Please enter catagory: 'sport' or 'fruit'" # input = gets.chomp # people.each do |catagory_under_consideration| # catagory = catagory_under_consideration["#{input}"] # name = catagory_under_consideration["name"] # if sort_by_groups["#{catagory}"] == nil # sort_by_groups["#{catagory}"] = [name] # else # sort_by_groups["#{catagory}"].push(name) # end # end # sort_by_groups.each { |item| puts item} ############################# # Write a program that calculates the score for a word in Scrabble. # It should: # * Ask the user for a word e.g. `apple`. # * `puts` the score for the word in Scrabble by totalling the points # for each letter in the word. # * Points for each letter: # * 0 points: blank tile # * 1 point: E, A, I, O, N, R, T, L, S, U # * 2 points: D, G # * 3 points: B, C, M, P # * 4 points: F, H, V, W, Y # * 5 points: K # * 8 points: J, X # * 10 points: Q, Z # * Note: You can assume that the user will enter a word that only # contains letters and blanks. You can assume the word will be in # uppercase. # puts "Please enter word" # word = gets.chomp # letter_score_2 = { # " " => 0, # "A" => 1, # "B" => 3, # "C" => 3, # "D" => 2, # "E" => 1, # "F" => 4, # "G" => 2, # "H" => 4, # "I" => 1, # "J" => 8, # "K" => 5, # "L" => 1, # "M" => 3, # "N" => 1, # "O" => 1, # "P" => 3, # "Q" => 10, # "R" => 1, # "S" => 1, # "T" => 1, # "U" => 1, # "V" => 4, # "W" => 4, # "X" => 8, # "Y" => 4, # "Z" => 10 # } # puts "Please enter word" # word = gets.chomp # score = 0 # word.split(//).each do |letter| # score += letter_score_2[letter] # end # puts score # score = 0 # word.split(//).each { |letter| # score += letter_score_2[letter] # } ############################# # # people = [ # # { "name" => "Mary", "sport" => "squash", "fruit" => "blackberry" }, # # { "name" => "Lauren", "sport" => "squash", "fruit" => "orange" }, # # { "name" => "Isla", "sport" => "weightlifting", "fruit" => "banana" }, # # { "name" => "Sam", "sport" => "cycling", "fruit" => "orange" }, # # { "name" => "Govind", "sport" => "squash", "fruit" => "banana" }, # # { "name" => "Awad", "sport" => "weightlifting", "fruit" => "kiwi" }, # # { "name" => "Will", "sport" => "cycling", "fruit" => "blackberry" } # # ] # # sort_by_groups = {} # # puts "Please enter catagory: 'sport' or 'fruit'" # # input = gets.chomp # # people.each do |catagory_under_consideration| # # catagory = catagory_under_consideration["#{input}"] # # name = catagory_under_consideration["name"] # # if sort_by_groups["#{catagory}"] == nil # # sort_by_groups["#{catagory}"] = [name] # # else # # sort_by_groups["#{catagory}"].push(name) # # end # # end # # puts sort_by_groups ############################# # # sports_groups = {} # # puts "Please enter catagory: 'sport' or 'fruit'" # # catagory = gets.chomp # # if catagory == "sport" # # catagory = 1 # # elsif catagory == "fruit" # # catagory = 2 # # end # # people.each do |person| # # sport = people[catagory] # # name = people[0] # # if sports_groups[catagory] == nil # # sports_groups[catagory] = [name] # # else # # sports_groups[catagory].push(name) # # end # # end # # puts sports_groups # people = [ # { "name" => "Mary", "sport" => "squash", "fruit" => "blackberry" }, # { "name" => "Lauren", "sport" => "squash", "fruit" => "orange" }, # { "name" => "Isla", "sport" => "weightlifting", "fruit" => "banana" }, # { "name" => "Sam", "sport" => "cycling", "fruit" => "orange" }, # { "name" => "Govind", "sport" => "squash", "fruit" => "banana" }, # { "name" => "Awad", "sport" => "weightlifting", "fruit" => "kiwi" }, # { "name" => "Will", "sport" => "cycling", "fruit" => "blackberry" } # ] # sort_by_groups = {} # puts "Please enter catagory: 'sport' or 'fruit'" # input = gets.chomp # puts "Enter what value to search for" # value = gets.chomp # people.each do |catagory_under_consideration| # catagory = catagory_under_consideration["#{input}"] # name = catagory_under_consideration["name"] # if sort_by_groups["#{catagory}"] == nil # sort_by_groups["#{catagory}"] = [name] # else # sort_by_groups["#{catagory}"].push(name) # end # endsort_by_groups = {} # puts "Please enter catagory: 'sport' or 'fruit'" # input = gets.chomp # puts "Enter what value to search for" # value = gets.chomp # people.each do |catagory_under_consideration| # catagory = catagory_under_consideration["#{input}"] # name = catagory_under_consideration["name"] # if sort_by_groups["#{catagory}"] == nil # sort_by_groups["#{catagory}"] = [name] # else # sort_by_groups["#{catagory}"].push(name) # end # end # puts sort_by_groups["#{value}"] # puts sort_by_groups["#{value}"] # # puts "Enter what category to search" # # catagory = gets.chomp # # puts "Enter what value to search for" # # value = gets.chomp # # outcome = {} # # people.each do |person_of_interest| # # first = people[catagory] # # second = people[value] # # if outcome[catagory] == nil # # outcome[catagory] = [value] # # else # # outcome[catagory].push(value) # # end # # end ############################# ############################# # # players = [ # # { :name => "Sam", :sport => "tennis" }, # # { :name => "Mary", :sport => "squash" }, # # { :name => "Ed", :sport => "tennis" }, # # { :name => "Mark", :sport => "football" } # # ] # # sorted_by_sport = {} # # players.each do |player_under_consideration| # # sport = player_under_consideration[:sport] # # name = player_under_consideration[:name] # # if sorted_by_sport[sport] == nil # # sorted_by_sport[sport] = [name] # # else # # sorted_by_sport[sport].push(name) # # end # # end # # puts sorted_by_sport ############################# ############################# # # puts "bear, river,salmon" # # curse = gets.chomp # # dictionary = { # # "bear" => "a createure that fished on a river for aslmon", # # "river" => "A body of water in which salmosn and bear inhabit", # # "salmon" => "Afish from a river", # # } # # puts dictionary[curse] ############################# ############################# # ################# CHAPTER 7 # puts "How many groups would you like" # number_of_groups = gets.chomp.to_i # names = [] # while true do # puts "Please enter name" # name_of_individual = gets.chomp # if name_of_individual != "stop" # names.push(name_of_individual) # elsif name_of_individual == "stop" # split_names = names.group_by.with_index { |_, index| index % number_of_groups }.values # puts "which group do you want to look at" # choice = gets.chomp.to_i # while true # last = split_names[choice] # # chosen = last.map { |i| '""' + i.to_s + '""'}.join(", ") # puts last # break # end # break # end # end ############################# ############################# # # word_sets = [[5,7,9]["LTC","BTC","MAKA"]] # # length = number_sets.length # # count = 0 # # second_count = 0 # # while true # # while second_count < 1000 # # while count <= length -1 # # puts sting = ["#{word_sets[0][count]}" , "infomation about things #{word_sets[1][count]} and here is some more #{word_sets[1][count]}"] # # count+=1 # # end # # if count == length # # count = 0 # # second_count+=1 # # end # # break # # end # # end ############################# ############################# # CROCC GAME ############################# ############################# # # river = "--P--,--C--,CC-CC,CC-CC" # # count = 0 # # position = 2 # # while count <= 3 # # river_split = river.split(",") # # if river_split[count][position] == "C" # # puts "Your eaten" # # break # # else # # river_split[count][position] == "P" # # end # # puts river_split # # if count == 3 # # puts "You survived" # # break # # else # # puts "Type left,right or neither" # # move = gets.chomp # # if move == "right" # # position += 1 # # count += 1 # # elsif move == "left" # # position -= 1 # # count += 1 # # else # # position = position # # count += 1 # # end # # end # # end # ###### WORKING but i need to print --P-- first line not ----- # # river = "-----,--C--,CC-CC,CC-CC" # # count = 0 # # position = 2 # # person = "P" # # while true # # river_split = river.split(",") # # river_split[count][position] = "P" # # puts river_split # # puts "Type left,right or neither" # # move = gets.chomp # # if move == "right" # # position += 1 # # count += 1 # # elsif move == "left" # # position -= 1 # # count += 1 # # else # # count +=1 # # end # # if river_split[count][position] == "C" # # puts "Your eaten" # # break # # end # # if count == 3 # # puts "You survived" # # break # # end # # end # # printable = river_4.split(",") # # puts printable # # split_river = river_4[1] # # puts split_river ############################# ############################# #### WORKING # puts "How many groups would you like" # number_of_groups = gets.chomp.to_i # names = [] # while true do # puts "Please enter name" # name_of_individual = gets.chomp # if name_of_individual != "stop" # names.push(name_of_individual) # elsif name_of_individual == "stop" # split_names = names.group_by.with_index { |_,index| index % number_of_groups }.values # break # end # end # while true do # puts "which group do you want to look at" # choice = gets.chomp # choice_num = choice.to_i - 1 # if choice == "stop" # break # end # if names.length > 0 # last = split_names[choice_num].join(", ") # puts last # else # puts split_names[choice_num] # end # end # # puts "How many groups would you like" # # number_of_groups = gets.chomp.to_i # # names = [] # # while true do # # puts "Please enter name" # # name_of_individual = gets.chomp # # if name_of_individual != "stop" # # names.push(name_of_individual) # # elsif name_of_individual == "stop" # # split_names = names.group_by.with_index { |_, index| index % number_of_groups }.values # # while true do # # puts "which group do you want to look at" # # choice = gets.chomp # # choice_num = choice.to_i - 1 # # if choice == "stop" # # exit # # end # # if names.length > 0 # # last = split_names[choice_num].join(", ") # # puts last # # else # # puts split_names[choice_num] # # end # # end # # end # # end # # chosen = last.map { |i| '""' + i.to_s + '""'}.join(", ") # ######## WORKING ON ONE PASS OVER NOT MULTIPLE # # puts "How many groups would you like" # # number_of_groups = gets.chomp.to_i # # names = [] # # while true do # # puts "Please enter name" # # name_of_individual = gets.chomp # # if name_of_individual != "stop" # # names.push(name_of_individual) # # elsif name_of_individual == "stop" # # break # # split_names = names.group_by.with_index { |_, index| index % number_of_groups }.values # # end # # end # # while true do # # puts "which group do you want to look at" # # choice = gets.chomp # # choice_num = choice.to_i - 1 # # if choice == "stop" # # break # # end # # if names.length > 0 # # last = split_names[choice_num].join(", ") # # puts last # # else # # puts split_names[choice_num] # # end # # end # # puts "How many groups would you like" # # number_of_groups = gets.chomp.to_i # # names = [] # # while true do # # puts "Please enter name" # # name_of_individual = gets.chomp # # if name_of_individual != "stop" # # names.push(name_of_individual) # # elsif name_of_individual == "stop" # # split_names = names.group_by.with_index { |_, index| index % number_of_groups }.values # # while true do # # puts "which group do you want to look at" # # choice = gets.chomp # # choice_num = choice.to_i - 1 # # if choice == "stop" # # exit # # end # # if names.length > 0 # # last = split_names[choice_num].join(", ") # # puts last # # else # # puts split_names[choice_num] # # end # # end # # end # # end ############################# ############################# # # while true do # # puts "Please enter name" # # name_of_individual = gets.chomp # # if name_of_individual != "stop" # # names.push(name_of_individual) # # elsif name_of_individual == "stop" # # split_names = names.group_by.with_index {|_,index| index % number_of_groups}.values # # puts "which group do you want to look at" # # while choice = gets.chomp.to_i # # print split_names[choice] # # break # # end # # break # # end # # end ############################# ############################# # # puts "How many groups would you like" # # number_of_groups = gets.chomp.to_i # # index_group = Hash.new() # # 1.upto(num).each do |i| # # i = Hash.new(0) # # end # # while true do # # puts "Enter name" # # name_of_individual = gets.chomp # # if name_of_individual != "stop" # # i.push(name_of_individual) # # elsif name_of_individual == "stop" # # break # # end # # end # # #make list of k,p with k == 1.upto(num) # # # gropes = Hash.new { |key| num[]} ############################# ############################# # # puts "How many groups would you like" # # number_of_groups = gets.chomp.to_i # # names = [] # # while true do # # puts "Please enter name" # # name_of_individual = gets.chomp # # if name_of_individual != "stop" # # names.push(name_of_individual) # # elsif name_of_individual == "stop" # # puts "which groupe do you want to see" # # choice = gets.chomp.to_i # # break # # end # # end # # puts names # # group_num = number_of_groups -1 # # grouping = (0..group_num) # # split_group = names.slice_when {grouping.next == group_num} # # puts choice # # puts split_group[choice] # # puts "How many groups would you like" # # number_of_groups = gets.chomp.to_i # # index_group = Hash.new() # # 1.upto(number_of_groups).each do |i| # # i = Hash.new(0) # # end # # while true do # # puts "Enter name" # # name_of_individual = gets.chomp # # if name_of_individual != "stop" # # i.push(name_of_individual) # # elsif name_of_individual == "stop" # # break # # end # # end # # puts "How many groups do you want to make" # # number_of_groups = gets.chomp.to_i # # index_groups = Array.new(number_of_groups) {Array.new} # # names = [] # # puts index_groups # # while true do # # puts "Enter name" # # nam = gets.chomp # # if nam == "stop" # # break # # end # # end # # names.delete("stop") # # current_index = 0 # # while names.length > 0 # # if current_index == number_of_groups # # current_index = 0 # # else # # names_to_push = names[0] # # name_to_push[current_index].push(name_to_push) # # names.delete_at(0) # # end # # end # # puts names # # puts index_groups # # puts "How many groups would you like" # # num = gets.chomp.to_i # # array = Array.new(group_num) {[]} # # puts "Give me a name" # # count = 0 # # while input_name = gets.chomp # # if input_name == "stop" # # puts "which group woudl yu like to see" # # choice = gets.chomp.to_i # # else puts "give me a name" # # a = [1.upto(num)] # # puts a # # groupes = Hash.new # # #groupes[num] = name # # count = 0 # # names = [] # # groupes = {} # # while true # # puts "names please" # # nam = gets.chomp # # if nam != "stop" # # names.push(nam) # # elsif nam == "stop" # # puts names # # break # # end # # end # # while true # # puts "Please enter name" # # nam = gets.chomp # # if nam != "stop" # # names.push(nam) # # elsif nam == "stop" # # while count <= num # # names.push(nam) # # count += 1 # # if count == num # # names.push(nam) # # count = 0 # # end # # elsif nam == "stop" # # puts "Which group would you like to see?" # # choice = gets.chomp.to_i # # puts names[choice] # #make list of k,p with k == 1.upto(num) # # gropes = Hash.new { |key| num[]} ############################# ############################# # # total = num # # count = 1 # # while play == true # # puts "please enter names one at a time, when finished type 'stop'" # # name_s = gets.chomp # # if name_1 != "stop" # # #add to has key = count value = name # # h = Hash.new { |hash, key| hash[key] = "#{key}: Names" } # # # h["c"] #=> "Go Fish: c" # # # h["c"].upcase! #=> "GO FISH: C" # # # h["d"] #=> "Go Fish: d" # # puts h.keys #=> ["c", "d"] # # while input = gets.chomp # # if input == "stop" # # puts names # ############# # # puts "How many groups would you like" # # num = gets.chomp.to_i # # groupes = Array.new(num) {Hash.new} # # while true # # puts "Please enter names" # # name_1 = gets.chomp # # if name_1 != "stop" # # groupes[num].push(name_1) # # elsif name_1 == "stop" # # 1.upto(num).each do |i| # # i = Hash.new(0) # # puts i # # end # # puts # # # total = group_num # # # count = 1 # # # #create hash of array with key as number # # # while true # # # puts "Please enter names one at a time" # # # name_1 = gets.chomp # # # if name != "stop" # # # Hash[count].push(name_1) # # #add to hash groupes = {number => name} # # # count += 1 # # # if count == group_num # # # count = 1 # # # end # # # end # # # end # # s = [['hey','you'][1,2]] # # s.each {|sub_array| # # sub_array.each{|y| puts y} # # } ############################# ############################# # # puts "How many groups would you like" # # group_num = gets.chomp.to_i # # total = group_num # # puts "Please enter list of names" # # group_nums = Hash.new(0) # #puts group_num.is_a? Integer # # group_num.each do |item| # # #create hash list with group num as key (value will be names) # # "group" # # in (1..group_num) # # group_num.times ############################# ############################# # # while playe == true # # puts "Please enter names for the groups" # # names = gets.chomp.split(",") # # if names == "stop" # # array_num = 1 # # names.each do |item| # # array_num+"num"(list of arrays).push(item) # # array_num += 1 # # if array_num == total # # array_num = 1 # # end # # end # # class Group_divide # # puts "Number of groups" # # number = gets.chomp.to_i # # def initialize(number, names) # # @number = number # # @names = names # # end # # def ############################# ############################# # #### Working graph generator # # puts "Please enter list of numbers with ',' between" # # numbers = gets.chomp # # split_num = numbers.split(",").join(" ") # # new_num = split_num.split(" ").map{|item| item.to_i} # # print numbers # # new_num.each do |item| # # puts "-"*item # # end ############################# ############################# # # numbers.split(",") # # num_array = Array.new # # numbers.map do |num| # # num.to_i # # end # # puts numbers # # list_1 = numbers.split(",") # # list_1.each do |item| # # num_array.push item # # end # # puts numbers # # puts numbers # # list_1.each do |num| # # puts num # # end # # list.each do |num| # # puts "-"*num # # end # ##### WORKING AND PAS TEST # # place = "hall" # # while true do # # if place == "hall" # # input_1 = gets.chomp # # if input_1.downcase == "look" # # puts "You are standing in a hall with a marble floor. You see a door." # # input_5 = gets.chomp # # if input_5 == "north" # # place = "studio" # # elsif input_5 == "quit" # # puts "Bye!" # # break # # end # # elsif input_1.downcase == "north" # # place = "studio" # # elsif input_1.downcase == "quit" # # puts "Bye!" # # break # # end # # elsif place == "studio" # # input_2 = gets.chomp # # if input_2.downcase == "look" # # puts "You are in a warm and cosy study. You see a safe. You see a desk." # # input_3 = gets.chomp # # if input_3.downcase == "look at desk" # # puts "You see a piece of paper that reads, The combination is 2451." # # input_4 = gets.chomp # # if input_4.downcase == "enter combination 2451" # # puts "You see some diamonds in the safe, pick them up and make your escape" # # break # # elsif input_4.downcase == "south" # # place == "hall" # # elsif input_4.downcase == "quit" # # puts "Bye!" # # break # # end # # elsif input_3.downcase == "south" # # place = "hall" # # elsif input_3.downcase == "quit" # # puts "Bye!" # # break # # end # # elsif input_2 == "look at desk" # # puts "You see a piece of paper that reads, The combination is 2451." # # input_6 = gets.chomp # # if input_6 == "enter combination 2451" # # puts "You see some diamonds in the safe, pick them up and make your escape" # # break # # elsif input_6 == 'quit' # # puts "Bye!" # # break # # end # # elsif input_2.downcase == "south" # # place = "hall" # # elsif input_2.downcase == "enter combination 2451" # # puts "You see some diamonds in the safe, pick them up and make your escape" # # break # # elsif input_2.downcase == "quit" # # puts "Bye!" # # break # # end # # end # # end ############################# ############################# # # ###### WORKING place = "hall" # # place = "hall" # # puts "type quit any time to leave" # # puts "commands prompted are in '__' " # # while true do # # if place == "hall" # # puts "You are in the Hall, What would you like to do? 'look' or 'north' or 'quit'?" # # input_1 = gets.chomp # # if input_1.downcase == "look" # # puts "You are standing in a hall with a marble floor. You see a door." # # puts "Now would oyu like to move 'north' or 'quit'" # # input_5 = gets.chomp # # if input_5 == "north" # # place = "studio" # # elsif input_5 == "quit" # # puts "Bye!" # # break # # end # # elsif input_1.downcase == "north" # # place = "studio" # # elsif input_1.downcase == "quit" # # puts "Bye!" # # break # # end # # elsif place == "studio" # # puts "You are now in the study. What would you like to do? 'Look' or 'south'?" # # input_2 = gets.chomp # # if input_2.downcase == "look" # # puts "You are in a warm and cosy study. You see a safe. You see a desk.\n" # # puts "What would you like to do? 'look at desk' or 'south'" # # input_3 = gets.chomp # # if input_3.downcase == "look at desk" # # puts "You see a piece of paper that reads, The combination is 2451" # # puts "would you like to 'enter combination 2451' or move 'south' or 'quit\n'" # # input_4 = gets.chomp # # if input_4.downcase == "enter combination 2451" # # puts "You see some diamonds in the safe, pick them up and make your escape" # # break # # elsif input_4.downcase == "south" # # place == "hall" # # elsif input_4.downcase == "quit" # # puts "Bye!" # # break # # end # # elsif input_3.downcase == "south" # # place = "hall" # # elsif input_3.downcase == "quit" # # puts "Bye!" # # break # # end # # elsif input_2.downcase == "south" # # place = "hall" # # elsif input_2.downcase == "enter combination 2451" # # puts "You see some diamonds in the safe, pick them up and make your escape" # # break # # elsif input_2.downcase == "quit" # # puts "Bye!" # # break # # end # # end # # end ############################# ############################# # #### WORKING AND PASSING TEST # # place = "passage" # # while true # # puts "please enter 'north' or 'south'" # # input_1 = gets.chomp # # if place == "passage" # # if input_1 == "north" # # place = "cave" # # else # # break # # end # # elsif place == "cave" # # puts "You are in a scary cave." # # if input_1 == "south" # # puts "You are in a scary passage." # # place = "passage" # # elsif input_1 == "north" # # puts "You walk into sunlight" # # break # # end # # end # # end ############################# ############################# # # #### Working passage/cave game # # place = "passage" # # while true # # puts "please enter north or south" # # input_1 = gets.chomp # # # player is in passage # # if place == "passage" # # if input_1 == "north" # # puts "You are in a scary cave." # # place = "cave" # # else # or elfis input == "soutn" > do something # # break # # end # # elsif place == "cave" # # if input_1 == "south" # # puts "You are in a scary passage." # # place = "passage" # # elsif input_1 == "north" # # puts "You walk into sunlight" # # break # # end # # end # # end ############################# ############################# # #### WORKING COUNTING ADD GAME # # total = 0 # # while true do # # puts "Give me a number" # # input_1 = gets.chomp # # if input_1 != "stop" # # total = input_1.to_i + total # # elsif input_1 == "stop" # # puts total # # break # # end # # end # # total = 0 ############################# ############################# # # while play == true # # puts "Give me a number" # # first_input = gets.chomp # # if first_input.to_i == Integer # # total = first_input.to_i + total # # elsif first_input == "stop" # != Inriger / first_input.downcase # # puts total # # play = false # # end # # end # # puts total # # while input = gets.chop.to_i # # if input == "stop" # # puts total ############################## ############################# # # puts "Please choose from Rock, paper or scissors" # # play = true # # while play == true # # puts "Player 1 choose first from 'rock', 'paper' or 'scissors'" # # player_1 = gets.chomp # # puts "Player 2 please choose first from 'rock', 'paper' or 'scissors'" # # player_2 = gets.chomp # # if player_1 == player_2 # # puts "It's a draw" # # elsif player_1 == "rock" and player_2 == "scissors" # # puts "Player 1 wins" # # elsif player_1 == "scissors" and player_2 == "paper" # # puts "Player 1 wins" # # elsif player_1 == "paper" and player_2 == "rock" # # puts "Player 1 wins" # # else # # puts "Player 2 wins" # # play = false # # break # # end # # end # #### ROCK PAPER Scisors # # puts "Please choose from Rock, paper or scissors" # # play = true # # while play == true # # puts "Player 1 choose first" # # player_1 = gets.chomp # # puts "Player 2 please choose" # # player_2 = gets.chomp # # # turn player input into number. relative numbers compete # # if player_1 == player_2 # # puts "It's a draw" # # elsif player_1 == "rock" and player_2 == "scissors" # # puts "Player 1 wins" # # elsif player_1 == "scissors" and player_2 == "paper" # # puts "Player 1 wins" # # elsif player_1 == "paper" and player_2 == "rock" # # puts "Player 1 wins" # # else # # puts "Player 2 wins" # # play = false # # end # # end # # # rock1 > scissors2 # # # scissors2 > paper3 # # # paper3 > rock1 # # # input == input ############################# ############################# # ### D&D GAME WITH RANDOM CHOICE # # puts "Hello Player, Welcome to the Dungeon game" # # puts "You will have the option to move your charecter" # # puts "either Right, Forward or Left" # # puts "Once you make two move sucsessfully you'll WIN" # # puts "You start facing forward" # # puts " " # # puts "Please enter you first move" # # move = gets.chomp # # count = 0 # # play_again = true # # moves = { # # 1 => "You got eaten! by a Goblin!", # # 2 => "A Werewolf got you!", # # 3 => "You made it to the next, now what?" # # } # # while play_again == true # # if count == 0 # # move = rand(1..3) # # if move == 1 # # puts moves[1] # # elsif move == 2 # # puts moves[2] # # elsif move == 3 # # puts moves[3] # # move_2 = gets.chomp # # end # # end # # if count == 1 # # if move_2 == 1 # # puts moves[1] # # elsif move_2 == 2 # # puts moves[2] # # elsif move_2 == 3 # # puts moves[3] # # move_3 = gets.chomp # # end # # end # # if count == 1 # # if move_3 == 1 # # puts moves[1] # # elsif move_3 == 2 # # puts moves[2] # # elsif move_3 == 3 # # puts "YOU MADE IT!!!!" # # end # # end # # puts "Woudl you like to play again? yes/no" # # choice = gets.chomp # # if choice.downcase == "yes" # # puts "Make your move" # # move = gets.chomp # # count = 0 # # elsif choice.downcase == "no" # # play_again = false # # end # # end ############################# ############################# # ## working D&D game # # puts "Hello Player, Welcome to the Dungeon game" # # puts "You will have the option to move your charecter" # # puts "either Right, Forward or Left" # # puts "Once you make two move sucsessfully you'll WIN" # # puts "You start facing forward" # # puts " " # # puts "Please enter you first move" # # move = gets.chomp # # play_again = true # # while play_again == true do # # if move.downcase == "right" # # puts "You got eaten! by a Werewolf!" # # break # # elsif move.downcase == "left" # # puts "Your eaten! By a Goblin!" # # break # # elsif move.downcase == "forward" # # puts "Well you made it of the mark! Where next?" # # move_2 = gets.chomp # # end # # if move_2.downcase == "right" # # puts "You got eaten! by a Werewolf!" # # break # # elsif move_2.downcase == "left" # # puts "Your eaten! By a Goblin!" # # break # # elsif move_2.downcase == "forward" # # puts "YOU MADE IT!!!!" # # end # # puts "Woudl you like to play again? yes/no" # # choice = gets.chomp # # if choice.downcase == "yes" # # puts "Make your move" # # move = gets.chomp # # elsif choice.downcase == "no" # # play_again = false # # end # # end ############################# ############################# # ### Wroking D&D game # # puts "Hello Player, Welcome to the Dungeon game" # # puts "You will have the option to move your charecter" # # puts "either Right, Forward or Left" # # puts "Once you make two move sucsessfully you'll WIN" # # puts "You start facing forward" # # puts " " # # puts "Please enter you first move" # # move = gets.chomp # # count = 0 # # play = true # # if count == 0 # # if move.downcase == "right" # # puts "You got eaten! by a Werewolf!" # # break # # elsif move.downcase == "left" # # puts "Your eaten! By a Goblin!" # # break # # elsif move.downcase == "forward" # # puts "Well you made it of the mark! Where next?" # # move_2 = gets.chomp # # count +=1 # # end # # end # # if count == 1 # # if move_2.downcase == "right" # # puts "You got eaten! by a Werewolf!" # # break # # elsif move_2.downcase == "left" # # puts "Your eaten! By a Goblin!" # # break # # elsif move_2.downcase == "forward" # # puts "YOU MADE IT!!!!" # # count += 1 # # end # # end # # if count == 2 # # puts "Woudl you like to play again? yes/no" # # play_again = gets.chomp # # if play_again.downcase == "yes" # # count = 0 # # else # # break # # end # # end ############################# ############################# # ## working # # puts "Hello Player, Welcome to the Dungeon game" # # puts "You will have the option to move your charecter" # # puts "either Right, Forward or Left" # # puts "Once you make two move sucsessfully you'll WIN" # # puts "You start facing forward" # # puts " " # # puts "Please enter you first move" # # move = gets.chomp # # play = true # # while play == true do # # if move.downcase == "right" # # puts "You got eaten! by a Werewolf!" # # break # # elsif move.downcase == "left" # # puts "Your eaten! By a Goblin!" # # break # # elsif move.downcase == "forward" # # puts "Well you made it of the mark! Where next?" # # move_2 = gets.chomp # # end # # if move_2.downcase == "right" # # puts "You got eaten! by a Werewolf!" # # break # # elsif move_2.downcase == "left" # # puts "Your eaten! By a Goblin!" # # break # # elsif move_2.downcase == "forward" # # puts "YOU MADE IT!!!!" # # break # # end # # end # # while count < 3 # # if move.downcase == "left" # # puts "You got eaten! by a Werewolf!" # # break # # elsif move.downcase == "right" # # puts "Your eaten! By a Goblin!" # # break # # elsif move.downcase == "forward" # # count += 1 # # puts "WOW you survived, Now which direction" # # end # # if count == 3 # # puts "YOU WIN!!!!!! and wernt eaten!" # # puts "would you like to start again? yes/no" # # play_again = gets.chomp # # if play_again.downcase == "yes" # # count == 0 # # elsif play_again.downcase == "No" # # puts "Thanks for playing" # # break # # end # # end # # end ############################# ############################# # # puts String.new("Welcome user") # # user = gets.chomp # # puts String.new("Hi " + user) # # if user.chr == String.new("S") # # puts user.upcase # # else # # puts String.new("Hi " + user) # # end # # puts "Please enter your name" # # user_name = gets.chomp.capitalize # # if user_name[0] == "S" # # puts user_name.upcase # # elsif user_name[0] != "S" # # puts "Hi #{user_name}" # # end # # puts "Enter user name" # # user = gets.chomp # # return user.upcase if user.chr == "S" # # return "Hi #{user}" # # todo_1 = String.new("Wash the dog") # # puts todo_1.capitalize # # one_string = String.new(1) # # two_string = String.new(6) # # puts one_string + two_string # # if false # # if nil # # return 0 # # end # # else # # if 0 # # return 0 # # end # # end # # count = 0 # # play = true # # while count < 20 do # # if count %3==0 # # puts count # # puts "Fizz" # # count += 1 # # elsif count %5==0 # # puts "Buzz" # # count += 1 # # end # # end # # while play == true do # # if count %3 == 0 # # puts "Fizz" # # count += 1 # # elsif count %5 == 0 # # puts "Buzz" # # count += 1 # # elsif count %5==0 && count %3==0 # # puts "FizzBuzz" # # count += 1 # # elsif count %3!=0 && count %5!=0 # # puts count # # elsif count == 20 # # play = false # # break # # end # # end # # sum = 0 # # count = 1 # # for num in 1..250 # # num + # # count +=1 # # end # # puts sum # # count = 1 # # sum = 1 # # while count <= 250 # # sum + count = sum # # count +=1 # # if count == 250 # # break # # end # # puts sum # # end # # puts sum # # sum = 0 # # for num in 1..250 # # x = num # # puts sum + x # # sum = x # # end # # puts sum # # count = 0 # # total = [] # # n = 0 # # sum = 0 # # while n <= 250 # # sum += n # # n += 1 # # end # # puts sum # # while count < 250 # # if count != 250 # # count + 1 # # total + count = total # # elsif count == 250 # # break # # end # # puts total # # end # # puts total # # while true do # # count +=1 # # puts count # # if count == 250 # # break # # end # # end # # count = 0 # # total = 0 # # for i in 1...250 # # i + total = total # # puts total # # end # # count = 1 # # total = 1 # # while count < 251 # # puts count # # # total + count = total # # count += 1 # # each in count # # i + total = total # # end # # end # # puts total # # total = 0 # # count = 0 # # loop do # # count +=1 # # count + total = total # # puts total # # break if count > 250 # # end # # puts total # # count = 0 # # total = 0 # # while true do # # puts total # # puts count # # if count < 250 # # total + count = total # # count += 1 # # elsif count > 250 # # puts total # # break # # end # # end # # count = 0 # # first_num = 0 # # second_num = 1 # # while count < 20 # # if count == 0 # # puts 0 # # count +=1 # # elsif count == 1 # # c = a + b # # if (c % 2 != 0) # # sum = sum + c # # end # # b = a # # a = c # # puts sum # # end #### COUNTING fibs # # while count < 20 # # if count < 2 # # puts count # # elsif count >= 2 # # puts fibs + num2 # # num1 = fibs # # num2 = num1 # # end # # count +=1 # # end # # count = 0 # # number = 0 # # while count <= 20 # # count += 1 # # number + count = number # # if count == 20 # # break # # end # # puts number # # end # # while count < 20 # # number + count = number # # for i in 1..20 # # puts i + i[+1] # # end
true
28a28ea8aca0796a7e4fea538cabe7d59f61d091
Ruby
MatzFan/bookmarks
/spec/features/adding_links_spec.rb
UTF-8
1,295
2.5625
3
[]
no_license
require 'spec_helper' feature 'User adds a new link' do scenario "from the homepage using an ajax form", :js => true do visit '/' click_link "New link" add_link("http://www.example.com/", "Example") expect(page).to have_content('Example') expect(current_path).to eq('/') # we're still on the frontpage end scenario 'without tags', :js => true do expect(Link.count).to eq(0) visit ('/') click_link 'New link' # needed to render the Ajax form add_link('http://www.makersacademy.com', "Maker's Academy") expect(Link.count). to eq(1) link = Link.first expect(link.url).to eq('http://www.makersacademy.com') expect(link.title).to eq("Maker's Academy") end scenario 'with a few tags' do visit '/' click_link 'New link' # needed to render the Ajax form add_link('http://makersacademy.com', "Maker's Academy", ['education', 'ruby']) link = Link.first expect(link.tags.map(&:text)).to include('education') expect(link.tags.map(&:text)).to include('ruby') end def add_link(url, title, tags = []) # optimal tags parameter fill_in 'url', with: url fill_in 'title', with: title # tags will be space-separated fill_in 'tags', with: tags.join(' ') click_button 'Add link' end end # of feature
true
940886c494ed6a2077c735be0405958129a6a288
Ruby
vigneshjb/youtour
/lib/tasks/sample_data.rake
UTF-8
1,456
2.53125
3
[]
no_license
require 'faker' namespace :db do desc "Fill database with sample data" task :populate => :environment do Rake::Task['db:reset'].invoke make_users make_tours make_trips end end def make_users User.create!(:username => "sample@youtour.com", :password => "test", :password_confirmation => "test") 99.times do email = Faker::Internet.email name = Faker::Name.name password = "abcd" User.create!(:username => email, :password => password, :password_confirmation => password, :name => name) end end def make_tours User.all(:limit => 10).each do |user| 10.times do |n| user_id = user.id from = Faker::Address.city to = Faker::Address.city des = Faker::Lorem.sentence(6) date = Faker::Base.regexify('/^(20[0-9]{2})-([1-9]{1}|1[0-2]{1})-([1-9]{1}|[1-2]{1}[0-9]{1})$/') user.tours.create!(:user_id => user.id, :from_loc => from, :to_loc => to, :doj => date, :desp => des) end end end def make_trips Tour.all(:limit => 50).each do |tour| 10.times do |n| num = Faker::Base.regexify('/^([1-9]{1}|[1-9]{1}[0-9]{1}|100)$/') p "from here" p num if num == tour.user_id num=num+1 end stat = Faker::Base.regexify('/^[0-1]{1}$/') tour.trips.create!(:tour_id => tour.id, :request_by => num, :status => stat) end end end
true
3f18f8a34766d15c7314eef125754df059a35ba0
Ruby
audiac/tealeaf-intro
/companion_workbook/advanced/quiz1/ex3.rb
UTF-8
183
3.078125
3
[]
no_license
# ex3.rb puts "A) one is: 'one'\ntwo is: 'two'\nthree is: 'three'" puts "B) one is: 'one'\ntwo is: 'two'\nthree is: 'three'" puts "C) one is: 'two'\ntwo is: 'three'\nthree is: 'one'"
true
131ee5477d25ed663e03d2525900ca9d19e5d118
Ruby
engineyard/rails_dev_directory
/vendor/rails/activesupport/lib/active_support/core_ext/array/wrapper.rb
UTF-8
591
2.734375
3
[ "MIT" ]
permissive
module ActiveSupport #:nodoc: module CoreExtensions #:nodoc: module Array #:nodoc: module Wrapper # Wraps the object in an Array unless it's an Array. Converts the # object to an Array using #to_ary if it implements that. def wrap(object) case object when nil [] when self object else if object.respond_to?(:to_ary) object.to_ary else [object] end end end end end end end
true
3d74c9961b59792c626dd59516c7950fa026cc71
Ruby
matthew-puku/ruby-challenges
/tests/16_palindrome_test.rb
UTF-8
240
2.8125
3
[]
no_license
# Add tests to me :D require 'test/unit' require_relative '../16_palindrome' class PalindromeTest < Test::Unit::TestCase def test_palidrome assert_true(palindrome("racecar")) assert_false(palindrome("hello")) end end
true
2aab3611db375518534ecf13a9066f746ad43927
Ruby
thelornenelson/oop-math-game
/math_game.rb
UTF-8
1,520
4.0625
4
[]
no_license
require './player' class MathGame def initialize @starting_lives = 3 @players = [Player.new(@starting_lives), Player.new(@starting_lives)] @max_question_number = 20 self.start_game end def start_game current_player = 0 loop do current_player %= 2 answers = self.ask_question(current_player) if check_answer(answers) puts "That's correct! Good Work!" else @players[current_player].lives -= 1 if @players[current_player].lives.zero? puts "Incorrect! Game Over!" current_player = (current_player + 1) % 2 puts "Player #{current_player + 1} Wins with a score of #{@players[current_player].lives}/#{@starting_lives}" break else puts "Incorrect! You lose a life!" end end puts "P1: #{@players[0].lives}/#{@starting_lives} vs P2: #{@players[1].lives}/#{@starting_lives}" puts '----- NEW TURN -----' current_player += 1 end end def ask_question(player) x = 1 + Random.rand(@max_question_number) y = 1 + Random.rand(@max_question_number) p "Player #{player + 1}, what is #{x} + #{y}? " player_answer = 0 while player_answer < 1 player_answer = gets.chomp.to_i p "That's not a valid guess. What is #{x} + #{y}? " if player_answer < 1 end return { player_answer: player_answer, answer: x + y } end def check_answer(answers) answers[:player_answer] == answers[:answer] ? true : false end end
true
0a2310e574692fafe01a29c9228c057f3d0cb519
Ruby
FelixAlvarado/aA-homeworks
/W2D1/simon/lib/simon.rb
UTF-8
1,129
3.734375
4
[]
no_license
class Simon COLORS = %w(red blue green yellow) attr_accessor :sequence_length, :game_over, :seq def initialize @sequence_length = 1 @game_over = false @seq = [] end def play until @game_over take_turn end game_over_message reset_game end def take_turn show_sequence require_sequence unless @game_over round_success_message @sequence_length += 1 end end def show_sequence add_random_color end def require_sequence puts "Puts in the color sequences! Seperate each color with a space!" input = gets.chomp.downcase.split @game_over = true if @seq != input end def add_random_color @seq << COLORS.sample puts "Here is the sequences!" p @seq end def round_success_message puts "Yay! You got the sequences right!!!" end def game_over_message puts "You got the sequence wrong!!!" puts "But lets play again!!!" end def reset_game @sequence_length = 1 @game_over = false @seq = [] end end if __FILE__ == $PROGRAM_NAME a = Simon.new while a.sequence_length == 1 a.play end end
true
f14fb7fda34c6a943d74646ae428e28ac85a9877
Ruby
malorie16/OO-mini-project-dumbo-web-051418
/app/models/Allergen.rb
UTF-8
168
2.875
3
[]
no_license
class Allergen attr_reader :ingredient @@all=[] def initialize(ingredient) @ingredient=ingredient @@all << self end def self.all @@all end end
true
0bf1bc77f2bfb6dc2c7a3a5b78109b742d1e0dad
Ruby
anfinil/activity-feed
/spec/support/shared/models.rb
UTF-8
1,630
2.703125
3
[ "MIT" ]
permissive
module ActivityFeed module Backend srand(1098010932048023984029) class FakeBackend include Backend ActivityFeed::User::Collection::FORWARDED_METHODS.each do |method| self.send(:define_method, method) do |*args| puts "#{self.inspect}: method: #{method} args: #{args}" end end end end class TestUser attr_accessor :id, :username, :followers def initialize(id = nil, username = nil) self.id = id self.username = username self.followers = [] end def follow!(followee) unless followee.followers.any?{|f| f == self or f.username == self.username } followee.followers << self end MyApp::Events::FollowedUserEvent.new(actor: self, target: followee).fire! end def comment!(body, other_user) MyApp::Events::CommentedOnPostEvent.new(actor: self, target: body, owner: other_user).fire! end def inspect "#{self.class.name.gsub(/.*::/, '')}:#{username} [id=#{id}] followed_by <—— #{followers.map(&:username).map(&:to_sym).inspect}" end class << self def define_users(user_names) user_names.map do |user_name| self.new(1024 + rand(2**29), user_name.to_s) end end def user_names @user_names ||= %i(kig tom pam).freeze end def users @users ||= define_users(user_names).freeze end end end class SerializableUser < TestUser include ActivityFeed::Serializable def eql?(other) other.is_a?(self.class) && other.id == id && other.username == username end end end
true
05063e93b07f8c4b049c0a357b1e792646c82aff
Ruby
hvilloria/Hack
/semana5/dia1/tienda/tienda.rb
UTF-8
1,391
3.078125
3
[]
no_license
require 'rest-client' require 'json' class Tienda def self.parsing link=RestClient.get('https://hack-stores-api.herokuapp.com/stores/22',{:params => {token: "nXeYvnFinShXEZu8x7yRmw"}}) puts link end def modificar_nombre link=RestClient.put 'https://hack-stores-api.herokuapp.com/stores/22',{'store': {'name': 'farmanada' }, 'token': 'nXeYvnFinShXEZu8x7yRmw'} end def check_my_inventory link=RestClient.get('https://hack-stores-api.herokuapp.com/inventories',:params =>{token: "nXeYvnFinShXEZu8x7yRmw"})#{:params => {id: 7, token: "nXeYvnFinShXEZu8x7yRmw"}}) puts link end #def create_product # link=RestClient.post'https://hack-stores-api.herokuapp.com/inventories',{'inventory':{'quantity':'32','item_attributes':{'name':'atamel','description':'Dolor de cabeza','price':'25'}},'token':'nXeYvnFinShXEZu8x7yRmw'} # end def edit_product RestClient.patch 'https://hack-stores-api.herokuapp.com/inventories/7', {'inventory': {'quantity':'15','item_attributes':{'name':'Parasetamolnuevo',"description":"para todo","price":50.0}},'token':'nXeYvnFinShXEZu8x7yRmw'} end end #{"id":7,"quantity":15,"item":{"id":9,"name":"Parasetamol","description":"para todo","price":50.0}} tienda= Tienda.new Tienda.parsing #tienda.modificar_nombre tienda.check_my_inventory #tienda.edit_product #tienda.check_my_inventory #{'inventory': {'quantity':'3232','item_attributes':{'name':'algo viejo','description':'algo mas especificado','price':'434.23'}},'token':'iawsdf435rete5tt5erw'}
true
5e2b2a7572f4db22a7b547fb761df810ca879131
Ruby
emanon001/atcoder-ruby
/abc063/c/main.rb
UTF-8
394
2.734375
3
[]
no_license
N = gets.to_i S = N.times.map { gets.to_i } MAX_S = N * 100 dp = Array.new(N + 10) { Array.new(MAX_S + 10, false) } dp[0][0] = true N.times do |i| s = S[i] (0..MAX_S).each do |j| if j - s < 0 dp[i + 1][j] = dp[i][j] else dp[i + 1][j] = dp[i][j] || dp[i][j - s] end end end ans = 0 (0..MAX_S).each do |i| if i % 10 != 0 && dp[N][i] ans = i end end puts ans
true
8ddeafdd3612ce3316217c2eef630abf79bed958
Ruby
nghong/project-euler
/test/test_largest_palindrome.rb
UTF-8
410
2.828125
3
[]
no_license
require_relative "../largest_palindrome" require "minitest/autorun" class TestLargestPalindrome < Minitest::Test def test_that_9009_is_largest_palindrome_made_from_product_of_two_2digit_numbers assert_equal 9009, largest_palindrome(10, 99) end def test_that_906609_is_largest_palindrome_made_from_product_of_two_3digit_numbers assert_equal 906609, largest_palindrome(100, 999) end end
true
029eb81ad1741e106e2b00fa35e6118031140f51
Ruby
dwiesenberg/project_sinatra_dashboard
/z_solution_project_sinatra_dashboard_Chris_Bideo/lib/yaml_saver.rb
UTF-8
210
2.640625
3
[]
no_license
require 'yaml' class YAMLSaver def save(filename, object) data = object.to_yaml path = "#{File.dirname(__FILE__)}/data/#{filename}.yaml" File.open(path, 'w') do |file| file.write(data) end end end
true
a433291e1431444a5c8b06f62e12e8460d29b977
Ruby
motikan2010/NamaTube
/app/controllers/concerns/service/video_service.rb
UTF-8
2,974
2.609375
3
[]
no_license
require 'unf' module Service::VideoService extend ActiveSupport::Concern include Util::YoutubeApiUtil include Util::AnalyzeEntityUtil # ビデオの検索 def search_video(params) if params[:t] # タグ検索 tag = Tag.where(:name => params[:t]).first tag.videos elsif params[:k] # キーワード検索 Video.where('title LIKE(?)', "%#{params[:k]}%") end end # 一覧に表示する情報 def get_first_video(video_rails) video_list_info =[] videos = Video.where(:video_rail_id => video_rails.map{|v| v.id}) videos.each{ |video| next unless video_list_info[video.video_rail_id] == nil # 最初の動画情報を格納 video_list_info[video.video_rail_id] = {:title => video.title, :thumbnail => video.thumbnail} } video_list_info end # ビデオの新規登録 def regist_video(video_ids, titles) @video_rail = VideoRail.create @video_rail.user_id = session[:user_id] @video_rail.save video_ids.each_with_index { |video_id, i| # ビデオの情報を取得 video_info = get_video_info(video_id) # 動画のサムネイル video_thumbnail_url = video_info['items'][0]['snippet']['thumbnails']['high']['url'] # 動画の再生時間 video_duration = video_info['items'][0]['contentDetails']['duration'] video_hour = (video_duration =~ /^PT([0-9]+)H/) ? video_duration.match(/^PT([0-9]+)H/)[1].to_i : 0 video_minutes = (video_duration =~ /([0-9]+)M/) ? video_duration.match(/([0-9]+)M/)[1].to_i : 0 video_second = (video_duration =~ /([0-9]+)S$/) ? video_duration.match(/([0-9]+)S$/)[1].to_i : 0 video = Video.create video.user_id = session[:user_id] video.video_rail_id = @video_rail.id video.sort = i video.youtube_id = video_id video.title = titles[i] video.thumbnail = video_thumbnail_url video.play_time = (video_hour * 3600 + video_minutes * 60 + video_second) unless video.save # 登録の失敗 false end # 動画タイトルの解析 analyzed_video_info = analyze_sentence(titles[i]) # タグの正規化 tags = [] analyzed_video_info['entities'].each { |value| UNF::Normalizer.normalize(value['name'], :nfkc).downcase.split(' ').each {|tag_name| if tag_name.size >= 3 tag = Tag.where(:name => tag_name).first if tag == nil # 存在しないタグの追加 tag = Tag.create tag.name = tag_name tag.save end tags.push(tag) end } } video.tags = tags video.save } true end # ユーザのビデオレールであるか def is_own_video_rail?(video_rail_id) p video_rail_id if VideoRail.where(:id => video_rail_id, :user_id => session[:user_id]).size > 0 true else false end end end
true
e74bdc805f2ec791a477fa310f42aee2a06ce88d
Ruby
tomekw/hash_assertions
/spec/hash_assertions/assert_required_keys_spec.rb
UTF-8
1,142
2.65625
3
[ "MIT" ]
permissive
require "spec_helper" require "hash_assertions/assert_required_keys" describe "assert_required_keys" do let(:hash) { { foo: "bar", baz: "qux" } } context "when all required keys in hash" do let(:required_keys) { [:foo, :baz] } it "passes" do expect { hash.assert_required_keys(*required_keys) }.to_not raise_error end end context "when some keys missing" do let(:required_keys) { [:foo, :baz, :bar] } it "fails" do expect do hash.assert_required_keys(*required_keys) end.to raise_error(ArgumentError, "Missing required key: bar") end end context "when using strings for required keys" do let(:required_keys) { [:foo, "baz"] } it "fails" do expect do hash.assert_required_keys(*required_keys) end.to raise_error(ArgumentError, "Missing required key: baz") end end context "when not splatting required keys array" do let(:required_keys) { [:foo, :baz] } it "fails" do expect do hash.assert_required_keys(required_keys) end.to raise_error(ArgumentError, "Missing required key: [:foo, :baz]") end end end
true
ef527c44ab683d4de67a1078bbe4b66a4f092e15
Ruby
DouglasAllen/code-Programming_Ruby_3rd_ed
/Part_IV--Ruby_Library_Reference/ch27_Built-in_Classes_and_Modules/Alphabetical_Listing/Array/Array_instance_methods/%26-i.rb
UTF-8
428
3.609375
4
[]
no_license
=begin Array#& (from ~/.rdoc) ------------------------------------------------------------------------------ ary & other_ary -> new_ary ------------------------------------------------------------------------------ Set Intersection---Returns a new array containing elements common to the two arrays, with no duplicates. [ 1, 1, 3, 5 ] & [ 1, 2, 3 ] #=> [ 1, 3 ] =end puts " #{[ 1, 1, 3, 5 ] & [ 1, 2, 3 ]}\n "
true
47f4b93a0df031d38b3ac993d27f254ae350e725
Ruby
HaChan/blog_oop
/spec/models/post_spec.rb
UTF-8
2,550
2.5625
3
[]
no_license
require "minitest/autorun" require "active_model" require_relative "../spec_helper_lite" require_relative "../../app/models/post" describe Post do subject{@post = Post.new} it "starts with blank attributes" do subject.title.must_be_nil subject.body.must_be_nil end it "supports reading and writing a title" do subject.title = "foo" subject.title.must_equal "foo" end it "supports reading and writing a post body" do subject.body = "foo" subject.body.must_equal "foo" end it "supports reading and writing a blog reference" do blog = Object.new subject.blog = blog subject.blog.must_equal blog end it "supports setting attributes in the initializer" do it = Post.new title: "mytitle", body: "mybody" it.title.must_equal "mytitle" it.body.must_equal "mybody" end it "is not valid with a blank title" do [nil, "", ""].each do |bad_title| subject.title = bad_title refute subject.valid? end end it "is valid with a non-blank title" do subject.title = "title" assert subject.valid? end describe "#publish" do before do @blog = MiniTest::Mock.new subject.title = "title" subject.blog = @blog end after do @blog.verify end it "adds the post to the blog" do @blog.expect :add_entry, nil, [subject] subject.publish end describe "given an invalid post" do before{subject.title = nil} it "wont add the post to the blog" do dont_allow(@blog).add_entry subject.publish end it "return false" do refute subject.publish end end end describe "#pubdate" do describe "before publishing" do it "is blank" do subject.pubdate.must_be_nil end end describe "after publishing" do before do @clock = stub! @now = DateTime.parse "2014-12-21T12:22" stub(@clock).now(){@now} subject.blog = stub! subject.title = "title" subject.publish @clock end it "is a datetime" do subject.pubdate.class.must_equal DateTime end it "is the current time" do subject.pubdate.must_equal @now end end end describe "#picture?" do it "is true when the post has a picture URL" do subject.image_url = "http://example.org/foo.png" assert subject.picture? end it "is false when the post has no picture URL" do subject.image_url = "" refute subject.picture? end end end
true
80f3f8973b7e1d718878e083f06d6d1bdc74893d
Ruby
v21/Sweareoke
/bad ruby/play.rb
UTF-8
1,046
2.9375
3
[]
no_license
#!/usr/bin/ruby require 'fuck' if (ARGV.length != 1) then puts "go away" exit end word = ARGV[0] puts "playing with #{word}" SDL.init(SDL::INIT_AUDIO | SDL::INIT_JOYSTICK | SDL::INIT_VIDEO) SDL::Mixer.open @fuck_sounds = [] @guitar = nil def poll_events while event = SDL::Event.poll case event when SDL::Event::JoyAxis puts "axis: #{event.axis}, #{event.value}" if (event.value != 0) then for button in @buttons do if (@guitar.button(button)) then play_sound(@fuck_sounds[@sound_button_map[button]]) end end end when SDL::Event::Quit break end end end def run_main while true do poll_events SDL.delay(33) end end if (SDL::Joystick.num == 0) then puts "no joystick" exit end @guitar = SDL::Joystick.open(0) SDL::Joystick.poll = true #info = get_json_data(word) #urls = info["items"].map{|item| item["pathogg"]} #urls.shuffle! #urls = urls[1..5] #@fuck_sounds = urls.map{|url| get_ogg(url)} @fuck_sounds = (1..5).to_a.map{|i| load_ogg("sounds/cunt#{i}.ogg")} run_main
true
c44a59b0ba35d5d8b98326b9a535e974040c0f3f
Ruby
gentoid/music_comparator
/lib/music_comparator/cli.rb
UTF-8
4,404
2.59375
3
[]
no_license
require 'thor' require 'colorize' require 'config' require 'condition' require 'corrector' require 'database' require 'files' require 'models/mp3_info' require 'parallel' module MusicComparator class Cli < Thor desc 'scan', 'Scan directory and DB for differences' def scan compute_changes output = generate_scan_output puts output unless output.empty? end desc 'remove_original_mix PATH', "Remove 'Original Mix' from music tags" method_option :jobs, aliases: '-j', default: -1, type: :numeric, banner: 'Number of threads' def remove_original_mix(path) MusicComparator::Corrector.remove_original_mix path, options end desc 'find_duplicates', 'Find duplicates' method_option :path, aliases: '-p', default: nil, type: :string, banner: 'Path to scan for duplicates, if not given path will be taken from config file' method_option :jobs, aliases: '-j', default: -1, type: :numeric, banner: 'Number of threads' def find_duplicates Mongoid.load!(File.join(File.dirname(__FILE__), '..', '..', 'mongoid.yml'), :development) parallel_options = {progress: 'Saving file info into DB'} parallel_options[:in_processes] = options[:jobs].floor if options[:jobs] >= 0 paths = options[:path] ? options[:path] : MusicComparator::Config.all_music_paths # MusicComparator::Models::MP3Info.delete_all Parallel.each(MusicComparator::Files.mp3_files(paths), parallel_options) do |filename| MusicComparator::Models::MP3Info.new(filename: filename).save end #[15] pry(main)> MusicComparator::Models::MP3Info.collection.aggregate( # [15] pry(main)* {'$group' => { '_id' => { 'a' => '$a', 't' => '$t' }, 'uniqueIds' => { '$addToSet' => '$_id' }, 'count' => { '$sum' => 1 } }}, # [15] pry(main)* { '$match' => { 'count' => { '$gte' => 2 } }}, # [15] pry(main)* { '$sort' => { 'count' => -1 }}, # [15] pry(main)* ) end private def conditions @result ||= begin result = [] (8..10).each do |rating| condition = MusicComparator::Condition.new condition .eq(:checked) .not_eq(:wordless) .rating = rating result << condition end (7..10).each do |rating| condition = MusicComparator::Condition.new condition .eq(:checked) .eq(:wordless) .rating = rating result << condition end result end end def compute_changes db = MusicComparator::Database.new conditions.each do |condition| condition.all_files, condition.to_copy, condition.to_delete = diff db.scan_for(condition), MusicComparator::Files.scan_for(condition) end end def generate_scan_output result = '' conditions.each do |condition| next unless condition.has_changes? result += "#{'['.yellow.bold} #{condition.path.green} #{']'.yellow.bold}\n" if condition.has_to_copy? condition.to_copy.each do |file_to_copy| result += "#{file_to_copy.green}\n" end end if condition.has_to_delete? condition.to_delete.each do |file_to_delete| result += file_to_delete.red if (moved_to = file_moved(file_to_delete, condition.path)) result += ' ' + '>>'.white.bold if moved_to[:exists] result += " #{ moved_to[:path].magenta } (file already exists)" else result += " #{ moved_to[:path].cyan }" end end result += "\n" end end end result end def file_moved(file, moved_from) result = nil conditions.each do |condition| next if condition.path == moved_from if condition.all_files.include?(file) result = { path: condition.path, exists: !condition.to_copy.include?(file) } break end end result end def diff(db, files) db_prepared = db.map { |row| row[:rpath].split('/')[-1] } files_prepared = files.map { |file| file.split('/')[-1] } to_delete = files_prepared - db_prepared to_copy = db_prepared - files_prepared [db_prepared, to_copy, to_delete] end end end
true
4c0518fcee83b63eac9310099a190890c67af824
Ruby
paulopatto/foot_stats
/lib/foot_stats/error_response.rb
UTF-8
1,320
2.875
3
[ "MIT" ]
permissive
module FootStats class ErrorResponse include Enumerable attr_reader :message # <b>Respect the contract with the Resource Instance and Resource Collections.</b> # This method is useful when you want to store the response in your database or # log this in your own way. # attr_reader :response def initialize(response, message) @response = response @message = message end # Compare to other Error response getting the exactly same message. # # @return [True, False] # def ==(other) @message == other.message end # The each method is here because it's useful <b>when getting the FootStats Info via polling</b>. # # @example # # championships = Championship.all # # => <# ErrorResponse message='500 Internal Server Error'> # # # When Error Response will not call #each and won't create anything. # championships.each { |championship| Championship.create(name: championship.name) } # # => [] # # @return [True, False] # def each(&block) [] end # This methods should return an empty collection for DSL purpose when Live, Narration returns Error. alias :players :each alias :goals :each alias :cards :each alias :details :each end end
true
706569104f823ff6a6d06b309d038fe6862588a6
Ruby
lisbethmarianne/ruby-project
/08_book_titles/book_titles.rb
UTF-8
274
3.40625
3
[]
no_license
class Book def title @title end def title=(name) array = name.split array.each do |word| word.capitalize! unless ["and", "or", "a", "to", "in", "the", "of", "an"].include?(word) end array[0].capitalize! @title = array.join(" ") end end
true
0b7879adfb7baf14cbf4dbca9c8eb184cd31595a
Ruby
liulikun/tsds
/spec/models/train_station_spec.rb
UTF-8
4,059
2.546875
3
[]
no_license
require 'spec_helper' describe TrainStation do it 'should do' do office = Geokit::Geocoders::GoogleGeocoder.geocode('Southern Cross Station, Melbourne VIC 3000, Australia') office = Geokit::Geocoders::GoogleGeocoder.geocode('Melbourne Central Station, Melbourne VIC 3000, Australia') p office p office.ll st = Geokit::Geocoders::GoogleGeocoder.geocode('Richmond Station, Richmond victoria') p st p st.ll distance=office.distance_from(st, :units=>:kms) p distance end it 'geocode all locations' do TrainStation::STATIONS.sort.uniq.each do |station| resp = Net::HTTP.get_response(URI.parse('http://maps.googleapis.com/maps/api/geocode/json?address=' + URI.escape(station + ' Station, VIC, Australia') + '&sensor=false')) result = JSON.parse(resp.body) found = false result['results'].each do |location| if (location['types'].include?('transit_station') || location['types'].include?('establishment')) && location['formatted_address'] =~ /^#{station}.*VIC.*Australia/ found = true puts "'#{station}' => '#{location['geometry']['location']['lat']},#{location['geometry']['location']['lng']}'," break end end puts '==========' + station unless found end end it 'loop through all stations' do address = '678 Victoria Street, Richmond VIC 3121, Australia' url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + URI.escape(address) + '&sensor=false' resp = Net::HTTP.get_response(URI.parse(url)) result = JSON.parse(resp.body) latlong = "#{result['results'][0]['geometry']['location']['lat']},#{result['results'][0]['geometry']['location']['lng']}" distance = {} TrainStation::TM.each do |station, geocode| u = "http://maps.google.com.au/maps?gl=au&output=dragdir&saddr=#{latlong}&daddr=#{geocode}" resp = Net::HTTP.get_response(URI.parse(u)) html = resp.body html =~ /.*(\(([0-9\.]+).*;(.*)\/.*\)).*/ puts "#{station} = #{$2} #{$3}" distance[station] = "#{$2} #{$3}" # {tooltipHtml:" (3.6\x26#160;km / 6 mins)",polylines:[ end distance.each do |station, d| puts "#{station} = #{d}" end end it 'calculate nearest station' do # address = '333 Collins Street, Melbourne VIC 3000 Australia' address = 'Breathtaker Rd, Mt Buller, Victoria, Australia' url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + URI.escape(address) + '&sensor=false' resp = Net::HTTP.get_response(URI.parse(url)) result = JSON.parse(resp.body) lat = result['results'][0]['geometry']['location']['lat'] long = result['results'][0]['geometry']['location']['lng'] # p "#{lat},#{long}" direct_distances = {} TrainStation::TM.each do |station, geocode| slat, slong = geocode.split(',') d = (slat.to_f - lat)**2 + (slong.to_f - long)**2 # p "#{station}=#{d}" direct_distances[station] = d # {tooltipHtml:" (3.6\x26#160;km / 6 mins)",polylines:[ end shortest_walk_distance = 9999999999 nearest_station = '' direct_distances.sort { |a, b| a[1] <=> b[1] }[0..9].each { |elem| u = "http://maps.google.com.au/maps?gl=au&dirflg=w&output=dragdir&saddr=#{lat},#{long}&daddr=#{TrainStation::TM[elem[0]]}" resp = Net::HTTP.get_response(URI.parse(u)) html = resp.body html =~ /.*(\(([0-9\.]+).*;(.*)\/.*\)).*/ candidate = "#{elem[0]} = #{$2} #{$3}" # puts candidate candidate_distance = $3.strip == 'km' ? ($2.strip.to_f * 1000).to_i : $2.strip.to_i if candidate_distance < shortest_walk_distance shortest_walk_distance = candidate_distance nearest_station = candidate end } puts nearest_station end end # #http://maps.google.com.au/maps?gl=au&output=dragdir&saddr=-37.8121912,145.0140166&daddr=-37.8239063,144.9897346 #http://maps.googleapis.com/maps/api/geocode/json?address=Flinders+Street,+Melbourne+VIC+3000,+Australia&sensor=false
true
e2c3f355cec2eef0b5537288254ee7c433d82f84
Ruby
shinosakarb/pair_programming
/20150926/kytiken_rito/draque/bin/draque.rb
UTF-8
469
2.96875
3
[]
no_license
#!/usr/bin/env ruby $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) require 'draque' monster = Monster.new('スライム') puts "#{monster.name}が現れた!" puts hero = Hero.new loop do hero.action_list.each do |action| puts "#{action[0]}. #{action[1]}" end print 'コマンドを入力してください? ' input_command = gets.to_i action = hero.action(input_command, monster) puts action[0] if action[1] == :end break end end
true
17e831ba3f1739939f2be0307262315f528ee494
Ruby
alto/aasm
/lib/aasm/base.rb
UTF-8
2,262
2.671875
3
[ "MIT" ]
permissive
module AASM class Base def initialize(clazz, options={}, &block) @clazz = clazz sm = AASM::StateMachine[@clazz] sm.config.column = options[:column].to_sym if options[:column] if options.key?(:whiny_transitions) sm.config.whiny_transitions = options[:whiny_transitions] elsif sm.config.whiny_transitions.nil? sm.config.whiny_transitions = true # this is the default, so let's cry end if options.key?(:skip_validation_on_save) sm.config.skip_validation_on_save = options[:skip_validation_on_save] elsif sm.config.skip_validation_on_save.nil? sm.config.skip_validation_on_save = false # this is the default, so don't store any new state if the model is invalid end end def initial_state AASM::StateMachine[@clazz].initial_state end def state(name, options={}) # @clazz.aasm_state(name, options) sm = AASM::StateMachine[@clazz] sm.create_state(name, @clazz, options) sm.initial_state = name if options[:initial] || !sm.initial_state @clazz.send(:define_method, "#{name.to_s}?") do aasm_current_state == name end end def event(name, options={}, &block) # @clazz.aasm_event(name, options, &block) sm = AASM::StateMachine[@clazz] unless sm.events.has_key?(name) sm.events[name] = AASM::SupportingClasses::Event.new(name, options, &block) end # an addition over standard aasm so that, before firing an event, you can ask # may_event? and get back a boolean that tells you whether the guard method # on the transition will let this happen. @clazz.send(:define_method, "may_#{name.to_s}?") do |*args| aasm_may_fire_event?(name, *args) end @clazz.send(:define_method, "#{name.to_s}!") do |*args| aasm_fire_event(name, {:persist => true}, *args) end @clazz.send(:define_method, "#{name.to_s}") do |*args| aasm_fire_event(name, {:persist => false}, *args) end end def states AASM::StateMachine[@clazz].states end def events AASM::StateMachine[@clazz].events end def states_for_select states.map { |state| state.for_select } end end end
true
ee5fb2fb1f521cc822980c8b6a69465940aa6429
Ruby
takagotch/ruby
/perfect_auth/sample_files/part3/06/list6.11.rb
UTF-8
324
2.640625
3
[]
no_license
# coding: utf-8 module IncludedModule def included_module_method :included_module_method end end class Klass include IncludedModule define_method :included_module_method, IncludedModule.instance_method(:included_module_method) end object = Klass.new object.included_module_method #=> :included_module_method
true
2a1ea6e5b6b360abe7b567634b4e6ef484ebb4c9
Ruby
gustavowt/ruby-nmap
/lib/nmap/status.rb
UTF-8
548
2.96875
3
[ "MIT" ]
permissive
module Nmap class Status # The state of a host attr_reader :state # The reason for the state attr_reader :reason # # Creates a new Status object. # # @param [Symbol] state # The state of a host. # # @param [String] reason # The reason for the state. # def initialize(state,reason) @state = state @reason = reason end # # Converts the status to a String. # # @return [String] # The state. # def to_s @state.to_s end end end
true
21efe5c02812f0c5b39c556bd678d4b8791a46ff
Ruby
Scott-Borecki/mastermind
/lib/game.rb
UTF-8
2,537
3.34375
3
[]
no_license
class Game attr_reader :guess, :guess_count, :message, :sequence, :timer def initialize(message, sequence, timer) @guess_count = 0 @guess = "" @message = message @sequence = sequence @timer = timer end def start_input @input = gets.chomp.downcase case @input when "p", "play" play when "i", "instructions" instructions when "q", "quit" quit else puts message.invalid_input self.start_input end end def quit puts message.quitter exit! end def instructions puts message.instructions puts message.lets_play start_input end def play sequence.generate timer.start puts message.heres_your_choices @guess_count = 0 game_flow end def game_flow until num_correct_position == 4 do puts message.whats_your_guess @guess = gets.chomp.downcase submit_guess end end def submit_guess case when @guess == "q", @guess == "quit" quit when @guess == "c", @guess == "cheat" cheat when @guess.length != 4 wrong_length when @guess.delete("rbgy").empty? evaluate_guess else puts message.try_again end end def cheat puts sequence.cheat_code puts message.cheater end def wrong_length if @guess.length > 4 puts message.too_long else puts message.too_short end end def evaluate_guess num_correct_total @guess_count += 1 if num_correct_position == 4 you_win else puts message.progress_report(guess_data) end end def num_correct_total colors = ['r', 'g', 'b', 'y'] guess_nums_correct = colors.map { |color| guesses.count(color) } sequence_nums_correct = colors.map { |color| sequence.secret_code.count(color) } compare_colors = guess_nums_correct.zip(sequence_nums_correct) num_correct_total = compare_colors.sum { |index| index.min } end def num_correct_position compare_positions = sequence.secret_code.zip(guesses) num_correct_position = compare_positions.count { |index| index[0] == index[1] } end def guesses @guess.split(//) end def you_win timer.end puts message.congrats(guess_data) start_input end def guess_data { guesses: guesses, guess_count: @guess_count, num_correct_total: num_correct_total, num_correct_position: num_correct_position, elapsed_minutes: timer.elapsed_minutes, elapsed_seconds: timer.elapsed_seconds, } end end
true
69b152b3a79b15db02dbcfbdc395caee67c89795
Ruby
theorygeek/yogurt
/lib/yogurt/code_generator/enum_class.rb
UTF-8
1,493
2.515625
3
[ "Apache-2.0" ]
permissive
# typed: strict # frozen_string_literal: true module Yogurt class CodeGenerator # For GraphQL enum classes class EnumClass < T::Struct extend T::Sig include Utils include DefinedClass const :name, String const :serialized_values, T::Array[String] sig {override.returns(T::Array[String])} def dependencies [] end sig {override.returns(String)} def to_ruby existing_constants = [] definitions = serialized_values.sort.map do |name| const_name = safe_constant_name(name, existing_constants) existing_constants << const_name "#{const_name} = new(#{name.inspect})" end <<~STRING class #{name} < T::Enum enums do #{indent(definitions.join("\n"), 2).strip} end end STRING end # Returns a valid Ruby constant name that doesn't conflict with the # existing constants. sig {params(desired_name: String, existing_constants: T::Array[String]).returns(String)} private def safe_constant_name(desired_name, existing_constants) desired_name = underscore(desired_name).upcase base_desired_name = desired_name escaping_level = 1 while existing_constants.include?(desired_name) escaping_level += 1 desired_name = "#{base_desired_name}#{escaping_level}" end desired_name end end end end
true
733f4239d6a3610eb0c96b2ec516b2474ab2317d
Ruby
compwron/minesweeper
/lib/game.rb
UTF-8
532
3.203125
3
[ "MIT" ]
permissive
require_relative 'board' class Game attr_reader :in_progress def initialize(board_size, bomb_count) @board = Board.new(board_size, bomb_count) @in_progress = true end def reveal(x, y) cell = @board.reveal(x, y) if cell.is_bomb? @in_progress = false @board.reveal_all elsif @board.full_and_accurate @in_progress = false end end def board @board.to_s end def flag(x, y) @board.flag(x, y) if @board.full_and_accurate @in_progress = false end end end
true
8b70860f81103ce2f85be761b8debca0d9d0dc06
Ruby
larger96/sub-strings
/sub_strings.rb
UTF-8
1,023
4.53125
5
[]
no_license
=begin Implement a method #substrings that takes a word as the first argument and then an array of valid substrings (your dictionary) as the second argument. It should return a hash listing each substring that was found in the original string and how many times it was found. Create a dictionary of substrings. Create an empty hash to store results. For each substring check if substring is in string. If substring is in string Scan string for occurences of substring Find the size of resulting scan array Store the size as a value in the empty hash Return results hash. =end def substrings(string, dictionary) results = {} string = string.downcase dictionary.each do |str| if string.include?(str) results[str] = string.scan(str).size end end puts results end dictionary = ["below","down","go","going","horn","how","howdy", "it","i","low","own","part","partner","sit"] substrings("below", dictionary) substrings("Howdy partner, sit down! How's it going?", dictionary)
true
c5432fb304adcefb894173852927569893f35409
Ruby
marco-t/onetwenys
/model/kit.rb
UTF-8
197
2.96875
3
[]
no_license
class Kit attr_accessor :cards def initialize @cards = [] end def add_card(card) @cards << card end def remove_cards cards = @cards @cards = [] cards end end
true
2aa3d4b98f59fc7f47655f9c5b1a6a385b4a9b01
Ruby
piasf/oo-tic-tac-toe-v-000
/lib/tic_tac_toe.rb
UTF-8
1,613
3.890625
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class TicTacToe def initialize(board=nil) @board= board || Array.new(9, " ") end WIN_COMBINATIONS = [ [0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2,5,8], [0,4,8], [2,4,6] ] def display_board puts " #{@board[0]} | #{@board[1]} | #{@board[2]} " puts "-----------" puts " #{@board[3]} | #{@board[4]} | #{@board[5]} " puts "-----------" puts " #{@board[6]} | #{@board[7]} | #{@board[8]} " end def move(input, token="X") @board[input.to_i-1]=token end def position_taken?(input) !(@board[input].nil? || @board[input]== " ") end def valid_move?(input) input.to_i.between?(1,9) && !position_taken?(input.to_i-1) end def turn puts "Please enter a number from 1-9" input = gets.chomp if !valid_move?(input) turn else move(input, current_player) display_board end end def turn_count turns = 0 @board.each do |index| if index == "X" || index == "O" turns +=1 end end turns end def current_player if turn_count % 2 == 0 return "X" else return "O" end end def won? WIN_COMBINATIONS.detect do |combo| @board[combo[0]] == @board[combo[1]] && @board[combo[1]] == @board[combo[2]] && position_taken?(combo[0]) end end def full? @board.all? {|place| place == "X" || place == "O"} end def draw? !won? && full? end def over? @board.all? {|x| won? || full? || draw?} end def winner if winning_combo = won? @board[winning_combo.first] end end def play while !over? turn end if won? puts "Congratulations #{winner}!" elsif draw? puts "Cats Game!" end end end
true
0e7d72c04da077acca6500774712e6c17d224b67
Ruby
mmanousos/ruby-small-problems
/small_problems/easy9/nine_grade_book.rb
UTF-8
1,916
4.65625
5
[]
no_license
=begin *assignment* Grade book Write a method that determines the mean (average) of the three scores passed to it, and returns the letter value associated with that grade. Numerical Score Letter Grade 90 <= score <= 100 'A' 80 <= score < 90 'B' 70 <= score < 80 'C' 60 <= score < 70 'D' 0 <= score < 60 'F' Tested values are all between 0 and 100. There is no need to check for negative values or values greater than 100. Examples: get_grade(95, 90, 93) == "A" get_grade(50, 50, 95) == "D" *problem* input: three integers output: letter representing the average of the three integers average = add all three values then divided by 3. check average against ranges using case statement *examples / test cases * see above *data structures* integers to string *algorithm* BEGIN declare a method that takes three integers as arguments SET avg = (arg1 + arg2 + arg3) / 3 case avg when 90..100 then 'A' when 80...90 then 'B' when 70...80 then 'C' when 60...70 then 'D' else 'F' END =end def get_grade(score1, score2, score3) avg = (score1 + score2 + score3) / 3 case avg when 90..100 then 'A' when 80...90 then 'B' when 70...80 then 'C' when 60...70 then 'D' else 'F' end end # Further exploration # How would you handle this if there was a possibility of extra credit grades # causing it to exceed 100 points? # can break out 'A' conditions into their own if statement and leave the rest of # the conditions from the case in the else conditional def get_grade(score1, score2, score3) avg = (score1 + score2 + score3) / 3 if avg >= 90 'A' else case avg when 80...90 then 'B' when 70...80 then 'C' when 60...70 then 'D' else 'F' end end end p get_grade(95, 90, 93) == 'A' p get_grade(50, 50, 95) == 'D' p get_grade(70, 70, 70) == 'C'
true
ab670e920fb32e0a8927e70634400953b2a3bcdb
Ruby
Diazware12/GIGIH_BE_Bangsa
/module7/session1/part2/circle.rb
UTF-8
157
3.3125
3
[]
no_license
class Circle attr_accessor :radius def initialize(radius) @radius = radius end def getArea Math::PI * @radius** end end
true
bd456d7c28f9d4d10e13db1002b7db8c4d19f602
Ruby
yungdai/Ruby-Fundamentals-Part-2
/arrays.rb
UTF-8
1,047
4.46875
4
[]
no_license
empty_array = [] numbers = ["one", "two", "three", "four", "five"] # 0 1 2 3 4 puts"dereferencing the value two with numbers[1] and last with numbers[4]" two = numbers[1] # dereference the value stored at index 1 last = numbers[4] puts two puts last puts "This is what happens when you << (shovel) the number six into the array" numbers << "six" # push "six" onto the end of array (shovel command) puts "This is what happens when you ask if six is numbers.included? in the array" puts numbers.include?("six") # -> true puts "What happens when you do a numbers.each?" numbers.each do |num| # num is the element inside the number array. Example: After you've set up the loop. # the loop will go through numbers.num for each element in the array puts num end puts "numbers.map {|num| num[0].upcase} takes the first value in the numbers array and uppercase it new_array will have the value of numbers[0] in uppercase" new_array = numbers.map {|num| num[0].upcase} puts new_array.each { |x| puts x }
true
6eedd92892a72ea3ad189bec0ad04fe28be21936
Ruby
clint7/Sandpit-Ninjas
/main.rb
UTF-8
2,111
2.546875
3
[]
no_license
require 'sinatra' require 'json' require 'sinatra/activerecord' class MyApp < Sinatra::Base get '/' do send_file File.join('public', '/index.html') end get '/test_api' do content_type :json { :key1 => "dope", :key2 => 'value2' }.to_json end get '/get_locs' do content_type :json locs = Location.uniq.pluck(:name) age = Age.uniq.pluck(:name) {:locations => locs, :age => age}.to_json end get '/get_locs' do content_type :json locs = Location.uniq.pluck(:name) age = Age.uniq.pluck(:name) {:locations => locs, :age => age}.to_json end post '/post_user_info' do json = JSON.parse(request.body.read) location = Location.where(name: json['loc']) age = Age.where(name: json['age']) crimes = Crime.where(gender: json['gen'], location: location, age: age) result = [] top_six = [] offs = Offence.all offs.each do |off| top_six << {id: off.id ,offence: off.face_name, long_name: off.name, total: crimes.where(offence: off).count} end top_six = top_six.take(6).sort { |x,y| y[:total] <=> x[:total] }; samples = top_six.sample(2) gen_off = samples.first puts gen_off gen_crime = Crime.where(offence_id: gen_off[:id]) puts "past" gender_pick = {offence: gen_off[:offence], offence_long_name: gen_off[:long_name], male: gen_crime.where(gender: "Male").count, female: gen_crime.where(gender: "Female").count} time_comp = samples.last puts time_comp time_crime = Crime.where(offence_id: time_comp[:id]) temp = [] Crime.uniq.pluck(:year).each do |year| temp << {year: year, total: time_crime.where(year: year).count} end temp = temp.sort { |x,y| x[:year] <=> y[:year] }; time_crime_result = {offence: time_comp[:offence], offence_long_name: time_comp[:long_name], data: temp} result = {} {:crimes => top_six, :gender => gender_pick, time_crime: time_crime_result}.to_json end # look at fixing this now # not_found do # content_type :json # halt 404, { error: 'URL not found' }.to_json # end end #end
true
448bf4daa65eafc189514fa2bd1d6e1a290fa3ee
Ruby
sand33pn/ruby-codes
/year.rb
UTF-8
1,929
3.9375
4
[]
no_license
puts "Enter first person's name :" first = gets.chomp puts "Enter second person's name :" second = gets.chomp puts "Enter #{first}'s birth year(yyyy) :" first_year = gets.chomp.to_i puts "Enter #{first}'s birth month(mm) :" first_month = gets.chomp.to_i puts "Enter #{first}'s birth day(dd) :" first_day = gets.chomp.to_i puts "Enter #{second}'s birth year(yyyy) :" second_year = gets.chomp.to_i puts "Enter #{second}'s birth month(mm) :" second_month = gets.chomp.to_i puts "Enter #{second}'s birth day(dd) :" second_day = gets.chomp.to_i first_birthdate = Time.mktime(first_year, first_month, first_day) second_birthdate = Time.mktime(second_year, second_month, second_day) year,month,day = 0 year = (first_year - second_year).abs if year == 0 #then do nothing elsif first_birthdate < second_birthdate if first_month > second_month year-=1 end elsif first_birthdate > second_birthdate if first_month < second_month year-=1 end end if first_birthdate < second_birthdate if first_month > second_month month = second_month - first_month + 12 else month = second_month - first_month end elsif first_birthdate > second_birthdate if first_month < second_month month = first_month - second_month + 12 else month = first_month - second_month end end if month == 0 #then do nothing elsif first_birthdate < second_birthdate if first_day > second_day month-=1 end elsif first_birthdate > second_birthdate if first_day < second_day month-=1 end end if first_birthdate < second_birthdate day = (second_birthdate - Time.mktime(first_year+year+(first_month+month)%12, (first_month+month)/12,first_day)).to_i/3600/24 elsif second_birthdate < first_birthdate day = (first_birthdate - Time.mktime(second_year+year+(second_month+month)%12, (second_month+month)/12,second_day)).to_i/3600/24 end puts puts puts "#{first} and #{second} were born #{year} years #{month} months and #{day} days apart..!"
true
7aba229df8e858a08eb78b0ced35dfa5060e9838
Ruby
onisan/ruby-tutor
/coding-test-2/practice-problems/lib/03_ordered_vowels.rb
UTF-8
560
3.515625
4
[]
no_license
def ordered_vowel_words(str) ord = str.split(' ') bad = [] ord.each {|s| tmp = "" tmp.concat(s) bad.push(s) unless ordered_vowel_word?tmp } bad.each {|b| ord.delete(b) } return ord.join(" ").chomp #if ordered_vowel_word?str end def ordered_vowel_word?(word) chars = [] while(word.slice(/[aeiou]/)) chars.push(word.slice!(/[aeiou]/)) end return true if chars.length == 1 chars.each_with_index{|c, i| if i == 0 return false if c > chars[i+1] else return false if c < chars[i-1] end } true end
true
c9e6aa80e5b044762c898b0e732200c624b34f5a
Ruby
activescaffold/active_scaffold
/lib/active_scaffold/data_structures/columns.rb
UTF-8
3,517
2.875
3
[ "MIT" ]
permissive
module ActiveScaffold::DataStructures class Columns include Enumerable include ActiveScaffold::Configurable # The motivation for this collection is that this Columns data structure fills two roles: it provides # the master list of all known columns, and it provides an inheritable list for all other actions (e.g. # Create and Update and List). Well we actually want to *know* about as many columns as possible, so # we don't want people actually removing columns from @set. But at the same time, we want to be able to # manage which columns get inherited. Tada! # # This collection is referenced by other parts of ActiveScaffold and by methods within this DataStructure. # IT IS NOT MEANT FOR PUBLIC USE (but if you know what you're doing, go ahead) def _inheritable=(value) @sorted = true @_inheritable = value end # This accessor is used by ActionColumns to create new Column objects without adding them to this set attr_reader :active_record_class def initialize(active_record_class, *args) @active_record_class = active_record_class @_inheritable = [] @set = [] @sorted = nil add(*args) end # the way to add columns to the set. this is primarily useful for virtual columns. # note that this also makes columns inheritable def add(*args) args.flatten! # allow [] as a param args = args.collect(&:to_sym) # make the columns inheritable @_inheritable.concat(args) # then add columns to @set (unless they already exist) args.each { |a| @set << ActiveScaffold::DataStructures::Column.new(a.to_sym, @active_record_class) unless find_by_name(a) } end alias << add # add columns from association (belongs_to or has_one) # these columns will use label translation from association model # they will be excluded, so won't be included in action columns # association columns will work for read actions only, not in form actions (create, update, subform) def add_association_columns(association, *columns) column = self[association] raise ArgumentError, "unknown column #{association}" if column.nil? raise ArgumentError, "column #{association} is not an association" if column.association.nil? raise ArgumentError, "column #{association} is not singular association" unless column.association.singular? raise ArgumentError, "column #{association} is polymorphic association" if column.association.polymorphic? klass = column.association.klass columns.each do |col| next if find_by_name col @set << ActiveScaffold::DataStructures::Column.new(col, klass, column.association) end end def exclude(*args) # only remove columns from _inheritable. we never want to completely forget about a column. args.each { |a| @_inheritable.delete a.to_sym } end # returns an array of columns with the provided names def find_by_names(*names) @set.find_all { |column| names.include? column.name } end # returns the column of the given name. def find_by_name(name) # this works because of `def column.==' column = @set.find { |c| c == name } column end alias [] find_by_name def each @set.each { |i| yield i } end def _inheritable if @sorted @_inheritable else @_inheritable.sort do |a, b| self[a] <=> self[b] end end end end end
true
5706451b00b7763b6f737c15dba2931664dfebbd
Ruby
jasonayre/rpg_codetest
/lib/rbrpg/computer.rb
UTF-8
359
2.765625
3
[ "MIT" ]
permissive
module Rbrpg class Computer attr_accessor :hero, :name def initialize(hero_type:, name:) @hero_type = hero_type @hero = hero_class.new @name = name end def valid_targets [ @hero ] end private def hero_class @hero_class ||= "rbrpg/characters/#{@hero_type}".classify.constantize end end end
true
9593f8d99285307a94f3805ccf2720c5becfe045
Ruby
marten/path_notifier
/lib/path_notifier/location_trigger.rb
UTF-8
2,222
2.5625
3
[ "MIT" ]
permissive
module PathNotifier class LocationTrigger def self.trigger # First, update coordinates PathNotifier::GeoloqiImporter.update(Models::Coordinate.latest.timestamp) current_coord = Models::Coordinate.latest # Next, find place associated with trigger location current_place = Models::Place.geo_near([current_coord.location[:lng], current_coord.location[:lat]], max_distance: 100, unit: :m).first if current_place # Then see if we have tasks associated with that place if current_place.has_tasks? # If we have stuff to do at that place, see if we'd normally do it last_place = last_place_left_since(current_coord) route = Models::Route.where(:source_id => last_place.id, :destination_id => current_place.id).first # We have stuff to do, and we have stopped here in the past to do stuff, so # notify the user that he should do stuff if route status = Notification.for(current_place).send {status: "notification sent", response: status, current_place: current_place.id} else {status: "no-route", last_place: last_place.id, current_place: current_place.id} end else {:status => "no-tasks", current_place: current_place.id} end else {:status => "no-place-near"} end end def self.last_place_left_since(coord) current_place = Models::Place.geo_near([coord.location[:lng], coord.location[:lat]], max_distance: 50, unit: :m).first Models::Coordinate.desc(:timestamp).where(:timestamp.lt => coord.timestamp).all.each do |other| # Find out if there is a place near `other` place = Models::Place.geo_near([other.location[:lng], other.location[:lat]], max_distance: 50, unit: :m).first # If the place near `other` is not where we're currently, return it if place and place != current_place return place end end # If we find nothing, return nil (instead of all coordinates) nil end end end
true
3d81a5118e559532aa7d00629c041f8feee72ccd
Ruby
saulo-lir/curso-ruby_e_ruby-on-rails
/curso-ruby/02-ruby-poo/09-constantes_e_classes_constantes.rb
UTF-8
348
3.03125
3
[]
no_license
# As variáveis são declaradas com letras minúsculas # As constantes são declaradas com letras MAIÚSCULAS # As constantes não mudam o valor em todo o sistema # Definindo uma classe constante class Teste PI = 3.14 NOME_APP = "Sistema de CRM" NOME_CLIENTE = "Fulano de Tal" end puts Teste::PI puts Teste::NOME_CLIENTE puts Teste::NOME_APP
true
e1bf98f9744b8e5e37b0d6d3c5f15b825afed5ed
Ruby
SahamAK/phase-0-tracks
/ruby/iteration.rb
UTF-8
2,449
4.1875
4
[]
no_license
#5.3 Mandtory pairing : Iteration #names: Saham Khozestani and Mike Tsou # Release 0 # iterating without parameter 5.times do puts "This is a test" end puts " " # iterating with parameter 3.times do |x| puts x + x end puts " " # one line block 4.times {|x| puts x + x} puts " " # Release 1 array = [2, 5, 3, 7, 9] full_name = { first: "adam", middle: "richard", last: "smith" } puts "array output" array.each do |x| puts x + 2 end p array puts " " puts "map output" new_array = array.map do |x| x * 2 end p new_array puts "" puts "map! output" array.map! do |x| x + 10 end p array puts " " puts "hash.each output" full_name.each do |x, y| puts "#{x} name is #{y}" end p full_name puts " " puts "hash.map output" new_full_name = full_name.map do |x, y| "#{x} name is #{y}" end p new_full_name puts " " # fails due to hash data structure #full_name.map! do |x, y| # "#{x} name is #{y}" #end #p full_name # Release 2 numbers = [0, 1, 3, 4, 5, 6, 7] letters = { a: 1, b: 2, c: 3, d: 4 } puts "reject less than 5 in array" puts "numbers array prior to command: #{numbers}" new_numbers = numbers.reject {|x| x < 5} p new_numbers puts " " puts "rejects value less than 5 in hash" puts "letters hash prior to reject command: #{letters}" new_letters = letters.reject {|x, y| y < 3} p new_letters puts " " puts "selects less than 5 in array" puts "array prior to select command: #{numbers}" new_numbers = numbers.select {|x| x < 5} p new_numbers puts " " puts "select value less than 3 in hash" puts "hash prior to select command: #{letters}" new_letters = letters.select {|x, y| y < 3} p new_letters puts " " puts "keeps if less than 6" puts "array prior to keep_if command: #{numbers}" numbers.keep_if {|x| x < 6} p numbers puts " " puts "keep if value doesn't equal 3" puts "hash prior to keep_if command: #{letters}" letters.keep_if {|x, y| y != 3} p letters puts " " puts "drop while less than 2" puts " numbers array prior to drop_while: #{numbers}" new_numbers = numbers.drop_while {|x| x < 2} p "new array: #{new_numbers}" puts "original array : #{numbers}" puts " " puts "drop while value is equal to 1" puts "letters hash prior to drop_while: #{letters}" new_letters = letters.drop_while {|x, y| y == 1} p "new hash: #{new_letters}" puts "original hash: #{letters}"
true
679782de99f1d11af908532d23241ec3ba8476c8
Ruby
chang-ryan/ruby-building-blocks
/bubble_sort.rb
UTF-8
782
3.90625
4
[]
no_license
def bubble_sort(numbers) swapped = true while swapped swapped = false for i in (0...numbers.size-1) if numbers[i] > numbers[i+1] numbers.insert(i, numbers.delete_at(i+1)) swapped = true end end end numbers end p bubble_sort([99,4,3,78,2,0,2]) # => [0,2,2,3,4,78,99] def bubble_sort_by(list) swapped = true while swapped swapped = false for i in (0...list.size-1) if yield(list[i], list[i+1]) > 0 list.insert(i, list.delete_at(i+1)) swapped = true end end end list end bubble_sort_by(["hi","hello","hey"]) do |left,right| left.length - right.length end # => ["hi", "hey", "hello"]
true
4fc23960e330dfd1b661611d8f3d4a5008db0e2d
Ruby
jasont01/chess
/lib/legality.rb
UTF-8
726
3.0625
3
[]
no_license
require_relative 'pieces/pieces.rb' module Legality def legal_move?(board, start, finish) return false if squares_legal?(board, start, finish) == false return false if in_moveset_and_unblocked?(board, start, finish) == false true end def in_moveset_and_unblocked?(board, start, finish) piece = board.positions[start[0]][start[1]] possible_moves = piece.all_possible_moves(board.positions) return true if possible_moves.include?(finish) false end def squares_legal?(board, start, finish) start_piece = board.positions[start[0]][start[1]] return false if start_piece.color != board.current_player && ![start, finish].flatten.all? {|i| i.between?(0, 7) } true end end
true
12b87306920b8623e7a7b2f2b434a8cbd8ca0913
Ruby
nicky90/code2html
/code2html.rb
GB18030
2,649
2.765625
3
[]
no_license
$path = ARGV[0] if ($path == nil || !File.exists?($path)) puts "Usage: code2html pathname" exit(-1) end $gid = 10000 #ļ $links = "" #Ŀ¼ $content = "" #ɵhtml $file2gid = {} #ļӦgidĿ¼htmlеļ #htmlбת룬<֮಻ʾ def html_escape(s) s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;") end def url_encode(s) s.to_s.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) } end #Ŀ¼,õȫֱʱҪĸ class Tree def initialize(root) @tree = {} @tree[root] = {} end def add(v) pcur = @tree v.each { |f| if (pcur[f] == nil) pcur[f] = {} end pcur = pcur[f] } end def print() p @tree end def dump() dump_tree("", @tree) end def dump_tree(p, tr) if (tr.size() > 0) tr.each {|k,v| dump_tree(p + "/" + k , v) } else puts p end end def write_node() pid = -1 @cid = 0 write_node_inner(pid, $path, $path, @tree[$path]) end def write_node_inner(pid, fullpath, pname, tr) link_gid = $file2gid[fullpath] #puts "#{fullpath}: #{link_gid}" if (link_gid == nil) $links += ("d.add(#{@cid}, #{pid}, \"#{pname}\", \"\")\n") else $links +=("d.add(#{@cid}, #{pid}, \"#{pname}\", \"javascript:open_file(#{link_gid});\")\n") end pid = @cid if (tr.size() > 0) tr.each {|k,v| @cid = @cid + 1 #puts("d.add(#{@cid}, #{pid}, \"#{k}\", \"\")") filepath = fullpath.length() > 0 ? fullpath + "/" + k : k write_node_inner(pid, filepath, k, v) } end end end # gen a path tree $t = Tree.new("#{$path}") def parse_to_tree(f) $t.add(f.split("/")) end def handle(fname) parse_to_tree(fname) # Ŀ¼ if (!File.file?(fname)) return end $gid = $gid + 1 #$links += "d.add(#{$gid}, 0, \"#{fname}\", \"javascript:open_file(#{$gid});\")\n" $file2gid[fname] = $gid c = File.read(fname) pre_class = "" if ($gid == 10001) pre_class = "class=\"prettyprint\"" end $content += %Q{ <div class="code" id="#{$gid}" style="margin:0px 0px 0px 0px; display:none;z-index:8"> <pre #{pre_class} id="#{$gid+100000}"> #{html_escape(c)} </pre> </div> } end Dir.glob("#{$path}/**/*"){|f| handle(f) } # put out result ........... $f_result = File.open("#{$path}_project.html", "w") $t.write_node() $html = File.read("template.html").each_line{|l| if (l.include?("9e62INDEX")) $f_result.puts $links elsif (l.include?("9e62FILECONTENT")) $f_result.puts $content else $f_result.puts l end } $f_result.close()
true
293186856c7ff9377e6eea646282c88999715d83
Ruby
sainu/atcoder
/contests/abc145/a.rb
UTF-8
259
2.859375
3
[]
no_license
# frozen_string_literal: true require 'bundler/setup' require 'pry' # ----- ここから下が提出コード ----- def gi; gets.to_i end def gs; gets.chomp end def gli; gets.split(' ').map(&:to_i) end def d(n); Math.log10(n).to_i + 1 end r = gi puts r**2
true
541f0ae9e13ec31147abadef08d3af5340caf88b
Ruby
zoer/xmlable
/lib/xmlable/types.rb
UTF-8
652
2.53125
3
[ "MIT" ]
permissive
XMLable::Builder.tap do |b| b.define_type :string, :str, String do cast { |val| val.to_s } end b.define_type :integer, :int, Integer do cast { |val| val.to_i } export_to_json { |val| val } end b.define_type :float, Float do cast { |val| val.to_f } export_to_json { |val| val } end b.define_type :date, Date do cast do |val| Date.parse(val) if val.is_a?(String) && !val.empty? end export { |val| val.is_a?(Date) ? val.to_s : val } end b.define_type :bool, :boolean do cast do |val| !['false', '0', ''].include?(val.to_s.downcase) end export_to_json { |val| val } end end
true
0d032e477b96476535916ceabba228ccc97a9d9b
Ruby
stanimirvasilev/prework-videos-intro-to-tests-online-web-sp-000
/conversions.rb
UTF-8
91
3.15625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def ounces_to_grams(ounces) unces_to_grams = 28.3495 ounces.to_f * unces_to_grams end
true
912f41bab98623598ef212c6ec7775e1a5f9f3fc
Ruby
jcsky/ruby-excise
/classes_and_objects_part1/ex1.rb
UTF-8
485
3.703125
4
[]
no_license
class MyCar attr_accessor :color def initialize(year, color, model) @year = year @color = color @model = model @speed = 0 end def speed_up @speed = @speed+1 puts "speed is #{@speed}" end def brake (@speed>0)? @speed = @speed-1 : @speed = 0 puts "speed is #{@speed}" end def shut @speed = 0 puts "speed is #{@speed}" end end car1 = MyCar.new(1985,"red","toyota") car1.speed_up car1.speed_up car1.brake car1.speed_up car1.shut
true
3cb8430a6bba9cbdbe068849662bcacdb7210863
Ruby
esminc/rubyagile
/config/initializers/core_ext.rb
UTF-8
167
2.53125
3
[ "MIT" ]
permissive
class Date private def feed_utils_to_time(dest, method) Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min, dest.sec, dest.zone) end end
true
856c68ac525a4af5b3220f4363d341e741effd55
Ruby
govaniso/phidgets-ffi
/lib/phidgets-ffi/led.rb
UTF-8
3,885
2.8125
3
[]
no_license
module Phidgets # This class represents a PhidgetLED. class LED Klass = Phidgets::FFI::CPhidgetLED include Phidgets::Common # Collection of LEDs # @return [LEDOuputs] attr_reader :leds attr_reader :attributes # The attributes of a PhidgetLED def attributes super.merge({ :leds => leds.size, }) end # @return [Phidgets::FFI::LEDCurrentLimit] returns the board current limit for all LEDs, or raises an error. Not supported on all PhidgetLEDs. def current_limit ptr = ::FFI::MemoryPointer.new(:int) Klass.getCurrentLimit(@handle, ptr) Phidgets::FFI::LEDCurrentLimit[ptr.get_int(0)] end # Sets the board current limit for all LEDs, or raises an error. Not supported on all PhidgetLEDs. # @param [Phidgets::FFI::LEDCurrentLimit] new_current_limit new current limit # @return [Phidgets::FFI::LEDCurrentLimit] returns the board current limit, or raises an error. def current_limit=(new_current_limit) ptr = ::FFI::MemoryPointer.new(:int) Klass.setCurrentLimit(@handle, Phidgets::FFI::LEDCurrentLimit[new_current_limit]) new_current_limit end # @return [Phidgets::FFI::LEDVoltage] returns the voltage level for all LEDs, or raises an error. Not supported on all PhidgetLEDs. def voltage ptr = ::FFI::MemoryPointer.new(:int) Klass.getVoltage(@handle, ptr) Phidgets::FFI::LEDVoltage[ptr.get_int(0)] end # Sets the voltage level for all LEDs, or raises an error. Not supported on all PhidgetLEDs. # @param [Phidgets::FFI::LEDVoltage] new_voltage new voltage # @return [Phidgets::FFI::LEDVoltage] returns the voltage level, or raises an error. def voltage=(new_voltage) ptr = ::FFI::MemoryPointer.new(:int) Klass.setVoltage(@handle, Phidgets::FFI::LEDVoltage[new_voltage]) new_voltage end # This class represents an led for a PhidgetLED. All the properties of an led are stored and modified in this class. class LEDOuputs Klass = Phidgets::FFI::CPhidgetLED private def initialize(handle, index) @handle, @index = handle, index.to_i end public # Displays data for an led. def inspect "#<#{self.class} @index=#{index}, @brightness=#{brightness}>" end # @return [Integer] returns the index of the led, or raises an error. def index @index end # @return [Float] returns the brightness level of an LED, or raises an error. def brightness ptr = ::FFI::MemoryPointer.new(:double) Klass.getBrightness(@handle, @index, ptr) ptr.get_int(0) end # Sets the brightness level of an LED, or raises an error. Brightness levels range from 0-100 # @param [Float] new_brightness new brightness # @return [Float] returns the brightness of an LED, or raises an error. def brightness=(new_brightness) Klass.setBrightness(@handle, @index, new_brightness.to_f) new_brightness.to_f end # @return [Float] returns the current limit of an LED, or raises an error. def current_limit ptr = ::FFI::MemoryPointer.new(:double) Klass.getCurrentLimitIndexed(@handle, @index, ptr) ptr.get_int(0) end # Sets the current limit of an LED, or raises an error. Current Limit levels range from 0-80 mA # @param [Float] new_current_limit new current limit # @return [Float] returns the current limit of an LED, or raises an error. def current_limit=(new_current_limit) Klass.setCurrentLimitIndexed(@handle, @index, new_current_limit.to_f) new_current_limit.to_f end end #LEDOutputs private def load_device_attributes load_leds end def load_leds ptr = ::FFI::MemoryPointer.new(:int) Klass.getLEDCount(@handle, ptr) @leds = [] ptr.get_int(0).times do |i| @leds << LEDOuputs.new(@handle, i) end end def remove_specific_event_handlers end end end
true
d3d2a80645551b32a30056fe3d88131b8df5422c
Ruby
gerndtr/ruby_practice
/pract2.rb
UTF-8
1,006
3.96875
4
[]
no_license
# def division (x, y) # ans = x / y # end # puts "How many people want a pair of cards?" # count == gets.chomp.to_i # puts "And the second one is..." # y = gets.chomp.to_i # if x == 0 || y == 0 # puts "Sorry, they cannot be zero. Try again." # division # elsif # x != Integer || y != Integer # division # end # puts division(x, y) # class Poker # def question1 # @question1 # puts "How many players want a pair of cards?" # @answer1 = gets.chomp.to_i # if @answer1 != integer # question1 # else # player1 # end # end # def player1 # @player1 # puts "Player one has a #{card_1 # @answer2 = gets.chomp.downcase # if @answer2 != "yes" || "no" # question2 # else # question2 # end # end # end deck = ["ah", "a] # link the card value to the index of the card in the array.
true
31edcc7c0528705a08f5bb1b459aba64aa26887d
Ruby
trevorbennett/mathematical-properties-of-card-shuffles
/lib/application.rb
UTF-8
95
2.734375
3
[ "Apache-2.0" ]
permissive
require_relative("weighted_deck") deck = WeightedDeck.new(52) puts(deck.size) puts(deck.deck)
true
a922091a330bd72dc7070489ad210f9c0c95ca33
Ruby
BurdetteLamar/minitest_log
/lib/helpers/array_helper.rb
UTF-8
744
2.59375
3
[ "MIT" ]
permissive
require 'diff/lcs' class ArrayHelper # Compare two arrays. def self.compare(expected, actual) sdiff = Diff::LCS.sdiff(expected, actual) changes = {} action_words = { '!' => 'changed', '+' => 'unexpected', '-' => 'missing', '=' => 'unchanged' } sdiff.each_with_index do |change, i| action_word = action_words.fetch(change.action) key = "change_#{i}" attrs = %W/ action=#{action_word} old_pos=#{change.old_position} old_ele=#{change.old_element} new_pos=#{change.old_position} new_ele=#{change.old_element} / value = attrs.join(' ') changes.store(key, value) end {:sdiff => changes} end end
true
b09b3ec53cee0ed7e2f6fd729f2c08cd27ee398f
Ruby
FillanL/keys-of-hash-nyc-web-career-031119
/lib/keys_of_hash.rb
UTF-8
241
3.1875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Hash def keys_of(*arguments) return_val = [] arguments.each do |item| self.each do |k, v| if item == v return_val << k end end end return_val end end
true
ca71faf920097f9fd3c9f8150382c9ce6b6d727f
Ruby
auranet/asapccf
/lib/asap/adt/gis/geographic_rectangle.rb
UTF-8
5,037
2.5625
3
[]
no_license
module ASAP module ADT module GIS class GeographicRectangle < GeographicPointContainer define_accessors :corners => {:type => Array, :required => true, :validator => lambda {|value| value.size == 2 && value.all? {|vertex| vertex.kind_of? GeographicPoint}}} def initialize(ne_longitude_value, ne_longitude_hemisphere, ne_latitude_value, ne_latitude_hemisphere, sw_longitude_value, sw_longitude_hemisphere, sw_latitude_value, sw_latitude_hemisphere, initializers={}) initializers = {:corners => [GeographicPoint.new(:longitude => Longitude.new(:value => ne_longitude_value.to_f.abs, :hemisphere => ne_longitude_hemisphere.to_sym), :latitude => Latitude.new( :value => ne_latitude_value.to_f.abs, :hemisphere => ne_latitude_hemisphere.to_sym)), GeographicPoint.new(:longitude => Longitude.new(:value => sw_longitude_value.to_f.abs, :hemisphere => sw_longitude_hemisphere.to_sym), :latitude => Latitude.new( :value => sw_latitude_value.to_f.abs, :hemisphere => sw_latitude_hemisphere.to_sym))]} super initializers end def to_s corners.join "; " end def ne_corner @corners = Array.new(2) unless corners corners[0] end def ne_corner=(value) @corners = Array.new(2) unless corners corners[0] = value end def ne_longitude_value (ne_corner && ne_corner.longitude) ? ne_corner.longitude.value : nil end def ne_longitude_value=(value) ne_corner ||= GeographicPoint.new ne_corner.longitude ||= Longitude.new ne_corner.longitude.value = value end def ne_longitude_hemisphere (ne_corner && ne_corner.longitude) ? ne_corner.longitude.hemisphere.to_sym : nil end def ne_longitude_hemisphere=(hemisphere) ne_corner ||= GeographicPoint.new ne_corner.longitude ||= Longitude.new ne_corner.longitude.hemisphere = hemisphere.to_sym end def ne_latitude_value (ne_corner && ne_corner.latitude) ? ne_corner.latitude.value : nil end def ne_latitude_value=(value) ne_corner ||= GeographicPoint.new ne_corner.latitude ||= Latitude.new ne_corner.latitude.value = value end def ne_latitude_hemisphere (ne_corner && ne_corner.latitude) ? ne_corner.latitude.hemisphere.to_sym : nil end def ne_latitude_hemisphere=(hemisphere) ne_corner ||= GeographicPoint.new ne_corner.latitude ||= Latitude.new ne_corner.latitude.hemisphere = hemisphere.to_sym end def sw_corner @corners = Array.new(2) unless corners corners[1] end def sw_corner=(value) @corners = Array.new(2) unless corners corners[1] = value end def sw_longitude_value (sw_corner && sw_corner.longitude) ? sw_corner.longitude.value : nil end def sw_longitude_value=(value) sw_corner ||= GeographicPoint.new sw_corner.longitude ||= Longitude.new sw_corner.longitude.value = value end def sw_longitude_hemisphere (sw_corner && sw_corner.longitude) ? sw_corner.longitude.hemisphere.to_sym : nil end def sw_longitude_hemisphere=(hemisphere) sw_corner ||= GeographicPoint.new sw_corner.longitude ||= Longitude.new sw_corner.longitude.hemisphere = hemisphere.to_sym end def sw_latitude_value (sw_corner && sw_corner.latitude) ? sw_corner.latitude.value : nil end def sw_latitude_value=(value) sw_corner ||= GeographicPoint.new sw_corner.latitude ||= Latitude.new sw_corner.latitude.value = value end def sw_latitude_hemisphere (sw_corner && sw_corner.latitude) ? sw_corner.latitude.hemisphere.to_sym : nil end def sw_latitude_hemisphere=(hemisphere) sw_corner ||= GeographicPoint.new sw_corner.latitude ||= Latitude.new sw_corner.latitude.hemisphere = hemisphere.to_sym end def area(unit) # TODO: Rewrite, accounting for units of measure and for curved surfaces (such as the Earth's!) Area.new(((corners[1].longitude.signed_value - corners[0].longitude.signed_value) * (corners[1].latitude.signed_value - corners[0].latitude.signed_value)).abs, unit) end end end end end
true
e02515ba627d23f45b9d6d09749734cd18159717
Ruby
philipluk/aspera-cli
/lib/aspera/cli/manager.rb
UTF-8
18,079
2.84375
3
[ "Apache-2.0" ]
permissive
require 'aspera/colors' require 'aspera/log' require 'aspera/cli/extended_value' require 'optparse' require 'io/console' module Aspera module Cli # raised by cli on error conditions class CliError < StandardError; end # raised when an unexpected argument is provided class CliBadArgument < CliError; end class CliNoSuchId < CliError def initialize(res_type,res_id) msg="No such #{res_type} identifier: #{res_id}" super(msg) end end # option is retrieved from another object using accessor class AttrAccessor #attr_accessor :object #attr_accessor :attr_symb def initialize(object,attr_symb) @object=object @attr_symb=attr_symb end def value @object.send(@attr_symb.to_s) end def value=(val) @object.send(@attr_symb.to_s+'=',val) end end # parse command line options # arguments options start with '-', others are commands # resolves on extended value syntax class Manager def self.time_to_string(time) time.strftime("%Y-%m-%d %H:%M:%S") end # boolean options are set to true/false from the following values TRUE_VALUES=[:yes,true] BOOLEAN_VALUES=TRUE_VALUES.clone.push(:no,false) BOOLEAN_SIMPLE=[:yes,:no] # option name separator on command line OPTION_SEP_LINE='-' # option name separator in code (symbol) OPTION_SEP_NAME='_' private_constant :TRUE_VALUES,:BOOLEAN_VALUES,:BOOLEAN_SIMPLE,:OPTION_SEP_LINE,:OPTION_SEP_NAME def enum_to_bool(enum);TRUE_VALUES.include?(enum);end # find shortened string value in allowed symbol list def self.get_from_list(shortval,descr,allowed_values) # we accept shortcuts matching_exact=allowed_values.select{|i| i.to_s.eql?(shortval)} return matching_exact.first if matching_exact.length == 1 matching=allowed_values.select{|i| i.to_s.start_with?(shortval)} raise cli_bad_arg("unknown value for #{descr}: #{shortval}",allowed_values) if matching.empty? raise cli_bad_arg("ambigous shortcut for #{descr}: #{shortval}",matching) unless matching.length.eql?(1) return enum_to_bool(matching.first) if allowed_values.eql?(BOOLEAN_VALUES) return matching.first end def self.cli_bad_arg(error_msg,choices) return CliBadArgument.new(error_msg+"\nUse:\n"+choices.map{|c| "- #{c.to_s}\n"}.sort.join('')) end attr_reader :parser attr_accessor :ask_missing_mandatory attr_accessor :ask_missing_optional # def initialize(program_name,argv,app_banner) # command line values not starting with '-' @unprocessed_cmd_line_arguments=[] # command line values starting with '-' @unprocessed_cmd_line_options=[] # a copy of all initial options @initial_cli_options=[] # option description: key = option symbol, value=hash, :type, :accessor, :value, :accepted @declared_options={} # do we ask missing options and arguments to user ? @ask_missing_mandatory=false # STDIN.isatty # ask optional options if not provided and in interactive @ask_missing_optional=false # those must be set before parse, parse consumes those defined only @unprocessed_defaults=[] @unprocessed_env=[] # Note: was initially inherited but it is prefered to have specific methods @parser=OptionParser.new @parser.program_name=program_name @parser.banner=app_banner # options can also be provided by env vars : --param-name -> ASLMCLI_PARAM_NAME env_prefix=program_name.upcase+OPTION_SEP_NAME ENV.each do |k,v| if k.start_with?(env_prefix) @unprocessed_env.push([k[env_prefix.length..-1].downcase.to_sym,v]) end end Log.log.debug("env=#{@unprocessed_env}".red) # banner is empty when help is generated for every plugin unless app_banner.empty? @parser.separator("") @parser.separator("OPTIONS: global") self.set_obj_attr(:interactive,self,:ask_missing_mandatory) self.set_obj_attr(:ask_options,self,:ask_missing_optional) self.add_opt_boolean(:interactive,"use interactive input of missing params") self.add_opt_boolean(:ask_options,"ask even optional options") self.parse_options! end @unprocessed_cmd_line_options=[] @unprocessed_cmd_line_arguments=[] process_options=true while !argv.empty? value=argv.shift if process_options and value.start_with?('-') if value.eql?('--') process_options=false else @unprocessed_cmd_line_options.push(value) end else @unprocessed_cmd_line_arguments.push(value) end end @initial_cli_options=@unprocessed_cmd_line_options.dup Log.log.debug("add_cmd_line_options:commands/args=#{@unprocessed_cmd_line_arguments},options=#{@unprocessed_cmd_line_options}".red) end def prompt_user_input(prompt,sensitive) return STDIN.getpass("#{prompt}> ") if sensitive print "#{prompt}> " return STDIN.gets.chomp end def get_interactive(type,descr,expected=:single) if !@ask_missing_mandatory if expected.is_a?(Array) raise self.class.cli_bad_arg("missing: #{descr}",expected) end raise CliBadArgument,"missing argument (#{expected}): #{descr}" end result=nil # Note: mandatory parenthesis here ! sensitive = (type.eql?(:option) and @declared_options[descr.to_sym][:sensitive].eql?(true)) default_prompt="#{type}: #{descr}" # ask interactively case expected when :multiple result=[] puts " (one per line, end with empty line)" loop do entry=prompt_user_input(default_prompt,sensitive) break if entry.empty? result.push(ExtendedValue.instance.evaluate(entry)) end when :single result=ExtendedValue.instance.evaluate(prompt_user_input(default_prompt,sensitive)) else # one fixed result=self.class.get_from_list(prompt_user_input("#{expected.join(' ')}\n#{default_prompt}",sensitive),descr,expected) end return result end def get_next_command(command_list); return get_next_argument('command',command_list); end # @param expected is # - Array of allowed value (single value) # - :multiple for remaining values # - :single for a single unconstrained value # @param is_type : :mandatory or :optional # @return value, list or nil def get_next_argument(descr,expected=:single,is_type=:mandatory) result=nil if !@unprocessed_cmd_line_arguments.empty? # there are values case expected when :single result=ExtendedValue.instance.evaluate(@unprocessed_cmd_line_arguments.shift) when :multiple result = @unprocessed_cmd_line_arguments.shift(@unprocessed_cmd_line_arguments.length).map{|v|ExtendedValue.instance.evaluate(v)} # if expecting list and only one arg of type array : it is the list if result.length.eql?(1) and result.first.is_a?(Array) result=result.first end else result=self.class.get_from_list(@unprocessed_cmd_line_arguments.shift,descr,expected) end else # no value provided if is_type.eql?(:mandatory) result=get_interactive(:argument,descr,expected) end end Log.log.debug("#{descr}=#{result}") return result end # declare option of type :accessor, or :value def declare_option(option_symbol,type) Log.log.debug("declare_option: #{option_symbol}: #{type}: skip=#{@declared_options.has_key?(option_symbol)}".green) if @declared_options.has_key?(option_symbol) raise "INTERNAL ERROR: option #{option_symbol} already declared. only accessor can be redeclared and ignored" unless @declared_options[option_symbol][:type].eql?(:accessor) return end @declared_options[option_symbol]={:type=>type} # by default passwords and secrets are sensitive, else specify when declaring the option set_is_sensitive(option_symbol) if !%w{password secret key}.select{|i| option_symbol.to_s.end_with?(i)}.empty? end def set_is_sensitive(option_symbol) @declared_options[option_symbol][:sensitive]=true end # define option with handler def set_obj_attr(option_symbol,object,attr_symb,default_value=nil) Log.log.debug("set attr obj #{option_symbol} (#{object},#{attr_symb})") declare_option(option_symbol,:accessor) @declared_options[option_symbol][:accessor]=AttrAccessor.new(object,attr_symb) set_option(option_symbol,default_value,"default obj attr") if !default_value.nil? end # set an option value by name, either store value or call handler def set_option(option_symbol,value,where="default") if ! @declared_options.has_key?(option_symbol) Log.log.debug("set unknown option: #{option_symbol}") raise "ERROR" #declare_option(option_symbol) end value=ExtendedValue.instance.evaluate(value) Log.log.debug("set_option(#{where}) #{option_symbol}=#{value}") if @declared_options[option_symbol][:values].eql?(BOOLEAN_VALUES) value=enum_to_bool(value) end Log.log.debug("set #{option_symbol}=#{value} (#{@declared_options[option_symbol][:type]}) : #{where}".blue) case @declared_options[option_symbol][:type] when :accessor @declared_options[option_symbol][:accessor].value=value when :value @declared_options[option_symbol][:value]=value else # nil or other raise "error" end end # get an option value by name # either return value or call handler, can return nil # ask interactively if requested/required def get_option(option_symbol,is_type=:optional) result=nil if @declared_options.has_key?(option_symbol) case @declared_options[option_symbol][:type] when :accessor result=@declared_options[option_symbol][:accessor].value when :value result=@declared_options[option_symbol][:value] else raise "unknown type" end Log.log.debug("get #{option_symbol} (#{@declared_options[option_symbol][:type]}) : #{result}") end Log.log.debug("interactive=#{@ask_missing_mandatory}") if result.nil? if !@ask_missing_mandatory if is_type.eql?(:mandatory) raise CliBadArgument,"Missing mandatory option: #{option_symbol}" end else # ask_missing_mandatory if @ask_missing_optional or is_type.eql?(:mandatory) expected=:single #print "please enter: #{option_symbol.to_s}" if @declared_options.has_key?(option_symbol) and @declared_options[option_symbol].has_key?(:values) expected=@declared_options[option_symbol][:values] end result=get_interactive(:option,option_symbol.to_s,expected) set_option(option_symbol,result,"interactive") end end end return result end # param must be hash def add_option_preset(preset_hash,op=:push) Log.log.debug("add_option_preset=#{preset_hash}") raise "internal error: setting default with no hash: #{preset_hash.class}" if !preset_hash.is_a?(Hash) # incremental override preset_hash.each{|k,v|@unprocessed_defaults.send(op,[k.to_sym,v])} end # generate command line option from option symbol def symbol_to_option(symbol,opt_val) result='--'+symbol.to_s.gsub(OPTION_SEP_NAME,OPTION_SEP_LINE) result=result+'='+opt_val unless opt_val.nil? return result end def highlight_current(value) STDOUT.isatty ? value.to_s.red.bold : "[#{value}]" end # define an option with restricted values def add_opt_list(option_symbol,values,help,*on_args) declare_option(option_symbol,:value) Log.log.debug("add_opt_list #{option_symbol}") on_args.unshift(symbol_to_option(option_symbol,'ENUM')) # this option value must be a symbol @declared_options[option_symbol][:values]=values value=get_option(option_symbol) help_values=values.map{|i|i.eql?(value)?highlight_current(i):i}.join(', ') if values.eql?(BOOLEAN_VALUES) help_values=BOOLEAN_SIMPLE.map{|i|((i.eql?(:yes) and value) or (i.eql?(:no) and not value))?highlight_current(i):i}.join(', ') end on_args.push(values) on_args.push("#{help}: #{help_values}") Log.log.debug("on_args=#{on_args}") @parser.on(*on_args){|v|set_option(option_symbol,self.class.get_from_list(v.to_s,help,values),"cmdline")} end def add_opt_boolean(option_symbol,help,*on_args) add_opt_list(option_symbol,BOOLEAN_VALUES,help,*on_args) end # define an option with open values def add_opt_simple(option_symbol,*on_args) declare_option(option_symbol,:value) Log.log.debug("add_opt_simple #{option_symbol}") on_args.unshift(symbol_to_option(option_symbol,"VALUE")) Log.log.debug("on_args=#{on_args}") @parser.on(*on_args) { |v| set_option(option_symbol,v,"cmdline") } end # define an option with date format def add_opt_date(option_symbol,*on_args) declare_option(option_symbol,:value) Log.log.debug("add_opt_date #{option_symbol}") on_args.unshift(symbol_to_option(option_symbol,"DATE")) Log.log.debug("on_args=#{on_args}") @parser.on(*on_args) do |v| case v when 'now'; set_option(option_symbol,Manager.time_to_string(Time.now),"cmdline") when /^-([0-9]+)h/; set_option(option_symbol,Manager.time_to_string(Time.now-$1.to_i*3600),"cmdline") else set_option(option_symbol,v,"cmdline") end end end # define an option without value def add_opt_switch(option_symbol,*on_args,&block) Log.log.debug("add_opt_on #{option_symbol}") on_args.unshift(symbol_to_option(option_symbol,nil)) Log.log.debug("on_args=#{on_args}") @parser.on(*on_args,&block) end # check if there were unprocessed values to generate error def command_or_arg_empty? return @unprocessed_cmd_line_arguments.empty? end # unprocessed options or arguments ? def final_errors result=[] result.push("unprocessed options: #{@unprocessed_cmd_line_options}") unless @unprocessed_cmd_line_options.empty? result.push("unprocessed values: #{@unprocessed_cmd_line_arguments}") unless @unprocessed_cmd_line_arguments.empty? return result end # get all original options on command line used to generate a config in config file def get_options_table(remove_from_remaining=true) result={} @initial_cli_options.each do |optionval| case optionval when /^--([^=]+)$/ # ignore when /^--([^=]+)=(.*)$/ name=$1 value=$2 name.gsub!(OPTION_SEP_LINE,OPTION_SEP_NAME) value=ExtendedValue.instance.evaluate(value) Log.log.debug("option #{name}=#{value}") result[name]=value @unprocessed_cmd_line_options.delete(optionval) if remove_from_remaining else raise CliBadArgument,"wrong option format: #{optionval}" end end return result end # return options as taken from config file and command line just before command execution def declared_options(all=true) return @declared_options.keys.inject({}) do |h,option_symb| v=get_option(option_symb) h[option_symb.to_s]=v if all or !v.nil? h end end def apply_options_preset(preset,where,force=false) unprocessed=[] preset.each do |pair| k,v=*pair if @declared_options.has_key?(k) # constrained parameters as string are revert to symbol if @declared_options[k].has_key?(:values) and v.is_a?(String) v=self.class.get_from_list(v,k.to_s+" in #{where}",@declared_options[k][:values]) end set_option(k,v,where) else unprocessed.push(pair) end end # keep only unprocessed values for next parse preset.clear preset.push(*unprocessed) end # removes already known options from the list def parse_options! Log.log.debug("parse_options!".red) # first conf file, then env var apply_options_preset(@unprocessed_defaults,"file") apply_options_preset(@unprocessed_env,"env") # command line override unknown_options=[] begin # remove known options one by one, exception if unknown Log.log.debug("before parse".red) @parser.parse!(@unprocessed_cmd_line_options) Log.log.debug("After parse".red) rescue OptionParser::InvalidOption => e Log.log.debug("InvalidOption #{e}".red) # save for later processing unknown_options.push(e.args.first) retry end Log.log.debug("remains: #{unknown_options}") # set unprocessed options for next time @unprocessed_cmd_line_options=unknown_options end end end end
true
b30556124ad9e05565895902e48d590a26d54a7d
Ruby
cameronjkelley/exercism
/ruby/raindrops/raindrops.rb
UTF-8
223
2.984375
3
[]
no_license
class Raindrops RAINDROPS = { "Pling" => 3, "Plang" => 5, "Plong" => 7 } def self.convert(num) result = RAINDROPS.select { |_key, value| num % value == 0 }.keys.join result.empty? ? num.to_s : result end end
true
e8d2c856fae259271e48b330ad35188e23638f2f
Ruby
marina-ferreira/poodr
/chapter_3/remove_argument_order_dependencies.rb
UTF-8
709
3.703125
4
[]
no_license
# Bad 🤢 # A message that requires arguments creates a dependency. Not only on the name # of the arguments, but also on their order. class Gear attr_reader :chainring, :cog, :wheel def initialize(chainring, cog, wheel) @chainring = chainring @cog = cog @wheel = wheel end end Gear.new(52, 11 Wheel.new(26, 1.5)) # Taking keyword arguments is a way to avoid arguments position class Gear attr_reader :chainring, :cog, :wheel def initialize(chainring:, cog:, wheel:) @chainring = chainring @cog = cog @wheel = wheel end end Gear.new( chainring: 52, cog: 11, wheel: Wheel.new(26, 1.5) ) Gear.new( :cog => 11, :chainring => 52, :wheel => Wheel.new(26, 1.5) )
true
fc20a5f82faccfdf1ca7613e18d56c9c607cc8fb
Ruby
recroot89/exercism
/ruby/matrix/matrix.rb
UTF-8
354
3.421875
3
[]
no_license
# frozen_string_literal: true class Matrix attr_reader :matrix def initialize(raw_data) @matrix = raw_data.split(/\n/) end def rows matrix.map { |m| m.split(' ').map(&:to_i) } end def columns (0..matrix.size - 1).reduce([]) do |acc, index| new_col = rows.map { |r| r[index] } acc.append(new_col) end end end
true
71baf3ae46a160ed2589b263fd262c780e27a3bb
Ruby
dhuh/sample_app
/shuffle.rb
UTF-8
64
2.515625
3
[]
no_license
class String def shuffle s.split('').shuffle.join end end
true
9658e2ebd0d9b1d46c28d4697e411ee16227e13c
Ruby
J-Y/RubyQuiz
/ruby_quiz/quiz126_sols/solutions/Daniel Martin/fizzbuzz2.rb
UTF-8
1,364
3.4375
3
[ "MIT" ]
permissive
# A> I CAN HAS INTERVIEW? I ARE ADVANCED PROGRAMMER. # # B> O HAI. U CAN HAS CALLCC? GIMMEH FIZZBUZZ SOLUTION! f_=b_=nil callcc { |o| loop do o = callcc {|i|f_=i; o[:Fizz]} 2.times{o = callcc{|i|f_=i;o[]}} end } callcc { |o,n| loop do o,n = callcc {|i|b_=i; o["#{n}Buzz"]} 4.times{o,n = callcc{|i|b_=i;o[n]}} end } f = lambda{callcc{|i|f_[i]}} b = lambda{|n|callcc{|i|b_[i,n]}} 1.upto(100){|i|puts b[f[]]||i} # B> KTHX. U CAN HAS THREADS? a = nil f = Thread.new { loop { sleep 3; print :Fizz; a = nil } } b = Thread.new { sleep 0.2; loop { sleep 5; print :Buzz; a = nil } } sleep 0.5 1.upto(100) {|i| a=i; sleep 1; puts "#{a}"} # B> LOL. UR CODE IS TEH SLOW # # A> I MADE U ONE WITH SEMAPHORE BUT I EATED IT. # # B> U CAN HAS INJECT? a='_//_/_//_/_'.gsub('_','Fizz').split('/') b='/_///_//_'.gsub('_','Buzz').split('/') class Array def roll self.push(self.shift).last end end (1..101).select{|n|(n%5)*(n%3)>0}.inject(0){|r,n| puts "#{a.roll}#{b.roll}" while n>r+=1 puts n if n<99 r } # B> I SEE WHAT YOU DID THERE # # A> WHAT YOU SAY !! # # B> U CAN HAS INJECT, RLY? NOT ALL SIDE EFFECTZ? (1..100).inject("x"){|p,n| p.sub(/^((?:(?:x[^x]*){3})*)$/,'\1Fizz'). sub(/^((?:(?:x[^x]*){5})*)$/,'\1Buzz'). sub(/x$/,"x#{n}") + 'x' }.sub(/^x/,'').gsub(/x/,"\n").display # B> KTHXBYE # # A> I CAN HAS PHONE CALL? PLZ?
true
ef6a7ce45f71d89be758d5c358d7927f1b9984a6
Ruby
samsara/samsara
/clients/ruby/lib/samsara_sdk/client.rb
UTF-8
2,044
2.984375
3
[ "Apache-2.0" ]
permissive
require 'samsara_sdk/config' require 'samsara_sdk/publisher' require 'samsara_sdk/ring_buffer' require 'samsara_sdk/event' # Samsara SDK module SamsaraSDK # A client for ingesting events into Samsara. # It is the main interface to communicate with Samsara API. class Client # initialize # # @param config [Hash] Configuration overrides. # @raise [SamsaraSDK::ConfigValidationError] if any config option is incorrect. def initialize(config) Config.setup! config @publisher = Publisher.new @queue = RingBuffer.new(Config.get[:max_buffer_size]) @activity = Thread.new { publishing_activity } if Config.get[:start_publishing_thread] end # Publishes given events list to Ingestion API immediately. # # @param events [Array<Hash>] List of events. # @return [Boolean] The result of publish operation. # @raise [SamsaraSDK::EventValidationError] if any option of the given event is invalid. # @see http://samsara-analytics.io/docs/design/events-spec Event specification def publish_events(events) events = events.map { |event| Event.validate(Event.enrich(event)) } @publisher.post events end # Pushes event to internal events' queue. # # @param event [Hash] Event data. # @option data [String] :eventName Name of the event. # @option data [String] :sourceId Source ID of the event. # @option data [Integer] :timestamp Timestamp in milliseconds. # @see http://samsara-analytics.io/docs/design/events-spec Event specification def record_event(event) event = Event.validate(Event.enrich(event)) @queue << event end private # Publishing activity. # Represents an infinite loop that periodically posts queued events to Ingestion API. # Used in a background thread. def publishing_activity loop do @queue.flush { |data| @publisher.post data } if @queue.count >= Config.get[:min_buffer_size] sleep Config.get[:publish_interval_ms] / 1000 end end end end
true
b80cedddecd0b4d038e8af1a796ee044db14d780
Ruby
deanscottg/programming-univbasics-4-crud-lab-nyc01-seng-ft-080320
/lib/array_crud.rb
UTF-8
851
3.828125
4
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def create_an_empty_array empty_array = Array.new end def create_an_array four_empty_array = Array.new(4) end def add_element_to_end_of_array(array, element) array.push(element) p array end def add_element_to_start_of_array(array, element) array.unshift(element) p array end def remove_element_from_end_of_array(array) array.pop end def remove_element_from_start_of_array(array) array.shift end def retrieve_element_from_index(array, index_number) retrieved_element = array[index_number] p retrieved_element end def retrieve_first_element_from_array(array) first_element = array.shift p first_element end def retrieve_last_element_from_array(array) last_element = array.pop p last_element end def update_element_from_index(array, index_number, element) array[index_number] = element p element end
true
f20600864ebdc5ac96c58580c5e8b3ff43e942c4
Ruby
alanlong9278/bindo-test
/data/generate_data.rb
UTF-8
521
3.21875
3
[ "MIT" ]
permissive
require 'json' def get_random_string(random_length) o = [('a'..'z'), ('A'..'Z')].map(&:to_a).flatten (0...random_length).map { o[rand(o.length)] }.join end rb_hash = JSON.parse('{ "data": []}') (0...200).map do |number| id = number name = get_random_string(5) age = rand(100) phone = (0...13).map { rand(9) }.join phrase = get_random_string(200) user = { id: id, name: name, age: age, phone: phone, phrase: phrase } rb_hash["data"] << user end open('user.json', 'w') do |f| f << rb_hash.to_json end
true
426ead8bc5f0500c110b47f913eecb4530f8213c
Ruby
mikisvaz/xmipp-www
/lib/xmipp.rb
UTF-8
1,551
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
module XMIPP BIN_DIR = File.join(ENV['HOME'], 'software', 'opt', 'xmipp', 'bin') DEFAULT_OPTIONS = { "sigma" =>1.5, "initialSeeds" =>300, "growSeeds" =>30, "stop" =>0.001, "targetError" =>0.02, "dontAllowMovement" => false, "dontAllowIntensity" => false, "intensityColumn" => "occupancy", "minDistance" =>0.001, "penalty" =>10, "sampling_rate" =>1, } STRING_OPTIONS = { "intensityColumn" => %w(occupancy Bfactor) } def self.process_options(options) options.delete_if{|key, value| ! DEFAULT_OPTIONS.keys.include?(key.to_s)} options = Hash[*options.collect{|key, value| key = key.to_s case when Integer === DEFAULT_OPTIONS[key] || Float === DEFAULT_OPTIONS[key] value = value.to_f when FalseClass === DEFAULT_OPTIONS[key] || TrueClass === DEFAULT_OPTIONS[key] value = value == true else value = STRING_OPTIONS[key].include?(value) ? value : DEFAULT_OPTIONS[key] end [key, value] }.flatten] options = DEFAULT_OPTIONS.merge(options) options.delete_if{|key, value| ! value} options end def self.volume_to_pseudoatom(infile, outfile, options = {}) options = process_options(options) params = options.collect {|param, value| "-#{param} '#{value}'" } * " " cmd = "#{File.join(BIN_DIR, 'xmipp_convert_vol2pseudo')} #{params} -i #{infile} -o '#{outfile}' -thr 2" system(cmd) end end if __FILE__ == $0 XMIPP.volume_to_pseudoatom('test/data/PolAB_msk4.spi', 'tmp/PolAB_msk4', {}) end
true
cf8c76ced74e5df101e13e8f57d995d6606561a8
Ruby
kohbis/leetcode
/algorithms/1252.cells-with-odd-values-in-a-matrix/solution.rb
UTF-8
441
3.203125
3
[]
no_license
def odd_cells(n, m, indices) matrix = Array.new(n) { Array.new(m, 0) } count = 0 # apply the increment to all indices indices.each do |ind| ri, ci = ind[0], ind[1] # row matrix[ri].map! { |cell| cell = cell + 1 } # column matrix.each { |row| row[ci] = row[ci] + 1 } end # matrix.flatten.count {|cell| cell % 2 != 0 } matrix.each do |row| count += row.count { |cell| cell % 2 != 0 } end count end
true
97dce2807ec481d7d2ffe37afc699bb1bfb2d29c
Ruby
vuonga1103/ruby-oo-object-relationships-collaborating-objects-lab-nyc04-seng-ft-053120
/lib/song.rb
UTF-8
585
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require "pry" class Song attr_accessor :name, :artist @@all = [] def initialize(name) @name = name @@all << self end def self.all @@all end def artist_name=(artist_name_str) artist_object = Artist.find_or_create_by_name(artist_name_str) artist_object.add_song(self) end def self.new_by_filename(filename) filename = filename.split(' - ') song_name_from_file = filename[1] artist_name_from_file = filename[0] new_song = Song.new(song_name_from_file) new_song.artist_name = artist_name_from_file new_song end end
true
7c755c772b1df6dd5d044b4b27563abdb3fd1c41
Ruby
DouglasAllen/code-Programming_Ruby_3rd_ed
/Part_IV--Ruby_Library_Reference/ch27_Built-in_Classes_and_Modules/Alphabetical_Listing/Object/nil%3f-i.rb
UTF-8
331
2.71875
3
[]
no_license
=begin Object#nil? (from ~/.rdoc) ------------------------------------------------------------------------------ nil?() ------------------------------------------------------------------------------ call_seq: nil.nil? -> true <anything_else>.nil? -> false Only the object nil responds true to nil?. =end
true
69f7bda097b983f25b2469752d96797723e109b3
Ruby
kotikan/isis
/plugins/koticast/koticast.rb
UTF-8
1,012
2.796875
3
[]
no_license
# Returns the current weather forecast for Kotikan HQ require 'forecast_io' require 'yaml' class Koticast < Isis::Plugin::Base def respond_to_message?(message) @commands = message.downcase.split %w(!koticast !kotikast !willitrain !scanthesky).include? @commands[0] end def response_html forecast = koticast %Q(<strong>Weather at Kotikan: </strong>#{forecast[:minutely]} #{forecast[:hourly]} <a href="#{forecast[:url]}">Full report...</a>) end def response_text forecast = koticast 'Weather at Kotikan:' + forecast[:minutely] + ' ' + forecast[:hourly] end private def koticast ForecastIO.api_key = forecast_api_key lat, lon = 55.946802, -3.201294 forecast = ForecastIO.forecast(lat, lon) { minutely: forecast.minutely.summary, hourly: forecast.hourly.summary, url: %Q(http://forecast.io/#/f/#{lat},#{lon}) } end def forecast_api_key config = YAML.load_file(File.join(File.dirname(__FILE__), 'config.yml')) config["api_key"] end end
true
c897b91096b83b8d332f900e4af58c58ab2b131e
Ruby
chaosdorf/mete
/app/controllers/wrapped_controller.rb
UTF-8
2,639
2.546875
3
[ "MIT" ]
permissive
class WrappedController < ApplicationController # GET /user/1/wrapped def index @user = User.find(params[:user_id]) @years = Date.today.year.downto(2010) .select { |y| audits_for(@user, y).any? } # index.html.haml end # GET /users/1/wrapped/1970 def show @user = User.find(params[:user_id]) @year = Integer(params[:id]) audits = audits_for(@user, @year) @empty = audits.where.not(drink: nil).none? return if @empty @most_bought_drink = most_bought_drink(audits, @year) @caffeine = caffeine(audits) @most_active = most_active(audits) # wrapped.html.haml end private def audits_for(user, year) Audit .where(user: user) .where(created_at: Date.new(year, 01, 01)..Date.new(year, 12, 31)) end def most_bought_drink(audits, year) drink, count = audits.where.not(drink: nil) .reorder(nil).group(:drink).count.max_by { |_, v| v } user_more = audits_for(User.where(audit: true), year) .where(drink: drink).reorder(nil).group(:user).count .select { |_, v| v > count } .size { drink: drink, count: count, user_more: user_more } end def caffeine(audits) total = audits.joins(:drink).sum(:caffeine) if total.positive? # for humans: overdose: 1000 mg, intoxication: 5000 mg would_kill_kg = total / 192.0 # lethal dosage (mg) per kg puts would_kill_kg would_kill = case would_kill_kg when 0..0.025 then nil when 0.025..0.3 then 'hamster' when 0.3..0.4 then 'squirrel' when 0.4..0.9 then 'rat' when 0.9..2.5 then 'guinea pig' when 2.5..5 then 'lemur' when 5..9 then 'cat' when 9..13 then 'koala' when 13..23 then 'coyote' when 23..55 then 'lynx' when 55..81 then 'capybara' when 81..101 then 'jaguar' when 101..140 then 'reindeer' when 140..175 then 'gorilla' when 175..278 then 'lion' when 278..368 then 'bear' when 368..540 then 'moose' when 540..Float::INFINITY then 'bison' end end { total: total, would_kill: would_kill } end def most_active(audits) weekday_hour = audits.select(:created_at).map(&:created_at).map do |dt| { weekday: dt.strftime('%A'), hour: dt.hour } end weekday_hour.tally.max_by { |_, v| v }[0] end end
true
5b7106cd460abd6ac974cd5c57cf9464003c08b3
Ruby
Katy600/oyster_card_day4
/spec/journey_spec.rb
UTF-8
463
2.5625
3
[]
no_license
require 'journey' describe Journey do let(:bank) {double :bank, name: "bank", zone: 3} let(:angel) {double :angel, name: "angel", zone: 1} subject(:journey) {described_class.new(bank)} it 'has an entry station' do expect(journey.entry_station).to eq bank end context 'after touching out' do before do journey.end_journey(angel) end it 'has an exit station' do expect(journey.exit_station).to eq angel end end end
true
db1dc258cd03e4b43d033a0141f427aab3c62d17
Ruby
handiwiguna/alexa_rubyengine
/lib/alexa_rubyengine/verse_of_the_day_intent.rb
UTF-8
1,342
3.015625
3
[ "MIT" ]
permissive
#encoding: UTF-8 require 'date' require 'alexa_rubykit' class VerseOfTheDayIntent attr_reader :response VERSES = [ "John 3 verse 16. For God so loved the world that he gave his one and only Son, that whoever believes in him shall not perish but have eternal life", "Jeremiah 29 verse 11. For I know the plans I have for you, declares the LORD, plans to prosper you and not to harm you, plans to give you hope and a future", "Romans 8 verse 28. And we know that in all things God works for the good of those who love him, who have been called according to his purpose", "Philippians 4 verse 13. I can do everything through him who gives me strength", "Philippians 4 verse 6. Do not be anxious about anything, but in everything, by prayer and petition, with thanksgiving, present your requests to God", "Proverbs 3 verse 6. Trust in the LORD with all your heart and lean not on your own understanding", "Romans 12 verse 2. Do not conform any longer to the pattern of this world, but be transformed by the renewing of your mind. Then you will be able to test and approve what Gods will is his good, pleasing and perfect will" ] def initialize @response = AlexaRubykit::Response.new @day = Date.today.wday end def call(request) @response.add_speech(VERSES[@day]) @response end end
true
8a6a27d6203326d8870c676de07e0813dfd90b04
Ruby
hguitton/fs-hiring-test
/db/seeds.rb
UTF-8
1,478
2.796875
3
[ "MIT" ]
permissive
User.destroy_all Booking.destroy_all Room.destroy_all Motel.destroy_all # Create 3 users user2 = User.create(email: "user@two.dev", password: "123456") user1 = User.create(email: "user@one.dev", password: "123456") User.create(email: "user@none.dev", password: "123456") def motels_url "https://luvotels-hiring-api.herokuapp.com/motels.json" end def rooms_url(motel_id) "https://luvotels-hiring-api.herokuapp.com/motels/#{motel_id}/rooms.json" end def bookings_url(motel_id) "https://luvotels-hiring-api.herokuapp.com/motels/#{motel_id}/bookings.json" end # Load datas from API JSON.parse(RestClient.get(motels_url)).each_with_index do |motel, index| # User1 gets one motel, User2 gets the others index == 1 ? (owner = user1) : (owner = user2) Motel.create( id: motel["id"], name: motel["name"], logo: motel["logo"], user_id: owner.id ) JSON.parse(RestClient.get(rooms_url(motel["id"]))).each do |room| Room.create( id: room["id"], motel_id: room["motel_id"], name: room["name"], picture: room["picture"] ) end JSON.parse(RestClient.get(bookings_url(motel["id"]))).each do |booking| Booking.create( room_id: booking["room_id"], motel_id: booking["motel_id"], amount_centavos: booking["amount_centavos"], fee_percentage: booking["fee_percentage"], booking_period: booking["booking_period"], created_at: booking["created_at"], paid_at: booking["paid_at"], booking_code: booking["booking_code"], ) end end
true
fc7a176e9b08ad62708f59141844ea6e13b8a154
Ruby
antwebes/IrcSocket
/lib/com.adobe.lccs/sampleApps/ExternalAuthentication/rails/lib/lccs.rb
UTF-8
35,029
2.5625
3
[]
no_license
#!env ruby # # = Synopsis # # This library allows you to connect to the Adobe LiveCycle Collaboration Service and # manage an account, including listing rooms and templates, creating new rooms, and # deleting rooms and templates. # # == Examples # # require 'lccs' # # # # # Create a new account manager object using your account URL. This URL is displayed # # in the Developer Portal when you log in. # # # am = RTC::AccountManager.new("http://connectnow.acrobat.com/<YOUR DEVELOPER ACCOUNT NAME>") # # # # # Use the login method to log in with your developer account's username and password. # # # am.login(accountowner, accountpassword) # # # # # Use the keepalice method to keep the authentication token alive # # # am.keepalive(accountowner, accountpassword) # # # # # Use the provided methods to list, create, and delete rooms and templates on-the-fly. # # # rooms = am.listRooms() # templates = am.listTemplates() # am.createRoom("newRoom") # am.deleteRoom("newRoom") # am.createRoom("newRoom", "fromTemplate") # am.deleteTemplate("fromTemplate") # # # # # External authentication # # # session = am.getSession("room1") # secret = "account-shared-secret" # puts session.getAuthenticationToken(secret, "raff", "x-raff", 100) # puts session.getAuthenticationToken(secret, "bob", "x-bob", 50) # puts session.getAuthenticationToken(secret, "bill", "x-bill", 5) # # am.invalidateSession(session) # # # # # Account and room info # # # puts am.getAccountInfo() # puts am.getRoomInfo("room").inspect # puts am.getRoomInfo("accountident/room").inspect # # # # # Collection and node info # # # puts am.getNodeConfiguration("room", "CollectionName", "NodeName").inspect # puts am.fetchItems("room", "CollectionName", "NodeName").inspect # puts am.publishItem("room", "CollectionName", "NodeName", item) # # # # # Events handling # # # puts am.registerHook("http://hook.endpoint.url", "securityToken") # puts am.subscribeCollection("room", "CollectionName") # # = Revision # $Revision: #2 $ - $Date: 2010/06/30 $ # # = Author # # Raffaele Sena # # = Copyright # # ADOBE SYSTEMS INCORPORATED # Copyright 2007 Adobe Systems Incorporated # All Rights Reserved. # # NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the # terms of the Adobe license agreement accompanying it. If you have received this file from a # source other than Adobe, then your use, modification, or distribution of it requires the prior # written permission of Adobe. # require "base64" require "digest/md5" require "date" require "net/https" require "rexml/document" require "openssl" module RTC DEBUG = false VERSION = "$Revision: #2 $ - $Date: 2010/06/30 $" # # An error thrown or generated by the RTC API. # class Error < StandardError end # # Constants for common user roles. These are mirrored in the Room Console as well. # class UserRole NONE = 0 LOBBY = 5 VIEWER = 10 PUBLISHER = 50 OWNER = 100 end # # Constants for node configuration # class NodeConfiguration STORAGE_SCHEME_SINGLE_ITEM = 0 STORAGE_SCHEME_QUEUE = 1 STORAGE_SCHEME_MANUAL = 2 end ##################################################### # # A class that generates RTC authentication tokens. # class Authenticator def initialize(url) @authURI = URI.parse(url) end # # Get an RTC authentication token give login and password. # def login(user, password, authHeaders) headers = { "Content-Type" => "text/xml" }; data = """ <request> <username>#{user}</username> <password>#{password}</password> </request> """ resp = RTC::http_post(@authURI, data, headers) response = REXML::Document.new(resp).root if response.attributes['status'] == "ok" authToken = response.elements['authtoken'] if authToken.attributes['type'] == "COOKIE" authHeaders['Cookie'] = authToken.text token = nil else auth = authToken.text gak = Base64.encode64(auth).gsub("\n","") token = "gak=#{gak}" end puts "token: #{token}, auth:#{auth}, headers:#{authHeaders.inspect}" if RTC::DEBUG return token else raise RTC::Error, resp end end # # Get a guest authentication token. # def self.guestLogin(user) guk = Base64.encode64("g:#{user}:").gsub("\n","") return "guk=#{guk}" end end ##################################################### # # A class that deals with meeting sessions and # external authentication. # class Session # # Get an external authentication token. # def getAuthenticationToken(accountSecret, name, id, role) token = "x:#{name}::#{@account}:#{id}:#{@room}:#{role.to_i}" signed = "#{token}:#{sign(accountSecret, token)}" # unencoded #return "ext=#{signed}" # encoded enc = Base64.encode64(signed).gsub("\n","") return "exx=#{enc}" end # # Get the userId that the server will generate for this user # def getUserID(id) return "EXT-#{@account}-#{id}".upcase end #:stopdoc: def initialize(instance, account, room) begin @instance = instance.gsub(/#room#/, room) rescue @instance = instance end @account = account @room = room @digest = OpenSSL::Digest::Digest.new('SHA1') end def getSecret(baseURL, authToken, authHeaders) data = RTC::http_get("#{baseURL}app/session?instance=#{@instance}&#{authToken}", authHeaders) puts data if RTC::DEBUG response = REXML::Document.new(data).root @secret = response.elements['session-secret'].text end def invalidate(baseURL, authToken, authHeaders) data = "action=delete&instance=#{@instance}&#{authToken}" res = RTC::http_post("#{baseURL}app/session", data, authHeaders) puts res if RTC::DEBUG @instance = nil @account = nil @room = nil @digest = nil @secret = nil response = REXML::Document.new(res).root RTC::check_status response end def marshal_dump [@instance, @account, @room, @secret] end def marshal_load(data) @instance = data.shift @account = data.shift @room = data.shift @secret = data.shift @digest = OpenSSL::Digest::Digest.new('SHA1') end protected def sign(acctSecret, data) return OpenSSL::HMAC.hexdigest(@digest, "#{acctSecret}:#{@secret}", data) end #:startdoc:#: end ##################################################### # # A class that contains room or template item information. # class Item protected def initialize(name, desc, created) @name = name @desc = desc @created = DateTime.parse(created) end public attr_reader :name, :desc, :created alias_method :templatename, :desc end ##################################################### # # A class that contains room session info # class RoomInfo attr_accessor :isConnected, :userCount, :bytesUp, :bytesDown, :messages, :peakUsers, :dateCreated, :dateStarted, :dateEnded, :dateExpired end ##################################################### # # A class that contains account session info # class AccountInfo attr_accessor :userCount, :peakUserCount, :bytesUp, :bytesDown, :messages, :userTime, :dateCreated, :dateExpired, :activeRooms end ##################################################### # # A class that deals with account information and provisioning. # class AccountManager public ROOM_ITEMS = "meetings" TEMPLATE_ITEMS = "templates" def url @url end def contentURL "#{@baseURL}app/content#{@contentPath}" end def initialize(url) @url = url @authToken = nil @authHeaders = {} @authenticator = nil @baseURL = nil @contentPath = nil @roomInstance = nil puts VERSION if DEBUG do_initialize end # # Login and connect to the account # def login(user, password = nil) if password != nil @authToken = @authenticator.login(user, password, @authHeaders) else @authToken = Authenticator.guestLogin(user) end do_initialize end # # Keep the authentication token alive by accessing the account. # # If the requerst fails with an authentication error # and credentials are provided, this method will authenticated again # def keepalive(user = nil, password = nil) @contentPath = nil return true if do_initialize return login(user, password) if user return false end # # Create a room. If no template is specified, use the default, empty template. # def createRoom(room, template = nil) template = "default" if !template data = "mode=xml&room=#{room}&template=#{template}&#{@authToken}" res = RTC::http_post(@url, data, @authHeaders) puts res if RTC::DEBUG response = REXML::Document.new(res).root if response.local_name != "meeting-info" raise RTC::Error, res else return "ok" end end # # List rooms or templates. # def list(type = ROOM_ITEMS) case type when ROOM_ITEMS: when TEMPLATE_ITEMS: else raise RTC::Error, "invalid-type" end data = RTC::http_get("#{contentURL}/#{type}/?#{@authToken}", @authHeaders) items = Array.new response = REXML::Document.new(data).root response.elements.each("children/node") { |n| name = n.elements["name"].text desc = n.elements["properties/property[@name = 'cr:description']"] desc = desc.elements["value"].text if desc created = n.elements["properties/property[@name = 'jcr:created']"] created = created.elements["value"].text if created items.push(Item.new(name, desc, created)) } return items end # # Delete a room or a template. # def delete(item, type = ROOM_ITEMS, list = false) case type when ROOM_ITEMS: when TEMPLATE_ITEMS: else raise RTC::Error, "invalid-type" end durl = "#{contentURL}/#{type}/#{item}" if list limitCount = "" else limitCount = "&count=0" end data = "action=delete&response=inline#{limitCount}&#{@authToken}" res = RTC::http_post(durl, data, @authHeaders) puts res if RTC::DEBUG response = REXML::Document.new(res).root return response end # # List rooms. # def listRooms() return list(ROOM_ITEMS) end # # List templates. # def listTemplates() return list(TEMPLATE_ITEMS) end # # Delete a room. # def deleteRoom(r, list = false) raise RTC::Error, "parameter-required" if r.nil? return delete(r.downcase, ROOM_ITEMS, list) end # # Delete a template. # def deleteTemplate(t, list = false) raise RTC::Error, "parameter-required" if t.nil? return delete(t, TEMPLATE_ITEMS, list) end # # Return a room session for external authentication. # def getSession(room) session = Session.new(@roomInstance, url.split("/")[-1], room) session.getSecret(@baseURL, @authToken, @authHeaders) return session end # # Invalidate the room session. # def invalidateSession(session) session.invalidate(@baseURL, @authToken, @authHeaders) end # # Return the node configuration # def getNodeConfiguration(room, coll, node) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end path = "/#{coll}/nodes/#{node}/configuration" data = RTC::http_get("#{@baseURL}app/rtc?instance=#{instance}&path=#{path}&#{@authToken}", @authHeaders) puts data if RTC::DEBUG response = REXML::Document.new(data).root RTC::check_status response coll = response.elements["collections/node"] raise RTC::Error, "invalid-collection" if coll.nil? node = coll.elements["collection/nodes/node"] raise RTC::Error, "invalid-node" if node.nil? return RTC::from_xml(node.elements["collection/configuration"]) end # # Return the RTC nodes @ path. # def fetchItems(room, coll, node, items=nil) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end params = "instance=#{instance}&collection=#{coll}&node=#{node}" if !items.nil? items = items.to_a params << items.unshift("").join("&item=") if items.length > 0 end params << "&#{@authToken}" data = RTC::http_get("#{@baseURL}app/rtc?#{params}", @authHeaders) puts data if RTC::DEBUG response = REXML::Document.new(data).root RTC::check_status response coll = response.elements["collections/node"] raise RTC::Error, "invalid-collection" if coll.nil? node = coll.elements["collection/nodes/node"] raise RTC::Error, "invalid-node" if node.nil? return RTC::from_xml(node.elements["collection/items"]) end # # Register endpoint URL for webhooks # def registerHook(endpoint=nil, token=nil) acctid = @roomInstance.split("/")[0] data = "account=#{acctid}&action=registerhook" data << "&endpoint=#{RTC.url_escape(endpoint)}" if endpoint data << "&token=#{RTC.url_escape(token)}" if token data << "&#{@authToken}" res = RTC::http_post("#{@baseURL}app/rtc", data, @authHeaders) puts res if RTC::DEBUG response = REXML::Document.new(res).root RTC::check_status response end # # Unregister endpoint URL for webhooks # def unregisterHook return registerHook() end # # Return the webhook information # def getHookInfo() acctid = @roomInstance.split("/")[0] data = RTC::http_get("#{@baseURL}app/rtc?action=hookinfo&account=#{acctid}&#{@authToken}", @authHeaders) puts data if RTC::DEBUG response = REXML::Document.new(data).root RTC::check_status response return { 'endpoint' => response.elements["param[@name='registerHookEndpoint']"].text, 'token' => response.elements["param[@name='registerHookToken']"].text } end # # Subscribe to collection events # def subscribeCollection(room, collection, nodes=nil) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end params="collection=#{collection}" if !nodes.nil? nodes = nodes.to_a params << nodes.unshift("").join("&node=") if nodes.length > 0 end data = "instance=#{instance}&action=subscribe&#{params}&#{@authToken}" res = RTC::http_post("#{@baseURL}app/rtc", data, @authHeaders) puts res if RTC::DEBUG response = REXML::Document.new(res).root RTC::check_status response end # # Unsubscribe to collection events # def unsubscribeCollection(room, collection, nodes=nil) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end params="collection=#{collection}" if !nodes.nil? nodes = nodes.to_a params << nodes.unshift("").join("&node=") if nodes.length > 0 end data = "instance=#{instance}&action=unsubscribe&#{params}&#{@authToken}" res = RTC::http_post("#{@baseURL}app/rtc", data, @authHeaders) puts res if RTC::DEBUG response = REXML::Document.new(res).root RTC::check_status response end # # Publish an item # def publishItem(room, collection, node, item, overwrite = false) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end headers = { "Content-Type" => "text/xml" } headers.merge! @authHeaders params = "instance=#{instance}&action=publish&collection=#{collection}&node=#{node}" params << "&overwrite=true" if overwrite params << "&#{@authToken}" data = """ <request> #{RTC::to_xml(item, "item")} </request> """ res = RTC::http_post("#{@baseURL}app/rtc?#{params}", data, headers) puts res if RTC::DEBUG response = REXML::Document.new(res).root RTC::check_status response end # # Retract an item # def retractItem(room, collection, node, item) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end data = "instance=#{instance}&collection=#{collection}&node=#{node}&item=#{item}&#{@authToken}" res = RTC::http_post("#{@baseURL}app/rtc", data, @authHeaders) puts res if RTC::DEBUG response = REXML::Document.new(res).root RTC::check_status response end # # Create a node # def createNode(room, collection, node, configuration=nil) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end params = "instance=#{instance}&action=configure&collection=#{collection}&node=#{node}&#{@authToken}" if configuration headers = { "Content-Type" => "text/xml" } headers.merge! @authHeaders data = """ <request> #{RTC::to_xml(configuration, "configuration")} </request> """ res = RTC::http_post("#{@baseURL}app/rtc?#{params}", data, headers) else res = RTC::http_post("#{@baseURL}app/rtc", params, @authHeaders) end puts res if RTC::DEBUG response = REXML::Document.new(res).root RTC::check_status response end # # Remove a node or collection # def removeNode(room, collection, node=nil) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end data = "instance=#{instance}&action=remove&collection=#{collection}&node=#{node}&#{@authToken}" res = RTC::http_post("#{@baseURL}app/rtc", data, @authHeaders) puts res if RTC::DEBUG response = REXML::Document.new(res).root RTC::check_status response end # # Configure a node # def setNodeConfiguration(room, collection, node, configuration) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end headers = { "Content-Type" => "text/xml" } headers.merge! @authHeaders params = "instance=#{instance}&action=configure&collection=#{collection}&node=#{node}&#{@authToken}" data = """ <request> #{RTC::to_xml(configuration, "configuration")} </request> """ res = RTC::http_post("#{@baseURL}app/rtc?#{params}", data, headers) puts res if RTC::DEBUG response = REXML::Document.new(res).root RTC::check_status response end # # Set user role # def setUserRole(room, user, role, collection=nil, node=nil) begin instance = @roomInstance.gsub(/#room#/, room) rescue instance = @roomInstance end data = "action=setrole&instance=#{instance}&user=#{user}&role=#{role.to_i}" data << "&collection=#{collection}" if collection data << "&node=#{node}" if node data << "&#{@authToken}" res = RTC::http_post("#{@baseURL}app/rtc", data, @authHeaders) puts res if RTC::DEBUG response = REXML::Document.new(res).root RTC::check_status response end # # Return information about the account if it is active. # def getAccountInfo() acctid = @roomInstance.split("/")[0] data = RTC::http_get("#{@baseURL}app/account?account=#{acctid}&#{@authToken}", @authHeaders) puts data if DEBUG response = REXML::Document.new(data).root RTC::check_status response info = response.elements['account-info'] ainfo = AccountInfo.new ainfo.userCount = info.elements['user-count'].text.to_i ainfo.peakUserCount = info.elements['peak-user-count'].text.to_i ainfo.bytesUp = info.elements['total-bytes-up'].text.to_i ainfo.bytesDown = info.elements['total-bytes-down'].text.to_i ainfo.messages = info.elements['total-messages'].text.to_i ainfo.userTime = RTC::parseElapsed(info.elements['total-time'].text) ainfo.dateCreated = RTC::parseDateTime(info.elements['date-created'].text) ainfo.dateExpired = RTC::parseDateTime(info.elements['date-expired'].text) activeInstances = info.elements['active-FMS-instances'].text ainfo.activeRooms = activeInstances[1,activeInstances.length-2].split(",").map { |v| v.match(/.*\/(.*)/)[1] } return ainfo end # # Return information about the room or room instance if it is active. # def getRoomInfo(room) if room.include? '/' instance = room else instance = @roomInstance.gsub(/#room#/, room) end data = RTC::http_get("#{@baseURL}app/account?instance=#{instance}&#{@authToken}", @authHeaders) puts data if DEBUG response = REXML::Document.new(data).root RTC::check_status response info = response.elements['meeting-info'] rinfo = RoomInfo.new rinfo.isConnected = info.elements['is-connected'].text == 'true' rinfo.userCount = info.elements['user-count'].text.to_i rinfo.bytesUp = info.elements['total-bytes-up'].text.to_i rinfo.bytesDown = info.elements['total-bytes-down'].text.to_i rinfo.messages = info.elements['total-messages'].text.to_i rinfo.peakUsers = info.elements['peak-users'].text.to_i rinfo.dateCreated = RTC::parseDateTime(info.elements['date-created'].text) rinfo.dateStarted = RTC::parseDateTime(info.elements['date-started'].text) rinfo.dateEnded = RTC::parseDateTime(info.elements['date-ended'].text) rinfo.dateExpired = RTC::parseDateTime(info.elements['date-expired'].text) return rinfo end #:stopdoc: protected def do_initialize return true if @contentPath uri = URI.parse(@url) data = RTC::http_get("#{@url}?mode=xml&accountonly=true&#{@authToken}", @authHeaders) begin response = REXML::Document.new(data).root rescue raise RTC::Error, "invalid-account" end case response.local_name when 'meeting-info' : @baseURL = response.elements['baseURL'].attributes['href'] @url = URI.join(@baseURL, uri.path).to_s @contentPath = response.elements['accountPath'].attributes['href'] if (response.elements['room']) @roomInstance = response.elements['room'].attributes['instance'] end if DEBUG puts "url:#{url}" puts "contentURL:#{contentURL}" puts "roomInstance:#{@roomInstance}" end return true when 'result' : if response.attributes['code'] == "unauthorized" authURL = response.elements['authentication'].attributes['href'] if response.elements['baseURL'] @baseURL = response.elements['baseURL'].attributes['href'] @url = URI.join(@baseURL, uri.path).to_s authURL = URI.join(@baseURL, authURL).to_s if authURL[0].chr == '/' if DEBUG puts "baseURL:#{@baseURL}" puts "url:#{@url}" puts "authURL:#{authURL}" end end @authenticator = Authenticator.new(authURL) return false end end raise RTC::Error, data end #:startdoc: end #:stopdoc: protected # # Get data and follow redirects. # def RTC.http_get(url, headers = nil) while true puts "http_get #{url}" if DEBUG puts " #{headers.inspect}" if DEBUG && headers uri = (url.kind_of? URI) ? url : URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == "https" http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end path = uri.path path << "?#{uri.query}" if uri.query http.start { resp, body = http.get(path, headers) puts "Host: #{resp['X-Acorn-Hostname']}" if DEBUG && resp['X-Acorn-Hostname'] case resp when Net::HTTPRedirection then url = resp['location'] when Net::HTTPSuccess then return body else raise RTC::Error, resp.code end } end end def RTC.http_post(url, data, headers = nil) puts "http_post #{url} #{data}" if DEBUG puts " #{headers.inspect}" if DEBUG && headers uri = (url.kind_of? URI) ? url : URI.parse(url) http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == "https" http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end path = uri.path path << "?#{uri.query}" if uri.query http.start { resp, body = http.post(path, data, headers) puts "Host: #{resp['X-Acorn-Hostname']}" if DEBUG && resp['X-Acorn-Hostname'] if resp.kind_of? Net::HTTPSuccess return body else raise RTC::Error, resp.code end } end def RTC.check_status(response) status = response.elements['status'] code = status.attributes['code'] subcode = status.attributes['subcode'] return code if code == "ok" raise RTC::Error, subcode.nil? ? code : subcode end def RTC.url_escape(url) url.gsub(/([^ a-zA-Z0-9_.-]+)/n) do '%' + $1.unpack('H2' * $1.size).join('%').upcase end.tr(' ', '+') end def RTC.to_xml(hash, root=nil) result = "" if root if root == 'item' id = hash.has_key?('itemID') ? hash['itemID'] : 'item' result << "<#{root} id=\"#{id}\">" else result << "<#{root}>" end end hash.each { |name,value| if root == 'configuration' result << "<field var=\"#{name}\">" else result << "<property name=\"#{name}\">" end type = if value.is_a? Fixnum "int" elsif value.is_a? Bignum "long" elsif value.is_a? Float "double" elsif value.is_a? String "string" elsif value.is_a?(TrueClass) || value.is_a?(FalseClass) "boolean" elsif value.is_a? Hash "object" elsif value.is_a? Array "array" else "undefined:#{value.class}" end result << "<value type=\"#{type}\">" if value.is_a?(Hash) #|| value.is_a?(Array) result << RTC::to_xml(value) elsif value.is_a? String result << REXML::Text.new(value, true).to_s else result << value.to_s end result << "</value>" if root == 'configuration' result << "</field>" else result << "</property>" end } result << "</#{root}>" if root return result end def RTC.from_xml(xml) hash = {} xml.each { |e| if e.local_name == 'item' name = e.attributes['id'] value = RTC::from_xml e else if e.local_name == 'field' name = e.attributes['var'] # field else name = e.attributes['name'] # property end v = e.elements['value'] if v type = v.attributes['type'] value = v.text case type when "boolean": value = (value == "true") when "int", "long": value = value.to_i when "double": value = value.to_f when "xml": value = REXML::Document.new(value).root when "object": value = RTC::from_xml v when "array": value = RTC::from_xml v end else value = nil end end hash[name] = value } return hash end # # parse a date/time # returns a DateTime # def RTC.parseDateTime(s) return nil if s.nil? return nil if s == 'NULL' #return DateTime.strptime(s, fmt='%a %b %d %H:%M:%S %Z %Y') return DateTime.parse(s) end # # parse elapsed time (days hh:mm:ss.xxx) # returns number of seconds # def RTC.parseElapsed(s) return nil if s.nil? return nil if s == 'NULL' empty,d,h,m,s = s.split(/\s*(\d+) (\d\d):(\d\d):(\d\d).*/) return (d.to_i*24 + h.to_i)*3600 + m.to_i*60 + s.to_i end #:startdoc: end # module RTC if __FILE__ == $0 def usage puts "usage: #{$0} [--debug] [--host=url] account user password command parameters..." puts "" puts "where <command> is:" puts " --list" puts " --create room [template]" puts " --delete room" puts " --delete-template template" puts " --ext-auth secret room username userid role" puts " --invalidate room" puts "" puts " --get-node-configuration room collection node" puts " --fetch-items room collection node" puts " --register-hook endpoint [token]" puts " --unregister-hook" puts " --hook-info" puts " --subscribe-collection room collection" puts " --unsubscribe-collection room collection" puts " --create-node room collection [node]" puts " --remove-node room collection [node]" puts " --set-user-role room userID role [collection [node]]" puts " --publish-item room collection node itemID body" puts " --retract-item room collection node itemID" exit 1 end def getRole(r) case r.downcase when "none" ; return RTC::UserRole::NONE when "lobby" ; return RTC::UserRole::LOBBY when "viewer" ; return RTC::UserRole::VIEWER when "publisher" ; return RTC::UserRole::PUBLISHER when "owner" ; return RTC::UserRole::OWNER else return r.to_i end end host = "http://connectnow.acrobat.com" while ARGV.length > 0 case ARGV[0] when /--host=(.*)/: host = Regexp.last_match[1] when "--debug": RTC::DEBUG = true else break end ARGV.shift end if ARGV.length < 3 usage end accountName = ARGV.shift username = ARGV.shift password = ARGV.shift accountURL = "#{host}/#{accountName}" puts "account: #{accountURL}" if RTC::DEBUG begin am = RTC::AccountManager.new(accountURL) am.login(username, password) if ARGV.length == 0 ARGV[0] = "--list" end while ARGV.length > 0 case ARGV.shift when "--list"; puts "==== template list for #{accountName} ====" am.listTemplates().each { |t| puts "#{t.name}:#{t.created.asctime}" } puts "==== room list for #{accountName} ====" am.listRooms().each { |r| puts "#{r.name}:#{r.templatename}:#{r.created.asctime}" } when "--create"; # # Create a room. # room = ARGV.shift template = if ARGV.length > 0; then ARGV.shift else nil end puts am.createRoom(room, template) when "--delete"; # # Delete a room. # room = ARGV.shift puts am.deleteRoom(room) when "--delete-template"; # # Delete a template. # template = ARGV.shift puts am.deleteTemplate(template) when "--ext-auth"; # # Get a session and create external authentication tokens. # secret = ARGV.shift room = ARGV.shift user = ARGV.shift userId = ARGV.shift if ARGV.length > 0 role = getRole(ARGV.shift) else role = RTC::UserRole::LOBBY end sess = am.getSession(room) puts sess.getAuthenticationToken(secret, user, userId, role) puts "userID: #{sess.getUserID(userId)}" when "--invalidate"; # # Invalidate a session. # room = ARGV.shift sess = am.getSession(room) puts am.invalidateSession(sess) when "--info"; # # Get account or room session information. # if ARGV.length == 0 puts am.getAccountInfo().inspect else room = ARGV.shift puts am.getRoomInfo(room).inspect end when "--get-node-configuration"; room = ARGV.shift collection = ARGV.shift node = ARGV.shift puts am.getNodeConfiguration(room, collection, node).inspect when "--fetch-items"; room = ARGV.shift collection = ARGV.shift node = ARGV.shift items = ARGV puts am.fetchItems(room, collection, node, items).inspect ARGV.clear when "--subscribe-collection"; room = ARGV.shift collection = ARGV.shift nodes = ARGV puts am.subscribeCollection(room, collection, nodes) ARGV.clear when "--unsubscribe-collection"; room = ARGV.shift collection = ARGV.shift nodes = ARGV puts am.unsubscribeCollection(room, collection, nodes) ARGV.clear when "--register-hook"; endpoint = ARGV.length > 0 ? ARGV.shift : nil token = ARGV.length > 0 ? ARGV.shift : nil puts am.registerHook(endpoint, token) ARGV.clear when "--unregister-hook"; puts am.registerHook() when "--hook-info"; puts am.getHookInfo().inspect when "--create-node"; room = ARGV.shift collectionName = ARGV.shift nodeName = ARGV.length > 0 ? ARGV.shift : nil puts am.createNode(room, collectionName, nodeName) when "--remove-node"; room = ARGV.shift collectionName = ARGV.shift nodeName = ARGV.length > 0 ? ARGV.shift : nil puts am.removeNode(room, collectionName, nodeName) when "--set-user-role"; room = ARGV.shift userID = ARGV.shift role = getRole(ARGV.shift) collectionName = ARGV.length > 0 ? ARGV.shift : nil nodeName = ARGV.length > 0 ? ARGV.shift : nil puts am.setUserRole(room, userID, role, collectionName, nodeName) when "--publish-item"; room = ARGV.shift collectionName = ARGV.shift nodeName = ARGV.shift itemID = ARGV.shift body = ARGV.shift itemVO = { "itemID" => itemID, "body" => body } puts am.publishItem(room, collectionName, nodeName, itemVO) when "--retract-item"; room = ARGV.shift collectionName = ARGV.shift nodeName = ARGV.shift itemID = ARGV.shift puts am.retractItem(room, collectionName, nodeName, itemID) else usage() end end rescue RTC::Error => e puts "Error: #{e.message}" end end
true
79af87baddef40f5980edc36a0994a601522141f
Ruby
henriquegavabarreto/sokoban
/lib/game_objects/helpers/movable.rb
UTF-8
3,045
3.5625
4
[]
no_license
require_relative './positioning' class Movable include Positioning attr_reader :size, :original_position, :target_position, :sprite, :current_direction, :distance_to_travel, :start_x, :start_y, :steps, :position_over_time def initialize(sprite, size) @size = size @sprite = sprite @start_x = sprite.x @start_y = sprite.y @is_moving = false @speed = 130 @current_direction = { x: 1, y: 0 } @distance_to_travel = 0 @total_traveled_distance = 0 @steps = 0 @position_over_time = [] add_to_position_over_time end def set_target_position @target_position = { x: self.x + (@size * @current_direction[:x]), y: self.y + (@size * @current_direction[:y]) } end def set_original_position @original_position = { x: self.x, y: self.y } end def set_direction(x, y) @current_direction = { x: x, y: y } end def target_x @target_position ? self.target_position_center[:x] : nil end def target_y @target_position ? self.target_position_center[:y] : nil end def is_moving? @is_moving end def target_position_center { x: @target_position[:x] + @size / 2, y: @target_position[:y] + @size / 2 } end def set_destination(x, y) # destination is only set if object is still return if @distance_to_travel > 0 @distance_to_travel = @size self.set_direction(x, y) self.set_target_position self.set_original_position end def cancel_movement @distance_to_travel = 0 end # the method below could be applied to move a box # moves the character in the facing direction or stops its motion if @target_position is reached def move(dt) return if @distance_to_travel == 0 traveled_distance = 0 unless @current_direction[:x] == 0 then traveled_distance = @current_direction[:x] * @speed * dt else traveled_distance = @current_direction[:y] * @speed * dt end if @total_traveled_distance + traveled_distance.abs < @distance_to_travel @is_moving = true unless @current_direction[:x] == 0 then @sprite.x += traveled_distance else @sprite.y += traveled_distance end @total_traveled_distance += traveled_distance.abs else self.end_movement end end def end_movement self.position(@target_position[:x], @target_position[:y]) @is_moving = false @total_traveled_distance = 0 @distance_to_travel = 0 @target_position = nil end def add_to_position_over_time @position_over_time << { x: self.x, y: self.y } end def slice_position_over_time(n) @position_over_time.slice!(n + 1, @position_over_time.count) end def reset_position_over_time slice_position_over_time(0) end end
true
036a5a9d42714fb88549513e4969652f2ecec088
Ruby
yooonsj/helloworld_ruby
/container&loop/ex04.rb
UTF-8
227
3.25
3
[]
no_license
puts('아이디를 입력하세요.') input_id = gets.chomp() members = ['egoing', 'leezche', 'grapittie'] for member in members do if member == input_id puts('Hello!, ' + member) exit end end puts('Who are you?')
true
11232f586e0b5d64c123f5eaec85d7ef7ded60fd
Ruby
turnon/gzlib
/test/gzlib_test.rb
UTF-8
1,231
2.765625
3
[]
no_license
require 'minitest_helper' require 'gzlib' class TestGzlib < Minitest::Test def test_has_ruby_book score_ruby = Gzlib.search 'ruby', sortWay: 'score' assert_match /^ruby/i, score_ruby.first.title end def test_one_isbn_one_book matz_ruby = Gzlib.search '9787115366467', searchWay: 'isbn' assert_equal 1, matz_ruby.count end def test_convenient_method matz_ruby = Gzlib::Search.isbn '9787115366467' assert_equal 1, matz_ruby.count end def test_convenient_method_accept_options_not_just_keyword ruby_books = Gzlib::Search.send :title, 'ruby', rows: 500 assert 50 < ruby_books.count assert_equal 1, ruby_books.curPage end def test_pages @ruby = Gzlib.search 'ruby', rows: 10 has_10_pages_more_result has_book_id can_fetch_book_in_next_page can_fetch_books_until_last_page end private def has_10_pages_more_result assert @ruby.pages > 5 end def has_book_id assert (not @ruby.first.id.nil?) end def can_fetch_book_in_next_page assert @ruby.any?{ |book| book.title.match /Effective Ruby/ } assert @ruby.curPage > 1 end def can_fetch_books_until_last_page assert @ruby.total > 50 assert @ruby.lastPage? end end
true
46f83c7134b93a3dcfb229274b2fccbcc51850d4
Ruby
christjin/rate_limiter
/lib/rate_limiter/rule.rb
UTF-8
506
2.578125
3
[ "MIT" ]
permissive
module RateLimiter class Rule attr_reader :name, :limit, :period, :block def initialize(name, options, block) @name, @block = name, block @limit = options[:limit] @period = options[:period] end def cache RateLimiter.cache end def against_by?(request) discriminator = block.call(request) return false unless discriminator key = "#{name}:#{discriminator}" count = cache.count(key, period) count > limit end end end
true
1dca6516869e2f9e9075366689c57abb8c426942
Ruby
tribbyfam/learning-Ruby
/Practice/library_book/code/Ch 7 programs/7-1.rb
UTF-8
1,355
4.15625
4
[]
no_license
#!/usr/bin/ruby # 35 students in our class NUM_STUDENTS = 35 # Max grade of 100% MAX_GRADE = 100 num_compare = 0 arr = Array.new(NUM_STUDENTS) # Randomly populate arr for i in 0..(NUM_STUDENTS - 1) # Maximum possible grade is 100%, keep in mind that rand(5) returns possible values 0-4, so we must add 1 to MAX_GRADE arr[i] = rand(MAX_GRADE + 1) end # Output current values of arr puts "Input list:" for i in 0..(NUM_STUDENTS - 1) puts "arr[" + i.to_s + "] ==> " + arr[i].to_s end # Now let's use a selection sort. # We first find the lowest number in the array and then we move it to the beginning of the list for i in 0..(NUM_STUDENTS - 2) min_pos = i for j in (i + 1)..(NUM_STUDENTS - 1) num_compare = num_compare + 1 if (arr[j] < arr[min_pos]) min_pos = j end end # Now that we know the min, swap it with the current first element (at position i) temp = arr[i] arr[i] = arr[min_pos] arr[min_pos] = temp end # Now output the sorted array puts "Sorted list:" for i in 0..(NUM_STUDENTS - 1) puts "arr[" + i.to_s + "] ==> " + arr[i].to_s end puts "Number of Comparisons ==> " + num_compare.to_s
true
b0d558f8a0f6085c77d8840ad518012e6a0e11fd
Ruby
fhernandez173/keys-of-hash-001
/lib/keys_of_hash.rb
UTF-8
1,101
3.578125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' {"sugar glider"=>"Australia", "aye-aye"=>"Madagascar", "red-footed tortoise"=>"Panama", "kangaroo"=>"Australia", "tomato frog"=>"Madagascar", "koala"=>"Australia"} # class Hash # def keys_of(*arguments) # animal_array = [] # self.collect do |animal, habitat| # # puts "#{habitat} : #{animal}" # # binding.pry # arguments.collect do |i| # # binding.pry # # if i == habitat # # puts animal # # end # if arguments.join == habitat # animal # end # # binding.pry # end # end # end # # animal_array # # binding.pry # end =begin self.values.each do |habitat| if habitat == arguments.join puts habitat end end =end class Hash def keys_of(*countries) animals = [] countries.each do |country| self.each do |animal, habitat| animals << animal if country == habitat end end animals end end # iterate through arguments first, then iterate through the values # then push then into an array after iterating through # # #
true
af870857594cada44e28eb6fe64dce29df11ec2e
Ruby
paulo-silva/conta_azul_api
/lib/conta_azul_api/product.rb
UTF-8
966
2.546875
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'ostruct' require 'conta_azul_api/models' module ContaAzulApi class Product < ::ContaAzulApi::Models class NotFound < StandardError; end PRODUCT_ENDPOINT = 'v1/products' MAX_PRODUCTS_PER_PAGE = 1000 def self.find(product_id) product_response = ContaAzulApi::Request.new.get( endpoint: "#{PRODUCT_ENDPOINT}/#{product_id}", authorization: request_authorization ) raise NotFound if product_response.status_code == :not_found OpenStruct.new(product_response.body) end def self.all products_response = ContaAzulApi::Request.new.get( endpoint: "#{PRODUCT_ENDPOINT}?size=#{MAX_PRODUCTS_PER_PAGE}", authorization: request_authorization ) products_response.body.map { |product| OpenStruct.new(product) } end def self.filter_by(name:) products = all products.select { |product| product.name.include?(name) } end end end
true
b14aa98ec446e238b56190c5a94f44b88ffe1f89
Ruby
chet-k/DSA-Problems
/cookie_distribution.rb
UTF-8
300
2.96875
3
[]
no_license
def find_content_children(g, s) cookies_handed_out = 0 g.sort! s.sort! gi = g.length - 1 s.reverse.each do |cookie| gi -= 1 until gi < 0 || g[gi] <= cookie break if gi < 0 cookies_handed_out += 1 gi -= 1 end cookies_handed_out end
true
4e5f78f23269f47ddebe9d75a2eb2f26854fc2d3
Ruby
pvhungpd01220/RubyLearn
/rubyTraining/ex2_array.rb
UTF-8
1,114
3.546875
4
[]
no_license
array = [1, 2, 3, 4, 5, 6, 7, 8, 9] #dem so chia het cho 4 biendem = 0 array.each do |item| if item % 4 == 0 biendem = biendem + end end p biendem #e #ex 3 tính tổng của 4 phần tử đầu của array arr = array[0..3] p arr.sum #ex 4 Tính tổng của phần tử đầu và phần tử cuối sau đó thêm vào đầu array array = [1, 2, 3, 4, 5, 6, 7, 8, 9] tong = array[0] + array[-1] array << tong p array #ex 5 Update array với mỗi phần tử cộng lên 1 array = [1, 2, 3, 4, 5, 6, 7, 8, 9] array.map! { |x| x + 1 } p array array = [1, 2, 3, 4, 5, 6, 7, 8, 9] biendem = 0 array.each do biendem = biendem + 1 end p biendem #ex6 tim so lon nhat va so nho nhat trong mang array = [1, 20, 3, 4, 5, 6, 7, 8, 9] #dau dien cho ra phan tu dau tien cua mang array[0] result = array[0] #sau do cho bien dem result = phan tu dau tien cua mang array[1..-1].each do |item| #cho vao result duyetj tung phan tu cua array so nao lon nhat thi if result < item #cho ket qua bang item roi in ra result = item end end p resultit
true
7598bc18f6a99f58d9c7b44dd380ac284abe4a3e
Ruby
michaelciletti/minedmindskata
/test_mm.kata.arrays.rb
UTF-8
247
2.578125
3
[]
no_license
require "minitest/autorun" require_relative "mm.kata.arrays.rb" class TestMinedMindsKata < Minitest::Test def test_1_returns_1 assert_equal(1,1) end def test_1_array_length results = minedmindskata() assert_equal(100,results.count) end end
true
383349fb93ac613d76b2e7822929184d50944a72
Ruby
tvw/simple_sheets
/lib/simple_sheets/data.rb
UTF-8
296
2.828125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
module SimpleSheets class Data def initialize(fh, content = nil) @content = content fh.puts "<Data#{type}>#{@content}</Data>" end def type return ' ss:Type="Number"' if @content.is_a?(Fixnum) or @content.is_a?(Float) ' ss:Type="String"' end end end
true
6f773cb622bfa80d64f969832a2d549170652d57
Ruby
brightshiny/whiskey
/app/models/item_for_display.rb
UTF-8
965
2.71875
3
[]
no_license
class ItemForDisplay < ActiveRecord::BaseWithoutTable attr_accessor :id, :title, :description, :link, :author, :feed_name, :feed_link, :published_at def initialize(item) @id = KEY.url_safe_encrypt64(item.id) @title = item.title @description = ItemForDisplay.clean(item.content) @link = item.link @feed_name = item.feed.title @feed_link = item.feed.link @published_at = item.published_at @author = item.author end def self.convert_items(array_of_items) a = [] array_of_items.each { |item| i = ItemForDisplay.new(item) a.push({ :id => i.id, :title => i.title, :description => i.description, :link => i.link, :author => i.author, :feed_name => i.feed_name, :feed_link => i.feed_link, :published_at => i.published_at.strftime('%m/%d/%Y %I:%M%p') }) } return a end def self.clean(text) text end end
true
45f0a2acd1974d52754ab3e887701178df91aeba
Ruby
dball1126/Coding_problems
/ruby/is_same_tree.rb
UTF-8
876
3.625
4
[]
no_license
def is_same_tree(p, q) queue = [p, q] while queue.length > 0 t1 = queue.shift t2 = queue.shift return false if t1.val != t2.val return false if !t1.left.nil? && t2.left.nil? return false if t1.left.nil? && !t2.left.nil? return false if !t1.right.nil? && t2.right.nil? return false if t1.right.nil? && !t2.right.nil? queue.push(t1.left, t2.left) if !t1.left.nil? queue.push(t1.right, t2.right) if !t1.right.nil? end return true end class TreeNode attr_accessor :val, :left, :right def initialize(val) @val = val @left, @right = nil, nil end end node1 = TreeNode.new(1) node2 = TreeNode.new(1) node3 = TreeNode.new(2) node4 = TreeNode.new(3) node1.left = node3 node1.right = node4 node2.left = node3 node2.right = node4 p is_same_tree(node1, node2)
true
775e5e026ff4597a5380ba9db7d9b6cee05ab91b
Ruby
asceth/bbcoder
/lib/bbcoder/configuration.rb
UTF-8
400
2.578125
3
[ "MIT" ]
permissive
class BBCoder class Configuration attr_accessor :tags def initialize @tags = {} end def [](value) @tags[value] end def clear @tags = {} end def remove name @tags.delete(name.to_sym) end def tag(name, options = {}, &block) @tags[name.to_sym] = BBCoder::Tag.new(name.to_sym, options.merge(:block => block)) end end end
true
98b94ed73ab5da6983413a8fed5b2b25162434f5
Ruby
tflecht/calendarized_reports
/lib/end_of_days.rb
UTF-8
436
2.921875
3
[]
no_license
require 'singleton' require 'reporting/date_extreme' module Reporting # EndOfDays is a fake datestamp that occurs _after_ all other date values. class EndOfDays < DateExtreme include Comparable include Singleton ## # The EndOfDays always comes after +other+! def <=>(other) 1 end def to_s # :nodoc: "<END OF DAYS>" end end END_OF_DAYS = EndOfDays.instance end # module Reporting
true
b9ab03d0f9258eaaae68420f1297e70cb404b8ad
Ruby
ambtus/mobile-pages
/app/models/filter.rb
UTF-8
5,545
2.546875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Filter LIMIT = 5 # number of pages to show in index def self.tag(name, start) Rails.logger.debug "Filter.tag(#{name}, #{start})" tag = Tag.find_by_name(name) tag = Tag.find_by_short_name(name) unless tag tag.pages.order('read_after ASC').limit(start + LIMIT)[start..-1] end def self.new(params={}) Rails.logger.debug "Filter.new(#{params})" pages = Page.all if params[:soon] if params[:soon] == "Now" pages = pages.where(soon: [-1,0,1,2]) elsif params[:soon] == "Never" pages = pages.where(soon: [3,4,5]) else index = Soon::LABELS.index(params[:soon]) -1 pages = pages.where(soon: index) end end pages = pages.where(:type => (params[:type] == "none" ? nil : params[:type])) if params[:type] unless params[:type] == "all" # ignore parts unless asking for a type or a url or a title or a fandom or sorting on last_created # TODO should this be an if, instead of an unless? blacklist or whitelist? unless params[:type] || params[:url] || params[:title] || params[:fandom] || params[:sort_by] == "last_created" pages = pages.where(:parent_id => nil) end # ignore parts if filtering on size unless you've chosen a type pages = pages.where(:parent_id => nil) if params[:size] && !params[:type] pages = pages.where(:last_read => nil) if params[:unread] == "Unread" pages = pages.where(:last_read => Page::UNREAD_PARTS_DATE) if params[:unread] == "Parts" pages = pages.where.not(:last_read => [nil, Page::UNREAD_PARTS_DATE]) if params[:unread] == "Read" pages = pages.where(:stars => params[:stars]) unless params[:stars].to_i == 0 pages = pages.where(:stars => [5,4]) if params[:stars] == "Better" pages = pages.where(:stars => [2,1]) if params[:stars] == "Worse" pages = pages.where(:stars => [9]) if params[:stars] == "unfinished" pages = pages.where(:size => params[:size]) if Page::SIZES.include?(params[:size]) pages = pages.where(:size => ["short", "drabble"]) if params[:size] == "Shorter" pages = pages.where(:size => ["long", "epic"]) if params[:size] == "Longer" [:title, :notes, :my_notes].each do |attrib| pages = pages.where("LOWER(pages.#{attrib.to_s}) LIKE ?", "%#{params[attrib].downcase}%") if params.has_key?(attrib) end if params.has_key?(:url) # strip the https? in case it was stored under the other pages = pages.where("pages.url LIKE ?", "%#{params[:url].sub(/^https?/, '')}%") end pages = case params[:sort_by] when "last_read" pages.order('last_read DESC') when "first_read" pages = pages.where('pages.last_read is not null') pages.order('last_read ASC') when "random" pages.random when "last_created" pages.order('created_at DESC') when "first_created" pages.order('created_at ASC') when "longest" pages.order('wordcount DESC') when "shortest" pages.order('wordcount ASC') else pages.order('read_after ASC') end tags=[] if params.has_key?(:hidden) tag = Hidden.find_by_short_name(params[:hidden]) Rails.logger.debug "with #{tag.base_name}" tags << tag elsif params[:show] == "hiddens" #no-op else pages = pages.where(hidden: false) end if params[:hide_all] == "cons" pages = pages.where(con: false) end if params[:show_any] == "pros" pages = pages.where(pro: true) end Tag.types.each do |tag_type| if params.has_key?(tag_type.downcase.to_s) model = tag_type.constantize tag = model.find_by_short_name(params[tag_type.downcase.to_s]) Rails.logger.debug "with #{model}s #{tag.base_name}" tags << tag end end if params.has_key?("tag") tag = Tag.find_by_short_name(params["tag"]) Rails.logger.debug "with Tag #{tag.base_name} (originally from find)" tags << tag end if tags.size < 2 if tags.size == 1 if tags.first.type == "Con" && !params.has_key?("tag") Filter.intersection(pages, tags, params) else pages = pages.joins(:tags).where(tags: {id: tags.first.id}).distinct Filter.normal(pages, params) end elsif tags.empty? Filter.normal(pages, params) end elsif tags.size > 1 Filter.intersection(pages, tags, params) end end def self.normal(pages, params) Rails.logger.debug "filter on one or fewer tags" Rails.logger.debug pages.to_sql start = params[:count].to_i pages.limit(start + LIMIT)[start..-1] end def self.intersection(pages, tags, params) Rails.logger.debug "filtering on intersection of #{tags.size} tags" results = [] tags.each_with_index do |tag, index| if tag.type == "Con" && !params.has_key?("tag") pages_without_tag = pages - tag.pages Rails.logger.debug "not #{tag.base_name} has #{pages_without_tag.count} pages: #{pages_without_tag.map(&:title)}" results << pages_without_tag else pages_with_tag = pages.joins(:tags).distinct.where(tags: {id: tag.id}) Rails.logger.debug "#{tag.base_name} has #{pages_with_tag.count} pages: #{pages_with_tag.map(&:title)}" results << pages_with_tag end end intersection = results.inject{|result, pages| result & pages} Rails.logger.debug "intersection has #{intersection.count} pages" start = params[:count].to_i intersection[start,LIMIT] end end
true