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
0162647e2035bb4259cbd7a627cff178c1c0d88c
Ruby
aneeshkhera/sp16-hw2
/app/controllers/concerns/persons.rb
UTF-8
320
3.828125
4
[]
no_license
class Person def initialize(name, age) @name = name @age = age @nickname = name[0,4] end def nickname return @nickname end def birth_year curr = Time.now.year curr - @age.to_i end def introduce "Hello, My name is " + @name.to_s + " and I am " + @age.to_s + " years old" end end
true
bd5f200368c254c14b5abf49e80d6d8fa7a4428e
Ruby
winber2/sql
/reply.rb
UTF-8
1,004
2.84375
3
[]
no_license
require_relative 'questions' class Reply < ModelBase attr_accessor :id, :question_id, :parent_id, :author_id, :body def initialize(options) @author_id = options['author_id'] @question_id = options['question_id'] @parent_id = options['parent_id'] @body = options['body'] @id = options['id'] end def self.find_by_author_id(id) replies = Reply.all.select do |reply| reply.author_id == id end puts "Replies with author_id #{id} not found." if replies.empty? replies end def self.find_by_question_id(id) questions = Reply.all.select do |reply| reply.question_id == id end puts "Questions with author_id #{id} not found." if questions.empty? questions end def author User.find_by_id(@author_id) end def question Question.find_by_id(@question_id) end def parent_reply Reply.find_by_id(@parent_id) end def child_replies Reply.all.select do |reply| reply.parent_id == @id end end end
true
73738fe58d6e091c5b93cfc18977366f696a5215
Ruby
18F/ruby-saml
/lib/onelogin/ruby-saml/logoutresponse.rb
UTF-8
8,645
2.578125
3
[ "MIT" ]
permissive
require "xml_security" require "onelogin/ruby-saml/saml_message" require "time" # Only supports SAML 2.0 module OneLogin module RubySaml # SAML2 Logout Response (SLO IdP initiated, Parser) # class Logoutresponse < SamlMessage # OneLogin::RubySaml::Settings Toolkit settings attr_accessor :settings # Array with the causes attr_accessor :errors attr_reader :document attr_reader :response attr_reader :options attr_accessor :soft # Constructs the Logout Response. A Logout Response Object that is an extension of the SamlMessage class. # @param response [String] A UUEncoded logout response from the IdP. # @param settings [OneLogin::RubySaml::Settings|nil] Toolkit settings # @param options [Hash] Extra parameters. # :matches_request_id It will validate that the logout response matches the ID of the request. # :get_params GET Parameters, including the SAMLResponse # @raise [ArgumentError] if response is nil # def initialize(response, settings = nil, options = {}) @errors = [] raise ArgumentError.new("Logoutresponse cannot be nil") if response.nil? @settings = settings if settings.nil? || settings.soft.nil? @soft = true else @soft = settings.soft end @options = options @response = decode_raw_saml(response) @document = XMLSecurity::SignedDocument.new(@response) end # Append the cause to the errors array, and based on the value of soft, return false or raise # an exception def append_error(error_msg) @errors << error_msg return soft ? false : validation_error(error_msg) end # Reset the errors array def reset_errors! @errors = [] end # Checks if the Status has the "Success" code # @return [Boolean] True if the StatusCode is Sucess # @raise [ValidationError] if soft == false and validation fails # def success? unless status_code == "urn:oasis:names:tc:SAML:2.0:status:Success" return append_error("Bad status code. Expected <urn:oasis:names:tc:SAML:2.0:status:Success>, but was: <#@status_code>") end true end # @return [String|nil] Gets the InResponseTo attribute from the Logout Response if exists. # def in_response_to @in_response_to ||= begin node = REXML::XPath.first( document, "/p:LogoutResponse", { "p" => PROTOCOL, "a" => ASSERTION } ) node.nil? ? nil : node.attributes['InResponseTo'] end end # @return [String] Gets the Issuer from the Logout Response. # def issuer @issuer ||= begin node = REXML::XPath.first( document, "/p:LogoutResponse/a:Issuer", { "p" => PROTOCOL, "a" => ASSERTION } ) node.nil? ? nil : node.text end end # @return [String] Gets the StatusCode from a Logout Response. # def status_code @status_code ||= begin node = REXML::XPath.first(document, "/p:LogoutResponse/p:Status/p:StatusCode", { "p" => PROTOCOL, "a" => ASSERTION }) node.nil? ? nil : node.attributes["Value"] end end def status_message @status_message ||= begin node = REXML::XPath.first( document, "/p:LogoutResponse/p:Status/p:StatusMessage", { "p" => PROTOCOL, "a" => ASSERTION } ) node.text if node end end # Aux function to validate the Logout Response # @return [Boolean] TRUE if the SAML Response is valid # @raise [ValidationError] if soft == false and validation fails # def validate reset_errors! valid_state? && validate_success_status && validate_structure && valid_in_response_to? && valid_issuer? && validate_signature end private # Validates the Status of the Logout Response # If fails, the error is added to the errors array, including the StatusCode returned and the Status Message. # @return [Boolean] True if the Logout Response contains a Success code, otherwise False if soft=True # @raise [ValidationError] if soft == false and validation fails # def validate_success_status return true if success? error_msg = 'The status code of the Logout Response was not Success' status_error_msg = OneLogin::RubySaml::Utils.status_error_msg(error_msg, status_code, status_message) append_error(status_error_msg) end # Validates the Logout Response against the specified schema. # @return [Boolean] True if the XML is valid, otherwise False if soft=True # @raise [ValidationError] if soft == false and validation fails # def validate_structure unless valid_saml?(document, soft) return append_error("Invalid SAML Logout Response. Not match the saml-schema-protocol-2.0.xsd") end true end # Validates that the Logout Response provided in the initialization is not empty, # also check that the setting and the IdP cert were also provided # @return [Boolean] True if the required info is found, otherwise False if soft=True # @raise [ValidationError] if soft == false and validation fails # def valid_state? return append_error("Blank logout response") if response.empty? return append_error("No settings on logout response") if settings.nil? return append_error("No issuer in settings of the logout response") if settings.issuer.nil? if settings.idp_cert_fingerprint.nil? && settings.idp_cert.nil? return append_error("No fingerprint or certificate on settings of the logout response") end true end # Validates if a provided :matches_request_id matchs the inResponseTo value. # @param soft [String|nil] request_id The ID of the Logout Request sent by this SP to the IdP (if was sent any) # @return [Boolean] True if there is no request_id or it match, otherwise False if soft=True # @raise [ValidationError] if soft == false and validation fails # def valid_in_response_to? return true unless options.has_key? :matches_request_id unless options[:matches_request_id] == in_response_to return append_error("Response does not match the request ID, expected: <#{options[:matches_request_id]}>, but was: <#{in_response_to}>") end true end # Validates the Issuer of the Logout Response # @return [Boolean] True if the Issuer matchs the IdP entityId, otherwise False if soft=True # @raise [ValidationError] if soft == false and validation fails # def valid_issuer? return true if settings.idp_entity_id.nil? || issuer.nil? unless URI.parse(issuer) == URI.parse(settings.idp_entity_id) return append_error("Doesn't match the issuer, expected: <#{settings.idp_entity_id}>, but was: <#{issuer}>") end true end # Validates the Signature if it exists and the GET parameters are provided # @return [Boolean] True if not contains a Signature or if the Signature is valid, otherwise False if soft=True # @raise [ValidationError] if soft == false and validation fails # def validate_signature return true unless !options.nil? return true unless options.has_key? :get_params return true unless options[:get_params].has_key? 'Signature' return true if settings.nil? || settings.get_idp_cert.nil? query_string = OneLogin::RubySaml::Utils.build_query( :type => 'SAMLResponse', :data => options[:get_params]['SAMLResponse'], :relay_state => options[:get_params]['RelayState'], :sig_alg => options[:get_params]['SigAlg'] ) valid = OneLogin::RubySaml::Utils.verify_signature( :cert => settings.get_idp_cert, :sig_alg => options[:get_params]['SigAlg'], :signature => options[:get_params]['Signature'], :query_string => query_string ) unless valid error_msg = "Invalid Signature on Logout Response" return append_error(error_msg) end true end end end end
true
8c533248fab0ecf58355c84e6b0702f852b3299e
Ruby
RJTaylor8286/ruby-objects-has-many-through-lab-online-web-pt-110419
/lib/patient.rb
UTF-8
256
2.984375
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Patient attr_accessor :appointment, :doctor @@all = [] def initialize(appointment, doctor) @appointment = appointment @name = name @@all << self end def self.all @@all end end ferris = Patient.new("Ferris Bueller")
true
fbc245b5ea879b49b14bac3a65e2bc564731e09b
Ruby
byungminsa/cucumber-template
/features/step_definitions/general_steps.rb
UTF-8
1,124
2.765625
3
[]
no_license
#Data hash to store the IDs of all editable fields fields = { } When /^I visit "(.*)"$/ do |site| visit site end #Navigates to site When /^I wait "(.*)"$/ do |time| sleep(time.to_i) end #Pauses execution, typically to allow elements to fully load When /^I should see "(.*)"$/ do |content| page.should have_content(content) end #searches the open page for visible text When /^I should not see "(.*)"$/ do |content| page.should_not have_content(content) end #Searches the page for invisible or non-existant text When /^I fill in "(.*)" with "(.*)"$/ do |field_id, text| #see fields hash for valid ids. fill_in fields[field_id], :with => text end #fills in a field located by id with text When /^I click "(.*)"$/ do |text| #Type must contain either button or link, to differentiate between the 2 types. e.g. "When I click "Save" "button"" click_on(text) end # Clicks a link or button based on text When /^I refresh$/ do visit current_url sleep(3) end # refreshes the view When /^URL should be "(.*)"$/ do |supposed_url| current_url.should == supposed_url end # checks that URL is as expected
true
118a8340a9f2d066d92fad628055fcad073ec33f
Ruby
danajackson2/cli-applications-simple-blackjack-sea01-seng-ft-111620
/lib/blackjack.rb
UTF-8
825
4.03125
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
def welcome puts "Welcome to the Blackjack Table" end def deal_card rand(1...11) end def display_card_total(num) puts "Your cards add up to #{num}" end def prompt_user puts "Type 'h' to hit or 's' to stay" end def get_user_input gets.chomp end def end_game(num) puts "Sorry, you hit #{num}. Thanks for playing!" end def initial_round num = deal_card + deal_card display_card_total(num) return num end def invalid_command puts "Please enter a valid command" end def hit?(num) prompt_user input = get_user_input if input == 's' num elsif input == 'h' num += deal_card num else invalid_command prompt_user input = get_user_input end end def runner welcome x = initial_round while x <= 21 x = hit?(x) end display_card_total(x) end_game(x) end
true
1a75c822d25d3189e3ad96fc0c4217b0dcc1474c
Ruby
jfigueras/duckduckgoose
/it.rb
UTF-8
718
3.015625
3
[]
no_license
class It < Player attr_reader :name, :goose, :nplayer attr_accessor :speed, :energy, :arms, :nplayer def post_initialize(args) @nplayer = args[:nplayer] @goose = _choose_goose end def introduction puts "player #{name} is the IT" puts "It has energy #{self.energy} energy" end def play self.energy = self.energy - 3 self.speed = energy + rand() * 50 puts "the it runs at #{speed.round(2)}" end def default_speed 8 end private def _choose_goose players1 = Array(0..name-1) players2 = Array(name+1..nplayer-1) players = players1.concat(players2) players = players.flatten goose = players.sample/10 end end
true
6d0e750028a52fa721183129133bebc7d10459d5
Ruby
lequangcanh/blog_korea
/app/forms/post_form.rb
UTF-8
1,915
2.59375
3
[]
no_license
class PostForm include ActiveModel::Model attr_accessor :status, :translation_title, :translation_content, :language_id, :user_id, :post, :post_translation validates :status, presence: true validates :translation_title, presence: true validates :translation_content, presence: true def initialize args = {} if args[:id] @post = Post.find_by id: args[:id] @post_translation = @post.post_translations.find_by language_id: args[:language_id] @status = args[:status] || @post.status @translation_title = args[:translation_title] || @post_translation&.title @translation_content = args[:translation_content] || @post_translation&.content @language_id = args[:language_id] || @post_translation.language_id @user_id = args[:user_id] || @post_translation&.user&.id else super args end end def persisted? @post&.persisted? end def id @post&.id end def save ActiveRecord::Base.transaction do if valid? create_post create_post_translation true else false end end rescue false end def update ActiveRecord::Base.transaction do if valid? update_post if @post_translation update_post_translation else create_post_translation end true else false end end rescue false end private def create_post @post = Post.create! status: status end def create_post_translation @post.post_translations.create! user_id: user_id, language_id: language_id, title: translation_title, content: translation_content end def update_post @post.update! status: status end def update_post_translation @post_translation.update! user_id: user_id, language_id: language_id, title: translation_title, content: translation_content end end
true
5c2531862dbe3d74b234909d99e375a63ff8f0da
Ruby
jskrwc/sep-assignments
/02-algorithms-and-complexity/02-algorithms-searching/fibonacci_iterative.rb
UTF-8
353
3.15625
3
[]
no_license
def fib_i(n) return 0 if n == 0 # needed bc fib(0) = 0*** fib_0 = 0 fib_1 = 1 (0..n-2).each do # can correct by using n-2, fixes fib(1) as well temp = fib_0 fib_0 = fib_1 fib_1 = temp + fib_1 end fib_1 end ## *** NOTE most fibonacci code examples start from 1, so 1,1,2,... # here starting from base case zero
true
0f2264a53bb1a87df1ea901a87fea56c7412ea05
Ruby
rcjara/Random-Twitter
/lib/TwitterConnector.rb
UTF-8
1,191
2.78125
3
[]
no_license
require 'twitter' require File.expand_path(File.dirname(__FILE__) + '/SimpleConfigParser') class TwitterConnector attr_reader :username include SimpleConfigParser def initialize(config_path) parse_config_file(config_path, :username, :password) end def tweet(post) raise "Not logged on" unless logged_on? @user.update(post) end def most_recent_post raise "Not logged on" unless logged_on? Twitter::Search.new.from(@username).to_a.first.text end def has_password? !@password.nil? end def password raise "Error: You cannot access a TwitterConnector's password." end def connect twitter_auth = Twitter::HTTPAuth.new(@username, @password) @user = Twitter::Base.new(twitter_auth) end def logged_on? return false unless @user @user.verify_credentials end class << self def recent_popular_content(limit = -1) current_trends = Twitter::Trends.current current_trends[0..limit].collect do |trend| Twitter::Search.new(trend.query).lang('en').collect do |result| {:text => result.text, :time => Time.now} end end.flatten end end end
true
6a5a3c4131b937d3b563344d7da1264f8965f269
Ruby
hmcts/hwf-calculator
/app/services/calculation_service.rb
UTF-8
4,337
2.984375
3
[]
no_license
# The primary interface for the calculator # # This class is used with sanitized data in the form of a hash # # @example Example usage for a complete calculation with no further info needed: # inputs = { # marital_status: 'single', # fee: 1000.0, # date_of_birth: Date.parse('1 December 2000'), # disposable_capital: 10000.0, # benefits_received: [], # number_of_children: 2, # total_income: 10000.0 # } # service = CalculationService.call(inputs) # service.help_not_available? # => true # service.help_available? # => false # service.messages # => [{ key: :likely, source: :disposable_capital }] # # @example Example usage for a partial calculation with more fields to fill in # inputs = { # marital_status: 'single', # fee: 1000.0, # } # service = CalculationService.call(inputs) # service.help_not_available? # => false # service.help_available? # => false # service.messages # => [{ key: :likely, source: :disposable_capital }] # # The second example shows that there is not a definitive answer yet, # This allows the front end to inform the user upon a partial success that it depends # on them providing the listed fields. # class CalculationService MY_FIELDS = [:marital_status].freeze DEFAULT_CALCULATORS = [ 'DisposableCapital', 'BenefitsReceived', 'HouseholdIncome' ].freeze # Create an instance of CalculationService # @param [Hash] inputs # @param [Array<BaseCalculatorService>] calculators A list of calculators to use. # This is optional, normally for testing. # @return [CalculationService] This instance def initialize(inputs, calculation, calculators: default_calculators) calculation.reset_messages self.inputs = inputs calculation.merge_inputs(inputs) self.calculation = calculation self.calculators = calculators end # Performs the calculation with the given inputs and configured calculators # # @param [Hash] inputs # @param [Array<BaseCalculatorService>] calculators A list of calculators to use. # This is optional, normally for testing. # @return [CalculationService] A newly created instance of this class def self.call(*args) new(*args).call end # Performs the calculation with the stored inputs and configured calculators # # @return [CalculationService] This instance - with the results available using other instance methods def call catch(:abort) do calculators.each do |calculator| my_result = catch(:invalid_inputs) do perform_calculation_using(calculator) end throw :abort, self if my_result.final_decision? || !my_result.valid? end end self end def result calculation end private def default_calculators DEFAULT_CALCULATORS.map { |c| "#{c}CalculatorService".constantize } end def perform_calculation_using(calculator) result = calculator.call(calculation.inputs.valid_only) post_process_failure result, calculator post_process_undecided result, calculator post_process_success result, calculator result end def post_process_failure(result, calculator) if result.available_help == :none add_failure(result, identifier: calculator.identifier) throw(:abort) end end def post_process_undecided(result, _calculator) if result.available_help == :undecided add_undecided(result) end end def post_process_success(result, calculator) if [:full, :partial].include? result.available_help add_success(result, identifier: calculator.identifier) end end def add_undecided(result) calculation.available_help = :undecided calculation.messages.concat result.messages end def add_failure(result, identifier:) calculation.available_help = :none calculation.final_decision_by = identifier if result.final_decision? calculation.messages.concat result.messages end def add_success(result, identifier:) calculation.available_help = result.available_help calculation.final_decision_by = identifier if result.final_decision? # The remission is always from the last value given, # so its ok to overwrite this calculation.remission = result.remission calculation.messages.concat result.messages end attr_accessor :calculators, :calculation, :inputs end
true
79bb676b060156aea0bae830356855550e8a859a
Ruby
b-studios/doc.js
/lib/code_object/base.rb
UTF-8
1,234
2.8125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
require_relative '../token/container' require_relative '../token/handler' require_relative '../dom/dom' require_relative '../parser/meta_container' module CodeObject class Base include Token::Container include Dom::Node include Parser::MetaContainer attr_reader :docs, :name, :path # The name instance variable is required by Dom::Node def initialize(path = "NO_PATH_SPECIFIED") path = path.to_s.split(/\s/).first # remove trailing spaces @path, @name = path, extract_name_from(path) super() end def to_s token_names = @tokens.keys if @tokens "#<#{self.class}:#{self.name} @parent=#{parent.name if parent} @children=#{@children.keys} @tokens=#{token_names}>" end # Automatically converts markdown-documentation to html def docs=(docstring) @docs = docstring.strip end # can be overriden by subclasses def display_name @name end protected # This is a Helpermethod, which can be used in subclasses like CodeObject::Function def self.token_reader(name, token = name) define_method name do self.token(token) end end end end
true
d3f8a9e44f7f9b9b8d0c856c07360545b3d76f51
Ruby
lissdy/CODEWARS
/Fluent_Calculator.rb
UTF-8
2,215
3.9375
4
[]
no_license
#https://www.codewars.com/kata/fluent-calculator/solutions?show-solutions=1 class Calc def initialize(*args) if args.size == 2 @operation = args[0] @number = args[1] end end %w(zero one two three four five six seven eight nine).each_with_index do |number,index| define_method number do if @operation.nil? index else @number.send(@operation,index) end end end end class Fixnum def plus; Calc.new(:+,self) end def minus; Calc.new(:-,self) end def times; Calc.new(:*,self) end def divided_by; Calc.new(:/,self) end end ##BEST PRACTICE class Fixnum def plus; Calc.new("+", self) end def minus; Calc.new("-", self) end def times; Calc.new("*", self) end def divided_by; Calc.new("/", self) end end class Calc def initialize(*arguments) if arguments.length == 2 @operation = arguments[0] @number = arguments[1] end end %w(zero one two three four five six seven eight nine).each_with_index do |w,i| define_method(w) { perform i } end def perform number if @operation @number.send(@operation, number) else number end end end ##BEST PRACTICE class Calc { zero: 0, one: 1, two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9 }.each do |m, n| define_method("#{m}") { @proc ? @proc.call(n) : (@number ||= n ; self ) } end { plus: :+, minus: :-, times: :*, divided_by: :/ }.each do |m, o| define_method("#{m}") { @proc ||= lambda { |a| @number.send(o, a) }; self } end end ##BEST PRACTICE class Calc ACCEPTED_METHODS = { one:'1', two:'2', three:'3', four:'4', five:'5', six:'6', seven:'7', eight:'8', nine:'9', ten:'10', plus:'+', minus:'-', times:'*', divided_by:'/' } def method_missing(name) @calc_string = "#{@calc_string} #{ACCEPTED_METHODS[name]}".strip @calc_string.split.size == 3 ? eval(@calc_string) : self end end # Calc.new.one.plus.two # Should return 3 # Calc.new.five.minus.six # Should return -1 # Calc.new.seven.times.two # Should return 14 # Calc.new.nine.divided_by.three # Should return 3
true
4518be142a2e92d2553e361a86d7a2f963b640df
Ruby
tosik/automazerb
/lib/automaze.rb
UTF-8
2,336
3.046875
3
[ "MIT" ]
permissive
# encoding: utf-8 require "active_support/inflector" require "panel" module Automaze class OddLengthMaze < Exception; end class Automaze DEFAULT_ALGORITHM = :dug_tunnels class << self def include_algorithm(algorithm) raise "cannot include because algorithm is nil" if algorithm.nil? require "algorithms/#{algorithm.to_s}" include algorithm.to_s.camelize.constantize end end def initialize(options={}) @panels = {} @size_x = options.delete(:size_x) || 30 @size_y = options.delete(:size_y) || 20 raise OddLengthMaze if @size_x.odd? || @size_y.odd? self.class.include_algorithm(options.delete(:algorithm) || DEFAULT_ALGORITHM) self.generate # included algorithm end attr_reader :size_x attr_reader :size_y # nil panel is wall def panels(x,y) @panels[[x,y]] ||= Panel.new(:wall) end def each_panels (0..@size_y).each do |y| (0..@size_x).each do |x| yield(panels(x,y), x, y) end end end def four_panels(x,y) [ panels(x-1,y), panels(x+1,y), panels(x,y-1), panels(x,y+1), ] end def three_panels(x,y) [ panels(x-1,y), panels(x+1,y), panels(x,y+1), ] end def even_hash_panels @panels.select {|xy, panel| xy[0].even? && xy[1].even? } end def random_floor(panels) floors = panels.select {|panel| panel.floor?} raise "no floors" if floors.empty? floors[rand(floors.length)] end def random_even_xy [rand(@size_x/2 + 1) * 2, rand(@size_y/2 + 1) * 2] end def random_floor_xy(hash_panels) floors = hash_panels.select {|xy, panel| panel.floor?} raise "no floors" if floors.empty? return floors.to_a.first.first if floors.length == 1 floors.to_a[rand(floors.length)].first end def out_of_map?(x, y) return true if x < 0 return true if x > @size_x return true if y < 0 return true if y > @size_y return false end def to_s (-1..@size_y+1).map {|y| (-1..@size_x+1).map {|x| if panels(x,y).wall? "XX" else " " end }.join + "\n" }.join end end end
true
5d8f9ae2c4697c2e06c0ceabce36971976188d2b
Ruby
almihoil/TECH.C
/submit/Masahiro1118/post_search_count.rb
UTF-8
1,316
3.46875
3
[]
no_license
require 'sqlite3' # DB操作用 class DBc def initialize @dbname = 'rb14' @tableName = 'zips' end def check_table? # 0の場合テーブルは存在しない sql = "SELECT COUNT(*) from sqlite_master where type='table' and name = ?;" SQLite3::Database.open(@dbname) do |db| db.execute(sql,@tableName) do |num| if (num[0] == 0) return false end end end return true end def search_post_count(post) sql = "SELECT * FROM #{@tableName} WHERE code LIKE ?" count = 0 SQLite3::Database.open(@dbname) do |db| db.execute(sql,"#{post}%%%%") do |num| count += 1 end end return count end end def integer_string?(str) Integer(str) true rescue ArgumentError false end # ------------------------------------------- # データベース操作クラス db = DBc.new() # データ存在チェック if db.check_table? == false puts "[post_initial.rb]を実行してください" end if ARGV[0] == nil puts "郵便番号の一部を入力してください" else if integer_string?(ARGV[0]) # 検索結果を表示 num = db.search_post_count(Integer(ARGV[0])) puts "[count = #{num}]" else puts "数値を入力してください" end end # -------------------------------------------
true
4f8e945f5677263b78f1896ba83ec4f8db188eeb
Ruby
DanElbert/thermostat
/lib/thermostat/sensors/relay_sensor.rb
UTF-8
725
3.171875
3
[]
no_license
module Thermostat module Sensors # Class to represent a 1 wire network branch controller (DS2405) # However, in this case, it is assumed the chip is controlling a relay. # This class has a property to determine if the relay is on or off, # and includes methods for switching the relay on or off class RelaySensor < Sensors::Base # Whether the relay is currently on def on? get_attribute('PIO').to_i == 1 end # Ensures the relay is off def turn_off if on? set_attribute('PIO', 0) end end # Ensures the relay is on def turn_on unless on? set_attribute('PIO', 1) end end end end end
true
5348e3dacdbaf4e727d0857497b089c2e5046f28
Ruby
fornext1119/Numeric-calculation
/rb/0101.rb
UTF-8
180
3.59375
4
[]
no_license
puts 3 + 5 puts 3 - 5 puts 3 * 5 puts 3 ** 5 puts 5 / 3.0 puts 5.0 / 3 puts 5 / 3 puts 5 % 3 print 3 * 5, "\n" printf "%3d\n", 3 * 5 printf "%23.20f\n", 5 / 3.0
true
10ef2582f785b9705549486d4dcb5370541c63f3
Ruby
opal/opal
/stdlib/logger.rb
UTF-8
2,227
3.125
3
[ "MIT" ]
permissive
# backtick_javascript: true class Logger module Severity DEBUG = 0 INFO = 1 WARN = 2 ERROR = 3 FATAL = 4 UNKNOWN = 5 end include Severity SEVERITY_LABELS = Severity.constants.map { |s| [(Severity.const_get s), s.to_s] }.to_h class Formatter MESSAGE_FORMAT = "%s, [%s] %5s -- %s: %s\n" DATE_TIME_FORMAT = '%Y-%m-%dT%H:%M:%S.%6N' def call(severity, time, progname, msg) format(MESSAGE_FORMAT, severity.chr, time.strftime(DATE_TIME_FORMAT), severity, progname, message_as_string(msg)) end def message_as_string(msg) case msg when ::String msg when ::Exception msg.full_message else msg.inspect end end end attr_reader :level attr_accessor :progname attr_accessor :formatter def initialize(pipe) @pipe = pipe @level = DEBUG @formatter = Formatter.new end def level=(severity) if ::Integer === severity @level = severity elsif (level = SEVERITY_LABELS.key(severity.to_s.upcase)) @level = level else raise ArgumentError, "invalid log level: #{severity}" end end def info(progname = nil, &block) add INFO, nil, progname, &block end def debug(progname = nil, &block) add DEBUG, nil, progname, &block end def warn(progname = nil, &block) add WARN, nil, progname, &block end def error(progname = nil, &block) add ERROR, nil, progname, &block end def fatal(progname = nil, &block) add FATAL, nil, progname, &block end def unknown(progname = nil, &block) add UNKNOWN, nil, progname, &block end def info? @level <= INFO end def debug? @level <= DEBUG end def warn? @level <= WARN end def error? @level <= ERROR end def fatal? @level <= FATAL end def add(severity, message = nil, progname = nil, &block) return true if (severity ||= UNKNOWN) < @level progname ||= @progname unless message if block_given? message = yield else message = progname progname = @progname end end @pipe.write(@formatter.call(SEVERITY_LABELS[severity] || 'ANY', ::Time.now, progname, message)) true end end
true
bef2424403d9301c7c2dfe0384156838e8629a45
Ruby
mykhaylomakhnovskyy/TeachBase
/lesson_08/Carriages/cargo_carriage.rb
UTF-8
554
3.34375
3
[]
no_license
# frozen_string_literal: true require_relative 'carriage' # Cargo Carriage Class class CargoCarriage < Carriage attr_accessor :carriage_number, :capacity attr_reader :occupied_volume def initialize(carriage_number, capacity) super @carriage_number = carriage_number @capacity = capacity @occupied_volume = 0 end def occupy_volume(volume) @capacity -= volume @occupied_volume += volume raise 'There is no free space left' if @capacity.negative? end def empty_volume @capacity - @occupied_volume end end
true
fd8a599de92fdc30c67a90724ac39c623d4ecf28
Ruby
Belkot/learn_ruby
/03_simon_says/simon_says.rb
UTF-8
387
3.984375
4
[]
no_license
def echo(str) str end def shout(str) str.upcase end def repeat(str, n=2) ("#{str} " * n).chop end def start_of_word(str, n) str[0...n] end def first_word(str) str.split.first end NO_CAPITALIZE_WORDS = %w( over ) def titleize(str) str[0] = str[0].upcase str.split .map { |e| e.length < 4 || NO_CAPITALIZE_WORDS.include?(e) ? e : e.capitalize } .join ' ' end
true
2ec17970f21d6f10af91755b6bb25c3917c34ca0
Ruby
oneilld136/mechanics-of-migrations-dumbo-web-career-042219
/artist.rb
UTF-8
233
2.71875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Artist attr_reader :name, :age @@all = [] def initialize @name = "Jon" @age = 30 @@all << self end end def save self.create end def find_by (name) self.all.find |info| info.self == name end ActiveRecord::Base
true
887adb058cc43188e4fa1fd5bb28e51337d64347
Ruby
katrinapriya/lime
/app/models/campus.rb
UTF-8
218
2.515625
3
[]
no_license
class Campus < ActiveRecord::Base belongs_to :resource def self.get_values ['Berkeley', 'Davis', 'Merced', 'Santa Cruz'] end def self.count(label) return Campus.where(:val => label).length; end end
true
af5cce85fe7246a5e48fd914e8f0bf94d7e44a41
Ruby
ashifmanjur/cryptor
/lib/cryptor/symmetric_encryption/ciphers/aes128cbchmacsha256128.rb
UTF-8
1,183
2.578125
3
[ "MIT" ]
permissive
require 'cryptor/symmetric_encryption/ciphers/aescbchmacsha2' module Cryptor class SymmetricEncryption module Ciphers # A concrete implementation of the generic AES_CBC_HMAC_SHA2 algorithm # using the HMAC message authentication code [RFC2104] with the SHA-256 # hash function [SHS] to provide message authentication, with the HMAC # output truncated to 128 bits, corresponding to the HMAC-SHA-256-128 # algorithm defined in [RFC4868]. # # For encryption, it uses AES in the Cipher Block Chaining (CBC) mode # of operation as defined in Section 6.2 of [NIST.800-38A], with PKCS#7 # padding and a 128 bit initialization vector (IV) value. class AES128CBCHMACSHA256128 < AESCBCHMACSHA2 # Number of bytes in a key for this cipher def self.key_bytes 64 end # Name of the cipher as implemented by OpenSSL def self.ossl_cipher 'aes-256-cbc' end # Name of the digest as implemented by OpenSSL def self.ossl_digest 'SHA256' end register :aes128cbchmacsha256128, key_bytes: key_bytes end end end end
true
5a01f771c113c81b7a9e75e5666a31ef4c17c9c3
Ruby
kouki-matsuura/ruby_study
/use-inheritance.rb
UTF-8
729
3.296875
3
[]
no_license
class General_User attr_accessor :name def self.usage puts "会員でない人は閲覧のみとなります" puts "会員の人は記事を書き込むことができます" end def initialize(name) @name = name end def browse_article puts "1.~~~~~~の記事" puts "2.~~~~~~の記事" end end class Member < General_User attr_writer :password def initialize(name, password) super(name) @password = password end def write_article puts "#{@name}さん、記事を書いてください" string = gets puts "\n記事:#{string}" end end pawl = General_User.new('pawl') pawl.browse_article smith = Member.new('smith', 'aaa') Member.usage smith.write_article
true
93f8e8060ff40595ed85da21d3726bf4eec8fd3b
Ruby
tartansinatra/Classwork-Week1-4
/functions.rb
UTF-8
334
3.828125
4
[]
no_license
def greeting(day, name) case day when 1 print_message(name, "Monday") when 2 print_message(name, "Tuesday") when 3 print_message(name, "Wednesday") when 4 print_message(name, "Thursday") end end def print_message(name, day) "Hello #{name} it is #{day}. It is awesome!" end puts greeting(1, 'Stu')
true
62c19ed922eef4708a68a6e67909a6dc8316d3dc
Ruby
MetinLamby/Selectfit
/lib/tasks/tester.rb
UTF-8
430
2.578125
3
[]
no_license
require_relative("scrape") require "open-uri" puts "deleting all fake products" products = scraper("https://de.gymshark.com/collections/t-shirts-tops/mens") file = products.first[:photo] puts file fileOpen = URI.open(file) puts fileOpen product = Product.new(name: products.first[:name]) product.photo.attach(io: fileOpen, filename: products.first[:name] + '.jpg', content_type: 'image/jpg') puts product.photo.attached?
true
35ca9ca15d0921ce9d4be091d28673431210e76a
Ruby
JOCOghub/key-for-min-value-onl01-seng-ft-070620
/key_for_min.rb
UTF-8
334
3.59375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
# prereqs: iterators, hashes, conditional logic # Given a hash with numeric values, return the key for the smallest value def key_for_min_value(hash) if hash.empty? return nil end ans = [hash.first[0],hash.first[1]] hash.each do |k,v| if v < ans[1] ans[1] = v ans[0] = k end end return ans[0] end
true
6a4094e9e3a375dd82300f12b6546077880c46dc
Ruby
jbonAA/AAHomework
/W3D4/map.rb
UTF-8
529
3.453125
3
[]
no_license
class Map def initialize(array) raise TypeError unless array.all? { |el| el.class == Array && el.length == 2 } @array = array end def set(key, value) @array.map { |subArr| subArr[1] = value if subArr[0] == key } end def get(key) @array.select { |subArr| subArr if subArr[0] == key } end def delete(key) @array.each_with_index do |pair, i| @array.delete_at(i) if pair[0] == key end end def show @array end end
true
b2f6d595c1a8456ada7921fab372a078c1859d7b
Ruby
aberant/tuio-ruby
/lib/tuio-ruby/core_ext/object.rb
UTF-8
855
3.140625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# this is a little meta magic to clean up some of the repetition in the client # i noticed that i kept making the same similiar methods for each event such as # # client_events :object_creation # # which causes these two methods to be created # def on_object_creation( &object_creation_blk ) # @object_creation_callback_blk = object_creation_blk # end # # def trigger_object_creation_callback( tuio ) # @object_creation_callback_blk.call( tuio ) if @object_creation_callback_blk # end class Object def client_events( *args ) args.each do | event | self.class_eval <<-EOF def on_#{event}( &#{event}_blk ) @#{event}_callback_blk = #{event}_blk end def trigger_#{event}_callback( tuio ) @#{event}_callback_blk.call( tuio ) if @#{event}_callback_blk end EOF end end end
true
b8585d126319dd1b809709d68c417b47b0e7a497
Ruby
Alexis-Trainee/ruby
/return.rb
UTF-8
114
3.359375
3
[ "MIT" ]
permissive
def compare(a, b) a > b end a= 1 b= 2 result = compare(a, b) puts "O resultado da comparação é '#{result}'"
true
f391bac9ece1d358016bd779755831f8e0564579
Ruby
phaedryx/mediaforge
/run
UTF-8
571
3.15625
3
[]
no_license
#!/usr/bin/env ruby require './lib/ball_clock' require 'trollop' options = Trollop::options do opt :file, "file with ball count, one per line, 0 is ignored", type: :string end Trollop::die :file, "option not provided" unless options[:file] Trollop::die :file, "#{options[:file]} not found" unless File.exist?(options[:file]) file = File.open(options[:file], "r") ball_clock = BallClock.new file.each_line do |count| count = count.strip.to_i break if count.to_i == 0 puts "#{count} balls cycle after #{ball_clock.ball_cycle_length_for_count(count)} days." end
true
c04b27cf46e12ed454f1c7130bfedba1e6f34aab
Ruby
arn-e/misc-utility-scripts
/list_comparison.rb
UTF-8
516
3.15625
3
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
require 'csv' file1 = ARGV[0] file2 = ARGV[1] list1 = CSV.read(file1).flatten list2 = CSV.read(file2).flatten puts "List Comparatinator Initialized" #ad-hoc column modification examples : list1.map! {|hash| hash.gsub(/^.*\//,"")} list1.map! {|hash| hash.gsub(".txt","")} missing_1 = list1 - list2 missing_2 = list2 - list1 count1 = missing_1.count count2 = missing_2.count puts "Delta between 1 & 2 : " + count1.to_s() + " \n" puts missing_1 puts "Delta between 2 & 1 : " + count2.to_s() + "\n" puts missing_2
true
ed08a540e542e1df21433853f1f671102b845281
Ruby
gzstudio/meal-picker
/meal-picker-server/app/controllers/users_controller.rb
UTF-8
2,256
2.53125
3
[]
no_license
class UsersController < ApplicationController # will be used to register a new user before_action :authorize_request, only: [ :get_by_id, :update_user, :delete_user ] def create_user userParams = params.require(:user) .permit(:name, :email, :password, :password_confirmation) user = User.new(userParams); if user.save() render json: user, status: :created else render json: { errors: user.errors.full_messages }, status: :unprocessable_entity end end # will be used to get details for a given user def get_by_id # the user_id param comes from our route user = User.find(params[:user_id]) if user render json: user, status: :ok else render json: { errors: 'User not found' }, status: :not_found end end # will be used to update a users information, # such as name, email or password def update_user end # will be used to delete a user, # such as if a user wishes to deactivate their account def delete_user end # will be used to verify a users credentials, and will return a # JWT for the user if their login details match # all 'protected' routes will need to provide the JWT # as part of the 'Authorise' request header def get_token # Get the user by email user = User.find_by_email(params[:email]) # return unauthorized if the user was not found if !user render json: { error: 'unauthorized' }, status: :unauthorized return end # if the user is not authenticated via the authenticate method # then return unauthorized if !user.authenticate( params[:password] ) render json: { error: 'unauthorized' }, status: :unauthorized return end # if our code gets here, we can generate a token and response. # JWT's include an expiry, we will expire the token in 24 hours token = jwt_encode({user_id: user.id}, 24.hours.from_now) render json: {token: token, exp: 24, username: user.email, userId: user.id}, status: :ok end end
true
e79f77d9b91682a40d3297afa8385344f39efed7
Ruby
alyssa0528/oo-student-scraper-v-000
/lib/student.rb
UTF-8
780
3.203125
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
require 'pry' class Student attr_accessor :name, :location, :twitter, :linkedin, :github, :blog, :profile_quote, :bio, :profile_url @@all = [] def initialize(student_hash) student_hash.each do |key, value| self.send("#{key}=", value) end @@all << self end #takes in an array with students' name, location, and profile URL def self.create_from_collection(students_array) students_array.each do |student| self.new(student) #binding.pry end end def add_student_attributes(attributes_hash) attributes_hash.each do |student_attribute| #student_attribute.each do |key, value| self.send("#{student_attribute[0]}=", student_attribute[1]) end self #binding.pry end def self.all @@all end end
true
c733f818172460e6d046d100662295e7f17bfb0c
Ruby
MerrilCode/Ruby
/classes/oo-basics/starter-code/app.rb
UTF-8
219
2.96875
3
[]
no_license
# Squares require_relative 'area_perimeter.rb' square = Square.new(4) puts "Area: #{square.area} Perimeter: #{square.perimeter}" scale = square.scale 10 puts "Area: #{square.area} Perimeter: #{square.perimeter}"
true
31e81e3700a110e2a2a10c70d34bdc21a5c2b734
Ruby
JoePascale/Kele
/lib/kele.rb
UTF-8
1,837
2.65625
3
[]
no_license
require 'httparty' require 'json' require './lib/roadmap' class Kele include HTTParty include Roadmap def initialize(email, password) @url = 'https://www.bloc.io/api/v1' response = self.class.post("#{@url}/sessions", body: { email: email, password: password }) @auth_token = response['auth_token'] puts response["message"] if response["message"] end def get_me response = self.class.get("#{@url}/users/me", headers: { "authorization" => @auth_token }) JSON.parse(response.body) end def get_mentor_availability(mentor_id) response = self.class.get("#{@url}/mentors/#{mentor_id}/student_availability", headers: { "authorization" => @auth_token}) hash = JSON.parse(response.body) hash.each do |time_slot| p time_slot["starts_at"] end end def get_messages(page = nil) response = self.class.get("#{@url}/message_threads", headers: { "authorization" => @auth_token}, body: { page: page }) JSON.parse(response.body) end def create_message(sender, recipient_id, subject, stripped_text) response = self.class.post("#{@url}/messages", headers: { "authorization" => @auth_token }, body: { sender: sender, recipient_id: recipient_id, subject: subject, "stripped-text" => stripped_text }) puts response["message"] if response["message"] end def create_submission(checkpoint_id, assignment_branch, assignment_commit_link, comment, enrollment_id) response = self.class.post("#{@url}/checkpoint_submissions", headers: { "authorization" => @auth_token }, body: { checkpoint_id: checkpoint_id, assignment_branch: assignment_branch, assignment_commit_link: assignment_commit_link, comment: comment, enrollment_id: enrollment_id }) puts response["message"] if response["message"] end end
true
dafa396f946cbe3a515ee40a4c854e07b28d9094
Ruby
vvlee/cos-ruby-sdk
/lib/cos/resource.rb
UTF-8
4,574
2.53125
3
[ "Apache-2.0" ]
permissive
# coding: utf-8 module COS class Resource attr_reader :bucket, :path, :dir_count, :file_count # 实例化COS资源迭代器 def initialize(bucket, path, options = {}) @bucket = bucket @path = path @more = options @results = Array.new @dir_count = 0 @file_count = 0 end # 实现迭代器 def next loop do # 从接口获取下一页结果 fetch_more if @results.empty? # 取出结果 r = @results.shift break unless r yield r end end # 返回迭代器 def to_enum self.enum_for(:next) end # 获取列表 def fetch client = bucket.client resp = client.api.list(path, @more.merge({bucket: bucket.bucket_name})) # 遍历结果转换为对应的对象 @results = resp[:infos].map do |r| if r[:filesize].nil? # 目录 COSDir.new(r.merge({ bucket: bucket, path: Util.get_list_path(path, r[:name]) })) else # 文件 COSFile.new(r.merge({ bucket: bucket, path: Util.get_list_path(path, r[:name], true) })) end end || [] @dir_count = resp[:dir_count] @file_count = resp[:file_count] @more[:context] = resp[:context] @more[:has_more] = resp[:has_more] end private # 如果有更多页继续获取下一页 def fetch_more return if @more[:has_more] == false fetch end end # COS资源,文件与目录的共有操作 class ResourceOperator < Struct::Base required_attrs :bucket, :path, :name, :ctime, :mtime optional_attrs :biz_attr, :filesize, :filelen, :sha, :access_url, :source_url, # 根目录(bucket)参数 :authority, :bucket_type, :migrate_source_domain, :need_preview, :refers, :blackrefers, :brower_exec, :cnames, :nugc_flag, :SKIP_EXTRA # 资源类型 attr_reader :type alias :file_size :filesize alias :file_len :filelen def initialize(attrs) super(attrs) end # 创建时间Time类型 # # @return [Time] def created_at Time.at(ctime.to_i) end # 更新时间Time类型 # # @return [Time] def updated_at Time.at(mtime.to_i) end # 参数转化为Hash类型 # # @return [Hash] def to_hash hash = { type: type, bucket: bucket.bucket_name, path: path, name: name, ctime: ctime, mtime: mtime, } optional_attrs.each do |key| hash[key] = send(key.to_s) if respond_to?(key) and send(key.to_s) != nil end hash end # 判断当前资源是否存在 # # @raise [ServerError] 服务端异常返回 # # @return [Boolean] 是否存在 # # @example # puts resource.exist? def exist? bucket.exist?(path) end alias :exists? :exist? # 获取(刷新)当前资源的状态 # # @note 如查询根目录('/', '')可以获取到bucket信息, 返回COSDir # # @raise [ServerError] 服务端异常返回 # # @return [COSFile|COSDir] 如果是目录则返回COSDir资源对象,是文件则返回COSFile资源对象 # # @example # puts resource.stat.name def stat bucket.stat(path) end # 更新当前资源的属性 # # @note 根目录('/') 不可更新, 否则会抛出异常 # # @param biz_attr [String] 目录/文件属性,业务端维护 # # @raise [ServerError] 服务端异常返回 # # @example # resource.update('i am the attr') def update(biz_attr) bucket.update(path, biz_attr) @mtime = Time.now.to_i.to_s @biz_attr = biz_attr self end # 删除当前资源 # # @note 非空目录及根目录不可删除,会抛出异常 # # @raise [ServerError] 服务端异常返回 # # @example # resource.delete def delete bucket.delete(path) self end # 删除当前资源, 不会抛出异常而是返回布尔值 # # @note 非空目录及根目录不可删除, 返回false # # @example # puts resource.delete! def delete! bucket.delete!(path) end end end
true
251136cbf6c677dfc69feb2926e7234fcf081de1
Ruby
byu/junkfood
/spec/junkfood/ceb/bus_spec.rb
UTF-8
5,818
2.59375
3
[ "Apache-2.0" ]
permissive
require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe 'Ceb::Bus' do it 'should acts_as_bus' do class TestFoo def initialize(valid) @valid = valid end def valid? @valid end end # Test that we have the proper attributes and methods created with defaults. controller_class = Class.new do include Junkfood::Ceb::Bus acts_as_bus :foo end controller_instance = controller_class.new controller_instance.respond_to?(:send_foo).should be_true controller_instance.respond_to?(:foo_executor).should be_true controller_instance.respond_to?(:foo_executor=).should be_true controller_instance.foo_executor.should be_kind_of(Proc) # Now override the executor on the initialization my_executor = mock('MyExecutor') controller_class = Class.new do include Junkfood::Ceb::Bus acts_as_bus :foo, my_executor end controller_instance = controller_class.new controller_instance.respond_to?(:send_foo).should be_true controller_instance.respond_to?(:foo_executor).should be_true controller_instance.respond_to?(:foo_executor=).should be_true controller_instance.foo_executor.should eql(my_executor) # Now test that we can override the executor, and that the # bus creates and executes with an instane of the TestCommand executor1 = mock('FooExecutor') executor1.should_receive(:call).with(an_instance_of(TestFoo)) controller_instance.foo_executor = executor1 controller_instance.foo_executor.should eql(executor1) controller_instance.send_foo 'test', true # Now we make sure that the TestCommand is invalid, so the # executor will not be called. executor2 = mock('FooExecutor') controller_instance.foo_executor = executor2 controller_instance.foo_executor.should eql(executor2) controller_instance.send_foo 'test', false end it 'should acts_as_command_bus' do class TestCommand def initialize(valid) @valid = valid end def valid? @valid end end # Test that we have the proper attributes and methods created controller_class = Class.new do include Junkfood::Ceb::Bus acts_as_command_bus end controller_instance = controller_class.new controller_instance.respond_to?(:send_command).should be_true controller_instance.respond_to?(:command_executor).should be_true controller_instance.respond_to?(:command_executor=).should be_true controller_instance.command_executor.should be_kind_of( Junkfood::Ceb::Executors::CommandExecutor) # Test again that we have the proper attributes and methods created my_executor = mock('MyExecutor') controller_class = Class.new do include Junkfood::Ceb::Bus acts_as_command_bus my_executor end controller_instance = controller_class.new controller_instance.respond_to?(:send_command).should be_true controller_instance.respond_to?(:command_executor).should be_true controller_instance.respond_to?(:command_executor=).should be_true controller_instance.command_executor.should eql(my_executor) # Now test that we can override the executor, and that the # bus creates and executes with an instane of the TestCommand executor1 = mock('CommandExecutor') executor1.should_receive(:call).with(an_instance_of(TestCommand)) controller_instance.command_executor = executor1 controller_instance.command_executor.should eql(executor1) controller_instance.send_command 'test', true # Now we make sure that the TestCommand is invalid, so the # executor will not be called. executor2 = mock('CommandExecutor') controller_instance.command_executor = executor2 controller_instance.command_executor.should eql(executor2) controller_instance.send_command 'test', false end it 'should acts_as_event_bus' do class TestEvent def initialize(valid) @valid = valid end def valid? @valid end end # Test that we have the proper attributes and methods created controller_class = Class.new do include Junkfood::Ceb::Bus acts_as_event_bus end controller_instance = controller_class.new controller_instance.respond_to?(:send_event).should be_true controller_instance.respond_to?(:event_executor).should be_true controller_instance.respond_to?(:event_executor=).should be_true controller_instance.event_executor.should be_kind_of( Junkfood::Ceb::Executors::EventExecutor) # Test again that we have the proper attributes and methods created my_executor = mock('MyExecutor') controller_class = Class.new do include Junkfood::Ceb::Bus acts_as_event_bus my_executor end controller_instance = controller_class.new controller_instance.respond_to?(:send_event).should be_true controller_instance.respond_to?(:event_executor).should be_true controller_instance.respond_to?(:event_executor=).should be_true controller_instance.event_executor.should eql(my_executor) # Now test that we can override the executor, and that the # bus creates and executes with an instane of the TestEvent executor1 = mock('EventExecutor') executor1.should_receive(:call).with(an_instance_of(TestEvent)) controller_instance.event_executor = executor1 controller_instance.event_executor.should eql(executor1) controller_instance.send_event 'test', true # Now we make sure that the TestEvent is invalid, so the # executor will not be called. executor2 = mock('EventExecutor') controller_instance.event_executor = executor2 controller_instance.event_executor.should eql(executor2) controller_instance.send_event 'test', false end end
true
a3fb8a5dc4f034a433b3d1fc8a3e92032773449f
Ruby
Mewtch/learn_ruby
/03_simon_says/simon_says.rb
UTF-8
417
3.859375
4
[]
no_license
def echo(word) word end def shout(word) word.upcase end def repeat(word, n=2) word = word + " " (word*n).strip end def start_of_word(word,n) word[0,n] end def first_word(word) word.split(' ')[0] end def titleize(word) small = ["and", "or", "the", "over", "to", "the", "a", "but","bung"] word.split(' ').each_with_index do |w,i| w.capitalize! if i==0 || (!small.include? w) end.join(' ') end
true
5a9262efc0f2c0d5d19a7d372f5303397adebf3a
Ruby
dhanesana/yongBot
/lib/old_plugins/p101_scrape.rb
UTF-8
1,986
2.78125
3
[ "MIT" ]
permissive
require 'nokogiri' require 'open-uri' module Cinch module Plugins class P101 include Cinch::Plugin match /(p101)$/ match /(p101) (.+)/, method: :with_num match /(help p101)$/, method: :help def execute(m) with_num(m, '.', 'p101', 1) end def with_num(m, prefix, p101, rank) return m.reply 'invalid rank bru' if rank == "0" return with_name(m, '.', 'p101', rank) if rank.to_i < 1 return m.reply "there's only 101 bru" if rank.to_i > 101 page = Nokogiri::HTML(open('http://mnettv.interest.me/produce101/rank.dbp')) href = page.css('li.mn_04 dd').last.children.first.attributes['href'].value recent_page = Nokogiri::HTML(open("http://mnettv.interest.me#{href}")) name = recent_page.css('p.name')[rank.to_i - 1].text agency = recent_page.css('p.agency')[rank.to_i - 1].text votes = recent_page.css('p.voteCount')[rank.to_i - 1].text href = recent_page.css('div.thumb a')[rank.to_i - 1].first[1] m.reply "Rank #{rank} - #{name}, Agency: #{agency}, Vote Count: #{votes} http://mnettv.interest.me/#{href}" end def with_name(m, prefix, p101, name) input_array = name.split(/[[:space:]]/) input = input_array.join(' ').downcase page = Nokogiri::HTML(open('http://mnettv.interest.me/produce101/rank.dbp')) href = page.css('li.mn_04 dd').last.children.first.attributes['href'].value recent_page = Nokogiri::HTML(open("http://mnettv.interest.me#{href}")) count = 0 recent_page.css('p.name').each do |contestant| count += 1 if contestant.text != input break if contestant.text == input end rank = count + 1 return m.reply "#{name} not found bru" if rank == 102 with_num(m, '.', 'p101', rank) end def help(m) m.reply 'returns produce101 contestant at specified voting rank or name' end end end end
true
f7717e8796e60dccd0f6d0ab144e2a9697579208
Ruby
my0shym/atcoder
/ABC/117/a.rb
UTF-8
205
3.09375
3
[]
no_license
# 4:05 1回ミス # 整数同士の割り算は、結果が切り捨てられて整数になるのを知らなかった。 # 特に他の回答に学びはない。 T, X = gets.split.map(&:to_f) puts T/X
true
3e4ac5e2468d9ee6a935f0c32fc4ad457786cc02
Ruby
thib123/TPJ
/Notes/Ruby/sample_code/ex0040.rb
UTF-8
172
3.734375
4
[ "MIT" ]
permissive
# Sample code from Programing Ruby, page 20 animals = %w( ant bee cat dog elk ) # create an array animals.each {|animal| puts animal } # iterate over the contents
true
7b9a846c8cff6937d9f3f21fb3821c10dca3c4f9
Ruby
drewjparker91/title-case
/lib/title_case.rb
UTF-8
257
3.21875
3
[]
no_license
def title_case(title) split_sentence = title.split split_sentence.each do |word| if word != ("above") && word != ("below") && (word.length > 3) word.capitalize!() end # elsif word.length <=3 end split_sentence.join(" ") end
true
1b5212d42cffdf5efb18dab1375d2deecc81a5a7
Ruby
Ramaze/ramaze
/lib/ramaze/helper/upload.rb
UTF-8
19,939
2.78125
3
[ "MIT" ]
permissive
module Ramaze module Helper ## # Helper module for handling file uploads. File uploads are mostly handled # by Rack, but this helper adds some convenience methods for handling # and saving the uploaded files. # # @example # class MyController < Ramaze::Controller # # Use upload helper # helper :upload # # # This action will handle *all* uploaded files # def handleupload1 # # Iterate over uploaded files and save them in the # # '/uploads/myapp' directory # get_uploaded_files.each_pair do |k, v| # v.save( # File.join('/uploads/myapp', v.filename), # :allow_overwrite => true # ) # # if v.saved? # Ramaze::Log.info( # "Saved uploaded file named #{k} to #{v.path}." # ) # else # Ramaze::Log.warn("Failed to save file named #{k}.") # end # end # end # # # This action will handle uploaded files beginning with 'up' # def handleupload2 # # Iterate over uploaded files and save them in the # # '/uploads/myapp' directory # get_uploaded_files(/^up.*/).each_pair do |k, v| # v.save( # File.join('/uploads/myapp', v.filename), # :allow_overwrite => true # ) # # if v.saved? # Ramaze::Log.info( # "Saved uploaded file named #{k} to #{v.path}." # ) # else # Ramaze::Log.warn("Failed to save file named #{k}.") # end # end # end # end # # @author Lars Olsson # @since 04-08-2011 # module Upload include Ramaze::Traited ## # This method will iterate through all request parameters and convert # those parameters which represents uploaded files to # Ramaze::Helper::Upload::UploadedFile objects. The matched parameters # will then be removed from the request parameter hash. # # Use this method if you want to decide whether to handle file uploads # in your action at runtime. For automatic handling, use # Ramaze::Helper::Upload::ClassMethods#handle_all_uploads or # Ramaze::Helper::Upload::ClassMethods#handle_uploads_for instead. # # @author Lars Olsson # @since 04-08-2011 # @param [Regexp] pattern If set, only those request parameters which # has a name matching the Regexp will be checked for file uploads. # @return [Array] The uploaded files. # @see Ramaze::Helper::Upload::ClassMethods#handle_all_uploads # @see Ramaze::Helper::Upload::ClassMethods#handle_uploads_for # def get_uploaded_files(pattern = nil) uploaded_files = {} # Iterate over all request parameters request.params.each_pair do |k, v| # If we use a pattern, check that it matches if pattern.nil? or pattern =~ k # Rack supports request parameters with either a single value or # an array of values. To support both, we need to check if the # current parameter is an array or not. if v.is_a?(Array) # Got an array. Iterate through it and check for uploaded files file_indices = [] v.each_with_index do |elem, idx| file_indices.push(idx) if is_uploaded_file?(elem) end # Convert found uploaded files to # Ramaze::Helper::Upload::UploadedFile objects file_elems = [] file_indices.each do |fi| file_elems << Ramaze::Helper::Upload::UploadedFile.new( v[fi][:filename], v[fi][:type], v[fi][:tempfile], ancestral_trait[:upload_options] || Ramaze::Helper::Upload::ClassMethods.trait[ :default_upload_options ] ) end # Remove uploaded files from current request param file_indices.reverse_each do |fi| v.delete_at(fi) end # If the request parameter contained at least one file upload, # add upload(s) to the list of uploaded files uploaded_files[k] = file_elems unless file_elems.empty? # Delete parameter from request parameter array if it doesn't # contain any other elements. request.params.delete(k) if v.empty? else # Got a single value. Check if it is an uploaded file if is_uploaded_file?(v) # The current parameter represents an uploaded file. # Convert the parameter to a # Ramaze::Helper::Upload::UploadedFile object uploaded_files[k] = Ramaze::Helper::Upload::UploadedFile.new( v[:filename], v[:type], v[:tempfile], ancestral_trait[:upload_options] || Ramaze::Helper::Upload::ClassMethods.trait[ :default_upload_options ] ) # Delete parameter from request parameter array request.params.delete(k) end end end end # If at least one file upload matched, override the uploaded_files # method with a singleton method that returns the list of uploaded # files. Doing things this way allows us to store the list of uploaded # files without using an instance variable. unless uploaded_files.empty? @_ramaze_uploaded_files = uploaded_files # Save uploaded files if autosave is set to true if ancestral_trait[:upload_options] and ancestral_trait[:upload_options][:autosave] uploaded_files().each_value do |uf| uf.save end end end # The () is required, otherwise the name would collide with the variable # "uploaded_files". return uploaded_files() end ## # Adds some class method to the controller whenever the helper # is included. # def self.included(mod) mod.extend(ClassMethods) end ## # Returns list of currently handled file uploads. # # Both single and array parameters are supported. If you give # your file upload fields the same name (for instance upload[]) Rack will # merge them into a single parameter. The upload helper will keep this # structure so that whenever the request parameter contains an array, the # uploaded_files method will also return an array of # Ramaze::Helper::Upload::UploadedFile objects for the same key. # # @return [Hash] Currently uploaded files. The keys in the hash # corresponds to the names of the request parameters that contained file # uploads and the values consist of Ramaze::Helper::Upload::UploadedFile # objects. # def uploaded_files return @_ramaze_uploaded_files || {} end private # Returns whether +param+ is considered an uploaded file # A parameter is considered to be an uploaded file if it is # a hash and contains all parameters that Rack assigns to an # uploaded file # # @param [Hash] param A request parameter # @return [Boolean] def is_uploaded_file?(param) if param.respond_to?(:has_key?) [:filename, :type, :name, :tempfile, :head].each do |k| return false if !param.has_key?(k) end return true else return false end end # Helper class methods. Methods in this module will be available # in your controller *class* (not your controller instance). module ClassMethods include Ramaze::Traited # Default options for uploaded files. You can change these options # by using the uploads_options method trait :default_upload_options => { :allow_overwrite => false, :autosave => false, :default_upload_dir => nil, :unlink_tempfile => false }.freeze ## # This method will activate automatic handling of uploaded files # for specified actions in the controller. # # @example # class MyController < Ramaze::Controller # # # Use upload helper # helper :upload # # # Handle all uploads for the foo and bar actions # handle_uploads_for :foo, :bar # # # Handle all uploads for the baz action and uploads beginning with # # 'up' for the qux action # handle_uploads_for :baz, [:qux, /^up.*/] # end # # @param [Array] args An arbitrary long list of arguments with action # names (and optionally patterns) that should handle file uploads # automatically. Each argument can either be a symbol or a two-element # array consisting of a symbol and a reqexp. # @see #handle_all_uploads # @see Ramaze::Helper::Upload#get_uploaded_files def handle_uploads_for(*args) args.each do |arg| if arg.respond_to?(:first) and arg.respond_to?(:last) before(arg.first.to_sym) do get_uploaded_files(arg.last) end else before(arg.to_sym) do get_uploaded_files end end end end ## # Sets options for file uploads in the controller. # # @example # # This controller will handle all file uploads automatically. # # All uploaded files are saved automatically in '/uploads/myapp' # # and old files are overwritten. # # # class MyController < Ramaze::Controller # # # Use upload helper # helper :upload # # handle_all_uploads # upload_options :allow_overwrite => true, # :autosave => true, # :default_upload_dir => '/uploads/myapp', # :unlink_tempfile => true # end # # # This controller will handle all file uploads automatically. # # All uploaded files are saved automatically, but the exact location # # is depending on a session variable. Old files are overwritten. # # # class MyController2 < Ramaze::Controller # # # Use upload helper # helper :upload # # # Proc to use for save directory calculation # calculate_dir = lambda { File.join('/uploads', session['user']) } # # handle_all_uploads # upload_options :allow_overwrite => true, # :autosave => true, # :default_upload_dir => calculate_dir, # :unlink_tempfile => true # end # @param [Hash] options Options controlling how file uploads # are handled. # @option options [Boolean] :allow_overwrite If set to *true*, uploaded # files are allowed to overwrite existing ones. This option is set to # *false* by default. # @option options [Boolean] :autosave If set to *true*, # Ramaze::Helper::Upload::UploadedFile#save will be called on all # matched file uploads # automatically. You can use this option to automatically save files # at a preset location, but please note that you will need to set the # :default_upload_dir (and possibly :allow_overwrite) options as well # in order for this to work correctly. This option is set to *false* # by default. # @option options [String|Proc] :default_upload_dir If set to a string # (representing a path in the file system) this option will allow you # to save uploaded files without specifying a path. If you intend to # call Ramaze::Helper::Upload::UploadedFile#save with a path you don't # need to set this option at all. If you need to delay the calculation # of the directory, you can also set this option to a proc. The proc # should accept zero arguments and return a string. This comes in handy # when you want to use different directory paths for different users # etc. This option is set to *nil* by default. # @option options [Boolean] :unlink_tempfile If set to *true*, this # option will automatically unlink the temporary file created by Rack # immediately after Ramaze::Helper::Upload::UploadedFile#save is done # saving the uploaded file. This is probably not needed in most cases, # but if you don't want to expose your uploaded files in a shared # tempdir longer than necessary this option might be for you. This # option is set to *false* by default. # @see Ramaze::Helper::Upload::UploadedFile#initialize # @see Ramaze::Helper::Upload::UploadedFile#save # def upload_options(options) trait( :upload_options => Ramaze::Helper::Upload::ClassMethods.trait[ :default_upload_options ].merge(options) ) end end # ClassMethods ## # This class represents an uploaded file. # # @author Lars Olsson # @since 18-08-2011 # class UploadedFile include Ramaze::Traited # Suggested file name # @return [String] attr_reader :filename # MIME-type # @return [String] attr_reader :type ## # Initializes a new Ramaze::Helper::Upload::UploadedFile object. # # @param [String] filename Suggested file name # @param [String] type MIME-type # @param [File] tempfile temporary file # @param [Hash] options Options for uploaded files. Options supported # match those available to # Ramaze::Helper::Upload::ClassMethods#upload_options # @return [Ramaze::Helper::Upload::UploadedFile] A new # Ramaze::Helper::Upload::UploadedFile object # @see #save # @see Ramaze::Helper::Upload::ClassMethods#upload_options def initialize(filename, type, tempfile, options) @filename = File.basename(filename) @type = type @tempfile = tempfile @realfile = nil trait :options => options end ## # Changes the suggested filename of this # Ramaze::Helper::Upload::UploadedFile. +name+ should be a string # representing the filename (only the filename, not a complete path), # but if you provide a complete path this method it will try to identify # the filename and use that instead. # # @param [String] name The new suggested filename. # def filename=(name) @filename = File.basename(name) end ## # Returns the path of the Ramaze::Helper::Upload::UploadedFile object. # The method will always return *nil* before *save* has been called # on the Ramaze::Helper::Upload::UploadedFile object. # # @return [String|nil] # def path return self.saved? ? @realfile.path : nil end ## # Saves the Ramaze::Helper::Upload::UploadedFile. # # If +path+ is not set, the method checks whether there exists default # options for the path and tries to use that instead. # # If you need to override any options set in the controller (using # upload_options) you can set the corresponding option in +options+ to # override the behavior for this particular # Ramaze::Helper::Upload::UploadedFile object. # # @param [String] path Path where the # Ramaze::Helper::Upload::UploadedFile will be saved # @param [Hash] options Options for uploaded files. Options supported # match those available to # Ramaze::Helper::Upload::ClassMethods#upload_options # @raise [StandardError] Will be raised if the save operation fails. # @see #initialize # @see Ramaze::Helper::Upload::ClassMethods#upload_options # def save(path = nil, options = {}) # Merge options opts = trait[:options].merge(options) unless path # No path was provided, use info stored elsewhere to try to build # the path unless opts[:default_upload_dir] raise StandardError.new('Unable to save file, no dirname given') end unless @filename raise StandardError.new('Unable to save file, no filename given') end # Check to see if a proc or a string was used for the # default_upload_dir parameter. If it was a proc, call the proc and # use the result as the directory part of the path. If a string was # used, use the string directly as the directory part of the path. dn = opts[:default_upload_dir] if dn.respond_to?(:call) dn = dn.call end path = File.join(dn, @filename) end path = File.expand_path(path) # Abort if file altready exists and overwrites are not allowed if File.exists?(path) and !opts[:allow_overwrite] raise StandardError.new('Unable to overwrite existing file') end # Confirm that we can read source file unless File.readable?(@tempfile.path) raise StandardError.new('Unable to read temporary file') end # Confirm that we can write to the destination file unless (File.exists?(path) and File.writable?(path)) \ or (File.exists?(File.dirname(path)) \ and File.writable?(File.dirname(path))) raise StandardError.new( "Unable to save file to #{path}. Path is not writable" ) end # If supported, use IO,copy_stream. If not, require fileutils # and use the same method from there if IO.respond_to?(:copy_stream) IO.copy_stream(@tempfile, path) else require 'fileutils' File.open(@tempfile.path, 'rb') do |src| File.open(path, 'wb') do |dest| FileUtils.copy_stream(src, dest) end end end # Update the realfile property, indicating that the file has been # saved @realfile = File.new(path) # But no need to keep it open @realfile.close # If the unlink_tempfile option is set to true, delete the temporary # file created by Rack unlink_tempfile if opts[:unlink_tempfile] end ## # Returns whether the Ramaze::Helper::Upload::UploadedFile has been # saved or not. # # @return [Boolean] # def saved? return !@realfile.nil? end ## # Deletes the temporary file associated with this # Ramaze::Helper::Upload::UploadedFile immediately. # def unlink_tempfile File.unlink(@tempfile.path) @tempfile = nil end end # UploadedFile end # Upload end # Helper end # Ramaze
true
bf7652ee0451d5cdf0ea17f4693b7af21c82bb69
Ruby
ExtractOfCactus/week_4_homework_3
/db/seeds.rb
UTF-8
974
2.875
3
[]
no_license
require_relative('../models/students') require_relative('../models/houses') require('pry-byebug') house_1 = House.new({ "name" => "Gryffindor", "logo" => "../images/Gryffindor.jpg" }) house_2 = House.new({ "name" => "Ravenclaw", "logo" => "../images/Ravenclaw.jpg" }) house_3 = House.new({ "name" => "Slytherin", "logo" => "../images/Slytherin.jpg" }) house_4 = House.new({ "name" => "Hufflepuff", "logo" => "../images/Hufflepuff.jpg" }) house_1.save() house_2.save() house_3.save() house_4.save() student_1 = Student.new({ "first_name" => "Harry", "last_name" => "Potter", "age" => 12, "house_id" => house_1.id }) student_2 = Student.new({ "first_name" => "Tom", "last_name" => "Roddick", "age" => 35, "house_id" => house_2.id }) student_3 = Student.new({ "first_name" => "Glen", "last_name" => "Young", "age" => 14, "house_id" => house_3.id }) student_1.save() student_2.save() student_3.save() binding.pry nil
true
6fbfe53319e180b6ddf35471ca03640745ac2475
Ruby
Rakatashii/cpp_ch11
/P11_12/generate_names.rb
UTF-8
1,014
2.9375
3
[]
no_license
#!/usr/bin/env ruby require 'Faker' require 'as-duration' n = 200 filename = "/Users/christianmeyer/cpp/ch11/P11_10/data.txt" File.open(filename, 'w') {|f| Faker::Config.random.seed printline = "" sep = "|"; endl = "\n"; n.times do |name, salary| name = Faker::Name.name printline += name + "|" description = Faker::MichaelScott.quote printline += description + "|" hours = rand(12); datetime_start = Faker::Time.forward(1000, :all) datetime_end = time_start + (60*60*hours) date_start = datetime_start.to_s[0, 10] date_end = datetime_end.to_s[0, 10] printline += date_start + "|" + date_end decider = rand(); if (decider >= 0.4) { time_start = datetime_start.to_s[12, 16] time_end = datetime_end.to_s[12, 16] printline += "|" + time_start + "|" + time_end + "\n" } else { printline += "\n" } f.write(printline) end }
true
b635bd904b4fc1b4a14d22dd92d3e625ebfe2a91
Ruby
lgleasain/rock_paper_scissors
/test/lib/judge_test.rb
UTF-8
831
3.296875
3
[]
no_license
require 'test/unit' class JudgeTest < Test::Unit::TestCase def base_strategy lambda{|players| players.first} end private :base_strategy def test_when_player_1_is_bye assert Judge.winner(base_strategy, [nil, :player2]) == :player2 end def test_when_player_2_is_bye assert Judge.winner(base_strategy, [:player1 ,nil]) == :player1 end def test_when_both_are_byes assert Judge.winner(base_strategy, [nil ,nil]) == nil end def test_when_more_than_2_players assert_raise ArgumentError do Judge.winner(base_strategy, [1,2,3]) end end def test_without_strategy assert_no_raise ArgumentError do Judge.winner(nil, [1,2]) end end def test_strategies player_1_wins = lambda{|players| players.first } assert Judge.winner(player_1_wins, [1,2]) == 1 end end
true
023adfff13853aa0434c74c05cb70e70621e3d79
Ruby
klatour324/enigma
/lib/encrypt.rb
UTF-8
328
2.90625
3
[]
no_license
require './lib/enigma' enigma = Enigma.new handle = File.open(ARGV[0], 'r') message = handle.read handle.close encrypted = enigma.encrypt(message) writer = File.open(ARGV[1], 'w') writer.write(encrypted[:encryption]) writer.close puts "Created '#{ARGV[1]}' with the key #{encrypted[:key]} and date #{encrypted[:date]}"
true
42f4c79c2b8c07398dc392f2dde1364a1dbddacb
Ruby
koad/My-Wallet-V3
/check-dependencies.rb
UTF-8
8,008
2.640625
3
[]
no_license
# This script ensures that all dependencies (NPM and Bower) are checked against a whitelist of commits. # Only non-minified source if checked, so always make sure to minify dependencies yourself. Development # tools - and perhaps some very large common libraties - are skipped in these checks. # npm-shrinkwrap.json should be present (e.g. generated with Grunt or # "npm shrinkwrap"). This contains the list of all (sub) dependencies. # Ruby is needed as well as the following gems: # gem install json # Github API requires authentication because of rate limiting. So run with: # GITHUB_USER=username GITHUB_TOKEN=personal_access_token ruby check-dependencies.rb require 'json' require 'open-uri' whitelist = JSON.parse(File.read('dependency-whitelist.json')) @failed = false ########## # Common # ########## def first_two_digits_match(a, b) # e.g. "1.1.x" and "1.1.3" matches # "1.1.x" and "1.2.0" does not match a.split(".")[0].to_i == b.split(".")[0].to_i && a.split(".")[1].to_i == b.split(".")[1].to_i end def getJSONfromURL(url) if ENV['GITHUB_USER'] and ENV['GITHUB_TOKEN'] http_options = {:http_basic_authentication=>[ENV['GITHUB_USER'], ENV['GITHUB_TOKEN']]} json = JSON.load(open(url, http_options)) else json = JSON.load(open(url)) end return json end # apply_math = lambda do |auth, , nom| # a.send(fn, b) # end # add = apply_math.curry.(:+) # subtract = apply_math.curry.(:-) # multiply = apply_math.curry.(:*) # divide = apply_math.curry.(:/) def set_dep(requested_version, whitelisted_repo_key, sha) if requested_version.include?("git+ssh") # Preserve URL return "#{ requested_version.split("#").first }##{ sha }" else return "#{ whitelisted_repo_key }##{ sha }" end end def check_commits!(deps, whitelist, output_deps, type) deps.keys.each do |key| if whitelist["ignore"].include? key # Skip check unless ["angular", "angular-mocks", "angular-animate", "angular-bootstrap", "angular-cookies", "angular-sanitize", "angular-translate-loader-static-files","bootstrap-sass"].include? key # Skip package altoghether output_deps.delete(key) end next end dep = deps[key] if whitelist[key] # puts key # For Bower it expects a version formatted like "1.2.3" or "1.2.x". It will use the highest match exact version. requested_version = type == :npm ? dep['version'] : dep requested_version = requested_version.split("#").last # e.g. "pernas/angular-password-entropy#0.1.3" -> "0.1.3" requested_digits = requested_version.split(".") if requested_version[0] == "~" || requested_digits.length != 3 || requested_digits[2] == "x" puts "Version format not supported: #{ key } #{ requested_version }" @failed = true elsif requested_digits[2] != "*" && requested_version == whitelist[key]['version'] # Exact match elsif requested_digits[2] == "*" and first_two_digits_match(requested_version, whitelist[key]['version']) else # https://github.com/weilu/bip39/compare/2.1.0...2.1.2 url = "https://github.com/#{ whitelist[key]["repo"] }/compare/#{ whitelist[key]['version'] }...#{ requested_version }" puts "#{ key } version #{ requested_version } has not been whitelisted yet. Most recent: #{ whitelist[key]['version'] }. Difference: \n" + url @failed = true next end url = "https://api.github.com/repos/#{ whitelist[key]["repo"] }/tags" # puts url tags = getJSONfromURL(url) tag = nil tags.each do |candidate| if candidate["name"] == "v#{ requested_version }" || candidate["name"] == requested_version tag = candidate break elsif requested_digits[2] == "*" && first_two_digits_match(requested_version, candidate["name"]) if whitelist[key]["version"] < candidate["name"].gsub("v","") puts "Warning: a more recent version #{ candidate["name"] } is available for #{ key }" else tag = candidate break end end end if !tag.nil? # Check if tagged commit matches whitelist commit (this or earlier version) if whitelist[key]["commits"].include?(tag["commit"]["sha"]) if type == :npm output_deps[key] = {"version" => "#{ whitelist[key]["repo"] }##{ tag["commit"]["sha"] }"} else output_deps[key] = set_dep(type == :npm ? dep['version'] : dep, whitelist[key]["repo"], tag["commit"]["sha"]) end else puts "Error: v#{ dep['version'] } of #{ key } does not match the whitelist." @failed = true next end else puts "Warn: no Github tag found for v#{ dep['version'] } of #{ key }." # Look through the list of commits instead: url = "https://api.github.com/repos/#{ whitelist[key]["repo"] }/commits" # puts url commits = getJSONfromURL(url) commit = nil commits.each do |candidate| if candidate["sha"] == whitelist[key]['commits'].first commit = candidate break end end if !commit.nil? if type == :npm output_deps[key] = {"version" => "#{ whitelist[key]["repo"] }##{ commit["sha"] }"} else output_deps[key] = set_dep(type == :npm ? dep['version'] : dep, whitelist[key]["repo"], commit["sha"]) end else throw "Error: no Github commit #{ whitelist[key]["commits"].first } of #{ key }." next end end if type == :npm && deps[key]["dependencies"] output_deps[key]["dependencies"] = {} check_commits!(deps[key]["dependencies"], whitelist, output_deps[key]["dependencies"], type) end else puts "#{key} not whitelisted!" @failed = true end end end package = JSON.parse(File.read('package.json')) ######### # NPM # ######### if package["name"] == "My-Wallet-HD" # Only My-Wallet-HD uses NPM shrinkwrap = JSON.parse(File.read('npm-shrinkwrap.json')) deps = shrinkwrap["dependencies"] output = JSON.parse(File.read('npm-shrinkwrap.json')) # More reliable than cloning output_deps = output["dependencies"] check_commits!(deps, whitelist, output_deps, :npm) # TODO: shrinkwrap each subdependency and/or disallow packages to install dependencies themselves? File.write("build/npm-shrinkwrap.json", JSON.pretty_generate(output)) output = package.dup # output["dependencies"] = {} # Remove unessential dev dependencies: output["devDependencies"].keys.each do |devDep| output["devDependencies"].delete(devDep) unless ["grunt-contrib-clean", "grunt-contrib-concat", "grunt-surround", "grunt-contrib-coffee"].include?(devDep) end output.delete("author") output.delete("contributors") output.delete("homepage") output.delete("bugs") output.delete("license") output.delete("repository") output["scripts"].delete("test") if package["name"] == "My-Wallet-HD" output["scripts"]["postinstall"] = "cd node_modules/sjcl && ./configure --with-sha1 && make && cd -" elsif package["name"] == "angular-blockchain-wallet" output["scripts"].delete("postinstall") else abort("Package renamed? " + package["name"]) end File.write("build/package.json", JSON.pretty_generate(output)) end ######### # Bower # ######### # Only used by the frontend if package["name"] == "angular-blockchain-wallet" bower = JSON.parse(File.read('bower.json')) output = bower.dup output.delete("authors") output.delete("main") output.delete("ignore") output.delete("license") output.delete("keywords") # output.delete("devDependencies") # TODO don't load LocalStorageModule in production deps = bower["dependencies"] check_commits!(deps, whitelist, output["dependencies"], :bower) File.write("build/bower.json", JSON.pretty_generate(output)) end if @failed abort "Please fix the above issues..." end
true
efa8f51c3bbb84c2676e2d32c67a22e7c6452989
Ruby
p-reznick/trumpku
/phrases.rb
UTF-8
4,486
3.53125
4
[]
no_license
require 'pry' require 'ruby_rhymes' class Phrases attr_accessor :all_sentences, :start_phrases, :mid_phrases, :end_phrases, :text ONES = %w(zero one two three four five six seven eight nine) TENS = %w(zero ten twenty thirty forty fifty sixty seventy eighty ninety) TEENS = {'ten one' => 'eleven', 'ten two' => 'twelve', 'ten three' => 'thirteen', 'ten four' => 'fourteen', 'ten five' => 'fifteen', 'ten six' => 'sixteen', 'ten seven' => 'seventeen', 'ten eight' => 'eighteen', 'ten nine' => 'nineteen'} MULTISYLLABLES = %w(ia io[^n] ua oi ed\z nuclear eo [^aeiou]le\z) def initialize(text) self.text = get_clean_text(text) self.all_sentences = get_all_sentences end def get_clean_text(text) if text =~ /\.(txt|md)\z/ File.open(text, 'r').each.inject('') do |string, line| string.concat(line) end else text end.gsub(/(\n|["])/, '') end def get_all_sentences sentences = text.scan(/[\A\.]\s+[^\.]+\./) end def get_syllable_count(word) count = 0 return 0 if word =~ /\A([?!\-—–'";:$%]|--|——)\z/ return get_acronym_syllable_count(word) if is_acronym?(word) begin count = make_english_word(word).to_phrase.syllables rescue puts "Error thrown with word: #{word}" end count += 2 if word =~ /[%$]/ count end def get_phrase_syllables(string) string.split.inject(0) do |sum, word| sum += get_syllable_count(word) end end def make_english_word(word) return word unless word =~ /\d+/ word = word.gsub(/,/, '') word = word.gsub(/(\d+)/) { decimal_to_word($1) } end def get_phrase(phase, num_syllables) case phase when "start" loop do phrase = start_phrases.sample return phrase if get_phrase_syllables(phrase) == num_syllables end when "mid" loop do phrase = mid_phrases.sample return phrase if get_phrase_syllables(phrase) == num_syllables end when "end" loop do phrase = end_phrases.sample return phrase if get_phrase_syllables(phrase) == num_syllables end end end def get_sentence(num_syllables) loop do sentence = all_sentences.sample return sentence if get_phrase_syllables(sentence) == num_syllables end end def decimal_to_word(word) # handles decimal numbers 0 to 999999 word = word.scan(/\d+/)[0] decimal = word.to_s.chars.reverse word_arr = [] decimal.each_with_index do |digit, index| if index % 3 == 0 word_arr.push(ONES[digit.to_i]) elsif index % 3 == 1 word_arr.push(TENS[digit.to_i]) elsif index % 3 == 2 word_arr.push(ONES[digit.to_i] + ' hundred') end end word_arr.reverse! if decimal.count === 6 count = 2 loop do current = word_arr[count] if current != 'zero' word_arr.insert(count + 1, 'thousand') break end count = count - 1 end elsif decimal.count > 3 insert_idx = decimal.count % 3 word_arr = word_arr.insert(insert_idx, 'thousand') end word_arr.delete_if { |word| word =~ /zero/ } unless word_arr.length == 1 word_str = word_arr.join(' ') TEENS.each do |k, v| word_str.gsub!(/#{k}/, v) end word_str end def is_acronym?(word) (word =~ /(\A([A-Z]\.){2,}+\z|\A([A-Z]){2,}+\z)/) ? true : false end def get_acronym_syllable_count(word) count = 0 count += word =~ /\./ ? word.length / 2 : word.length return word =~ /w/i ? count + 1 : count end def get_splittable_text(syllable_pattern, sentence_lengths) loop do full_text = sentence_lengths.reduce('') do |aggregate, length| aggregate.concat(get_sentence(length)) end return full_text if match_syllable_pattern?(full_text, syllable_pattern) end end def match_syllable_pattern?(text, pattern) total_lengths = [] pattern.each_with_index do |length, i| total_lengths[i] = pattern[0..i].reduce(:+) end total_lengths = total_lengths.select do |length| length != 0 end match_count = 0 text.split.reduce('') do |aggregate, word| aggregate.concat(' ' + word) match_count += 1 if total_lengths.include?(get_syllable_count(aggregate)) aggregate end match_count == total_lengths.length end end
true
43fd23d3b47460df0df4d5687127afa24edec64c
Ruby
Universe-Man/code_challenge_practice_1.3
/airline.rb
UTF-8
637
3.15625
3
[]
no_license
class Airline ALL = [] attr_reader :name, :hq def initialize(name, hq) @name = name @hq = hq ALL << self end def self.all ALL end def flights Flight.all.select do |flight| flight.airline == self end end def destinations flights.map do |flight| flight.destination.location end end def clear_for_takeoff(number, destination) Flight.new(number, self, destination) end def self.all_aboard Airline.all.each do |airline| puts "Thank you for choosing #{airline.name}! Promising a safe flight from our Headquarters in #{airline.hq}." end end end
true
8c3c61c13703a06ea8b9f8a836258647382f9bd2
Ruby
jpclark6/advent-of-code-2018
/solutions/day_6.rb
UTF-8
2,145
3.375
3
[]
no_license
require 'pry' input = File.read('./puzzle_txt/day_6.txt') input = input.split("\n").map { |line| [line.split(", ")[0].to_i, line.split(", ")[1].to_i]} def find_grid_dims(input) [input.max_by { |a, b| a }[0], input.max_by { |a, b| b }[1]] end def find_manhattan_distance(x1, y1, x2, y2) (x1 - x2).abs + (y1 - y2).abs end def grid_with_distances(grid, x, y, index) streets = Array.new(grid.length) { Array.new(grid[0].length) } grid.length.times do |column| grid[0].length.times do |row| streets[column][row] = {index => find_manhattan_distance(x, y, row, column)} end end streets end max_x = find_grid_dims(input)[0] + 2 max_y = find_grid_dims(input)[1] + 2 grid = Array.new(max_y) {Array.new(max_x, {0 => 1000})} each_input_with_dist = input.map.with_index do |xy, i| grid_with_distances(grid, xy[0], xy[1], i) end each_input_with_dist.each_with_index do |one_grid, i| one_grid.each_with_index do |one_row, y| one_row.each_with_index do |one_loc, x| if grid[y][x].values[0] > one_loc.values[0] grid[y][x] = 0 grid[y][x] = one_loc elsif grid[y][x].values[0] == one_loc.values[0] grid[y][x] = {500 => one_loc.values[0]} end end end end def edge?(loc, grid) edges = [] grid[0].each { |key| edges << key.keys.first } grid[-1].each { |key| edges << key.keys.first } (0...grid.length).each do |i| edges << grid[i][0].keys.first edges << grid[i][-1].keys.first end edges.include?(loc) end flat_grid = grid.flatten answer = flat_grid.group_by { |hash| hash.keys.first } .map { |key, val| [val.length, key] } .sort .reverse .find { |value, loc| edge?(loc, grid) == false } .first binding.pry puts "Part 1 answer: #{answer}" distance_grid = grid.map.with_index do |row, i| row.map.with_index do |loc, j| distance_to_all = 0 input.each do |x, y| distance_to_all += find_manhattan_distance(x, y, i, j) end distance_to_all end end answer_2 = distance_grid.flatten.count { |loc| loc < 10000 } puts "Part 2 answer: #{answer_2}"
true
9b5bf44e66ba48dd8581934879aaf79759480084
Ruby
carol-yao/coding_challenges
/adding_array.rb
UTF-8
286
3.4375
3
[]
no_license
# animals = []['dog', 4], ['cat', 3], ['dogs',7]] # becomes { 'dogs' => 11, 'cats' => 3} animals = [['dogs', 4], ['cats', 3], ['dogs',7]] hash = {} animals.each do |animal| if hash[animal[0]] != nil hash[animal[0]] += animal[1] else hash[animal[0]] = animal[1] end end
true
0f4e2b01cbe9c8b7621c9df889acfc11033619cc
Ruby
elibar-uk/pixel
/lib/editor.rb
UTF-8
1,277
3.65625
4
[]
no_license
require './lib/image' class Editor attr_reader :image COMMANDS = { 'I' => :create, 'H' => :horizontal, 'V' => :vertical, 'L' => :colourize, 'C' => :clear, 'S' => :show }.freeze def create(*args) @image = Image.new(*args) end def run @running = true while @running print '> ' input = gets.chomp execute_command(input) end end def execute_command(input) command, *args = input.split(" ") case command when "I" create(*args) when "X" exit_session when "?" help else image.send(COMMANDS.fetch(command), *args) end end def exit_session @running = false end def help help_text = <<~TEXT ? - Help I M N - Create a new M x N image with all pixels coloured white (O). C - Clears the table, setting all pixels to white (O). L X Y C - Colours the pixel (X,Y) with colour C. V X Y1 Y2 C - Draw a vertical segment of colour C in column X between rows Y1 and Y2 (inclusive). H X1 X2 Y C - Draw a horizontal segment of colour C in row Y between columns X1 and X2 (inclusive). S - Show the contents of the current image X - Terminate the session TEXT puts help_text end end
true
0432bbf21b7c6fe92b05b049d318dc6ded43810a
Ruby
tamsenrochelle1/RubyLearnings
/rubyBranching.rb
UTF-8
422
4.09375
4
[]
no_license
# if else conditions # sunday, dec 15 #condition = false #another_condition = false #if condition || another_condition # puts "one condition met" #else # puts "no conditions" #end # puts "la la la" # || or # && and name = "Joe" if name == "Tamsen" puts "welcome to the program, tamsen" elsif name == "Jaron" #elsif gives a second option puts "welcome to the program, jaron" else puts "welcome to the jungle" end
true
8e21a1c9166653314633afab308a42185b2ddf0a
Ruby
Slav666/pub_lab_week_02
/specs/customer_spec.rb
UTF-8
941
2.921875
3
[]
no_license
require("minitest/autorun") require("minitest/rg") require_relative("../customer") require_relative("../drink") require_relative("../pub") class CustomerTest < MiniTest::Test def setup @drink_L = Drink.new({name: "gin and tonic", price: 10}) @drink_S = Drink.new({namee: "red wine", price: 8}) @customer_1 = Customer.new({name: "Lacey", wallet: 300}) #this is one customer @customer_2 = Customer.new({name: "Slav", wallet: 600}) #this is another customer end # def test_customer_class_exist # assert_equal(Customer, @customer.class) # end def test_customer_name assert_equal("Lacey", @customer_1.check_customer_name) end def test_customer_wallet_amount assert_equal(600, @customer_2.check_customer_wallet_amount) end def test_customer_wallet_decrease @customer_1.customer_buys_drink(@drink_L) assert_equal(290, @customer_1.check_customer_wallet_amount) end end
true
59154aef0b1a9074c5f4ec27076688838a3014eb
Ruby
StevenClontz/roman_scrabble_words
/spec/roman_scrabble_word_spec.rb
UTF-8
558
2.578125
3
[]
no_license
require_relative '../main' describe 'The Roman scrabble word identifier' do it 'recognizes CIVIC' do expect('CIVIC'.is_roman?).to be_truthy end it "doesn't recognize EFFACED or FOOBAR" do expect('EFFACED'.is_roman?).to be_falsy expect('FOOBAR'.is_hexy?).to be_falsy end end describe 'The Hex scrabble word identifier' do it "doesn't recognize CIVIC or FOOBAR" do expect('CIVIC'.is_hexy?).to be_falsy expect('FOOBAR'.is_hexy?).to be_falsy end it "recognizes EFFACED" do expect('EFFACED'.is_hexy?).to be_truthy end end
true
5e11313e72aab9549ea225379b0d5a4e452b8210
Ruby
counterThreat/chess_app
/spec/models/piece_spec.rb
UTF-8
13,471
2.78125
3
[ "MIT" ]
permissive
require 'rails_helper' RSpec.describe Piece, type: :model do # VALIDATIONS it "has a valid factory" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) queen = FactoryGirl.create(:piece, game: game1, user: elvis) expect(queen).to be_valid end it "is not valid without an id" do piece = FactoryGirl.build(:piece, id: nil) expect(piece).not_to be_valid end it "is not valid without a type" do piece = FactoryGirl.build(:piece, type: nil) expect(piece).not_to be_valid end it "is not valid without a color" do piece = FactoryGirl.build(:piece, color: nil) expect(piece).not_to be_valid end it "has an x_position" do piece = FactoryGirl.build(:piece, x_position: nil) expect(piece).not_to be_valid end it "has a y_position" do piece = FactoryGirl.build(:piece, y_position: nil) expect(piece).not_to be_valid end # ASSOCIATIONS describe "ActiveRecord Associations" do it { is_expected.to belong_to(:game) } it { is_expected.to belong_to(:user) } end # Subclasses # describe "subclass interactions" do # it "allows subclasses to be obstructed" # end # Instance Methods describe 'your_turn? method' do it 'returns false if black_player tries to move during white_player turn' do user = create(:user) user2 = create(:user) game = create(:game) create(:king_white_51, game_id: game.id, user_id: user.id) king_black = create(:king_black_58, game_id: game.id, user_id: user2.id) king_black.move(5, 7) game.reload expect(king_black.your_turn?).to eq(false) end it 'returns true if black_player tries to move during black_player turn' do user3 = create(:user) user4 = create(:user) game2 = create(:game) king_white2 = create(:king_white_51, game_id: game2.id, user_id: user3.id) king_black2 = create(:king_black_58, game_id: game2.id, user_id: user4.id) king_white2.move(5, 2) king_black2.reload expect(king_black2.your_turn?).to eq(true) end end describe 'on_board? method' do it 'returns false if a piece moves out of bound' do piece = FactoryGirl.build(:piece, x_position: 10, y_position: 7) expect(piece.on_board?).to eq false end end describe 'attack!' do it 'returns false if opponent color is equal to attacker color' do user1 = create(:user) user2 = create(:user) game = create(:game_with_white_and_black_players) piece1 = create(:piece, game: game, user_id: user1.id) piece2 = create(:rook, game: game, user_id: user2.id) expect(piece1.attack!(piece2.x_position, piece2.y_position)).to eq(false) end it 'returns true if the square is not occupied' do user1 = create(:user) game = create(:game_with_white_and_black_players) piece1 = create(:piece, game: game, user_id: user1.id) expect(piece1.attack!(0, 0)).to eq(true) end it 'sets piece to captured if attack successful' do user1 = create(:user) user2 = create(:user) game = create(:game_with_white_and_black_players) piece1 = create(:piece, game: game, user_id: user1.id) piece2 = create(:black_rook, game: game, user_id: user2.id) piece1.attack!(piece2.x_position, piece2.y_position) piece2.reload expect(piece2.captured).to eq(true) end end describe 'occupied?' do it 'returns true if a square is occupied' do user = create(:user) game = create(:game) piece = create(:piece, game: game, user: user) expect(piece.occupied?(piece.x_position, piece.y_position)).to eq(true) end it 'returns false if a square is empty' do user = create(:user) game = create(:game) piece = create(:piece, game: game, user: user) expect(piece.occupied?(1, 1)).to eq(false) end end # MOVE METHOD describe "move method" do it "records if move has taken place" do user = FactoryGirl.create(:user) user2 = FactoryGirl.create(:user) game = FactoryGirl.create(:game, black_player_id: user2.id, white_player_id: user.id) rook = FactoryGirl.create(:rook, game: game, user_id: user.id) rook.move(4, 5) expect(rook.move_num).to eq(1) end it "allows a piece to change x position" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 7, y_position: 6) piece = FactoryGirl.create(:rook, game: game1, user: elvis) piece.move(6, 4) expect(piece.x_position).to eq 6 end it "allows a piece to change y position" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 7, y_position: 6) piece = FactoryGirl.create(:rook, game: game1, user: elvis) piece.move(4, 5) expect(piece.y_position).to eq 5 end it "allows a piece to move diagonally" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 7, y_position: 6) piece = FactoryGirl.create(:bishop_white, game: game1, user: elvis) piece.move(2, 2) expect(piece.x_position).to eq 2 expect(piece.y_position).to eq 2 end end # MOVE METHOD WHEN IN CHECK describe "move method in relation to check" do it "does not allow a king to move itself into check" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 7, y_position: 6) black_rook = FactoryGirl.create(:rook, color: 'black', game: game1, user: michael, x_position: 6, y_position: 2) game1.player_turn = 'white' white_king.move(5, 2) white_king.reload expect(white_king.y_position).to eq 1 end it "does not allow a piece to make a move that exposes that piece's king to check" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king_white_51, game: game1, user: elvis) black_king = FactoryGirl.create(:king_black_58, game: game1, user: michael) white_rook = FactoryGirl.create(:rook, color: 'white', game: game1, user: elvis, x_position: 5, y_position: 2) black_rook = FactoryGirl.create(:rook, color: 'black', game: game1, user: michael, x_position: 5, y_position: 7) game1.player_turn = 'white' white_rook.move(6, 2) white_rook.reload expect(white_rook.x_position).to eq 5 expect(white_rook.y_position).to eq 2 end it "allows a capture that resolves check" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 8, y_position: 7) black_rook = FactoryGirl.create(:rook, color: 'black', game: game1, user: michael, x_position: 5, y_position: 4) white_rook = FactoryGirl.create(:rook, color: 'white', game: game1, user: elvis, x_position: 5, y_position: 7) game1.player_turn = 'white' white_rook.move(5, 4) white_rook.reload expect(white_rook.x_position).to eq 5 expect(white_rook.y_position).to eq 4 expect(game1.check).to eq nil end it "allows a move that resolves check by blocking the king" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 8, y_position: 7) black_rook = FactoryGirl.create(:rook, color: 'black', game: game1, user: michael, x_position: 5, y_position: 4) white_rook = FactoryGirl.create(:rook, color: 'white', game: game1, user: elvis, x_position: 4, y_position: 2) game1.player_turn = 'white' white_rook.move(5, 2) white_rook.reload expect(white_rook.x_position).to eq 5 expect(white_rook.y_position).to eq 2 expect(game1.check).to eq nil end it "allows a king to move out of check" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 8, y_position: 7) black_rook = FactoryGirl.create(:rook, color: 'black', game: game1, user: michael, x_position: 5, y_position: 4) white_rook = FactoryGirl.create(:rook, color: 'white', game: game1, user: elvis, x_position: 4, y_position: 2) game1.player_turn = 'white' white_king.move(4, 1) white_king.reload expect(white_king.x_position).to eq 4 expect(white_king.y_position).to eq 1 expect(game1.check).to eq nil end it "does not allow a move that doesn't resolve check" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 8, y_position: 7) black_rook = FactoryGirl.create(:rook, color: 'black', game: game1, user: michael, x_position: 5, y_position: 4) white_rook = FactoryGirl.create(:rook, color: 'white', game: game1, user: elvis, x_position: 6, y_position: 1) game1.player_turn = 'white' white_rook.move(6, 3) white_rook.reload expect(white_rook.x_position).to eq 6 expect(white_rook.y_position).to eq 1 end it "does not allow a king move that doesn't resolve check" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 8, y_position: 7) black_rook = FactoryGirl.create(:rook, color: 'black', game: game1, user: michael, x_position: 5, y_position: 4) white_rook = FactoryGirl.create(:rook, color: 'white', game: game1, user: elvis, x_position: 6, y_position: 1) game1.player_turn = 'white' white_king.move(5, 2) white_king.reload expect(white_king.x_position).to eq 5 expect(white_king.y_position).to eq 1 expect(game1.check).to eq 'white' end # In this test, the king is in check by two pieces. Capturing one doesn't # resolve check and therefore isn't allowed. it "does not allow a capture move that doesn't resolve check" do game1 = FactoryGirl.create(:game) elvis = FactoryGirl.create(:user) michael = FactoryGirl.create(:user) white_king = FactoryGirl.create(:king, color: 'white', game: game1, user: elvis) black_king = FactoryGirl.create(:king, color: 'black', game: game1, user: michael, x_position: 8, y_position: 7) black_rook = FactoryGirl.create(:rook, color: 'black', game: game1, user: michael, x_position: 5, y_position: 4) black_bishop = FactoryGirl.create(:bishop, color: 'black', game: game1, user: michael, x_position: 3, y_position: 3) white_rook = FactoryGirl.create(:rook, color: 'white', game: game1, user: elvis, x_position: 5, y_position: 8) game1.player_turn = 'white' white_rook.move(5, 4) white_rook.reload expect(white_rook.x_position).to eq 5 expect(white_rook.y_position).to eq 8 end end # OBSTRUCTED METHOD describe "obstructed method" do game2 = FactoryGirl.create(:game) bobby = FactoryGirl.create(:user) deepblue = FactoryGirl.create(:user) piece2 = FactoryGirl.create(:piece, game: game2, user: bobby, color: "black") it "returns false if path is unblocked" do x_new = 7 y_new = 7 expect(piece2.obstructed?(x_new, y_new)).to eq false end it "returns true if path is blocked" do x_new = 2 y_new = 2 blocker = FactoryGirl.create(:piece, game: game2, user: deepblue, x_position: 3, y_position: 3) expect(piece2.obstructed?(x_new, y_new)).to eq true end it "returns false if there is a piece on the destination square" do x_new = 3 y_new = 3 expect(piece2.obstructed?(x_new, y_new)).to eq false end end end
true
06752c0efa71bb4e9c28f1b45c844e229b2c4d2a
Ruby
jondot/ratom
/lib/atom/extensions/media.rb
UTF-8
872
2.75
3
[ "MIT" ]
permissive
require 'atom' # # Media extension (see http://video.search.yahoo.com/mrss) # # Exaple: # f.entries << Atom::Entry.new do |e| # e.media_content = Media.new :url => article.media['image'] # end # class Media include Atom::Xml::Parseable include Atom::SimpleExtensions attribute :url, :fileSize, :type, :medium, :isDefault, :expression, :bitrate, :height, :width, :duration, :lang def initialize(o = {}) case o when XML::Reader parse(o, :once => true) when Hash o.each do |k, v| self.send("#{k.to_s}=", v) end else raise ArgumentError, "Got #{o.class} but expected a Hash or XML::Reader" end yield(self) if block_given? end end Atom::Feed.add_extension_namespace :media, "http://search.yahoo.com/mrss/" Atom::Entry.element "media:content", :class => Media
true
536b23efb217f81b16fdc88b1d22acf899b5af2e
Ruby
aaishaa/psychedelic-dream-game
/extra_gosu_app/gosutest.rb
UTF-8
8,048
4.03125
4
[ "MIT" ]
permissive
require 'Gosu' # class Welcome # attr_accessor :x, :y, :w, :h # def initialize(window) # # all setup is done in reset so it can be reused # reset(window) # end # def reset(window) # # create a new image using a random one from the candyList # @image = Gosu::Image.new(window, "welcome.png", false) # @w = @image.width # @h = @image.height # # position it in the center of the window useing the window and image dimensions # # place it half way across the screen and the pull it back half the width of the image # @x = window.width / 2 - @image.width / 2 # @y = window.height / 2 - @image.height / 2 # end # def draw # @image.draw(@x, @y, 1) # end # end class Candy # accessors are here so we can figure out if items hit each other attr_accessor :x, :y, :w, :h # list of all sweet images def candyList ['sweet1.png','sweet2.png','sweet3.png','sweet4.png','sweet5.png','sweet6.png','sweet7.png','sweet8.png'] end # automatically called when a new candy is made def initialize(window) # all setup is done in reset so it can be reused reset(window) end # generic draw call. called each frame def draw @image.draw(@x, @y, 1) end # all the setup stuff def reset(window) # create a new image using a random one from the candyList @image = Gosu::Image.new(window, candyList.sample) # set w,h based on image size @w = @image.width @h = @image.height # a random Y value so it starts at a random place @y = Random.rand(window.height - @h) # velocity of Y is random from -5 to 5 # this changes the angle of the candy @vy = rand(-5..5) # x is set to the full width of the window so it starts on the right side @x = window.width end # updates the candy's position def move # move 5px to the left @x = @x - 5 # move up or down based on the Y velocity @y = @y + @vy end end #### STAR #### class Star # accessors are here so we can figure out if items hit each other attr_reader :x, :y, :w, :h def initialize(window) # velocitys of the star are always 5 or -5 : always 45 degree angles @vx = -5 # initially going left @vy = 5 # initially going down # create the gosu image @image = Gosu::Image.new(window,"star.png", false) # set the width and height based on the image @w = @image.width @h = @image.height # get a random x and y. # ensure it will be on the screen by setting the limit to the screen width/height minus the stars width/height @x = Random.rand(window.width - @w) @y = Random.rand(window.height - @h) end # updates the position of the star def move(window) # use the velocities to move the x and y @x = @x + @vx @y = @y + @vy # if the star hits the left edge change the vx to positive 5 if @x < 0 @vx = 5 end # if the star hits the right side of the screen change the vx to negative 5 if @x > window.width - @image.width @vx = -5 end # if the star hits the top of the screen change the vy to positive 5 if @y < 0 @vy = 5 end # if the star hits the bottom of the screen change the vy to negative 5 if @y > window.height - @image.height @vy = -5 end end # generic draw call. called each frame def draw @image.draw(@x, @y, 1) end end #### HORSE #### class Horse attr_reader :x, :y, :w, :h def initialize(window) # create the gosu image @image = Gosu::Image.new(window, "horse.png", false) # set the width and heigh based on the image @w = @image.width @h = @image.height # position it in the center of the window useing the window and image dimensions # place it half way across the screen and the pull it back half the width of the image @x = window.width / 2 - @image.width / 2 @y = window.height / 2 - @image.height / 2 end # called when a star hits the horse def reset(window) # put the horse back in the center @x = window.width / 2 - @image.width / 2 @y = window.height / 2 - @image.height / 2 end # called when down arrow is pressed def move_down(window) # if the horse isn't yet at the bottom of the screen move it down 20 if @y < window.height - @image.height @y = @y +20 end end # called when up arrow is pressed def move_up # if the horse isn't yet at the top of the screen move it up 20 if @y > 0 @y = @y -20 end end # called when left arrow is pressed def move_left # if the horse isn;t yet at the left of of the screne move it left 20 if @x > 0 @x = @x -20 end end # caalled when right arrow is pressed def move_right(window) # if the horse isn't yet at the right edge move it right 20 if @x < window.width - @image.width @x = @x +20 end end # generic draw call. called each frame def draw @image.draw(@x, @y, 1) end end ### GameWindow ### # this is the main game class. there is only 1 per game. # it loads all the other stuff and keeps track of timing class GameWindow < Gosu::Window # called at start def initialize # width and height of the screen # these are chosen based on the size of the horse and the move speed so the horse doesn't go off the edges # horse width + a value evenly divisble by 20 (move speed) super 710, 568, false # call the initialize method of your superclass of Gosu::Window # text that appears at the top of the window self.caption = "get dat candy" # creates an array of stars and puts 1 star in it @stars = [Star.new(self)] # create the horse @horse = Horse.new(self) # create the candy @candy = Candy.new(self) # start the score at 0 @score = 0 # create a score text object @score_text = Gosu::Font.new(self, 'Arial', 72) # @welcome = Welcome.new(self) # sets the background image @background_image = Gosu::Image.new("bg.png", :tileable => true) end def are_touching?(obj1, obj2) # to determine if star and bricks are touching - generic collision method for two rectangles obj1.x > obj2.x - obj1.w and obj1.x < obj2.x + obj2.w and obj1.y > obj2.y - obj1.h and obj1.y < obj2.y + obj2.h # able to write the .x and .y because of the attr_readers # this was in the project i modified to make this but it seems that it checks each edge of the objects to see if they overlap end # this is called every "frame" def update # sets up all the button controls if button_down?(Gosu::KbDown) # part of the Gosu gem # the self is this window object # this is needed for the position calculations @horse.move_down(self) end if button_down?(Gosu::KbUp) # part of the Gosu gem @horse.move_up end if button_down?(Gosu::KbLeft) # part of the Gosu gem @horse.move_left end if button_down?(Gosu::KbRight) @horse.move_right(self) end # move all the stars @stars.each do |star| star.move(self) # check and see if any of them touch the horse if are_touching?(star, @horse) # if they touch the horse reset the game self.reset end end # move the candy @candy.move # if the candy gets passed the left edge of the screen reset it @candy.reset(self) if @candy.x < 0 # see if the horse and candy touch if are_touching?(@candy, @horse) # increase the score every time the horse touches a candy @score = @score + 1 # reset the candy when the horse touches it @candy.reset(self) # every time the score hits a multiple of 5 if ( @score % 5 == 0 ) # add another star @stars.push(Star.new(self)) end end end # reset the game def reset # rest horese @horse.reset(self) # clear stars to just 1 @stars = [Star.new(self)] # reset score @score = 0 # @welcome = Welcome.new(self) end # draw called every frame def draw # draws the background image # @welcome.draw @background_image.draw(0, 0, 0) # go through each star and draw them @stars.each do |star| star.draw end # draw the horse @horse.draw # draw the candy @candy.draw # draw the score @score_text.draw("#{@score}", 0, 0, 1) end end # initialize the game @window = GameWindow.new # show the game @window.show
true
e1c9458f79783d55072e936be927755bc2c8e49b
Ruby
snags88/euler-club
/project-euler-summation-of-primes/Problem_10_summation_of_primes.rb
UTF-8
874
4.1875
4
[]
no_license
# The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. # Find the sum of all the primes below two million. # To solve this problem user Sieve of Eratosthenes. # The basis is to go through min through limit numbers and eliminating incremental values. def primes_up_to(max) repository = (0..max).collect{true} #=> Create flag array limit = (max ** 0.5) #=> establish search limit for index in 2..limit #=> search through flag aray next if !repository[index] num = (index * 2) while num <= max #=> unflag multiples of primes repository[num] = false num += index end end # => convert numbers into arrays primes = repository.collect.with_index do |flag, value| value if flag end # return cleaned array primes.shift primes.shift primes.compact end # puts 'input max number' x = 2000000 puts primes_up_to(x).inject(:+)
true
3f6ab04aeca5039fec080c896e44363c4a08cf0e
Ruby
mafaher/TPFINAL
/classes/usuario.rb
UTF-8
337
2.6875
3
[]
no_license
class Usuario attr_accessor :nombre, :apellido, :sexo, :edad attr_reader :idusuario, :fechacreacion def initialize(nombre="noname", apellido="nosurname", sexo="blank", edad="blank", fechacreacion="blank") @nombre = nombre @apellido = apellido @sexo = sexo @edad = edad.to_i @fechacreacion = fechacreacion end end
true
b70d16a5b4bcc257a6803f5f24a23f21af00fb25
Ruby
omkz/algorithms-in-ruby
/lib/linked_lists/node.rb
UTF-8
165
3.015625
3
[]
no_license
class Node attr_accessor :next, :prev, :value, :key def initialize(value, key: nil) @value = value @key = key @next = nil @prev = nil end end
true
136544a5c41cbd2b563063da75a043ed377e1257
Ruby
anorico/project-euler-even-fibonacci-q-000
/lib/oo_even_fibonacci.rb
UTF-8
452
3.625
4
[]
no_license
# Implement your object-oriented solution here! class EvenFibonacci def initialize(limit) @fibonacci_array = Array.new(2,1) @limit = limit end def sum sum = 0 i = 1 while @fibonacci_array.last < @limit @fibonacci_array << (@fibonacci_array[i-1] + @fibonacci_array[i]) i += 1 end @fibonacci_array.select do |i| if i < @limit && i % 2 == 0 sum += i end end return sum end end
true
cffeba8c040eec90193e79e990486449467d1008
Ruby
popo03/furima-35693
/spec/models/user_spec.rb
UTF-8
4,939
2.625
3
[]
no_license
require 'rails_helper' RSpec.describe User, type: :model do describe 'ユーザー新規登録' do before do @user = FactoryBot.build(:user) end context '内容に問題がない場合' do it 'すべての情報があれば登録できる' do expect(@user).to be_valid end end context '内容に問題がある場合' do it 'nicknameが空では登録できないこと' do @user.nickname = '' @user.valid? expect(@user.errors.full_messages).to include("Nickname can't be blank") end it 'emailが空では登録できないこと' do @user.email = '' @user.valid? expect(@user.errors.full_messages).to include("Email can't be blank") end it 'emailに@が含まれない場合登録できないこと' do @user.email = 'hogehoge.com' @user.valid? expect(@user.errors.full_messages).to include('Email is invalid') end it '重複したemailが存在する場合登録できないこと' do @user.save another_user = FactoryBot.build(:user) another_user.email = @user.email another_user.valid? expect(another_user.errors.full_messages).to include('Email has already been taken') end it 'passwordが空では登録できないこと' do @user.password = '' @user.valid? expect(@user.errors.full_messages).to include("Password can't be blank") end it 'passwordが存在してもpassword_confirmationが空では登録できないこと' do @user.password_confirmation = '' @user.valid? expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password") end it 'passwordが5文字以下であれば登録できないこと' do @user.password = 'aaa11' @user.password_confirmation = 'aaa11' @user.valid? expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)") end it 'passwordが半角英数混合でないと登録できないこと(英字のみ)' do @user.password = 'aaabbb' @user.password_confirmation = 'aaabbb' @user.valid? expect(@user.errors.full_messages).to include("Password is invalid") end it 'passwordが半角英数混合でないと登録できないこと(数字のみ)' do @user.password = '111222' @user.password_confirmation = '111222' @user.valid? expect(@user.errors.full_messages).to include("Password is invalid") end it 'passwordが半角でないと登録できないこと' do @user.password = 'AAA111' @user.password_confirmation = 'AAA111' @user.valid? expect(@user.errors.full_messages).to include("Password is invalid") end it 'family_nameが空では登録できないこと' do @user.family_name = '' @user.valid? expect(@user.errors.full_messages).to include("Family name can't be blank") end it 'family_nameが全角日本語でないと登録できないこと' do @user.family_name = 'yamada' @user.valid? expect(@user.errors.full_messages).to include("Family name is invalid") end it 'first_nameが空では登録できないこと' do @user.first_name = '' @user.valid? expect(@user.errors.full_messages).to include("First name can't be blank") end it 'first_nameが全角日本語では登録できないこと' do @user.first_name = 'tarou' @user.valid? expect(@user.errors.full_messages).to include("First name is invalid") end it 'family_name_kanaが空では登録できないこと' do @user.family_name_kana = '' @user.valid? expect(@user.errors.full_messages).to include("Family name kana can't be blank") end it 'family_name_kanaが全角カタカナでないと登録できないこと' do @user.family_name_kana = 'やまだ' @user.valid? expect(@user.errors.full_messages).to include("Family name kana is invalid") end it 'first_name_kanaが空では登録できないこと'do @user.first_name_kana = '' @user.valid? expect(@user.errors.full_messages).to include("First name kana can't be blank") end it 'first_name_kanaが全角カタカナでは登録できないこと' do @user.first_name_kana = 'たろう' @user.valid? expect(@user.errors.full_messages).to include("First name kana is invalid") end it 'birthdayが空では登録できないこと' do @user.birthday = '' @user.valid? expect(@user.errors.full_messages).to include("Birthday can't be blank") end end end end
true
5762e3ab7a8f04232887a1dae67d44bf4a4293fd
Ruby
andreatl/rails_reviews
/app/models/restaurant.rb
UTF-8
266
2.828125
3
[]
no_license
class Restaurant < ActiveRecord::Base #attr_accessible :name, :phone has_many :reviews def average_stars avg = self.reviews.average(:stars) # rounds ratings to nearest integer; returns that many asterisks. Don't need to round! "*" * avg.round(1) end end
true
48ef7bb27aafc0707095be00be1eba9edb5992b1
Ruby
guyogev/lazy_load
/server.rb
UTF-8
195
2.578125
3
[]
no_license
require 'sinatra' require 'json' counter = 0 get '/' do redirect 'index.html' end get '/give_me_more' do counter += 1 counter <= 3 ? ((1..10).map { rand 100_000_000 }).to_json : nil end
true
a17747455beaeeff910ef094344472256b7e91c3
Ruby
ValRmo/learn_to_program
/cap10/dictionary_sort.rb
UTF-8
555
3.640625
4
[]
no_license
def dictionary_sort list_words recursive_dictionary list_words, [] end def recursive_dictionary unsorted, sorted if unsorted.length <= 0 return sorted end smallest = unsorted.pop still_unsorted = [] unsorted.each do |small_word| if small_word.downcase < smallest.downcase still_unsorted.push(smallest) smallest = small_word else still_unsorted.push(small_word) end end sorted.push(smallest) recursive_dictionary still_unsorted, sorted end puts dictionary_sort(["Helps", "coding", "me" ,"Thinking"])
true
5ba5c61b5c3fca10b45b81b5b697689e0f858e4c
Ruby
geomsb/video-store-api
/app/models/movie.rb
UTF-8
504
2.625
3
[]
no_license
class Movie < ApplicationRecord has_many :rentals validates :title, :overview, :release_date, presence: true validates :inventory, numericality: true, presence: true def movie_avail? if self.available_inventory >= 1 return true else return false end end def reduce_avail_inv self.available_inventory = self.available_inventory - 1 self.save end def increase_avail_inv self.available_inventory = self.available_inventory + 1 self.save end end
true
0fe6df3b414377098a1eb987b6277b9ff8851a1a
Ruby
pfaithmtan/W2D3
/poker/lib/card.rb
UTF-8
713
3.046875
3
[]
no_license
require 'rspec' require 'spec_helper' class Card CARD_VALUES = { two: 2, three: 3, four: 4, five: 5, six: 6, seven: 7, eight: 8, nine: 9, ten: 10, J: 11, Q: 12, K: 13, A: 14 } CARD_SUITS = { spades: '♠', hearts: '♥', diamonds: '♦', clubs: '♣', } attr_accessor :suit, :value def initialize(value, suit) @suit = suit @value = value end def self.values(key) CARD_VALUES[key] end def suits CARD_SUITS.keys end def <=>(other_card) if self < other_card return -1 elsif self > other_card return 1 else return 0 end end ### end
true
29a7d05e75248fffa1f5d5785a295c98cea2f0f8
Ruby
AcademicWorks/reveal
/lib/reveal.rb
UTF-8
462
3.0625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
class Reveal def self.read(file_or_text) file = coerce_to_file(file_or_text) gzip_reader = Zlib::GzipReader.new(file ) unzipped_data = gzip_reader.readlines.join gzip_reader.close return unzipped_data rescue Zlib::GzipFile::Error => e file.rewind return file.readlines.join end private def self.coerce_to_file(file_or_text) return file_or_text if file_or_text.is_a?(IO) return StringIO.new(file_or_text) end end
true
2190f3a09d9e1d549195968cb44c116fd6e5005d
Ruby
GSergeevich/ror
/Ruby_basic/lesson1/triangle_area.rb
UTF-8
360
3.15625
3
[]
no_license
#! /usr/bin/env ruby puts 'Введите длину основания треугольника:' base = gets.chomp.to_i puts 'Введите высоту треугольника:' height = gets.chomp.to_i puts "Площадь треугольника с основанием #{base} и высотой #{height} составляет #{0.5 * base * height}"
true
781fc4fc8249a5abf413da8b26867336573bbb92
Ruby
kfili/codewars
/6kyu-difficulty-level/find-the-odd-int/solution.rb
UTF-8
135
2.65625
3
[]
no_license
def find_it(seq) tracker = Hash[seq.group_by { |x| x }.map { |k, v| [k, v.count] }] tracker.each { |k, v| return k if v.odd? } end
true
4c1ddac7fa7c033c5a1aac732f9577cb12cc997a
Ruby
bardoloi/projecteuler
/problems/009.rb
UTF-8
769
3.890625
4
[]
no_license
# http://projecteuler.net/problem=9 # The math: # ---------- # a + b + c = 1000 # => (a + b + c)**2 = 1,000,000 # => a**2 + b**2 + c**2 + 2ab + 2bc + 2ca = 1,000,000 # Replace c**2 with (a**2 + b**2) as they are Pyth. triplets # => 2*(a**2 + b**2) + 2ab + 2c(a + b) = 1,000,000 # Replace c with (1000 - a - b) # => 2*(a**2 + b**2) + 2ab + 2(a+b)(1000 - a - b) = 1,000,000 # Reduce the left hand side of this equation, we get: # 1000(a+b) - ab = 500,000 # As a < b < c and a + b + c = 1000, b cannot exceed 499, and a cannot exceed 333 def find_pythagorean_triplets 1.upto(333) do |a| (a+1).upto(499) do |b| if (1000*(a + b) - (a * b)) == 500000 c = Math.sqrt((a**2) + (b**2)).to_i return a * b * c end end end return -1 end
true
732645e96ad0e0938fbeb35a7be245f5eafe9deb
Ruby
fleeree2013/ruby-challenges
/case.rb
UTF-8
478
3.84375
4
[]
no_license
puts "What is the weather?" weather = gets.chomp case (weather) when 'sunny' puts "Put on lots of suncreen and get out in the sun." when 'cloudy' puts "Don't forget your umbrella. It's cloudy" when 'foggy' puts "It might be hard to see today, it's foggy" when 'rainy' puts "Don't forget your raincoat and rubber boots. I't raining!" when 'snowing' puts "Schools might close today. It's snowing." else puts "I don't know what the weather is. I'm not a weather person!" end
true
2bb7ad7637137c8afa515d4df28759f6c6625949
Ruby
georgecode/phase-0-tracks
/ruby/gps2_2.rb
UTF-8
2,794
4.25
4
[]
no_license
# Method to create a list # input: string of items separated by spaces (example: "carrots apples cereal pizza") # steps:create an empty hash # add a create list method(food_str) # .split it # set default to 1 test 0 too #loop through list # print the list to the console [can you use one of your other methods here?] print hash # output: [hash?] # Method to add an item to a list # input: item name and optional quantity # steps: add item food_str, and qty_num # output: updated hash # Method to remove an item from the list # input: food_str # steps: delete food_str # output: updated hash # Method to update the quantity of an item # input: food_str qty_num # steps: override qty # output:updated hash # Method to print a list and make it look pretty # input: hash # steps: loop make pretty # output: updated hash def create_list(list_str) food_list = {} list_array=list_str.split(" ") default_qty = 1 list_array.each do |food| food_list[food.to_sym] = default_qty end food_list end # drive code food_list = create_list("") #p food_list def add_item(food_list, new_food, qty_num = 1) food_list[new_food.to_sym] = qty_num food_list end def remove_item(food_list, food_remove) food_list.delete(food_remove.to_sym) food_list end def update_item(food_list, food, qty_num) food_list[food.to_sym] = qty_num food_list end def pretty_list(food_list) food_list.each do |food, qty| puts "#{food}: #{qty}" end end add_item(food_list, "lemonade", 2) add_item(food_list, "tomatoes", 3) add_item(food_list, "onions", 1) add_item(food_list, "ice cream", 4) remove_item(food_list, "lemonade") update_item(food_list, "ice cream", 1) pretty_list(food_list) # What did you learn about pseudocode from working on this challenge? #It's a goldilocks art form not too little not too much # What are the tradeoffs of using arrays and hashes for this challenge? # We techinically used both .split(" ") created an array and we stored the data # in a hash from there, so we got the best of both worlds # What does a method return? # The last result before it's end # What kind of things can you pass into methods as arguments? # variables, strings, boolens, and numbers # How can you pass information between methods? # In this exercise we passed a method into another method by # saving the method to be passed as a variable # What concepts were solidified in this challenge, and what concepts are still confusing? # The coolest thing I learned in this challange was the abilty to set a default to a parameters. # I wouldn't say im confused about anything more like disapointed in ruby for not # letting me access a hash outside of a method and the flunkyness of explicit return # (the more i get to know ruby, the fonder i become of javascript)
true
a9f257ac3e63c33c6ec72834bb1ff03a53c3d09b
Ruby
aendra-rininsland/monocle-assets
/lib/asset.rb
UTF-8
1,671
2.828125
3
[]
no_license
require 'uri' require 'net/http' require 'net/https' module Asset extend self class ConnectionError < StandardError attr_reader :response def initialize(response, message = nil) @response = response @message = message end def to_s message = "Failed." message << " Response code = #{response.code}." if response.respond_to?(:code) message << " Response message = #{response.message}." if response.respond_to?(:message) message end end class BadRequest < ConnectionError; end class Redirection < ConnectionError def to_s; response['Location'] ? "#{super} => #{response['Location']}" : super; end end def get(url) result = Tempfile.new("nfr.#{rand(1000)}") stream(url) do |io| io.read_body do |chunk| result.write(chunk) end end result.rewind result rescue Redirection => error get error.response['Location'] end def stream(url) uri = URI.parse(url) unless uri.is_a?(URI::HTTP) || uri.is_a?(URI::HTTPS) throw URI::InvalidURIError end http = Net::HTTP.new(uri.host, uri.port) method = Net::HTTP::Get.new(uri.path) if uri.is_a?(URI::HTTPS) http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end http.start do |stream| stream.request(method) do |response| handle_response(response) yield response end end end protected def handle_response(response) case response.code.to_i when 200...299 response when 301,302 raise Redirection.new(response) else raise BadRequest.new(response) end end end
true
3354855d7e48e33621a7a84399abdfef38fa00b6
Ruby
hironobuochiai/kadai-ruby-1
/kadai-introduce.rb
UTF-8
126
2.875
3
[]
no_license
myoji = '落合' namae = '博宣' nenrei = 29 shimei = myoji + namae puts shimei + "です。" + nenrei.to_s + '歳です。'
true
63cd14b57c9b0c2c74343c5b89909fa2bedbc731
Ruby
biancamutaquiha/desafio-coffee-app
/spec/builder/drink_builder_spec.rb
UTF-8
1,339
2.71875
3
[]
no_license
require 'builder/drink_builder' require 'json' describe 'drikn builder' do it 'should return a list price' do prices_json = [ { "drink_name": "long black", "prices": { "small": 3.25, "medium": 3.50 } }, { "drink_name": "flat white", "prices": { "small": 3.50, "medium": 4.00, "large": 4.50 } }, { "drink_name": "short espresso", "prices": { "small": 3.03 } } ] drink_builder = DrinkBuilder.new drinks = drink_builder.build_drink_list(prices_json.to_json) expect(drinks.size).to eq 3 expect(drinks[0].name).to eq ('long black') expect(drinks[1].name).to eq ('flat white') expect(drinks[2].name).to eq ('short espresso') end it 'should to ignore wrong hash' do prices_json = [ { "prices": { "small": 3.25, "medium": 3.50 } }, { "drink_name": "flat white" }, { "drink_name": "short espresso", "prices": { "small": 3.03 } } ] drink_builder = DrinkBuilder.new drinks = drink_builder.build_drink_list(prices_json.to_json) expect(drinks.size).to eq 1 expect(drinks[0].name).to eq ('short espresso') end it 'should return empty list when drink list is empty' do prices_json = [] drink_builder = DrinkBuilder.new drinks = drink_builder.build_drink_list(prices_json.to_json) expect(drinks.size).to eq 0 end end
true
01889d2d60b37e3e8eb720444b5873096fc250c9
Ruby
gdean123/configuration-encryptor
/src/value_encryptor.rb
UTF-8
798
2.796875
3
[]
no_license
require 'openssl' require 'base64' require 'ostruct' module ValueEncryptor KEY_LENGTH = 4096 def self.generate_keypair keypair = OpenSSL::PKey::RSA.new(KEY_LENGTH) OpenStruct.new( public_key: OpenSSL::PKey::RSA.new(keypair.public_key.to_pem), private_key: OpenSSL::PKey::RSA.new(keypair.to_pem) ) end def self.encrypt(plaintext_value, public_key_content) public_key = OpenSSL::PKey::RSA.new(public_key_content) encrypted_binary = public_key.public_encrypt(plaintext_value) Base64.encode64(encrypted_binary) end def self.decrypt(encrypted_value, private_key_content) private_key = OpenSSL::PKey::RSA.new(private_key_content) encrypted_binary = Base64.decode64(encrypted_value) private_key.private_decrypt(encrypted_binary) end end
true
676e3a7880de1f6cb2eb5ff4d2ce593662c52e96
Ruby
badCompany110/LearningProjectcs
/Projects/Ruby/Blocks/library_block_examples.rb
UTF-8
1,481
4.84375
5
[]
no_license
# Code Samples # Given the following array: array = [1, 2, 3] Array#each array.each { |item| print "-#{item}-" } Prints out: -1--2--3- Array#select: array.select { |item| item > 2 } This returns a new array with the following: [3] Array#delete_if array.delete_if { |item| item == 1 } The array is now: [2, 3] Array#reject array.reject { |item| item % 3 == 0 } The above returns a new array: [1, 2] Array#count array.count The above returns 3. But count can also be passed a block: array.count { |item| item % 3 == 0 } The above statement returns 1. # Hashes # Given the following hash: hash = { 'name' => 'Jason', 'location' => 'Treehouse' } Hash#each hash.each do |key, value| puts "key: #{key} value: #{value}" end Prints the following: key: name value: Jason key: location value: Treehouse Hash#each_key: hash.each_key{ |key| puts "key: #{key}" } Prints the following: key: name key: location Hash#each_value: hash.each_value { |val| puts "val: #{val}" } Prints the following: val: Jason val: Treehouse Hash#keep_if hash.keep_if{ |key, val| key == "name" } The hash is now: { 'name' => 'Jason' } Hash#reject hash.reject { |key, val| key == "name" } The hash is now: {} Hash#select hash.select { |key, val| key == "name" } Returns a new hash: { 'name' => 'Jason' }
true
6abfb0d607fda7b4f0941146367a70278ad016b2
Ruby
cvaleriac/my-each-v-000
/my_each.rb
UTF-8
133
3.125
3
[ "LicenseRef-scancode-public-domain", "LicenseRef-scancode-unknown-license-reference" ]
permissive
def my_each (array)# put argument(s) here w = 0 while w < array.length yield array[w] w = w + 1 end return array end
true
b989d8b985ce032447516fdcec1ba3a357227b28
Ruby
illacceptanything/illacceptanything
/code/rails/activesupport/test/encrypted_file_test.rb
UTF-8
1,626
2.546875
3
[ "MIT", "Ruby" ]
permissive
# frozen_string_literal: true require "abstract_unit" require "active_support/encrypted_file" class EncryptedFileTest < ActiveSupport::TestCase setup do @content = "One little fox jumped over the hedge" @content_path = File.join(Dir.tmpdir, "content.txt.enc") @key_path = File.join(Dir.tmpdir, "content.txt.key") File.write(@key_path, ActiveSupport::EncryptedFile.generate_key) @encrypted_file = ActiveSupport::EncryptedFile.new( content_path: @content_path, key_path: @key_path, env_key: "CONTENT_KEY", raise_if_missing_key: true ) end teardown do FileUtils.rm_rf @content_path FileUtils.rm_rf @key_path end test "reading content by env key" do FileUtils.rm_rf @key_path begin ENV["CONTENT_KEY"] = ActiveSupport::EncryptedFile.generate_key @encrypted_file.write @content assert_equal @content, @encrypted_file.read ensure ENV["CONTENT_KEY"] = nil end end test "reading content by key file" do @encrypted_file.write(@content) assert_equal @content, @encrypted_file.read end test "change content by key file" do @encrypted_file.write(@content) @encrypted_file.change do |file| file.write(file.read + " and went by the lake") end assert_equal "#{@content} and went by the lake", @encrypted_file.read end test "raise MissingKeyError when key is missing" do assert_raise(ActiveSupport::EncryptedFile::MissingKeyError) do ActiveSupport::EncryptedFile.new( content_path: @content_path, key_path: "", env_key: "", raise_if_missing_key: true ).read end end end
true
3c1731f4416aef7ef2babc8a35e37b95ac16b3b6
Ruby
RouanThompson/ruby-oo-object-relationships-kickstarter-lab-nyc04-seng-ft-053120
/lib/project.rb
UTF-8
424
2.921875
3
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
class Project attr_reader :title def initialize(title) @title = title end def add_backer(backer) ProjectBacker.new(self, backer) end def backers all_project_projectbackers = ProjectBacker.all.select do |projectbacker_instance| projectbacker_instance.project == self end all_project_projectbackers.map do |projectbacker_instance| projectbacker_instance.backer end end end
true
875feb5d1ea46954220a172f48d723879f0fc265
Ruby
TIYZAP/w2d1-lipsum-wanted
/lipsum.rb
UTF-8
2,987
3.375
3
[]
no_license
#!/usr/bin/env ruby require 'erb' #Needed in order to run index.html.erb! require 'shellwords' #Needed in order to run shellescape! lipsum_wanted = ARGV[0].to_s.downcase #Arguments below were created to display more than one paragraph! multiple_paragraphs = ARGV[1].to_i if multiple_paragraphs < 1 multiple_paragraphs = 1 end puts ARGV.inspect puts lipsum_wanted sam = "My money's in that office, right? If she start giving me some bullshit about it ain't there, and we got to go someplace else and get it, I'm gonna shoot you in the head then and there. Then I'm gonna shoot that bitch in the kneecaps, find out where my goddamn money is. She gonna tell me too. Hey, look at me when I'm talking to you, motherfucker. You listen: we go in there, and that nigga Winston or anybody else is in there, you the first motherfucker to get shot. You understand?" hipster = "Typewriter VHS you probably haven't heard of them esse, photo booth butcher direct trade mlkshk small batch fixie kickstarter poke crucifix sustainable. Truffaut williamsburg vape, shoreditch lumbersexual franzen woke retro. Nihil nesciunt bushwick velit tacos neutra. Readymade jean shorts hexagon, chartreuse seitan ex woke tempor elit meh iPhone veniam. Meh roof party chambray paleo pug, pour-over nisi blog vape fugiat vero beard. Sapiente 3 wolf moon drinking vinegar, do portland kitsch labore iceland consectetur flexitarian est farm-to-table fixie humblebrag scenester. Vinyl fugiat vice sed, synth sustainable hoodie esse squid tumeric echo park tbh." oldschool = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi metus felis, ultrices non feugiat sit amet, vulputate et quam. Mauris at ex orci. Etiam feugiat urna et augue rutrum, vitae rutrum est venenatis. Sed libero dolor, molestie nec sodales vel, vestibulum quis libero. Nulla sed porttitor nunc, eu tincidunt augue. Integer et nisi sit amet arcu hendrerit condimentum vel et nisi. Nam pulvinar est est, consequat dictum libero placerat non. Etiam pellentesque at justo nec aliquam. Ut interdum lacus nec ligula scelerisque efficitur. Mauris suscipit augue et dapibus pellentesque. Donec condimentum sagittis nunc, in blandit nulla volutpat ac. Aliquam faucibus euismod erat id scelerisque. Sed malesuada luctus tortor at finibus. Nulla fermentum arcu eu ante condimentum pellentesque. Quisque efficitur augue nec arcu ullamcorper, eu tincidunt metus malesuada. Suspendisse in odio et massa commodo mattis." if lipsum_wanted == "samuel" output = sam elsif lipsum_wanted == "hip" output = hipster elsif lipsum_wanted == "old" output = oldschool else puts "Pick from one of these. samuel, hip or old" end puts output.inspect #Displays output in Terminal! if output system ("echo #{(output * multiple_paragraphs).shellescape} | pbcopy") #Copies lipsum to clip board! new_file = File.open("./#{lipsum_wanted}.html", "w+") new_file << ERB.new(File.read("index.html.erb")).result(binding) new_file.close end
true
bcf1132f9ebe7b1d72a552f739e6bc33acdcdb86
Ruby
PauloGuilhermeAlmeida/Curso-Ruby
/Tipo_Dados.rb
UTF-8
5,475
3.59375
4
[]
no_license
=begin Informacoes ************************************************************* * Curso de Ruby * ************************************************************* * Aluno.....: Paulo Guilherme Almeida * * Linguagem.: Ruby * * Arquivo...: Tipo_Dados.rb * * Aula......: 02 * * URL.......: https://www.youtube.com/watch?v=JH_aEjoD4C0 * * Data......: 12 de Agosto de 2021 * ************************************************************* =end #Cabecalho puts '╔' + '═' * 78 + '╗' puts "║ ▼ Curso de Ruby - Conceitos Basicos (Tipos de dados)" + ' ' * 12 + "- □ x ║" puts '╠' + '═' * 78 + '╣' #Integer _varDinamica = 505 puts "║ ┌" + '─' * 32 + " Integer " + '─' * 33 + "┐ ║" puts "║ │ _varDinamica = 505" + ' ' * 54 + "│ ║" puts "║ │ puts _varDinamica Resultado: #{_varDinamica}" + ' ' * 26 + "│ ║" puts "║ │ puts _varDinamica.class Resultado: #{_varDinamica.class}" + ' ' * 22 + "│ ║" puts "║ └" + '─' * 74 + "┘ ║" #Float _varDinamica = 5.05 puts "║ ┌" + '─' * 33 + " Float " + '─' * 34 + "┐ ║" puts "║ │ _varDinamica = 5.05" + ' ' * 53 + "│ ║" puts "║ │ puts _varDinamica Resultado: #{_varDinamica}" + ' ' * 25 + "│ ║" puts "║ │ puts _varDinamica.class Resultado: #{_varDinamica.class}" + ' ' * 24 + "│ ║" puts "║ └" + '─' * 74 + "┘ ║" #Boolean _varDinamica = true puts "║ ┌" + '─' * 32 + " Boolean " + '─' * 33 + "┐ ║" puts "║ │ _varDinamica = true" + ' ' * 53 + "│ ║" puts "║ │ puts _varDinamica Resultado: #{_varDinamica}" + ' ' * 25 + "│ ║" puts "║ │ puts _varDinamica.class Resultado: #{_varDinamica.class}" + ' ' * 20 + "│ ║" _varDinamica = false puts "║ │ _varDinamica = false" + ' ' * 52 + "│ ║" puts "║ │ puts _varDinamica Resultado: #{_varDinamica}" + ' ' * 24 + "│ ║" puts "║ │ puts _varDinamica.class Resultado: #{_varDinamica.class}" + ' ' * 19 + "│ ║" puts "║ └" + '─' * 74 + "┘ ║" #String _varDinamica = "Paulo" puts "║ ┌" + '─' * 33 + " String " + '─' * 33 + "┐ ║" puts "║ │ _varDinamica = \"Paulo\"" + ' ' * 50 + "│ ║" puts "║ │ puts _varDinamica Resultado: #{_varDinamica}" + ' ' * 24 + "│ ║" puts "║ │ puts _varDinamica.class Resultado: #{_varDinamica.class}" + ' ' * 23 + "│ ║" puts "║ └" + '─' * 74 + "┘ ║" #Array _varDinamica = [5, 5.05, "Paulo", true] puts "║ ┌" + '─' * 34 + " Array " + '─' * 33 + "┐ ║" puts "║ │ _varDinamica = [5, 5.05, \"Paulo\", true]" + ' ' * 33 + "│ ║" puts "║ │ puts _varDinamica Resultado: #{_varDinamica}" + ' ' * 5 + "│ ║" puts "║ │ puts _varDinamica.class Resultado: #{_varDinamica.class}" + ' ' * 24 + "│ ║" puts "║ │ puts _varDinamica[0] Resultado: #{_varDinamica[0]}" + ' ' * 28 + "│ ║" puts "║ │ puts _varDinamica[0].class Resultado: #{_varDinamica[0].class}" + ' ' * 22 + "│ ║" puts "║ │ puts _varDinamica[1] Resultado: #{_varDinamica[1]}" + ' ' * 25 + "│ ║" puts "║ │ puts _varDinamica[1].class Resultado: #{_varDinamica[1].class}" + ' ' * 24 + "│ ║" puts "║ │ puts _varDinamica[2] Resultado: #{_varDinamica[2]}" + ' ' * 24 + "│ ║" puts "║ │ puts _varDinamica[2].class Resultado: #{_varDinamica[2].class}" + ' ' * 23 + "│ ║" puts "║ │ puts _varDinamica[3] Resultado: #{_varDinamica[3]}" + ' ' * 25 + "│ ║" puts "║ │ puts _varDinamica[3].class Resultado: #{_varDinamica[3].class}" + ' ' * 20 + "│ ║" puts "║ └" + '─' * 74 + "┘ ║" #Hash _varDinamica = {nome: "Paulo", idade: 51} puts "║ ┌" + '─' * 34 + " Hash " + '─' * 34 + "┐ ║" puts "║ │ _varDinamica = {nome: \"Paulo\", idade: 50}" + ' ' * 31 + "│ ║" puts "║ │ puts _varDinamica Resultado: #{_varDinamica}" + " │ ║" puts "║ │ puts _varDinamica.class Resultado: #{_varDinamica.class}" + ' ' * 25 + "│ ║" puts "║ │ puts _varDinamica[:nome] Resultado: #{_varDinamica[:nome]}" + ' ' * 24 + "│ ║" puts "║ │ puts _varDinamica[:nome].class Resultado: #{_varDinamica[:nome] .class}" + ' ' * 23 + "│ ║" puts "║ │ puts _varDinamica[:idade] Resultado: #{_varDinamica[:idade]}" + ' ' * 27 + "│ ║" puts "║ │ puts _varDinamica[:idade].class Resultado: #{_varDinamica[:idade].class}" + ' ' * 22 + "│ ║" puts "║ └" + '─' * 74 + "┘ ║" #Symbol _varDinamica = :simbolo puts "║ ┌" + '─' * 33 + " Symbol " + '─' * 33 + "┐ ║" puts "║ │ _varDinamica = :simbolo" + ' ' * 49 + "│ ║" puts "║ │ puts _varDinamica Resultado: #{_varDinamica}" + ' ' * 22 + "│ ║" puts "║ │ puts _varDinamica.class Resultado: #{_varDinamica.class}" + ' ' * 23 + "│ ║" puts "║ └" + '─' * 74 + "┘ ║" #Rodape puts '╟' + '─' * 78 + '╢' puts "║ Paulo Guilherme Almeida" + ' ' * 53 + '║' puts '╚' + '═' * 78 + '╝' #Fim do Codigo
true
f84b2b0605b4b8e1f423ed6c8ac3123e62d82f23
Ruby
charlag/Mmmail
/lib/email.rb
UTF-8
1,023
2.984375
3
[ "MIT" ]
permissive
require './lib/parser' require './lib/contact' require './lib/parts' class Email attr_reader :id attr_reader :headers attr_reader :subject, :from, :to, :part def initialize(id, string) @id = id @headers, @part = RFC822Parser.parse_message(string) @subject = headers['Subject'].force_encoding('UTF-8') @from = EmailContact.from_string(@headers['From'].force_encoding('UTF-8')) @to = EmailContact.from_string(@headers['To'].force_encoding('UTF-8')) end def to_s puts @headers['From'] puts @headers['From'].force_encoding('UTF-8') puts @from.to_s puts @from.to_s&.force_encoding('UTF-8') "From: #{@from.to_s&.force_encoding('UTF-8')}\n" + "To: #{@to.to_s&.force_encoding('UTF-8')}\n" + "Subject: #{@subject}\n\n" + "#{@part&.to_s&.force_encoding('UTF-8')}" end def html_view(folder_name) Dir.mkdir(folder_name) unless File.exists?(folder_name) @part.html_view(folder_name) end end
true
3dc8572c38ff26943c37963048ac9528e845b119
Ruby
cyberarm/mruby-gosu
/examples/classic_shooter.rb
UTF-8
12,352
3.1875
3
[]
no_license
# A simple Gorilla-style shooter for two players. # Shows how Gosu to generate a map, implement # a dynamic landscape and generally look great. # Also shows a very minimal, yet effective way of designing a game's object system. # Doesn't make use of Gosu's Z-ordering. Not many different things to draw, it's # easy to get the order right without it. # Known issues: # * Collision detection of the missiles is lazy, allows shooting through thin walls. # * The look of dead soldiers is, err, by accident. Soldier.png needs to be # designed in a less obfuscated way :) WIDTH = 640 HEIGHT = 480 GAME_PATH = File.expand_path("..", __FILE__) SMOKE = Gosu::Image.new("#{GAME_PATH}/media/smoke.png") TRANSPARENT = 0 # The class for this game's map. # Design: # * Dynamic map creation at startup, holding it as a Gosu::Image in @image # * Testing for solidity by testing @image's pixel values # * Drawing from a Gosu::Image instance # * Blasting holes into the map is implemented by inserting transparent # image strips generated by `generate_circle` class Map # Radius of a crater. CRATER_RADIUS = 25 # Radius of a crater, Shadow included. SHADOW_RADIUS = 45 def initialize @sky = Gosu::Image.new("#{GAME_PATH}/media/landscape.png", tileable: true) @image = Gosu.render(1, 1) {} # Generate a bunch of single pixel width images used to dig out the craters @crater_segments = generate_circle(CRATER_RADIUS) # Create the map @map_data = [] create_map extract_map_pixels end def generate_circle(radius, color = Gosu::Color::NONE) images = [] width = radius * 2 height = 0 x2 = 0 width.times do |i| x2 = i height = 0 radius.times do |j| if (Gosu.distance(radius, radius, x2, j) < radius) height = radius - j break end end y2 = radius - height y3 = radius + height _height = (y3 - y2) == 0 ? 1 : (y3 - y2) images << Gosu.render(1, _height) do Gosu.draw_line(1, 0, color, 1, _height, color) end end return images end def pixel_solid?(x, y) @map_data[(x + WIDTH * y) * 4 + 4] != TRANSPARENT end def solid?(x, y) # Map is open at the top. return false if y < 0 # Map is closed on all other sides. return true if x < 0 || x >= WIDTH || y >= HEIGHT # Inside of the map, determine solidity from the map image. pixel_solid?(x, y) end def draw # Sky background. @sky.draw(0, 0, 0) # The landscape. @image.draw(0, 0, 0) end def blast(x, y) @crater_segments.size.times do |i| image = @crater_segments[i] @image.insert(image, x - (CRATER_RADIUS - i), y - (image.height / 2)) end extract_map_pixels end private def create_map earth = Gosu::Image.new("#{GAME_PATH}/media/earth.png") star = Gosu::Image.new("#{GAME_PATH}/media/large_star.png") heightmap = [] seed = rand(0xffffff) frequency = 0.01 amplitude = [25, rand(100)].max # Generate a simple curve to make the level not flat WIDTH.times do |x| heightmap << (amplitude * (Math.cos(frequency * (seed + x)) + 1) / 2).to_i end strips = Gosu::Image.load_tiles("#{GAME_PATH}/media/earth.png", 1, earth.height) # Paint about half the map with the earth texture @image = Gosu.render(WIDTH, HEIGHT) do ((HEIGHT / 2) / earth.height).ceil.to_i.times do |y| WIDTH.times do |x| _height = heightmap[x] strips[x % earth.width].draw(x, (HEIGHT / 2) + y * earth.height + _height, 0) end end _x = (WIDTH / 2) - (star.width / 2) _height = heightmap[_x] _y = ((HEIGHT / 2) + _height) - star.height star.draw(_x, _y, 0) end end private def extract_map_pixels @map_data = @image.to_blob.bytes end end # Player class. # Note that applies to the whole game: # All objects implement an informal interface. # draw: Draws the object (obviously) # update: Moves the object etc., returns false if the object is to be deleted # hit_by?(missile): Returns true if an object is hit by the missile, causing # it to explode on this object. class Player # Magic numbers considered harmful! This is the height of the # player as used for collision detection. HEIGHT = 14 attr_reader :x, :y, :dead # Only load the images once for all instances of this class. @@images = Gosu::Image.load_tiles("#{GAME_PATH}/media/soldier.png", 40, 50) def initialize(window, x, y, color) @window = window @x, @y = x, y @color = color @vy = 0 # -1: left, +1: right @dir = -1 # Aiming angle. @angle = 90 end def draw if dead # Poor, broken soldier. @@images[0].draw_rot(@x, @y, 0, 290 * @dir, 0.5, 0.65, @dir * 0.5, 0.5, @color) @@images[2].draw_rot(@x, @y, 0, 160 * @dir, 0.95, 0.5, 0.5, @dir * 0.5, @color) else # Was moved last frame? if @show_walk_anim # Yes: Display walking animation. frame = Gosu.milliseconds / 200 % 2 else # No: Stand around (boring). frame = 0 end # Draw feet, then chest. @@images[frame].draw(x - 10 * @dir, y - 20, 0, @dir * 0.5, 0.5, @color) angle = @angle angle = 180 - angle if @dir == -1 @@images[2].draw_rot(x, y - 5, 0, angle, 1, 0.5, 0.5, @dir * 0.5, @color) end end def update # First, assume that no walking happened this frame. @show_walk_anim = false # Gravity. @vy += 1 if @vy > 1 # Move upwards until hitting something. @vy.times do if @window.map.solid?(x, y + 1) @vy = 0 break else @y += 1 end end else # Move downwards until hitting something. (-@vy).times do if @window.map.solid?(x, y - HEIGHT - 1) @vy = 0 break else @y -= 1 end end end # Soldiers are never deleted (they may die, but that is a different thing). return true end def aim_up @angle -= 2 unless @angle < 10 end def aim_down @angle += 2 unless @angle > 170 end def try_walk(dir) @show_walk_anim = true @dir = dir # First, magically move up (so soldiers can run up hills) 2.times { @y -= 1 unless @window.map.solid?(x, y - HEIGHT - 1) } # Now move into the desired direction. @x += dir unless @window.map.solid?(x + dir, y) || @window.map.solid?(x + dir, y - HEIGHT) # To make up for unnecessary movement upwards, sink downward again. 2.times { @y += 1 unless @window.map.solid?(x, y + 1) } end def try_jump @vy = -12 if @window.map.solid?(x, y + 1) end def shoot @window.objects << Missile.new(@window, x + 10 * @dir, y - 10, @angle * @dir) end def hit_by?(missile) if Gosu.distance(missile.x, missile.y, x, y) < 30 # Was hit :( @dead = true return true else return false end end end # Implements the same interface as Player, except it's a missile! class Missile attr_reader :x, :y, :vx, :vy # All missile instances use the same sound. EXPLOSION = Gosu::Sample.new("#{GAME_PATH}/media/explosion.wav") def initialize(window, x, y, angle) # Horizontal/vertical velocity. @window = window @x, @y = x, y @angle = angle @vx, @vy = Gosu.offset_x(angle, 20).to_i, Gosu.offset_y(angle, 20).to_i @x, @y = x + @vx, y + @vy end def update # Movement, gravity @x += @vx @y += @vy @vy += 1 # Hit anything? if @window.map.solid?(x, y) || @window.objects.any? { |o| o.hit_by?(self) } # Create great particles. 5.times { @window.objects << Particle.new(x - 25 + rand(51), y - 25 + rand(51)) } @window.map.blast(x, y) # # Weeee, stereo sound! EXPLOSION.play_pan((1.0 * @x / WIDTH) * 2 - 1) return false else return true end end def draw # Just draw a small rectangle. Gosu.draw_rect x - 2, y - 2, 4, 4, 0xff_800000 end def hit_by?(missile) # Missiles can't be hit by other missiles! false end end # Very minimal object that just draws a fading particle. class Particle def initialize(x, y) # All Particle instances use the same image @x, @y = x, y @color = Gosu::Color.new(255, 255, 255, 255) end def update @y -= 5 @x = @x - 1 + rand(3) @color.alpha -= 4 # Remove if faded completely. return @color.alpha > 0 end def draw SMOKE.draw(@x - 25, @y - 25, 0, 1, 1, @color) end def hit_by?(missile) # Smoke can't be hit! false end end # Finally, the class that ties it all together. # Very straightforward implementation. class ClassicShooter < Gosu::Window attr_reader :map, :objects def initialize super(WIDTH, HEIGHT) # Texts to display in the appropriate situations. @player_instructions = [] @player_won_messages = [] 2.times do |plr| @player_instructions << Gosu::Image.from_markup( "It is the #{plr == 0 ? "<c=ff00ff00>green</c>" : "<c=ffff0000>red</c>"} toy soldier's turn.\n" + "(Arrow keys to walk and aim, Control to jump, Space to shoot)", 30, width: width, align: :center) @player_won_messages << Gosu::Image.from_markup( "The #{plr == 0 ? "<c=ff00ff00>green</c>" : "<c=ffff0000>red</c>"} toy soldier has won!", 30, width: width, align: :center) end # Create everything! @map = Map.new @players = [] @objects = [] @arrow = Gosu.render(32, 64) do Gosu.draw_rect(8, 0, 16, 48, Gosu::Color::WHITE) Gosu.draw_triangle(0, 48, Gosu::Color::WHITE, 32, 48, Gosu::Color::WHITE, 16, 64, Gosu::Color::WHITE, 0) end # Let any player start. @current_player = rand(2) # Currently not waiting for a missile to hit something. @waiting = false p1, p2 = Player.new(self, 100, 40, 0xff_308000), Player.new(self, WIDTH - 100, 40, 0xff_803000) @players.push(p1, p2) @objects.push(p1, p2) self.caption = "Classic Shooter Demo" end def draw # Draw the main game. @map.draw @objects.each { |o| o.draw } # Draw an arrow over the current players head unless @players[@current_player].dead || @waiting player = @players[@current_player] @arrow.draw(player.x - @arrow.width / 2, player.y - (@arrow.height + 32), 0, 1, 1, Gosu::Color::GRAY) end # If any text should be displayed, draw it - and add a nice black border around it # by drawing it four times, with a little offset in each direction. cur_text = @player_instructions[@current_player] if !@waiting cur_text = @player_won_messages[1 - @current_player] if @players[@current_player].dead if cur_text x, y = 0, 30 cur_text.draw(x - 1, y, 0, 1, 1, 0xff_000000) cur_text.draw(x + 1, y, 0, 1, 1, 0xff_000000) cur_text.draw(x, y - 1, 0, 1, 1, 0xff_000000) cur_text.draw(x, y + 1, 0, 1, 1, 0xff_000000) cur_text.draw(x, y, 0, 1, 1, 0xff_ffffff) end end def update # if waiting for the next player's turn, continue to do so until the missile has # hit something. @waiting &&= !@objects.select { |obj| obj.is_a?(Missile) }.empty? # Remove all objects whose update method returns false. @objects.reject! { |o| o.update == false } # If it's a player's turn, forward controls. if !@waiting && !@players[@current_player].dead player = @players[@current_player] player.aim_up if Gosu.button_down? Gosu::KB_UP player.aim_down if Gosu.button_down? Gosu::KB_DOWN player.try_walk(-1) if Gosu.button_down? Gosu::KB_LEFT player.try_walk(+1) if Gosu.button_down? Gosu::KB_RIGHT player.try_jump if Gosu.button_down?(Gosu::KB_LEFT_CONTROL) || Gosu.button_down?(Gosu::KB_RIGHT_CONTROL) end end def button_down(id) if id == Gosu::KB_SPACE && !@waiting && !@players[@current_player].dead # Shoot! This is handled in button_down because holding space shouldn't auto-fire. @players[@current_player].shoot @current_player = 1 - @current_player @waiting = true else super end end end # So far we have only defined how everything *should* work - now set it up and run it! ClassicShooter.new.show
true
30242f3c30976dd1943183306b1961cab763eff8
Ruby
duboviy/algoholic
/algoholic/ruby_solutions/codewars/jaden_casing_string.rb
UTF-8
359
3.90625
4
[ "MIT" ]
permissive
# Public: To convert strings to how they would be written by Jaden Smith (always capitalizing every word). # # Examples # # "How can mirrors be real if our eyes aren't real".toJadenCase # # => "How Can Mirrors Be Real If Our Eyes Aren't Real" # # Returns the modified string. class String def toJadenCase self.split.map(&:capitalize).join(' ') end end
true
6dd7393c3e9494879a5ee31f2f8268eec512097f
Ruby
WaffleHacks/hackathon-manager
/app/lib/webhooks.rb
UTF-8
5,315
2.6875
3
[ "MIT" ]
permissive
require 'discordrb/webhooks' require 'net/http' module Webhooks READABLE_EVENTS = { questionnaire_pending: "New Application", questionnaire_late_waitlist: "New Late Application", questionnaire_rsvp_confirmed: "RSVP Confirmed", questionnaire_rsvp_denied: "RSVP Denied", questionnaire_discord: "Discord username updated", testing: "Webhooks work!", }.freeze def self.emit(format, url, secret, type, **data) return unless Webhook::POSSIBLE_FORMATS.include? format case format when "json" then standard(url, secret, type.to_sym, **data) when "discord" then discord(url, type.to_sym, **data) when "slack" then slack(url, type.to_sym, **data) end end class << self private def standard(url, secret, type, **data) # Parse the URI uri = URI.parse(url) # Add headers headers = { 'Content-Type' => 'application/json' } if secret != "" headers['Authorization'] = secret end # Build the request req = Net::HTTP::Post.new(uri, headers) req.body = { type: type }.deep_merge(data).to_json # Send the request response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(req) end [response.code.to_i, response.body] end def discord(url, type, **data) # Generate the human readable content for the message description, fields = generate_content(type, **data) client = Discordrb::Webhooks::Client.new(url: url) response = client.execute do |builder| builder.add_embed do |embed| # Set the constants embed.author = Discordrb::Webhooks::EmbedAuthor.new(name: HackathonConfig['name'], icon_url: HackathonConfig['logo_asset']) embed.color = '#1c7ed6' embed.timestamp = Time.now # Set the title and content embed.title = READABLE_EVENTS[type] embed.description = description # Set the fields fields.each { |field| embed.add_field(**field, inline: true) } end end [response.code, response.body] end def slack(url, type, **data) # Generate the human readable content for the message description, fields = generate_content(type, **data) # Parse the URI uri = URI.parse(url) # Build the request req = Net::HTTP::Post.new(uri, { 'Content-Type' => 'application/json' }) # Setup the request body as an attachment body = { text: "#{type}: #{data.to_json}", blocks: [ { type: "header", text: { type: "plain_text", text: READABLE_EVENTS[type], emoji: false, } }, { type: "section", block_id: "description", fields: [ { type: "plain_text", text: description } ] } ] } # Add fields if necessary unless fields.empty? body[:blocks] << { type: "section", block_id: "fields", fields: fields.map { |field| { type: "mrkdwn", text: "*#{field[:name]}*: #{field[:value]}" } } } end # Add the body to the request req.body = body.to_json # Send the request response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: uri.scheme == 'https') do |http| http.request(req) end [response.code.to_i, response.body] end def generate_content(type, **data) case type when :questionnaire_pending questionnaire = data[:questionnaire] school = questionnaire.school user = questionnaire.user [ "_#{user.first_name} #{user.last_name}_ (id: #{user.id}) just applied!", [ { name: "School", value: school.full_name.present? ? school.full_name : "<not provided>" }, { name: "Discord", value: questionnaire.discord } ] ] when :questionnaire_late_waitlist questionnaire = data[:questionnaire] school = questionnaire.school user = questionnaire.user [ "_#{user.first_name} #{user.last_name}_ (id: #{user.id}) just applied! They were automatically waitlisted since the deadline passed.", [ { name: "School", value: school.full_name.present? ? school.full_name : "<not provided>" }, { name: "Discord", value: questionnaire.discord } ] ] when :questionnaire_rsvp_confirmed questionnaire = data[:questionnaire] user = questionnaire.user ["_#{user.first_name} #{user.last_name}_ (id: #{user.id}) will be attending!", []] when :questionnaire_rsvp_denied questionnaire = data[:questionnaire] user = questionnaire.user ["_#{user.first_name} #{user.last_name}_ (id: #{user.id}) will not be attending.", []] when :testing then ["Just testing that webhooks work.", []] else ["Invalid event, something went very wrong", []] end end end end
true
d3086eaf254639b1f5dca4026d0764a8b692111f
Ruby
mflorin/greenlight
/examples/example_lib.rb
UTF-8
902
2.6875
3
[ "MIT" ]
permissive
require 'greenlight' # we can wrap only the request in a function and use it afterwards def login_request(username, password) post(data['hosts']['auth'] + '/login', { headers: { 'Content-Type' => 'application/json' }, body: { username: username, password: password } }) end # ... or we can actually run the request as part of the function call def login(username, password) resp = post(data['hosts']['auth'] + '/login', { headers: { 'Content-Type' => 'application/json' }, body: { username: username, password: password } }).expect { assert(code == 200) assert(body.is_a? Hash) assert(body.length > 0) assert(body.key?('token')) } # add this authorization header to all future requests add_header(:Authorization, "Bearer #{resp.body['token']}") resp end
true
3d908cbd033371fcc52f7a86fe4bd4450686374b
Ruby
Gary1690/ruby-oo-practice-relationships-domains-nyc01-seng-ft-051120
/app/models/actor.rb
UTF-8
446
3.421875
3
[]
no_license
class Actor @@all = [] attr_accessor :name def initialize(name) @name = name Actor.all << self end def characters Character.all.select{|x| x.actor == self} end def character_count self.characters.count end def self.most_characters self.all.max {|actor1,actor2| actor1.character_count <=> actor2.character_count} end def self.all @@all end end
true
1e253ad6ec119af09bc6153a82919f423b41ff46
Ruby
filipay/graphicKanagroo
/grid.rb
UTF-8
279
3.453125
3
[]
no_license
require_relative "point" class Grid attr_reader :dimension def initialize (dimension) @dimension = dimension - 1 end #Checks if a given point is outside def lies_outside? point x = point.x y = point.y x < 0 or x > @dimension or \ y < 0 or y > @dimension end end
true
981f0d2778a3474ca75c71cf6d04405eca98c9b2
Ruby
singhanilk1959/rpl
/library_intro_4/bk/x.rb
UTF-8
45
2.921875
3
[]
no_license
s = "hello world" # print s.chars.to_a
true
fa60c7fcf5a4036f326ddab817558bb9f7003206
Ruby
jfitisoff/marqeta-example
/spec/user_spec.rb
UTF-8
2,841
2.53125
3
[]
no_license
require_relative 'spec_helper' describe "/users" do before(:all) do if CREDS.keys.length < 3 || CREDS.values.any? { |v| v.blank? } raise "credentials.yml must be populated before running tests (see README.)" end @api = MarqetaCore.new( CREDS['base_url'], CREDS['app_token'], CREDS['access_token'] ) end let(:api) { @api } let(:user) { @api.users.post(FactoryBot.create(:user)) } let(:minimal_user) { @api.users.post(FactoryBot.create(:user, :minimal)) } context "GET" do it "gets an individual resource" do expect(api.users.get(user.token).status_code).to eq(200) end it "gets a collection" do arr = api.users.get expect(arr.length).to be > 1 end it "accepts a pagination count" do expect(api.users.get(count: 2).length).to eq(2) end it "accepts a start index for the query" do first = api.users.get.first second = api.users.get(start_index: 2).first expect(first.token).to_not eq(second.token) end xit "handles 'search_type' query parameter" do end it "limits fields returned when using 'fields' query parameter" do expect(user.get(fields: "last_name").attributes.first_name).to be_nil end it "sorts results by lastModifiedTime, descending" do x = api.users.get(sort_by: '-lastModifiedTime').map(&:last_modified_time) expect(x).to eq(x.sort.reverse) end it "sorts results by lastModifiedTime, ascending" do x = api.users.get(sort_by: 'lastModifiedTime').map(&:last_modified_time) expect(x).to eq(x.sort) end it "sorts results by createdTime, descending" do x = api.users.get(sort_by: '-createdTime').map(&:created_time) expect(x).to eq(x.sort.reverse) end it "sorts results by createdTime, ascending" do x = api.users.get(sort_by: 'lastName').map(&:created_time) expect(x).to eq(x.sort) end it "sorts results by lastName, descending (case insensitive)" do x = api.users.get(count: 50, sort_by: '-lastName') .map(&:last_name) .map(&:to_s) .map(&:downcase) expect(x).to eq(x.sort.reverse) end it "sorts results by lastName, ascending (case insensitive)" do x = api.users.get(count: 50, sort_by: 'lastName') .map(&:last_name) .map(&:to_s) .map(&:downcase) expect(x).to eq(x.sort) end end context "POST" do it "creates a user with minimal parameters" do expect(minimal_user.status_code).to eq(201) end it "creates a 'non-minimal' user" do expect(user.status_code).to eq(201) end it "raises an error when creating a user with name > 40 chars" do expect {api.users.post(first_name: 'a'*41) }.to raise_error(RestClient::BadRequest) end end end
true
a4e0d8fff46a88db5943fa9a115c84e4969fda89
Ruby
higginsmt/githug
/levels/reorder.rb
UTF-8
775
2.640625
3
[ "MIT" ]
permissive
difficulty 4 description "You have committed several times but in the wrong order. Please reorder your commits." setup do repo.init FileUtils.touch "README" repo.add "README" repo.commit_all "Initial Setup" FileUtils.touch "file1" repo.add "file1" repo.commit_all "First commit" FileUtils.touch "file3" repo.add "file3" repo.commit_all "Third commit" FileUtils.touch "file2" repo.add "file2" repo.commit_all "Second commit" end solution do return false unless repo.commits[2].message == "First commit" return false unless repo.commits[1].message == "Second commit" return false unless repo.commits[0].message == "Third commit" true end hint do puts "Take a look the `-i` flag of the rebase command." end
true
2b7fec4a69d6dacc886c42aa7e6280e449c1154f
Ruby
rhysd/TwitPrompt
/src/twit_prompt.rb
UTF-8
5,344
2.65625
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # encoding: utf-8 # Monkey patch to making String colorful class String # {{{ { dark_blue: "0;34", dark_green: "0;32", dark_cyan: "0;36", dark_red: "0;31", dark_purple: "0;35", dark_yellow: "0;33", red: "1;31", blue: "1;34", en: "1;32", cyan: "1;36", red: "1;31", purple: "1;35", yellow: "1;33", black: "0;30", dark_gray: "0;37", gray: "1;30", white: "1;37" }.each do |color,code| define_method(color) do "\e[#{code}m#{self}\e[0m" end end end # }}} # Name space of this application module TwitPrompt # {{{ # app's config module Config extend self # {{{ Root = File.expand_path('~')+'/.twit_prompt' Setting = Root+'/.twit_prompt_config.yml' Cache = "/tmp/timeline" ScreenName = "@Linda_pp" def check unless File.exist? Setting File.open(Setting, "w") do |file| file.print <<-EOS.gsub(/^\s+/, '') # get app keys at https://dev.twitter.com/ and write them consumer_key: YourConsumerKey consumer_secret: YourConsumerSecretKey oauth_token: YourOAuthToken oauth_token_secret: YourOAuthSecretToken EOS end STDERR.puts "Configuration-keys are not found." STDERR.puts "Write your consumer keys and OAuth keys to #{Setting}" open_editor end end def open_editor system 'bash', '-c', (ENV['EDITOR'] || 'vi')+' "$@"', '--', Setting end def config_twitter require 'twitter' require 'yaml' yaml = YAML.load(File.open(Setting).read) Twitter::Client.new( consumer_key: yaml['consumer_key'], consumer_secret: yaml['consumer_secret'], oauth_token: yaml['oauth_token'], oauth_token_secret: yaml['oauth_token_secret'] ) end private :config_twitter def client @client ||= config_twitter end end # }}} # maintain timeline cache class Timeline # {{{ def head # head of cached tweets # not implemented end def all # list of cached tweets # not implemented end def construct File.delete(Config::Cache) if File.exist?(Config::Cache) update end def ignore? status false end def update Config::check Process.daemon true,true # get timelines from the file twitter = Config::client last_update = File.exist?(Config::Cache) ? File.atime(Config::Cache) : Time.local(1900) File.open(Config::Cache,"w+") do |file| twitter.home_timeline.reverse_each do |status| break if status.created_at < last_update unless ignore? status user = status.user.screen_name text = status.text.gsub /\n/,' ' created_at = status.created_at file.puts created_at,user,text end end end end private :update, :ignore? end # }}} # Main module module Main extend self # {{{ @timeline = Timeline.new def reply?(text) text =~ /^#{@screen_name}/ end def mention?(text) text.include? @screen_name end def rt?(text) text =~ /^RT @[a-zA-Z0-9_]+: / end def build_tweet(user,text,created_at) user = "@#{user}: ".dark_cyan text = text.gsub /\n/,' ' text = text.include?(Config::ScreenName) ? text.dark_green : text # whether mention or not created_at = ' [' + Time.new(created_at).strftime("%m/%d %T") + ']' created_at = created_at.dark_yellow user + text + created_at end private :build_tweet, :reply?, :mention?, :rt? def init(options) @timeline.construct end def prompt(options) puts build_tweet("Linda_pp","aiueo @Linda_pp kakikukeko sasissuseso","2012-06-30 11:35:36 +0900") end def timeline(options) end def tweet(options,text) puts text puts "tweeted: #{text}" if options[:verbose] end def reply(options,text) puts "replied: #{text}" if options[:verbose] end def retweet(options) puts "retweeted: " if options[:verbose] end def fav(options) puts "faved: " if options[:verbose] end def config(options) Config::open_editor end end # }}} # Command line interface require 'thor' # {{{ class App < Thor private def self.def_command(name) define_method name do |*args| Main::__send__ name,options,*args end end def self.verbose_option method_option :verbose, :type => :boolean, :aliases => '-v', :default => true, :desc => 'output result' end public desc 'init', 'initialize timeline cache' def_command :init desc 'prompt', 'show a tweet for a shell prompt' def_command :prompt desc 'timeline', 'show timeline to stdout' def_command :timeline desc 'tweet [TEXT]', 'tweet TEXT' def_command :tweet desc 'reply [TEXT]', 'reply to last-displayed tweet' verbose_option def_command :reply desc 'retweet', 'retweet last-displayed tweet' verbose_option def_command :retweet desc 'fav', 'add last-desplayed tweet to favorite tweets' verbose_option def_command :fav desc 'config', 'configure YAML setting file' def_command :config end # }}} end # module TwitPrompt }}} # # main # if __FILE__ == $0 then TwitPrompt::App.start end
true
e7adeab81fd69bb4526d0124983d762f23a51a2c
Ruby
vinodmunagala/seat_availablity
/lib/best_seats/finder.rb
UTF-8
2,190
3.25
3
[]
no_license
require "forwardable" require "ostruct" require "best_seats/matrix" require "best_seats/best_seat_index_finder" require "best_seats/seat_group" require "best_seats/venue" module BestSeats class Finder extend Forwardable DEFAULT_OPTIONS = { matrix_builder: BestSeats::Matrix, index_finder: BestSeats::BestSeatIndexFinder, venue_builder: BestSeats::Venue, seat_group: BestSeats::SeatGroup }.freeze INITIAL_SEAT_INDEX = 0 attr_reader :input, :seats_requested def_delegators :venue, :rows, :columns, :seats def_delegators :options, :matrix_builder, :index_finder, :venue_builder, :seat_group def initialize(input, seats_requested, options = {}) @input = input @seats_requested = seats_requested @options = DEFAULT_OPTIONS.merge(options) end def all selected_seats = [] available_seats_matrix.each do |line| next if insuficient_seats?(line.size) sorted_seats = selected_seats.sort return sorted_seats if all_seats_found?(sorted_seats) selected_seats = [] (INITIAL_SEAT_INDEX...seats_requested).each do |seat| index = index_to_remove(line.size) value = line.delete_at(index) selected_seats << value end end selected_seats.sort end private def available_seats_matrix @_available_seats_matrix ||= matrix_builder.new( rows, columns, seats ).available end def insuficient_seats?(total) total < seats_requested end def all_seats_found?(selected_seats) enough_selected?(selected_seats.size) && consecutive_values?(selected_seats) end def enough_selected?(selected_count) selected_count == seats_requested end def consecutive_values?(seats) seat_group.new( seats.sort ).consecutive_values? end def index_to_remove(collection_size) index_finder.new(collection_size).call end def venue @_venue ||= venue_builder.new(input) end def options @_options ||= OpenStruct.new(@options) end end end
true
32f50755a69248b3456330a03f5910d0f001d6a9
Ruby
mateuszalmannai/dmtk
/spec/models/tool_spec.rb
UTF-8
372
3.078125
3
[]
no_license
describe "A tool" do it "is free if the price is $0" do tool = Tool.new(price: 0) expect(tool.free?).to eq(true) end it "is not free if the price is non-$0" do tool = Tool.new(price: 10.00) expect(tool.free?).to eq(false) end it "is free if the price is blank" do tool = Tool.new(price: nil) expect(tool.free?).to eq(true) end end
true
aef48e9312cfa76a5832fe659233fdefa5e6d89c
Ruby
cdimartino/schedulizr
/app/models/schedule.rb
UTF-8
968
2.6875
3
[]
no_license
class Schedule < ActiveRecord::Base has_many :activities validates :schedule_date, uniqueness: true, presence: true def display_date format='%A, %B %d, %Y' schedule_date.strftime(format) end def ordered_activities activities.order('start_time asc, end_time asc') end def deep_clone date dup.tap do |me| me.activities = activities.map { |a| a.dup.tap { |copy| copy.schedule_id = nil } } me.schedule_date = date end end def slug schedule_date.strftime('%Y-%m-%d') end class << self def upcoming where(schedule_date: [3.days.ago .. Time.now + 7.days]).order(:schedule_date) end def around where(schedule_date: [14.days.ago .. Time.now + 14.days]).order(:schedule_date) end def today find_by(schedule_date: Date.today) end def between start_date, end_date where(schedule_date: [start_date .. end_date]).includes(:activities) end end end
true