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
66018c49fafd5450d62fbc31d2647838aeb404ab
Ruby
fma2/colocated-charters-nyc-script
/all-colocated-script.rb
UTF-8
345
3
3
[ "MIT" ]
permissive
def create_csv_with_same_address_schools(schools, csv) schools.each do |school| address = school.Primary_Address matched_item = schools.find { | item | item.Primary_Address == address && item.ATS_System_Code != school.ATS_System_Code } school.Same_Address_As_Another_School = true; if matched_item != nil csv << school end end end
true
29f0b7b8fbf68ab940a4de3bf9fd43ce70783542
Ruby
IIIIIIIIll/RubyQuizess
/Quiz17/question7.rb
UTF-8
202
2.8125
3
[]
no_license
first = 'speed' second = 'racer' p binding.local_variables p TOPLEVEL_BINDING.local_variables #class Motivation def speak eval('"Go #{first} #{second}!!!"', TOPLEVEL_BINDING) end #end p speak
true
a61950de28a279ffd69dbc0f571f9192784e49a9
Ruby
yehudamakarov/inspiration-please
/lib/inspiration_please/cli.rb
UTF-8
2,225
3.71875
4
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class InspirationPlease::CLI attr_reader :date_page def initialize @date_page = InspirationPlease::DatePage.new end def call list_date menu end def menu puts '' input = nil begin while input != 'exit' puts '' puts " > Enter '1' for today's day in Jewish History." puts " > Enter '2' for today's Daily Thought." puts " > Or enter 'exit'." puts '' input = gets.strip case input when '1' print_jewish_history when '2' print_daily_thought when 'exit' goodbye end end rescue Interrupt => e goodbye end end def list_date puts justify_text(" Today is: ", "≡") puts '' puts justify_text(date_page.todays_date, ' ') puts justify_text(date_page.date_hebrew, ' ') puts justify_text(date_page.date_english, ' ') puts '' puts justify_text('There is something special about today.', '≡') puts '' end def print_jewish_history if date_page.jewish_history? date_page.history.each do |header, content| puts "" puts justify_text(date_page.date_hebrew, '-') puts "" puts justify_text(header.strip, '-') puts "" puts content.strip puts "" end else puts '' puts 'Today in Jewish History is a canvas waiting to be painted by you. Try the daily thought. :) ' puts '' end end def print_daily_thought if date_page.daily_thought? date_page.daily_thought.each do |header, content| puts '' puts justify_text(date_page.date_hebrew, '-') puts '' puts justify_text(header.strip, '-') puts '' puts content.strip puts '' end else puts '' puts 'Maybe you have a daily thought? :) ' puts '' end end def goodbye puts "\n" puts justify_text('', '.') puts justify_text(' Make it a day full of good things. ', '.') puts justify_text(' ♥ ', '.') end def justify_text(str, char) str.center(50, char) end end
true
074b3532665e100d8909ed869968112d08cc804d
Ruby
rorysaur/chess
/king.rb
UTF-8
272
3.1875
3
[]
no_license
# -*- coding: utf-8 -*- require_relative './stepping_piece.rb' class King < SteppingPiece DELTAS = [ [-1, -1], [-1, 0], [-1, 1], [0, 1], [0, -1], [1, -1], [1, 0], [1, -1] ] def to_s @color == :white ? "♚ " : "♔ " end end
true
65b3df2c33f1cecfd4e1886e35089863367e4f68
Ruby
leungwensen/70-math-quizs-for-programmers
/zh_CN/q61_02.rb
UTF-8
1,268
3.390625
3
[ "MIT" ]
permissive
# 设置方格点数目 W, H = 5, 4 # 移动方向 @move = [[0, 1], [0, -1], [1, 0], [-1, 0]] @log = {} # 递归遍历 def search(x, y, depth) return 0 if x < 0 || W <= x || y < 0 || H <= y return 0 if @log.has_key?(x + y * W) return 1 if depth == W * H # 遍历到一半,检查剩下的点是否连结 if depth == W * H / 2 then remain = (0..(W*H-1)).to_a - @log.keys check(remain, remain[0]) return 0 if remain.size > 0 end cnt = 0 @log[x + y * W] = depth @move.each{|m| # 上下左右移动 cnt += search(x + m[0], y + m[1], depth + 1) } @log.delete(x + y * W) return cnt end # 检查是否连结 def check(remain, del) remain.delete(del) left, right, up, down = del - 1, del + 1, del - W, del + W # 如果前方是同色的,则检索 check(remain, left) if (del % W > 0) && remain.include?(left) check(remain, right) if (del % W != W - 1) && remain.include?(right) check(remain, up) if (del / W > 0) && remain.include?(up) check(remain, down) if (del / W != H - 1) && remain.include?(down) end count = 0 (W * H).times{|i| count += search(i % W, i / W, 1) } # 起点终点互换位置得到的路径和原先一致,所以最终数目减半 puts count / 2
true
8b3e2b5106434db4afebc68e239ef7ce85def51f
Ruby
jalapl/state_machine
/lib/state_machine/base.rb
UTF-8
1,747
2.703125
3
[ "MIT" ]
permissive
module StateMachine module Base module ClassMethods extend Forwardable def_delegators :@state_collection, :states, :initial_state attr_accessor :options def whiny_transitions? options[:whiny_transitions] == true end def state_collection @state_collection ||= StateMachine::StateCollection.new end def event_collection @event_collection ||= StateMachine::EventCollection.new end def state_machine(**args, &block) self.options = args StateMachine::StateMachineFactory.define(state_collection, event_collection, &block) define_check_state_methods define_may_methods define_event_methods end def define_event_methods event_collection.all.each do |event| define_method(event.name) do return false if !public_send("may_#{event.name}?") && self.class.whiny_transitions? raise InvalidTransition unless public_send("may_#{event.name}?") raise GuardCheckFailed if event.guard && !instance_eval(&event.guard) instance_eval(&event.before_callback) if event.before_callback @state = event.to instance_eval(&event.after_callback) if event.after_callback end end end def define_may_methods event_collection.all.each do |event| define_method("may_#{event.name}?") do event.from.include?(@state) end end end def define_check_state_methods state_collection.all.map(&:name).each do |new_state| define_method("#{new_state}?") do @state == new_state end end end end end end
true
3291bd0b7949fee92265970c2999aaff988648aa
Ruby
JackBracken/Connect4
/lib/board.rb
UTF-8
937
3.65625
4
[]
no_license
module Connect4 class Board attr_reader :board ROWS = 5 COLS = 7 EMPTY_SPACE = 'o' def initialize # 5 rows, 7 columns @board = Array.new(COLS){ Array.new(ROWS, EMPTY_SPACE) } @veto = -1 end def to_s #@board.reverse.each { |x| print "#{x} #{x.size}\n" } (ROWS - 1).downto(0) do |i| print '[ ' for j in 0...COLS print "#{@board[j][i]} " end print "]\n" end print "\n" end def play(col, player) return 1 unless @board[col].include?(EMPTY_SPACE) return 2 if col == @veto first_empty_space = @board[col].index(EMPTY_SPACE) @board[col][first_empty_space] = player return 0 end def veto(col) end end end b = Connect4::Board.new b.to_s b.play(3, "R") b.to_s b.play(3, "Y") b.to_s b.play(3, "R") b.to_s b.play(3, "Y") b.to_s b.play(3, "R") b.to_s b.play(3, "Y") b.to_s
true
88adf3a65d1f8737ac279364e2b6242d003d4f53
Ruby
morsedigital/morse_controller_helpers
/spec/morse_controller_helpers_spec.rb
UTF-8
2,304
2.546875
3
[ "MIT" ]
permissive
require "spec_helper" class GenericController < ActionController::Base include MorseControllerHelpers end class Thing; end class ThingStuff; end RSpec.describe MorseControllerHelpers, type: :controller do let(:controller) { GenericController.new } describe 'klass' do it 'should constantize the klass_camel' do allow(controller).to receive(:klass_camel).and_return('ThingStuff') expect(controller.klass).to eq ThingStuff end end describe 'klass_camel' do before do allow(controller).to receive(:controller_name).and_return('things') end it 'should singularize the controller name' do expect(controller.klass_camel).to eq 'thing' end end describe 'klass_humanized' do before do allow(controller).to receive(:klass_camel).and_return('ThingStuff') end it 'should singularize the klass_camel' do expect(controller.klass_humanized).to eq 'Thingstuff' end end describe 'klass_id' do before do allow(controller).to receive(:klass_snake).and_return('thing_stuff') end it 'should add id to the klass_snake' do expect(controller.klass_id).to eq 'thing_stuff_id' end end describe 'klass_pluralized' do before do allow(controller).to receive(:klass_snake).and_return('thing_stuff') end it 'should singularize the klass_snake' do expect(controller.klass_pluralized).to eq 'thing_stuffs' end end describe 'klass_snake' do it 'should underscore the klass_camel' do allow(controller).to receive(:klass_camel).and_return('ThingStuff') expect(controller.klass_snake).to eq 'thing_stuff' end end describe 'params_resource_ids' do it 'should extract the params ending in _id' do allow(controller).to receive(:params).and_return({'whev' => 'hello', 'thing_id' => 12, 'other_thing_id' => 10}) expected = ['thing_id', 'other_thing_id'] expect(controller.params_resource_ids).to eq expected end end describe 'params_resources' do it 'should turn params_resource_ids into resources' do allow(controller).to receive(:params_resource_ids).and_return ['thing_id', 'other_thing_id'] expected = ['thing', 'other_thing'] expect(controller.params_resources).to eq expected end end end
true
3c8e3c948795877aaa0111c002e2ac8b343bcf47
Ruby
AlexHg/Teoria-Computacional
/Practica3.Automatas.Finitos.Deterministas/autom.rb
UTF-8
4,093
3.25
3
[]
no_license
class AFD attr_accessor :hash def initialize hash, fin, expresion @hash = hash @fin = fin @is = false @expresion = expresion puts "Se ha creado un nuevo AFD" puts "\nEspresión regular: "+@expresion+"\n" end def is_number? string true if Float(string) rescue false end def verificar_01 word puts word if word.count("0") == word.count("1") puts "si es igual el numero de 0 que de 1" else puts "No es igual el numero de 0 y 1" end end def verificar word, mode #@edo_actual = @hash["q0"] @is = false @finis = false @state = "q0" print "State log:\n -> q0" word.split("").each do |w| @ww = w @ww = "@" if is_number?(@ww) && mode == "digit" if @hash[@state][@ww] @is = true @state = @hash[@state][@ww] print " -> "+@state else @is = false break end end puts "\n\nWord: "+word @fin.each do |l| @finis = true if @state == l end if @is && @finis puts "\nState: Es una palabra valida" else puts "\nState: No es una palabra valida" end return @is end end puts "\n\n\n" inciso_a = AFD.new({ "q0" => {"@" => "q1"}, "q1" => {"@" => "q1", "." => "q2", "E" => "q4"}, "q2" => {"@" => "q3"}, "q3" => {"@" => "q3", "E" => "q4"}, "q4" => {"+" => "q5", "-" => "q5", "@" => "q6"}, "q5" => {"@" => "q6"}, "q6" => {"@" => "q6"} }, ["q3","q6"], "@( @*,( (.,@)|( .,@,E,(-|+|@),@ ) ) )"); puts "\n\nA)\n\n" inciso_a.verificar '031E+1', "digit" puts "\n\n\n" inciso_a.verificar '982.112', "digit" puts "\n\n\n" inciso_a.verificar '12E+.12', "digit" puts "\n\n\n" inciso_a.verificar '982.112E+1654.31', "digit" puts "\n\n\n" inciso_b = AFD.new({ "q0" => {"b" => "q1", "a" => "q4"}, "q1" => {"c" => "q2", "a" => "q3", "b" => "q3"}, "q2" => {"a" => "q2", "c" => "q3", "b" => "q3"}, "q3" => {"a" => "q3", "b" => "q3", "c" => "q3"}, "q4" => {"c" => "q4", "a" => "q3"}, }, ["q2","q4"], "( ac*|bca* )"); puts "\n\nB)\n\n" inciso_b.verificar 'acccccc', "normal" puts "\n\n\n" inciso_b.verificar 'bcaaaaaa', "normal" puts "\n\n\n" inciso_b.verificar 'bcccaaaa', "normal" puts "\n\n\n" inciso_b.verificar 'aaaaccc', "normal" puts "\n\n\n" inciso_c = AFD.new({ "q0" => {"1" => "q0", "0" => "q0"} }, ["q0"], "( {0n1n} n > 0 )"); puts "\n\nC)\n\n" inciso_c.verificar_01 '0000011111' puts "\n\n\n" inciso_c.verificar_01 '01010101' puts "\n\n\n" inciso_c.verificar_01 '1101' puts "\n\n\n" inciso_c.verificar_01 '00111' puts "\n\n\n" inciso_d = AFD.new({ "q0" => {"a" => "q1"}, "q1" => {"a" => "q3", "b" => "q2"}, "q2" => {"a" => "q6", "b" => "q2"}, "q3" => {"a" => "q3", "b" => "q4"}, "q4" => {"a" => "q5"}, "q5" => {"a" => "q5"}, "q6" => {"a" => "q5"} }, ["q5"], "a(b+a|a+b)a+"); puts "\n\nD)\n\n" inciso_d.verificar 'abbbaa', "normal" puts "\n\n\n" inciso_d.verificar 'abaa', "normal" puts "\n\n\n" inciso_d.verificar 'abaab', "normal" puts "\n\n\n" inciso_d.verificar 'baabaa', "normal" # 10 = X puts "\n\n\n" inciso_e = AFD.new({ "q0" => {"1" => "q1", "2" => "q2", "5" => "q5", "X" => "q10"}, "q1" => {"1" => "q2", "2" => "q4", "5" => "q6", "X" => "q11"}, "q2" => {"1" => "q3", "2" => "q5", "5" => "q7", "X" => "q12"}, "q3" => {"1" => "q4", "2" => "q6", "5" => "q8", "X" => "q12"}, "q4" => {"1" => "q5", "2" => "q7", "5" => "q9", "X" => "q12"}, "q5" => {"1" => "q6", "2" => "q8", "5" => "q10", "X" => "q12"}, "q6" => {"1" => "q7", "2" => "q9", "5" => "q11", "X" => "q12"}, "q7" => {"1" => "q8", "2" => "q10", "5" => "q12", "X" => "q12"}, "q8" => {"1" => "q9", "2" => "q11", "5" => "q12", "X" => "q12"}, "q9" => {"1" => "q10", "2" => "q12", "5" => "q12", "X" => "q12"}, "q10" => {"1" => "q11", "2" => "q12", "5" => "q12", "X" => "q12"}, "q11" => {"1" => "q12", "2" => "q12", "5" => "q12", "X" => "q12"}, "q12" => {"1" => "q12", "2" => "q12", "5" => "q12", "X" => "q12"} }, ["q12"], "a(b+a|a+b)a+"); puts "\n\nE)\n\n X=10" inciso_e.verificar 'X11', "normal" puts "\n\n\n" inciso_e.verificar 'X5', "normal" puts "\n\n\n" inciso_e.verificar '551', "normal" puts "\n\n\n" inciso_e.verificar 'X', "normal"
true
e8d88a93dafd8d78fd3d4493c424c9225548cd5d
Ruby
Samy-Amar/gosu_smb
/lib/characters/mario.rb
UTF-8
1,137
2.828125
3
[]
no_license
# frozen_string_literal: true require_relative 'base_character' require_relative '../assets/mario/repository' module Characters # Manages the mario character - # Mario-specific movement and actions, as well as assets class Mario < Characters::BaseCharacter def initial_position { x: 0, y: 250, }.freeze end SPRITE_PATH = 'lib/assets/mario/tmp_mario_1.jpg' def initialize set_speed_and_movement_defaults @image = Gosu::Image.new(SPRITE_PATH) @x = initial_position[:x] @y = initial_position[:y] end def update manage_movement end def draw @image.draw_rot(@x, @y, 1, 0) end private def manage_movement if Gosu.button_down? Gosu::KbRight move_right elsif Gosu.button_down? Gosu::KbLeft move_left end manage_jump if Gosu.button_down?(Gosu::KbUp) || @jumping end def set_speed_and_movement_defaults @base_speed = 3 @acceleration_factor = 0 @acceleration_update_factor = 1 @max_acceleration_factor = 10 @max_jump_height = 10 end end end
true
025ce6049262ddb9a095f9e39c7cc90ee0600717
Ruby
rcjara/project-euler
/85-Problem/ruby/solve.rb
UTF-8
724
3.625
4
[]
no_license
def num_rectangles(h, w) (1..w).inject(0) do |sum, width| (1..h).inject(0) do |s, height| s + (h - height + 1) * (w - width + 1) end + sum end end h = 1 w = 1 h += 1 while num_rectangles(h, w) < 2_000_000 max_h = h max_w = max_h / 2 nearest = (2_000_000 - num_rectangles(h, w) ).abs nearest_area = h * w h = max_h (1..max_w).each do |w| num_rects = num_rectangles(h, w) prev = (2_000_000 - num_rects).abs puts "#{w}, #{h}" until prev <= nearest || num_rects + nearest < 2_000_000 h -= 1 num_rects = num_rectangles(h, w) prev = (2_000_000 - num_rects).abs if prev < nearest nearest = prev max_h = h nearest_area = h * w end end end puts nearest_area
true
c406291082aee90b088881b72bc2f0864f6c4550
Ruby
MikeWestHub/tic_tac_toe
/lib/game.rb
UTF-8
839
3.953125
4
[]
no_license
require_relative 'player' require_relative 'board' require "pry" class Game attr_reader :board def initialize @board = Board.new end def create_player puts "Player 1, you will be X. Please enter your name." @player_1 = Player.new(gets.chomp, "x") puts "Player 2, you will be O. Please enter your name." @player_2 = Player.new(gets.chomp, "o") end def play create_player get_players_move(@player_1) get_players_move(@player_2) end def valid?(input) @valid_input = ["a1", "a2", "a3", "b1", "b2", "b3", "c1", "c2", "c3"] if @valid_input.include?(input) true else puts "Invalid selection." false end end def get_players_move(player) input = nil until valid?(input) input = player.select_move end end def game_over end end
true
bb881cfcbd326ecdc941b0b4afa13290f3369918
Ruby
kotobuki562/Ruby
/drill_12.rb
UTF-8
366
3.859375
4
[]
no_license
class Fruits @@sum = 0 def self.get_sum puts "合計の価格は#{@@sum}円です" end def initialize(name, price) @name = name @price = price @@sum = @@sum + price end end apple = Fruits.new("リンゴ", 120) orange = Fruits.new("オレンジ", 200) strawberry = Fruits.new("イチゴ", 60) Fruits.get_sum
true
8d0b2837fe45260bed2d8d6cc2966fb86de72d74
Ruby
samesystem/social_security_number
/lib/social_security_number/country/ca.rb
UTF-8
1,306
3.125
3
[ "MIT" ]
permissive
module SocialSecurityNumber # SocialSecurityNumber::Ca validates Canadian Social Insurance Numbers (SINs) # The Social Insurance Number (SIN) is a 9-digit identifier issued to # individuals for various government programs. SINs that begin with a 9 are # issued to temporary workers who are neither Canadian citizens nor permanent # residents. # https://en.wikipedia.org/wiki/Social_Insurance_Number class Ca < Country def validate @error = if !check_by_regexp(REGEXP) 'bad number format' elsif !check_number 'number control sum invalid' end end private MODULUS = 10 CONTROLCIPHERS = [1, 2, 1, 2, 1, 2, 1, 2, 1].freeze REGEXP = /^(?<f_nmr>\d{3})[- .]?(?<s_nmr>\d{3})[- .]?(?<l_nmr>\d{3})$/ def check_number (count_number_sum % 10).zero? end def count_number_sum digits = digit_number.split(//) new_number = [] sum = 0 digits.each_with_index do |digit, i| n = digit.to_i * CONTROLCIPHERS[i].to_i new_number << if n > 9 n - 9 else n end end new_number.each do |digit| sum += digit.to_i end sum end end end
true
047dfe3dbd529e660ba7dd36020a2fdfe09bba47
Ruby
nate-hunter/deli-counter-dumbo-web-career-010719
/deli_counter.rb
UTF-8
1,416
4.03125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# Write your code here. def line (deli_line) if deli_line.count == 0 puts "The line is currently empty." else current_line = "The line is currently:" deli_line.each.with_index(1) do |name, position| current_line << " #{position}. #{name}" #current_line.push(" #{position}. #{name}") end puts current_line end end def take_a_number ( deli_line, customer) deli_line.push(customer) puts "Welcome, #{customer}. You are number #{deli_line.count} in line." end def now_serving (deli_line) if deli_line.count == 0 puts "There is nobody waiting to be served!" else puts "Currently serving #{deli_line.shift}." end end =begin katz_deli = [] take_a_number(katz_deli, "Ada") #=> Welcome, Ada. You are number 1 in line. take_a_number(katz_deli, "Grace") #=> Welcome, Grace. You are number 2 in line. take_a_number(katz_deli, "Kent") #=> Welcome, Kent. You are number 3 in line. line(katz_deli) #=> "The line is currently: 1. Ada 2. Grace 3. Kent" now_serving(katz_deli) #=> "Currently serving Ada." line(katz_deli) #=> "The line is currently: 1. Grace 2. Kent" take_a_number(katz_deli, "Matz") #=> Welcome, Matz. You are number 3 in line. line(katz_deli) #=> "The line is currently: 1. Grace 2. Kent 3. Matz" now_serving(katz_deli) #=> "Currently serving Grace." line(katz_deli) #=> "The line is currently: 1. Kent 2. Matz" =end
true
510bfe8fdb77578596d4d19f678da365c85c6c6d
Ruby
alrawi90/ruby-objects-has-many-lab-re-coded-000
/lib/artist.rb
UTF-8
381
3.234375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist attr_accessor :name @@song_count=0 def initialize(name) @name=name @songs=[] end def songs return @songs end def add_song(song) song.artist=self @songs.push(song) @@song_count +=1 end def add_song_by_name(song_name) song=Song.new(song_name) song.artist=self @songs.push(song) @@song_count +=1 end def self.song_count return @@song_count end end
true
8384c52e7da683b33182acf2c7e0279b8f060a73
Ruby
Jandrocks/POO_RUBY
/cuenta_bancaria.rb
UTF-8
814
3.6875
4
[]
no_license
class CuentaBancaria attr_accessor :nombre_de_usuario, :nuemero_de_cuenta, :tipo def initialize(nombre_de_usuario, nuemero_de_cuenta, tipo = 0) @nombre_de_usuario = nombre_de_usuario @nuemero_de_cuenta = nuemero_de_cuenta @tipo = tipo raise RangeError, 'Cuenta debe tener 8 digitos' if (@nuemero_de_cuenta.digits).size != 8 raise RangeError, 'debes ingresr tipo 1 o 0' if @tipo != 0 && @tipo != 1 end def nuemero_de_cuenta() if @tipo == 1 puts "Nombre: #{nombre_de_usuario} ""|"" Cliente VIP: #{@tipo}-#{@nuemero_de_cuenta}" else puts "Nombre: #{nombre_de_usuario} ""|"" Cliente: #{@tipo}-#{@nuemero_de_cuenta}" end end end p = CuentaBancaria.new("alejandro",12345678, 0) p.nuemero_de_cuenta
true
31270459299c1094b8cae28a625d4a36d98c7b2d
Ruby
sooo-s/AtCoder
/abc214/c/main.rb
UTF-8
403
3.109375
3
[]
no_license
N = gets.to_i # 10 S = gets.chomp.split.map(&:to_i) # n = 10, m = 20 T = gets.chomp.split.map(&:to_i) # n = 10, m = 20 t_first = T.find_index(T.min) s = [S[t_first..], S[...t_first]].flatten t = [T[t_first..], T[...t_first]].flatten dp = Array.new(N) { 0 } dp[0] = t[0] (1...N).each do |n| dp[n] = [t[n], dp[n - 1] + s[n - 1]].min end [dp[-t_first..], dp[...-t_first]].flatten.map { |x| puts x }
true
7059e2955239f896b7d753c4bd2b5bdd48b8a982
Ruby
wili3/banker
/app/services/transaction_agent.rb
UTF-8
1,145
2.9375
3
[]
no_license
class TransactionAgent def initialize(transaction, same_bank) @transaction = transaction @same_bank = same_bank end # send money is triggered at the end of the TransactionCreator in order to deliver the money def send_money if @transaction.status == "Succeed" @money = @transaction.money remove_money give_money get_comission end end private #removes money from sender account def remove_money account = Account.where(id: @transaction.sender_id).first account.update_attribute(:money, account.money - @money) end #gives money to receiver account def give_money account = Account.where(id: @transaction.receiver_id).first account.update_attribute(:money, account.money + @money) end #gets comission and gives it to the account's bank def get_comission if !@same_bank Account.where(id: @transaction.sender_id).first.update_attribute(:money, Account.where(id: @transaction.sender_id).first.money - 5) Account.where(id: @transaction.sender_id).first.bank.update_attribute(:comissions_amount_earned, Account.where(id: @transaction.sender_id).first.bank.comissions_amount_earned + 5) end end end
true
bc871d7a968dcd0438f684b707c6d97212f56caf
Ruby
lishulongVI/leetcode
/ruby/115.Distinct Subsequences(不同的子序列).rb
UTF-8
4,364
3.796875
4
[ "MIT" ]
permissive
=begin <p>Given a string <strong>S</strong> and a string <strong>T</strong>, count the number of distinct subsequences of <strong>S</strong> which equals <strong>T</strong>.</p> <p>A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, <code>&quot;ACE&quot;</code> is a subsequence of <code>&quot;ABCDE&quot;</code> while <code>&quot;AEC&quot;</code> is not).</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input: </strong>S = <code>&quot;rabbbit&quot;</code>, T = <code>&quot;rabbit&quot; <strong>Output:</strong>&nbsp;3 </code><strong>Explanation: </strong> As shown below, there are 3 ways you can generate &quot;rabbit&quot; from S. (The caret symbol ^ means the chosen letters) <code>rabbbit</code> ^^^^ ^^ <code>rabbbit</code> ^^ ^^^^ <code>rabbbit</code> ^^^ ^^^ </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input: </strong>S = <code>&quot;babgbag&quot;</code>, T = <code>&quot;bag&quot; <strong>Output:</strong>&nbsp;5 </code><strong>Explanation: </strong> As shown below, there are 5 ways you can generate &quot;bag&quot; from S. (The caret symbol ^ means the chosen letters) <code>babgbag</code> ^^ ^ <code>babgbag</code> ^^ ^ <code>babgbag</code> ^ ^^ <code>babgbag</code> ^ ^^ <code>babgbag</code> ^^^ </pre> <p>给定一个字符串&nbsp;<strong>S&nbsp;</strong>和一个字符串&nbsp;<strong>T</strong>,计算在 <strong>S</strong> 的子序列中 <strong>T</strong> 出现的个数。</p> <p>一个字符串的一个子序列是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,<code>&quot;ACE&quot;</code>&nbsp;是&nbsp;<code>&quot;ABCDE&quot;</code>&nbsp;的一个子序列,而&nbsp;<code>&quot;AEC&quot;</code>&nbsp;不是)</p> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入: </strong>S = <code>&quot;rabbbit&quot;</code>, T = <code>&quot;rabbit&quot; <strong>输出:</strong>&nbsp;3 </code><strong>解释: </strong> 如下图所示, 有 3 种可以从 S 中得到 <code>&quot;rabbit&quot; 的方案</code>。 (上箭头符号 ^ 表示选取的字母) <code>rabbbit</code> ^^^^ ^^ <code>rabbbit</code> ^^ ^^^^ <code>rabbbit</code> ^^^ ^^^ </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入: </strong>S = <code>&quot;babgbag&quot;</code>, T = <code>&quot;bag&quot; <strong>输出:</strong>&nbsp;5 </code><strong>解释: </strong> 如下图所示, 有 5 种可以从 S 中得到 <code>&quot;bag&quot; 的方案</code>。 (上箭头符号 ^ 表示选取的字母) <code>babgbag</code> ^^ ^ <code>babgbag</code> ^^ ^ <code>babgbag</code> ^ ^^ <code>babgbag</code> ^ ^^ <code>babgbag</code> ^^^</pre> <p>给定一个字符串&nbsp;<strong>S&nbsp;</strong>和一个字符串&nbsp;<strong>T</strong>,计算在 <strong>S</strong> 的子序列中 <strong>T</strong> 出现的个数。</p> <p>一个字符串的一个子序列是指,通过删除一些(也可以不删除)字符且不干扰剩余字符相对位置所组成的新字符串。(例如,<code>&quot;ACE&quot;</code>&nbsp;是&nbsp;<code>&quot;ABCDE&quot;</code>&nbsp;的一个子序列,而&nbsp;<code>&quot;AEC&quot;</code>&nbsp;不是)</p> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入: </strong>S = <code>&quot;rabbbit&quot;</code>, T = <code>&quot;rabbit&quot; <strong>输出:</strong>&nbsp;3 </code><strong>解释: </strong> 如下图所示, 有 3 种可以从 S 中得到 <code>&quot;rabbit&quot; 的方案</code>。 (上箭头符号 ^ 表示选取的字母) <code>rabbbit</code> ^^^^ ^^ <code>rabbbit</code> ^^ ^^^^ <code>rabbbit</code> ^^^ ^^^ </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入: </strong>S = <code>&quot;babgbag&quot;</code>, T = <code>&quot;bag&quot; <strong>输出:</strong>&nbsp;5 </code><strong>解释: </strong> 如下图所示, 有 5 种可以从 S 中得到 <code>&quot;bag&quot; 的方案</code>。 (上箭头符号 ^ 表示选取的字母) <code>babgbag</code> ^^ ^ <code>babgbag</code> ^^ ^ <code>babgbag</code> ^ ^^ <code>babgbag</code> ^ ^^ <code>babgbag</code> ^^^</pre> =end # @param {String} s # @param {String} t # @return {Integer} def num_distinct(s, t) end
true
f8ebbba9efdc4564b08cf4a403a9f966043f2a12
Ruby
bogdan/accept_values_for
/lib/accept_values_for/matcher.rb
UTF-8
2,124
2.640625
3
[ "MIT" ]
permissive
require "active_model" module AcceptValuesFor class Matcher def initialize(attribute, *values) @attribute = attribute @values = values @failed_values = {} end def matches?(model) base_matches?(model) do |value| unless model.errors[@attribute].to_a.empty? @failed_values[value] = Array(model.errors[@attribute]).join(", ") end end end def does_not_match?(model) base_matches?(model) do |value| if model.errors[@attribute].to_a.empty? @failed_values[value] = nil end end end def failure_message result = "expected #{@model.inspect} to accept values #{formatted_failed_values} for #{@attribute.inspect}, but it was not\n" sorted_failed_values.each do |key| result << "\nValue: #{key.inspect}\tErrors: #{@attribute} #{@failed_values[key]}" end result end def failure_message_when_negated "expected #{@model.inspect} to not accept values #{formatted_failed_values} for #{@attribute.inspect} attribute, but was" end alias :failure_message_for_should :failure_message alias :failure_message_for_should_not :failure_message_when_negated def description "accept values #{@values.map(&:inspect).join(', ')} for #{@attribute.inspect} attribute" end private def base_matches?(model) @model = model !has_validations_module?(model) and return false old_value = @model.send(@attribute) @values.each do |value| model.send("#@attribute=", value) model.valid? yield(value) if @model.respond_to?(:errors) && @model.errors.is_a?(ActiveModel::Errors) end return @failed_values.empty? ensure @model.send("#@attribute=", old_value) if defined?(old_value) end def has_validations_module?(model) model.class.included_modules.include?(ActiveModel::Validations) end def formatted_failed_values sorted_failed_values.map(&:inspect).join(", ") end def sorted_failed_values @failed_values.keys.sort_by(&:to_s) end end end
true
9cf08dad1561706930c14fcdd16821fcb93eba20
Ruby
rocky/rb8-trepanning
/processor/command-ruby-debug/catchpoint.rb
UTF-8
1,517
2.8125
3
[]
no_license
module Trepan class CatchCommand < OldCommand # :nodoc: self.allow_in_control = true def regexp /^\s* cat(?:ch)? (?:\s+ (\S+))? (?:\s+ (off))? \s* $/ix end def execute excn = @match[1] if not excn # No args given. info_catch elsif not @match[2] # One arg given. if 'off' == excn Debugger.catchpoints.clear if confirm("Delete all catchpoints? (y or n) ") else binding = @state.context ? get_binding : TOPLEVEL_BINDING unless debug_eval("#{excn}.is_a?(Class)", binding) print "Warning #{excn} is not known to be a Class\n" end Debugger.add_catchpoint(excn) print "Catch exception %s.\n", excn end elsif @match[2] != 'off' errmsg "Off expected. Got %s\n", @match[2] elsif Debugger.catchpoints.member?(excn) Debugger.catchpoints.delete(excn) print "Catch for exception %s removed.\n", excn else errmsg "Catch for exception %s not found.\n", excn end end class << self def help_command 'catch' end def help(cmd) %{ cat[ch]\t\tsame as "info catch" cat[ch] <exception-name> [on|off] \tIntercept <exception-name> when there would otherwise be no handler. \tWith an "on" or "off", turn handling the exception on or off. cat[ch] off\tdelete all catchpoints } end end end end
true
4a732c16a9a7fa455cf6f4d6399f68dae4f07b82
Ruby
shlima/translate_enum
/lib/translate_enum/builder.rb
UTF-8
1,466
2.578125
3
[ "MIT" ]
permissive
# frozen_string_literal: true module TranslateEnum class Builder attr_accessor :i18n_scope attr_accessor :i18n_key attr_accessor :enum_instance_method_name attr_accessor :enum_klass_method_name attr_accessor :method_name_singular attr_accessor :method_name_plural attr_reader :model, :attribute # @param model [ActiveModel::Model, ActiveRecord::Base] # @param attribute [String] def initialize(model, attribute) @model = model @attribute = attribute yield(self) if block_given? end # like "activerecord.attributes" or "activemodel.attributes" def i18n_scope @i18n_scope ||= "#{model.i18n_scope}.attributes" end def i18n_key @i18n_key ||= "#{attribute}_list" end def i18n_location(key) "#{model.model_name.i18n_key}.#{i18n_key}.#{key}" end def i18n_default_location(key) :"attributes.#{i18n_key}.#{key}" end # @param [String] # like "translated_genders" def method_name_plural @method_name_plural ||= "translated_#{attribute.to_s.pluralize}" end # @param [String] # like "translated_gender" def method_name_singular @method_name_singular ||= "translated_#{attribute.to_s.singularize}" end def enum_klass_method_name @enum_klass_method_name ||= attribute.to_s.pluralize end def enum_instance_method_name @enum_instance_method_name ||= attribute end end end
true
1c63a5023eceaa5f72ee2f769fb5792f5356762f
Ruby
corbinsykes/Calculator
/calculator.rb
UTF-8
3,893
3.75
4
[]
no_license
def get_two_numbers puts "What's the first number?" first = gets.chomp.to_f puts "What's the second number?" second = gets.chomp.to_f return first, second end def add(x,y) return x+y end def subtract(x,y) return x-y end def multiply(x,y) return x*y end def divide_decimal(x,y) return x/y end def divide_remainder(x,y) return (x/y).to_s + " with a remainder of " + (x%y).to_s end def slugging_pct(a,w,x,y,z) return (w+(2*x)+(3*y)+(4*z))/a end def bmi_us(m,h) return (m/(h**2))*703.06957964 end def bmi_metric(m,h) return (m/(h**2)) end def earned_run_average(earned_runs_allowed,innings_pitched) return (earned_runs_allowed/innings_pitched)*9 end def passer_rtg(att,yds,tds,comp,int) return ((8.4*yds)+(330*tds)+(100*comp)-(200*int))/att end puts "Before we get started, what's your name?" name = gets.chomp puts "Welcome, #{name}. I'm a calculator. Let's get started, shall we?" puts "What type of function would you like to perform? (Select a Number)" puts "1. Arithmetic" puts "2. Slugging Percentage" puts "3. Body Mass Index" puts "4. Earned Run Average" puts "5. NCAA Passer Rating" function_choice = gets.chomp case function_choice.downcase when "1" puts "Which Operation? (Select a Number)" puts "1. Addition" puts "2. Subtraction" puts "3. Multiplication" puts "4. Division" operation_choice = gets.chomp case operation_choice.downcase when "1" x, y = get_two_numbers p add(x,y) when "2" x, y = get_two_numbers p subtract(x,y) when "3" x, y = get_two_numbers p multiply(x,y) when "4" puts "Would you like a decimal or a remainder?" division_choice = gets.chomp case division_choice.downcase when "decimal" x, y = get_two_numbers p divide_decimal(x,y) when "remainder" puts "What's the first number?" x = gets.chomp.to_i puts "What's the second number?" y = gets.chomp.to_i p divide_remainder(x,y) end end when "2" puts "How many at-bats did you (or whoever) take?" at_bats = gets.chomp.to_f puts "Of those at-bats, how many singles were hit?" singles = gets.chomp.to_f puts "How many doubles?" doubles = gets.chomp.to_f puts "Triples?" triples = gets.chomp.to_f puts "Home Runs?" home_runs = gets.chomp.to_f p slugging_pct(at_bats, singles, doubles, triples, home_runs) when "3" puts "What is your preferred number system? (Select a Number)" puts "1. Metric" puts "2. U.S." units_choice = gets.chomp case units_choice when "1" puts "How tall are you (in meters)?" height = gets.chomp.to_f puts "How much do you weigh (in kilograms)?" weight = gets.chomp.to_f p bmi_metric(weight,height) when "2" puts "How tall are you (in inches)?" height = gets.chomp.to_f puts "How much do you weigh (in pounds)?" weight = gets.chomp.to_f p bmi_us(weight,height) end when "4" puts "How many total innings were pitched?" x = gets.chomp.to_f puts "How many earned runs were allowed?" y = gets.chomp.to_f p earned_run_average(y,x) when "5" puts "How many passes were thrown?" att = gets.chomp.to_f puts "How many yards were accrued through the air?" yds = gets.chomp.to_f puts "How many touchdowns were thrown?" tds = gets.chomp.to_f puts "How many completions?" comp = gets.chomp.to_f puts "How many picks (interceptions)?" int = gets.chomp.to_f p passer_rtg(att,yds,tds,comp,int) end
true
43522f3884e6f14dc803db3255e978ba24cbd6e6
Ruby
jackaquigley/testingtask
/specs/card_spec.rb
UTF-8
917
3.109375
3
[]
no_license
require("minitest/autorun") require('minitest/reporters') Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new require_relative("../card_game.rb") require_relative("../card.rb") class CardTest < Minitest::Test def setup @card1 = Card.new("Clubs", 8) @card2 = Card.new("Spades", 1) @card3 = Card.new("Spades", 5) @card_game = CardGame.new() @cards = [@card1, @card2, @card3] end def test_card_has_suit() assert_equal("Clubs", @card1.suit) end def test_card_has_value() assert_equal(1, @card2.value) end def test_card_is_ace() result = @card_game.check_for_ace(@card2) assert_equal(true, result) end def test_highest_card() result = @card_game.highest_card(@card1, @card2) assert_equal(@card1, result) end def test_total_value() result = CardGame.cards_total(@cards) assert_equal("You have a total of 14", result) end end
true
39046a045d422ff21d9aac15338b44522fc6fc93
Ruby
nc-trevorb/rbon
/spec/rbon_value_spec.rb
UTF-8
4,438
2.640625
3
[]
no_license
require 'spec_helper' describe RbonValue do { RbonBool => false, RbonNumber => 3, RbonString => 'asdf', RbonObject => {}, RbonArray => [], }.each do |rbon_type, value| context "for any type (#{rbon_type})" do describe '#to_json_schema' do let(:json_schema) { RbonValue.create(value).to_json_schema } it "should always return a HashWithIndifferentAccess with a 'type' key" do expect(json_schema).to be_a(HashWithIndifferentAccess) expect(json_schema[:type]).not_to be(nil) expect(json_schema[:type]).to eq(json_schema['type']) expect(json_schema[:type]).to eq(rbon_type.schema_type) end end describe '#schema_type' do it "should always be a string" do expect(rbon_type.schema_type).to be_a(String) end end end end { RbonBool => false, RbonNumber => 3, RbonString => 'asdf', }.each do |json_type, value| context "for value types (#{json_type})" do describe '#to_json_schema' do let(:json_schema) { RbonValue.create(value).to_json_schema } it "should not have any other properties" do expect(json_schema.keys).to eq(['type']) end end describe '#paths' do let(:prefix) { 'prefix' } let(:paths) { RbonValue.create(value).paths(prefix: prefix) } it "should be a single path with the prefix" do expect(paths.length).to eq(1) expect(paths.first).to eq("#{prefix}:#{json_type.schema_type}") end end end end context "for RbonArray types" do describe '#to_json_schema' do let(:json_schema) { RbonValue.create([1,2,3]).to_json_schema } it "should have items" do expect(json_schema[:items]).not_to be(nil) end it "should get the schemas of elements in the array" do expect(json_schema[:items]).to include({ type: RbonNumber.schema_type }) end end describe '#paths' do [ [1,2,3], ['asdf'], ].each do |value| context "nested primitives (#{value})" do let(:json_value) { RbonValue.create(value) } it "should use square brackets" do paths = json_value.paths(prefix: 'prefix') type = RbonValue.create(value.first).schema_type expect(paths).to include("prefix[]:#{type}") end end end [ [[{ a: 1 }], 'number'], [[{ a: [{ b: 'asdf' }] }], 'string'], ].each do |value, type| context "nested objects (#{value})" do let(:json_value) { RbonValue.create(value) } it "should use square brackets" do path = json_value.paths(prefix: 'prefix').first expect(path.start_with?("prefix[]/a")).to be(true) expect(path.end_with?(":#{type}")).to be(true) end end end end end context "for RbonObject types" do describe '#to_json_schema' do let(:json_schema) { RbonValue.create({ a: 1 }).to_json_schema } it "should have properties" do nested_schema = json_schema[:properties][:a] expect(nested_schema[:type]).to eq(RbonNumber.schema_type) end it "should build nested properties" do json_schema = RbonValue.create({ a: { b: 'hi' }}).to_json_schema nested_schema = json_schema[:properties][:a] deep_nested_schema = nested_schema[:properties][:b] expect(nested_schema[:type]).to eq(RbonObject.schema_type) expect(deep_nested_schema[:type]).to eq(RbonString.schema_type) end end describe '#paths' do [ [{ a: 1 }, ["prefix/a:number"]], [{ a: 1, b: 'asdf' }, ["prefix/a:number", "prefix/b:string"]], [{ a: { b: 'asdf' } }, ["prefix/a/b:string"]], [{ a: [{ b: [1, 'asdf'] }] }, ["prefix/a[]/b[]:string"]], ].each do |value, expected_paths| it "should list every path" do json_value = RbonValue.create(value) paths = json_value.paths(prefix: 'prefix') expected_paths.each do |path| expect(paths).to include(path) end end end end end describe "creation" do it "should recurse into objects to create more RbonValues" do arg = { a: 'asdf' }.indifferent expect(RbonValue.create(arg).value.values.first).to be_a(RbonValue) end end end
true
f793de86a3d590d3ec9350bd8bea14b79f701a74
Ruby
crowdcompass/middleman-breadcrumbs
/spec/breadcrumbs_helper_spec.rb
UTF-8
3,031
2.640625
3
[ "MIT" ]
permissive
require_relative './spec_helper' require 'ostruct' require 'middleman-breadcrumbs/breadcrumbs_helper' describe BreadcrumbsHelper do before do @helper = Object.new @helper_class = @helper.singleton_class end describe '.included' do describe 'link_to is defined' do it 'does not include Padrino::Helpers' do methods = @helper_class.instance_methods @helper_class.stub :instance_methods, methods + [:link_to] do @helper_class.send :include, BreadcrumbsHelper @helper_class.wont_include Padrino::Helpers end end end describe 'link_to is not defined' do it 'includes Padrino::Helpers' do @helper_class.send :include, BreadcrumbsHelper @helper_class.must_include Padrino::Helpers end end end describe '#breadcrumbs' do before do @helper.singleton_class.send :include, BreadcrumbsHelper self.singleton_class.send :include, Padrino::Helpers @page = page end describe 'top-level page' do it 'returns a link to the page' do @helper.breadcrumbs(@page).must_equal link_to(@page.data.title, "/#{@page.path}") end end describe 'non-top-level page' do before do @parent = page @grandparent = page @page.parent = @parent @page.parent.parent = @grandparent end describe 'separator' do describe 'specified' do it 'joins all links to parent pages with the specified separator' do separator = Faker::Lorem.characters(5) @helper.breadcrumbs(@page, separator: separator).must_equal breadcrumb_links.join separator end describe 'nil' do it 'does not use a separator' do @helper.breadcrumbs(@page, separator: nil).must_equal breadcrumb_links.join end end end describe 'not specified' do it 'uses " > " as the separator' do @helper.breadcrumbs(@page).must_equal breadcrumb_links.join ' &gt; ' end end end describe 'wrapper' do describe 'specified' do it 'wraps breadcrumbs in the specified element type' do wrapper = Faker::Lorem.word.to_sym wrapped_links = breadcrumb_links.collect {|link| content_tag(wrapper) { link } } @helper.breadcrumbs(@page, wrapper: wrapper, separator: nil).must_equal wrapped_links.join end end describe 'not specified' do it 'does not wrap breadcrumbs in tags' do @helper.breadcrumbs(@page, separator: nil).must_equal breadcrumb_links.join end end end end end private def breadcrumb_links [@grandparent, @parent, @page].collect do |level| link_to level.data.title, "/#{level.path}" end end def page path = Faker::Internet.url title = Faker::Lorem.sentence data = OpenStruct.new title: title OpenStruct.new data: data, path: path end end
true
b60acee7865574316f694ed83d87cb7d93326d7c
Ruby
Fem-Fem/my_anime_list
/lib/my_anime_list/anime.rb
UTF-8
765
3.03125
3
[ "MIT" ]
permissive
class MyAnimeList::Anime @@all = [] attr_accessor :name, :show_length, :time_aired, :members_watched, :url, :description, :genres def initialize(name=nil, show_length=nil, time_aired=nil, members_watched=nil, url=nil) @name = name @show_length = show_length @time_aired = time_aired @members_watched = members_watched @url = url if_gintama? @@all << self end def if_gintama? if self.name.include? "°" replace = self.name.split("Â") complete_item = replace[0] + replace[1] self.name = complete_item replace = self.url.split("°") complete_item = replace[0] self.url = complete_item end end def self.all @@all end def self.find(int) @@all[int-1] end end
true
4bdced0090589d95acda907f310c152c3aad2eb0
Ruby
Mehwisha/ttt-10-current-player-v-000
/lib/current_player.rb
UTF-8
304
3.59375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def turn_count(board) counter = 0 board.each do |space| if space == "X" || space == "O" counter += 1 end end return counter end def current_player(board) if turn_count(board) == 0 || turn_count(board).even? return "X" elsif turn_count(board).odd? return "O" end end
true
dd6ecbd3cb60678cbcf742460ff06c2447984840
Ruby
b-ggs/indinero-circleci-slack-build-alerts
/helpers/slack_helper.rb
UTF-8
2,065
2.828125
3
[]
no_license
require 'httparty' module SlackHelper SLACK_API_POST_MESSAGE_URL = 'https://slack.com/api/chat.postMessage' SUCCESS_COLOR = '#41AA58' FAIL_COLOR = '#D10C20' RUNNING_COLOR = '#66D3E4' SUCCESS_MESSAGE = 'Your build passed!' NON_SUCCESS_MESSAGE = 'There was a problem with your build.' def is_slack_user?(recipient) recipient[0] == '@' end def is_success?(outcome) %w(success fixed).include? outcome end def build_slack_message(build_details, slack_recipient, options = {}) message = if is_success? build_details[:outcome] options[:custom_success_message] || SUCCESS_MESSAGE else options[:custom_non_success_message] || NON_SUCCESS_MESSAGE end attachments = [ { title: 'Build details', color: is_success?(build_details[:outcome]) ? SUCCESS_COLOR : FAIL_COLOR, fields: [ { title: 'Outcome', value: build_details[:outcome], short: true }, { title: 'Branch', value: build_details[:branch], short: true }, { title: 'Build Number', value: "<#{build_details[:build_url]}|##{build_details[:build_num]}> (triggered by #{build_details[:vcs_login]})", short: true }, { title: 'Last Commit', value: "<#{build_details[:vcs_commit_url]}|#{build_details[:vcs_commit_hash]}> by #{build_details[:vcs_commit_login]}", short: true } ] } ] { token: @slack_token, channel: slack_recipient, text: message, link_names: true, attachments: attachments.to_json } end def send_slack_message(slack_message) resp = HTTParty.post(SLACK_API_POST_MESSAGE_URL, body: slack_message) if resp.ok? log LogHelper::DEBUG, "Successfully sent Slack message to #{slack_message[:channel]}" else log LogHelper::ERROR, "Failed to send Slack message with error: #{resp['error']}" end end end
true
544cdcf9cd2b80921d3fa928753279812c161caa
Ruby
cocupu/mjg_twitter
/lib/runners/url_dataset_reducer_runner.rb
UTF-8
2,996
2.671875
3
[]
no_license
require 'fileutils' require 'date' class UrlDatasetReducerRunner < BaseRunner attr_accessor :message, :dataset_path, :dat_repository def initialize(opts={}) @start_date = opts[:start_date].kind_of?(DateTime) ? opts[:start_date] : DateTime.strptime(opts[:start_date], "%Y%m%d") @end_date = opts[:end_date].kind_of?(DateTime) ? opts[:end_date] : DateTime.strptime(opts[:end_date], "%Y%m%d") @original_dataset_path = opts[:dataset_path] if opts[:dataset_path] @dat_repository = opts[:dat_repository] end # * concatenate new linkreport(s) with trending_urls.json dataset # * reduce the concatenate datasets using url_dataset_reducer # * write the result to trending_urls-{date_string}.json def process FileUtils::mkdir_p output_directory export_original_dataset_from_dat if dat_repository dates_to_process.sort.each do |date| destination_path = destination_file_path_for(date) puts "Combining data from #{expression_for_files_to_process(date)} with the dataset #{path_to_dataset} " %x(cat #{path_to_dataset} #{expression_for_files_to_process(date)} | bundle exec wu-local #{reducer_path} > #{destination_path}) # for each consecutive pass, the output from the previous run is used as the starting dataset @dataset_path = destination_path end import_results_into_dat if dat_repository @message = "Finished merging data from #{dates_to_process.count} days with the data from #{original_dataset_path}. The cumulative result is in #{dataset_path}" end def processed_reports puts "start_date: #{start_date}" puts "start_date: #{end_date}" puts "last: #{dates_to_process.to_a.last}" destination_file_path_for(dates_to_process.to_a.last) end private def export_original_dataset_from_dat File.delete(original_dataset_path) if File.exists?(original_dataset_path) puts 'exporting original dataset from dat' dat_repository.export(dataset:'urls', write_to:original_dataset_path) end def import_results_into_dat puts 'importing results into dat' dat_repository.import(dataset: 'urls', key: 'url', file: dataset_path, message: "data for #{start_date.strftime('%F')} through #{end_date.strftime('%F')}") end def path_to_dataset @dataset_path ||= original_dataset_path end def original_dataset_path @original_dataset_path ||= data_directory+"/trending_urls.json" end def expression_for_files_to_process(date) data_directory+"/#{date.strftime("%Y_%m_%d")}-linkReport.json" end def destination_file_path_for(date) data_directory+"/trending_urls-#{date.strftime("%Y_%m_%d")}.json" end def reducer_path extractor_path = File.join(File.dirname(__FILE__),"..", "dataflows", "reduce_to_cumulative_url_history.rb") end # In this processor, data_directory and output_directory are the same def data_directory output_directory end def default_output_directory Dir.pwd+"/output" end end
true
8da54882aa1745ababfe07abb612f5d699e54d5a
Ruby
nosyjoe/codejam
/2013/round1c/a/a.rb
UTF-8
2,919
3.21875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env ruby -wKU def write_output_line(i, data) "Case ##{i}: #{data}" end def write_output_file(filename, data) i = 1 File.open(filename, 'w') do |file| data.each do |a_case| file.puts(write_output_line(i, a_case)) i += 1 end end end def read_input_file(filename) i = 1 cases = [] File.open(filename) do |file| test_count = file.readline file.each_line do |line| v = line.split("\s") cases << [v[0],v[1].to_i] end i += 1 end #puts "warning: the number of expected test cases does not match the actual" if test_count != cases.length cases end CONS = ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] CONSRE = /[bcdfghjklmnpqrstvwxyz]/ def find(word, s,e,n) if word[s,e] =~ /[bcdfghjklmnpqrstvwxyz]{n}/ return 1 + find(word, s, ) else end end # def count(word, index, n) # result = 0 # l = n # s = index # e = index+l # # while (s >= 0) # while (e <= word.length) # puts "#{s} #{e} #{l}" # result +=1 # e += 1 # end # e=index+l # s = s-1 # end # # puts "" # # result # end def count(word, index, n) result = [] l = n s = index e = index+l sub = word[index,l] while (s >= 0) while (e <= word.length) # puts "#{s} #{e} #{l}" result << "#{s},#{e}" e += 1 end e=index+l s = s-1 end # puts "" result end def find_indices(word, str) result =[] s = word while (s && i = s.index(str)) result << i s = s[i+str.length] end result end def find_nstreak(word, n) result = [] l = word.length s = 0 i = 0 while (i <l-n+1) sub = word[i,n] # puts "#{sub}" if (sub =~ /[bcdfghjklmnpqrstvwxyz]/) result << [i, sub] end i += 1 end result end OBJ = Object.new def process(data) result = [] data.each do |di| word = di[0] n = di[1] nvalue = 0 #matches = word.scan(/[bcdfghjklmnpqrstvwxyz]{#{n}}/) # positions = word.enum_for(:scan, /[bcdfghjklmnpqrstvwxyz]{#{n}}/).map { Regexp.last_match.begin(0) } #matches + find_doubles(word, matches, n) matches = find_nstreak(word, n) # puts "#{matches}" temp = {} matches.each do |m| ids = count(word, m[0], n) ids.each do |id| # puts "id: #{id}" temp[id] = OBJ end end # puts "#{positions}" # positions.each do |index| # nvalue += count(word, index, n) # end result << temp.length # result << nvalue end # do something here result end inFilename = ARGV[0] if inFilename outFilename = inFilename.sub("\.in", ".out") cases = read_input_file(inFilename) processed_data = process(cases) write_output_file(outFilename, processed_data) else puts "Please specify input file" end
true
89664bfdcf3edc2d44e27240360ace8ec0178cb5
Ruby
talgoldfus/Tic-Tac
/lib/opponent.rb
UTF-8
218
3.375
3
[]
no_license
class Opponent attr_accessor :mark ,:score attr_reader :name def initialize(mark) @mark=mark @score=0 @name="Computer" end def turn puts "Computer is choosing his next move" choice = rand(1..9) end end
true
d94e3f5f03dc4ff1fc7c1e7a8a527f899b1eabaa
Ruby
nishimura121/oyou10
/config/schedule.rb
UTF-8
963
2.65625
3
[]
no_license
# Use this file to easily define all of your cron jobs. # # It's helpful, but not entirely necessary to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron env :PATH, ENV['PATH'] # 絶対パスから相対パス指定 set :output, 'log/cron.log' # ログの出力先ファイルを設定 set :environment, :development # 環境を設定 every 1.minutes do rake 'mail:sample' end =begin class Tasks::Marimotask def self.marimo #modelやlibのメソッド呼んだり Marimodel.hoge Malib::Marimo.nyanya #適当な処理書いたり foo #putsしてみたり puts "成功しました!" end end =end # Example: # # set :output, "/path/to/my/cron_log.log" # # every 2.hours do # command "/usr/bin/some_great_command" # runner "MyModel.some_method" # rake "some:great:rake:task" # end # # every 4.days do # runner "AnotherModel.prune_old_records" # end # Learn more: http://github.com/javan/whenever
true
74d65ec7290cdd9f7316c0d62516508cb1c89644
Ruby
intuit-archive/s3cmd-cookbook
/libraries/download.rb
UTF-8
331
2.59375
3
[ "Apache-2.0" ]
permissive
class Download def command(args) bucket = args[:bucket] object_name = args[:object_name] file_name = args[:file_name] force = args[:force] ? '--force' : '' object_url = "s3://#{File.join bucket, object_name}" cmd = "s3cmd #{force} " cmd << "get #{object_url} #{file_name}" end end
true
9a92cdac8e12bbedbb2f98eb6eb43d67088e7f4c
Ruby
hatuyo/kadai
/pico.rb
UTF-8
3,152
3.75
4
[]
no_license
# coding: utf-8 require 'minitest/autorun' # ピコ太郎を表すクラス # @author Kento Matsumoto # @attr [String] name 人の名前 # @attr [String] right 右手の物 # @attr [String] left 左手の物 # @attr [String] result1 合わされた物1 # @attr [String] result2 合わされた物2 class Pico attr_accessor :name, :right, :left, :ummm # コンストラクタ # @param name [String] 人の名前 # @param right [String] right 右手の物 # @param left [String] left 左手の物 # @param [String] result1 合わされた物1 # @param [String] result2 合わされた物2 def initialize(name, right, left, result1, result2) @name = name @right = right @left = left @result1 = result1 @result2 = result2 end # 右手になにを持つか決める時に呼ばれるメソッド # @param obj [Fixnum] 右手に何をもつか # @return [Pico] ピコ太郎を返す # @example 右手にペンを持つ # Pico.I_have_a_right("pen") def I_have_a_right(obj) @right = obj self end # 左手になにを持つか決める時に呼ばれるメソッド # @param obj [Fixnum] 左手に何をもつか # @return [Pico] ピコ太郎を返す # @example 左手にペンを持つ # Pico.I_have_a_left("pen") def I_have_a_left(obj) @left = obj self end # 両手に何か持ってる時にだけ合体させ、あわよくば終わるメソッド # @param left [Fixnum] 左手 # @param right [Fixnum] 右手 # @return [Pico] ピコ太郎を返す # @example 両手の物を合わせる # Pico.ummm(right,left) def ummm(right,left) if @right == right && @left == left then if @result1.empty? then @result1 = right + left elsif @result2.empty? then @result2 = right + left else puts "ERROR!手に持ってる物がおかしいです" end if ! @result1.empty? && ! @result2.empty? then puts "#{@result1}#{@result2}" puts "#{@result1}#{@result2}" puts "曲が終わり!" end end end tarou = Pico.new("ピコ太郎", "", "", "", "",) tarou.I_have_a_right("Pen") tarou.I_have_a_left("Pineapple") tarou.ummm(tarou.right,tarou.left) tarou.I_have_a_left("Apple") tarou.I_have_a_right("Pen") tarou.ummm(tarou.right,tarou.left) end class TestPico < Minitest::Test def setup @pc = Pico.new("ピコ太郎", "", "", "", "",) end # I_have_a_rightで右手に持つことをチェック def test_I_have_a_right @pc.I_have_a_right("Pen") assert_equal("Pen", @pc.right) end # I_have_a_leftで左手に持つことをチェック def test_I_have_a_left @pc.I_have_a_left("Painappow") assert_equal("Painappow", @pc.left) end # ummmでresultに合わせた結果入れることをチェック #メソッドが見つかららない?なぞのエラーにつきテスト断念 def test_ummm @pc.I_have_a_right("Pen") assert_equal("Pen", @pc.right) @pc.I_have_a_left("Painappow") assert_equal("Painappow", @pc.left) @pc.ummm(@pc.right,@pc.left) assert_equal("PenPainappow", @pc.result1) end end
true
fd5e40770be027061279c668bbd239874489d6cc
Ruby
camerican/wdi-sep-2017
/week5/lunch.rb
UTF-8
202
3.359375
3
[]
no_license
# take an array of menu options # then pick a random lunch item options = ["Thai Sliders","Bon Chon","Jubiliee"] def lunch( menu ) #menu[rand(menu.length)] menu.sample end puts lunch( options )
true
b76faff0816231503b6154ce29e8ee0fc9a67936
Ruby
xpmethod/torn-apart
/ruby/article-grabber.rb
UTF-8
890
2.796875
3
[]
no_license
require "csv" require "httparty" # articles = CSV.read(File.join("data", "state-articles.csv"), headers: true) articles = CSV.read(File.join("..", "data", "everything-articles.csv"), headers: true) articles.to_a.shuffle.each_with_index do |row, i| # filename = "#{row[0]}-#{row[2]}-#{i}.html" filename = "#{row[0]}-#{row[1]}-#{i}.html" if File.exist?(File.join("..", "data", "downloads", "everything", "html", filename)) puts "skipping #{filename}" else begin response = HTTParty.get(row[5]) # response = HTTParty.get(row[6]) File.open(File.join("..", "data", "downloads", "everything", "html", filename),"w") { |file| file.write(response.body) } puts "#{row[0]}: #{row[1]}." # puts "#{row[0]}: #{row[2]}." rescue puts "Errored on index #{i} with #{row[5]}." # puts "Errored on index #{i} with #{row[6]}." end end end
true
512cc9f4d04a669d918cd4e3b5c6d4a2b765f442
Ruby
eliastre100/Advent-of-Code-2020
/day 15/day_15.rb
UTF-8
509
3.625
4
[ "MIT" ]
permissive
#!/usr/bin/env ruby require_relative 'count_table' if ARGV.size != 2 warn 'Usage: ./day_15.rb [input file] [target]' exit 1 end input = File.read(ARGV.first).chomp target = ARGV[1].to_i count_table = CountTable.new(input) puts "Playing the game until the turn #{target}. It might take a while depending on your target" until count_table.turns == target do count_table.play_turn end puts "After #{count_table.turns} turns, the last number to have been spoken is #{count_table.last_spoken_number}"
true
e654b233ec500e4484c93bf7811717481ce7d866
Ruby
digitalh2o2/project-euler-multiples-3-5-q-000
/lib/oo_multiples.rb
UTF-8
425
3.84375
4
[]
no_license
# Enter your object-oriented solution here! class Multiples def initialize(limit) @limit = limit end def limit @limit end def collect_multiples numbers = [] (1...limit).each do |num| if num % 3 == 0 || num % 5 == 0 numbers << num end end numbers end def sum_multiples sum = 0 collect_multiples.each do |number| sum += number end sum end end
true
06fc963f723eb2d71a5bb48c00e0b21c5a6ab34b
Ruby
onorton/gottree
/characterAdder.rb
UTF-8
3,549
3.734375
4
[]
no_license
#!/usr/bin/env ruby def createCharacter puts "Creating character...\n\n" total_string = "" total_string += (IO.readlines('characters.txt').last.split(" ")[0].to_i+1).to_s + "\t" puts "Please enter the character's name:\n" total_string += gets.chomp + "\t" puts "Please enter the character's gender (M, F, or NULL):\n" gender = gets.chomp if gender.empty? total_string += "NULL" else total_string += gender end total_string += "\t" puts "Please enter the character's house (or NULL):\n" house = gets.chomp if house.empty? total_string += "NULL" else total_string += house end total_string += "\t" puts "Please enter the character's father (or NULL):\n" father = gets.chomp if father.empty? total_string += "NULL" else total_string += father end total_string += "\t" puts "Please enter the character's mother (or NULL):\n" mother = gets.chomp if mother.empty? total_string += "NULL" else total_string += mother end total_string += "\t" puts "Please enter the character's year of birth (or -1):\n" year_of_birth = gets.chomp if year_of_birth.empty? total_string += "-1" else total_string += year_of_birth end total_string += "\t" puts "Please enter the character's year of death (or NULL for alive or -1):\n" year_of_death = gets.chomp if year_of_death.empty? total_string += "NULL" else total_string += year_of_death end total_string += "\t" puts "Please enter the character's wiki link (or NULL):\n" wiki_link = gets.chomp if wiki_link.empty? total_string += "NULL" else total_string += wiki_link end open('characters.txt', 'a') { |f| f.puts total_string } puts "Character added to characters.txt\n" end def addRelationship puts "Adding relationship\n" total_string = "" total_string += (IO.readlines('relationships.txt').last.split(" ")[0].to_i+1).to_s + "\t" puts "Please enter the primary person:\n" primary = gets.chomp if primary.empty? total_string += "NULL" else total_string += primary end total_string += "\t" puts "Please enter the secondary person:\n" secondary = gets.chomp if secondary.empty? total_string += "NULL" else total_string += secondary end total_string += "\t" puts "Is the relationship legitimate?:\n" legitimate = gets.chomp if legitimate.empty? total_string += "0" else total_string += legitimate end open('relationships.txt', 'a') { |f| f.puts total_string } puts "Relationship added to relationships.txt\n" end puts "Welcome to character adder.\n" done = false while !done do puts "Would you like to:\n" puts "\t1. Add a new character\n" puts "\t2. Add a new relationship\n" puts "Hit q to quit\n\n" choice = gets.chomp case choice when "1" createCharacter() when "2" addRelationship() else done = true end end
true
5cbee6ae55d0312a6695f0adf7fca6ccc9922929
Ruby
tblanchard01/oyster_card
/lib/Oystercard.rb
UTF-8
922
3.671875
4
[]
no_license
# boots up new Oyster class Oystercard MIN_BALANCE = 1 attr_reader :balance attr_accessor :in_journey, :entry_station, :exit_station, :list_of_journeys def initialize(monies = 0) @balance = monies @in_journey = false @entry_station = nil @exit_station = nil @list_of_journeys = [] end def top_up(amount) raise 'error: balance cannot exceed 90' if @balance + amount > 90 @balance += amount end def touch_in(entry_station) raise 'Error: Insufficient funds' if @balance.zero? @in_journey = true @entry_station = entry_station @list_of_journeys.push(entry: entry_station) #creates new hash end def touch_out(exit_station) @in_journey = false @exit_station = exit_station deduct(MIN_BALANCE) @list_of_journeys.last[:exit] = exit_station # adds to existing hash end private def deduct(amount) @balance -= amount end end
true
6124a0d68f1c7e19b7012c8f9f4d45c5f928da84
Ruby
russellkoons/learning-ruby
/module_6/01strings.rb
UTF-8
169
4.03125
4
[]
no_license
puts "I am a string" puts "I can also include characters and \nnumbers: # $ ! 5 9" name = "Russell" puts name.length puts name.class p 5.to_s # Makes 5 into a string
true
52e31c969a3d0634fdcb1dd5471b462fb18b8a4e
Ruby
qubis741/ruby-interview
/checkout.rb
UTF-8
1,725
3.140625
3
[]
no_license
require './promotional_rule_factory' require './promotional_rule' class Checkout attr_accessor :promotional_rules, :total, :items, :total_percentage_discount def initialize(promotional_rules) @promotional_rules = promotional_rules.map do |pr| PromotionalRuleFactory.build( id: pr[:id], name: pr[:name], condition: pr[:condition], offer: pr[:offer] ) end @items = {} @total = 0 @total_percentage_discount = 1 end def scan(item) @items["item_#{@items.size}"] = item.clone count_total apply_promotional_rules @promotional_rules.each { |pr| pr.applied_rule = false } end def total "#{@total} £" end private def apply_promotional_rules promotional_rules.each do |pr| next if !pr || pr.applied_rule if pr.is_a?(TotalPricePercentageDiscount) apply_rule(pr) do @total_percentage_discount = pr.apply_rule(@total) end end if pr.is_a?(ItemPriceChange) item_count = item_count(pr.condition[:target]) apply_rule(pr) do map_items_of_kind(pr.offer[:target]) do |items_of_kind| pr.apply_rule(item_count, items_of_kind) end end end end count_total end def apply_rule(pr) yield apply_promotional_rules if pr.applied_rule end def map_items_of_kind(id) items_of_kind = items.select { |_key, item| item.id == id } yield(items_of_kind) end def item_count(id) items.select { |_key, item| item.id == id }.count end def count_total temp = 0 @items.each { |_key, item| temp += item.price } @total = (temp * @total_percentage_discount).round(2) end end
true
b0c8ad6511a4130bc04342151cd5d98c9c5ec539
Ruby
CepCap/intern
/work/bisrch/bisrch.rb
UTF-8
625
3.34375
3
[]
no_license
def bisrch(arr, find_value) arr.sort! loop do mid = arr.length/2 break if mid.zero? if arr.length == 2 if arr[0] == find_value break true elsif arr[1] == find_value break true else break false end end mid_el = arr[mid] if mid_el == find_value break true elsif mid_el > find_value arr = arr[0..mid] else arr = arr[mid..-1] end end end p bisrch([1,2,3,4,5], 1) p bisrch([1,2,3,4,5], 5) p bisrch((1..500000).to_a, 23425) p bisrch([2,3,76,345,323,4346,457,54,63], 63) p bisrch([12432,436457457,243436456,2341231231], 1)
true
555bf0f7270492d553ef7813c6639b9c66fe0b57
Ruby
nomlab/swimmy
/lib/swimmy/resource/event.rb
UTF-8
604
2.578125
3
[ "MIT" ]
permissive
# coding: utf-8 require 'pp' require 'date' require 'fileutils' require 'active_support/time' module Swimmy module Resource class Event attr_reader :start,:summary,:calendar_name def initialize(start, summary, calendar_name) @start = DateTime.parse(start) @summary = summary @calendar_name = calendar_name end def day_of_week days_of_week = ["None","月","火","水","木","金","土","日"] day_of_week = @start.strftime('%u') day_of_week = days_of_week[day_of_week.to_i]; end end end end
true
f05c37e8fba245635f834ebae5fc89b6eeb26955
Ruby
ctrhansen/OO-Art-Gallery-houston-web-career-021819
/tools/console.rb
UTF-8
398
2.65625
3
[]
no_license
require_relative '../config/environment.rb' painting1 = Painting.new("A Happy Landscape", 3000, "Bob Ross", "Houston Art Gallery") painting2 = Painting.new("A Sad Landscape", 1000, "Bob Ross", "New York Art Gallery") painting3 = Painting.new("A Moody Landscape", 3000, "Bob Ross", "San Francisco Art Gallery") gallery = Gallery.new("Houston Art Gallery", "Houston") binding.pry puts "Bob Ross rules."
true
7033b2b2529d7a484715c6364421686b7066fd92
Ruby
Jordan-1996/Arrays
/aumento_precios.rb
UTF-8
425
3.328125
3
[]
no_license
prices = [200, 3000, 5000] # multiplicador = rand(3) # def augment(prices, multiplicador) # resolve = [] # prices.count.times do |i| # prices[i] *= multiplicador # resolve.append(prices[i]) # end # return resolve # end # print augment(prices, multiplicador) prices = ARGV def augment(array, factor) array.map do |price| price.to_i*factor end end print augment(prices,4)
true
4b7723c89f56db382d4e30b4237d4533971d9155
Ruby
alexnvb/Ruby
/Old study/Lesson 14/class_plane.rb
UTF-8
825
3.125
3
[]
no_license
class Airplane attr_reader :model attr_reader :alt attr_reader :speed def initialize(model) @model=model @alt=0 @speed=0 end def fly @speed=800 @alt=10000 end def land @speed=0 @alt=0 end def moving? return @speed>0 end end plane1=Airplane.new("SuperJet") puts "Model: #{plane1.model} Speed: #{plane1.speed} Alt: #{plane1.alt}" puts "Plane moving: #{plane1.moving?}" plane1.fly puts "Model: #{plane1.model} Speed: #{plane1.speed} Alt: #{plane1.alt}" puts "Plane moving: #{plane1.moving?}" plane1.land puts "Model: #{plane1.model} Speed: #{plane1.speed} Alt: #{plane1.alt}" puts "Plane moving: #{plane1.moving?}" plane2=Airplane.new('TU-154') plane2.fly puts "Model: #{plane2.model} Speed: #{plane2.speed} Alt: #{plane2.alt}" puts "Plane moving: #{plane2.moving?}"
true
57ed198a4e486ef413dc8ad68b9c55a639f6fb31
Ruby
jeffrafter/gemstalker
/bin/gemstalk
UTF-8
1,663
2.859375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/usr/bin/env ruby $LOAD_PATH.unshift(File.dirname(__FILE__), '..', 'lib') require 'gem_stalker' def usage puts "" puts "Usage:" puts "" puts " #{File.basename $0} <username> <repository> [version] [--install]" puts "" puts "Begins stalking a gem at the specified location. Example:" puts "" puts " #{File.basename $0} techinicalpickles jeweler" end if ARGV.length == 0 || ARGV.include?("-h") || ARGV.include?("--help") usage exit end trap "SIGINT" do puts "" puts "Stopping" exit end options = {:username => ARGV[0], :repository => ARGV[1]} options[:version] = ARGV[2] if ARGV.length >= 3 && ARGV[2] != '--install' options[:install] = true if ARGV.include?('--install') stalker = GemStalker.new(options) $stdout.sync = true unless stalker.gem? puts "The repository is not configured as a rubygem yet." puts "Go to the following url, and check 'RubyGem'" puts "\t#{stalker.edit_repo_url}" exit end if ARGV.length < 3 puts "Using version #{stalker.version}" end waiting = false puts "Checking to see if the gem has been built:" loop do if stalker.built? puts "." if waiting puts "=> Zomg, it's built, I'm so telling everyone!" puts "=> http://gems.github.com/#{stalker.gem_path}" break end print "." waiting = true sleep(5) end # Now that it is built lets install if options[:install] puts "=> Installing built gem" stalker.install end waiting = false puts "Checking to see if it is in the specfile:" loop do if stalker.in_specfile? puts "." if waiting puts "=> Sweeeet, everyone can install it now!" break end print "." waiting = true sleep(60*5) end
true
ca9277cf241a85dcc0860d550d321c49d95d363f
Ruby
ktlacaelel/abstract_command
/lib/abstract_command.rb
UTF-8
2,064
3.375
3
[ "MIT" ]
permissive
require 'open3' require 'shellwords' # Shell Command Abstraction. # # Hides away all the details to generate a command. # And provides an easy interface to interact with shell commands as if # they were objects. # # This is good for the following reasons: # # - Enforces standardization. # - Enforces separation of command definition and consumption. # - Enforces configuration over code. # - Enforces configuration over refactoring. # - Enforces simple shell-command definition. # - Enforces automatic sanitization of variables that get interpolated. # - Provides a simple Object Oriented Interface. # - Provides a scope for variables that belong to the command. # - Provides getters and setter for every interpolation in command. # - Provides a neat interface that plugs to data structures transparently. # - Avoids methods with many arguments. # - Avoids changes in the standared libarary: system, backtick, etc. # class AbstractCommand # '%<name>s'.scan(/(%<)(\w+)(>)/) # => [["%<", "name", ">"]] VARIABLE_REGEX = /(%<)(\w+)(>)/ def template raise 'must implement' end def variables result = [] template.scan(VARIABLE_REGEX).each do |variable| result.push(variable[1]) end result end def initialize(properties = {}) variables.each do |variable| self.class.send(:attr_accessor, variable.to_sym) end properties.each do |key, value| setter = (key.to_s + '=').to_sym send(setter, value) end end def to_s bindings = {} variables.each do |variable| value = instance_variable_get("@#{variable}") bindings[variable.to_sym] = "#{value}".shellescape end format(template, bindings) end def system super(to_s) end def backtick `#{to_s}` end def execute begin stdout, stderr, status = Open3.capture3(to_s) status = status.exitstatus rescue StandardError => error stdout = "" if(error.message) stderr = error.message end status = 1 end return stdout, stderr, status end end
true
d894d9b38090607137b0052450f8dd0a72430e04
Ruby
mkroman/mumble
/library/mumble/connection.rb
UTF-8
2,346
2.609375
3
[]
no_license
# encoding: utf-8 module Mumble class Connection < EM::Connection HeaderSize = 6 # The header is 6 bytes. HeaderFormat = 'nN' # The type is 2 bytes, and the length value is 4 bytes def initialize client = nil # Create a new server connection. # # @param [Server] server The server reference. def initialize server = nil @server = server @server.connection = self super end # Called post-initialization. def post_init @log = Logging.logger[self] @buffer = String.new @message_handlers = [] @log.debug "Creating secure connection" tls_options = { ssl_version: :TLSv1, private_key_file: @server.cert_manager.private_key_path, cert_chain_file: @server.cert_manager.public_certificate_path } start_tls tls_options end def ssl_handshake_completed @log.debug "SSL handshake completed" @server.connection_completed end def ssl_verify_peer peer_cert p peer_cert end # Called when data have been received. def receive_data data @buffer << data while @buffer.bytesize >= HeaderSize # Read the header. type, length = @buffer.unpack HeaderFormat message_size = HeaderSize + length # Read the body. if @buffer.bytesize >= message_size if klass = Messages::MessageTypes[type] # Parse the message. message = klass.new message.parse_from_string @buffer.slice HeaderSize, length @server.receive_message message end @buffer.slice! 0, message_size end end end # Send a message to the server. # # @param [Protobuf::Message] message_type The message class. # @param [Hash] attributes The message attributes. def send_message message_type, attributes = {} message = message_type.new attributes.each do |name, value| message.__send__ :"#{name}=", value end @log.debug "Sending message #{message_type}" @log.debug message.to_hash.ai body = message.serialize_to_string header = [Messages::MessageTypes.key(message_type), body.bytesize].pack HeaderFormat send_data header + body end def unbind @log.fatal "Connection lost" end end end
true
dfd5cf3d0df6ce397b96e70055c4ab5fe3be3d1a
Ruby
nickzaf95/project-euler-largest-prime-factor-london-web-021720
/lib/oo_largest_prime_factor.rb
UTF-8
598
3.625
4
[]
no_license
# Enter your object-oriented solution here! class LargestPrimeFactor attr_accessor :limit def initialize(limit) @limit = limit end def number n = @limit test = 1 while test % 2 == 0 do test = n / 2 end if test == 2 return 2 end i = 3 while i < ((n**0.5).round()) do while n % i == 0 do test = i n = n / i end i = i + 2 end if n > 2 test = n end return test end end
true
633d9e46ca98219cc08cad58d30a411aba5d736c
Ruby
TPei/faas_orchestrator
/lib/post_function.rb
UTF-8
466
2.59375
3
[ "MIT" ]
permissive
class PostFunction < Function def execute(data) header = {'Content-Type': 'text/json'} # Create the HTTP objects http = Net::HTTP.new(@uri.host, @uri.port) request = Net::HTTP::Post.new(@uri.request_uri, header) request.body = data.to_json # Send the request res = http.request(request) if res.is_a?(Net::HTTPSuccess) log_results(data, res, 'POST') return res.body else handle_error(data) end end end
true
ea5ab26d473a062c802932256c7774c411d76381
Ruby
schlos/OpenAidRegister
/app/models/project_sector.rb
UTF-8
2,730
2.59375
3
[]
no_license
class ProjectSector # find Project Sector by id #---------------------------------------------------------------------- def self.find(id) sql = 'select cartodb_id, project_id, sector_id, the_geom_str FROM project_sectors WHERE cartodb_id = ?' result = Oar::execute_query(sql, id) result.rows.first end def self.create(project_id, sector_id) sql = "INSERT INTO project_sectors (project_id, sector_id) VALUES (?, ?)" Oar::execute_query(sql, project_id, sector_id) end def self.create_many(project_id, sectors) if sectors sectors.each do |sector| ProjectSector.create(project_id, sector[:id]) end end end # Returns an array of sector ids that belongs to the given project # # @param [Integer] the project_id # @return [Array] array of sector ids #---------------------------------------------------------------------- def self.ids_where_project_id(project_id) sql = "select array_agg(sector_id) from project_sectors where project_id = ?" result = Oar::execute_query(sql, project_id) first_row = result.rows.first if first_row[:array_agg] eval("[#{first_row[:array_agg][1..-2]}]") else [] end end # Returns an array of hashes with the key ":id" and the value == the sector_id # these sectors belongs to the given project # # @param [Integer] the project_id # @return [Array] array of hashes of the form {:id => sector_id} #---------------------------------------------------------------------- def self.kv_ids_where_project_id(project_id) sql = "select sector_id as id from project_sectors where project_id = ?" result = Oar::execute_query(sql, project_id) result.try :rows end def self.by_organization_id_grouped_by_project(organization_id) sql = "select project_id, array_agg(project_sectors.sector_id) AS sector_id from project_sectors INNER JOIN projects ON project_sectors.project_id = projects.cartodb_id WHERE organization_id =? GROUP BY project_id" result = Oar::execute_query(sql, organization_id) #result.rows.each do |row| # row[:sector_id] = eval('['+row[:sector_id][1..-2]+']') #end result.rows end def self.names sql = "select project_sectors.sector_id, name, sector_code from project_sectors INNER JOIN sectors ON project_sectors.sector_id = sectors.cartodb_id" result = Oar::execute_query(sql) result.rows end # DELETE! #---------------------------------------------------------------------- def self.delete_by_project_id(project_id) sql = "DELETE FROM project_sectors where project_id = '?'" Oar::execute_query(sql, project_id) end end
true
cc1d97ecc9edcbb11103543bf3fb15ff59207d42
Ruby
m-negishi/ruby_training
/TeachYourselfRuby/section8/8_check.5.rb
UTF-8
520
3.71875
4
[]
no_license
# 何乗するかを保持する場合 def make_gs_gen(ft, cr) ans = 0 count = 0 lambda do ans = ft * (cr ** count) count += 1 ans end end # 今の解答を保持する場合 # def make_gs_gen(ft, cr) # ans = 0 # lambda do # if ans != 0 # ans *= cr # else # ans = ft # end # end # end gen1 = make_gs_gen(1, 2) # 初項1, 公比2 gen2 = make_gs_gen(10, 10) # 初項10, 公比10 puts gen1.call puts gen1.call puts gen1.call puts gen2.call puts gen2.call puts gen2.call
true
a0819edd3758f28b0b01a3c3ac0a37322003a306
Ruby
ricamarena/Code-KIEI925
/final/db/seeds.rb
UTF-8
2,062
2.5625
3
[]
no_license
puts "Deleting..." Project.delete_all User.delete_all Owner.delete_all Investment.delete_all puts "Creating Owners..." altaventures = Owner.create(name: "Alta Ventures", summary:"alta ventures is a firm", rating: 4) fivere = Owner.create(name: "5 RE", summary:"5re is a firm", rating: 5) lp = Owner.create(name: "Leisure Partners", summary:"LP is a firm", rating: 6) hydepark = Owner.create(name: "Hyde Park Venture Partners", summary:"Hyde Park is a firm", rating: 7) bjb = Owner.create(name: "BJB", summary:"Crappy Management", rating: 4) puts "Creating Projects..." house1 = Project.create(name: "Beach House", location: "Miami", image:"beach.jpg", summary: "On the Beach", owner_id: altaventures.id, raised: "0", goal: "5000") house2 = Project.create(name: "Country House", location: "Milwakee", image:"country.jpg", summary: "On the Country", owner_id: fivere.id, raised: "0", goal: "4000" ) house3 = Project.create(name: "City House", location: "Chicago", image:"city.jpg", summary: "House on the City", owner_id: lp.id, raised: "0", goal: "3000") house4 = Project.create(name: "Apartment", location: "New York", image:"apartment.jpg", summary: "Big Apartment", owner_id: hydepark.id, raised: "0", goal: "2000") house5 = Project.create(name: "Condo", location: "Evanston", image:"condo.jpg", summary: "Small Condo", owner_id: bjb.id, raised: "0", goal: "1000") puts "Creating Users..." john = User.create(name: "John", username: "ke5", bio:"I am Doe") doe = User.create(name: "Doe", username: "ke4", bio:"I am Doe") smith = User.create(name: "Smith", username: "ke3", bio:"I am Smith") jane = User.create(name: "Jane", username: "ke2", bio:"I am Jane") sparta = User.create(name: "Sparta", username: "ke1", bio:"I am Sparta") kellogg = User.create(name: "Kellogg", username: "ke0", bio:"I am Kellogg") puts "Creating Investments..." Investment.create(project_id: house1.id, user_id: john.id, amount: 300) Investment.create(project_id: house3.id, user_id: doe.id, amount: 500) Investment.create(project_id: house3.id, user_id: sparta.id, amount: 1000)
true
6de9ac27caf61952ae36fa4fae604d4b80e25a34
Ruby
Smorenor91/Battleship
/game.rb
UTF-8
2,367
3.671875
4
[]
no_license
#!/usr/bin/ruby require 'matrix' class Matrix def to_readable i = 0 self.each do |number| print number.to_s + " " i+= 1 if i == self.column_size print "\n" i = 0 end end end def []= (row, column, value) @rows[row][column] = value end end class Board def initialize() @board = Matrix.build(11,11) {|row, col| "[ ]"} for i in 1..10 @board[0,i] = "[#{i}]" @board[i,0] = "[#{i}]" end end def printAll() for i in 0..11 for j in 0..11 print @board[i,j] end puts "" end end def putsShips(x, y, n, o, l) l = l.to_i x = x.to_i y = y.to_i if(@board[x.to_i,y.to_i] == "[ ]") if(o == "V") if(x+l >= 11) puts "Error, espacio inadecuado" return true end for i in 0..l if(@board[i+x,y] != "[ ]") puts "Espacio ya ocupado" return true end end else(o =="H") if(y+l >= 11) puts "Error, espacio inadecuado" return true end for i in 0..1 if(@board[x,y+1] != "[ ]") puts "Espacio ya ocupado" return true end end end else puts "Espacio ya ocupado" return true end puts "SI JALO" if(o == "V") for i in 0..l @board[x+i,y] = "[#{n}]" end else(o =="H") for i in 0..l @board[x, y+i] = "[#{n}]" end end return false end end $myBoard = Board.new() $enemyBoard = Board.new() $myBoard.printAll varLetra=0 varNumero=0 orientacion= "" shipList = [] shipList[0]= "Lancha" shipList[1]= "Avance" shipList[2]= "Batalla" shipList[3]= "Destructor" shipList[4]= "Transportador" letterList = [] letterList[0]= "L" letterList[1]= "A" letterList[2]= "B" letterList[3]= "D" letterList[4]= "T" for i in 0..4 acepta = true while acepta do rest= 5-i puts "Tienes #{rest} unidades que escojer:" puts "Donde quieres poner el #{shipList[i]}" puts "Eje X" varLetra = gets varLetra.to_i puts "Eje Y" varNumero = gets varNumero.to_i puts "Orientacion (V/H)" orientacion= gets.chomp l = i + 1 acepta =$myBoard.putsShips(varLetra, varNumero, letterList[i], orientacion, l) end $myBoard.printAll end
true
801b6d2209fa25352afbeb8fd38c3d835f94dacf
Ruby
UC10D/RubyDemo
/ruby_lang/error.rb
UTF-8
159
2.953125
3
[]
no_license
# 异常捕获 puts '===================Error=================='; (-10 .. 10).each { |a| begin puts 100/ a rescue Exception => e p e.to_s end }
true
acca2fcdd4d437daf1f4f6f6b8e295a55d62b310
Ruby
rudyoyen/starSearch
/rubySolution/movies.rb
UTF-8
729
3.234375
3
[]
no_license
require "./utils/MovieDatabase" require "./utils/Output" first_arg, second_arg = ARGV first_name = first_arg || '' last_name = second_arg || '' full_name = last_name == '' ? first_name : first_name + ' ' + last_name if full_name == '' puts "Please provide a star's name to search" exit(true) end #Define meta data for source file FILE_NAME = "./movies.txt" LINES_PER_MOVIE = 4 SPACES_BETWEEN_MOVIE = 1 STARS_LINE_INDEX = LINES_PER_MOVIE - 1 #assumes the line with the list of stars is last in each movie data chunk movie_db = MovieDatabase.new(FILE_NAME, LINES_PER_MOVIE, SPACES_BETWEEN_MOVIE, STARS_LINE_INDEX) results = movie_db.search(full_name) Output.new(results, full_name).ascending.without_current_star.print
true
33e027fca5ec611de7a9cfc2087509b9974603ee
Ruby
itsolutionscorp/AutoStyle-Clustering
/assignments/ruby/hamming/src/218.rb
UTF-8
205
3.109375
3
[]
no_license
def compute(s1, s2) i = 0 n = s1.length n_differences = 0 while (i < n) if (s1[i] != s2[i]) n_differences += 1 end i += 1 end return n_differences end
true
67673b3201224a2df867afb6b79e16916cd58fff
Ruby
h4hany/yeet-the-leet
/algorithms/Easy/1260.shift-2d-grid.rb
UTF-8
1,249
3.609375
4
[]
no_license
# # @lc app=leetcode id=1260 lang=ruby # # [1260] Shift 2D Grid # # https://leetcode.com/problems/shift-2d-grid/description/ # # algorithms # Easy (61.37%) # Total Accepted: 18.8K # Total Submissions: 30.6K # Testcase Example: '[[1,2,3],[4,5,6],[7,8,9]]\n1' # # Given a 2D grid of size m x n and an integer k. You need to shift the grid k # times. # # In one shift operation: # # # Element at grid[i][j] moves to grid[i][j + 1]. # Element at grid[i][n - 1] moves to grid[i + 1][0]. # Element at grid[m - 1][n - 1] moves to grid[0][0]. # # # Return the 2D grid after applying shift operation k times. # # # Example 1: # # # Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 1 # Output: [[9,1,2],[3,4,5],[6,7,8]] # # # Example 2: # # # Input: grid = [[3,8,1,9],[19,7,2,5],[4,6,11,10],[12,0,21,13]], k = 4 # Output: [[12,0,21,13],[3,8,1,9],[19,7,2,5],[4,6,11,10]] # # # Example 3: # # # Input: grid = [[1,2,3],[4,5,6],[7,8,9]], k = 9 # Output: [[1,2,3],[4,5,6],[7,8,9]] # # # # Constraints: # # # m == grid.length # n == grid[i].length # 1 <= m <= 50 # 1 <= n <= 50 # -1000 <= grid[i][j] <= 1000 # 0 <= k <= 100 # # # # @param {Integer[][]} grid # @param {Integer} k # @return {Integer[][]} def shift_grid(grid, k) end
true
7a61294abf6b05bd32da34fbef0418288cd76a8c
Ruby
rralcala/pyeduca-infra
/mothership/puppet/puppetcontent/configs/check_nodes/check_nodes.rb
UTF-8
2,187
3.1875
3
[]
no_license
#!/usr/bin/ruby # # Get the list of nodes from a conf file and loop # forever checking status (via tcp ping) and update # their status via ActiveResource # require File.join(File.dirname(__FILE__), 'node.rb') require 'ping' require "socket" class NetworkNode def initialize(node_id, ip_address) @node_id = node_id @ip_address = ip_address end def update_status() stat = get_status() Node.setStatus(@node_id, stat) end private def get_status() Ping.pingecho(@ip_address) ? :up : :down end end class CheckNodes SLEEP_TIME = 120 MAX_RETRIES = 3 CONF_FILE = File.join(File.dirname(__FILE__), "../etc", "nodes.conf") def initialize(conf_file = CheckNodes::CONF_FILE) @conf_file = conf_file readConfFile() @site = getConfKey("site") @user = getConfKey("user") @password = getConfKey("password") @sleep_time = getConfKey("sleep_time") || CheckNodes::SLEEP_TIME @sleep_time = @sleep_time.to_i @hostname = Socket.gethostname end def run nodes = getNodes() if nodes != [] while true begin nodes.each { |n| n.update_status() } rescue Node.log("run loop : " + $!.to_s) end sleep(@sleep_time) end else Node.log("ZERO nodes retrieved.") end end private def getNodes() Node.set_params(@site, @user, @password) nodes = [] while (nodes == []) nodes = Node.allNodesAt(@hostname) sleep(@sleep_time) if nodes == [] end nodes.map { |n| NetworkNode.new(n["id"], n["ip_address"]) } end def readConfFile() @conf_settings = Hash.new File.open(@conf_file, "r") do |fp| lines = fp.readlines() lines.each { |l| next if l.match(/^#/) l.chomp! k,v = l.split("=") k = clean_str(k) v = clean_str(v) @conf_settings[k] = v } end @conf_settings end def getConfKey(k) @conf_settings[k] end def clean_str(s) ret = s ret.gsub!(/\"/, "") if ret.match(/\"/) ret.gsub!(/ /, "") if ret.match(/ /) ret end end # main cn = CheckNodes.new cn.run()
true
183afee58e54bff7f1b88d4648225c41147cae21
Ruby
cdalbergue/drivy-backend-challenge
/backend/level4/commission.rb
UTF-8
856
3.1875
3
[]
no_license
class Commission COMMISSION_PERCENTAGE = 0.3 INSURANCE_COMMISSION = 0.5 ROADSIDE_ASSISTANCE_COMMISSION = 100 attr_reader :price, :duration, :total_commission def initialize(rental) @price = rental.price @duration = rental.duration @total_commission = total_commission end def value { insurance_commission: insurance_commission, assistance_commission: roadside_assistance_commission, drivy_commission: drivy_commission } end def total_commission price * COMMISSION_PERCENTAGE end private def insurance_commission (total_commission * INSURANCE_COMMISSION).to_i end def roadside_assistance_commission (duration * ROADSIDE_ASSISTANCE_COMMISSION).to_i end def drivy_commission (total_commission - insurance_commission - roadside_assistance_commission).to_i end end
true
e0f78302c0e0fdc0941994e5000bb7f8af5a014d
Ruby
isabella232/puppet-adopt
/lib/puppet_x/adopter/util.rb
UTF-8
345
2.53125
3
[]
no_license
module PuppetX::Adopter::Util def self.run_with_spinner(timeout = 30, &block) spin_thread = Thread.new do loop do ['|','/','-','\\'].each { |c| print c; sleep 0.1; print "\b" } end end Timeout::timeout(timeout) do return block.call end ensure spin_thread.terminate print "\n" end end
true
f404427c6d08c53b364de294e6f0d1d34a60264e
Ruby
rickpeyton/learntoprogram_chris_pine
/chapter11archive.rb
UTF-8
4,396
3.515625
4
[]
no_license
require 'yaml' test_array = [ ['Rick','Brady'], ['Rebecca','Kaarin'], ['Abe','Richard'], ] test_string = test_array.to_yaml filename = 'rick_test.txt' File.open filename, 'w' do |f| f.write test_string end read_string = File.read(filename) read_array = YAML::load read_string puts(read_string == test_string) puts(read_array == test_array) puts test_string puts read_array puts read_array[2][1] ##### buffy_quote_1 = '\'Kiss rocks\'? Why would anyone want to kiss... Oh, wait. I get it.' buffy_quote_2 = "'Kiss rocks'?\n" + "Why would anyone want to kiss...\n" + "Oh, wait. I get it." puts buffy_quote_1 puts buffy_quote_2 puts(buffy_quote_1 == buffy_quote_2) puts "3...\n2...\n1...\nHappy New Year!" puts "#{2 * 10 **4 + 1} Leagues Under the Sea, THE REVENGE!!!" ##### require 'yaml' # Define yaml save and load methods... def yaml_save object, filename File.open filename, 'w' do |f| f.write(object.to_yaml) end end def yaml_load filename yaml_string = File.read filename YAML::load yaml_string end test_array = [ 'Slick Shoes', 'Bully Blinders', 'Pinchers of Peril' ] filename = 'DatasGadgets.txt' # Save it yaml_save test_array, filename # Load it read_array = yaml_load filename puts(read_array == test_array) ##### # Moving and renaming pictures program Dir.chdir '/Users/rick/Desktop/Chapter 11 Finished Pictures' # First we find all of the pictures to be moved. pic_names = Dir['/Users/rick/Desktop/Chapter 11 Picture Renaming/**/*.jpg'] puts 'What would you like to call this batch?' batch_name = gets.chomp puts print "Downloading #{pic_names.length} files: " # This is out counter. We'll start at 1 today, # though normally I like to count from 0. pic_number = 1 pic_names.each do |name| print '.' # This is our "progress bar". new_name = if pic_number < 10 "#{batch_name}0#{pic_number}.jpg" else "#{batch_name}#{pic_number}.jpg" end # New name contained the entire directory path # new_name stripped out the directory path and # is replaced via File.rename below. File.rename name, new_name pic_number = pic_number + 1 end puts # This is so we aren't on progress bar line. puts 'Done.' ##### puts "Safer Picture Downloading" # Moving and renaming pictures program Dir.chdir '/Users/rick/Desktop/Chapter 11 Finished Pictures' # First we find all of the pictures to be moved. pic_names = Dir['/Users/rick/Desktop/Chapter 11 Picture Renaming/**/*.jpg'] puts 'What would you like to call this batch?' batch_name = gets.chomp puts print "Downloading #{pic_names.length} files: " # This is out counter. We'll start at 1 today, # though normally I like to count from 0. pic_number = 1 def renamer older_name, newer_name, picture_increment File.rename older_name, newer_name picture_increment = picture_increment + 1 return picture_increment end pic_names.each do |name| print '.' # This is our "progress bar". new_name = if pic_number < 10 "#{batch_name}0#{pic_number}.jpg" else "#{batch_name}#{pic_number}.jpg" end # Check to see if the new file already exists if (File.exists? new_name) == true puts '' puts "#{new_name} already exists." puts 'Would you like to skip (S), replace (R) or exit (X)?' response = gets.chomp.capitalize good_response = false while good_response != true if response == 'S' puts "Skipping #{new_name}" pic_number = pic_number + 1 good_response = true elsif response == 'R' puts "Replacing #{new_name}" pic_number = renamer(name, new_name, pic_number) good_response = true elsif response == 'X' puts 'Exiting program' exit else puts 'Please enter S, R or X' response = gets.chomp.capitalize end end else pic_number = renamer(name, new_name, pic_number) end end puts # This is so we aren't on progress bar line. puts 'Done.' ##### puts 'Build Your Own Playlist Program v1.0' # Each line in a text file is the path to a song. # Give the filename an .m3u extension # Use the shuffle method to create a playlist # Store the playlists here # /Users/rick/Desktop/generated_playlists filename = 'playlist1.m3u' Dir.chdir('/Users/rick/Desktop/generated_playlists') # Find all of the mp3s # /Users/rick/Desktop/music_keep all_music = Dir['/Users/rick/Desktop/music_keep/**/*.mp3'] shufflled_music = all_music.shuffle File.open filename, 'w' do |d| shufflled_music.each do |x| d.write x + "\n" end end
true
9f082ac7511fbf3e0a97c2a0aa01a2a3f128783c
Ruby
lbvf50mobile/til
/20221230_Friday/20221230.rb
UTF-8
856
3.421875
3
[]
no_license
# Leetcode: 797. All Paths From Source to Target. # https://leetcode.com/problems/all-paths-from-source-to-target/ # = = = = = = = = = = = = = = # Accepted. # Thanks God, Jesus Christ! # = = = = = = = = = = = = = = # Runtime: 156 ms, faster than 84.62% of Ruby online submissions for All Paths From Source to Target. # Memory Usage: 215.2 MB, less than 7.69% of Ruby online submissions for All Paths From Source to Target. # @param {Integer[][]} graph # @return {Integer[][]} def all_paths_source_target(graph) @n = graph.size @l = @n - 1 @g = graph @v = Array.new(@n,false) @path = [] @answer = [] backtracking(0) return @answer end def backtracking(i) return if @v[i] @path.push(i) @v[i] = true if @l == i @answer.push(@path.clone) else @g[i].each do |j| backtracking(j) end end @path.pop() @v[i] = false end
true
3e6ca67fea90c56899821b5fba9c14a403f4e8e0
Ruby
adilgondal1/sinatra-mvc-lab-yale-web-yss-052520
/models/piglatinizer.rb
UTF-8
565
3.75
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class PigLatinizer def initialize() end def piglatinize(str) str.split(" ").map {|word| piglatinize_word(word)}.join(" ") end def piglatinize_word(str) vowels = ['a' , 'e' , 'i' , 'o' ,'u'] ary = str.split(//) index = ary.find_index {|c| vowels.include?(c.downcase)} if index == 0 str + "way" else consonants = str[0...index] new_start = str[index..] new_start + consonants + "ay" end end #binding.pry end
true
4c2d1e8208acca562a26723d46b8dd0b8450047d
Ruby
MattKwong/myssp-cedar
/spec/models/program_spec.rb
UTF-8
4,870
2.65625
3
[]
no_license
require 'spec_helper' # == Schema Information # # Table name: programs # # id :integer not null, primary key # active :boolean # created_at :timestamp # end_date :date # name :varchar(255) # program_type_id :integer # short_name :varchar(255) # site_id :integer # start_date :date # updated_at :timestamp # describe Program do before (:each) do @attr = { :name => "Program", :site_id => Site.find_by_name("Test Site 3").id, :start_date => Date.today+3, :end_date => Date.today+4, :program_type_id => ProgramType.find_by_name("Summer Domestic").id, :active => true} end #validates :name, :presence => true, :uniqueness => true #validates :short_name, :presence => true, :uniqueness => true #validates :site_id, :presence => true #validates :start_date, :presence => true #validates :end_date, :presence => true #validates :program_type_id, :presence => true #validates :active, :inclusion => [true, false] #validate :start_date_before_end_date # NOT THIS ONE YET #validate :start_date_not_in_past it "should create a new instance with valid attributes" do #relies on seed data for a program type item = Program.new(@attr) item.should be_valid end describe "name/short name tests" do it "should automatically generate a name" do item = Program.new(@attr.merge(:name => "")) item.should be_valid end it "should be unique" do item1 = Program.create!(@attr.merge(:name => "")) item2 = Program.new(@attr.merge(:name => "")) item2.should_not be_valid end it "should generate correct name" do item1 = Program.create!(@attr.merge(:name => "")) item1.name.should == "Test Site 3 Summer Domestic 2013" end it "should generate correct short_name" do item1 = Program.create!(@attr.merge(:short_name => "")) item1.short_name.should == "SN SuDo 13" end end it "should require a site_id (and thereby a site to link to)" do expect { item = Program.create!(@attr.merge(:site_id => "")) }.to raise_error #item = Program.create!(@attr.merge(:site_id => "")) #item.should_not be_valid end it "should require a start date" do expect { item = Program.create!(@attr.merge(:start_date => "")) }.to raise_error #item = Program.new(@attr.merge(:start_date => "")) #item.should_not be_valid end it "should require a end date" do #expect { item = Program.create!(@attr.merge(:end_date => "")) }.to raise_error item = Program.new(@attr.merge(:end_date => "")) item.should_not be_valid end it "should require a program type id" do expect { item = Program.create!(@attr.merge(:program_type_id => "")) }.to raise_error #item = Program.new(@attr.merge(:program_type_id => "")) #item.should_not be_valid end it "should require active boolean" do #expect { item = Program.create!(@attr.merge(:active => "")) }.to raise_error item = Program.new(@attr.merge(:active => "")) item.should_not be_valid end it "summer_domestic? should return true if it is a Summer Domestic Program" do item = Program.new(@attr) item.summer_domestic?.should == true end #it "summer_domestic? should return false if it is not a Summer Domestic Program" do # item = Program.new(@attr.merge(:program_type => "Not a Summer Domestic")) # item.summer_domestic?.should == false #end pending "How to test total days?" do item = Program.new(@attr) puts(item.total_days) end it "start date should be before end date" do #expect { item = Program.create!(@attr.merge(:active => "")) }.to raise_error item = Program.new(@attr.merge(:end_date => Date.today, :start_date => Date.today+1)) item.should_not be_valid end it "start date should not be in the past" do #expect { item = Program.create!(@attr.merge(:active => "")) }.to raise_error item = Program.new(@attr.merge(:end_date => Date.today-3)) item.should_not be_valid end it "How to test to_current?" it "How to test first_session_start?" it "How to test last_session_end?" it "How to test to_s" it "How to test number of adults" it "How to test number of youth" it "How to test budget_item_name" it "How to test budget_item_spent" it "How to test budget_item_spent_with_tax" it "How to test budget_item_budgeted" it "How to test budget_item_remaining" it "How to test spent_total" it "How to test spent_with_tax_total" it "How to test budgeted_total" it "How to test remaining_total" it "How to test purchased_items" it "How to test purchased_food_items" it "How to test purchased_food_items (there are 2 of these?)" it "How to test first_session_id" it "How to test last_session_id" end
true
d3551b12cc69d2e2085b87985441d943ae6cc56f
Ruby
michaelhayman/dogood-api
/test/unit/models/user_test.rb
UTF-8
1,784
2.578125
3
[]
no_license
class UserTest < DoGood::TestCase def setup super @user = FactoryGirl.create(:user) end test "has a valid name" do assert @user.valid?, "Should be valid" end test "should be valid with all default values" do assert FactoryGirl.build(:user).valid? end test "should have an email address" do assert FactoryGirl.build(:user).valid? refute FactoryGirl.build(:user, email: "").valid? end test "should have a password" do assert FactoryGirl.build(:user).valid? refute FactoryGirl.build(:user, password: "").valid? end test "should return a specific user" do user2 = FactoryGirl.create(:user, email: Faker::Internet.email) assert_equal @user, User.by_id(@user.id) end test "test should return a user's rank" do assert_equal "Beginner", @user.rank @user.level = 1 @user.save assert_equal "Volunteer", @user.rank end test "it should return a user's points" do points = 5000 @user.add_points(points, category: 'Bonus') assert_equal points, @user.points end class UserTest::UpdatePassword < DoGood::TestCase def setup super @user = FactoryGirl.create(:user) @password = HashWithIndifferentAccess.new({ current_password: @user.password, password: "oh_billy", password_confirmation: "oh_billy" }) end test "no errors returned if the params are valid" do @user.update_password(@password) assert @user.errors.count == 0 end test "errors with missing params" do @bad_password = HashWithIndifferentAccess.new({ current_password: "", password: "", password_confirmation: "" }) @user.update_password(@bad_password) assert @user.errors.count > 0 end end end
true
c6fd893aa29583730991835824f19c3fba3d0e41
Ruby
achalaggarwal/myimdb
/lib/myimdb/scraper/base.rb
UTF-8
2,006
2.796875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
class UnformattedHtml < Exception; end class DocumentNotFound < Exception; end class ScraperNotFound < Exception; end module Myimdb module HandleExceptions EXCEPTIONS_ENABLED = true def self.included(base) base.send(:include, InstanceMethods) base.send(:extend, ClassMethods) end module InstanceMethods end module ClassMethods def handle_exceptions_for(*method_names) method_names.each do |method_name| alias_method("_#{method_name}", method_name) define_method(method_name) do begin send("_#{method_name}") rescue if EXCEPTIONS_ENABLED raise UnformattedHtml.new("Unable to find tag: #{method_name}, probably you are parsing the wrong page.") else nil end end end end end end end module Scraper class Base include HandleExceptions include Myimdb::Scraper::StringExtensions def name; end def directors; end def directors_with_url; end def writers; end def writers_with_url; end def rating; end def votes; end def genres; end def tagline; end def plot; end def year; end def release_date; end def image; end def summary [:directors, :writers, :rating, :votes, :genres, :tagline, :plot, :year, :release_date].collect do |meth| data = send(meth) data = data.join(", ") if Array === data sprintf("%-15s : %s", meth.to_s.capitalize, data) end.join("\n") end def to_hash movie_as_hash = {} [:directors, :writers, :rating, :votes, :genres, :tagline, :plot, :year, :release_date].each do |meth| movie_as_hash[meth] = send(meth) end movie_as_hash end def self.all ['Freebase', 'Metacritic', 'RottenTomatoes', 'Imdb'] end end end end
true
b0ade60d330c4ac575f874b17557ac9b76659b48
Ruby
panesofglass/RubyOnMonads
/lib/identity.rb
UTF-8
179
3.03125
3
[]
no_license
class Identity attr_reader :value def initialize( value ) @value = value end def bind yield @value end def map Identity.new( yield @value ) end end
true
55c5fc3e81fcf1e2b6899616f0cb42b587705e22
Ruby
sg552/bubu
/app/models/category.rb
UTF-8
1,055
2.609375
3
[]
no_license
class Category < ActiveRecord::Base PRINCIPLE_BY_USAGE = "by_usage" PRINCIPLE_BY_SHAPE= "by_shape" PRINCIPLE_BY_AGE = "by_age" AGE_SCOPES_FOR_SEARCH = ["0-3", "4-6", "7-9", "10-14"] # define scope # :by_usage # :by_shape # :by_age [PRINCIPLE_BY_AGE, PRINCIPLE_BY_USAGE, PRINCIPLE_BY_SHAPE].each do |by| scope by.to_sym, where(:principle => by).where("name != '不限'") end def generic_items(limit=nil) generic_items = GenericItem.where("category_id_#{principle} = #{id}") limit.blank? ? generic_items.all : generic_items.limit(limit) end def self.get_categories_by_scope( string_scope, principle) result = [] self.send(principle).all.each do |category| if (self.to_array(category.name) & self.to_array(string_scope)).size > 0 result << category end end return result end private def self.to_range(string_scope) array = string_scope.split("-") (array.first.to_i..array.last.to_i) end def self.to_array(string_scope) to_range(string_scope).to_a end end
true
b2df29218e85de0a601efc6e4d486a5119ce3f58
Ruby
mrdougal/textmate2-rubocop
/Support/vendor/gems/rubocop-0.18.1/spec/rubocop/cop/style/favor_sprintf_spec.rb
UTF-8
1,309
2.53125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# encoding: utf-8 require 'spec_helper' describe Rubocop::Cop::Style::FavorSprintf do subject(:cop) { described_class.new } it 'registers an offence for a string followed by something' do inspect_source(cop, ['puts "%d" % 10']) expect(cop.offences.size).to eq(1) expect(cop.messages) .to eq(['Favor sprintf over String#%.']) end it 'registers an offence for something followed by an array' do inspect_source(cop, ['puts x % [10, 11]']) expect(cop.offences.size).to eq(1) expect(cop.messages) .to eq(['Favor sprintf over String#%.']) end it 'does not register an offence for numbers' do inspect_source(cop, ['puts 10 % 4']) expect(cop.offences).to be_empty end it 'does not register an offence for ambiguous cases' do inspect_source(cop, ['puts x % 4']) expect(cop.offences).to be_empty inspect_source(cop, ['puts x % Y']) expect(cop.offences).to be_empty end it 'works if the first operand contains embedded expressions' do inspect_source(cop, ['puts "#{x * 5} %d #{@test}" % 10']) expect(cop.offences.size).to eq(1) expect(cop.messages) .to eq(['Favor sprintf over String#%.']) end end
true
b0168ae84797cde3f0ba8b94057cd9be6c1e5aa3
Ruby
EDalSanto/OperatingSystems
/processes/unix_processrb/pipes_spawning.rb
UTF-8
256
3.09375
3
[]
no_license
# UNIX pipes in pure ruby puts IO.popen("ls").read # an IO object is passed into black # in this case we open the stream for writing, # so the stream is set to the STDIN of the spawned process IO.popen("less", "w") { |stream| stream.puts "some\ndata" }
true
2fd687cc21c3044fd432106df47b71e928637e73
Ruby
bdarfler/CodeKata
/ruby/05/KataFiveTest.rb
UTF-8
812
3.140625
3
[]
no_license
require 'test/unit' require 'KataFive' class KataFiveTest < Test::Unit::TestCase @@spell_checker = BloomFilter.new('/usr/share/dict/words') def test_contains word = 'hello' bloom_filter = BloomFilter.new() bloom_filter.insert(word) assert(bloom_filter.contains(word), "filter should contain #{word}") end def test_does_not_contain word = 'hello' bloom_filter = BloomFilter.new() bloom_filter.insert("#{word} world") assert(!bloom_filter.contains(word), "filter should not contain #{word}") end def test_spelling_contains word = 'hello' assert(@@spell_checker.contains(word), "#{word} should be a word") end def test_spelling_does_not_contain word = 'bobloblaw' assert(!@@spell_checker.contains(word), "#{word} should not be a word") end end
true
177f91cf899f65042725999bdd5553235baa1081
Ruby
swethagnath/ruby-programs
/arrayornot.rb
UTF-8
326
4.5
4
[]
no_license
#Write a Ruby method to check whether an `input` is an array or not. # e.g. - check_is_array(10) # => false # check_is_array([10,20,30]) # => true def check_is_array(number) if number.class == Array return true else return false end end puts check_is_array(10) puts check_is_array([10,20,30])
true
a7ed8f161c53042f52d220fdba5d954c60a52396
Ruby
alu0100600810/LPP_T_03
/lib/examen/exam.rb
UTF-8
569
3.3125
3
[ "MIT" ]
permissive
# coding: utf-8 require "lista" # Clase gestora de examenes con preguntas class Exam attr_accessor :list # Crea una instancia de la clase Exam , a partir de una pregunta. def initialize(p) @list = Lista.new(p) end # Definición del Metotodo to_s, para la clase Exam. def to_s "#{@list}" end # Sobrecarga del operador << para insertar preguntas al final del Examen. def <<(p) @list << p end # Inserta una o varias preguntas sucesivamente. def push_back(*preguntas) preguntas.each { |p| @list << p} preguntas end end
true
ec620e40e248b1abe2a224de5ff0bc6f39b166fc
Ruby
Duncan-Britt/Launch-School-Prep-Exercises
/Loops_and_Iterators/3.rb
UTF-8
91
2.984375
3
[]
no_license
def count_down(num=10) return if num == 0 puts num count_down(num-1) end count_down
true
101ec27b77c1112d1756c51e9bc5cb1db304c8b7
Ruby
turingschool-examples/vehicle_boolean
/lib/vehicle_analysis.rb
UTF-8
794
3.390625
3
[]
no_license
# vehicle_analysis.rb class VehicleAnalysis def analyze(vehicle) if vehicle.car? if vehicle.four_wheel_drive? || !vehicle.four_wheel_drive? puts "Vehicle has four wheels " if vehicle.four_wheel_drive? puts "with four wheel drive" else puts "with two wheel drive" end end elsif vehicle.tractor? puts "Vehicle has four wheels " if vehicle.big_back_wheels? puts "with big wheels in the back" end elsif vehicle.pickup? puts "Vehicle has four wheels " if vehicle.four_wheel_drive? puts "with four wheel drive" else puts "with two wheel drive" end if vehicle.big_back_wheels? puts "with big wheels in the back" end end end end
true
6d08298cbf1ffbf03ead789b53302a166296125e
Ruby
imurchie/chess
/lib/chess.rb
UTF-8
1,572
3.765625
4
[ "Apache-2.0" ]
permissive
require_relative './board' require_relative './human_player' module Chess class Game GRID_MAP = { "h" => 7, "g" => 6, "f" => 5, "e" => 4, "d" => 3, "c" => 2, "b" => 1, "a" => 0, "1" => 7, "2" => 6, "3" => 5, "4" => 4, "5" => 3, "6" => 2, "7" => 1, "8" => 0 } def initialize end def play board = Board.new players = [HumanPlayer.new(:white), HumanPlayer.new(:black)] current_player = 0 until board.game_over?(players[current_player].color) # puts board board.show_grid while true begin start_pos, end_pos = get_input(players[current_player]) board.move(start_pos, end_pos, players[current_player].color) rescue InvalidMoveException => e puts e.message next end break end current_player = next_player(current_player) end board.show_grid if board.checkmate?(:white) puts "Black won!" else puts "White won!" end end private def get_input(player) puts "#{player.name}: Enter move." # input = gets.chomp.gsub(/[^12345678abcdefghq]/, "") input = player.next_move if input == "q" exit end original = [GRID_MAP[input[1]], GRID_MAP[input[0]]] target = [GRID_MAP[input[3]], GRID_MAP[input[2]]] [original, target] end def next_player(player) (player == 0 ? 1 : 0) end end end chess = Chess::Game.new chess.play
true
c8d4e255c67eca46cf5c28c161d217feb9e4fd2f
Ruby
andeeisaacs/prework_backend
/db/notseeds2.rb
UTF-8
14,112
3.296875
3
[]
no_license
# Parent classes topics = [{ # Topic id 1 title: 'Html' }, { # Topic id 2 title: 'JavaScript' }, { # Topic id 3 title: 'CSS' }] # Creates Topic for seed file topics.each do |v| Topic.create v end # START OF HTML # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # Code Modules but in this case Lessons codeModules = [{ # Code Module id 1 lesson: 'Intro to HTML Elements & Structure', completed: false, topic_id: 1 }, { # Code Module id 2 lesson: 'Tables', completed: false, topic_id: 1 }, { # Code Module id 3 lesson: 'Types Of Lists', completed: false, topic_id: 1 }] # Creates CodeModules for seed file codeModules.each do |v| CodeModule.create v end # Code Module 1 starts here ~~~~~~~~~~~~~~~~~~~~~ lessons = [{ # Lesson id 1 title: 'History of HTML', content: "Hyper Text Markup Language: structure and content of a page. Not the styling, not the functionality. Basically the skeleton. In the early days of the internet, there was no standardized way of sending information and documents. Internet was mostly used for communication between colleges and universities as well as the military. If I wanted any formatting to happen with my document, I needed to be able to break that down to smaller pieces. Thus, HTML was made to handle it around 1989/1990. Some headers, some things are bolded or important italicized, some bullet points, bigger and smaller text, etc Eventually moved onto more broad uses. Remember myspace? Probably used HTML/CSS to edit your page. Think of HTML as the skelton of your program!", completed: false, code_module_id: 1 }, { # Lesson id 2 title: 'What is a tag?', content: "HTML tags are the hidden keywords within a web page that define how your web browser must format and display the content. HTML tags typically fall into the following format: There are hundreds of tags in HTML! You can look to MDN (Mozilla Developer Network) ar W3 Schools to see all of the tags available. Don't feel obligated by any means to memorize these. There are a few that you will use often (div, h1, p, etc.) and some that you will likely never use! At this point, just get familiar with the anatomy of a typical HTML tag.", completed: false, code_module_id: 1, img_src: "https://camo.githubusercontent.com/391be322ebc71fef013423d9b4ff55812e79f2ba/68747470733a2f2f692e6962622e636f2f363878664679422f53637265656e2d53686f742d323032302d30342d30362d61742d31302d35342d30392d414d2e706e67", }, { # Lesson id 3 title: 'HTML Boiler Plate', content: "In your text editor (Atom or VS Code), if you type HTML and hit tab, the text editor will generate an HTML boiler plate. Let's break down what it is you're looking at in the boiler plate: It is important to understand what each tag in the boiler plate is responsible for! But for now, we will be working inside of the body tag.", completed: false, code_module_id: 1, img_src: "https://camo.githubusercontent.com/6c03627339b71f371fadd857e3858af7759fca24/68747470733a2f2f692e6962622e636f2f486759685733682f53637265656e2d53686f742d323032302d30342d30362d61742d31312d34362d32392d414d2e706e67" }, { # Lesson id 4 title: "What is an HTML attribute?", content: "HTML attributes are special words used inside the opening tag to control the element's behaviour. HTML attributes are a modifier of an HTML element type. For example, an <a> tag defines a hyperlink on your page. Techniaclly, the <a> tag is a complete tag on it's own. However, we need to add an href attribute to tell the hyperlink where we want to go once it's clicked. An entire <a> tag will look something like this: <a href='www.google.com'>Click this link to go to Google!</a> Above, we see the <a> tag, the href attribute inside of the opening tag, a URL defined inside of the href attribute, some text for the user to click on, and a closing </a> tag! Voila! Let's look at another example. An <img> tag will render an image. But the tag alone cannot do the job, we need to add an attribute! Here, we will add a src attribute which will include the URL of the image we want to render. <img src='www.image_source_goes_here.com'> Notice how the <img> tag doesn't close? That's because it's a self-closing tag! Since there is no inner HTML in an image, this tag doesn't required a closing tag. To take a deeper dive on inner HTML, make sure you join Jumpstart! One more example. A <p> tag represents a paragraph. You can change how the text in your paragraph looks by using a style attribute! The code below will change the font color to blue. <p style='color:blue'>I'm blue da ba dee da ba daa</p> To recap, in all of our examples, the attribute is modifying the HTML element in some way. ", completed: false, code_module_id: 1 # Code Module 1 ends here~~~~~~~~~ }, # Code Module 2 starts here~~~~~~~~ { # Lesson id 5 title: 'Intro To Tables', content: "Let's use a <table> tag to build the table below!", completed: false, code_module_id: 2, img_src: "https://camo.githubusercontent.com/7e2f94fe63c11541611feaca0ad881ac2bf6aecc/68747470733a2f2f692e6962622e636f2f3934366b6431482f53637265656e2d53686f742d323032302d30342d30382d61742d31302d32352d31372d414d2e706e67" }, { # Lesson id 6 title: 'The Table Tag', content: "First, we will need to code opening and closing <table> tags. <table> </table>", completed: false, code_module_id: 2 }, { # Lesson id 7 title: 'Table Rows', content: "Next we will need to tell the table how many rows we would like. We do this by nesting <tr> (table row) tags inside of the <table> tags. The table we hope to make will have three rows. <table> <tr></tr> <tr></tr> <tr></tr> </table>", completed: false, code_module_id: 2 }, { # Lesson id 8 title: 'Adding Cells', content: "Now we need to tell the table how many columns we will need. We do this my nesting <td> (table data) tags inside of the <tr> tags. Each <td> tag represents a cell in the row. We know we want the table to be three cells wide. First things first though, we need to stay organized since our table is getting more complicated! We are going to drop all of the closing </tr> tags down to a new line before adding in our <td>'s. This will make it very clear to us where exactly each row ends. <table> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> <tr> <td></td> <td></td> <td></td> </tr> </table> Look how clean that is! Each nested section is indented a single tab over and we can clearly see where all of our elements begin and end!", completed: false, code_module_id: 2 }, { # Lesson id 9 title: 'Adding Data', content: "We probably want our table to contain some data right? Let's drop some text inside of the cells in the table. <table> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td>9</td> </tr> </table> Lastly, we will want to add a border so that we can outline the table and all of it's cells. We do this by adding an attribute to the opening <table> tag. <table border=1> <tr> <td>1</td> <td>2</td> <td>3</td> </tr> <tr> <td>4</td> <td>5</td> <td>6</td> </tr> <tr> <td>7</td> <td>8</td> <td>9</td> </tr> </table>", completed: false, code_module_id: 2 }, { # Lesson id 10 title: 'Practice Time With Tables!', content: "Great work! Practice coding out the HTML table below:", completed: false, code_module_id: 2, img_src: "https://camo.githubusercontent.com/408a38b72849652bae524ac29f7d743d016bae24/68747470733a2f2f692e6962622e636f2f746d306b644a642f53637265656e2d53686f742d323032302d30342d30382d61742d31302d34342d33312d414d2e706e67" # Code Module 2 ends here ~~~~~~~~~~~~~~~~~~~~~~~ }, # Code Module 3 starts here ~~~~~~~~~~~~~~~~~~~~~ { # Lesson id 11 title: 'Ordered Lists', content: "Let's talk about listing items! In HTML, there are two ways to write a list. There can be ordered (numbered) lists:", img_src: "https://camo.githubusercontent.com/3e2b6d58ec0f617feda92721d3d35f186aecbac6/68747470733a2f2f692e6962622e636f2f537448667250322f53637265656e2d53686f742d323032302d30342d30392d61742d31302d33302d34362d414d2e706e67", completed: false, code_module_id: 3 }, { # Lesson id 12 title: 'Unordered List', content: "Or unordered (bullet-point) lists:", img_src: "https://camo.githubusercontent.com/e98556a8606b91962c7fe139d22daee7a21c518c/68747470733a2f2f692e6962622e636f2f466d47464d39352f53637265656e2d53686f742d323032302d30342d30392d61742d31302d33302d35382d414d2e706e67", completed: false, code_module_id: 3 }, { # Lesson id 13 title: 'Adding List Items (Table Data)', content: "Let's walk through the process. Say we want to create a seating list for a party at our restaurant. We have 2 tables, and we want to have 3 people at every table. First, we know we want an ordered list for all of the tables. We start an ordered list with the <ol> tag: <ol> </ol> Now we need to add the tables to our list. We create list items with the <li> tag. <ol> <li></li> <li></li> </ol> At this point, our table has no data. We will want to add our table names: <ol> <li>Patio</li> <li>Dining Room</li> </ol> Our list is starting to take shape!", img_src: "https://camo.githubusercontent.com/f50bc64e157588e4568b750de97cf1f598127b7a/68747470733a2f2f692e6962622e636f2f67746d5a3162322f53637265656e2d53686f742d323032302d30342d30392d61742d31302d34332d35382d414d2e706e67", completed: false, code_module_id: 3 }, { # Lesson id 14 title: 'Nesting Unordered List', content: "Now it's time to assign guests to tables. We can do that by nesting a unordered lists inside of out ordered lists. We will start by dropping the closing </li> tags down to the next line to make room for our nested list. Like in the Tables Module, we want our code to be very organized and clean. <ol> <li>Patio </li> <li>Dining Room </li> </ol> Between our opening and closing <li> tags, we are going to start new unordered lists. We already know that each table will have three guests. We can go ahead and add three <li>'s (list items) inside of each <ul> (unordered list): <ol> <li>Patio <ul> <li></li> <li></li> <li></li> </ul> </li> <li>Dining Room <ul> <li></li> <li></li> <li></li> </ul> </li> </ol> Looking good!", img_src: "https://camo.githubusercontent.com/56953c64e651591f50f0fb446598ef6f254f0a9f/68747470733a2f2f692e6962622e636f2f307456717934582f53637265656e2d53686f742d323032302d30342d30392d61742d31302d35312d31362d414d2e706e67", completed: false, code_module_id: 3 }, { # Lesson id 15 title: 'Adding List Items Part 2', content: "Finally, we can add the guests' names to each <li> within the <ul>'s: <ol> <li>Patio <ul> <li>Jose</li> <li>Gina</li> <li>Blanca</li> </ul> </li> <li>Dining Room <ul> <li>Heather</li> <li>Sean</li> <li>Macy</li> </ul> </li> </ol> Woo! That's a good lookin' list!", img_src: "https://camo.githubusercontent.com/3be7a620cab2e641428b54d2855b55794d64ae09/68747470733a2f2f692e6962622e636f2f376a76304672792f53637265656e2d53686f742d323032302d30342d30392d61742d31302d35332d32312d414d2e706e67", completed: false, code_module_id: 3 }, { # Lesson id 16 title: 'Practice Time With Tables Part 2!', content: "Now you try!", completed: false, code_module_id: 3 }] # Code module 3 ends here~~~~~~~~~~~~~~~~~~~~~~~~~~ # Creates Lessons for seed file lessons.each do |v| Lesson.create v end questions = [{ # Question id 1 multiple_choice: false, completed: false, lesson_id: 10, code_module_id: 2 }, { # Question id 2 multiple_choice: false, completed: false, lesson_id: 16, code_module_id: 3 }, { # Question id 3 (Render your first h1!) multiple_choice: false, title: "Render Your First h1!", content: "HTML: <h1> Hello world! </h1>", completed: false, lesson_id: 1, code_module_id: 1 }, { # Question id 4 (Quiz: The anatomy of a tag) multiple_choice: true, title: 'Where is the opening tag?', content: "'A', 'B', 'C'", answer: 'A', img_src: "https://camo.githubusercontent.com/3c835e90505422e327d1b6f8b69611da2adcb343/68747470733a2f2f692e6962622e636f2f477642624c33702f7175697a2e706e67", completed: false, lesson_id: 2, code_module_id: 1 }] # Creates Questions for seed file questions.each do |v| Question.create v end resources = [{ # Resource id 1 name: 'MDN HTML Tags', link: "https://developer.mozilla.org/en-US/docs/Web/HTML/Element", question_id: 4 }] # Creates Resources for seed file resources.each do |v| Resource.create v end
true
6dd6ce7161f3b674ea34b94350be38b65e2c6e60
Ruby
lenertzdiane/api-muncher
/lib/muncher_api_wrapper.rb
UTF-8
1,469
3.03125
3
[]
no_license
require "httparty" # require 'pry' class MuncherApiWrapper BASE_URL = "https://api.edamam.com/" KEY = ENV["EDAMAM_KEY"] ID = ENV["EDAMAM_ID"] class ApiError < StandardError end def self.search(search_term, from = 0) url = BASE_URL + "search?q=" + search_term + "&app_id=#{ID}" + "&app_key=#{KEY}" + "&from=#{from}" puts "about to send request for recipes" data = HTTParty.get(url) puts "got response" puts " status: #{data.code}: #{data.message}" puts "parsed_response is #{data.parsed_response}" # unless data["ok"] # raise ApiError.new("Call to list recipes failed") # end recipes_list = [] if data["hits"] data["hits"].each do |recipe_data| recipes_list << create_recipe(recipe_data["recipe"]) end end return recipes_list end def self.show(uri) encoded_uri = URI.encode(uri) url = BASE_URL + "search?r=#{encoded_uri}" #+ uri + "&app_id=#{ID}" + "&app_key=#{KEY}" data = HTTParty.get(url) return create_recipe(data[0]) #where what is returned just for one, how to access?? end private def self.create_recipe(recipe_params) return Recipe.new( recipe_params["label"], recipe_params["uri"], { image: recipe_params["image"], ingredients: recipe_params["ingredientLines"], health: recipe_params["healthLabels"], source: recipe_params["source"] } ) end end
true
52a7134c10cdbc5571ab10c4d5a8c1d22a1cced0
Ruby
shysteph/vagrant-port
/lib/vagrant-port/command.rb
UTF-8
1,072
2.515625
3
[]
no_license
module VagrantPort class Command < Vagrant.plugin("2", :command) Settings = Struct.new(:machines) def execute require "optparse" settings = Settings.new settings.machines = [] options = OptionParser.new do |o| o.banner = "Query which host port is mapped to the given guest port.\n" \ "Usage: vagrant port <guest_port_number>" o.on("-m MACHINE", "The machine to query") do |value| settings.machines << value end end settings.machines = ["default"] if settings.machines.empty? argv = parse_options(options) if argv.nil? || argv.empty? puts options.help return 1 end found = false with_target_vms(settings.machines) do |machine| machine.provider.driver.read_forwarded_ports.each do |active, name, host, guest| if argv.include?(guest.to_s) puts host found = true end end end return 1 if !found # fail if no forwarded ports found. return 0 end end end
true
300375e1c114ea0efe693f187ac6872747e98381
Ruby
fapapa/ar-exercises
/lib/store.rb
UTF-8
722
2.578125
3
[]
no_license
# frozen_string_literal: true class Store < ActiveRecord::Base validates :name, length: { minimum: 3 } validates :annual_revenue, numericality: { greater_than: 0, only_integer: true } validate :mens_apparel_or_womens_apparel_must_be_true has_many :employees before_destroy :check_for_employees def mens_apparel_or_womens_apparel_must_be_true if !mens_apparel && !womens_apparel errors.add(:mens_apparel, "can't be false if womens apparel is also false") errors.add(:womens_apparel, "can't be false if mens apparel is also false") end end private def check_for_employees return false if employees.count.positive? end end
true
49e3f168637996452eaae9497652963f07a0a7a1
Ruby
Gabbendorf/martian_robots
/spec/movements_spec.rb
UTF-8
1,630
3.296875
3
[]
no_license
require_relative '../lib/movements' RSpec.describe Movements do let (:movements) {Movements.new} describe "Robot turns clockwise" do it "returns E if robot's initial orientation is N" do expect(movements.change_orientation_clockwise("N")).to eq("E") end it "returns W if robot's initial orientation is S" do expect(movements.change_orientation_clockwise("S")).to eq("W") end end describe "Robot turns anticlockwise" do it "returns S if robot's initial orientation is W" do expect(movements.change_orientation_anticlockwise("W")).to eq("S") end it "returns N if robot's initial orientation is E" do expect(movements.change_orientation_anticlockwise("E")).to eq("N") end end describe "Robot moves forward" do it "returns 2 as value for coordinate x if robot starts from [1,1] and moves East" do coordinates = [1,1] movements.move_forward('E',coordinates) expect(coordinates[0]).to eq(2) end it "returns 2 as value for coordinate y if robot starts from [1,1] and moves North" do coordinates = [1,1] movements.move_forward('N',coordinates) expect(coordinates[1]).to eq(2) end it "returns 4 as value for coordinate x if robot starts from [5,3] and moves West" do coordinates = [5,3] movements.move_forward('W',coordinates) expect(coordinates[0]).to eq(4) end it "returns 8 as value for coordinate y if robot starts from [7,9] and moves South" do coordinates = [7,9] movements.move_forward('S',coordinates) expect(coordinates[1]).to eq(8) end end end
true
5c7cd56bcc75fe12ff7418237474876954edcba7
Ruby
tKeitttt/furima-34165
/spec/models/item_spec.rb
UTF-8
4,579
2.609375
3
[]
no_license
require 'rails_helper' RSpec.describe Item, type: :model do before do @item = FactoryBot.build(:item) end describe '商品情報の保存' do context '商品が登録できる場合' do it '商品名、商品説明、商品画像、カテゴリ、状態、配送料、発送元、発送までの日数、価格の入力があれば投稿できる' do @item expect(@item).to be_valid end end context '商品が登録できない場合' do it 'ユーザーが紐付いていなければ投稿できない' do @item.user = nil @item.valid? expect(@item.errors.full_messages).to include('User must exist') end it '商品名が空では投稿できない' do @item.item_name = '' @item.valid? expect(@item.errors.full_messages).to include "Item name can't be blank" end it '商品説明が空では投稿できない' do @item.item_text = '' @item.valid? expect(@item.errors.full_messages).to include "Item text can't be blank" end it '商品画像が空では投稿できない' do @item.item_image = nil @item.valid? expect(@item.errors.full_messages).to include "Item image can't be blank" end it 'カテゴリが空では投稿できない' do @item.category_id = '' @item.valid? expect(@item.errors.full_messages).to include "Category can't be blank" end it 'カテゴリが1では投稿できない' do @item.category_id = 1 @item.valid? expect(@item.errors.full_messages).to include 'Category must be other than 1' end it 'ステータスが空では投稿できない' do @item.status_id = '' @item.valid? expect(@item.errors.full_messages).to include "Status can't be blank" end it 'ステータスが1では投稿できない' do @item.status_id = 1 @item.valid? expect(@item.errors.full_messages).to include 'Status must be other than 1' end it '配送料が空では投稿できない' do @item.delivery_fee_id = '' @item.valid? expect(@item.errors.full_messages).to include "Delivery fee can't be blank" end it '配送料が1では投稿できない' do @item.delivery_fee_id = 1 @item.valid? expect(@item.errors.full_messages).to include 'Delivery fee must be other than 1' end it '発送元が空では投稿できない' do @item.prefecture_id = '' @item.valid? expect(@item.errors.full_messages).to include "Prefecture can't be blank" end it '発送元が1では投稿できない' do @item.prefecture_id = 1 @item.valid? expect(@item.errors.full_messages).to include 'Prefecture must be other than 1' end it '発送日数が空では投稿できない' do @item.shipment_date_id = '' @item.valid? expect(@item.errors.full_messages).to include "Shipment date can't be blank" end it '発送日数が1では投稿できない' do @item.shipment_date_id = 1 @item.valid? expect(@item.errors.full_messages).to include 'Shipment date must be other than 1' end it '価格が空では投稿できない' do @item.price = '' @item.valid? expect(@item.errors.full_messages).to include "Price can't be blank" end it '価格が全角数字では投稿できない' do @item.price = '300' @item.valid? expect(@item.errors.full_messages).to include 'Price is not a number' end it '価格が半角英数混合では投稿できない' do @item.price = 'abc123' @item.valid? expect(@item.errors.full_messages).to include 'Price is not a number' end it '価格が半角英語では投稿できない' do @item.price = 'abc' @item.valid? expect(@item.errors.full_messages).to include 'Price is not a number' end it '価格が300未満では投稿できない' do @item.price = rand(1..299) @item.valid? expect(@item.errors.full_messages).to include 'Price must be greater than or equal to 300' end it '価格が10000000以上では投稿できない' do @item.price = 10_000_000 @item.valid? expect(@item.errors.full_messages).to include 'Price must be less than or equal to 9999999' end end end end
true
4421f45dce8d0d6f0a0e0c55c58b67040577e173
Ruby
NLanese/ttt-with-ai-project-online-web-sp-000
/lib/players/computer.rb
UTF-8
1,880
3.40625
3
[]
no_license
require 'pry' module Players class Computer < Player WIN_COMBINATIONS = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [6, 4, 2] ] def move(inputBoard) if self != "X" opp = "O" else opp = "X" end selectedSpace = -1 WIN_COMBINATIONS.each do | selectedCombo | if (inputBoard.cells[selectedCombo[0]] == opp && inputBoard.cells[selectedCombo[1]] == opp) selectedSpace = selectedCombo[2] break elsif (inputBoard.cells[selectedCombo[1]] == opp && inputBoard.cells[selectedCombo[2]] == opp) selectedSpace = selectedCombo[0] break elsif (inputBoard.cells[selectedCombo[0]] == opp && inputBoard.cells[selectedCombo[2]] == opp) selectedSpace = selectedCombo[1] break end end #binding.pry if (selectedSpace == -1) WIN_COMBINATIONS.each do | selectedCombo | if (inputBoard.cells[selectedCombo[0]] == self && inputBoard.cells[selectedCombo[1]] == self) selectedSpace = selectedCombo[2] break elsif (inputBoard.cells[selectedCombo[1]] == self && inputBoard.cells[selectedCombo[2]] == self) selectedSpace = selectedCombo[0] break elsif (inputBoard.cells[selectedCombo[0]] == self && inputBoard.cells[selectedCombo[2]] == self) selectedSpace = selectedCombo[1] break end end end #binding.pry if (selectedSpace == -1) i = 0 inputBoard.cells.each do | space | if space == " " selectedSpace = i break end end end #binding.pry selectedSpace = (selectedSpace + 1).to_s return selectedSpace end end end
true
cb9f8b3f1cbccf61d2e4058d16519a572d1f2970
Ruby
colbySherwood/Boolean-Gurus
/Project1/userTurn.rb
UTF-8
2,417
3.5625
4
[]
no_license
require "./noSetsOption.rb" require "./setsOnTable.rb" # divided into small parts in case we want to change behavior of some of them # designed so we call turn in a loop, puts current table, then updates score and table def validIn? (inStr) if inStr.to_i == 0 puts "Invalid input!" return false end return true end def turn(table, player, deck) #clear console system("cls") || system("clear") || puts("\e[H\e[2J") table.putTable puts "#{player.username}, please pick your first card or enter \"no set\" " s = gets.chomp until s == "no set" || s == "no sets" || validIn?(s) puts "#{player.username}, please pick your first card or enter \"no set\" " s = gets.chomp end if (s == "no set" || s == "no sets") playerClickedNoSets(table, player,deck) else pickCardsOption(table, player,s.to_i,deck) end end def pickCardsOption (table, player, firstCard,deck) firstCardNum = firstCard - 1 puts "#{player.username}, please pick your second card" inStr = gets.chomp until validIn?(inStr) && inStr.to_i - 1 != firstCardNum puts "Aha you tried to enter two identical cards!" if inStr.to_i - 1 == firstCardNum puts "#{player.username}, please pick your second card" inStr = gets.chomp end secondCardNum = inStr.to_i - 1 puts "#{player.username}, please pick your third card" inStr = gets.chomp until validIn?(inStr) && inStr.to_i - 1 != firstCardNum && inStr.to_i - 1 != secondCardNum puts "Aha you tried to enter two identical cards!" if inStr.to_i - 1 == firstCardNum ||inStr.to_i - 1 == secondCardNum puts "#{player.username}, please pick your third card" inStr = gets.chomp end thirdCardNum = inStr.to_i - 1 if isProperSet(table.currentTable[firstCardNum], table.currentTable[secondCardNum], table.currentTable[thirdCardNum]) pickedProper(table, player, firstCardNum, secondCardNum, thirdCardNum, deck) else pickedImproper(player) end end def pickedProper(table, player, firstCardNum, secondCardNum, thirdCardNum,deck) player.increase_score puts "You are right! Your score now is #{player.score}" if (deck.cardCount > 0 ) table.changeCards(firstCardNum, secondCardNum, thirdCardNum,deck) else table.removeCards(firstCardNum, secondCardNum, thirdCardNum) end end def pickedImproper(player) player.decrease_score puts "Wrong! Please try again. Your score now is #{player.score}" end
true
bb11240e11dc1eaa1731f7097f28d384f7cd4df3
Ruby
sugamasao/kirico
/lib/kirico/validators/space_divider_validator.rb
UTF-8
1,565
2.609375
3
[ "MIT" ]
permissive
# frozen_string_literal: true require 'active_model' require 'active_model/validator' require 'active_model/validations/format' # 文字種別を検証する # # 設定例: # validate :name, space_divider: { space: :full_width } # validate :name_yomi, space_divider: { space: :half_width } # validate :name, space_divider: { space: :both_width } # # space に指定可能なオプション: # # :full_width # 全角スペース # # :half_width # 半角スペース # # :both_width(デフォルト) # 半角、全角問わない module Kirico class SpaceDividerValidator < ActiveModel::EachValidator HALF_WIDTH_SPACE_RULE = ' ' FULL_WIDTH_SPACE_RULE = ' ' BOTH_WIDTH_SPACE_RULE = '[  ]' def self.regexp(space_divider_rule) /\A[^\p{blank}]+(#{space_divider_rule}[^\p{blank}]+)+\z/ end CHECKS = { half_width: regexp(HALF_WIDTH_SPACE_RULE), full_width: regexp(FULL_WIDTH_SPACE_RULE), both_width: regexp(BOTH_WIDTH_SPACE_RULE) }.freeze def check_validity! raise ArgumentError, "Invalid space option #{space_option}. Specify the :full_width, half_width, or :both_width." unless CHECKS.key?(space_option) end def validate_each(record, attribute, value) record.errors.add(attribute, (options[:message] || :invalid_space_divider), space_type: space_type_i18n) if value.to_s !~ CHECKS[space_option] end private def space_option options[:space] || :both_width end def space_type_i18n I18n.t('space_type')[space_option] end end end
true
1ac49f9275f28b790b50499cc89b7f5a09543f26
Ruby
joemcbride/frostbite
/scripts/disarm.rb
UTF-8
5,003
3.09375
3
[ "MIT" ]
permissive
# desc: Disarm boxes you have in open containers or holding in your right hand, # harvest only on quick and blind disarms. # requirements: - # run: anywhere @harvest = true if $args.join(" ").include? "noh" @harvest = false; end def ident(box) put "disarm my #{box} ident" match = { :wait => [/\.\.wait/], :ident => ["fails to reveal to you what"], :quick => ["can take down any time", "a simple matter", "should not take long", "aged grandmother could defeat", "could do it blindfolded"], :normal => ["this trap is precisely at your", "only minor troubles", "has the edge on you"], :careful => ["have some chance of being able to", "odds are against you", "would be a longshot"], :hard => ["really don't have any", "prayer would be a good start", "same shot as a snowball", "pitiful snowball encased", "just jump off a cliff"], :end => ["guess it is already disarmed", "Roundtime"] } result = match_wait match case result when :wait, :ident pause 0.5 ident box when :end exit_script("*** Box is disarmed! ***") when :hard exit_script("*** Unable to disarm! ***") else disarm(box, result) end end #>disarm my skippet quick #You quickly work at disarming the skippet. #You work with the trap for a while but are unable to make any progress. #You get the distinct feeling your manipulation caused something to shift inside the trap mechanism. This is not likely to be a good thing. #Roundtime: 1 sec. #>disarm my coffer normal #You begin work at disarming the coffer. #You work with the trap for a while but are unable to make any progress. #You get the distinct feeling your manipulation caused something to shift inside the trap mechanism. This is not likely to be a good thing. #Roundtime: 4 sec. #>disarm my coffer normal #You believe that the crate is not yet fully disarmed. def disarm(box, method) put "disarm my #{box} #{method.to_s}" match = { :wait => [/\.\.\.wait/], :next_method => ["shift inside the trap"], :continue => ["progress"], :analyze => ["not yet fully disarmed"], :analyze_last => ["Roundtime"] } result = match_wait match case result when :wait, :continue pause 0.5 disarm(box, method) when :next_method # does not work! next_index = @disarm_methods.index(method.to_s) disarm(box, @disarm_methods.fetch(next_index + 1, "careful")) when :analyze if @harvest and (method == :blind or method == :quick) analyze box, false else ident box end when :analyze_last if method == :blind or method == :quick analyze box, true else exit_script("*** box disarmed! ***") end else exit_script "*** ERROR in - disarm(box, method)! ***" end end def analyze(box, last) put "disarm my #{box} analyze" match = { :wait => [/\.\.\.wait/], :reanalyze => ["unable to determine"], :ident => ["not fully disarmed", "what could you possibly analyze"], :end => ["unsuitable for"], :harvest => ["Roundtime"] } result = match_wait match case result when :wait, :reanalyze pause 0.5 analyze box, last when :ident if last exit_script("*** Box disamed! ***") else ident box end when :end exit_script "*** Box disarmed! ***" when :harvest harvest box, last else exit_script "*** ERROR in - analyze(box)! ***" end end def harvest(box, last) put "disarm my #{box} harvest" match = { :wait => [/\.\.\.wait/], :harvest => ["unable to extract"], :end => ["inept fumblings have damaged", "mangled remnants"], :stow => ["Roundtime"] } result = match_wait match case result when :wait, :harvest pause 0.5 harvest box, last when :end if last exit_script("*** Box disamed! ***") else ident box end when :stow put "stow left" if last exit_script("*** Box disamed! ***") else ident box end else exit_script "*** ERROR in - harvest(box)! ***" end end def exit_script(message) echo message exit end @box_types = ["chest", "trunk", "box", "skippet", "strongbox", "coffer", "crate", "casket", "caddy"] @disarm_methods = ["blind", "quick", "normal", "careful"] wield_right = Wield::right_noun if wield_right != "" @box_types.each do |box| if wield_right == box ident box end end end @box_types.each_with_index do |box| put "get my first #{box}" match = { :wait => [/\.\.\.wait/], :next => ["were you referring"], :open => ["You get"] } res = match_wait match case res when :open ident box when :wait pause 0.5 redo end end exit_script "*** All boxes disarmed! ***"
true
8d23d0ee7a8b22c5839b128ada7eeb0052f4a62f
Ruby
alarryant/jungle-rails
/spec/models/user_spec.rb
UTF-8
2,673
2.546875
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do subject { User.new(first_name: "Angela", last_name: "Larryant", email: "[email protected]", password: 'pass1234', password_confirmation: 'pass1234') } describe 'Validations' do it 'is valid with valid attributes' do expect(subject).to be_valid end it "is not valid without a unique email" do User.create(first_name: "Angela", last_name: "Larryant", email: "[email protected]", password: 'pass1234', password_confirmation: 'pass1234') expect(subject).to_not be_valid end it "is not valid if email is not unique without caps lock" do User.create(first_name: "Angela", last_name: "Larryant", email: "[email protected]", password: 'pass1234', password_confirmation: 'pass1234') expect(subject).to_not be_valid end it "is not valid if password doesn't match password_confirmation" do subject.password_confirmation = "nomatch" expect(subject).to_not be_valid end it "is not valid without a first_name" do subject.first_name = nil expect(subject).to_not be_valid end it "is not valid without a last_name" do subject.last_name = nil expect(subject).to_not be_valid end it "is not valid without an email" do subject.email = nil expect(subject).to_not be_valid end it "is not valid with password below 6 characters" do subject.password = "ha" subject.password_confirmation = "ha" expect(subject).to_not be_valid end end describe '.authenticate_with_credentials' do it "is valid if email and password matches" do user_db = User.create(first_name: "Angela", last_name: "Larryant", email: "[email protected]", password: 'pass1234', password_confirmation: 'pass1234') user_login = User.authenticate_with_credentials("[email protected]", "pass1234") expect(user_db).to eq user_login end it "is valid if email and password matches, even if email has leading and/or trailing whitespace" do user_db = User.create(first_name: "Angela", last_name: "Larryant", email: "[email protected]", password: 'pass1234', password_confirmation: 'pass1234') user_login = User.authenticate_with_credentials(" [email protected] ", "pass1234") expect(user_db).to eq user_login end it "is valid if email and password matches, even if email has varying cases" do user_db = User.create(first_name: "Angela", last_name: "Larryant", email: "[email protected]", password: 'pass1234', password_confirmation: 'pass1234') user_login = User.authenticate_with_credentials("[email protected]", "pass1234") expect(user_db).to eq user_login end end end
true
456d0b9892fd459a4a91616d36121bd19552a43e
Ruby
cprasarn/furniture-store
/plugins/store/Bookcase.rb
UTF-8
4,516
3.25
3
[]
no_license
class Bookcase def initialize(spaces, width, depth) @spaces = spaces - 1 @width = width @depth = depth @thickness = 1 case spaces when 2 @height = 29.25 when 3 @height = 41 when 4 @height = 52.75 when 5 @height = 64.5 when 6 @height = 76.25 when 7 @height = 88 end end def draw_panel(name, pt1, pt2, pt3, pt4, thickness) # Get handles to our model and the Entities collection it contains. model = Sketchup.active_model entities = model.entities # Group group = entities.add_group group.name = name group.description = 'Fixed' group_entities = group.entities # Call methods on the Entities collection to draw stuff. new_face = group_entities.add_face pt1, pt2, pt3, pt4 new_face.pushpull thickness, true end def draw() # Top x1 = @thickness x2 = @width - @thickness y1 = 0 y2 = @depth - @thickness z = @height pt1 = [x1, y1, z] pt2 = [x2, y1, z] pt3 = [x2, y2, z] pt4 = [x1, y2, z] draw_panel 'Top', pt1, pt2, pt3, pt4, @thickness # Spaces draw_spaces() # Bottom z = @thickness pt1 = [x1, y1, z] pt2 = [x2, y1, z] pt3 = [x2, y2, z] pt4 = [x1, y2, z] draw_panel 'Bottom', pt1, pt2, pt3, pt4, @thickness # Sides draw_sides() end def draw_spaces() height = @thickness thickness = 0.875 # Loop across the same code several times for step in 1..@spaces case step when 1 rise = 13 + (1 - thickness) when 2 rise = 12 else rise = 11 end height += rise height += thickness # Calculate our space corners. x1 = @thickness x2 = @width - @thickness y1 = 0 y2 = @depth - @thickness z = height # Create a series of "points", each a 3-item array containing x, y, and z. pt1 = [x1, y1, z] pt2 = [x2, y1, z] pt3 = [x2, y2, z] pt4 = [x1, y2, z] draw_panel "Space", pt1, pt2, pt3, pt4, thickness end end def draw_sides thickness = @height # Left x1 = 0 x2 = @thickness y1 = 0 y2 = @depth - @thickness z = @thickness # Create a series of "points", each a 3-item array containing x, y, and z. pt1 = [x1, y1, z] pt2 = [x2, y1, z] pt3 = [x2, y2, z] pt4 = [x1, y2, z] draw_panel "Left", pt1, pt2, pt3, pt4, thickness # Right x1 = @width - @thickness x2 = @width y1 = 0 y2 = @depth - @thickness # Create a series of "points", each a 3-item array containing x, y, and z. pt1 = [x1, y1, z] pt2 = [x2, y1, z] pt3 = [x2, y2, z] pt4 = [x1, y2, z] draw_panel "Right", pt1, pt2, pt3, pt4, thickness # Back x1 = 0 x2 = @width y1 = @depth - @thickness y2 = @depth # Create a series of "points", each a 3-item array containing x, y, and z. pt1 = [x1, y1, z] pt2 = [x2, y1, z] pt3 = [x2, y2, z] pt4 = [x1, y2, z] draw_panel "Back", pt1, pt2, pt3, pt4, thickness end end #----------------------------------------------------------------------------- def draw_bookcase # With four params, it shows a drop down box for prompts that have # pipe-delimited lists of options. In this case, the Gender prompt # is a drop down instead of a text box. prompts = ["Width (inches)", "Spaces", "Depth (inches)"] defaults = [32, 3, 9] list = ['32|36|42|48', '2|3|4|5|6|7', '7|9|9.25|11|12|13'] input = UI.inputbox prompts, defaults, list, "Bookcase Dimensions" # Dimensions spaces = input[1].to_i; width = input[0].to_i; depth = input[2].to_f; # Draw a bookcase object = Bookcase.new(spaces, width, depth) object.draw() end if( not file_loaded?("Bookcase.rb") ) UI.menu("Plugins").add_item("Bookcase") { draw_bookcase } end file_loaded("Bookcase.rb")
true
21c14d4c747650e06baed4601c440c4d3d376233
Ruby
cicloid/pingpong-master
/app/models/game.rb
UTF-8
2,294
2.890625
3
[]
no_license
class Game < ApplicationRecord belongs_to :player_one, class_name: 'User', foreign_key: 'player_one_id' belongs_to :player_two, class_name: 'User', foreign_key: 'player_two_id' validates :player_one_score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 21 }, presence: true validates :player_two_score, numericality: { only_integer: true, greater_than_or_equal_to: 0, less_than_or_equal_to: 21 }, presence: true validate :valid_point_lead_for_win def rating_one rating_for_player( result: game_result, old_rating: player_one.rating, opponent_rating: player_two.rating, k_factor: player_one.k_factor ) end def rating_two rating_for_player( result: (1.0 - game_result), old_rating: player_two.rating, opponent_rating: player_one.rating, k_factor: player_two.k_factor ) end # Based on Elo Rating System... thanks to all those hours playing Destiny I # alredy knew about this one. # # http://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details def rating_for_player(result: nil, old_rating: 1000, opponent_rating: 1000, k_factor: 32) (old_rating.to_f + (k_factor.to_f * ( result.to_f - expected_rating( opponent_rating, old_rating ) )).to_i ) end # Based on Elo Rating System... thanks to all those hours playing Destiny I # alredy knew about this one. # # http://en.wikipedia.org/wiki/Elo_rating_system#Mathematical_details def expected_rating(other, old) 1.0 / ( 1.0 + ( 10.0 ** ((other.to_f - old.to_f) / 400.0) ) ) end def game_result if player_one_score > player_two_score 1.0 elsif player_one_score == player_two_score 0.5 else 0 end end private # TODO: Intent should be clear on this one. probable a less convuluted way # to do this exists def valid_point_lead_for_win return unless self.player_one_score && self.player_two_score scores = [self.player_one_score, self.player_two_score].sort difference = scores[1] - scores[0] if difference < 2 && difference > 0 errors.add(:base, "Point difference should be of at least two points") end end end
true
819e68151b884db7aa878678ae49e8600818ab2d
Ruby
karottenreibe/dome
/test/css/parser_tests.rb
UTF-8
12,724
2.546875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby require 'test/unit' require 'dome/css' class CSSParserTests < Test::Unit::TestCase include Dome include Selectors def testElement p = CSSParser.new CSSLexer.new("batman") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "batman", f.value f = p.next assert_kind_of NilClass, f end def testAttr p = CSSParser.new CSSLexer.new("the[joker]") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "the", f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"joker",nil,nil], f.value f = p.next assert_kind_of NilClass, f end def testAttrInList p = CSSParser.new CSSLexer.new("bruce[wayne~=awesome]") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "bruce", f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"wayne",:in_list,"awesome"], f.value f = p.next assert_kind_of NilClass, f end def testAttrContains p = CSSParser.new CSSLexer.new("white[knight*=twoface]") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "white", f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"knight",:contains,"twoface"], f.value f = p.next assert_kind_of NilClass, f end def testAttrMatches p = CSSParser.new CSSLexer.new("master[bruce/=hero]") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "master", f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"bruce",:matches,"hero"], f.value f = p.next assert_kind_of NilClass, f end def testAttrBeginsWith p = CSSParser.new CSSLexer.new("the[story^=gordon]") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "the", f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"story",:begins_with,"gordon"], f.value f = p.next assert_kind_of NilClass, f end def testAttrEndsWith p = CSSParser.new CSSLexer.new("the[film$=batpod]") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "the", f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"film",:ends_with,"batpod"], f.value f = p.next assert_kind_of NilClass, f end def testAttrBeginsWithDash p = CSSParser.new CSSLexer.new("first[movie|=batman-begins]") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "first", f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"movie",:begins_with_dash,"batman-begins"], f.value f = p.next assert_kind_of NilClass, f end def testNoArgPseudoSelectors p = CSSParser.new CSSLexer.new( ":root:first-child:last-child:first-of-type:last-of-type:only-child" + ":only-of-type:empty:only-text") f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"root",nil], f.value f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"first-child",nil], f.value f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"last-child",nil], f.value f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"first-of-type",nil], f.value f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"last-of-type",nil], f.value f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"only-child",nil], f.value f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"only-of-type",nil], f.value f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"empty",nil], f.value f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"only-text",nil], f.value f = p.next assert_kind_of NilClass, f end def testIDClassSelectors p = CSSParser.new CSSLexer.new(".awesome#girl") f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"class",:in_list,"awesome"], f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"id",:equal,"girl"], f.value f = p.next assert_kind_of NilClass, f end def testCombinators p = CSSParser.new CSSLexer.new("one two + three>four ~ five <six% seven") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "one", f.value f = p.next assert_kind_of Token, f assert_equal :descendant, f.type assert_equal nil, f.value f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "two", f.value f = p.next assert_kind_of Token, f assert_equal :neighbour, f.type assert_equal nil, f.value f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "three", f.value f = p.next assert_kind_of Token, f assert_equal :child, f.type assert_equal nil, f.value f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "four", f.value f = p.next assert_kind_of Token, f assert_equal :follower, f.type assert_equal nil, f.value f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "five", f.value f = p.next assert_kind_of Token, f assert_equal :reverse_neighbour, f.type assert_equal nil, f.value f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "six", f.value f = p.next assert_kind_of Token, f assert_equal :predecessor, f.type assert_equal nil, f.value f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "seven", f.value f = p.next assert_kind_of NilClass, f end def testAttrQuoted p = CSSParser.new CSSLexer.new("seven[children='gon\"e']") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "seven", f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"children",:equal,"gon\"e"], f.value f = p.next assert_kind_of NilClass, f p = CSSParser.new CSSLexer.new('seven[children="go\\\"[]ne"]') f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "seven", f.value f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"children",:equal,"go\"[]ne"], f.value f = p.next assert_kind_of NilClass, f end def testNthPseudo args = %w{2n+1 2n n+1 1 -2n+1 4n-1 -n-2 n-5 -3 -n} resps = [[2,1],[2,0],[1,1],[0,1],[-2,1],[4,-1],[-1,-2],[1,-5],[0,-3],[-1,0]] %w{child last-child of-type last-of-type}.each do |word| args.zip(resps).each do |(arg,response)| p = CSSParser.new CSSLexer.new(":nth-#{word}(#{arg})") f = p.next assert_kind_of Token, f assert_equal :pseudo, f.type assert_equal [:"nth-#{word}",response], f.value f = p.next assert_kind_of NilClass, f end end end def testRestNil p = CSSParser.new CSSLexer.new("sand") f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "sand", f.value 5.times { f = p.next assert_kind_of NilClass, f } end def testNotEps args = ["element[attr]","not valid[>stuff + you ~ know",":root",":nth-child(2n+1)"] klasses = [[ElementSelector,AttributeSelector],nil,[RootSelector],[NthChildSelector]] [:not,:eps].each do |op| args.zip(klasses).each do |(arg,kls)| p = CSSParser.new CSSLexer.new(":#{op}(#{arg})") f = p.next assert_kind_of Token, f if kls.nil? assert_equal :tail, f.type else assert_equal :pseudo, f.type assert_equal op, f.value[0] kls.each_with_index { |k,i| assert_kind_of k, f.value[1].selectors[i] } end f = p.next assert_kind_of NilClass, f end end end def testElementNamespaces p = CSSParser.new CSSLexer.new("*|max") f = p.next assert_kind_of Token, f assert_equal :namespace, f.type assert_equal :any, f.value f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "max", f.value f = p.next assert_kind_of NilClass, f p = CSSParser.new CSSLexer.new("|max") f = p.next assert_kind_of Token, f assert_equal :namespace, f.type assert_equal nil, f.value f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "max", f.value f = p.next assert_kind_of NilClass, f p = CSSParser.new CSSLexer.new("sam|max") f = p.next assert_kind_of Token, f assert_equal :namespace, f.type assert_equal "sam", f.value f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "max", f.value f = p.next assert_kind_of NilClass, f end def testAttrNamespaces p = CSSParser.new CSSLexer.new("[*|max]") f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [:any,"max",nil,nil], f.value f = p.next assert_kind_of NilClass, f p = CSSParser.new CSSLexer.new("[|max]") f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal [nil,"max",nil,nil], f.value f = p.next assert_kind_of NilClass, f p = CSSParser.new CSSLexer.new("[sam|max]") f = p.next assert_kind_of Token, f assert_equal :attribute, f.type assert_equal ["sam","max",nil,nil], f.value f = p.next assert_kind_of NilClass, f end def testParentSelector p = CSSParser.new CSSLexer.new("..") f = p.next assert_kind_of Token, f assert_equal :parent, f.type assert_equal nil, f.value f = p.next assert_kind_of NilClass, f end def testOr ["foo,bar", "foo, bar"].each do |sel| p = CSSParser.new CSSLexer.new(sel) f = p.next assert_kind_of Token, f assert_equal :element, f.type assert_equal "foo", f.value f = p.next assert_kind_of Token, f assert_equal :or, f.type o = f.value assert_kind_of Selector, o s = o.selectors assert_equal 1, s.length assert_kind_of ElementSelector, s[0] assert_equal "bar", s[0].instance_variable_get(:@tag) f = p.next assert_kind_of NilClass, f end end end
true
810977b314e1891fe282e61304b3d3728f4c08d5
Ruby
gscho/inspec-osquery
/libraries/osquery.rb
UTF-8
1,130
2.546875
3
[ "Apache-2.0" ]
permissive
require 'inspec/utils/object_traversal' require 'json' class OSQuery < Inspec.resource(1) name 'osquery' desc ' run osquery via InSpec. ' example " describe osquery('SELECT * FROM users;') do its('length') { should_not eq 0 } end " attr_reader :params include ObjectTraverser def initialize(query) @params = { 'result_set' => [], 'length' => 0 } @cli = "osqueryi" exec(query) end def exec(query) command = "#{@cli} --json \"#{query}\"" @res = inspec.command(command) @params['result_set'] = JSON.parse @res.stdout unless @res.stdout.eql?('') @params['length'] = @params['result_set'].size @params['result_set'].first.each { |k,v| @params[k.to_s] = v } end def stdout @res.stdout end def stderr @res.stderr end def exit_status @res.exit_status.to_i end # This is borrowed directly from https://github.com/inspec/inspec/blob/master/lib/inspec/resources/json.rb def method_missing(*keys) keys.shift if keys.is_a?(Array) && keys[0] == :[] value(keys) end def value(key) extract_value(key, params) end end
true
7dfdfba1cc45d9ac86d10bad0a3c2db009b2328a
Ruby
lfborjas/estructuras_de_datos
/stack_queue.rb
UTF-8
2,348
3.984375
4
[]
no_license
#Estamos "editando" la clase Array para que tenga algunos métodos que una list #debería tener. En ruby podemos agregar o sobreescribir métodos de #una clase en tiempo de ejecución class Array alias :get_at :[] def get_first self.index self.first or 0 end def end self.index(self.last) + 1 end end class Stack < Array #procedimiento anula alias :purge :clear #procedimiento tope def peek self.get_at self.get_first end #devuelve el elemento que acaba de suprimir def pop self.delete_at self.get_first end def push(x) self.insert self.get_first, x end #Array ya tiene un método empty? alias :is_empty :empty? end class Cola < Array alias :purge :clear #el método first de Array ya devuelve el elemento #en la primera posición alias :front :first def enqueue self.insert self.end, x end #el método `shift` ya hace esto... alias :dequeue :shift alias :is_empty :empty? end def eval_rpn(exp) ops = {} %w{+ - * /}.each do |operation| ops[operation] = lambda{|a,b| eval "a #{operation} b"} end =begin Lo de arriba equivale a esto: ops = { "+" => lambda{|a,b| a+b}, "-" => lambda{|a,b| a-b}, "*" => lambda{|a,b| a*b}, "/" => lambda{|a,b| a/b} } =end tokens = exp.split /\s+/ stack = Stack.new for token in tokens unless ops.include? token stack.push token.to_i else operands = [] operation = ops[token] operation.arity.times do raise "Insufficient operands" if stack.empty? operands << stack.pop end stack.push operation.call(*operands) end end result = stack.pop raise "Unbalanced expression" unless stack.empty? result end #usar el shunting yard algorithm (http://en.wikipedia.org/wiki/Shunting-yard_algorithm) #para convertir una expresión en notación infija def parse_infix(exp) tokens = exp.split /\s+/ raise "Not implemented yet, :P" end puts "Escriba una expresión en RPN" expression = gets.chomp puts eval_rpn(expression) puts "Conversión de notación infija a polaca"
true
8f516fc5867846554f5bc7a193bba43d8b1a6835
Ruby
idit/instituto-gabi
/app/models/data_file.rb
UTF-8
2,026
2.75
3
[]
no_license
# == Schema Information # # Table name: data_files # # id :integer not null, primary key # name :string(255) # path :string(255) # file_type :integer # created_at :datetime not null # updated_at :datetime not null # mime_type :string(255) # description :string(255) # class DataFile < ActiveRecord::Base attr_accessible :file_type, :name, :path, :mime_type, :description before_save :identify_file_type # Tipos de Arquivos APPLICATION = 1 # .doc, .pdf, .docx, etc. AUDIO = 2 EXAMPLE = 3 IMAGE = 4 MESSAGE = 5 MODEL = 6 MULTIPART = 7 TEXT = 8 VIDEO = 9 # Mime Types APPLICATION_MIMETYPE = ["application/pdf", "application/msword", "application/x-shockwave-flash"] IMAGE_MIMETYPE = ["image/gif", "image/jp2", "image/jpeg", "image/png", "image/bmp", "image/x-icon"] VIDEO_MIMETYPE = ["video/mpeg", "video/jpeg", "video/mp4"] TEXT_MIMETYPE = ["text/html"] def self.paginate_all(page) paginate :per_page => 6, :page => page, :order => "name" end def file= (f) @file = f end def application? self.file_type == APPLICATION end def audio? self.file_type == AUDIO end def example? self.file_type == EXAMPLE end def image? self.file_type == IMAGE end def message? self.file_type == MESSAGE end def model? self.file_type == MODEL end def multipart? self.file_type == MULTIPART end def text? self.file_type == TEXT end def video? self.file_type == VIDEO end private def identify_file_type if APPLICATION_MIMETYPE.include?(self.mime_type) self.file_type = APPLICATION end if IMAGE_MIMETYPE.include?(self.mime_type) self.file_type = IMAGE end if VIDEO_MIMETYPE.include?(self.mime_type) self.file_type = VIDEO end if TEXT_MIMETYPE.include?(self.mime_type) self.file_type = TEXT end end end
true
cd0f289e8b1ade7a5a7a97a98102e2b4669f5e1f
Ruby
syborg/mme_tools
/lib/mme_tools/args_proc.rb
UTF-8
710
2.75
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# NamedArgs # Marcel Massana 13-Sep-2011 # # Extends Hash with methods based on ideas from # http://saaientist.blogspot.com/2007/11/named-arguments-in-ruby.html # Also thanks to ActiveSupport from Rails module MMETools extend self module ArgsProc # Tests if +options+ includes only valid keys. Raises an error if # any key is not included within +valid_options+. # +valid_options+ is a Hash that must include all accepted keys. values # aren't taken into account. def assert_valid_keys(options, valid_options) unknown_keys = options.keys - valid_options.keys raise(ArgumentError, "Unknown options(s): #{unknown_keys.join(", ")}") unless unknown_keys.empty? end end end
true
8b02fd8657b4e3b67bbda6f4ec76394baf1930ad
Ruby
rosette-proj/rosette-core
/lib/rosette/core/extractor/repo_config.rb
UTF-8
13,935
2.859375
3
[]
no_license
# encoding: UTF-8 module Rosette module Core # Configuration for a single repository. Instances of {RepoConfig} can # be configured to: # # * Extract phrases (via {#add_extractor}). Phrase extraction means # certain files (that you specify) will be monitored for changes and # processed. For example, you could specify that all files with a .yml # extension be monitored. When Rosette, using git, detects that any of # those files have changed, it will parse the files using an extractor # and store the phrases in the datastore. The Rosette project contains # a number of pre-built extractors. Visit github for a complete list: # https://github.com/rosette-proj. For example, the yaml extractor is # called rosette-extractor-yaml and is available at # https://github.com/rosette-proj/rosette-extractor-yaml. You would # need to add it to your Gemfile and require it before use. # # * Serialize phrases (via {#add_serializer}). Serializing phrases can be # thought of as the opposite of extracting them. Instead of parsing a # yaml file for example, serialization is the process of turning a # collection of foreign language translations into a big string of yaml # that can be written to a file. Usually serialization happens when # you're ready to export translations from Rosette. In the Rails world # for example, you'd export (or serialize) translations per locale and # store them as files in the config/locales directory. Spanish # translations would be exported to config/locales/es.yml and Japanese # translations to config/locales/ja.yml. The Rosette project contains # a number of pre-built serializers. Visit github for a complete list: # https://github.com/rosette-proj. For example, the yaml serializer is # called rosette-serializer-yaml and is available at # https://github.com/rosette-proj/rosette-serializer-yaml. You would # need to add it to your Gemfile and require it before use. # # * Pre-process phrases using {SerializerConfig#add_preprocessor}. # Serializers can also pre-process translations (see the example below). # Pre-processing is the concept of modifying a translation just before # it gets serialized. Examples include rosette-preprocessor-normalization, # which is capable of applying Unicode's text normalization algorithm # to translation text. See https://github.com/rosette-proj for a complete # list of pre-processors. # # * Interact with third-party libraries or services via integrations (see # the {#add_integration} method). Integrations are very general in that # they can be almost anything. For the most part however, integrations # serve as bridges to external APIs or libraries. For example, the # Rosette project currently contains an integration called # rosette-integration-smartling that's responsible for pushing and # pulling translations to/from the Smartling translation platform # (Smartling is a translation management system, or TMS). Since Rosette # is not a TMS (i.e. doesn't provide any GUI for entering translations), # you will need to use a third-party service like Smartling or build # your own TMS solution. Another example is rosette-integration-rollbar. # Rollbar is a third-party error reporting system. The Rollbar # integration not only adds a Rosette-style {ErrorReporter}, it also # hooks into a few places errors might happen, like Rosette::Server's # rack stack. # # @example # config = RepoConfig.new('my_repo') # .set_path('/path/to/my_repo/.git') # .set_description('My awesome repo') # .set_source_locale('en-US') # .add_locales(%w(pt-BR es-ES fr-FR ja-JP ko-KR)) # .add_extractor('yaml/rails') do |ext| # ext.match_file_extension('.yml').and( # ext.match_path('config/locales') # ) # end # .add_serializer('rails', format: 'yaml/rails') do |ser| # ser.add_preprocessor('normalization') do |pre| # pre.set_normalization_form(:nfc) # end # end # .add_integration('smartling') do |sm| # sm.set_api_options(smartling_api_key: 'fakefake', ... ) # sm.set_serializer('yaml/rails') # end # # @!attribute [r] name # @return [String] the name of the repository. # @!attribute [r] repo # @return [Repo] a {Repo} instance that can be used to perform git # operations on the local working copy of the associated git # repository. # @!attribute [r] locales # @return [Array<Locale>] a list of the locales this repo supports. # @!attribute [r] hooks # @return [Hash<Hash<Array<Proc>>>] a hash of callbacks. The outer hash # contains the order while the inner hash contains the action. For # example, if the +hooks+ hash has been configured to do something # after commit, it might look like this: # { after: { commit: [<Proc #0x238d3a>] } } # @!attribute [r] description # @return [String] a description of the repository. # @!attribute [r] extractor_configs # @return [Array<ExtractorConfig>] a list of the currently configured # extractors. # @!attribute [r] serializer_configs # @return [Array<SerializerConfig>] a list of the currently configured # serializers. # @!attribute [r] tms # @return [Rosette::Tms::Repository] a repository instance from the chosen # translation management system. class RepoConfig include Integrations::Integratable attr_reader :name, :rosette_config, :repo, :locales, :hooks, :description attr_reader :extractor_configs, :serializer_configs, :tms attr_reader :placeholder_regexes # Creates a new repo config object. # # @param [String] name The name of the repository. Usually matches the # name of the directory on disk, but that's not required. def initialize(name, rosette_config) @name = name @rosette_config = rosette_config @extractor_configs = [] @serializer_configs = [] @locales = [] @placeholder_regexes = [] @hooks = Hash.new do |h, key| h[key] = Hash.new do |h2, key2| h2[key2] = [] end end end # Sets the path to the repository's .git directory. # # @param [String] path The path to the repository's .git directory. # @return [void] def set_path(path) @repo = Repo.from_path(path) end # Sets the description of the repository. This is really just for # annotation purposes, the description isn't used by Rosette. # # @param [String] desc The description text. # @return [void] def set_description(desc) @description = desc end # Gets the path to the repository's .git directory. # # @return [String] def path repo.path if repo end # Gets the source locale (i.e. the locale all the source files are in). # Defaults to en-US. # # @return [Locale] the source locale. def source_locale @source_locale ||= Locale.parse('en-US', Locale::DEFAULT_FORMAT) end # Sets the source locale. # # @param [String] code The locale code. # @param [Symbol] format The format +locale+ is in. # @return [void] def set_source_locale(code, format = Locale::DEFAULT_FORMAT) @source_locale = Locale.parse(code, format) end # Set the TMS (translation management system). TMSs must contain a class # named +Repository+ that implements the [Rosette::Tms::Repository] # interface. # # @param [Const, String] tms The TMS to use. When this parameter is a # string, +use_tms+ will try to look up the corresponding +Tms+ # constant. If a constant is given instead, it's used without # modifications. In both cases, the +Tms+ constant will have +configure+ # called on it and is expected to yield a configuration object. # @param [Hash] options A hash of options passed to the TMS's # constructor. # @return [void] def use_tms(tms, options = {}) const = case tms when String if const = find_tms_const(tms) const else raise ArgumentError, "'#{tms}' couldn't be found." end when Class, Module tms else raise ArgumentError, "'#{tms}' must be a String, Class, or Module." end @tms = const.configure(rosette_config, self) do |configurator| yield configurator if block_given? end nil end # Adds an extractor to this repo. # # @param [String] extractor_id The id of the extractor you'd like to add. # @yield [config] yields the extractor config # @yieldparam config [ExtractorConfig] # @return [void] def add_extractor(extractor_id) klass = ExtractorId.resolve(extractor_id) extractor_configs << ExtractorConfig.new(klass).tap do |config| yield config if block_given? end end # Adds a serializer to this repo. # # @param [String] name A semantic name for this serializer. Means nothing # to Rosette, simply a way for you to label the serializer. # @param [Hash] options A hash of options containing the following entries: # * +format+: The id of the serializer, eg. "yaml/rails". # @yield [config] yields the serializer config # @yieldparam config [SerializerConfig] # @return [void] def add_serializer(name, options = {}) serializer_id = options[:format] klass = SerializerId.resolve(serializer_id) serializer_configs << SerializerConfig.new(name, klass, serializer_id).tap do |config| yield config if block_given? end end # Adds a locale to the list of locales this repo supports. # # @param [String] locale_code The locale you'd like to add. # @param [Symbol] format The format of +locale_code+. # @return [void] def add_locale(locale_code, format = Locale::DEFAULT_FORMAT) add_locales(locale_code) end # Adds multiple locales to the list of locales this repo supports. # # @param [Array<String>] locale_codes The list of locales to add. # @param [Symbol] format The format of +locale_codes+. # @return [void] def add_locales(locale_codes, format = Locale::DEFAULT_FORMAT) @locales += Array(locale_codes).map do |locale_code| Locale.parse(locale_code, format) end end # Adds an after hook. You should pass a block to this method. The # block will be executed when the hook fires. # # @param [Symbol] action The action to hook. Currently the only # supported action is +:commit+. # @return [void] def after(action, &block) hooks[:after][action] << block end # Retrieves the extractor configs that match the given path. # # @param [String] path The path to match. # @return [Array<ExtractorConfig>] a list of the extractor configs that # were found to match +path+. def get_extractor_configs(path) extractor_configs.select do |config| config.matches?(path) end end # Retrieves the extractor config by either name or extractor id. # # @param [String] name_or_id The name or extractor id. # @return [nil, ExtractorConfig] the first matching extractor config. # Potentially returns +nil+ if no matching extractor config can be # found. def get_extractor_config(extractor_id) extractor_configs.find do |config| config.extractor_id == extractor_id end end # Retrieves the serializer config by either name or serializer id. # # @param [String] name_or_id The name or serializer id. # @return [nil, SerializerConfig] the first matching serializer config. # Potentially returns +nil+ if no matching serializer config can be # found. def get_serializer_config(name_or_id) found = serializer_configs.find do |config| config.name == name_or_id end found || serializer_configs.find do |config| config.serializer_id == name_or_id end end # Retrieves the locale object by locale code. # # @param [String] code The locale code to look for. # @param [Symbol] format The locale format +code+ is in. # @return [nil, Locale] The locale who's code matches +code+. Potentially # returns +nil+ if the locale can't be found. def get_locale(code, format = Locale::DEFAULT_FORMAT) locale_to_find = Locale.parse(code, format) locales.find { |locale| locale == locale_to_find } end # Adds a regex that matches a placeholder in translation text. For # example, Ruby placeholders often look like this "Hello %{name}!". # Some integrations rely on these regexes to detect and format # placeholders correctly. # # @param [Regexp] placeholder_regex The regex to add. # @return [void] def add_placeholder_regex(placeholder_regex) placeholder_regexes << placeholder_regex end protected def find_tms_const(name) const_str = "#{Rosette::Core::StringUtils.camelize(name)}Tms" if Rosette::Tms.const_defined?(const_str) Rosette::Tms.const_get(const_str) end end end end end
true