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 |
---|---|---|---|---|---|---|---|---|---|---|---|
30173c6299e7cb979529ff5b0159b721f7d9d582
|
Ruby
|
elanthia-online/urnon
|
/lib/urnon/util/synchronized-socket.rb
|
UTF-8
| 409 | 2.875 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
class SynchronizedSocket
def initialize(o)
@delegate = o
@mutex = Mutex.new
self
end
def puts(*args, &block)
@mutex.synchronize {
@delegate.puts *args, &block
}
end
def write(*args, &block)
@mutex.synchronize {
@delegate.write *args, &block
}
end
def method_missing(method, *args, &block)
@delegate.__send__ method, *args, &block
end
end
| true |
6f9bf7fbb0ed6af61bb7a9f6fa008298adf28ef4
|
Ruby
|
fbenton93/guessing-cli-nyc-web-080618
|
/guessing_cli.rb
|
UTF-8
| 433 | 3.796875 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def run_guessing_game
number = rand(1..6)
response = nil
while true
puts "Guess a number between 1 and 6."
user_input = gets.chomp
if user_input == "exit"
puts "Goodbye!"
break
elsif user_input.to_i == number
response = true
else
response = false
end
end
if response == true
puts "You guessed the correct number!"
else
puts "The computer guessed #{5}."
end
end
| true |
dff1cb73d329b8e20089a3ba1d2b12c479b48895
|
Ruby
|
JustinTArthur/engineyard-serverside
|
/lib/vendor/dataflow/spec/by_need_spec.rb
|
UTF-8
| 1,405 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
require "#{File.dirname(__FILE__)}/spec_helper"
describe 'A by_need expression' do
describe 'when a method is called on it' do
it 'binds its variable' do
local do |x, y, z|
Thread.new { unify y, by_need { 4 } }
Thread.new { unify z, x + y }
Thread.new { unify x, by_need { 3 } }
z.should == 7
end
end
end
describe 'when a bound variable is unified to it' do
it 'passes unififcation for equal values' do
local do |x|
unify x, by_need { 1 }
unify x, 1
x.should == 1
y = by_need { 1 }
unify y, 1
y.should == 1
end
end
it 'fails unififcation for unequal values' do
local do |x|
unify x, by_need { 1 }
lambda { unify x, 2 }.should raise_error(Dataflow::UnificationError)
y = by_need { 1 }
lambda { unify y, 2 }.should raise_error(Dataflow::UnificationError)
end
end
describe 'when it is unified to a bound variable' do
it 'passes unififcation for equal values' do
local do |x|
unify x, 1
unify x, by_need { 1 }
x.should == 1
end
end
it 'fails unification for unequal values' do
local do |x|
unify x, 1
lambda { unify x, by_need { 2 } }.should raise_error(Dataflow::UnificationError)
end
end
end
end
end
| true |
d408b8d94bfd0fb13a159b647e5cdaf24f2bcd02
|
Ruby
|
mgreg90/Gilded-Rose-Ruby
|
/lib/gilded_rose.rb
|
UTF-8
| 362 | 3.015625 | 3 |
[] |
no_license
|
require 'pry'
require_relative 'gilded_rose/item'
class GildedRose
attr_accessor :item
def initialize(name:, days_remaining:, quality:)
@item = Item.create(name, days_remaining, quality)
end
def tick
item.tick
end
def name
item.name
end
def days_remaining
item.days_remaining
end
def quality
item.quality
end
end
| true |
5118d1e7d42e54f6eaf28d81603484c4cb59e281
|
Ruby
|
avni510/time_logger
|
/spec/console/console_ui_spec.rb
|
UTF-8
| 11,934 | 2.640625 | 3 |
[] |
no_license
|
require "spec_helper"
module TimeLogger
module Console
describe ConsoleUI do
let(:mock_io_wrapper) { double }
let(:console_ui) { ConsoleUI.new(mock_io_wrapper) }
describe ".puts_space" do
it "displays a space" do
expect(mock_io_wrapper).to receive(:puts_string).with("")
console_ui.puts_space
end
end
describe ".get_user_input" do
it "prompts the user for input" do
expect(mock_io_wrapper).to receive(:get_action).exactly(1).times
console_ui.get_user_input
end
end
describe ".username_display_message" do
it "asks the user for their username" do
expect(mock_io_wrapper).to receive(:puts_string).with("Please enter your username")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.username_display_message
end
end
describe ".username_does_not_exist_message" do
context "the username entered does not exist in the data" do
it "displays the a message that it does not exist" do
expect(mock_io_wrapper).to receive(:puts_string).with("This username does not exist")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.username_does_not_exist_message
end
end
end
describe ".enter_new_username_message" do
context "an admin selects the option to create a new user" do
it "displays a message to enter the new username" do
expect(mock_io_wrapper).to receive(:puts_string).with("Please enter the username you would like to create")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.enter_new_username_message
end
end
end
describe ".create_admin_message" do
context "an admin creates a new user" do
it "displays a message to ask the user if they would like the new user to be an admin or not" do
expect(mock_io_wrapper).to receive(:puts_string).with("Would you like the user to be an admin?")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.create_admin_message
end
end
end
describe ".no_company_log_entries_message" do
context "an admin runs a report and there are no log entries" do
it "displays a message that there no log entries" do
expect(mock_io_wrapper).to receive(:puts_string).with("The company doesn't have any log entries for the current month")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.no_company_log_entries_message
end
end
end
describe ".no_company_timecode_hours" do
context "an admin runs a report and there are no log times with timecodes" do
it "displays a message that there no hours logged for the timecodes" do
expect(mock_io_wrapper).to receive(:puts_string).with("There are no hours logged for the timecodes")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.no_company_timecode_hours
end
end
end
describe ".no_client_hours" do
context "an admin runs a report and there are no log times for clients" do
it "displays a message that there no hours logged clients" do
expect(mock_io_wrapper).to receive(:puts_string).with("There are no hours logged clients")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.no_client_hours
end
end
end
describe ".invalid_client_selection_message" do
context "the user selects a client not on the list" do
it "displays a message to enter a valid client" do
expect(mock_io_wrapper).to receive(:puts_string).with("Please enter a client number from the list")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.invalid_client_selection_message
end
end
end
describe ".no_clients_message" do
context "there are no clients in memory" do
it "displays a message to select a different timecode" do
expect(mock_io_wrapper).to receive(:puts_string).with("There are no clients")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.no_clients_message
end
end
end
describe ".new_client_name_message" do
it "displays a message to enter the name of a client" do
expect(mock_io_wrapper).to receive(:puts_string).with("Please enter the new client's name")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.new_client_name_message
end
end
describe ".no_log_times_message" do
context "there are no log times for a give user" do
it "displays a message to the user that there are no log times" do
expect(mock_io_wrapper).to receive(:puts_string).with("You do not have any log times for this month")
expect(console_ui).to receive(:puts_space).exactly(2).times
console_ui.no_log_times_message
end
end
end
describe ".menu_selection_message" do
it "displays a message to the user to select an option from the menu" do
expect(mock_io_wrapper).to receive(:puts_string).with("Please select an option")
expect(console_ui).to receive(:puts_space).exactly(3).times
expect(mock_io_wrapper).to receive(:puts_string).with("Enter the number next to the choice")
console_ui.menu_selection_message
end
end
describe ".display_menu_options" do
it "displays the menu options" do
expect(mock_io_wrapper).to receive(:puts_string).with("Please select an option from below")
employee_menu_options =
{
"1" => "1. Do you want to log your time?",
"2" => "2. Do you want to run a report for the current month?"
}
expect(mock_io_wrapper).to receive(:puts_string).exactly(2).times
expect(console_ui).to receive(:puts_space)
console_ui.display_menu_options(employee_menu_options)
end
end
describe ".date_log_time_message" do
it "displays a message to the user to enter the date to log time for" do
expect(console_ui).to receive(:puts_space)
expect(mock_io_wrapper).to receive(:puts_string).with("Date (MM-DD-YYYY)")
expect(console_ui).to receive(:get_user_input)
console_ui.date_log_time_message
end
end
describe ".hours_log_time_message" do
it "displays a message to the user to enter the hours worked" do
expect(console_ui).to receive(:puts_space)
expect(mock_io_wrapper).to receive(:puts_string).with("Hours Worked")
expect(console_ui).to receive(:get_user_input)
console_ui.hours_log_time_message
end
end
describe ".timecode_log_time_message" do
it "displays a message to the user to enter their timecode" do
expect(console_ui).to receive(:puts_space).exactly(2).times
timecode_hash = {
"1" => "1. Billable Work",
"2" => "2. Non-Billable Work",
"3" => "3. PTO"
}
expect(console_ui).to receive(:display_menu_options).with(timecode_hash)
expect(console_ui).to receive(:get_user_input)
console_ui.timecode_log_time_message(timecode_hash)
end
end
describe ".format_employee_report" do
it "returns a report for the employee" do
log_times_sorted = [
[ "09-02-2016", "7", "Billable", "Microsoft" ],
[ "09-04-2016", "5", "Billable", "Microsoft" ],
[ "09-06-2016", "6", "Non-Billable", nil ],
[ "09-07-2016","10", "Billable", "Google" ],
[ "09-08-2016", "5", "PTO", nil ]
]
expect(mock_io_wrapper).to receive(:puts_string).with("This is a report for the current month")
expect(console_ui).to receive(:puts_space).exactly(5).times
expect(mock_io_wrapper).to receive(:puts_string).with("Date" + " " + "Hours Worked" + " " + "Timecode" + " " + "Client")
expect(mock_io_wrapper).to receive(:puts_string).with("09-02-2016" + " " + "7" + " " + "Billable" + " " + "Microsoft")
expect(mock_io_wrapper).to receive(:puts_string).with("09-04-2016" + " " + "5" + " " + "Billable" + " " + "Microsoft")
expect(mock_io_wrapper).to receive(:puts_string).with("09-06-2016" + " " + "6" + " " + "Non-Billable")
expect(mock_io_wrapper).to receive(:puts_string).with("09-07-2016" + " " + "10" + " " + "Billable" + " " + "Google")
expect(mock_io_wrapper).to receive(:puts_string).with("09-08-2016" + " " + "5" + " " + "PTO")
total_hours_worked_per_client = { "Google": "10", "Microsoft": "12" }
expect(mock_io_wrapper).to receive(:puts_string).with("Total hours worked for Google" + " : " + "10")
expect(mock_io_wrapper).to receive(:puts_string).with("Total hours worked for Microsoft" + " : " + "12")
total_hours_worked_per_timecode = { "Billable": "22", "Non-Billable": "6", "PTO": "5" }
expect(mock_io_wrapper).to receive(:puts_string).with("Total Billable hours worked" + " : " + "22")
expect(mock_io_wrapper).to receive(:puts_string).with("Total Non-Billable hours worked" + " : " + "6")
expect(mock_io_wrapper).to receive(:puts_string).with("Total PTO hours worked" + " : " + "5")
console_ui.format_employee_report(log_times_sorted, total_hours_worked_per_client, total_hours_worked_per_timecode)
end
end
describe ".format_admin_report" do
it "returns an admin report" do
expect(mock_io_wrapper).to receive(:puts_string).with("This is a report for the current month")
expect(console_ui).to receive(:puts_space).exactly(3).times
timecode_hash =
{
"Billable" => 7,
"PTO" => 5
}
client_hash =
{
"Microsoft" => 4,
"Google" => 6
}
expect(mock_io_wrapper).to receive(:puts_string).with("Company total Billable hours: 7")
expect(mock_io_wrapper).to receive(:puts_string).with("Company total PTO hours: 5")
expect(mock_io_wrapper).to receive(:puts_string).with("Company total hours for Microsoft: 4")
expect(mock_io_wrapper).to receive(:puts_string).with("Company total hours for Google: 6")
console_ui.format_admin_report(timecode_hash, client_hash)
end
context "there are no clients" do
it "returns an admin report" do
expect(mock_io_wrapper).to receive(:puts_string).with("This is a report for the current month")
expect(console_ui).to receive(:puts_space).exactly(3).times
timecode_hash =
{
"Billable" => 7,
"PTO" => 5
}
expect(mock_io_wrapper).to receive(:puts_string).with("Company total Billable hours: 7")
expect(mock_io_wrapper).to receive(:puts_string).with("Company total PTO hours: 5")
expect(console_ui).to receive(:no_client_hours)
console_ui.format_admin_report(timecode_hash, nil)
end
end
end
end
end
end
| true |
66a0b877402772db0d0e48828a341fe88016315b
|
Ruby
|
amree/tueetion
|
/app/models/payment.rb
|
UTF-8
| 1,013 | 2.703125 | 3 |
[] |
no_license
|
class Payment < ActiveRecord::Base
belongs_to :bill
belongs_to :user
validates :paid_at, presence: true
validates :amount, presence: true
validates :amount, numericality: true
validate :less_than_bill_balance, if: "amount.present? && amount >= 0"
validate :paid_at_should_not_be_from_the_future, if: "paid_at.present?"
after_create :update_bill_paid_status
after_destroy :update_bill_paid_status
protected
def less_than_bill_balance
if self.amount > (self.bill.total_amount - self.bill.total_amount_paid)
errors.add(:amount, "The amount should not be more than the bill's balance")
end
end
def update_bill_paid_status
if self.bill.total_amount_paid == self.bill.total_amount
self.bill.is_paid = true
self.bill.save
else
self.bill.is_paid = false
self.bill.save
end
end
def paid_at_should_not_be_from_the_future
if Time.zone.now < self.paid_at
errors.add(:paid_at, "Should not be from the future")
end
end
end
| true |
6346f5de203248ea7983ea5e6ce008a0774f3641
|
Ruby
|
meh/ruby-cmus
|
/bin/cmus-remote.rb
|
UTF-8
| 2,749 | 2.609375 | 3 |
[] |
no_license
|
#! /usr/bin/env ruby
require 'cmus'
require 'optparse'
options = {}
OptionParser.new do |o|
o.on '--server SOCKET', 'connect using SOCKET instead of ~/.cmus/socket' do |value|
options[:server] = value
end
o.on '--version', 'display version information and exit' do
puts "cmus-remote.rb for #{Cmus.version}"
exit
end
o.on '-p', '--play', 'start playing' do
options[:player] = :play
end
o.on '-u', '--pause', 'toggle pause' do
options[:player] = :pause
end
o.on '-s', '--stop', 'stop playing' do
options[:player] = :stop
end
o.on '-n', '--next', 'skip forward in playlist' do
options[:player] = :next
end
o.on '-r', '--prev', 'skip backward in playlist' do
options[:player] = :prev
end
o.on '-v', '--volume VOL', 'changes volume' do |value|
options[:player] = :volume
options[:value] = value
end
o.on '-k', '--seek SEEK', 'seek' do |value|
options[:player] = :seek
options[:value] = value
end
o.on '-R', '--repeat', 'toggle repeat' do
options[:toggle] = :repeat
end
o.on '-S', '--shuffle', 'toggle shuffle' do
options[:toggle] = :shuffle
end
o.on '-Q', 'get player status information' do
options[:status] = true
end
o.on '-l', '--library', 'modify library instead of playlist' do
options[:library] = true
end
o.on '-P', '--playlist', 'modify playlist (default)' do
options[:playlist] = true
end
o.on '-q', '--queue', 'modify play queue instead of playlist' do
options[:queue] = true
end
o.on '-c', '--clear', 'clear playlist, library (-l) or play queue (-q)' do
options[:clear] = true
end
o.on '-C', '--raw', 'treat arguments (instead of stdin) as raw commands' do
options[:raw]
end
end.parse!
controller = options[:server] ? Cmus::Controller.new(options[:server]) : Cmus::Controller.new
if options[:clear]
controller.clear(options[:queue] ? :queue : options[:library] ? :library : :playlist)
end
if options[:player]
controller.player.__send__ *[options[:player], options[:value]].compact
end
if options[:toggle]
controller.toggle.__send__ options[:toggle]
end
if options[:status]
controller.status.tap {|status|
puts "status #{status.to_sym}"
puts "file #{status.path}" if status.path
puts "duration #{status.song.duration}" if status.song.duration
puts "position #{status.song.position}" if status.song.position
status.song.tags.marshal_dump.each {|name, value|
puts "tag #{name} #{value}"
}
status.settings.marshal_dump.each {|name, value|
puts "set #{name} #{value}"
}
}
end
if options[:raw]
ARGV.each {|command|
controller.send command
}
while line = controller.readline
puts line
end
else
ARGV.each {|path|
controller.add(options[:queue] ? :queue : options[:library] ? :library : :playlist, path)
}
end
| true |
f2ba2cda0582fafed0ceb8fd6b539f79da1fd55d
|
Ruby
|
gwenh11/LS_core
|
/ruby_exercises/120/easy_2/10_nobility.rb
|
UTF-8
| 3,276 | 4.34375 | 4 |
[] |
no_license
|
=begin
Now that we have a Walkable module, we are given a new challenge.
Apparently some of our users are nobility, and the regular way
of walking simply isn't good enough. Nobility need to strut.
We need a new class Noble that shows the title and name when walk is called:
byron = Noble.new("Byron", "Lord")
p byron.walk
# => "Lord Byron struts forward"
We must have access to both name and title because they are needed
for other purposes that we aren't showing here.
byron.name
=> "Byron"
byron.title
=> "Lord"
=end
module Walkable
def walk
"#{self} #{gait} forward"
end
end
class Person
attr_reader :name
include Walkable
def initialize(name)
@name = name
end
def to_s
name
end
private
def gait
"strolls"
end
end
class Cat
attr_reader :name
include Walkable
def initialize(name)
@name = name
end
def to_s
name
end
private
def gait
"saunters"
end
end
class Cheetah
attr_reader :name
include Walkable
def initialize(name)
@name = name
end
def to_s
name
end
private
def gait
"runs"
end
end
class Noble
attr_reader :name, :title
include Walkable
def initialize(name, title)
@title = title
@name = name
end
def to_s
"#{title} #{name}"
end
private
def gait
"struts"
end
end
byron = Noble.new("Byron", "Lord")
p byron.walk
# => "Lord Byron struts forward"
=begin
Before we can do anything, we must first decide how we are going to approach this problem. As suggested in the Approach/Algorithm section, the easiest approach involves providing a method that returns the name and title for Nobles, and just the name for regular Persons, Cats, and Cheetahs. A reasonable way to do this is to define an appropriate #to_s method for all 4 classes, and then change Walkable#walk so it calls #to_s on the object.
So, this is exactly what we do. We define #to_s in all 4 classes, returning just the name in 3 classes, and returning both the title and name in the Noble class. Finally, we tell Walkable#walk to use #to_s to obtain the person's name (or name and title).
Wait just one minute. How are we doing that? There's no mention of #to_s in Walkable#walk, is there? Actually, there is - it's just hidden. When you perform interpolation on some value in a string, ruby automatically calls #to_s for you. So, #{self} in the string is actually #{self.to_s} in disguise. In the case of a Cat object, this calls Cat#to_s, but in the case of a Noble, it calls Noble#to_s.
=end
=begin
Further Exploration
This exercise can be solved in a similar manner by using inheritance; a Noble is a Person, and a Cheetah is a Cat, and both Persons and Cats are Animals. What changes would you need to make to this program to establish these relationships and eliminate the two duplicated #to_s methods?
Is to_s the best way to provide the name and title functionality we needed for this exercise? Might it be better to create either a different name method (or say a new full_name method) that automatically accesses @title and @name? There are tradeoffs with each choice -- they are worth considering.
=end
| true |
dd45b423d7477ee405c5ddcc011cbfafc54ffb88
|
Ruby
|
SephoraM/LS-ruby-basics
|
/variable_scope/ex111.rb
|
UTF-8
| 335 | 3.859375 | 4 |
[] |
no_license
|
# What will the following code print, and why?
a = 7
array = [1, 2, 3]
def my_value(ary)
ary.each do |b|
a += b
end
end
my_value(array)
puts a
#=> an error because you can't use the += method on an uninitialized variable
# because that variable would have a nil value and += is not a method that
# is available to nil.
| true |
acc8cd0e1ad169e3e68a0a8ab6dc4a78701d49eb
|
Ruby
|
patrickmult/ruby_sandbox
|
/drills/the_hard_way/ex09.rb
|
UTF-8
| 247 | 3.203125 | 3 |
[] |
no_license
|
days = "Mon Tue Wed Thu Fri Sat Sun"
months = "Jan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
puts "Here are the days: #{days}"
puts "Here are the months: #{months}"
puts """
Inside three double quotes
We type as many new lines as we like.
Line 3
"""
| true |
f3659c6ca2ea4d07ec539273ccfbcbdc19c8db81
|
Ruby
|
vecchp/sevenlanguages
|
/Ruby/Day 1/day1.rb
|
UTF-8
| 227 | 3.859375 | 4 |
[] |
no_license
|
# Print String Hello World
puts 'Hello World'
# Index of Ruby
'Hello, Ruby'.index('Ruby')
# Print name 10 Times
(0..9).each{|x| puts "Paul"}
# Print Sentence from 1 to 10
(1..10).each{|x| puts "This is sentence number #{x}"}
| true |
90e0f586663c78403021e20b78fea98f82989d3e
|
Ruby
|
emezac/Temperature
|
/TemperatureModel.rb
|
UTF-8
| 708 | 3.421875 | 3 |
[] |
no_license
|
class TemperatureModel
def initialize
@listeners = []
end
def add_listener(listener)
@listeners << listener
end
def upF(temp)
@temp = temp
@temp += 1
@listeners.each {|l| l.faranheit_changer(@temp) }
end
def downF(temp)
@temp = temp
@temp -= 1
@listeners.each {|l| l.faranheit_changer(@temp) }
end
def upC(temp)
@temp = temp
@temp += 1
@listeners.each {|l| l.celsius_changer(@temp) }
end
def downC(temp)
@temp = temp
@temp -= 1
@listeners.each {|l| l.celsius_changer(@temp) }
end
def newtC(temp)
@temp = temp
@listeners.each {|l| l.celsius_changer(@temp) }
end
end
| true |
0748ba8a2639f3670f57de611e409d62bd5e5baa
|
Ruby
|
BrentonEarl/Generate-slack-required
|
/lib/slack-required.rb
|
UTF-8
| 2,122 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'find'
class SlackRequired
def initialize(configuration_file)
@repository = IO.readlines(configuration_file)[1].strip!
@includedFileExtensions = IO.readlines(configuration_file)[3].chomp.split(",")
@excludedFileNames = IO.readlines(configuration_file)[5].chomp.split(",")
@excludedDirectories = IO.readlines(configuration_file)[7].chomp.split(",")
@requires_regex = /REQUIRES\=\".*\"/
end
attr_reader :repository, :includedFileExtensions, :excludedFileNames, :exludedDirectories, :requires_regex
def CorrectFile
@infofile
end
def SlackRequiredFile
@slack_required
end
def CreateSlackRequired
@createSlackRequired = File.open(@slack_required, "w").close()
end
def EmptySlackRequired
@emptySlackRequired = File.truncate(@slack_required, 0)
end
def DestroySlackRequired
@destroySlackRequired = File.delete(@slack_required)
end
def SearchandWrite
Find.find(@repository) do |path|
if FileTest.directory?(path)
# Black list exludes
if @excludedFileNames.include?(File.basename(path.downcase))
Find.prune
elsif @excludedDirectories.include?(File.basename(path.downcase))
Find.prune
else
next
end
else
filetype = File.basename(path.downcase).split(".").last
if @includedFileExtensions.include?(filetype)
@infofile = File.absolute_path(path)
@infofile_dir = File.dirname(@infofile)
@slack_required = @infofile_dir + "/" + "slack-required"
# Not so good. Reads whole files into memory, resource hog
#@read_infofile = File.readlines(@infofile)
#@matches = @read_infofile.select { |requires| requires[@requires_regex] }
# Reads regex line from each file one at a time and writes out
# Better with resources
File.open(@infofile).each do |requires|
@matches = @requires_regex.match(requires)
f = File.new(@slack_required, "w")
f.write(@matches)
end
end
end
end
end
end
| true |
39c40202045828e9749952597ec9a83f30dc7ec3
|
Ruby
|
igorsimdyanov/gb
|
/part2/lesson3/yield_self.rb
|
UTF-8
| 162 | 3.109375 | 3 |
[] |
no_license
|
hello = 'Hello, %s!'.yield_self do |str|
print 'Пожалуйста, введите имя '
format(str, gets.chomp)
end
puts hello
| true |
9d1d115946505f01ba8c438b542415ae2e118bcb
|
Ruby
|
yurifrl/curly
|
/lib/curly/compiler.rb
|
UTF-8
| 5,165 | 3.109375 | 3 |
[
"Apache-2.0"
] |
permissive
|
require 'curly/scanner'
require 'curly/component_compiler'
require 'curly/component_parser'
require 'curly/error'
require 'curly/invalid_component'
require 'curly/incorrect_ending_error'
require 'curly/incomplete_block_error'
module Curly
# Compiles Curly templates into executable Ruby code.
#
# A template must be accompanied by a presenter class. This class defines the
# components that are valid within the template.
#
class Compiler
# Compiles a Curly template to Ruby code.
#
# template - The template String that should be compiled.
# presenter_class - The presenter Class.
#
# Raises InvalidComponent if the template contains a component that is not
# allowed.
# Raises IncorrectEndingError if a conditional block is not ended in the
# correct order - the most recent block must be ended first.
# Raises IncompleteBlockError if a block is not completed.
# Returns a String containing the Ruby code.
def self.compile(template, presenter_class)
new(template, presenter_class).compile
end
# Whether the Curly template is valid. This includes whether all
# components are available on the presenter class.
#
# template - The template String that should be validated.
# presenter_class - The presenter Class.
#
# Returns true if the template is valid, false otherwise.
def self.valid?(template, presenter_class)
compile(template, presenter_class)
true
rescue Error
false
end
attr_reader :template
def initialize(template, presenter_class)
@template = template
@presenter_classes = [presenter_class]
end
def compile
if presenter_class.nil?
raise ArgumentError, "presenter class cannot be nil"
end
tokens = Scanner.scan(template)
@blocks = []
parts = tokens.map do |type, value|
send("compile_#{type}", value)
end
if @blocks.any?
raise IncompleteBlockError.new(@blocks.pop)
end
<<-RUBY
buffer = ActiveSupport::SafeBuffer.new
presenters = []
#{parts.join("\n")}
buffer
RUBY
end
private
def presenter_class
@presenter_classes.last
end
def compile_conditional_block_start(component)
compile_conditional_block "if", component
end
def compile_inverse_conditional_block_start(component)
compile_conditional_block "unless", component
end
def compile_collection_block_start(component)
name, identifier, attributes = ComponentParser.parse(component)
method_call = ComponentCompiler.compile_component(presenter_class, name, identifier, attributes)
as = name.singularize
counter = "#{as}_counter"
begin
item_presenter_class = presenter_class.presenter_for_name(as)
rescue NameError
raise Curly::Error,
"cannot enumerate `#{component}`, could not find matching presenter class"
end
push_block(name, identifier)
@presenter_classes.push(item_presenter_class)
<<-RUBY
presenters << presenter
items = Array(#{method_call})
items.each_with_index do |item, index|
item_options = options.merge(:#{as} => item, :#{counter} => index + 1)
presenter = #{item_presenter_class}.new(self, item_options)
RUBY
end
def compile_conditional_block(keyword, component)
name, identifier, attributes = ComponentParser.parse(component)
method_call = ComponentCompiler.compile_conditional(presenter_class, name, identifier, attributes)
push_block(name, identifier)
<<-RUBY
#{keyword} #{method_call}
RUBY
end
def compile_conditional_block_end(component)
validate_block_end(component)
<<-RUBY
end
RUBY
end
def compile_collection_block_end(component)
@presenter_classes.pop
validate_block_end(component)
<<-RUBY
end
presenter = presenters.pop
RUBY
end
def compile_component(component)
# begin
# name, identifier, attributes = ComponentParser.parse(component)
# rescue Exception => e
# return ''
# end
name, identifier, attributes = ComponentParser.parse(component)
method_call = ComponentCompiler.compile_component(presenter_class, name, identifier, attributes)
code = "#{method_call} {|*args| yield(*args) }"
"buffer.concat(#{code.strip}.to_s)"
end
def compile_text(text)
"buffer.safe_concat(#{text.inspect})"
end
def compile_comment(comment)
"" # Replace the content with an empty string.
end
def validate_block_end(component)
name, identifier, attributes = ComponentParser.parse(component)
last_block = @blocks.pop
if last_block.nil?
raise Curly::Error, "block ending not expected"
end
unless last_block == [name, identifier]
raise Curly::IncorrectEndingError.new([name, identifier], last_block)
end
end
def push_block(name, identifier)
@blocks.push([name, identifier])
end
end
end
| true |
af00e2615974169e9241ef78fbfb623fa3cce14d
|
Ruby
|
chad/rubinius
|
/lib/rbyaml/util.rb
|
UTF-8
| 363 | 3 | 3 |
[
"MIT"
] |
permissive
|
class Object
def __is_str; false end
def __is_sym; false end
def __is_a; false end
def __is_int; false end
end
class String
def __is_str; true end
end
class Symbol
def __is_sym; true end
end
class Array
def __is_a; true end
end
class Integer
def __is_int; true end
end
class Fixnum
def __is_ascii_num
self <= ?9 && self >= ?0
end
end
| true |
813dc9ff03ef1aac4fb866e1857349e6bea3b8da
|
Ruby
|
jerrifel/ruby_book
|
/methods/exercise_5.rb
|
UTF-8
| 145 | 3.703125 | 4 |
[] |
no_license
|
#exercise_5.rb
def scream(words)
words = words + "!!!!"
return puts words
end
scream("Yippeee")
# what does it return now? => returns nil
| true |
725c8a3a83ebaad3ce5b8adf46540babfd503f2c
|
Ruby
|
teddythetwig/origin-server
|
/controller/app/controllers/members_controller.rb
|
UTF-8
| 7,941 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
class MembersController < BaseController
def index
render_success(:ok, "members", members.map{ |m| get_rest_member(m) }, "Found #{pluralize(members.length, 'member')}.")
end
def create
authorize! :change_members, membership
errors = []
warnings = []
singular = params[:members].nil?
ids, logins = {}, {}
# Find input members
members_params = (params[:members] || [params[:member]].compact.presence || [params.slice(:id, :login, :role)]).compact
members_params.each_with_index do |m, i|
errors << Message.new(:error, "You must provide a member with an id and role.", 1, nil, i) and next unless m.is_a? Hash
role = Role.for(m[:role]) || (m[:role] == 'none' and :none)
errors << Message.new(:error, "You must provide a role for each member - you can add or update (with #{Role.all.map{ |s| "'#{s}'" }.join(', ')}) or remove (with 'none').", 1, :role, i) and next unless role
if m[:id].present?
ids[m[:id].to_s] = [role, i]
elsif m[:login].present?
logins[m[:login].to_s] = [role, i]
else
errors << Message.new(:error, "Each member being changed must have an id or a login.", 1, nil, i)
end
end
if errors.present?
Rails.logger.error errors
return render_error(:bad_request, errors.first.text, nil, nil, nil, errors) if singular
return render_error(:bad_request, "The provided members are not valid.", nil, nil, nil, errors)
end
return render_error(:unprocessable_entity, "You must provide at least a single member that exists.") unless ids.present? || logins.present?
# Perform lookups of users by login and create members for new roles
new_members = changed_members_for(ids, logins, errors)
remove = removed_ids(ids, logins, errors)
if errors.present?
return render_error(:not_found, errors.first.text, nil, nil, nil, errors) if singular
return render_error(:not_found, "Not all provided members exist.", nil, nil, nil, errors)
end
# Warn about partial inputs
invalid_members = []
remove.delete_if do |id, pretty|
unless membership.member_ids.detect{ |m| m === id }
invalid_members << pretty
end
end
if invalid_members.present?
msg = "#{invalid_members.to_sentence} #{invalid_members.length > 1 ? "are not members" : "is not a member"} and cannot be removed."
return render_error(:bad_request, msg) if singular
warnings << Message.new(:warning, msg, 1, nil)
end
count_remove = remove.count
count_update = (membership.member_ids & new_members.map(&:id)).count
count_add = new_members.count - count_update
membership.remove_members(remove.keys)
membership.add_members(new_members)
if save_membership(membership)
msg = [
("added #{pluralize(count_add, 'member')}" if count_add > 0),
("updated #{pluralize(count_update, 'member')}" if count_update > 0),
("removed #{pluralize(count_remove, 'member')}" if count_remove > 0),
("ignored #{pluralize(invalid_members.length, 'missing member')} (#{invalid_members.join(', ')})" if invalid_members.present?),
].compact.join(", ").humanize + '.'
if (count_add + count_update == 1) and (count_remove == 0) and (member = members.detect{|m| m._id == new_members.first._id })
render_success(:ok, "member", get_rest_member(member), msg, nil, warnings)
else
render_success(:ok, "members", members.map{ |m| get_rest_member(m) }, msg, nil, warnings)
end
else
render_error(:unprocessable_entity, "The members could not be added due to validation errors.", nil, nil, nil, get_error_messages(membership))
end
end
def destroy
authorize! :change_members, membership
remove_member(params[:id])
end
def destroy_all
authorize! :change_members, membership
ids, logins = [], []
(params[:members].presence || [params[:member].presence] || []).compact.each do |m|
if m.is_a?(Hash)
if m[:id].present?
ids << m[:id].to_s
elsif m[:login].present?
logins << m[:login].to_s
else
return render_error(:unprocessable_entity, "Each member must have an id or a login.")
end
else
ids << m.to_s
end
end
ids.concat(CloudUser.in(login: logins).map(&:_id)) if logins.present?
if ids.blank?
membership.reset_members
else
membership.remove_members(*ids)
end
if save_membership(membership)
render_success(:ok, "members", members.map{ |m| get_rest_member(m) }, ids.blank? ? "Reverted members to the defaults." : "Removed or reset #{pluralize(ids.length, 'member')}.")
else
render_error(:unprocessable_entity, "The members could not be removed due to an error.", nil, nil, nil, get_error_messages(membership))
end
end
def leave
authorize! :leave, membership
return render_error(:bad_request, "You are the owner of this #{membership.class.model_name.humanize.downcase} and cannot leave.") if membership.owned_by?(current_user)
remove_member(current_user._id)
end
protected
def membership
raise "Must be implemented to return the resource under access control"
end
def remove_member(id)
membership.remove_members(id)
if save_membership(membership)
if m = members.detect{ |m| m._id === id }
render_success(:ok, "member", get_rest_member(m), nil, nil, Message.new(:info, "The member #{m.name} is no longer directly granted a role.", 132))
else
render_success(requested_api_version <= 1.4 ? :no_content : :ok, nil, nil, "Removed member.")
end
else
render_error(:unprocessable_entity, "The member could not be removed due to an error.", nil, nil, nil, get_error_messages(membership))
end
end
#
# Subclass if saving the resource requires any additional steps (Application.save needs to be
# run with the application lock). Should return the result of .save
#
def save_membership(resource)
if resource.save
resource.run_jobs
true
end
end
def get_rest_member(m)
RestMember.new(m, is_owner?(m), get_url, nolinks)
end
def is_owner?(member)
membership.owner_id == member._id
end
def members
membership.members
end
private
def changed_members_for(ids, logins, errors)
if ids.present? or logins.present?
ids = ids.select{ |id, (role, _)| role != :none }
logins = logins.select{ |id, (role, _)| role != :none }
users = CloudUser.accessible(current_user).with_ids_or_logins(ids.keys, logins.keys).each.to_a
missing_user_logins(errors, users, logins)
missing_user_ids(errors, users, ids)
users.map do |u|
m = u.as_member
m.role = (ids[u._id.to_s] || logins[u.login.to_s])[0]
m
end
else
[]
end
end
def removed_ids(ids, logins, errors)
ids = ids.inject({}){ |h, (id, (role, _))| h[id] = id if role == :none; h }
logins = logins.select{ |id, (role, _)| role == :none }
if logins.present?
users = CloudUser.accessible(current_user).with_ids_or_logins(nil, logins.keys).each.to_a
missing_user_logins(errors, users, logins)
ids.merge!(users.inject({}){ |h, u| h[u._id.to_s] = u.login; h })
end
ids
end
def missing_user_logins(errors, users, map)
(map.keys - users.map(&:login)).each do |login|
errors << Message.new(:error, "There is no account with login #{login}.", 132, :login, map[login].last)
end
end
def missing_user_ids(errors, users, map)
(map.keys - users.map{ |u| u._id.to_s }).each do |id|
errors << Message.new(:error, "There is no account with identifier #{id}.", 132, :id, map[id].last)
end
end
include ActionView::Helpers::TextHelper
end
| true |
260f9f83b81701967e50f6953baa91ad0ef968b5
|
Ruby
|
KeithYJohnson/codility
|
/cyclic_rotation/cyclic_rotation.rb
|
UTF-8
| 323 | 3.515625 | 4 |
[] |
no_license
|
# https://codility.com/programmers/lessons/2-arrays/cyclic_rotation/
def solution(a, num_times)
rotated_a = [nil] * a.length
a.each_with_index do |e, idx|
new_index = (idx + num_times) % a.length
rotated_a[new_index] = e
end
rotated_a
end
a = [3, 8, 9, 7, 6]
a_solution = [9, 7, 6, 3, 8]
p solution a, 3
| true |
5df0300784ed016c64c98ec0877d6dc46a91de8a
|
Ruby
|
larrykas/project-5
|
/while_until.rb
|
UTF-8
| 183 | 3.078125 | 3 |
[] |
no_license
|
a = 1
a *= 2 while a < 100
a -= 10 until a < 100
# a → 98
puts a
$i = 1
$num = 6
begin
puts("This is day #$i" )
$i +=1
end while $i < $num
puts "Thank you all for coming."
| true |
bfefc71d62a395b3c441c447ac28bfbac7c57546
|
Ruby
|
artemisxen/Boris-Bikes
|
/spec/garage_spec.rb
|
UTF-8
| 545 | 2.65625 | 3 |
[] |
no_license
|
require 'Garage'
describe Garage do
subject { Garage.new }
let(:bike) { double(:bike, :fix => true, :working? => true)}#Individual bike
let(:broken_bike) { double(:bike, :working? => false, :fix => true)}
it "Garage should make all stored bikes working when fix_bikes method is called" do
subject.store(bike)
subject.store(broken_bike)
allow(broken_bike).to receive(:fix!)
allow(broken_bike).to receive(:working?).and_return(true)
expect(subject.bikes[0].working?).to eq true
expect(subject.bikes[1].working?).to eq true
end
end
| true |
bb1c245bd7f201045c1f04999fa01ecfaefc323b
|
Ruby
|
ManageIQ/manageiq
|
/app/models/account.rb
|
UTF-8
| 4,494 | 2.578125 | 3 |
[
"BSD-2-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class Account < ApplicationRecord
belongs_to :vm_or_template
belongs_to :host
include RelationshipMixin
self.default_relationship_type = "accounts"
def self.add_elements(parent, xmlNode)
user_map = add_missing_elements(parent, xmlNode, "accounts/users", "user")
add_missing_elements(parent, xmlNode, "accounts/groups", "group")
add_missing_relationships(parent, user_map)
end
def self.add_missing_elements(parent, xmlNode, findPath, typeName)
hashes = xml_to_hashes(xmlNode, findPath, typeName)
return if hashes.nil?
new_accts = []
member_map = {}
deletes = parent.accounts.where(:accttype => typeName).pluck(:id, :name)
hashes.each do |nh|
member_map[nh[:name]] = nh.delete(:members)
found = parent.accounts.find_by(:name => nh[:name], :accttype => typeName)
found.nil? ? new_accts << nh : found.update(nh)
deletes.delete_if { |ele| ele[1] == nh[:name] }
end
parent.accounts.create(new_accts)
# Delete the IDs that correspond to the remaining names in the current list.
_log.info("Account deletes: #{deletes.inspect}") unless deletes.empty?
deletes = deletes.transpose[0]
Account.destroy(deletes) unless deletes.nil?
member_map
end
def self.add_missing_relationships(parent, user_map)
return if user_map.nil?
# Only need to check one direction, as both directions are implied in the xml
user_map.each do |name, curr_groups|
acct = parent.accounts.find_by(:name => name, :accttype => 'user')
prev_groups = acct.groups.collect(&:name)
# Remove the common elements from both groups to determine the add/deletes
common = prev_groups & curr_groups
prev_groups -= common
curr_groups -= common
prev_groups.each { |group| acct.remove_group(parent.accounts.find_by(:name => group, :accttype => 'group')) }
curr_groups.each { |group| acct.add_group(parent.accounts.find_by(:name => group, :accttype => 'group')) }
end
end
def self.xml_to_hashes(xmlNode, findPath, typeName)
el = XmlFind.findElement(findPath, xmlNode.root)
return nil unless MiqXml.isXmlElement?(el)
result = []
el.each_element do |e|
nh = e.attributes.to_h
nh[:accttype] = typeName
# Change the specific id type to an acctid
nh[:acctid] = nh.delete("#{typeName}id".to_sym)
nh[:acctid] = nil unless nh[:acctid].respond_to?(:to_int) || nh[:acctid].to_s =~ /^-?[0-9]+$/
# Convert to signed integer values for acctid
nh[:acctid] = [nh[:acctid].to_i].pack("I").unpack("i")[0] unless nh[:acctid].nil?
# Find the users for this group / groups for this user
nh[:members] = []
e.each_element { |e2| nh[:members] << e2.attributes['name'] }
result << nh
end
result
end
def self.accttype_opposite(accttype)
case accttype
when 'group' then 'user'
when 'user' then 'group'
end
end
def accttype_opposite
Account.accttype_opposite(accttype)
end
def with_valid_account_type(valid_account_type)
if accttype == valid_account_type
yield
else
raise _("Cannot call method '%{caller}' on an Account of type '%{type}'") % {:caller => caller[0][/`.*'/][1..-2],
:type => accttype}
end
end
# Relationship mapped methods
def users
with_valid_account_type('group') { children }
end
def add_user(owns)
with_valid_account_type('group') { add_child(owns) }
end
def remove_user(owns)
with_valid_account_type('group') { remove_child(owns) }
end
def remove_all_users
with_valid_account_type('group') { remove_all_children(:of_type => self.class.name) }
end
def groups
with_valid_account_type('user') { parents }
end
def add_group(owner)
with_valid_account_type('user') { add_parent(owner) }
end
def remove_group(owner)
with_valid_account_type('user') { remove_parent(owner) }
end
def remove_all_groups
with_valid_account_type('user') { remove_all_parents(:of_type => self.class.name) }
end
# Type ambivalent relationship methods
#
# FIXME: Why not use .pluralize?
#
def members
send("#{accttype_opposite}s")
end
def add_member(member)
send("add_#{accttype_opposite}", member)
end
def remove_member(member)
send("remove_#{accttype_opposite}", member)
end
def remove_all_members
send("remove_all_#{accttype_opposite}s")
end
end
| true |
8b6eac140ed20f8b00bc3f82de793668e0892b6b
|
Ruby
|
niquola/famili
|
/spec/famili_spec.rb
|
UTF-8
| 9,106 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
require 'spec_helper'
require "uuid"
describe Famili do
before :all do
TestDbUtils.ensure_schema
end
after :all do
TestDbUtils.drop_database
end
class User < ActiveRecord::Base
has_many :articles
validates_presence_of :login
def full_name
"#{last_name}, #{first_name}"
end
def nickname=(value)
@nickname = value
end
def calculate_nickname
@nickname || @login
end
def method_missing(name, *args)
if name.to_s == "not_defined_method"
"#{name} is not defined"
else
super
end
end
end
class Article < ActiveRecord::Base
belongs_to :user
end
module Famili
class User < Mother
last_name { 'nicola' }
login { "#{last_name}_#{unique}" }
number { sequence_number }
def before_save(user)
user.first_name = 'first_name'
end
def after_create(model)
end
end
end
class Person
attr_accessor :id, :name
end
class PersonFamili < Famili::GrandMother
name { 'Some Person' }
def save(model)
model.id = UUID.generate
end
end
class ArticleFamili < Famili::Mother
has :user do
last_name { 'nicola' }
end
title { "article by #{user.last_name}" }
end
class CommentableArticleFamili < ArticleFamili
self.model_class = Article
title { "cmt article by #{user.last_name}" }
end
class UserFamili < Famili::Mother
first_name { 'john' }
last_name { 'smith' }
login { "#{last_name}_#{first_name}" }
last_login_datetime { created_at }
created_at { Time.now - Random.rand(1000) }
seq_no { sequence_number }
def mother_random(n)
rand(n)
end
trait :russian do
first_name { 'ivan' }
last_name { 'petrov' }
end
trait :unidentified do
last_name { 'unknown' }
end
scope :with_articles do |count|
scoped(articles: -> { ArticleFamili.build_brothers(count, user: self) })
end
scope :prefixed do |prefix|
scoped(last_name: "#{prefix}#{attributes[:last_name]}")
end
scope :suffixed do |suffix|
scoped(last_name: "#{attributes[:last_name]}#{suffix}")
end
scope :mr_junior do
prefixed('Mr ').suffixed(', Jr')
end
end
it "should have access to Kernel functions" do
user = UserFamili.create(:last_name => -> { "smith_#{rand(100)}" })
user.last_name.should =~ /smith_\d{1,3}/
end
it "should delegate method call to mother" do
user = UserFamili.create(:last_name => -> { "smith_#{mother_random(100)}" })
user.last_name.should =~ /smith_\d{1,3}/
end
it "should auto-evaluate model class" do
Famili::User.send(:model_class).should == User
UserFamili.send(:model_class).should == User
end
it "should be evaluated in context of model" do
user = UserFamili.create :login => -> { self.to_s }
user.login.should == user.to_s
end
it "should bypass method_missing to model" do
user = UserFamili.create :login => -> { not_defined_method }
user.login.should == "not_defined_method is not defined"
end
it "should create model with only set access propeties" do
user = UserFamili.create(:nickname => -> { "Mr #{login}" })
user.calculate_nickname.should == "Mr #{user.login}"
end
describe "scopes" do
it "should create from scope" do
user = UserFamili.russian.create({})
user.first_name.should == 'ivan'
user.last_name.should == 'petrov'
user.login.should == "petrov_ivan"
end
it "should build from scope" do
user = UserFamili.russian.build({})
user.first_name.should == 'ivan'
user.last_name.should == 'petrov'
user.login.should == "petrov_ivan"
end
it "should build_hash from scope" do
hash = UserFamili.russian.build_hash
hash[:first_name].should == 'ivan'
hash[:last_name].should == 'petrov'
hash[:login].should == 'petrov_ivan'
end
it "should chain scopes" do
user = UserFamili.russian.unidentified.build
user.first_name.should == 'ivan'
user.last_name.should == 'unknown'
user.login.should == 'unknown_ivan'
end
it "should support anonymous scope" do
shared = UserFamili.scoped(:first_name => 'jeffry')
shared.create(:last_name => 'stone').login.should == 'stone_jeffry'
shared.create(:last_name => 'snow').login.should == 'snow_jeffry'
shared.unidentified.create.login.should == 'unknown_jeffry'
end
it "should parameterize scope" do
user = UserFamili.with_articles(5).create
user.articles.count.should == 5
end
it "should access previous attribute values" do
user = UserFamili.scoped(last_name: 'Smith').mr_junior.create
user.last_name.should == 'Mr Smith, Jr'
end
it 'should use scopes using famili instance' do
user = UserFamili.new.russian.build(last_name: 'Smith')
user.full_name.should == "Smith, ivan"
end
end
describe "brothers" do
it "should build brothers" do
brothers = UserFamili.build_brothers(2, :login => -> { "#{last_name}_#{first_name}_#{rand(100)}" })
first, second = brothers
first.should_not be_persisted
second.should_not be_persisted
first.first_name.should == second.first_name
first.last_name.should == second.last_name
first.login.should_not == second.login
end
it "should create brothers" do
brothers = UserFamili.create_brothers(2, :login => -> { UUID.generate })
first, second = brothers
first.should be_persisted
second.should be_persisted
first.first_name.should == second.first_name
first.last_name.should == second.last_name
first.login.should_not == second.login
end
it "should build brothers with init block" do
brothers = UserFamili.build_brothers(1) { |brother| brother.login = "#{brother.login}_#{rand(100)}" }
brothers += UserFamili.build_brothers(1) { |brother, i| brother.login = "#{brother.login}_#{i}" }
first, second = brothers
first.should_not be_persisted
second.should_not be_persisted
first.first_name.should == second.first_name
first.last_name.should == second.last_name
first.login.should_not == second.login
first.login.should =~ /#{first.last_name}_#{first.first_name}_\d{1,3}/
second.login.should == "#{second.last_name}_#{second.first_name}_0"
end
it 'should build brothers using famili instance' do
brothers = UserFamili.new.build_brothers(1, first_name: 'John', last_name: 'Smith')
brothers.first.full_name.should == "Smith, John"
end
end
it "should calculate field value only once and cache" do
user = UserFamili.create
user.created_at.should == user.last_login_datetime
end
it "should use save! model" do
lambda { Famili::User.create(:login => nil) }.should raise_error
end
it "should create model" do
nicola = Famili::User.create
nicola.class.should == User
nicola.last_name.should == 'nicola'
nicola.first_name.should == 'first_name'
ivan = Famili::User.create(:name => 'ivan')
ivan.name.should == 'ivan'
end
it "mother should have #build method" do
user = UserFamili.build(:last_name => 'stone')
user.last_name.should == 'stone'
user.first_name.should == 'john'
end
it "mother should have #build_hash method returning symbolized hash" do
hash = Famili::User.build_hash
hash.keys.each { |key| key.should be_kind_of(Symbol) }
end
it "should create model with association" do
article = ArticleFamili.create
article.user.should_not be_nil
article.user.class.should == ::User
article.title.should == "article by nicola"
end
it "mother should have unique,sequence_number methods" do
seq_number = UserFamili.build.seq_no
next_seq_number = UserFamili.build.seq_no
next_seq_number.should == (seq_number + 1)
end
it "mother should generate unique numbers" do
logins = []
10000.times do
logins << Famili::User.build_hash[:login]
end
logins.include?(Famili::User.build_hash[:login]).should_not be_true
end
it "should not add attribute name" do
Famili::User.name
Famili::User.attributes.should_not include(:name)
lambda {
Famili::User.unexisting
}.should raise_error(NoMethodError)
end
describe "associations" do
it "should override association" do
user = UserFamili.create
article = ArticleFamili.create(user: user)
article.user.should == user
end
end
describe "inheritance" do
it "should inherit associations" do
commentable_article = CommentableArticleFamili.create
commentable_article.user.last_name.should == 'nicola'
end
end
describe 'custom persistence' do
it 'should build model' do
person = PersonFamili.build(name: 'John Smith')
person.name.should == 'John Smith'
person.id.should be_nil
end
it 'should create model' do
person = PersonFamili.create(name: 'John Smith')
person.name.should == 'John Smith'
person.id.should_not be_nil
end
end
end
| true |
504e2e6dc2dcc36be625110072d8d49923dd723a
|
Ruby
|
rokn/Count_Words_2015
|
/fetched_code/ruby/suggest_spec.rb
|
UTF-8
| 920 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
# encoding: utf-8
RSpec.describe TTY::Prompt, '#suggest' do
let(:possible) { %w(status stage stash commit branch blame) }
subject(:prompt) { TTY::TestPrompt.new }
it 'suggests few matches' do
prompt.suggest('sta', possible)
expect(prompt.output.string).
to eql("Did you mean one of these?\n stage\n stash\n")
end
it 'suggests a single match for one character' do
prompt.suggest('b', possible)
expect(prompt.output.string).to eql("Did you mean this?\n blame\n")
end
it 'suggests a single match for two characters' do
prompt.suggest('co', possible)
expect(prompt.output.string).to eql("Did you mean this?\n commit\n")
end
it 'suggests with different text and indentation' do
prompt.suggest('b', possible, indent: 4, single_text: 'Perhaps you meant?')
expect(prompt.output.string).to eql("Perhaps you meant?\n blame\n")
end
end
| true |
d8a48bf3c9843faa00ee915ec643ad9062c95d56
|
Ruby
|
gilmae/AdventureCapital
|
/lib/adventure_capital/challenge.rb
|
UTF-8
| 1,441 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
module AdventureCapital
class Challenge
attr_accessor :targets, :level, :damage#, :themes
def initialize
@targets = {}
@themes = []
end
def generate level
@level = level
abilities = Abilities::ALL_ABILITIES.clone + @themes
abilities.delete :health
create_target abilities
create_target(abilities) if 1.d4 <= 2
@damage = [level.d4 / 2,1].max
self
end
def encounter party
success = true
@targets.each{|k,v| success &= party.ability(k).d6 > v.d6}
party.take_damage(@damage) unless success
party.xp += xp if success
success
end
def xp
# The reward should be proportional to the risk. The risk itself is the
# amount of damage failure will incur multiplied by the chance of
# failure. A Challenge that causes 100 damage but is failed only 1% of
# the time should give limited reward. A Challenge that causes a large
# percentage of a party's health in damage and is failed 50% of the time
# should offer a large reward.
difficulty = targets.map{|k,v| v}.max
difficulty += targets.length - 1
damage * difficulty/level
end
def create_target abilities
ability = pick_challenge_type abilities
abilities.delete ability
targets[ability] = [@level + 1.d4 - 2, 1].max
end
def pick_challenge_type abilities
index = 1.d(abilities.length) - 1
abilities[index]
end
end
end
| true |
cff1df592d0e1a507e07c0ad99bda40c5fb8c40c
|
Ruby
|
KirillUsoltsev/rubylovo
|
/plaforms_controller.rb
|
UTF-8
| 483 | 2.546875 | 3 |
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
require "serialport"
require "websocket-eventmachine-client"
require "json"
serial = SerialPort.open("/dev/cu.usbmodem1431")
EM.run do
ws = WebSocket::EventMachine::Client.connect(:uri => "ws://0.0.0.0:1666")
ws.onopen do
puts "Connected"
end
EM.defer do
while data = serial.gets(";")
raw = data.chomp.strip
values = raw.split(",").map { |value| value.to_i >= 800 }
if values.size == 4
ws.send values.to_json
end
end
end
end
| true |
e8744a8baa41e7e1ca756339b53190218b8dfbfe
|
Ruby
|
tayjohno/project-euler-ruby
|
/solutions/023.rb
|
UTF-8
| 1,944 | 3.6875 | 4 |
[] |
no_license
|
# frozen_string_literal: true
require './lib/taylor_math.rb'
#####################
# Problem 23 #
# ----------------- #
# Non-Abundant Sums #
#####################
class TwentyThree
def initialize(max = 28_123)
@max = max
end
def solve
a = (0..@max).to_a
i = j = 0
all_abundant_numbers = TaylorMath::Abundance.all_abundant_numbers
length = all_abundant_numbers.length
while i < length
while j < length
sum = all_abundant_numbers[i] + all_abundant_numbers[j]
break if sum > 28_123
a[sum] = 0
j += 1
end
i += 1
j = i
end
TaylorMath::Array.sum(a)
end
end
# THIS WAS A BAD IDEA
#
# def twentythree_refactoring(initial_array=((1..28123).to_a))
# input_array = initial_array
# output_array = []
# i = 0
# x = 0
# y = 0
# all_abundant_numbers = TaylorMath::Abundance.all_abundant_numbers
# max_j = max_i = all_abundant_numbers.length - 1
#
# while input_array.length > 0
#
# # Grab a number from the Array
# value = input_array.pop
#
# # Find closest number
# while (sum = 2 * all_abundant_numbers[max_i]) > value
# if input_array.include? sum
# input_array.delete(sum)
# else
# puts "WASTED DELETE - B"
# end
# max_i -= 1
# end
# j = i = max_i
# input_array.delete(all_abundant_numbers[i] + all_abundant_numbers[j])
#
# # Find a number that equals it.
# sum = 0
# while (sum = all_abundant_numbers[i] + all_abundant_numbers[j]) != value && i > 0 && j < max_j
# if input_array.include? sum
# input_array.delete(sum)
# else
# puts "WASTED DELETE - B"
# end
# if sum > value
# i -= 1
# else
# j += 1
# end
# end
# output_array.push sum unless sum == value
# puts "#{input_array.length}/#{output_array.length}"
# end
# return output_array
# end
# ANSWER: 4179871
| true |
2623718ccd291ab100215b4102cedd4405543a6f
|
Ruby
|
bensek/Ruby-Programming
|
/Chapt3/solutions3.rb
|
UTF-8
| 2,129 | 4.40625 | 4 |
[] |
no_license
|
# [ CHAPTER 3 SOLUTIONS]
# 1. We can manipulate Strings with strings, integers with integers, floats with floats and integers with floats.
# 2.
puts "********************* ( 2 )***************************"
x = 5
y = 3
z = 8
c = x/y*z + y
puts "2) The value of c without parentheses is #{c}" # c = 11
c = (x/(y*z) + y)
puts "2) The value of c with parentheses is #{c}" # c = 3
#3. Ruby executes operations of the same precendence from left to right
# When it comes to integer division, it wont show the decimals. Hence
# 5 / 2 * 1.0 = 2 * 1.0 = 2.0
# 1.0 * 5 / 2 = 2.5 ...Here the irb first converts 5 into a float
#4. Integer division and
puts "********************* ( 4 )***************************"
# a)
x = 9
x = x/2
puts "4a) The value of x is #{x}" # x = 4
# b)
x = 9
x = x/2.0
puts "4b) The value of x is #{x}" # x = 4.5
#5
puts "********************* ( 5 )***************************"
#a)
a = Math.sqrt(9)
b = 2
c = a/b
puts "5a) The value of c is #{c}" # c = 1.5
#b)
a = 5
b = 2
c = a/b
puts "5b) The value of c is #{c}" # c = 2
#6. A program that computes the average temp in a year
puts "********************* ( 6 )***************************"
puts "Enter the temp in winter : " # 1.2
temp_winter = gets.to_f
puts "Enter the temp in spring : " #10
temp_spring = gets.to_f
puts "Enter the temp in summer : " #30.5
temp_summer = gets.to_f
puts "Enter the temp in fall : " #20.0
temp_fall = gets.to_f
avg_temp = (temp_winter + temp_spring + temp_summer + temp_fall)/ 4 # avg_temp = 15.425
# if we the parentheses are not there, it will give incorrect results
puts "The average temp of the year is #{avg_temp}"
#7. logic errors also known as semantic errors are those which the interpreter doesnot not recognize,
# but they lead to incorrect results in the output.
# EXAMPLE: avg = 4 + 6 /2
# Syntax errors arise when the programmer uses the wrong keywords or operators, i.e not obeying the
# the laws of the ruby language
# EXAMPLE: x = math.sqrt(9) or c = "Ruby " + 45
| true |
9537c1b1c3173c2145ddfca48125f01722d81e0b
|
Ruby
|
rajanjamu/codeastra
|
/problem10_v5.rb
|
UTF-8
| 551 | 4.15625 | 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.
# Remove multiples of 2,3,5,7...
limit = 200000
list = (2..limit).to_a
boolean = Array.new
(0...list.length).each do |item|
boolean << 1
end
(0...list.length-1).each do |i|
if (boolean[i] == 1)
prime = list[i]
(i+1...list.length).each do |j|
# puts "#{i} #{j}"
if (list[j]%prime == 0)
boolean[j] = 0
end
end
end
end
# Print out prime numbers
(0...list.length).each do |i|
if (boolean[i] == 1)
puts list[i]
end
end
| true |
14689e2e3b6a6f57e96455194d63c34bf9426422
|
Ruby
|
ist420/ist420
|
/app/models/client.rb
|
UTF-8
| 274 | 2.71875 | 3 |
[] |
no_license
|
class Client < ActiveRecord::Base
validates :name, presence: true
has_many :timestamps
validates :name, uniqueness: true
def sum_hours
sum = 0.0
self.timestamps.each {|t| sum += t.duration[:total]/60/60 }
sum.round(2)
end
end
| true |
897cdb3759cee2536a96d45443e174c23963a508
|
Ruby
|
fishkel-truelogic/carrito
|
/carritoBack/item.rb
|
UTF-8
| 243 | 3.03125 | 3 |
[] |
no_license
|
require 'json'
class Item
attr_accessor :nombre
attr_accessor :precio
def initialize(nombre, precio)
self.nombre = nombre
self.precio = precio
end
def getJson()
return {:nombre => self.nombre , :precio => self.precio}.to_json
end
| true |
d7b3e06bd9d3ad836fee9b47f1f4fdf514cea127
|
Ruby
|
francisluong/zz_ruby_netdev_interaction
|
/scratch/030.secret.rb
|
UTF-8
| 148 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env ruby
require 'highline/import'
secret = ask("What's your secret? "){|a| a.echo = false}
puts "I'm telling your secret: #{secret}"
| true |
d1bd1571422919b8bc65f6a1683cbae14b6a9299
|
Ruby
|
matherton/depot
|
/app/helpers/store_helper.rb
|
UTF-8
| 668 | 2.96875 | 3 |
[] |
no_license
|
module StoreHelper
#attempt to convert $ to £ but did not work here - think changing app/locales/en.yml did
#number_to_currency(1234567890.50) > #=> $1,234,567,890.50 number_to_currency(1234567890.506) > #=> $1,234,567,890.51
#number_to_currency(1234567890.50, :unit => "£", :separator => ",", :delimiter => "") > #=> £1234567890,50
#end
# number_to_currency method calls ActionView::Helpers::NumberHelper#number_to_currency with different default options
#module StoreHelper
# def number_to_currency(number, options= {:unit => "£", :separator => ","})
# Object.new.extend(ActionView::Helpers::NumberHelper).number_to_currency(number, options)
# end
end
| true |
221d4924e45b794669ec56d228c635bfecb973b1
|
Ruby
|
nmbits/ruby-fiddle-fuse
|
/lib/ffuse/filesystem/abstract_filesystem.rb
|
UTF-8
| 3,174 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
require 'ffuse/filesystem'
module FFUSE
module Filesystem
class AbstractFilesystem
def lookup(path)
if path == '/'
return root, "."
end
inode = root
name = nil
loop do
m = /\/([^\/]+)/.match path
name = m[1]
path = m.post_match
break if path.empty?
inode = inode[name]
raise Errno::EINVAL if inode.nil? || (!inode.respond_to? :[])
end
return inode, name
end
def noent_and_raise(dir, name)
unless dir[name]
raise Errno::ENOENT
end
end
private :noent_and_raise
def exist_and_raise(dir, name)
if dir[name]
raise Errno::EEXIST
end
end
private :exist_and_raise
def check_respond_to(inode, sym)
unless inode.respond_to? sym
raise Errno::ENOTSUP
end
end
private :check_respond_to
def check_not_dir(inode)
if inode.respond_to? :[]
raise Errno::EISDIR
end
end
private :check_not_dir
def self.enable(*methods)
methods.each do |sym|
case sym
when :getattr, :readlink, :chmod, :chown,
:truncate, :open, :read, :write,
:flush, :release, :fsync, :utimens,
:opendir, :readdir, :releasedir
define_method sym do |path, *a|
dir, name = lookup path
noent_and_raise dir, name
inode = dir[name]
check_respond_to inode, sym
inode.__send__ sym, *a
end
when :mkdir, :create
define_method sym do |path, *a|
dir, name = lookup path
check_respond_to dir, sym
exist_and_raise dir, name
dir.__send__ sym, name, *a
end
when :unlink, :rmdir
define_method sym do |path, *a|
dir, name = lookup path
check_respond_to dir, sym
noent_and_raise dir, name
dir.__send__ sym, name, *a
end
when :rename
def rename(path1, path2)
dir1, name1 = lookup path1
check_respond_to dir1, :rename
noent_and_raise dir1, name1
dir2, name2 = lookup path2
exist_and_raise dir2, name2
dir1.rename name1, dir2, name2
end
when :link
def link(path1, path2)
dir1, name1 = lookup path1
check_respond_to dir1, :link
noent_and_raise dir1, name1
dir2, name2 = lookup path2
exist_and_raise dir2, name2
inode = dir1[name1]
check_not_dir inode
dir2.link name2, inode
end
when :symlink
def symlink(path1, path2)
dir2, name2 = lookup path2
check_respond_to dir2, :symlink
exist_and_raise dir2, name2
dir2.symlink name2, path1
end
end
end
end
end
end
end
| true |
4aae4e8443be4fde353d3f0b0d43a343a564fe35
|
Ruby
|
adorableio/cryptid.rb
|
/lib/cryptid/client.rb
|
UTF-8
| 939 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
require 'json'
require 'excon'
module Cryptid
class Client
attr_writer :conn, :tracker_id
def initialize(options={})
@conn = options[:conn] if options[:conn]
if options[:tracker_id]
@tracker_id = options[:tracker_id]
else
@tracker_id = Cryptid.configuration.tracker_id
end
end
def url
Cryptid.configuration.url
end
def conn
@conn ||= ::Excon.new(url)
end
def tracker_id
@tracker_id or raise 'Missing tracker_id. Set in initializer or Cryptid::Client constructor'
end
def headers
{
'Content-Type' => 'application/json',
'Accept' => 'application/json'
}
end
def send(event)
conn.post(body: build_event_payload(event), headers: headers)
end
def build_event_payload(event)
{
event: Helpers.camelize(event.merge(tracker_id: tracker_id))
}.to_json
end
end
end
| true |
580372cddca764beb5f6ea53ecd77ce3190e14e2
|
Ruby
|
jimmy2822/niu-class-materia
|
/exercise/ex_1_group_by.rb
|
UTF-8
| 179 | 2.921875 | 3 |
[] |
no_license
|
people = { jimmy: 'teacher', bill: 'doctor', alex: 'doctor',
tina: 'driver', sam: 'singer', tim: 'actor', bob: 'singer' }
puts people.group_by { |k,v| v == 'singer' }
| true |
de2b2860479ef7c0855e2ecec896d9beedafe2bb
|
Ruby
|
jorgejuanp/ruby-testing-rspec
|
/lexiconomitron.rb
|
UTF-8
| 284 | 3.1875 | 3 |
[] |
no_license
|
class Lexiconomitron
def eat_t(input)
input.downcase.delete "t"
end
def shazam(input)
output = input.map do |word|
eat_t(word.reverse)
end
[output.first, output.last]
end
def oompa_loompa(input)
input.delete_if {|word| word.length > 3}
end
end
| true |
5560707337e62479c55c7515f80980fbd2120691
|
Ruby
|
DevinPierce/emoticon-translator-nyc-web-060418
|
/lib/translator.rb
|
UTF-8
| 757 | 3.125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'yaml'
def load_library(file_path)
emoticons_raw = YAML.load_file(file_path)
translation_hash = {'get_meaning' => {}, 'get_emoticon' => {}}
emoticons_raw.each_pair do |meaning, emot_array|
translation_hash['get_meaning'][emot_array[1]] = meaning
translation_hash['get_emoticon'][emot_array[0]] = emot_array[1]
end
translation_hash
end
def get_japanese_emoticon(file_path, english_emoticon)
translation_hash = load_library(file_path)
translation_hash['get_emoticon'][english_emoticon] || "Sorry, that emoticon was not found"
end
def get_english_meaning(file_path, japanese_emoticon)
translation_hash = load_library(file_path)
translation_hash['get_meaning'][japanese_emoticon] || "Sorry, that emoticon was not found"
end
| true |
8a7772af2d43c2a6dbd592eef67b2dec1db60625
|
Ruby
|
harrie429/ruby-challenges
|
/oop2.rb
|
UTF-8
| 584 | 3.65625 | 4 |
[] |
no_license
|
class Ferret
@@total_ferrets = 0
def initialize
@@total_ferrets += 1
end
def self.current_count
puts "there are currently #{@@total_ferrets} instances of my Ferret class."
end
def set_name=(ferret_name)
@name = ferret_name
end
def get_name
return @name
end
def owner_name=(owner_name)
@owner_name = owner_name
end
def get_owner
return @owner_name
end
def squeal
return "squeeeeee"
end
end
my_ferret = Ferret.new
my_ferret.set_name = "Fredo"
ferret_name = my_ferret.get_name
Ferret.current_count
puts Ferret.inspect
puts my_ferret.inspect
| true |
06871580f12e6fbe476435024ed70c1462baacc5
|
Ruby
|
kaktusyaka/marketing_opt_in_api
|
/lib/mark_opt_in_api.rb
|
UTF-8
| 1,247 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
require "mark_opt_in_api/version"
module MarkOptInApi
require 'httparty'
class Configuration
attr_accessor :host, :port
def initialize
self.host = 'localhost'
self.port = 3000
end
end
def self.configuration
@configuration ||= Configuration.new
end
def self.configure
yield(configuration) if block_given?
end
class Api
def self.add options = {}
raise ArgumentError.new('Options should be present') if options.empty?
response = HTTParty.post("http://#{MarkOptInApi.configuration.host}:#{MarkOptInApi.configuration.port}/marketings", query: { marketing: options })
puts response
end
def self.update id = nil, options = {}
raise ArgumentError.new('ID and Options should be present') if id.nil? || options.empty?
response = HTTParty.put("http://#{MarkOptInApi.configuration.host}:#{MarkOptInApi.configuration.port}/marketing/#{id}", query: { marketing: options })
puts response
end
def self.delete id = nil
raise ArgumentError.new('ID should be present') unless id
response = HTTParty.delete("http://#{MarkOptInApi.configuration.host}:#{MarkOptInApi.configuration.port}/marketing/#{id}")
puts response
end
end
end
| true |
580926212d5681e0b45e83c93b1fd9e49b6226e8
|
Ruby
|
kylebennett-sage/AdventOfCode2020
|
/day_2.rb
|
UTF-8
| 3,368 | 4.0625 | 4 |
[] |
no_license
|
#day_2.rb
# --- Day 2: Password Philosophy ---
# Your flight departs in a few days from the coastal airport; the easiest way down to the coast from here is via toboggan.
# The shopkeeper at the North Pole Toboggan Rental Shop is having a bad day. "Something's wrong with our computers; we can't log in!" You ask if you can take a look.
# Their password database seems to be a little corrupted: some of the passwords wouldn't have been allowed by the Official Toboggan Corporate Policy that was in effect when they were chosen.
# To try to debug the problem, they have created a list (your puzzle input) of passwords (according to the corrupted database) and the corporate policy when that password was set.
# For example, suppose you have the following list:
# 1-3 a: abcde
# 1-3 b: cdefg
# 2-9 c: ccccccccc
# Each line gives the password policy and then the password. The password policy indicates the lowest and highest number of times a given letter must appear for the password to be valid. For example, 1-3 a means that the password must contain a at least 1 time and at most 3 times.
# In the above example, 2 passwords are valid. The middle password, cdefg, is not; it contains no instances of b, but needs at least 1. The first and third passwords are valid: they contain one a or nine c, both within the limits of their respective policies.
# How many passwords are valid according to their policies?
input = File.readlines('resources/day2_input.txt')
valid = 0
for i in input
split = i.split(':')
policy_split = split[0].strip
password = split[1].strip
policy = policy_split.match /(?<min>\d+)-(?<max>\d+) (?<char>\w+)/
char_count = password.count(policy[:char])
valid += 1 if char_count >= policy[:min].to_i && char_count <= policy[:max].to_i
end
puts "Part 1 - #{valid}"
# --- Part Two ---
# While it appears you validated the passwords correctly, they don't seem to be what the Official Toboggan Corporate Authentication System is expecting.
# The shopkeeper suddenly realizes that he just accidentally explained the password policy rules from his old job at the sled rental place down the street! The Official Toboggan Corporate Policy actually works a little differently.
# Each policy actually describes two positions in the password, where 1 means the first character, 2 means the second character, and so on. (Be careful; Toboggan Corporate Policies have no concept of "index zero"!) Exactly one of these positions must contain the given letter. Other occurrences of the letter are irrelevant for the purposes of policy enforcement.
# Given the same example list from above:
# 1-3 a: abcde is valid: position 1 contains a and position 3 does not.
# 1-3 b: cdefg is invalid: neither position 1 nor position 3 contains b.
# 2-9 c: ccccccccc is invalid: both position 2 and position 9 contain c.
# How many passwords are valid according to the new interpretation of the policies?
valid = 0
for i in input
split = i.split(':')
policy_split = split[0].strip
password = split[1].strip
policy = policy_split.match /(?<pos_a>\d+)-(?<pos_b>\d+) (?<char>\w+)/
char = policy[:char]
pos_a = policy[:pos_a].to_i - 1
pos_b = policy[:pos_b].to_i - 1
valid += 1 unless
(password[pos_a] == char && password[pos_b] == char) || (password[pos_a] != char && password[pos_b] != char)
end
puts "Part 2 - #{valid}"
| true |
e7aa81792382d0ac08ce56f356d29790c94a503a
|
Ruby
|
jastack/toy_problems
|
/interview_prep/get_different_number.rb
|
UTF-8
| 2,548 | 4.3125 | 4 |
[] |
no_license
|
# Ok, this question comes from pramp
# Given an array arr of unique nonnegative integers, implement a function
#get_different_number that finds the smallest nonnegative integer that is NOT in the array.
# solve first for case when not allowed to modify the input arr, then when
# you can.
#
# Other notes:
# Not ordered
#
# Case 1:
# arr = [0, 1, 2, 3]
# result => 4
#
# Case 2:
# arr = [0, 2, 3, 4]
# result => 1
#
# Case 3:
# arr = [6, 3, 9, 0]
# result => 1
#
# Approach 1: Brute force / naive
# sort the arr, in O(nlog(n)) time, then iterate through and return
# first value that does not match index. If all match, return next value.
# If length of arr is 2^31 - 1, return undefined (extreme edge case).
#
# Approach 2: Use a set
# Convert the arr to set. Starting at 0, check if each number is in the
# set. As soon as one isn't, return that number. Time complexity O(n).
#
# Pseudocode:
# function(arr)
# create new set from arr values
# starting at 0, check if each number until length of arr is in set
# if is not, return that number
# After it gets through it all and hasn't returned, check if length of
# arr is 2^31 - 1. If so, return undefined. If not, return length of array
# function(arr)
# in ruby must require set
require 'set'
def get_different_number(arr)
set = Set.new(arr)
i = 0
while i < arr.length
if !set.include?(i)
return i
end
i += 1
end
if arr.length == 2**31 - 1
return undefined
else
return arr.length
end
end
arr1 = [0, 1, 2, 3]
arr2 = [0, 2, 3, 4]
arr3 = [6, 3, 9, 0]
p get_different_number(arr1) == 4
p get_different_number(arr2) == 1
p get_different_number(arr3) == 1
# This question had a quasi - bonus part: the in-place solution
#
# Pseudocode:
# function get_different_number(arr) => [0, 3, 2, 3]
# ^
# set variable n equal to arr length => n = 4
# set variable temp equal to zero => temp = 0
# set variable i equal to zero => i = 0
# while i less than n => i = 2
# set temp equal to arr at i => temp = 2
# while temp less than n and arr at temp does not equal temp
# swap temp and arr at temp
# now increment i again from zero and check if in array
#
require 'byebug'
def get_different_number_in_place(arr)
n = arr.length
temp = 0
index = 0
while index < n
temp = arr[index]
while (temp < n) && (arr[temp] != temp)
temp, arr[temp] = arr[temp], temp
p arr
end
index += 1
end
arr
end
arr4 = [0, 2, 3, 4]
p get_different_number_in_place(arr4)
| true |
23ff3cbc37e6a5d37bcc4a3d07a8127a8c607328
|
Ruby
|
mochetts/better_settings
|
/spec/better_settings/better_settings_spec.rb
|
UTF-8
| 3,984 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
require 'spec_helper'
require 'support/settings'
describe BetterSettings do
def new_settings(value)
Settings.new(value, parent: 'new_settings')
end
it 'should access settings' do
expect(Settings.setting2).to eq 5
end
it 'should access nested settings' do
expect(Settings.setting1.setting1_child).to eq 'saweet'
end
it 'should access settings in nested arrays' do
expect(Settings.array.first.name).to eq 'first'
end
it 'should access deep nested settings' do
expect(Settings.setting1.deep.another).to eq 'my value'
end
it 'should access extra deep nested settings' do
expect(Settings.setting1.deep.child.value).to eq 2
end
it 'should enable erb' do
expect(Settings.setting3).to eq 25
end
it 'should namespace settings' do
expect(DevSettings.language.haskell.paradigm).to eq 'functional'
expect(DevSettings.language.smalltalk.paradigm).to eq 'object-oriented'
expect(DevSettings.environment).to eq 'development'
end
it 'should distinguish nested keys' do
expect(Settings.language.haskell.paradigm).to eq 'functional'
expect(Settings.language.smalltalk.paradigm).to eq 'object oriented'
end
it 'should not override global methods' do
expect(Settings.global).to eq 'GLOBAL'
expect(Settings.custom).to eq 'CUSTOM'
end
it 'should raise a helpful error message' do
expect {
Settings.missing
}.to raise_error(BetterSettings::MissingSetting, /Missing setting 'missing' in/)
expect {
Settings.language.missing
}.to raise_error(BetterSettings::MissingSetting, /Missing setting 'missing' in 'language' section/)
end
it 'should raise an error on a nil source argument' do
expect { NoSource.foo.bar }.to raise_error(ArgumentError, '`source` must be specified for the settings')
end
it 'should support instance usage as well' do
expect(new_settings(Settings.setting1).setting1_child).to eq 'saweet'
end
it 'should handle invalid name settings' do
expect {
new_settings('some-dash-setting#' => 'dashtastic')
}.to raise_error(BetterSettings::InvalidSettingKey)
end
it 'should handle settings with nil value' do
expect(Settings.nil).to eq nil
end
it 'should handle settings with false value' do
expect(Settings.false).to eq false
end
# If .name is called on BetterSettings itself, handle appropriately
# by delegating to Hash
it 'should have the parent class always respond with Module.name' do
expect(BetterSettings.name).to eq 'BetterSettings'
end
# If .name is not a property, delegate to superclass
it 'should respond with Module.name' do
expect(DevSettings.name).to eq 'DevSettings'
end
# If .name is a property, respond with that instead of delegating to superclass
it 'should allow a name setting to be overriden' do
expect(Settings.name).to eq 'test'
end
describe 'to_h' do
it 'should handle empty file' do
expect(NoSettings.to_h).to be_empty
end
it 'should be similar to the internal representation' do
expect(settings = Settings.send(:root_settings)).to be_is_a(Settings)
expect(hash = settings.send(:settings)).to be_is_a(Hash)
expect(Settings.to_h).to eq hash
end
it 'should not mutate the original when getting a copy' do
result = Settings.language.to_h.merge('haskell' => 'awesome')
expect(result.class).to eq Hash
expect(result).to eq(
'haskell' => 'awesome',
'smalltalk' => { 'paradigm' => 'object oriented' },
)
expect(Settings.language.haskell.paradigm).to eq('functional')
expect(Settings.language).not_to eq Settings.language.merge('paradigm' => 'functional')
end
end
describe '#to_hash' do
it 'should return a new instance of a Hash object' do
expect(Settings.to_hash).to be_kind_of(Hash)
expect(Settings.to_hash.class.name).to eq 'Hash'
expect(Settings.to_hash.object_id).not_to eq Settings.object_id
end
end
end
| true |
f8a52a20cf75cc52d6e4582c7d4c703477cdb5bf
|
Ruby
|
BaobabHealthTrust/mnch-hotline
|
/application/app/helpers/report_helper.rb
|
UTF-8
| 9,968 | 2.59375 | 3 |
[] |
no_license
|
module ReportHelper
## The following functions will generate table cells for Tips Activity Report
def pregnancy_data_cell(content_type)
if (content_type.capitalize == "All" || content_type.capitalize == "Pregnancy")
content_type.capitalize == "Pregnancy" ? colspan = '4': colspan = '2'
table_cell = "<td width=\"12%\" colspan = #{colspan} class=\"cellleft cellbottom main-table-cell\" style=\"font-weight: bold; text-align:center;\">" + "Pregnancy" +"</td>"
end
table_cell
end
def child_data_cell(content_type)
if (content_type.capitalize == "All" || content_type.capitalize == "Child")
content_type.capitalize == "Child" ? colspan = '4' : colspan = '2'
table_cell = "<td width=\"12%\" colspan = #{colspan} class=\"cellleft cellbottom main-table-cell\" style=\"font-weight: bold; text-align:center;\">" + "Child" +"</td>"
end
table_cell
end
def wcba_data_cell(content_type)
if (content_type.capitalize == "All" || content_type.upcase == "WCBA")
content_type.upcase == "WCBA" ? colspan = '4' : colspan = '2'
table_cell = "<td width=\"12%\" colspan = #{colspan} class=\"cellleft cellbottom main-table-cell\" style=\"font-weight: bold; text-align:center;\">" + "WCBA" +"</td>"
end
table_cell
end
def chiyao_data_cell(language)
if (language.capitalize == "All" || language.capitalize == "Yao" )
language.capitalize == "All" ? colspan = '2': colspan = '4'
table_cell = "<td width=\"12%\" colspan = #{colspan} class=\"cellleft cellbottom main-table-cell\" style=\"font-weight: bold; text-align:center;\">" + "Chiyao" +"</td>"
end
table_cell
end
def chichewa_data_cell(language)
if (language.capitalize == "All" || language.capitalize == "Chichewa" )
language.capitalize == "All" ? colspan = '2': colspan = '4'
table_cell = "<td width=\"12%\" colspan = \"#{colspan}\" class=\"cellleft cellbottom main-table-cell\" style=\"font-weight: bold; text-align:center;\">" + "Chichewa" +"</td>"
end
table_cell
end
def sms_data_cell(delivery)
if (delivery.capitalize == "All" || delivery.capitalize == "Sms" )
delivery.capitalize == "All" ? colspan = '2': colspan = '4'
table_cell = "<td width=\"12%\" colspan = \"#{colspan}\" class=\"cellleft cellbottom main-table-cell\" style=\"font-weight: bold; text-align:center;\">" + "SMS" +"</td>"
end
table_cell
end
def voice_data_cell(delivery)
if (delivery.capitalize == "All" || delivery.capitalize == "Voice" )
delivery.capitalize == "All" ? colspan = '2': colspan = '4'
table_cell = "<td width=\"12%\" colspan = \"#{colspan}\" class=\"cellleft cellbottom cellright main-table-cell\" style=\"font-weight: bold; text-align:center;\">" + "Voice" +"</td>"
end
table_cell
end
def pregnancy_count_and_percent_header(content_type)
if ( content_type.capitalize == "All" || content_type.capitalize == "Pregnancy" )
content_type.capitalize == "Pregnancy" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" +"Count" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" + "%age" + "</td>"
end
end
def child_count_and_percent_header(content_type)
if (content_type.capitalize == "All" || content_type.capitalize == "Child" )
content_type.capitalize == "Child" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" +"Count" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" + "%age" + "</td>"
end
table_cell
end
def wcba_count_and_percent_header(content_type)
if (content_type.capitalize == "All" || content_type.upcase == "WCBA" )
content_type.upcase == "WCBA" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" +"Count" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" + "%age" + "</td>"
end
table_cell
end
def chiyao_count_and_percent_header(language)
if (language.capitalize == "All" || language.capitalize == "Yao" )
language.capitalize == "Yao" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" +"Count" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" + "%age" + "</td>"
end
table_cell
end
def chichewa_count_and_percent_header(language)
if (language.capitalize == "All" || language.capitalize == "Chichewa" )
language.capitalize == "Chichewa" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" +"Count" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" + "%age" + "</td>"
end
table_cell
end
def sms_count_and_percent_header(delivery)
if (delivery.capitalize == "All" || delivery.capitalize == "Sms")
delivery.capitalize == "Sms" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" +"Count" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" + "%age" + "</td>"
end
table_cell
end
def voice_count_and_percent_header(delivery)
if (delivery.capitalize == "All" || delivery.capitalize == "Voice" )
delivery.capitalize == "Voice" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" style=\"font-weight: bold;\">" +"Count" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom cellright main-table-cell\" style=\"font-weight: bold;\">" + "%age" + "</td>"
end
table_cell
end
def pregnancy_count_and_percent_values(content_type, pregnancy_value, pregnancy_pct_value)
if (content_type.capitalize == "All" || content_type.capitalize == "Pregnancy" )
content_type.capitalize == "Pregnancy" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" >" +"#{pregnancy_value}" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\">" + "#{pregnancy_pct_value}" + "</td>"
end
table_cell
end
def child_count_and_percent_values(content_type, child_value, child_pct_value)
if (content_type.capitalize == "All" || content_type.capitalize == "Child" )
content_type.capitalize == "Child" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" >" +"#{child_value}" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\">" + "#{child_pct_value}" + "</td>"
end
table_cell
end
def wcba_count_and_percent_values(content_type, wcba_value, wcba_pct_value)
if (content_type.capitalize == "All" || content_type.upcase == "WCBA" )
content_type.upcase == "WCBA" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" >" +"#{wcba_value}" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\">" + "#{wcba_pct_value}" + "</td>"
end
table_cell
end
def chiyao_count_and_percent_values(language, chiyao_count, chiyao_pct_value)
if (language.capitalize == "All" || language.capitalize == "Yao" )
language.capitalize == "Yao" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" >" +"#{chiyao_count}" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\">" + "#{chiyao_pct_value}" + "</td>"
end
table_cell
end
def chichewa_count_and_percent_values(language, chichewa_count, chichewa_pct_value)
if (language.capitalize == "All" || language.capitalize == "Chichewa")
language.capitalize == "Chichewa" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" >" +"#{chichewa_count}" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\">" + "#{chichewa_pct_value}" + "</td>"
end
table_cell
end
def sms_count_and_percent_values(delivery, sms_count, sms_pct_value)
if (delivery.capitalize == "All" || delivery.capitalize == "Sms" )
delivery.capitalize == "Sms" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" >" +"#{sms_count}" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\">" + "#{sms_pct_value}" + "</td>"
end
table_cell
end
def voice_count_and_percent_values(delivery, voice_count, voice_pct_value)
if (delivery.capitalize == "All" || delivery.capitalize == "Voice" )
delivery.capitalize == "Voice" ? colspan = '2' : colspan = '1'
table_cell = "<td colspan = \"#{colspan}\" class=\" cellleft cellbottom main-table-cell\" >" +"#{voice_count}" + "</td>" + "<td colspan = \"#{colspan}\" class=\" cellright cellleft cellbottom main-table-cell\">" + "#{voice_pct_value}" + "</td>"
end
table_cell
end
end
| true |
4ebdc2d3fc903fb9b93b00be12d7e37598f3b59d
|
Ruby
|
J-Y/RubyQuiz
|
/ruby_quiz/quiz61_sols/solutions/Joby Bednar/dice.rb
|
UTF-8
| 431 | 3.703125 | 4 |
[
"MIT"
] |
permissive
|
class Array
def to_dice
logic = [
lambda{|n| '+-----+ '},
lambda{|n| (n>3 ? '|O ' : '| ')+(n>1 ? ' O| ' : ' | ')},
lambda{|n| (n==6 ? '|O ' : '| ')+
(n%2==1 ? 'O' : ' ')+(n==6 ? ' O| ' : ' | ')},
lambda{|n| (n>1 ? '|O ' : '| ')+(n>3 ? ' O| ' : ' | ')}
]
str=''
5.times {|row|
self.each {|n| str += logic[row%4].call(n) }
str+="\n"
}
str
end
end
#Example:
puts [1,2,3,4,5,6].to_dice
| true |
28b44bfa52a2782c4db06b645107229bb8e9b249
|
Ruby
|
yuqiqian/ruby-leetcode
|
/111_min_depth_BT.rb
|
UTF-8
| 307 | 3.265625 | 3 |
[] |
no_license
|
def min_depth(root)
if root == nil
return 0
elsif root.left == nil && root.right == nil
return 1
elsif root.left == nil
return 1 + min_depth(root.right)
elsif root.right == nil
return 1 + min_depth(root.left)
else
return 1 + [min_depth(root.left), min_depth(root.right)].min
end
end
| true |
a5159f044e569c55a1a2c786a91a09657cad96c8
|
Ruby
|
ElzMoore13/TwO-O-Player-Math-Game
|
/Question.rb
|
UTF-8
| 988 | 3.765625 | 4 |
[] |
no_license
|
class Question
def initialize(curr_player)
@curr_player = curr_player
@question
@correct_answer
@player_guess
end
def rand_num(min, max)
rand(max) + min
end
def make_question
num_1 = rand_num(1, 20)
num_2 = rand_num(1, 20)
if rand(10) % 2 == 0
operator = 'plus'
@correct_answer = num_1 + num_2
else
operator = 'minus'
@correct_answer = num_1 - num_2
end
@question = "#{@curr_player.name}, what does #{num_1} #{operator} #{num_2} equal?"
end
def ask_question
make_question
puts @question
@player_guess = gets.chomp
end
def is_right?(guess)
@correct_answer == guess.to_i
end
def game_response
if is_right?(@player_guess)
puts "Congrats #{@curr_player.name}! You are correct!\n\n"
else
puts "Damn #{@curr_player.name}.... no.... that was wrong!"
puts "The correct answer is: #{@correct_answer}\n\n"
@curr_player.loseLife
end
end
end
| true |
50609c7c2c69ff7d090fc1b0202f853c2827a36d
|
Ruby
|
astrowalls/proyectos
|
/Ruby/prueba.rb
|
UTF-8
| 66 | 3.1875 | 3 |
[] |
no_license
|
puts"escriba un numero"
a = gets.chomp
a = a.to_i
3.times{puts a}
| true |
bf2302a191736aa2885bbf248f441055a7c40ee4
|
Ruby
|
Progressbar/transactions
|
/lib/fio_bank_mail.rb
|
UTF-8
| 2,254 | 2.75 | 3 |
[] |
no_license
|
# encoding: utf-8
class FioBankMail < IncomingMail
def default
@data = parse_body @message.body.to_s.force_encoding('UTF-8')
@data[:raw] = ::Base64.strict_encode64(@message.to_s)
@data[:realized_at] = @message.date || DateTime.now
self
end
def data
@data
end
def income?
@message.subject =~ /prijem/ ? true : false
end
def outcome?
@message.subject =~ /vydej/ ? true : false
end
def parse_body body
if income?
data = parse_income body
elsif outcome?
data = parse_outcome body
else
raise Exception, 'Unable parse unknown email (transaction) type'
end
data
end
def parse_income body
data = { :primary_type => 'income' }
to_account_rgxp = body.match '^Příjem na kontě: (.+)$'
from_account_rgxp = body.match '^Protiúčet: (.+)$'
amount_rgxp = body.match '^Částka: (.+)$'
vs_rgxp = body.match '^VS: (.+)$'
message_rgxp = body.match '^Zpráva příjemci: (.+)$'
raise Exception, 'income: to account parse error' if to_account_rgxp.nil?
raise Exception, 'income: from account parse error' if from_account_rgxp.nil?
raise Exception, 'income: amount parse error' if amount_rgxp.nil?
data[:to_account] = to_account_rgxp[1].strip
data[:from_account] = from_account_rgxp[1].strip
data[:amount] = amount_rgxp[1].strip
data[:vs] = vs_rgxp[1].strip if vs_rgxp
data[:message] = message_rgxp[1].strip if message_rgxp
data
end
def parse_outcome body
data = { :primary_type => 'outcome' }
to_account_rgxp = body.match '\nVýdaj na kontě: (.+)$'
from_account_rgxp = body.match '\nProtiúčet: (.+)$'
amount_rgxp = body.match '\nČástka: (.+)$'
vs_rgxp = body.match '\nVS: (.+)$'
message_rgxp ='\nUS: (.*)'
raise Exception, 'outcome: to account parse error' if to_account_rgxp.nil?
raise Exception, 'outcome: from account parse error' if from_account_rgxp.nil?
raise Exception, 'outcome: amount parse error' if amount_rgxp.nil?
data[:to_account] = to_account_rgxp[1]
data[:from_account] = from_account_rgxp[1]
data[:amount] = amount_rgxp[1]
data[:vs] = vs_rgxp[1] if vs_rgxp
data[:message] = message_rgxp[1] if message_rgxp
data
end
end
| true |
1ba4660f496dbc7fad4ab08ddf0b23ca8d0692cf
|
Ruby
|
Sheikh-Inzamam/AppAcademy-1
|
/w1d1/myeach.rb
|
UTF-8
| 140 | 3.515625 | 4 |
[] |
no_license
|
class Array
def my_each
self.count.times { |index| yield(self[index]) }
self
end
end
a = [1, 2, 3].my_each { |k| puts k }
p a
| true |
2ade37194c2e1cf3a4c3470638d53f8b94b83058
|
Ruby
|
simlegate/nebulas.rb
|
/spec/nebulas/account_spec.rb
|
UTF-8
| 2,057 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
require 'base64'
RSpec.describe Nebulas::Account do
let(:private_key){
"3d55e39c7267b64cedce79519ff790c13e7d24f5ad17308a48a76cc9d5cf18de"
}
let(:address) {
"n1FJ17N3PxrCJkQ5Yj5pPktfde9QxZD9NkM"
}
let(:account) {
account = Nebulas::Account.new(private_key)
}
describe "#initialize" do
it "generate random account" do
account = Nebulas::Account.new
expect(account.private_key).to be_instance_of(OpenSSL::BN)
expect(account.public_key).to be_instance_of(OpenSSL::PKey::EC::Point)
expect(account.address).to be_instance_of(Nebulas::Address)
end
it "specify private_key" do
expect(account.private_key).to be_instance_of(OpenSSL::BN)
expect(account.public_key).to be_instance_of(OpenSSL::PKey::EC::Point)
expect(account.address).to be_instance_of(Nebulas::Address)
expect(account.private_key_str).to eq(private_key)
end
end
describe "#addr_str" do
it "get human-readable address" do
expect(account.addr_str).to eq(address)
end
end
it "#sign" do
expect(hex_str?(account.sign("password"))).to be true
end
describe "#verify" do
it "return true when sign is correct" do
sign = "3046022100936bbdf53d7815778a0959facbc610b7abea7e688cab857fe67c96292089d85f0221009e8e458434d91638c6448d6d0af58644385fc079409d0a9eb4405c6bf302fd41"
expect(account.verify("password", sign)).to be true
end
it "return true when sign is wrong" do
expect(account.verify("password", "3046022100936bbdf53d78")).to be false
end
end
it "#private_key_str" do
expect(hex_str?(account.private_key_str)).to be true
end
it "#pubilc_key_str" do
expect(hex_str?(account.pubilc_key_str)).to be true
end
describe ".from_keystore" do
it "get account instance" do
restored_account = Nebulas::Account.from_keystore(account.keystore("123456"), "123456")
expect(restored_account.addr_str).to eq(account.addr_str)
expect(restored_account.private_key_str).to eq(account.private_key_str)
expect(restored_account.pubilc_key_str).to eq(account.pubilc_key_str)
end
end
end
| true |
9a733ee4ad47039b5d471981905a210de5436016
|
Ruby
|
hswick/sandoz_demo
|
/example_sketches/demo1.rb
|
UTF-8
| 769 | 2.9375 | 3 |
[] |
no_license
|
defsketch do
n = 30
setup do
size 600, 600
@x = width / 2 + random(-width/4, width/4)
@y = height / 2 + random(-height/4, height/4)
range = (0..n).to_a
@vals = range.select { |n| n.even? }
@vals2 = range.select { |n| n.odd? }
end
r = 30
speed_x = 3
speed_y = 1
draw do
background 0, 0, 0
@vals.each do |v|
stroke_weight 10 - v
stroke 255, 0, 0
x = 0 + (v * width / n)
line x, 0, x, height
end
no_stroke
fill 255, 255, 255
ellipse @x, @y, r, r
@x+=speed_x
@y+=speed_y
speed_y *= -1 if @y + r / 2 >= height || @y - r / 2 <= 0
speed_x *= -1 if @x + r / 2 >= width || @x - r / 2 <= 0
@vals2.each do |v|
stroke_weight 10 - v
stroke 255, 0, 0
x = 0 + (v * width / n)
line x, 0, x, height
end
end
end
| true |
aaedb3cf41dcc6cfbf51b3cfaca89faf60b38c19
|
Ruby
|
amorobert/phase-0-tracks
|
/ruby/iteration.rb
|
UTF-8
| 2,122 | 4.1875 | 4 |
[] |
no_license
|
#Release 1
#declare and populate an hash
students = {"Bob" => "Computer Science", "Caitlin" => "Political Ecology", "Anita" => "Interior Design"}
#iterate through hash with .each
students.each do |name, major|
puts name
end
#modify hash with .map
modified_students = students.map do |name, major|
major.upcase
end
#display modified hash
puts "After .map call:"
p modified_students
#declare an array
junkfood = ["Cookies", "Cake", "Cupcakes"]
#iterate through array with .each
junkfood.each do |food|
puts food
end
#modify array with .map!
junkfood.map! do |food|
food.upcase
end
#display modified array
puts "After .map call:"
p junkfood
#Release 2
# 1. method that iterates through the items, deleting any that meet a certain condition.
# declare and populate an array
names = ["Bob", "Kate", "Robin", "Tom"]
# delete item in array if given condition is met
names.delete_if {|name| name.length>3}
p names
#declare and populate a hash
name_age = {"Bob" => 2, "Kate" => 30, "Robin" =>10, "Tom"=> 50}
#delete item in hash if given condition is met
name_age.delete_if {|name, age| age<20}
p name_age
#2.method that filters a data structure for only items that do satisfy a certain condition
#declare and populate an array
names = ["Bob", "Kate", "Robin", "Tom"]
#keep item in array if given condition is met
names.select! {|name| name.length>3}
p names
#declare and populate a hash
name_age = {"Bob" => 2, "Kate" => 30, "Robin" =>10, "Tom"=> 50}
#keep key:value pair in hash if given condition is met
name_age.select! {|name, age| age<20}
p name_age
#3. different method that filters a data structure for only items satisfying a certain condition.
#declare and populate an array
names = ["Bob", "Kate", "Robin", "Tom"]
#remove the key:value pair if the given condition is not met
names.reject! {|name| name.length==3}
p names
#declare and populate a hash
name_age = {"Bob" => 2, "Kate" => 30, "Robin" =>10, "Tom"=> 50}
#remove the key:value pair if given condition is not met
name_age.reject! {|name, age| age<20}
p name_age
| true |
98a0a67d824ad0b4f693b3e5b7f16601090a1308
|
Ruby
|
ismcodes/tcpserver
|
/tcp_server_spec.rb
|
UTF-8
| 1,202 | 2.53125 | 3 |
[] |
no_license
|
require 'rspec'
require_relative 'tcp_server'
#require 'httparty'?
RSpec.describe "TCP implementation" do
before :all do
# will this just stay running? does it need to be threaded separately?
@tcp = IsaacTCP.new
# not server because @tcp has a server instance variable within
# @tcp.start
end
describe "#query_resource" do
it "should return a 200 OK for existing resource" do
expect(@tcp.query_resource("/welcome").status).to match(/.*200 OK.*/)
end
it "should return a 404 Not Found for resource that does not exist" do
expect(@tcp.query_resource("/unwelcome").status).to match(/.*404 Not Found.*/)
end
end
describe "#server_response" do
it "should return the status, body length, and body of the input Struct" do
status = "HTTP/1.11000 Not OK Not Even Close"
body = "<html></html>"
htpr = HttpResponse.new(status, body)
expect(@tcp.server_response(htpr)).to match(/#{status}.*#{body.length}.*#{body}/)
end
it "should include the proper headers" do
htpr = HttpResponse.new('','')
expect(@tcp.server_response(htpr)).to match(/.*Content-Length:.*Content-type:.*Connection:/)
end
end
end
| true |
f97ab34ab7517d821e4b06f0965b7b60f0100223
|
Ruby
|
mikerodrigues/rtcbx
|
/lib/rtcbx.rb
|
UTF-8
| 3,755 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'coinbase/exchange'
require 'rtcbx/orderbook'
require 'rtcbx/candles'
require 'rtcbx/trader'
require 'rtcbx/version'
require 'eventmachine'
class RTCBX
# seconds in between pinging the connection.
#
PING_INTERVAL = 2
# The Coinbase Pro product being tracked (eg. "BTC-USD")
attr_reader :product_id
# Boolean, whether the orderbook goes live on creation or not
# If +false+, +#start!+ must be called to initiate tracking.
attr_reader :start
# API key used to authenticate to the API
# Not required for Orderbook or Candles
attr_reader :api_key
# An array of blocks to be run each time a message comes in on the Websocket
attr_reader :message_callbacks
# The Websocket object
attr_reader :websocket
# The Coinbase Pro Client object
# You can use this if you need to make API calls
attr_reader :client
# The message queue from the Websocket.
# The +websocket_thread+ processes this queue
attr_reader :queue
# Epoch time indicating the last time we received a pong from Coinbase Pro in response
# to one of our pings
attr_reader :last_pong
# The thread that consumes the websocket data
attr_reader :websocket_thread
# Create a new RTCBX object with options and an optional block to be run when
# each message is called.
#
# Generally you won't call this directly. You'll use +RTCBX::Orderbook.new+,
# +RTCBX::Trader.new+, or +RTCBX::Candles.new+.
#
# You can also subclass RTCBX and call this method through +super+, as the
# classes mentioned above do.
#
# RTCBX handles connecting to the Websocket, setting up the client, and
# managing the thread that consumes the Websocket feed.
#
def initialize(options = {}, &block)
@product_id = options.fetch(:product_id, 'BTC-USD')
@start = options.fetch(:start, true)
@api_key = options.fetch(:api_key, '')
@api_secret = options.fetch(:api_secret, '')
@api_passphrase = options.fetch(:api_passphrase, '')
@message_callbacks = []
@message_callbacks << block if block_given?
@client = Coinbase::Exchange::Client.new(
api_key,
api_secret,
api_passphrase,
product_id: product_id
)
@websocket = Coinbase::Exchange::Websocket.new(
keepalive: true,
product_id: product_id
)
@queue = Queue.new
start! if start
end
# Starts the thread to consume the Websocket feed
def start!
start_websocket_thread
end
# Stops the thread and disconnects from the Websocket
def stop!
websocket_thread.kill
websocket.stop!
end
# Stops, then starts the thread that consumes the Websocket feed
def reset!
stop!
start!
end
private
attr_reader :api_secret
attr_reader :api_passphrase
# Configures the websocket to pass each message to each of the defined message
# callbacks
def setup_websocket_callback
websocket.message do |message|
queue.push(message)
message_callbacks.each { |b| b&.call(message) }
end
end
# Starts the thread that consumes the websocket
def start_websocket_thread
@websocket_thread = Thread.new do
setup_websocket_callback
EM.run do
websocket.start!
setup_ping_timer
setup_error_handler
end
end
end
# Configures the websocket to periodically ping Coinbase Pro and confirm connection
def setup_ping_timer
EM.add_periodic_timer(PING_INTERVAL) do
websocket.ping do
@last_pong = Time.now
end
end
end
# Configures the Websocket object to print any errors to the console
def setup_error_handler
EM.error_handler do |e|
print "Websocket Error: #{e.message} - #{e.backtrace.join("\n")}"
end
end
end
| true |
8df45780f9c39955bdffd93372eb57f901f36140
|
Ruby
|
eturino/eapi
|
/lib/eapi/list.rb
|
UTF-8
| 4,174 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
module Eapi
module List
include Comparable
include Enumerable
extend Common
module ClassMethods
def is_multiple?
true
end
end
def self.add_features(klass)
Eapi::Common.add_features klass
klass.extend(ClassMethods)
klass.include(Eapi::Methods::Properties::ListInstanceMethods)
klass.extend(Eapi::Methods::Properties::ListCLassMethods)
end
def self.extended(mod)
def mod.included(klass)
Eapi::List.add_features klass
end
end
def self.included(klass)
Eapi::List.add_features klass
end
def is_multiple?
true
end
def to_a
render
end
def _list
@_list ||= []
end
def add(value)
self << value
self
end
def <=>(other)
(_list <=> other) || (other.respond_to?(:_list) && _list <=> other._list)
end
# From Array
# ary.replace(other_ary) -> ary
# ary.initialize_copy(other_ary) -> ary
#
# Replaces the contents of +self+ with the contents of +other_ary+,
# truncating or expanding if necessary.
#
# a = [ "a", "b", "c", "d", "e" ]
# a.replace([ "x", "y", "z" ]) #=> ["x", "y", "z"]
# a #=> ["x", "y", "z"]
def initialize_copy(other_ary)
if other_ary.kind_of? List
@_list = other_ary._list.dup
elsif other_ary.respond_to? :to_a
@_list = other_ary.to_a
else
raise ArgumentError, 'must be either a List or respond to `to_a`'
end
end
protected :initialize_copy
private
def perform_render
_list.reduce([]) do |array, value|
set_value_in_final_array(array, value)
array
end
end
def perform_before_validation
if self.class.prepare_value_for_elements?
_list.map! { |v| prepare_value_for_element(v) }
end
end
# transpose, assoc, rassoc , permutation, combination, repeated_permutation, repeated_combination, product, pack ?? => do not use the methods
end
class ListMethodDefiner
DESTRUCTIVE_SELF_OR_NIL = [:uniq!, :compact!, :flatten!, :shuffle!, :concat, :clear, :replace, :fill, :reverse!, :rotate!, :sort!, :keep_if]
DUP_METHODS = [:uniq, :compact, :flatten, :shuffle, :+, :-, :&, :|, :reverse, :rotate, :sort, :split, :in_groups, :in_groups_of, :from, :to]
DELEGATED_METHODS = [
# normal delegation
:frozen?, :[], :[]=, :at, :fetch, :first, :last, :<<, :push, :pop, :shift, :unshift, :insert, :length, :size, :empty?, :rindex, :join, :collect, :map, :select, :values_at, :delete, :delete_at, :delete_if, :reject, :include?, :count, :sample, :bsearch, :to_json_without_active_support_encoder, :slice, :slice!, :sort_by!, :shuffle, :shuffle!,
# for Enumerable
:each, :each_index,
# pose as array
:to_ary, :*,
# active support
:shelljoin, :append, :prepend, :extract_options!, :to_sentence, :to_formatted_s, :to_default_s, :to_xml, :second, :third, :fourth, :fifth, :forty_two, :to_param, :to_query,
# destructive that return selection
:collect!, :map!, :select!, :reject!,
]
def self.finalise(klass)
delegate_methods_to_list klass
pose_as_array klass
destructive_self_or_nil klass
dup_methods klass
end
private
def self.delegate_methods_to_list(klass)
klass.send :delegate, *DELEGATED_METHODS, to: :_list
end
def self.destructive_self_or_nil(klass)
# Destructive methods that return self or nil
DESTRUCTIVE_SELF_OR_NIL.each do |m|
klass.send :define_method, m do |*args, &block|
res = _list.send m, *args, &block
res.nil? ? nil : self
end
end
end
def self.pose_as_array(klass)
klass.send :alias_method, :index, :find_index
end
def self.dup_methods(klass)
# Non destructive methods that return a new object
DUP_METHODS.each do |m|
klass.send :define_method, m do |*args, &block|
dup.tap { |n| n.initialize_copy(n._list.send m, *args, &block) }
end
end
end
end
ListMethodDefiner.finalise List
end
| true |
3502594dcfb2139fde9a2f1d79d9bfa86dccb237
|
Ruby
|
bdezonia/ian
|
/analyses/IDM.rb
|
WINDOWS-1250
| 2,692 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
require InstallPath + 'AnalysisType'
require InstallPath + 'OutputSummary'
class Analysis
def initialize(engine,options,image,distUnit,areaUnit,args)
@image = image
@options = options
end
def run
backGround = -1
setting = @options.find("Background")
backGround = setting.dig_to_i(setting.value) if setting
eightNeighs = true
setting = @options.find("Neighborhood")
eightNeighs = false if setting and setting.value == "4"
pIJ = @image.file.pIJ(eightNeighs,backGround)
idm = 0.0
rows = pIJ.rows
cols = pIJ.cols
rows.each do | row |
cols.each do | col |
idm += pIJ[row,col] / (1.0 + (row-col).abs);
end
end
[OutputSummary.new(name,abbrev,outType,idm,units,family,precision)]
end
def help(verbose)
if verbose
["IDM - Inverse Difference Moment",
"",
" IDM reports the inverse difference moment of an image. It is a",
" measure of image texture. IDM ranges from 0.0 for an image that is",
" highly textured to 1.0 for an image that is untextured (such as an",
" image with a single class).",
"",
" Note: This measure uses an adjacency matrix. [Riitters 96] discusses",
" how the method used to create the adjacency matrix can have a large",
" impact upon resulting metrics.",
"",
" Definition: given t, an adjacency matrix between the classes present:",
" IDM = sum of all combinations of classes of:",
" (t(i,j)*t(i,j)) / (1 + (i-j)(i-j))",
"",
" Limitations: Since IDM relies on the magnitude of differences between",
" cell values it is only appropriate to compute it from interval data",
" (as opposed to nominal data).",
"",
" Reference: For more information see [Musick 91]",
"",
" [Musick 91] - Musick, and Grover 1991. Image Textural Measures as",
" Indices of Landscape Pattern, chapter in Quantitative Methods in",
" Landscape Ecology, Turner and Gardner (1991). Springer-Verlag.",
" New York, New York, USA.",
"",
" [Riitters 96] - Riitters, ONeill, et al. 1996. A note on contagion",
" indices for landscape analysis. Landscape Ecology 11:197-202."
]
else
["IDM - Inverse Difference Moment"]
end
end
def name
"Inverse Difference Moment"
end
def abbrev
"IDM"
end
def units
NoUnit
end
def precision
3
end
def outType
AnalysisType::IMAGE
end
def family
"scalar"
end
end
| true |
e1302444bcb37021f3d967bca2f59f77a6c1239f
|
Ruby
|
AllonsyThor/WDI
|
/happy_new_year.rb
|
UTF-8
| 123 | 3.21875 | 3 |
[] |
no_license
|
seconds_left = 10
while seconds_left > 0
puts(seconds_left)
seconds_left = seconds_left - 1
end
puts ("Happy New Year!")
| true |
f2449622693521fc8303953cd55d68bb5cc11c4c
|
Ruby
|
oh2gxn/advent_of_code
|
/2019/spec/rocket_module_spec.rb
|
UTF-8
| 626 | 2.5625 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require_relative '../fuel_counter_upper'
RSpec.describe RocketModule do
let :subject { described_class.new(mass) }
context 'with mass of 14' do
let :mass { 14 }
it 'requires 2 units of fuel' do
expect(subject.fuel_required).to eq(2)
end
end
context 'with mass of 1969' do
let :mass { 1969 }
it 'requires 966 units of fuel' do
expect(subject.fuel_required).to eq(966)
end
end
context 'with mass of 100756' do
let :mass { 100756 }
it 'requires 50346 units of fuel' do
expect(subject.fuel_required).to eq(50346)
end
end
end
| true |
084a877b8636ca380accd1f0778d1cc7cb7933d6
|
Ruby
|
hollyglot/code-exercises
|
/ruby-exercises/sketching_examples/product/ratings_calculation.rb
|
UTF-8
| 1,999 | 2.578125 | 3 |
[] |
no_license
|
require_relative '../sketches_init'
main_title 'Calculate Ratings'
log = Telemetry::MongoidLog
log.clear!
Benchmark.bmbm do |x|
x.report do
def update_rating(product)
rates = []
puts product.ratings.where(rater_type: 'Subscriber').to_a
puts "\n---------------------------------------------\n"
# # Old method
# product.ratings.where(rater_type: 'Subscriber').each{ |rating| rates << rating.results.values if rating.present? }
# rates.transpose.each_with_index { |values,i| rates[i] = (values.inject(0.0){ |sum, el| sum + el.to_i }.to_f / values.size).round(2) }
# puts rates.inspect
# rates
# New method
all_rates = []
rates_a = []
rates_b = []
rates_c = []
rates_d = []
rates_e = []
rates_f = []
rates_g = []
product.ratings.where(rater_type: 'Subscriber').each do |rating|
rates_a << rating.results.values[0] unless rating.results.values[0] == "0"
rates_b << rating.results.values[1] unless rating.results.values[1] == "0"
rates_c << rating.results.values[2] unless rating.results.values[2] == "0"
rates_d << rating.results.values[3] unless rating.results.values[3] == "0"
rates_e << rating.results.values[4] unless rating.results.values[4] == "0"
rates_f << rating.results.values[5] unless rating.results.values[5] == "0"
rates_g << rating.results.values[6] unless rating.results.values[6] == "0"
end
all_rates << rates_a << rates_b << rates_c << rates_d << rates_e << rates_f << rates_g
all_rates.each do |array|
if array.empty?
array << nil
end
end
puts all_rates.inspect
all_rates.each_with_index { |values,i| all_rates[i] = (values.inject(0.0){ |sum, el| sum + el.to_i }.to_f / values.size).round(2) }
puts all_rates.inspect
end
product = Product.find '51bba377f983f5535a0003a6'
update_rating(product)
end
end
log.output!
| true |
7ab5697f3d4191b5a6f5bba2201a19524f64f7b2
|
Ruby
|
Linzeur/codeable-exercises
|
/week-4/day-1/Brayan/Miniassigment/Exercises4.rb
|
UTF-8
| 320 | 3.203125 | 3 |
[] |
no_license
|
class HolidayPriorityQueue
def initialize
@list = []
end
def addGift gift
@list << gift
@list.length
end
def buyGift
return "" if @list.length == 0
gift = @list.min {|val1, val2| val1["priority"] <=> val2["priority"]}
@list.delete_at(@list.index(gift))
gift["gift"]
end
end
| true |
cef34f137f9b95ae7f556ec5637bd8dc0ae76090
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/hamming/4e98469217e547ad8c3285c2148f83aa.rb
|
UTF-8
| 207 | 3.125 | 3 |
[] |
no_license
|
class Hamming
def self.compute(strand_1, strand_2)
dif = 0
[strand_1.length, strand_2.length].min.times do |i|
dif += 1 unless strand_1[i] == strand_2[i]
end
return dif
end
end
| true |
2f8804ba08171d77c6aa5f959ed13a55c74a3786
|
Ruby
|
kentakodama/aa_prep
|
/Methods/review.rb
|
UTF-8
| 18,938 | 4 | 4 |
[] |
no_license
|
p "review these problems"
def FormattedDivision(num1,num2)
#float divide
quot = num1.fdiv(num2)
return "#{quot.to_s}" if quot < 1
num_array = quot.to_s.split(".")
decimal = num_array.last
integers = num_array.first.split("")
threes = []
while integers.length > 0
last_three = integers.pop(3).join("") "IMPORTANT!!!!!!!!!!"
threes.unshift(last_three)
end
p threes
joined_integers = threes.join(",")# must store conversion in var
return "#{joined_integers}.#{decimal}"
end
FormattedDivision(503394930, 43)
##########################
# USE CONDITIONAL TO BREAK OUT OF LOOP
def NearestSmallerValues(arr)
# results array
results = []
# loop forward
i = 0
while i < arr.length
if arr[0..i].any? {|num| num < arr[i]}
found = false # use this for the conditional below
j = i-1
while j >= 0 && !found #this is the smart way, dont use counter reset to escape
if arr[j] < arr[i]
results << arr[j]
found = true
end
j -= 1
end
else
results << -1
end
i += 1
end
results.join(" ")
end
def SimplePassword(str)
# 1. It must have a capital letter.
# 2. It must contain at least one number.
# 3. It must contain a punctuation mark.
# 4. It cannot have the word "password" in the string.
# 5. It must be longer than 7 characters and shorter than 31 characters.
return false if (str.downcase.include? "password") || !(str.length.between?(8, 30))
chars = str.split("")
return false if chars.all? {|char| char != char.to_i.to_s}
return false if (chars & ["!", ".", ",", "?", "/", ":", ";", "="]).empty?
return false if chars.all? {|char| char.downcase == char}
return true
end
def LongestConsecutive(arr)
# get unique sorted array
list = arr.uniq.sort
# loop through each
current = 0
i = 0
while i < list.length
j = i + 1
while j < list.length
if list[i..j] == (list[i]..list[j]).to_a "this is the important part"
count = list[i..j].length
if count > current
current = count
end
end
j += 1
end
i += 1
end
return current
# see subsequent j count
# have a most counter
end
# #
# ##
# ###
# ####
# #####
# ######
# if num 3
def staircase(num)
p "" if num == 0
# create loop that goes from 1 to num
# difference between put/p: adds \n and print: same line
i = 1
while i <= num
spaces = " "*(num-i)
hashes = "#"*i
p "#{spaces}#{hashes}"
i += 1
end
# prints string
# " " num - i + # i
# create end statements at same time as opening it
# if/end etc
end
m1 = [
[9,3,4],
[10,7,6],
[12,5,8]
]
# input m1, output [[3,4,5], [6,7,8], [9,10,12]]
def sort_matrix(matrix)
rows = matrix.length
arr = matrix.flatten.sort
#flatten to i d array
# sort array
# create matrix newly sorted
arr.each_slice(rows).to_a
#each slice method!!!!
end
#Rearrange characters in a string such that no two adjacent are same
# Given a string with repeated characters, task is rearrange characters in a string so that no two adjacent characters are same.
# Note : It may be assumed that the string has only lowercase English alphabets.
#Rearrange characters in a string such that no two adjacent are same
# Given a string with repeated characters, task is rearrange characters in a string so that no two adjacent characters are same.
# Note : It may be assumed that the string has only lowercase English alphabets.
def rearrange(str)
#must be arr
letters = str.split("")
#check whether possible
hash = Hash.new(0)
letters.each {|letter| hash[letter] += 1 }
most = hash.values.max
return "not possible" if most > (letters.length/2.0).ceil
#baaabb
letters.sort! p "this is important SORT to lump all together"
#aaabbb
i = 0
while i < letters.length
if letters[i] == letters[i+1]
j = i + 1
found = false
while j < letters.length && !found
if letters[j] != letters[i]
letters[i+1], letters[j] = letters[j], letters[i+1]
found = true
end
j += 1
end
end
i += 1
end
#loop thru and switch positions
letters.join("")
end
#how to find PRIME factors of a num
def get_factors(num)
factors = []
i = 2
while i <= num
if prime?(i) && num % i == 0
until num % i != 0
num /= i
factors << i
end
end
i += 1
end
factors
end
def prime?(num)
return true if num == 2
return false if num <= 1
i = 2
while i < num
if num % i == 0
return false
end
i += 1
end
return true
end
get_factors(213)
def koltaz(num)
results = [num]
until results.last == 1
if results.last.even?
num /= 2
else
num = (3*num) + 1
end
results << num
end
results.length
end
def StringScramble(str1,str2)
first = str1.split("")
second = str2.split("")
second.all? {|char| first.include? char}
end
def SimpleMode(arr)
hash = Hash.new(0)
arr.each {|num| hash[num] += 1}
hash.max_by {|k, v| v}[0]
#this will return the first max if there are two of the same value
end
SimpleMode([1, 2, 2, 1])
def CaesarCipher(str,num)
num = num.to_i
# create alphabet array
letters = str.split("")
alphabet = ("a".."z").to_a
results = []
# check index of each char, add num, and find index of that make sure to mod 26
i = 0
while i < letters.length
capital = false
if letters[i].upcase == letters[i]
capital = true
letters[i].downcase! #downcase HERE!!
end
#### DONT DOWNCASE HERE
char = alphabet[(alphabet.index(letters[i])+num) % 26]
if capital
char.upcase!
end
results << char
i += 1
end
results.join("")
# adjust for capitals, while checking index, figure out if upcase and downcase, upcase downcase if necessary
end
arr = [1, 2, 3, 4, 5, 6, 7, 8]
def reducer(arr)
until arr.length == 1
arr = arr.select do |el|
arr.index(el).even?
end
arr.reverse!
end
arr[0]
end
def substrings_count(string)
#return nil if empty
return nil if string == ""
# assume lowercase
combos = []
# get all substrings and push to combo array
chars = string.split("")
i = 0 #[a, b, c]
while i < chars.length
# i = 1
# j = 0
j = i # another way to do this, make sure j does go below i
while j < chars.length
substring = chars[i..j].join("")
combos << substring
j += 1
end
i += 1
end
# filter combo array for same first and last char
filtered = combos.select {|substring| substring[0] == substring[-1]}
# get the count for filtered array
filtered.length
end
p substrings_count("abcab") == 7
# Find largest word in dictionary by deleting some characters of given string
# Giving a dictionary and a string ‘str’, find the longest string in dictionary which can be formed by deleting some characters of the given ‘str’.
# Examples:
# Input : dict = ["ale", "apple", "monkey", "plea"]
# str = "abpcplea"
# Output : apple
# Input : dict = ["pintu", "geeksfor", "geeksgeeks", "forgeek"]
# str = "geeksforgeeks"
# Output : geeksgeeks
def longest_sub(dictionary, string)
# return nil if it doesnt exist
return nil if string == ""
longest = ""
# check each of the dictionary words
dictionary.each do |word|
# str = "helo" word = "hello"
# ["h", "e", "l"] == ["h", "e", "l", "l"] => false
duplicate = string.dup
count = 0
word.split("").each do |char|
i = 0
while i < duplicate.length
if char == duplicate[i]
count += 1
duplicate.slice!(i, 1)
end
i += 1
end
if count == word.length
if word.length > longest.length
longest = word
end
end
end
end
return "not possible" if longest.length == 0
longest
# if possible to delete the string char to make a particular word
# have a counter that updates accordingly for longest value
end
#################################
p "how to build out an array in a pattern"
#example 1
arithmetic = [arr[0]]
until arithmetic.length == arr.length
sum = arithmetic.last + diff
arithmetic << sum
end
#example 2
#fibanacci
def nth_fib(nth)
fib = [1, 2]
until fib.length >= nth
next_el = fib[-2..-1].reduce(:+)
fib << next_el
end
fib[-1]
end
def sum_sequence(nth)
return nil if nth < 1
results = [1, 2]
until results.length >= nth
next_element = results.reduce(:+)
results << next_element
end
results[-1]
end
##########################################################################
def nth_palindrome(n, k)
# catch false values
#helper function to check if palindrome
# start count at the lowest of k digits
start = 10**(k-1)
finish = 10**(k)
results = []
i = start
while i < finish
if palindrome?(i)
results << i
end
i += 1
end
return "Does not exist" if n > results.length
results[n-1]
end
def palindrome?(num)
str = num.to_s
reversed = str.reverse
if str == reversed
return true
else
return false
end
end
###################################
p "without division!!!"
def array_products(arr)
results = []
i = 0
while i < arr.length
copy = arr.dup
copy.slice!(i, 1)
product = copy.reduce(:*)
results << product
i += 1
end
results
end
####################################
def staircase(num)
p "" if num == 0
# create loop that goes from 1 to num
# difference between put/p: adds \n and print: same line
i = 1
while i <= num
spaces = " "*(num-i)
hashes = "#"*i
p "#{spaces}#{hashes}"
i += 1
end
# prints string
# " " num - i + # i
# create end statements at same time as opening it
# if/end etc
end
# Write a method that takes a string in and returns true if the letter
# "z" appears within three letters **after** an "a". You may assume
# that the string contains only lowercase letters.
#
# Difficulty: medium.
p "use restriction in conditional not the counter"
def nearby_az(string)
idx1 = 0
while idx1 < string.length
if string[idx1] != "a"
idx1 += 1
next
end
idx2 = idx1 + 1
while (idx2 < string.length) && (idx2 <= idx1 + 3) ### HERE
if string[idx2] == "z"
return true
end
idx2 += 1
end
idx1 += 1
end
return false
end
# Write a method that takes an array of numbers in. Your method should
# return the third greatest number in the array. You may assume that
# the array has at least three numbers in it.
#
# Difficulty: medium.
def third_greatest(nums)
first = nil
second = nil
third = nil
idx = 0
while idx < nums.length
value = nums[idx]
if first == nil || value > first
third = second
second = first
first = value
elsif second == nil || value > second
third = second
second = value
elsif third == nil || value > third
third = value
end
idx += 1
end
return third
end
def letter_count(str)
counts = Hash.new(0)
str.each_char do |char|
counts[char] += 1 unless char == " "
end
counts
end
p "is it possible to get any words in the arr by deleting char from the funky string"
def deleted?(arr, funky)
results = []
arr.each do |word|
combos = funky.split("").combination(word.length).to_a
combos.map!{|combo| combo.sort}
results << word if combos.include?(word.split("").sort)
end
results
end
deleted?(["hi", "char", "bye", "nice", "great", "thanks"], "jkdhnsrlkeica")
p "be careful for evaluation errors"
def third(arr)
first = nil
second = nil
third = nil
#iterate through each
arr.each do |num|
if first == nil || num > first #the order of the nil comparison must be first
third = second
second = first
first = num
elsif second == nil || num > second
third = second
second = num
elsif third == nil || num > third
third = num
end
end
# compare with first, second, third, and assign if the num is bigger than one or value is nil
#assign it num to that var and push first to second second to third etc
third
#return the third largest
end
def ClosestEnemy(arr)
# find the 1 index
start = arr.index(1)
# set right and left as same 1 index
right = start
left = start
#
#set count
count = 0
# until reach the ends of the array
until left == 0 && right == arr.length-1
left -= 1 if left != 0
right += 1 if right != arr.length-1
count += 1
if arr[left..right].include?(2)
return count
end
end
# check if the range created by right and left contains a 2
# if contains a 2 then return the count
# expand right and left limits unless at the outer edge
#every time expand, increment count
return 0
end
def ClosestEnemyII(strArr)
matrix = strArr
#find 1 coordinates
oneX = nil
oneY = nil
i = 0
while i < matrix.length
j = 0
while j < matrix[i].length
if matrix[i][j] == "1"
oneX = j
oneY = i
end
j += 1
end
i += 1
end
min_moves = nil
y = 0
while y < matrix.length
x = 0
while x < matrix[y].length
total_moves = 0
if matrix[y][x] == "2" #below is tricky, good technique to get min
y_moves = [(oneY-y).abs, (matrix.length - (oneY-y).abs)].min
x_moves = [(oneX-x).abs, (matrix[y].length - (oneX-x).abs)].min
total_moves = y_moves + x_moves
if min_moves == nil || total_moves < min_moves
min_moves = total_moves
end
end
x += 1
end
y += 1
end
min_moves
#loop thru to find all 2s
# when find 2
# get diff in x and y values and check how many moves
#get the abs diff between the x1 and x2 and subtract from length of x
# same with y
# have a min move that updates
end
def ThreeNumbers(str)
#for each word
words = str.split(" ")
#exactly three unique nums, check if num, if yes push to nums array, get uniq and see if same length, return false if not
words.each do |word|
#unique test
nums = []
i = 0
while i < word.length
if word[i] == word[i].to_i.to_s
nums << word[i]
end
i += 1
end
return false if nums.length != 3
return false if nums.uniq.length != 3
first = word.index(nums[0])
last = word.index(nums[2])
return false if last-first == 2
end
true
# within same iterationg, cant all be adjacent if the diff in index of first and last is 2 return false
# return true
end
def NumberAddition(str)
nums = []
#check if something number, if num start another loop while the next is a num, take the string of nums and join and TO I
i = 0
while i < str.length
if str[i] == str[i].to_i.to_s
digits = [str[i]]
j = i+1
while j < str.length && str[j] == str[j].to_i.to_s
digits << str[j]
j += 1
end
number = digits.join("").to_i
nums << number
i = j
else
i += 1
end
end
# num string to i
#check if its multi digit
# add those together]
nums.reduce(:+)
end
p "replace non letters with a space then split to words"
j = 0
while j < chars.length
if !alphabet.include? chars[j]
chars[j] = " "
end
j += 1
end
p "extract all nums from a string/nums with multiple digits"
def just_nums(str)
chars = str.split("")
results = []
i = 0
while i < chars.length
if chars[i] == chars[i].to_i.to_s
j = i + 1
while j < chars.length && chars[j] == chars[j].to_i.to_s
j += 1
end
results << chars[i...j].join("").to_i
i = j
else
i += 1 #this is important to increment in else
end
end
results
end
just_nums("hbjwerjn294u2pl2mr 3k2l3lm1nh444i2k3m44 3n22")
min = arr[0]
max = arr[0]
arr.each do |num|
if num < min #update both min and max within same loop
min = num
elsif num > max
max = num
end
end
def longest_letter_streak(str, search_letters)
greatest = 0
letters = str.split("")
i = 0
while i < letters.length do
if search_letters.include?(letters[i])
j = i + 1
while j < letters.length && search_letters.include(letters[j]) do
j += 1
end
streak = letters[i...j].length
if streak > greatest
greatest = streak
end
i = j
else
i += 1
end
end
greatest
end
def longetst(str, search_letters)
longest_streak = 0
current_streak = 0
letters_streak = ''
curr_lett_streak = ''
str.each_char do | char |
if search_lettes.include?(char)
current_streak += 1
curr_lett_streak += char
if current_streak > longest_streak
longest_streak = current_steak
letters_streak = curr_letters_streak
end
else
current_streak = 0
curr_letters_streak = ''
end
end
letters_streak
end
| true |
972cd68dae6f309021561cedcc2be81116182723
|
Ruby
|
vrybas/git-pcheckout
|
/lib/git-pcheckout/handle_branch.rb
|
UTF-8
| 887 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
class HandleBranch < Struct.new(:branch)
def initialize(branch)
self.branch = branch
end
def perform
if branch_exists_locally?
checkout_local_branch && pull_from_origin
else
fetch_from_origin && checkout_and_track_branch
end
end
private
def branch_exists_locally?
return true unless `git show-ref refs/heads/#{branch}`.empty?
end
def checkout_local_branch
puts "branch already exists. Checkout..."
system "git checkout #{branch}"
end
def pull_from_origin
puts "pull from origin..."
system "git pull origin #{branch}"
end
def fetch_from_origin
puts "no local branch found. Fetching from origin..."
system "git fetch origin"
end
def checkout_and_track_branch
puts "checkout and track branch..."
system "git checkout --track origin/#{branch}"
end
end
| true |
c485e30c54cf4fc47bfc0c00cb8907858474e967
|
Ruby
|
aliceFung/assignment_sinatra_blackjack
|
/helpers/blackjack.rb
|
UTF-8
| 2,233 | 3.578125 | 4 |
[] |
no_license
|
class Blackjack
attr_reader :game
SUITS= ["Hearts", "Clubs", "Spades", "Diamonds"]
def initialize(state = nil)
if state
@game = state
@deck = @game[0]
@hand = @game[1]
@dealer = @game[2]
else
@deck = generate_deck
@hand, @dealer = [], []
@game = [@deck, @hand, @dealer]
deal_initial
end
end
def generate_deck
deck = []
values = (1..13).to_a
52.times do |i|
deck << {"suit" => SUITS[i%4], "value" => values[i%13]}
end
deck.shuffle!
end
def deal_initial
2.times do |c|
@hand << @deck.pop
@dealer << @deck.pop
end
# blackjack? = true if hand_value(@hand) == 21
end
def hit
@hand << @deck.pop
end
def render
special_names = {1 => "Ace", 11 => "Jack", 12 => "Queen", 13 => "King"}
str = "Your Cards:<br>"
@hand.each do |card|
if special_names[card["value"]]
str += "#{special_names[card["value"]]} of #{card["suit"]}<br>"
else
str += "#{card["value"]} of #{card["suit"]}<br>"
end
end
str += "Dealer's Cards:<br>"
current_hand = @dealer
@dealer[1..-1].each do |card|
if special_names[card["value"]]
str += "#{special_names[card["value"]]} of #{card["suit"]}<br>"
else
str += "#{card["value"]} of #{card["suit"]}<br>"
end
end
str += "And an unknown card."
str
end
def hand_value(arr = @hand)
total = 0
aces = 0
#adding everything but the ace
arr.each do |card|
total += card["value"] if (2..10).include?(card["value"])
total += 10 if (11..13).include?(card["value"])
if card["value"] == 1
total += 11
aces += 1
end
end
while total > 21 && aces > 0
total -= 10
aces -= 1
end
total
end
def check_gameover?
bust?(@hand) || win?
end
def bust?(arr = @hand)
hand_value(arr) > 21
end
def win?
bust?(@dealer) || ((hand_value(@hand) && hand_value(@hand)<=21) > hand_value(@dealer))
end
def blackjack?
hand_value(@hand) > 21
end
def dealer_move
until hand_value(@dealer)> 17
@dealer << @deck.pop
end
end
end
| true |
05177f1125c1314e5f465451404b87ecedeac6bc
|
Ruby
|
kitop/suntimes
|
/parse.rb
|
UTF-8
| 1,091 | 2.59375 | 3 |
[] |
no_license
|
require 'bundler'
Bundler.require(:parser)
require 'open-uri'
require 'nokogiri'
require 'oj'
city = ARGV[0] || 51 # Buenos Aires
year = ARGV[1] || Date.today.year - 1
url = "http://www.timeanddate.com/worldclock/astronomy.html?n=%{city}&month=%{month}&year=%{year}&obj=sun&afl=-11&day=1"
days = []
(1..12).each do |month|
doc = Nokogiri::HTML( open(url % {month: month, year: year, city: city},
"Accept-Language" => "en-US,en;q=0.8,es;q=0.6") )
days += doc.at("table.spad").search("tbody tr").map do |tr|
# skip notes
tds = tr.search("td:not(.l)")
next if tds.empty?
date = Time.parse tds[0].text
sunrise = tds[1].text.sub('-', '').split(':').map(&:to_i)
#check for edge cases like iceland or greenland
sunset = tds[2].text.sub('-', '').split(':').map(&:to_i)
if sunset[0] == 0 or sunset.empty?
sunset = [23, 59]
end
{
date: date.to_i * 1000,
sunrise: sunrise,
sunset: sunset,
noon: tds[5].text.split(':').map(&:to_i)
}
end.compact
end
puts Oj.dump days, mode: :compat
| true |
afc0529f8e59c52395b410abfab5fa64542118cc
|
Ruby
|
Ronalechat/wdi17-homework
|
/ron_tan/week_04/calculator.rb
|
UTF-8
| 2,329 | 4 | 4 |
[] |
no_license
|
def get_user_choice
puts "(+) - Addition"
puts "(-) - Subtraction"
puts "(*) - Multiply"
puts "(/) - Divide"
puts "(**) - Exponent"
puts "(sr) - Square root"
puts "(q) - Quit"
print "Enter your selection: "
selection = gets.chomp
# if selection = '+'
# calculate =
end
def addition
print "What is the first number you would like to add: "
firstNum = gets.to_i
print "What is the second number you would like to add: "
secNum = gets.to_i
puts "The sum of #{firstNum} + #{secNum} = #{firstNum + secNum}"
end
def addition
print "What is the first number you would like to add: "
firstNum = gets.to_i
print "What is the second number you would like to add: "
secNum = gets.to_i
puts "The sum of #{firstNum} + #{secNum} = #{firstNum + secNum}"
end
def subtraction
print "What is the first number you would like to subtract: "
firstNum = gets.to_i
print "What is the second number you would like to substract: "
secNum = gets.to_i
puts "The total of #{firstNum} - #{secNum} = #{firstNum - secNum}"
end
def multiplication
print "What is the first number you would like to multiply: "
firstNum = gets.to_i
print "What is the second number you would like to multiply: "
secNum = gets.to_i
puts "The total of #{firstNum} * #{secNum} = #{firstNum * secNum}"
end
def division
print "What is the first number you would like to divide: "
firstNum = gets.to_i
print "What is the second number you would like to divide: "
secNum = gets.to_i
puts "The total of #{firstNum} / #{secNum} = #{firstNum / secNum}"
end
def exponent
print "What is the base number: "
firstNum = gets.to_i
print "To what number should the base be to the power of: "
secNum = gets.to_i
puts "The total of #{firstNum} ** #{secNum} = #{firstNum ** secNum}"
end
def square_root
print "What number would you like to find the square root of: "
firstNum = gets.to_i
puts "The square root of #{firstNum} = #{Math.sqrt(firstNum)}"
end
menu_choice = get_user_choice
until menu_choice == 'q'
case menu_choice
when '+'
addition
when '-'
subtraction
when '*'
multiplication
when '/'
division
when '**'
exponent
when 'sr'
square_root
end
# Perform the user's desired action
# Get the next operation
menu_choice = get_user_choice
end
| true |
2c3ee4e803460f726b002ffcd69585b560b4d521
|
Ruby
|
caueguedes/RubySandBox
|
/Metaprogramming Ruby 2/1.2 Mondeay The object model.rb
|
UTF-8
| 3,878 | 3.53125 | 4 |
[] |
no_license
|
## Refinements
module StringExtensions
refine String do
def reverse
"esrever"
end
end
end
module StringStuff
using StringExtensions
"my_string".reverse # => "esrever"
end
# ##Method Execution
# class MyClass
# def testing_self
# @var = 10
# my_method()
# self
# end
#
# def my_method
# @var = @var + 1
# end
# end
# obj = MyClass.new
# obj.testing_self # => obj.testing_self # => #<MyClass:0x007f93ab08a728 @var=11>
# def my_method
# temp = @x + 1
# my_other_method(temp)
# end
# ##Method Lookup
# require 'awesome_print'
#
# local_time = {:city => "Rome", :now => Time.now}
# ap local_time, :indent => 2
# # module M1; end
# #
# # module M2
# # include M1
# # end
# #
# # module M3
# # prepend M1
# # include M2
# # end
# #
# # M3.ancestors # => [M1, M2, M3]
#
# # module M1
# # def my_method
# # 'M1#my_method()'
# # end
# # end
# #
# # class C
# # include M1 # add the module above the including class
# # prepend M1 # add the module below the including class
# # end
# #
# # class D < C; end
# #
# # D.ancestors # => [D, C, M1, Object, Kernel, BasicObject]
#
# # class MyClass
# # def my_method; 'my_method()'; end
# # end
# #
# # class MySubClass < MyClass
# # end
# #
# # obj = MySubClass.new
# # obj.my_method() # => my_method()
# # obj.ancestors # => [D2, M2, C2, Object, Kernel, BasicObject]
# ## Namespacing
# # load('file.rb', true) Loads the file and address a anonymous namespace to it
# module BookWorm
# class Text
# end
# end
# ## CONSTANTS
# # module M
# # class C
# # module M2
# # Module.nesting # => [M::C::M2, M::C, M]
# # end
# # end
# # end
#
# # Y = 'a root-level constant'
# # module M
# # Y = 'a constant in M'
# # Y # => "a constant in M"
# # ::Y # => "a root-level constant"
# # end
#
# # module M
# # class C
# # X = 'a constant'
# # end
# # C::X # => "a constant"
# # end
# #
# # M::C::X # => "a constant"
#
# # module MyModule
# # MyConstant = 'Outer constant'
# #
# # class MyClass
# # MyConstant = 'Inner constant'
# # end
# # end
# ##INSIDE THE OBJECT MODEL
# class MyClass
# def my_method
# @v = 1
# end
# end
#
# obj = MyClass.new
# obj.class # => MyClass
# ## THE PROBLEM WITH OPEN CLASSES
# class Array
# def replace(original, replacement)
# self.map {|e| e == original ? replacement : e }
# end
# end
#
# def test_replace
# original = ['one', 'two', 'one', 'three']
# replaced = original.replace('one', 'zero')
# assert_equal ['zero', 'two', 'zero', 'three'], replaced
# end
#
# def replace(array, original, replacement)
# array.map {|e| e == original ? replacement : e }
# end
# def test_replace
# original = ['one', 'two', 'one', 'three']
# replaced = replace(original, 'one', 'zero')
# assert_equal ['zero', 'two', 'zero', 'three'], replaced
# end
# ## INSIDE CLASSES DEFINITIONS
# # # Money gem alters the Numeric class and add a method called money as follow
# # class Numeric
# # def to_money(currency = nil)
# # Money.from_numeric(self, currency || Money.default_currency)
# # end
# # end
#
# require 'money'
#
# bargain_price = Money.from_numeric(99, "USD")
# bargain_price.format # => "$99.00"
#
# standart_price = 100.to_money("USD")
# standart_price.format # => "$100.00"
#
## OPEN CLASSES
# class String
# def to_alphanumeric
# gsub(/[^\w\s]/, '')
# end
# end
#
# class StringExtensionsTest < Test::Unit::TestCase
# def test_strip_non_alphanumeric_characters
# assert_equal '3 the Magic Number', '#3, the *Magic, Number*?'.to_alphanumeric
# end
# end
#
# def to_alphanumeric(s)
# s.gsub(/[^|w\s]/, '')
# end
#
# class ToAlphanumericTest < Test::Unit::TestCase
# def test_strip_non_alphanumeric_characters
# assert_equal '3 the Magic Number', to_alphanumeric('#3, the *Magic, Number*?')
# end
# end
| true |
a1425ff447feaddf6077caf97db05188c9361383
|
Ruby
|
AnnaErshova/playlister-rb-web-0615-public
|
/lib/artist.rb
|
UTF-8
| 536 | 3.3125 | 3 |
[] |
no_license
|
class Artist
attr_accessor :name, :songs, :genres
@@artists = Array.new
def initialize
@songs = Array.new
@genres = Array.new
@@artists << self
end
def add_song(song)
@songs << song
@genres << song.genre
song.artist = self
song.genre.add_artist(self) unless song.genre == nil # Artist with songs can have a song added
end
# class methods
def self.all
@@artists
end
def self.count
@@artists.count
end
def self.reset_artists
@@artists.clear
end
end # end class
| true |
ec0fbdd2704d043693d14d05db7a98c7f890a49f
|
Ruby
|
eregon/Classes
|
/math/fixnum.rb
|
UTF-8
| 676 | 2.75 | 3 |
[] |
no_license
|
class Fixnum
# Lazy evaluation for: n * lambda { do_something_expensive }
# Short-circuit if n == 0 (and then n is of course a Fixnum)
# This is of course a very bad idea to re-define Fixnum * ...
# alias :_old_mul :*
# def * o
# if Proc === o
# return 0 if self == 0
# self * o.call
# else
# _old_mul(o)
# end
# end
end
if __FILE__ == $0
require "minitest/autorun"
require "benchmark"
class TestFixnum < MiniTest::Unit::TestCase
def test_mul
assert Benchmark.realtime { 2 * 0 * lambda { sleep 2; 1 } } < 0.1
assert_equal 0, 2 * 0 * lambda { sleep 2; 1 }
assert_equal 6, 2 * lambda { 3 }
end
end
end
| true |
1d37a2a103c067092f7e65d6a8abe4e7dd17db47
|
Ruby
|
Aldo510/Quora
|
/app/helpers/user.rb
|
UTF-8
| 320 | 2.65625 | 3 |
[] |
no_license
|
#Helpers para que sea mas facil saber que usuario esta en la session
helpers do
#Metodo para saber que usuario es
def current_user
if session[:user_id]
@current_user ||= User.find_by_id(session[:user_id])
end
end
#Metodo para saber si esta logeado
def logged_in?
!current_user.nil?
end
end
| true |
0ce276a7e40335605084539573413dc8d4dbd1c5
|
Ruby
|
sunatthegilddotcom/buildpacks-ci
|
/spec/lib/safe_execution_spec.rb
|
UTF-8
| 3,998 | 2.75 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
# encoding: utf-8
require 'spec_helper'
require_relative '../../lib/safe_execution'
describe SafeExecution do
include described_class
before do
allow(SafeExecution::Exiter).to receive(:exit_now)
end
describe '#exit_with_message' do
it 'prints a message' do
expect { exit_with_message 'Oh noooo' }.to output("Oh noooo\n").to_stdout
end
context 'default exit code' do
it 'exits with default error code' do
expect { exit_with_message 'Oh nooooo' }.to output("Oh nooooo\n").to_stdout
expect(SafeExecution::Exiter).to have_received(:exit_now).with(1)
end
end
context 'user-defined exit code' do
it 'returns specified error code' do
expect { exit_with_message 'Oh nooooo', 5 }.to output("Oh nooooo\n").to_stdout
expect(SafeExecution::Exiter).to have_received(:exit_now).with(5)
end
end
end
describe '#execute_with_console_logging!' do
context 'is passed a logger object' do
let(:logger) { Logger.new(STDOUT) }
it 'uses the logger to print messages' do
expect(logger).to receive(:info).with('Output from command { echo quack }:')
expect(logger).to receive(:info).with('quack')
execute_with_console_logging!('echo quack', logger)
end
end
context 'is not passed a logger object' do
it 'prints stdout of executed command' do
expect { execute_with_console_logging! 'echo quack', nil }.to output("quack\n").to_stdout
end
it 'prints stderr of executed command' do
expect { execute_with_console_logging! 'echo quack 1>&2', nil }.to output("quack\n").to_stdout
end
describe 'success exit code' do
it 'returns nil' do
expect do
expect(execute_with_console_logging! 'echo quack', nil).to eq nil
end.to output("quack\n").to_stdout
end
it 'does not exit' do
expect do
execute_with_console_logging! 'echo quack', nil
end.to output("quack\n").to_stdout
expect(SafeExecution::Exiter).to_not have_received(:exit_now)
end
end
describe 'failure exit code' do
it 'exits with the status code of the command' do
expect do
execute_with_console_logging! 'exit 2', nil
end.to output("exit 2 failed\n").to_stdout
expect(SafeExecution::Exiter).to have_received(:exit_now).with(2)
end
end
end
end
describe '#stdout_capture_with_console_logging!' do
context 'is passed a logger object' do
let(:logger) { Logger.new(STDOUT) }
it 'uses the logger to print messages' do
expect(logger).to receive(:info).with('Output from command { echo quack }:')
expect(logger).to receive(:info).with('quack')
expect do
expect(stdout_capture_with_console_logging!('echo quack', logger)).to eq ['quack']
end.to output("quack\n").to_stdout
end
end
context 'is not passed a logger object' do
describe 'successful execution' do
it 'returns the command output' do
expect do
expect(stdout_capture_with_console_logging! 'echo quack', nil).to eq ['quack']
end.to output("quack\n").to_stdout
expect(SafeExecution::Exiter).to_not have_received(:exit_now)
end
end
describe 'failed execution' do
it 'exits with the status code of the command' do
expect do
stdout_capture_with_console_logging! 'exit 2', nil
end.to output("exit 2 failed\n").to_stdout
expect(SafeExecution::Exiter).to have_received(:exit_now).with(2)
end
it 'returns nil' do
expect do
result = stdout_capture_with_console_logging! 'echo quack; echo quack; exit 2', nil
expect(result).to eq nil
end.to output("quack\nquack\necho quack; echo quack; exit 2 failed\n").to_stdout_from_any_process
end
end
end
end
end
| true |
48f1f8f2cb7d5efc5743dfc7bf6ebee5299733e9
|
Ruby
|
jesslns/chitter-challenge
|
/lib/user.rb
|
UTF-8
| 2,022 | 2.953125 | 3 |
[] |
no_license
|
# require 'bcrypt'
require 'pg'
require_relative 'database_connection'
class User
attr_reader :id, :name, :email, :username, :password
def initialize(id:, name:, email:, username:, password:)
@id = id
@name = name
@email = email
@username = username
@password = password
end
def self.all
result = DatabaseConnection.query("SELECT * FROM users;")
users = result.map do |user|
User.new(
id: user['id'],
name: user['name'],
username: user['username'],
email: user['email'],
password: user['password']
)
end
end
def self.create(name:, email:, username:, password:)
result = DatabaseConnection.query("INSERT INTO users (name, email, username, password) VALUES ('#{name}', '#{email}', '#{username}', '#{password}') RETURNING id, name, email, username, password;")
# encrypted_password = BCrypt::Password.create(password)
# result = connection.exec("INSERT INTO users (name, email, username, password) VALUES ('#{name}', '#{email}', '#{username}', '#{encrypted_password}') RETURNING id, name, email, username, password;")
User.new(id: result[0]['id'], name: result[0]['name'], email: result[0]['email'], username: result[0]['username'], password: result[0]['password'])
end
def self.find(id:)
result = DatabaseConnection.query("SELECT * FROM users WHERE id = '#{id}';")
User.new(id: result[0]['id'], name: result[0]['name'], email: result[0]['email'], username: result[0]['username'], password: result[0]['password'])
end
def self.authenticate(username:, password:)
# result = DatabaseConnection.query("SELECT * FROM users WHERE email = '#{email}'")
result = DatabaseConnection.query("SELECT * FROM users WHERE username = '#{username}';")
return unless result.any?
return unless result[0]['password'] == password
User.new(id: result[0]['id'], name: result[0]['name'], email: result[0]['email'], username: result[0]['username'], password: result[0]['password'])
end
end
| true |
088b56bb99c00f31e5ce75918965a842bc5f8f34
|
Ruby
|
oggy/looksee
|
/lib/looksee/columnizer.rb
|
UTF-8
| 2,107 | 3.09375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module Looksee
module Columnizer
class << self
#
# Arrange the given strings in columns, restricted to the given
# width. Smart enough to ignore content in terminal control
# sequences.
#
def columnize(strings, width)
return '' if strings.empty?
num_columns = 1
layout = [strings]
loop do
break if layout.first.length <= 1
next_layout = layout_in_columns(strings, num_columns + 1)
break if layout_width(next_layout) > width
layout = next_layout
num_columns += 1
end
pad_strings(layout)
rectangularize_layout(layout)
layout.transpose.map do |row|
' ' + row.compact.join(' ')
end.join("\n") << "\n"
end
private # -----------------------------------------------------
def layout_in_columns(strings, num_columns)
strings_per_column = (strings.length / num_columns.to_f).ceil
(0...num_columns).map{|i| strings[i*strings_per_column...(i+1)*strings_per_column] || []}
end
def layout_width(layout)
widths = layout_column_widths(layout)
widths.inject(0){|sum, w| sum + w} + 2*layout.length
end
def layout_column_widths(layout)
layout.map do |column|
column.map{|string| display_width(string)}.max || 0
end
end
def display_width(string)
# remove terminal control sequences
string.gsub(/\e\[.*?m/, '').length
end
def pad_strings(layout)
widths = layout_column_widths(layout)
layout.each_with_index do |column, i|
column_width = widths[i]
column.each do |string|
padding = column_width - display_width(string)
string << ' '*padding
end
end
end
def rectangularize_layout(layout)
return if layout.length == 1
height = layout[0].length
layout[1..-1].each do |column|
column.length == height or
column[height - 1] = nil
end
end
end
end
end
| true |
5b1e4c5a264a7aa0ce149fbdf890f170307efa96
|
Ruby
|
shwe-yuji/atcoder
|
/ABC161.rb
|
UTF-8
| 579 | 3.046875 | 3 |
[] |
no_license
|
# 問題1
nums = gets.split(" ").map(&:to_i)
nums[0], nums[1] = nums[1], nums[0]
nums[0], nums[2] = nums[2], nums[0]
puts "#{nums[0]} #{nums[1]} #{nums[2]}"
# 問題2
n, m = gets.split(" ").map(&:to_i)
vote = gets.split(" ").map(&:to_i)
rate = 1 / (4 * m).to_f
vote_all = vote.inject(:+)
border = rate * vote_all
judge = []
vote.each do |num|
if num >= border
judge << "Yes"
end
end
if judge.count("Yes") >= m
puts "Yes"
else
puts "No"
end
# 問題3(不正解)
N, K = gets.chomp.split(" ").map(&:to_i)
first = N % K
second = (first - K).abs
puts [first, second].min
| true |
d0e65bfd8e1930f195034a628e5dc6a9a7c003f7
|
Ruby
|
johnisaac/notionhub
|
/lib/rating_logic.rb
|
UTF-8
| 3,991 | 3.390625 | 3 |
[] |
no_license
|
# ModuleName: RatingLogic
# Purpose: to be included in all the models which needs rating
# Created: 10/12/2010
# Author: John Felix
# Methods:
# => id_value
# => increase_rating(object_id, user_id)
# => decrease_rating(object_id, user_id)
# => insert_rating(object_id, user_id, rating, type_detail)
# => update_rating(object, new_rating, type_detail)
module RatingLogic
def id_value
# Retrieve the [ClassName, primary_key] based on the name of the id value user input parameter
case
when self.name == "UserAnswers" then
return [Kernel.const_get("Answer"), "answer_id"]
when self.name == "UserQuestions" then
return [Kernel.const_get("Question"), "question_id"]
when self.name == "UserLinks" then
return [Kernel.const_get("Link"), "link_id"]
end
end
def increase_rating(object_id, user_id)
# After the retrieving the [ClassName, PrimaryKey] using the id_value method,
# use it to check whether the user has a record associated with the object,
# If the user has a record,
# => update the record
# Else
# => insert the record
type_detail = id_value()
@user_results = where("#{type_detail[1]} = ? AND user_id = ?", object_id, user_id).first # i need the id type value
if @user_results.nil?
return insert_rating(object_id, user_id, 1, type_detail)
else
return update_rating(@user_results, 1, type_detail)
end
end
def decrease_rating(object_id, user_id)
# After the retrieving the [ClassName, PrimaryKey] using the id_value method,
# use it to check whether the user has a record associated with the object,
# If the user has a record,
# => update the record
# Else
# => insert the record
type_detail = id_value()
@user_results = where("#{type_detail[1]} = ? AND user_id = ?", object_id, user_id).first # i need the id type value
if @user_results.nil?
return insert_rating(object_id, user_id, -1, type_detail)
else
return update_rating(@user_results, -1, type_detail)
end
end
def insert_rating(object_id, user_id, rating, type_detail)
# Create a new UserSpecific record using the input parameters
# Call the Change Rating specific to the class
# Save the new record and return [1 or -1, new rating value, rating message]
new_rating = new("#{type_detail[1]}".to_sym => object_id, :user_id => user_id, :rating => rating) # how are you going to pass the answer_id, question_id or link_id
change_rating = type_detail[0].change_rating(object_id, user_id, rating)# we need the class name here
if change_rating[0] == 1 && new_rating.save
return [1, change_rating[1], "Rating is updated."]
else
return [-1, change_rating[1], "Oops! There is a problem while updating the rating. Please try again later."]
end
end
def update_rating(object, new_rating, type_detail)
# Create a Old UserSpecific record using the input parameters
# Call the Change Rating specific to the class
# Update the altered record and return [1 or -1, new rating value, rating message]
# Update the Question's Rating and save it
if object.rating != Integer(new_rating)
object.rating = new_rating
change_rating = type_detail[0].change_rating(object["#{type_detail[1]}"], object.user_id, new_rating) # I need the class name here, may be i can check the object type
puts change_rating.inspect
if change_rating[0] == 1 && object.save
return [1, change_rating[1], "Rating is updated"]
else
return [-1, change_rating[1], "Oops! There is a problem while updating the rating. Please try again later."]
end
else
q_rating = type_detail[0].select("rating").where("id = ?",object["#{type_detail[1]}"]).first # I need the class name here,
return [-2, -2000, "You have already rated this..."]
end
end
end
| true |
f5d96a11113e3cfb0b579ca1fe03ccad9450f481
|
Ruby
|
mouchtaris/rubylib
|
/util/refinements/deep_freeze.rb
|
UTF-8
| 972 | 3.015625 | 3 |
[] |
no_license
|
module Util
module Refinements
module DeepFreeze
extend Util::Refiner
# "Deeply" freeze this object by calling {#deep_freeze}
# on all instance variables, elements or values.
#
# @return this object frozen
refinement target: ::Object, as: :deep_freeze, method:
def deep_freeze_for_Object
for var in instance_variables do
instance_variable_get(var).deep_freeze
end
freeze
end
# @!method Simple_deep_freeze
refinement target: ::String, as: :deep_freeze, method:
def deep_freeze_simple
freeze
end
# @!method Hash_deep_freeze
refinement target: ::Hash, as: :deep_freeze, method:
def deep_freeze_for_Hash
for key, val in self do
key.deep_freeze
val.deep_freeze
end
freeze
end
# @!method Array_deep_freeze
refinement target: ::Array, as: :deep_freeze, method:
def deep_freeze_for_Array
each &:deep_freeze
freeze
end
end#module DeepFreeze
end#module Refinements
end#module Util
| true |
1fc23ce6b269e66c0caf1ce86fda8f68a1063ad1
|
Ruby
|
gregDrizagit/oo-counting-sentences-web-103017
|
/lib/count_sentences.rb
|
UTF-8
| 373 | 3.921875 | 4 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
require 'pry'
class String
def sentence?
self.end_with?(".")
end
def question?
self.end_with?("?")
end
def exclamation?
self.end_with?("!")
end
def count_sentences
new_arr = self.split(" ")
arr = new_arr.select do |item|
item.end_with?("." , "?", "!")
end
arr.length
end
end
"one. two, three?".count_sentences
| true |
e2ff27301e9bc3352231aa4178c21c6785498f4f
|
Ruby
|
OneEyedEagle/EAGLE-RGSS3
|
/Event System/呼叫指定事件.rb
|
UTF-8
| 13,677 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
#==============================================================================
# ■ 呼叫指定事件 by 老鹰(https://github.com/OneEyedEagle/EAGLE-RGSS3)
# ※ 本插件需要放置在【组件-通用方法汇总 by老鹰】之下
#==============================================================================
$imported ||= {}
$imported["EAGLE-CallEvent"] = "1.2.2"
#==============================================================================
# - 2022.11.26.14 修复在战斗场景中卡死的bug
#==============================================================================
# - 本插件新增了在事件解释器中呼叫任意事件页并执行的事件脚本
# (与 呼叫公共事件 效果一致,会等待执行结束)
# - 本插件新增了事件页的插入,通过注释,可以把指定事件页的全部内容黏贴到注释位置
# (就仿佛一开始编写了这些指令,可以确保像是【事件消息机制】等能够找到标签)
#---------------------------------------------------------------------------
# 【使用:标准参数格式】
#
# - 在事件脚本中,使用如下指令调用指定事件页(整页调用):
#
# call_event(mid, eid, pid)
#
# 其中 mid 为编辑器中的地图序号(若填入 0,则为当前地图)
# eid 为编辑器中的事件序号(若填入 0,则为当前事件)
# pid 为事件编辑器中的页号(若填入 0,则为符合出现条件的最大页号)
#
# - 示例:
#
# · 事件脚本 call_event(0, 5, 0) 为调用当前地图5号事件的当前事件页,并等待结束
#
# · 事件脚本 call_event(1, 2, 1) 为调用1号地图2号事件的1号页,并等待结束
#
# - 注意:
#
# · 具体调用效果同默认事件指令的 呼叫公共事件,当前事件将等待该调用结束
#
# · 被调用的事件页中,全部的【本事件】将替换为当前事件
#
#---------------------------------------------------------------------------
# 【使用:标签字符串格式】
#
# - 在事件脚本中,使用如下指令调用指定事件页:
#
# t = "tags"
# call_event(t)
#
# 其中 tags 为以下语句的任意组合,用空格分隔
# (等号左右可以添加冗余空格)
#
# mid=数字 → 数字 替换为编辑器中的地图序号
# (若填入 0,或不写该语句,则取当前地图)
# (若填入 -1,则取公共事件)
# eid=数字 → 数字 替换为编辑器中的事件序号
# (若填入 0,或不写该语句,则取当前事件)
# pid=数字 → 数字 替换为事件编辑器中的页号
# (若填入 0,或不写该语句,则取符合出现条件的最大页号)
#
# (若使用了【事件互动扩展 by老鹰】,可使用下述标签)
# sym=字符串 → 字符串 替换为目标事件中的互动标签
# (若不写该语句,默认执行整个事件页)
#
# - 示例:
#
# · 事件脚本 t = "mid=1 eid=3 pid=2"; call_event(t)
# 为调用1号地图3号事件的2号页的全部指令,并等待结束
# 此句与 call_event(1,3,2) 效果相同
#
# · 事件脚本 t = "eid=5 sym=调查"; call_event(t)
# 若使用了【事件互动扩展 by老鹰】:
# 为调用当前地图5号事件的当前事件页中的【调查】互动,并等待结束
# 若未使用:
# 为调用当前地图5号事件的当前事件页的全部指令,并等待结束
#
#---------------------------------------------------------------------------
# 【使用:脚本中任意位置】
#
# - 在脚本中,使用如下指令调用指定事件页(参数与上述一致):
#
# EAGLE.call_event(mid, eid, pid)
#
# EAGLE.call_event(t)
#
# - 示例:
#
# · 脚本中编写 EAGLE.call_event(1,3,2)
# 为在当前场景调用1号地图3号事件的2号页的全部指令,并等待结束
#
# - 注意:
#
# · 当不在地图上时,调用事件时,部分与地图相关的指令会被忽略
#
# 以下指令将被忽略:
# 场所移动、地图卷动、设置移动路径、显示动画、显示心情图标、集合队伍成员
#
# · 被调用的事件页中,全部的【本事件】依然为原始事件
#
#---------------------------------------------------------------------------
# 【使用:事件页替换】
#
# - 考虑到有些插件会依据事件页中存在的指令来进行设置,比如【事件消息机制 by老鹰】,
# 就是检查事件页的指令列表中,是否含有指定名称的“标签”。
#
# 但呼叫指定事件只能保证事件的执行,而无法帮助这些插件进行它们的设置。
#
# 因此增加该功能,可以在事件生成时,依据指定注释指令进行指令的替换,
# 把目标事件页完整的复制到该注释的位置处,就仿佛一开始便写了这一些指令在事件页中。
#
# - 在事件指令-注释中,编写该样式文本:
#
# 事件页替换|tag字符串
#
# 其中 事件页替换 为固定的识别文本,不可缺少
# 其中 tag字符串 与上述介绍保持一致
#
# - 示例:
#
# · 事件注释 “事件页替换|mid=1 eid=2 pid=1”
# 为在该注释位置处,插入1号地图2号事件的1号页的全部指令
#
# - 注意:
#
# · 请确保每个注释指令中,只含有一个事件页替换
#
#=============================================================================
module EAGLE
#--------------------------------------------------------------------------
# ○【常量】事件指令-注释 中进行事件页替换的文本
#--------------------------------------------------------------------------
COMMENT_PAGE_REPLACE = /^事件页替换 *?\| *?(.*)/mi
#--------------------------------------------------------------------------
# ○ 处理事件指令的替换
#--------------------------------------------------------------------------
def self.process_page_replace(event, list)
index = 0
while(true)
index_start = index
command = list[index]
index += 1
break if command.code == 0
next if command.code != 108
# 获取完整的注释内容
comments = [command.parameters[0]]
while list[index + 1] && list[index + 1].code == 408
index += 1
comments.push(list[index].parameters[0])
end
index_end = index
t = comments.inject { |t, v| t = t + "\n" + v }
# 检查是否存在事件页替换
t =~ EAGLE::COMMENT_PAGE_REPLACE
if $1
ps = $1.strip # tags string # 去除前后空格
h = call_event_args([ps])
next if h == nil
page = call_event_page(h)
list2 = page.list
# 去除结尾的空指令
list2.pop if list2[-1].code == 0
# 加入到当前列表
list.insert(index, list2)
list.flatten!
# 删去注释指令
d = index_end - index_start
d.times { list.delete_at(index_start) }
end
end
return list
end
#--------------------------------------------------------------------------
# ● 呼叫指定事件 - 解析参数
#--------------------------------------------------------------------------
def self.call_event_args(args)
h = {}
if args.size == 1
# 当只传入1个参数时,认定为tag字符串
_h = EAGLE_COMMON.parse_tags(args[0])
h.merge!(_h)
h[:mid] = h[:mid].to_i if h[:mid]
h[:eid] = h[:eid].to_i if h[:eid]
h[:pid] = h[:pid].to_i if h[:pid]
elsif args.size == 3
# 当传入3个参数时,认定为 地图ID,事件ID,页ID
h[:mid] = args[0]
h[:eid] = args[1]
h[:pid] = args[2]
else
# 否则返回nil,在调用处进行报错提示
return nil
end
return h
end
#--------------------------------------------------------------------------
# ● 呼叫指定事件 - 获取事件页
#--------------------------------------------------------------------------
def self.call_event_page(h)
event = nil
if h[:mid] == -1
return $data_common_events[h[:eid]]
end
if h[:mid] != $game_map.map_id
map = EAGLE_COMMON.get_map_data(h[:mid])
event_data = map.events[h[:eid]] rescue return
event = Game_Event.new(h[:mid], event_data)
else
event = $game_map.events[h[:eid]] rescue return
end
page = nil
if h[:pid] == nil || h[:pid] == 0
page = event.find_proper_page
else
page = event.event.pages[h[:pid]-1] rescue return
end
return page
end
#--------------------------------------------------------------------------
# ● 呼叫指定事件 - 任意时刻调用
#--------------------------------------------------------------------------
def self.call_event(*args)
h = EAGLE.call_event_args(args)
if h == nil
p "【警告】执行 EAGLE.call_event 时发现参数数目有错误!"
p "EAGLE.call_event 来自于脚本【呼叫指定事件 by老鹰】," +
"请仔细阅读脚本说明并进行修改!"
return false
end
h[:mid] = $game_map.map_id if h[:mid] == nil || h[:mid] == 0
page = EAGLE.call_event_page(h)
return if page == nil
# 实际执行
if SceneManager.scene_is?(Scene_Map) # 如果在地图上
interpreter = Game_Interpreter.new
else # 如果在其他场景
interpreter = Game_Interpreter_EagleCallEvent.new
message_window = Window_EagleMessage.new if $imported["EAGLE-MessageEX"]
message_window ||= Window_Message.new
end
interpreter.setup(page.list, h[:eid])
if $imported["EAGLE-EventInteractEX"]
interpreter.event_interact_search(h[:sym]) if h[:sym]
end
if SceneManager.scene_is?(Scene_Map) # 如果在地图上
while true
SceneManager.scene.update
interpreter.update
break if !interpreter.running?
end
else # 如果在其他场景
while true
SceneManager.scene.update_basic
interpreter.update
message_window.update
break if !interpreter.running?
end
message_window.dispose if message_window
end
return true
end
end
#===============================================================================
# ○ 定制的Game_Interpreter
#===============================================================================
class Game_Interpreter_EagleCallEvent < Game_Interpreter
#--------------------------------------------------------------------------
# ● 场所移动
#--------------------------------------------------------------------------
def command_201
end
#--------------------------------------------------------------------------
# ● 地图卷动
#--------------------------------------------------------------------------
def command_204
end
#--------------------------------------------------------------------------
# ● 设置移动路径
#--------------------------------------------------------------------------
def command_205
end
#--------------------------------------------------------------------------
# ● 显示动画
#--------------------------------------------------------------------------
def command_212
end
#--------------------------------------------------------------------------
# ● 显示心情图标
#--------------------------------------------------------------------------
def command_213
end
#--------------------------------------------------------------------------
# ● 集合队伍成员
#--------------------------------------------------------------------------
def command_217
end
end
#===============================================================================
# ○ Game_Interpreter
#===============================================================================
class Game_Interpreter
#--------------------------------------------------------------------------
# ● 呼叫指定事件
#--------------------------------------------------------------------------
def call_event(*args)
h = EAGLE.call_event_args(args)
if h == nil
p "【警告】执行 #{@map_id} 号地图 #{@event_id} 号事件中" +
"事件脚本 call_event 时发现参数数目有错误!"
p "事件脚本 call_event 来自于脚本【呼叫指定事件 by老鹰】," +
"请仔细阅读脚本说明并进行修改!"
return false
end
h[:mid] = $game_map.map_id if h[:mid] == nil || h[:mid] == 0
h[:eid] = @event_id if h[:eid] == nil || h[:eid] == 0
page = EAGLE.call_event_page(h)
return false if page == nil
# 实际调用
child = Game_Interpreter.new(@depth + 1)
child.setup(page.list, @event_id)
if $imported["EAGLE-EventInteractEX"]
child.event_interact_search(h[:sym]) if h[:sym]
end
child.run
return true
end
end
#===============================================================================
# ○ Game_Event
#===============================================================================
class Game_Event < Game_Character
attr_reader :event
#--------------------------------------------------------------------------
# ● 设置事件页的设置
#--------------------------------------------------------------------------
alias eagle_page_replace_setup_page_settings setup_page_settings
def setup_page_settings
@list = list = EAGLE.process_page_replace(self, @page.list)
eagle_page_replace_setup_page_settings
@list = list # 覆盖掉其它插件可能的修改
end
end
| true |
4c3b7aa85883dc9b263fa104cc830995c4a42c59
|
Ruby
|
ngodi/rest-client
|
/bing_search.rb
|
UTF-8
| 783 | 2.75 | 3 |
[] |
no_license
|
require 'rest-client'
class Bing
attr_accessor :search_query, :search_results
URL = "https://www.bing.com/search"
def initialize(search_query)
@search_query = earch_query
end
def remove_spaces
@search_query.gsub!(/\s/, '+')
end
def search
remove_spaces
@search_results = RestClient.get URL, {params: {q: @search_query}}
end
def display_search_results
p search_results.code
p search_results.cookies
p search_results.headers
p search_results.body
end
def display_response_cookies
p @search_results.cookies
end
def display_response_code
p @search_results.code
end
def display_response_headers
p @search_results.headers
end
def display_response_body
p @search_results.body
end
end
| true |
5ece9a6f4c8b2270e1746a8de0a1975a8f809e1f
|
Ruby
|
Jacob-Brink/214
|
/projects/08/script.rb
|
UTF-8
| 8,361 | 3.578125 | 4 |
[] |
no_license
|
Script started on 2020-04-15 17:04:04-0400
]0;jacob@DESKTOP-TMA4I98: ~/214/projects/08/ruby[01;32mjacob@DESKTOP-TMA4I98[00m:[01;34m~/214/projects/08/ruby[00m$ cat temp_tester.rb
# temp_tester.rb tests class Temperature and its operations
#
# Begun by: Dr. Adams, for CS 214 at Calvin College.
# Completed by: Jacob Brink
# Date: 4/15/2020
# Project: 8
####################################################
require "./temperature.rb"
def temp_tester
puts "Enter baseTemp: "
baseTemp = Weather::Temperature.read()
puts "Enter limitTemp: "
limitTemp = Weather::Temperature.read()
puts "Enter stepValue: "
stepValue = gets.to_f
while (baseTemp.equals(limitTemp)) or (stepValue > 0 ? baseTemp.lessthan(limitTemp) : limitTemp.lessthan(baseTemp))
print "#{baseTemp.getFahrenheit()} #{baseTemp.getCelsius()} #{baseTemp.getKelvin()}\n"
baseTemp = baseTemp.raise(stepValue)
end
# Handle user failure in a nice way
rescue StandardError => error
puts error
end
if __FILE__ == $0
temp_tester()
end
]0;jacob@DESKTOP-TMA4I98: ~/214/projects/08/ruby[01;32mjacob@DESKTOP-TMA4I98[00m:[01;34m~/214/projects/08/ruby[00m$ cat temperature.rb
# temperature.rb tests class Name and its operations
#
# Begun by: Dr. Adams, for CS 214 at Calvin College.
# Completed by: Jacob Brink
# Date: 4/15/2020
# Project: 8
####################################################
module Weather
class Temperature
# Invalid_Temperature is a custom Standard Error for invalid temperatures
########################################################################
class Invalid_Temperature < StandardError
end
# Invalid_Scale is a custom Standard Error for invalid scales
########################################################################
class Invalid_Scale < StandardError
end
# isValid() checks if given parameters are valid
# Input: degrees, a float; scale, a string
# Output: throws Invalid_Temperature if below 0 K
# throws Invalid_Scale if given scale does
# exist
######################################################
def isValid(degrees, scale)
invalid_temp = "#{degrees} #{scale} is below 0 K"
invalid_scale = "Temperature Scale #{scale} is invalid"
if scale =~ /f/ then
Kernel::raise Invalid_Temperature, invalid_temp if degrees < -459.67
elsif scale =~ /c/ then
Kernal::raise Invalid_Temperature, invalid_temp if degrees < -273.15
elsif scale =~ /k/ then
Kernel::raise Invalid_Temperature, invalid_temp if degrees < 0
else
Kernel::raise Invalid_Scale, invalid_scale
end
end
# initialize() intializes Temperature object
# Input: degrees, a float; scale, a string
# Returns: Temperature object if valid parameters
# else exception
######################################################
def initialize(degrees, scale)
scale = scale.downcase
isValid(degrees, scale)
@degrees, @scale = degrees, scale
end
attr_reader :degrees, :scale
# raise()
# Input: delta, a float
# Returns: new Temperature with risen degrees
######################################################
def raise(delta)
Temperature.new(@degrees + delta, @scale)
end
# lower()
# Input: delta, a float
# Returns: new Temperature with delta degrees less
# or exception if new temperature is lower
# than 0 K
######################################################
def lower(delta)
Temperature.new(@degrees - delta, @scale)
end
# getFahrenheit() returns Fahrenheit temperature
# Input: none
# Returns: new Temperature with same temperature
# in new scale
######################################################
def getFahrenheit()
if scale =~ /f/ then
Temperature.new(@degrees, @scale)
elsif scale =~ /c/ then
Temperature.new(@degrees * (9.0/5) + 32, "f")
else
Temperature.new((@degrees + 273.15) * (9.0/5) + 32, "f")
end
end
# getCelsius() returns Celsius temperature
# Input: none
# Returns: new Temperature with same temperature
# in new scale
######################################################
def getCelsius()
if scale =~ /f/ then
Temperature.new((@degrees-32)*(5.0/9), "c")
elsif scale =~ /c/ then
Temperature.new(@degrees, @scale)
else
Temperature.new(@degrees - 273.15, "c")
end
end
# getKelvin() returns Kelvin temperature
# Input: none
# Returns: new Temperature with same temperature
# in new scale
######################################################
def getKelvin()
if scale =~ /f/ then
Temperature.new((@degrees-32)*(5.0/9)+273.15, "k")
elsif scale =~ /c/ then
Temperature.new(@degrees + 273.15, "k")
else
Temperature.new(@degrees, @scale)
end
end
# read() reads in user input
# Input: none
# Returns: new Temperature according to user input
# if not valid, an exception
######################################################
def self.read()
rawText = gets
splitText = rawText.split
degrees = splitText[0].to_f
scale = splitText[1]
Temperature.new(degrees, scale)
end
# to_s() allows for pretty printing of object
# Input: none
# Returns: formatted String with degrees and scale
######################################################
def to_s
"#{@degrees.round(2)} #{@scale}"
end
# equals() shows equality
# Input: other_object
# Returns: true if equal, else false
######################################################
def equals(other_object)
if !(other_object.instance_of? Temperature) then
false
else
(other_object.getKelvin().degrees == self.getKelvin().degrees)
end
end
# lessthan() shows inequality
# Input: other_object
# Returns: true if self is less than other
######################################################
def lessthan(other_object)
if !(other_object.instance_of? Temperature) then
false
else
(self.getKelvin().degrees < other_object.getKelvin().degrees)
end
end
end
end
]0;jacob@DESKTOP-TMA4I98: ~/214/projects/08/ruby[01;32mjacob@DESKTOP-TMA4I98[00m:[01;34m~/214/projects/08/ruby[00m$ ruby temp_tester.rb
Enter baseTemp:
12 F
Enter limitTemp:
40 F
Enter stepValue:
2
12.0 f -11.11 c 262.04 k
14.0 f -10.0 c 263.15 k
16.0 f -8.89 c 264.26 k
18.0 f -7.78 c 265.37 k
20.0 f -6.67 c 266.48 k
22.0 f -5.56 c 267.59 k
24.0 f -4.44 c 268.71 k
26.0 f -3.33 c 269.82 k
28.0 f -2.22 c 270.93 k
30.0 f -1.11 c 272.04 k
32.0 f 0.0 c 273.15 k
34.0 f 1.11 c 274.26 k
36.0 f 2.22 c 275.37 k
38.0 f 3.33 c 276.48 k
40.0 f 4.44 c 277.59 k
]0;jacob@DESKTOP-TMA4I98: ~/214/projects/08/ruby[01;32mjacob@DESKTOP-TMA4I98[00m:[01;34m~/214/projects/08/ruby[00m$ ruby temp_tester.rb
Enter baseTemp:
40 F
Enter limitTemp:
20 20 F
Enter stepValue:
-5
40.0 f 4.44 c 277.59 k
35.0 f 1.67 c 274.82 k
30.0 f -1.11 c 272.04 k
25.0 f -3.89 c 269.26 k
20.0 f -6.67 c 266.48 k
]0;jacob@DESKTOP-TMA4I98: ~/214/projects/08/ruby[01;32mjacob@DESKTOP-TMA4I98[00m:[01;34m~/214/projects/08/ruby[00m$ ruby temp_tester.rb
Enter baseTemp:
- -2 K
-2.0 k is below 0 K
]0;jacob@DESKTOP-TMA4I98: ~/214/projects/08/ruby[01;32mjacob@DESKTOP-TMA4I98[00m:[01;34m~/214/projects/08/ruby[00m$ ruby temp_tester.rb
Enter baseTemp:
-2000 F
-2000.0 f is below 0 K
]0;jacob@DESKTOP-TMA4I98: ~/214/projects/08/ruby[01;32mjacob@DESKTOP-TMA4I98[00m:[01;34m~/214/projects/08/ruby[00m$ ruby temp_tester.rb
Enter baseTemp:
200 Y
Temperature Scale y is invalid
]0;jacob@DESKTOP-TMA4I98: ~/214/projects/08/ruby[01;32mjacob@DESKTOP-TMA4I98[00m:[01;34m~/214/projects/08/ruby[00m$ exit
Script done on 2020-04-15 17:08:10-0400
| true |
8124cef415699095ed51e18d72b7d4df317b1d12
|
Ruby
|
mainangethe/learn-to-code-w-ruby-bp
|
/old_sections/float_methods.rb
|
UTF-8
| 231 | 3.1875 | 3 |
[] |
no_license
|
p 10.5.to_i
p 10.5
#floor method
p 10.5.floor
p 10.5.ceil
#round method
p 10.345.round(2)
p 10.34554.round
p 3.6.round
p 3.4.round
#abs method
# always going to be positive
#distance from zero
p 35.67.abs
p -10.abs
p 304.abs
| true |
c9fd546f7254f872d01e24dff8e8c201e8772b19
|
Ruby
|
devery512/ruby_fun
|
/ruby_methods/classes.rb
|
UTF-8
| 3,937 | 4.125 | 4 |
[] |
no_license
|
class Dog
def initialize(name,health,stamina,strength)
@name = name
@health = health
@stamina = stamina
@strength = strength
end
def bark
puts "Woof Woof! The dog barks!"
@stamina -= 5
@strength += 3
end
def fetch
puts "The dog fetchs the ball"
@stamina -=7
end
end
class Fox
def initalize(name,health,stamina,strength)
@name = name
@health = health
@stamina = stamina
@strength = strength
end
def bark
puts "Woof Woof! The dog barks!"
@stamina -= 5
@strength += 3
end
def fetch
puts "The dog fetchs the ball"
@stamina -=7
puts "stamina decresed, stamina is now #{@stamina.to_s}"
end
end
dog1 = Dog.new("Tyrone",100,70,30)
fox1 = Fox.new()
dog1.fetch()
#Excercise2
class Human
def initialize(name,health,stamina,weight,thirst)
@name = name
@health = health
@stamina = stamina
@weight = weight
@thirst = thirst
end
def run
puts "#{@name} went for a run."
puts "Resulting in a loss of stamina and weight."
puts "And an increase in thirst."
@stamina -= 15
@weight -= 2
@thirst += 10
puts "Stamina is now #{@stamina},"
puts "weight"
end
def sleep
puts "#{@name} fell asleep."
@stamina += 30
puts "Stamina has increased, stamina is now #{@stamina.to_s}"
end
def fall
puts "#{@name} fell hard resulting in a decrease of health"
@health -= 5
puts "Health is now #{@health.to_s}"
end
end
player1 = Human.new("James",100,50,50,12)
player2 = Human.new("Jarred",100,80,50,30)
player3 = Human.new("Brittani",100,70,50,25)
player4 = Human.new("June",100,85,50,30)
puts "Pick a character: "
puts "Your options are player1,player2,player3, and player4"
player = gets.chomp
if player =
end
player1.fall()
player2.sleep()
player3.run()
player4.fall()
#play a game
class Human
def initialize(name,health,stamina,weight,thirst)
@name = name
@health = health
@stamina = stamina
@weight = weight
@thirst = thirst
end
def run
puts "#{@name} went for a run."
puts "Resulting in a loss of stamina and weight."
puts "And an increase in thirst."
@stamina -= 15
@weight -= 2
@thirst += 10
puts "Stamina is now #{@stamina},"
puts "weight"
end
def sleep
puts "#{@name} fell asleep."
@stamina += 30
puts "Stamina has increased, stamina is now #{@stamina.to_s}"
end
def fall
puts "#{@name} fell hard resulting in a decrease of health"
@health -= 5
puts "Health is now #{@health.to_s}"
end
end
player1 = Human.new("James",100,50,50,12)
player2 = Human.new("Jarred",100,80,50,30)
player3 = Human.new("Brittani",100,70,50,25)
player4 = Human.new("June",100,85,50,30)
puts "Pick a character: "
puts "Your options are player1, player2, player3, and player4"
player = gets.chomp
if player == "player1"
puts "Welcome player1!"
puts "Did Player1 run, sleep, or fall?"
answer = gets.chomp
if answer == "fall"
puts player1.fall()
elsif answer == "sleep"
puts player1.sleep()
elsif answer == "run"
puts player1.run()
end
end
#player1.fall()
#player2.sleep()
#player3.run()
#player4.fall()
#Exercise 3
class Vehicle
def initialize(brand,model,year,color,body,tire_health,oil_health,brake_health,fuel_level)
@brand = brand
@model = model
@year = year
@color = color
@body = body
@tire_health = tire_health
@oil_health = oil_health
@brake_health = brake_health
@fuel_level = fuel_level
end
def go_to_work
@fuel_level -= 5
@brake_health -= 3
@tire_health -= 1
end
def oil_change
@oil_health += 80
@tire_health += 10
end
def tire_change
@tire_health += 100
end
def paint_job
@color += 100
end
def road_trip
@fuel_level -= 80
@tire_health -= 20
@oil_health -= 10
end
end
car1 = Vehicle.new("","")
car2 = Vehicle.new("","",)
car3 = Vehicle.new()
car4 = Vehicle.new()
| true |
b8bc13ae47d1a8e086b2b247858ec040363e06de
|
Ruby
|
votiakov/expert-octo-memory
|
/app/models/promotion.rb
|
UTF-8
| 955 | 2.6875 | 3 |
[] |
no_license
|
# == Schema Information
#
# Table name: promotions
#
# id :integer not null, primary key
# kind :string not null
# value :float
# code :string
# can_combine :boolean default(FALSE)
# quantity :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Promotion < ApplicationRecord
KINDS = [:percent, :amount, :product]
# has_many :promotion_items
# has_many :items, through: :promotion_items
has_one :promotion_item
has_one :item, through: :promotion_item
scope :percents, -> { where(kind: :percent) }
scope :amounts, -> { where(kind: :amount) }
scope :products, -> { where(kind: :product) }
scope :codes, -> { where.not(kind: :product) }
scope :not_combinable, -> { codes.where(can_combine: false) }
def price
item.try(:price)
end
def full_info
'Buy ' + quantity.to_s + ' ' + item.name + ' for £' + value.to_s
end
end
| true |
7fd5026db630d1561df480c1fd6f4ca9d9d1f398
|
Ruby
|
mbarrins/module-one-final-project-guidelines-london-web-051319
|
/app/models/event.rb
|
UTF-8
| 916 | 2.59375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Event < ActiveRecord::Base
has_many :user_events
has_many :users, through: :user_events
has_many :reviews
has_many :event_dates
belongs_to :segment
belongs_to :genre
belongs_to :sub_genre
def average_rating
(self.reviews.inject(0){|sum, review| sum + review.rating}/self.reviews.length.to_f).round(2)
end
def display_reviews
if reviews.length == 0
puts "There are no reviews for this event"
else
puts "Overall rating: #{average_rating}"
puts "--------------------------"
reviews.each.with_index(1) do |review, i|
puts "Review #{i}: #{review.event.event_name}"
puts "Rating: #{review.rating}"
puts "Review: #{review.review}"
puts "Reviewed by: #{review.user.first_name}"
puts "--------------------------"
end
end
end
end
| true |
4571fdb41486696a0a43209563fc588b4db322d5
|
Ruby
|
MaximeAlexandre/Exercism
|
/ruby/difference-of-squares/difference_of_squares.rb
|
UTF-8
| 261 | 3.734375 | 4 |
[] |
no_license
|
class Squares
attr_reader :square_of_sum, :sum_of_squares
def initialize(number)
@square_of_sum = (1..number).sum ** 2
@sum_of_squares = (1..number).map { |digit| digit ** 2 }.sum
end
def difference
square_of_sum - sum_of_squares
end
end
| true |
8213ad7210c80ac5068ed898bab72f7c22c17077
|
Ruby
|
muhenge/Tic-tac-toe
|
/lib/validation.rb
|
UTF-8
| 455 | 3.609375 | 4 |
[] |
no_license
|
class Validation
attr_reader :token
attr_accessor :user_input
def initialize
@user_input = user_input
@token = [1, 2, 3, 4, 5, 6, 7, 8, 9]
end
def valid?
(1..9).each do |x|
return true if x == @user_input
end
false
end
def avaliable?
%w[x o].each { |x| return false if @token[@user_input - 1] == x }
true
end
def add_symbol(turn)
@token[@user_input - 1] = (turn % 2).zero? ? 'x' : 'o'
end
end
| true |
c6e89e780ccb496068646fbb488ccae5fa059a5d
|
Ruby
|
mlainezb/G7-GuiaRuby
|
/Ejercicio3.rb
|
UTF-8
| 158 | 3.609375 | 4 |
[] |
no_license
|
# 3 Crear un método para eliminar todos los números pares del arreglo.
array = [1,2,3,9,1,4,5,2,3,6,6]
array.delete_if {|array| array % 2 == 0 }
puts array
| true |
c0a10847c8b443eab3f92cb08e58eeb2742d7cfd
|
Ruby
|
KarlHeitmann/project-euler
|
/01-25/problema22-executor.rb
|
UTF-8
| 785 | 3.171875 | 3 |
[] |
no_license
|
require 'awesome_print'
require 'byebug'
require 'rubygems'
require 'json'
POSICIONES = { 'A' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5, 'F' => 6, 'G' => 7, 'H' => 8, 'I' => 9, 'J' => 10, 'K' => 11, 'L' => 12, 'M' => 13, 'N' => 14, 'O' => 15, 'P' => 16, 'Q' => 17, 'R' => 18, 'S' => 19, 'T' => 20, 'U' => 21, 'V' => 22, 'W' => 23, 'X' => 24, 'Y' => 25, 'Z' => 26 }
buffer = File.open('p022_names_ordered.txt', 'r').read
nombres = JSON.parse(buffer)
#ap nombres
score = 0
def calculo_valor(palabra)
val = 0
for i in 0..(palabra.length - 1) do
val = val + POSICIONES[palabra[i]]
end
return val
end
i = 0
nombres.each do |nombre|
i += 1
score += calculo_valor(nombre) * i
if i == 938
ap nombre
ap calculo_valor nombre
ap score
end
end
ap score
| true |
5e40c55e3ee8e78f866eedd57e748cbbc65298af
|
Ruby
|
keshav-c/algo
|
/basic-DS/07-balanced-brackets/main.rb
|
UTF-8
| 1,530 | 3.96875 | 4 |
[] |
no_license
|
class Node
attr_accessor :value, :next_node
def initialize(value, next_node = nil)
@value = value
@next_node = next_node
end
end
class Stack
attr_accessor :top
def initialize()
@top = nil
end
def push(bracket)
node = Node.new(bracket)
if @top.nil?
@top = node
else
node.next_node = @top
@top = node
end
end
def pop()
popped_node, result = @top, nil
if !popped_node.nil?
@top = @top.next_node
result = popped_node.value
end
result
end
def get_top()
@top.nil? ? nil : @top.value
end
def empty?
@top.nil?
end
end
def balanced_brackets?(string)
opening_bracket = {
")" => "(",
"}" => "{",
"]" => "["
}
bracket_stack = Stack.new
string.each_char do |c|
if "{([".include?(c)
bracket_stack.push(c)
elsif "})]".include?(c)
unless bracket_stack.pop == opening_bracket[c]
return false
end
end
end
return bracket_stack.empty?
end
puts balanced_brackets?('(hello)[world]')
# => true
puts balanced_brackets?('([)]')
# => false
puts balanced_brackets?('[({a}{}{df})(2[32])]')
# => true
puts balanced_brackets?("(hello")
# => false
puts balanced_brackets?("([)]")
# => false
puts balanced_brackets?("as)")
# => false
puts balanced_brackets?("{wari}")
# => true
| true |
3426c55e95d23cca5265391b0b36dc0ed7ce7fb2
|
Ruby
|
ninkibah/icu_ratings_app
|
/app/presenters/icu_ratings/war.rb
|
UTF-8
| 3,942 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
module IcuRatings
class WAR
Row = Struct.new(:player, :icu, :fide, :average)
def initialize(params)
@maximum = 50
@gender = params[:gender]
if params[:method] == "war"
@rating_weight = [0.2, 0.3, 0.5]
@type_weight = { icu: 0.6, fide: 0.4 }
else
@rating_weight = [1.0]
@type_weight = { icu: 0.5, fide: 0.5 }
end
end
def years
@years ||= @rating_weight.size
end
def types
@types ||= @type_weight.keys
end
def available?
lists.select{ |type, list| list.size == years }.size == types.size
end
# Compute something like this: { icu: [date1, date2, date3], fide: [date1, date2, date3] }.
def lists
return @lists if @lists
year = latest_common_year
@lists = year ? types.inject({}) { |hash, type| hash[type] = lists_for(type, year); hash } : []
end
# Return an array of ordered Row objects for display, one row per player.
def players
return @players if @players
# Get raw rating data, initially using a hash to tie ICU and FIDE ratings together for each player.
rows = icu_players
fide_players(rows)
# Turn into an array and then calculate an average for each row.
rows = rows.values
rows.each do |row|
average, weight = 0.0, 0.0
average, weight = rating_average(row, average, weight, :icu)
average, weight = rating_average(row, average, weight, :fide)
row.average = weight > 0.0 ? average / weight : 0.0
end
# Sort the array.
rows.sort! { |a,b| b.average <=> a.average }
# Finally, truncate, cache and return.
@players = rows[0..@maximum-1]
end
def methods_menu
[["Simple average of latest ratings", "simple"], ["Three year weighted average", "war"]]
end
def gender_menu
[["Men and Women", ""], ["Women only", "F"]]
end
private
def lists_for(type, year)
klass = type == :icu ? IcuRating : FideRating
years.times.inject([]) do |arry, i|
date = klass.unscoped.where("list LIKE '#{year - i}%'").maximum(:list)
arry.unshift(date) if date
arry
end
end
def latest_common_year
icu = IcuRating.unscoped.maximum(:list).try(:year)
fide = FideRating.unscoped.maximum(:list).try(:year)
return unless icu && fide
icu <= fide ? icu : fide
end
def icu_players
threshold = @gender == "F" ? 1000 : 1800
players = IcuPlayer.unscoped.joins(:icu_ratings).includes(:icu_ratings)
players = players.where("fed = 'IRL' OR fed IS NULL").where(deceased: false)
players = players.where("list IN (?)", lists[:icu]).where("full = 1").where("rating >= #{threshold}")
players = players.where("gender = 'F'") if @gender == "F"
players.inject({}) do |phash, player|
row = Row.new(player)
row.icu = player.icu_ratings.inject({}) { |rhash, icu_rating| rhash[icu_rating.list] = icu_rating.rating; rhash }
row.fide = {}
phash[player.id] = row
phash
end
end
def fide_players(rows)
players = FidePlayer.unscoped.joins(:fide_ratings).includes(:fide_ratings)
players = players.where("icu_id IN (?)", rows.keys)
players = players.where("list IN (?)", lists[:fide])
players.each do |player|
row = rows[player.icu_id]
player.fide_ratings.each { |fide_rating| row.fide[fide_rating.list] = fide_rating.rating }
end
end
def rating_average(row, average, weight, type)
av, wt = 0.0, 0.0
lists[type].each_with_index do |list, i|
rating = row.send(type)[list]
if rating
av += @rating_weight[i] * rating
wt += @rating_weight[i]
end
end
if wt > 0.0
average += @type_weight[type] * av / wt
weight += @type_weight[type]
end
[average, weight]
end
end
end
| true |
3a3dfc0c0a8f6a577347bae549607182614c0cdc
|
Ruby
|
kapilchouhan99/boggle_game_rails_react
|
/app/controllers/boggle_controller.rb
|
UTF-8
| 1,223 | 2.640625 | 3 |
[] |
no_license
|
class BoggleController < ApplicationController
def index
end
def create
Score.create!(name: params[:name], score: params[:score])
end
def check_word
@response = DICTIONARY.include?(params[:word])
respond_to do |format|
format.json { render json: { response: @response } }
end
end
def start_game
characters = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
letters = characters.split("").sample(16).join("")
render json: { letters: letters }
end
def highscores
scores = Score.order("score DESC")
render json: { scores: scores }
end
def play_boggle
player_name = params[:player_name]
word = params[:word]
boggle = JSON.parse(params[:boggle])
boggle_obj = Boggle.new({ boggle: boggle })
result = boggle_obj.check_word(word)
Score.create!(player_name: player_name, score: word.length, word: word)
if result.present?
render json: { response: { result: result, score: word.length } , status: "success" }
else
render json: { response: { result: result, score: "" } , status: "success" }
end
end
end
| true |
aa9b6208ef97a90783f6e954d92174a151c70948
|
Ruby
|
gregmoreno/lingpipe
|
/demos/tutorial/posTags/run_medpost.rb
|
UTF-8
| 1,705 | 2.578125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
require 'lingpipe'
require 'java'
require 'pathname'
filename = Pathname(__FILE__).dirname + '../../models/pos-en-bio-medpost.HiddenMarkovModel'
model = Java::java.io.File.new(filename.to_s) # NOTE: Ruby file != java.io.File
hmm = LingPipe::AbstractExternalizable.readObject(model);
decoder = LingPipe::HmmDecoder.new(hmm)
TOKEN_REGEX = "(-|'|\\d|\\p{L})+|\\S"
tokenizer_factory = LingPipe::RegExTokenizerFactory.new(TOKEN_REGEX)
sample = "This correlation was also confirmed by detection of early carcinoma."
tokenizer = tokenizer_factory.tokenizer(Java::java.lang.String.new(sample).toCharArray, 0, sample.length)
# damn conversion
tokens = tokenizer.tokenize
a_tokens = tokens.inject([]) { |l, i| l << i }
j_tokens = a_tokens.to_java(:string)
token_list = Java::java.util.Arrays.asList(j_tokens) # (tokenizer.tokenize) doesn't work
puts sample
puts "FIRST BEST"
tagging = decoder.tag(token_list)
0.upto(tagging.size - 1) do |i|
print "#{tagging.token(i)}_#{tagging.tag(i)} "
end
puts ""
puts 'N BEST'
puts '# JointLogProb Analysis'
taggings = decoder.tagNBest(token_list, 5)
taggings.each_with_index do |tagging, n|
printf "%s %9.3f ", n, tagging.score
0.upto(token_list.size - 1) do |i|
print "#{tagging.token(i)}_#{tagging.tag(i)} "
end
puts ""
end
puts 'CONFIDENCE'
printf "%-3s %-15s\n", '#', 'Token', '(Prob:Tag)*'
lattice = decoder.tagMarginal(token_list)
0.upto(token_list.size - 1) do |token_index|
printf "%-3s %-15s", token_index, token_list[token_index]
tag_scores = lattice.tokenClassification(token_index)
0.upto(4) do |i|
prob = tag_scores.score(i)
tag = tag_scores.category(i)
printf "%9.3f:%-4s", prob, tag
end
puts ''
end
| true |
61f6ccf8f75cb5c1d8f0cfcdc41d8602ee636bed
|
Ruby
|
BetimShala/Algorithmic-Problem-Solving
|
/hackerrank/BirthdayChocolate.rb
|
UTF-8
| 421 | 3.125 | 3 |
[] |
no_license
|
def solve(n, s, d, m)
# Complete this function
counter=0
if n==s.length
for i in 0...s.length
res=[*s[i,m]].inject(:+)
if res==d
counter+=1
end
end
end
return counter
end
n = gets.strip.to_i
s = gets.strip
s = s.split(' ').map(&:to_i)
d, m = gets.strip.split(' ')
d = d.to_i
m = m.to_i
result = solve(n, s, d, m)
puts result;
| true |
5612f5ed17f2d9f28f4b5eff1f42627671b06b0b
|
Ruby
|
ILYAKOINOV/Lesson24
|
/app.rb
|
UTF-8
| 1,383 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
require 'rubygems'
require 'sinatra'
require 'sinatra/reloader'
get '/' do
erb "Hello! <a href=\"https://github.com/bootstrap-ruby/sinatra-bootstrap\">Original</a> pattern has been modified for <a href=\"http://rubyschool.us/\">Ruby School</a>"
end
get '/about' do
@error = 'something wrong!'
erb :about
end
get '/visit' do
erb :visit
end
post '/visit' do
@username = params[:username]
@phone = params[:phone]
@datetime = params[:datetime]
@barber = params[:barber]
@color = params[:color]
# хэш
hh = {
:username => 'Введите имя',
:phone => 'Введите номер телефона',
:datetime => 'Введите дату и время'}
# для каждой пары ключ-значение
#hh.each do |key, value|
# если параметр пуст
# if params[key] == ''
# переменной error присвоить value из хэша hh
# (а value из хэша hh это сообщение об ошибке)
# т.е. переменной error присвоить сообщение об ошибке
# @error = hh[key]
#Вернуть представление visit
# return erb :visit
# end
#end
@error = hh.select {|key,_| params[key] == ""}.values.join(", ")
if @error != ''
return erb :visit
end
erb "OK, username is #{@username}, #{@phone}, #{@datetime}, #{@barber}, #{@color}"
end
| true |
56be87080709ee85540bcf31501f553ce137bad9
|
Ruby
|
amd61/week_2_day_1_homework
|
/specs/student_spec.rb
|
UTF-8
| 769 | 3.046875 | 3 |
[] |
no_license
|
require("minitest/autorun")
require ("minitest/rg")
require_relative ("../student")
class TestStudent < Minitest::Test
def setup
@daniel = Student.new("Daniel", 1)
@arlene = Student.new("Arlene", 12)
end
def test_student_get_name
assert_equal("Daniel", @daniel.student_name)
end
def test_student_get_cohort
assert_equal(1, @daniel.cohort)
end
def test_student_change_name
@daniel.name = "dan"
assert_equal("dan", @daniel.name)
end
def test_cohort_change_cohort
@daniel.cohort = 2
assert_equal(2, @daniel.cohort)
end
def test_student_can_talk
assert_equal("I can talk", @daniel.talk)
end
def test_has_favourite_language
assert_equal("My favourite language is Ruby", @daniel.favourite_language("Ruby"))
end
end
| true |
bc47413550bba536021ffa3c00dc28d3919f91e7
|
Ruby
|
aliyamerali/ruby-exercises
|
/initialize/lib/monkey.rb
|
UTF-8
| 199 | 2.859375 | 3 |
[] |
no_license
|
class Monkey
attr_reader :name, :type, :favorite_food
def initialize(array_of_info)
@name = array_of_info[0]
@type = array_of_info[1]
@favorite_food = array_of_info[2]
end
end
| true |
58c23680754204cdeff135483f2634040e30edec
|
Ruby
|
ivanmalor/Nimgame
|
/lib/player.rb
|
UTF-8
| 1,556 | 3.625 | 4 |
[] |
no_license
|
class Player
@@players = {}
attr_accessor :given_name, :family_name
attr_reader :username, :games_played, :games_won
def self.add
puts "\nEnter username\n\n"
username = gets.chomp
while username_exist?(username)
puts "\nThe player already exist. Please use a different username\n\n"
username = gets.chomp
end
puts "\nEnter given name\n\n"
given_name = gets.chomp
puts "\nEnter family name\n\n"
family_name = gets.chomp
Player.new(username, given_name, family_name)
end
def self.remove
puts "\nEnter username\n\n"
username = gets.chomp
until username_exist?(username)
puts "\nThe player doesn't exist. Please enter an existent username\n\n"
username = gets.chomp
end
@@players.delete(username)
puts "Player #{username} has been deleted"
end
def self.edit
puts "\nEnter username\n\n"
username = gets.chomp
until username_exist?(username)
puts "\nThe player doesn't exist. Please enter an existent username\n\n"
username = gets.chomp
end
player = @@players[username]
puts "\nChange given name\n\n"
player.given_name = gets.chomp
puts "\nChange last name\n\n"
player.family_name = gets.chomp
end
def self.username_exist?(username)
@@players.has_key?(username)
end
def initialize(username, given_name, family_name)
@username = username
@given_name = given_name
@family_name = family_name
@games_played, @games_won = 0,0
@@players.store(@username, self)
end
end
| true |
4f03374036a05179de475ccd25ff0bd9f606f5be
|
Ruby
|
ilkerinanc/voicev4
|
/test/unit/survey_test.rb
|
UTF-8
| 649 | 2.59375 | 3 |
[] |
no_license
|
require 'test_helper'
class SurveyTest < ActiveSupport::TestCase
def test_should_be_valid
assert !Survey.new.valid?
end
test "should not save survey without name" do
survey = Survey.new
survey.name = nil
assert !survey.save, "Saved the survey without a name"
end
test "should not save survey without start_time" do
survey = Survey.new
survey.start_time = nil
assert !survey.save, "Saved the survey without a start_time"
end
test "should not save survey without finish_time" do
survey = Survey.new
survey.finish_time = nil
assert !survey.save, "Saved the survey without a finish_time"
end
end
| true |
91945491c2344aed0e42ed56e024c7c3d272649e
|
Ruby
|
eladmeidar/diakonos
|
/lib/diakonos/buffer-management.rb
|
UTF-8
| 1,684 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
module Diakonos
class Diakonos
attr_reader :buffer_current
# @param [Buffer] the Buffer to switch to
# @option opts [Boolean] :do_display
# Whether or not to update the display after closure
# @return [Boolean] true iff the buffer was successfully switched to
def switch_to( buffer, opts = {} )
return false if buffer.nil?
do_display = opts.fetch( :do_display, true )
@buffer_stack -= [ @buffer_current ]
if @buffer_current
@buffer_stack.push @buffer_current
end
@buffer_current = buffer
@session[ 'buffer_current' ] = buffer_to_number( buffer )
run_hook_procs( :after_buffer_switch, buffer )
update_status_line
update_context_line
if do_display
display_buffer buffer
end
true
end
# @param [Fixnum] buffer_number should be 1-based, not zero-based.
# @return nil if no such buffer exists.
def buffer_number_to_name( buffer_number )
return nil if buffer_number < 1
b = @buffers[ buffer_number - 1 ]
if b
b.name
end
end
# @return [Fixnum] 1-based, not zero-based.
# @return nil if no such buffer exists.
def buffer_to_number( buffer )
i = @buffers.index( buffer )
if i
i + 1
end
end
def show_buffer_file_diff( buffer = @buffer_current )
current_text_file = @diakonos_home + '/current-buffer'
buffer.save_copy( current_text_file )
`#{@settings[ 'diff_command' ]} #{current_text_file} #{buffer.name} > #{@diff_filename}`
diff_buffer = open_file( @diff_filename )
yield diff_buffer
close_buffer diff_buffer
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.