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 |
---|---|---|---|---|---|---|---|---|---|---|---|
a68f9689976fa4fe8a92c743715a3a5669c0032e
|
Ruby
|
iangraham20/cs214
|
/projects/08/scripts/script.ruby
|
UTF-8
| 5,477 | 3.296875 | 3 |
[] |
no_license
|
Script started on Tue 10 Apr 2018 03:10:20 PM EDT
ls
igc2@backus-naur:~/workspace/214/projects/08/ruby$ ls
script.ruby Temperature.rb temperatureTester.rb
igc2@backus-naur:~/workspace/214/projects/08/ruby$ ruby T temperatureTester.rb
Testing Constructor... Passed!
Testing toFahrenheit... Passed!
Testing toCelsius... Passed!
Testing toKelvin... Passed!
Testing raiseTemp... Passed!
Testing lowerTemp... Passed!
Testing equalTo... Passed!
Testing lessThan... Passed!
Testing fromString and toString...
Enter a Temperature value: 10 2352.47 C
Temperature value fromString: 2352.47 CAll Tests Passed!
Enter the base temperature: 0 F
Enter the limit temperature: 100 C
Enter the step value: 2.5
Celsius | Fahrenheit | Kelvin
-17.78 C | 0.0 F | 255.37 K
-16.39 C | 2.5 F | 256.76 K
-15.0 C | 5.0 F | 258.15 K
-13.61 C | 7.5 F | 259.54 K
-12.22 C | 10.0 F | 260.93 K
-10.83 C | 12.5 F | 262.32 K
-9.44 C | 15.0 F | 263.71 K
-8.06 C | 17.5 F | 265.09 K
-6.67 C | 20.0 F | 266.48 K
-5.28 C | 22.5 F | 267.87 K
-3.89 C | 25.0 F | 269.26 K
-2.5 C | 27.5 F | 270.65 K
-1.11 C | 30.0 F | 272.04 K
0.28 C | 32.5 F | 273.43 K
1.67 C | 35.0 F | 274.82 K
3.06 C | 37.5 F | 276.21 K
4.44 C | 40.0 F | 277.59 K
5.83 C | 42.5 F | 278.98 K
7.22 C | 45.0 F | 280.37 K
8.61 C | 47.5 F | 281.76 K
10.0 C | 50.0 F | 283.15 K
11.39 C | 52.5 F | 284.54 K
12.78 C | 55.0 F | 285.93 K
14.17 C | 57.5 F | 287.32 K
15.56 C | 60.0 F | 288.71 K
16.94 C | 62.5 F | 290.09 K
18.33 C | 65.0 F | 291.48 K
19.72 C | 67.5 F | 292.87 K
21.11 C | 70.0 F | 294.26 K
22.5 C | 72.5 F | 295.65 K
23.89 C | 75.0 F | 297.04 K
25.28 C | 77.5 F | 298.43 K
26.67 C | 80.0 F | 299.82 K
28.06 C | 82.5 F | 301.21 K
29.44 C | 85.0 F | 302.59 K
30.83 C | 87.5 F | 303.98 K
32.22 C | 90.0 F | 305.37 K
33.61 C | 92.5 F | 306.76 K
35.0 C | 95.0 F | 308.15 K
36.39 C | 97.5 F | 309.54 K
37.78 C | 100.0 F | 310.93 K
39.17 C | 102.5 F | 312.32 K
40.56 C | 105.0 F | 313.71 K
41.94 C | 107.5 F | 315.09 K
43.33 C | 110.0 F | 316.48 K
44.72 C | 112.5 F | 317.87 K
46.11 C | 115.0 F | 319.26 K
47.5 C | 117.5 F | 320.65 K
48.89 C | 120.0 F | 322.04 K
50.28 C | 122.5 F | 323.43 K
51.67 C | 125.0 F | 324.82 K
53.06 C | 127.5 F | 326.21 K
54.44 C | 130.0 F | 327.59 K
55.83 C | 132.5 F | 328.98 K
57.22 C | 135.0 F | 330.37 K
58.61 C | 137.5 F | 331.76 K
60.0 C | 140.0 F | 333.15 K
61.39 C | 142.5 F | 334.54 K
62.78 C | 145.0 F | 335.93 K
64.17 C | 147.5 F | 337.32 K
65.56 C | 150.0 F | 338.71 K
66.94 C | 152.5 F | 340.09 K
68.33 C | 155.0 F | 341.48 K
69.72 C | 157.5 F | 342.87 K
71.11 C | 160.0 F | 344.26 K
72.5 C | 162.5 F | 345.65 K
73.89 C | 165.0 F | 347.04 K
75.28 C | 167.5 F | 348.43 K
76.67 C | 170.0 F | 349.82 K
78.06 C | 172.5 F | 351.21 K
79.44 C | 175.0 F | 352.59 K
80.83 C | 177.5 F | 353.98 K
82.22 C | 180.0 F | 355.37 K
83.61 C | 182.5 F | 356.76 K
85.0 C | 185.0 F | 358.15 K
86.39 C | 187.5 F | 359.54 K
87.78 C | 190.0 F | 360.93 K
89.17 C | 192.5 F | 362.32 K
90.56 C | 195.0 F | 363.71 K
91.94 C | 197.5 F | 365.09 K
93.33 C | 200.0 F | 366.48 K
94.72 C | 202.5 F | 367.87 K
96.11 C | 205.0 F | 369.26 K
97.5 C | 207.5 F | 370.65 K
98.89 C | 210.0 F | 372.04 K
igc2@backus-naur:~/workspace/214/projects/08/ruby$ ruby temperature. Tester.rb
Testing Constructor... Passed!
Testing toFahrenheit... Passed!
Testing toCelsius... Passed!
Testing toKelvin... Passed!
Testing raiseTemp... Passed!
Testing lowerTemp... Passed!
Testing equalTo... Passed!
Testing lessThan... Passed!
Testing fromString and toString...
Enter a Temperature value: -295 F
Temperature value fromString: -295.0 FAll Tests Passed!
Enter the base temperature: 0 K
Enter the limit temperature: 212 F
Enter the step value: 20.0
Celsius | Fahrenheit | Kelvin
-273.15 C | -459.67 F | 0.0 K
-253.15 C | -423.67 F | 20.0 K
-233.15 C | -387.67 F | 40.0 K
-213.15 C | -351.67 F | 60.0 K
-193.15 C | -315.67 F | 80.0 K
-173.15 C | -279.67 F | 100.0 K
-153.15 C | -243.67 F | 120.0 K
-133.15 C | -207.67 F | 140.0 K
-113.15 C | -171.67 F | 160.0 K
-93.15 C | -135.67 F | 180.0 K
-73.15 C | -99.67 F | 200.0 K
-53.15 C | -63.67 F | 220.0 K
-33.15 C | -27.67 F | 240.0 K
-13.15 C | 8.33 F | 260.0 K
6.85 C | 44.33 F | 280.0 K
26.85 C | 80.33 F | 300.0 K
46.85 C | 116.33 F | 320.0 K
66.85 C | 152.33 F | 340.0 K
86.85 C | 188.33 F | 360.0 K
igc2@backus-naur:~/workspace/214/projects/08/ruby$ ls
script.ruby Temperature.rb temperatureTester.rb
igc2@backus-naur:~/workspace/214/projects/08/ruby$ exit
Script done on Tue 10 Apr 2018 03:11:42 PM EDT
| true |
2b7c63f50bfed10d3e43b8941c4e83e9275d607e
|
Ruby
|
lorantcsiszer1119/socialdog
|
/app/models/twitter_user.rb
|
UTF-8
| 1,883 | 2.59375 | 3 |
[] |
no_license
|
require 'net/http'
class TwitterUser < ActiveRecord::Base
include TwitterAuth
belongs_to :user
# Post a new tweet to Twitter and return either the tweet id on success, or false on failure
def post_update(text)
access_token = token
resp = access_token.post('/statuses/update.json', :status => text)
case resp
when Net::HTTPSuccess
json = JSON.parse(resp.body)
return json['id'].to_i
else
# We should return a more detailed response probably...
return false
end
end
def self.identify_or_create_by_access_token(user, token, secret = nil)
path_prefix = URI.parse(TwitterAuth.config['base_url']).path
token = OAuth::AccessToken.new(TwitterUsersController.consumer, token, secret) unless token.is_a?(OAuth::AccessToken)
resp = token.get(path_prefix + '/account/verify_credentials.json')
case resp
when Net::HTTPSuccess
@twitter_user = find_or_create_by_user_id(user.id)
user_info = JSON.parse(resp.body)
# Update user with fresh info from twitter
attributes = {}
user_info.each do |k,v|
attributes[k] = v if @twitter_user.has_attribute?(k)
end
# OAuth token/secret
attributes['access_token'] = token.token
attributes['access_secret'] = token.secret
# Clear timestamps
attributes.delete('created_at')
attributes.delete('updated_at')
# user id and login
attributes['twitter_id'] = user_info['id']
attributes['login'] = user_info['screen_name']
@twitter_user.update_attributes(attributes) unless attributes.empty?
end
return @twitter_user
end
def token
OAuth::AccessToken.new(TwitterUsersController.consumer, self.access_token, self.access_secret) if (self.access_token && self.access_secret)
end
end
| true |
b5859d9453900486483b5f4da327a80a53009d83
|
Ruby
|
micahlagrange/ruby-podcast-rss-generator
|
/lib/s3.rb
|
UTF-8
| 2,506 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
require "open3"
require "aws-sdk-s3"
require "json"
require "time"
# Call:
# Podcast::S3Buckets.episodes
#
# #<struct Podcast::S3Buckets::Episode
# path="episodes/draft-stb-2019-03-03-first.mp3",
# guid="63f25dfa4743c0d9315d4e5:e75a3fb242f080349a84b2b03119:94ab40aa86624892e0acc802d38",
# release_date="2019-03-20"
# episode_number=1>
module Podcast
GUID = "guid".freeze # the unique id for the podcast episode
RELEASE_DATE = "release_date".freeze # the date after which the episode will be put into the feed
EPISODE_NUMBER = "episode_number".freeze # the chronological number of the episode
module S3Buckets
Episode = Struct.new(:path, :guid, :release_date, :episode_number) do
def valid?
[episode_number, guid, release_date].all? { |i| !i.nil? }
end
def pubdate
Time.parse(release_date).utc
end
end
def self.client
Aws::S3::Client.new
end
def self.tag_name(tags, key)
found = tags.find { |t| t.key == key }
found.value unless found.nil?
end
def self.upload_podcast_xml(bucket:, xml_file:, name: "podcast.xml")
tags = "lastBuildDate=#{Time.now.iso8601}"
resp = client.put_object(
body: File.read(xml_file),
bucket: bucket,
key: name,
tagging: tags,
content_type: "application/rss+xml",
)
resp.successful?
end
def self.upload_episode(bucket:, audio_file:, guid:, pubdate:, episode_number:, mime_type:, path_prefix: "episodes")
tags = "guid=#{guid}&release_date=#{pubdate}&episode_number=#{episode_number}"
resp = File.open(audio_file, "rb") do |file|
resp = client.put_object(
body: file,
bucket: bucket,
key: "#{path_prefix}/#{File.basename(audio_file)}",
content_type: mime_type,
tagging: tags,
)
end
resp.successful?
end
def self.episodes(bucket:, path_prefix: "episodes")
ep_list = []
episodes = client.list_objects(bucket: bucket, prefix: path_prefix).contents
episodes.select { |e| e.size != 0 }&.each do |ep|
details = client.get_object_tagging(bucket: bucket, key: ep.key).tag_set
ep_list << Episode.new(ep.key, tag_name(details, GUID), tag_name(details, RELEASE_DATE),
tag_name(details, EPISODE_NUMBER).to_i)
end
ep_list.select(&:valid?)
end
end
end
| true |
217958f2d48b62f1150e78e1443de96da7c526f8
|
Ruby
|
scarlettperry/algos
|
/ruby/fizzbuzz.rb
|
UTF-8
| 320 | 3.90625 | 4 |
[] |
no_license
|
def fizz_buzz(int)
fizz_buzz_array = []
(1..int).each do |i|
if i % 3 == 0 && i % 5 == 0
fizz_buzz_array << "FizzBuzz"
elsif i % 3 == 0
fizz_buzz_array << "Fizz"
elsif i % 5 == 0
fizz_buzz_array << "Buzz"
else
fizz_buzz_array << i.to_s
end
end
fizz_buzz_array
end
| true |
dc04b1e30ff1491800f7bd7eb07d14f4d64b8289
|
Ruby
|
NikValdez/learn_ruby
|
/01_temperature/temperature.rb
|
UTF-8
| 77 | 2.828125 | 3 |
[] |
no_license
|
F2C = (5.0/9.0)
def ftoc f
(f-32.0)*F2C
end
def ctof c
32.0+(c/F2C)
end
| true |
d4dfe4d9535cd7154c9d788246f65b18e1cdba68
|
Ruby
|
wjordan/libev_scheduler
|
/test/test_io.rb
|
UTF-8
| 1,027 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require 'bundler/setup'
require 'minitest/autorun'
require 'minitest/reporters'
require 'libev_scheduler'
class TestFiberIO < MiniTest::Test
MESSAGE = "Hello World"
def test_read
i, o = IO.pipe
message = nil
thread = Thread.new do
scheduler = Libev::Scheduler.new
Fiber.set_scheduler scheduler
Fiber.schedule do
message = i.read(20)
i.close
end
Fiber.schedule do
o.write("Hello World")
o.close
end
end
thread.join
assert_equal MESSAGE, message
assert_predicate(i, :closed?)
assert_predicate(o, :closed?)
end
def test_heavy_read
16.times.map do
Thread.new do
i, o = IO.pipe
scheduler = Libev::Scheduler.new
Fiber.set_scheduler scheduler
Fiber.schedule do
i.read(20)
i.close
end
Fiber.schedule do
o.write("Hello World")
o.close
end
end
end.each(&:join)
end
end
| true |
9538798322da93a0589bde7d0974d926b4a38478
|
Ruby
|
dux/lux-fw
|
/lib/overload/raise_variants.rb
|
UTF-8
| 1,483 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
class Object
# raise object
def r what
if what.is_a?(Method)
rr [:source_location, what.source_location.join(':')]
else
rr what
end
raise StandardError.new(what)
end
# better console log dump
def rr what
klass = what.class
klass = '%s at %s' % [klass, what.source_location.join(':').sub(Lux.root.to_s, '.')] if klass == Method
from = caller[0].include?('raise_variants.rb') ? caller[1] : caller[0]
from = from.sub(Lux.root.to_s+'/', './').split(':in ').first
ap ['--- START (%s) %s - %s ---' % [klass, from, Lux.current.request.url], what, '--- END ---']
end
# unique methods for object
# includes methods from modules
def r? object
dump = []
dump.push 'Class: %s' % object.class
instance_unique = object.methods - object.class.ancestors[0].instance_methods
class_unique = object.methods
object.class.ancestors.drop(1).each do |_|
class_unique -= _.instance_methods
if _.class != Module
dump.push 'Parent Class: %s' % _
break
end
end
dump.push ['Instance uniqe', instance_unique.sort] if instance_unique[0]
dump.push ['Uniqe from parent', class_unique.sort.join(', ')]
dump.push ['Uniqe from parent simple', object.class.instance_methods(false)]
rr dump
end
end
###
# if we dont have awesome print in prodction, define mock
method(:ap) rescue Proc.new do
class Object
def ap(*args)
puts args
end
end
end.call
| true |
0bc0e6224594a7bbd735ba9ec922e23a32c929e3
|
Ruby
|
ellefaraday/tic-tac-toe-rb-v-000
|
/lib/tic_tac_toe.rb
|
UTF-8
| 2,424 | 4.28125 | 4 |
[] |
no_license
|
def display_board(board)
puts " #{board[0]} | #{board[1]} | #{board[2]} "
puts "-----------"
puts " #{board[3]} | #{board[4]} | #{board[5]} "
puts "-----------"
puts " #{board[6]} | #{board[7]} | #{board[8]} "
end
def input_to_index(input)
index = input.to_i - 1
end
def position_taken?(board, index)
!(board[index].nil? || board[index] == " ")
end
def valid_move?(board, index)
if index <= 8 && index >= 0 && position_taken?(board,index) == false
return true
else
return false
end
end
def move(board, index, char)
board[index] = char
end
def turn(board)
puts "Please enter 1-9:"
input = gets.strip
index = input_to_index(input)
if valid_move?(board, index) == true
move(board,index,current_player(board))
display_board(board)
else
turn (board)
end
end
def turn_count(board)
count = 0
board.each do |place|
if place != " "
count += 1
else
end
end
return count
end
def current_player(board)
if turn_count(board) % 2 == 0
"X"
else
"O"
end
end
WIN_COMBINATIONS = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
def won?(board)
winning_array = []
WIN_COMBINATIONS.each do |win_combination|
win_index_1 = win_combination[0]
win_index_2 = win_combination[1]
win_index_3 = win_combination[2]
position_1 = board[win_index_1]
position_2 = board[win_index_2]
position_3 = board[win_index_3]
if position_1 == "X" && position_2 == "X" && position_3 == "X"
winning_array = win_combination
elsif position_1 == "O" && position_2 == "O" && position_3 == "O"
winning_array = win_combination
else
end
end
if winning_array.empty?
false
else
winning_array
end
end
def full?(board)
board.none? {|place| place == " "}
end
def draw?(board)
if full?(board)
if won?(board) != false
false
else
true
end
else
false
end
end
def over?(board)
if won?(board) != false
true
elsif draw?(board)
true
else
false
end
end
def winner(board)
if won?(board) != false
return board[won?(board)[0]]
else
return nil
end
end
def play(board)
loop do
if over?(board) == false
turn(board)
elsif won?(board) != false
puts "Congratulations #{winner(board)}!"
break
else
puts "Cat's Game!"
break
end
end
end
| true |
213f2b560b3851d8b3636d98c3b9ecc52369e6c3
|
Ruby
|
andreadelfante/gitlab-release-tools
|
/lib/gitlab/release/changelog/generator.rb
|
UTF-8
| 5,184 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
require 'gitlab/release/api_client'
require 'gitlab/release/changelog/entries'
require 'gitlab/release/changelog/entry'
require 'gitlab/release/version'
module Gitlab
module Release
module Changelog
##
# This class generates the changelog entries
#
class Generator < ApiClient
##
# @option [String] endpoint Optional. The API endpoint URL. Default: ENV['GITLAB_API_ENDPOINT'] and falls back to ENV['CI_API_V4_URL']
# @option [String] private_token Optional. User's private token or OAuth2 access token. Default: ENV['GITLAB_API_PRIVATE_TOKEN']
# @option [Integer] max_loops_merge_requests Optional. The limit of the loop to fetch merge requests. Default: 2000
# @option [Integer] max_loop_issues Optional. The limit of the loop to fetch issues. Default: 2000
#
def initialize(options = {})
@max_loops_merge_requests = options[:max_loops_merge_requests] || 2000
@max_loop_issues = options[:max_loop_issues] || 2000
super(options)
end
##
# Generate the changelog.
#
# @param [String] version_name Required. The name of the version. (ex: 1.0)
# @option [String or Integer] project_id Optional. The id of this project, given from GitLab. Default ENV["CI_PROJECT_ID"]
# @option [Boolean] include_mrs Optional. Should the generator include merge requests? Default: true
# @option [Boolean] include_issues Optional. Should the generator include issues? Default false
# @option [Array[String]] filtering_labels Optional. A general list of labels to filter items. Default: []
# @option [Array[String]] filtering_mrs_labels Optional. A specific list of labels to filter merge requests. Default: []
# @option [Array[String]] filtering_issues_labels Optional. A specific list of labels to filter issues. Default: []
# @return [Entries]
#
def changelog(version_name, options = {})
project_id = options[:project_id] || ENV["CI_PROJECT_ID"]
include_mrs = options[:include_mrs] || true
include_issues = options[:include_issues] || false
filtering_mrs_labels = options[:filtering_mrs_labels] || options[:filtering_labels] || []
filtering_issue_labels = options[:filtering_issues_labels] || options[:filtering_labels] || []
entries = Entries.new
if include_mrs
changelog_from_merge_requests(entries,
project_id,
version_name,
filtering_mrs_labels)
end
if include_issues
changelog_from_issues(entries,
project_id,
version_name,
filtering_issue_labels)
end
entries
end
# @param [Entries] entries
# @param [String or Integer] project_id
# @param [String] version_name
# @param [Array[String]] filtering_labels
private def changelog_from_merge_requests(entries, project_id, version_name, filtering_labels)
select_milestones(project_id, version_name).each do |milestone|
i = 1
all = false
while i < @max_loops_merge_requests and !all
merge_requests = @client.milestone_merge_requests(project_id, milestone.id, {page: i})
all = merge_requests.empty?
merge_requests.each do |mr|
if check_mr(mr, filtering_labels)
entries.push(MergeRequest.new(mr.iid, mr.title))
end
end
i += 1
end
end
end
# @param [Gitlab::ObjectifiedHash] mr
# @param [Array[String]] filtering_labels
# @return [Boolean]
private def check_mr(mr, filtering_labels)
mr.state == 'merged' and (filtering_labels - mr.labels).empty?
end
# @param [Entries] entries
# @param [String or Integer] project_id
# @param [String] version_name
# @param [Array[String]] filtering_labels
private def changelog_from_issues(entries, project_id, version_name, filtering_labels)
select_milestones(project_id, version_name).each do |milestone|
i = 1
all = false
while i < @max_loop_issues and !all
issues = @client.milestone_issues(project_id, milestone.id, {page: i})
all = issues.empty?
issues.each do |issue|
if check_issue(issue, filtering_labels)
entries.push(Issue.new(issue.id, issue.title))
end
end
i += 1
end
end
end
# @param [Gitlab::ObjectifiedHash] issue
# @param [Array[String]] filtering_labels
# @return [Boolean]
private def check_issue(issue, filtering_labels)
issue.state == 'closed' and (filtering_labels - issue.labels).empty?
end
end
end
end
end
| true |
91707ab87d1189af9cf1e488ea353f871ec4a9aa
|
Ruby
|
davidjnelson/aws_static_website_deploy
|
/lib/aws_static_website_deploy/YamlParser.rb
|
UTF-8
| 521 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
require 'uri'
class YamlParser
public
def initialize(configFilePath)
File.open(configFilePath) do |configFile|
@config = YAML::load(configFile)
end
end
public
def getUrl()
url = @config['url']
uri = URI.parse(url)
host = uri.host
if !host.match(/^www\./)
raise 'url in _config.yml must start with www.'
end
return host
end
public
def getAwsKey()
return @config['aws_key']
end
public
def getAwsSecret()
return @config['aws_secret']
end
end
| true |
f28c83a54afa339a955ca3e3e91525f955d5bb26
|
Ruby
|
DaikiMasaoka/lesson
|
/lesson14.rb
|
UTF-8
| 191 | 3.296875 | 3 |
[] |
no_license
|
# 長さ 3の文字列
# Sが与えられます。
# Sの先頭の文字を
# Sの末尾に移動して得られる文字列
# S′を出力してください。
s = gets
puts s[1]+s[2]+s[0]
| true |
9f913fcf269121340b937d686da79d590b78be24
|
Ruby
|
jcasimir/slimgin
|
/test/invoice_repository_test.rb
|
UTF-8
| 5,145 | 2.765625 | 3 |
[] |
no_license
|
require_relative 'test_helper'
require_relative '../lib/invoice_repository.rb'
require_relative '../lib/sales_engine.rb'
class InvoiceRepositoryTest < Minitest::Test
attr_reader :engine
def setup
@engine = SalesEngine.new("./test/fixtures")
engine.startup
end
def test_it_can_find_all_successful_invoices
repo = engine.invoice_repository
result = repo.successful_invoices
assert_equal 14, result.size
assert_equal Invoice, result[1].class
end
def test_it_can_find_pending_invoices
repo = engine.invoice_repository
result = repo.pending_invoices
assert_equal 6, result.size
end
def test_can_create_an_invoice
s_engine = SalesEngine.new("./test/fixtures")
s_engine.startup
repo = s_engine.invoice_repository
count = repo.all.values.size
item1 = Item.new(s_engine.item_repository, id: 99, unit_price: 1, created_at: Time.now, updated_at: Time.now )
item2 = Item.new(s_engine.item_repository, id: 999, unit_price: 1, created_at: Time.now, updated_at: Time.now)
customer = s_engine.customer_repository.find_by_id(1)
merchant = s_engine.merchant_repository.find_by_id(1)
invoice = repo.create(customer: customer, merchant: merchant, status: "shipped",
items: [item1, item2, item1])
assert_equal (count + 1), repo.all.values.size
end
def test_it_can_charge_a_credit_card
s_engine = SalesEngine.new("./test/fixtures")
s_engine.startup
repo = s_engine.invoice_repository
count = repo.all.values.size
item1 = Item.new(s_engine.item_repository, id: 99, unit_price: 1, created_at: Time.now, updated_at: Time.now )
item2 = Item.new(s_engine.item_repository, id: 999, unit_price: 1, created_at: Time.now, updated_at: Time.now)
customer = s_engine.customer_repository.find_by_id(1)
merchant = s_engine.merchant_repository.find_by_id(1)
invoice = repo.create(customer: customer, merchant: merchant, status: "shipped",
items: [item1, item2, item1])
args = { credit_card_number: "4444333322221111",
credit_card_expiration: "10/13", result: "success" }
invoice.charge(args)
assert invoice.transactions.any? { |transaction| transaction.credit_card_number == '4444333322221111' }
end
##########PREVIOUS DEVELOPER########
def test_it_is_a_repository
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
assert_kind_of Repository, invoice_repo
end
def test_it_knows_what_file_it_refers_to
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
assert_kind_of File, invoice_repo.location
end
def test_it_can_fetch_an_invoice
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
assert_kind_of Invoice, invoice_repo.id(1)
end
def test_it_can_fetch_using_all
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
assert_kind_of Hash, invoice_repo.all
end
def test_it_fetches_invoices_using_all
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
assert_kind_of Invoice, invoice_repo.all.values[0]
end
def test_it_fetches_a_random_instance
# this test has a one in a quadrillion chance of accidentally failing
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
invoices = []
50.times do
invoices << invoice_repo.random
end
assert_equal 50, invoices.length
refute_equal 1, invoices.uniq.length
end
def test_random_instance_is_id_attributes_pair
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
random = invoice_repo.random
assert_kind_of Invoice, random
end
def test_it_can_find_by_attribute
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
invoices = invoice_repo.find_all_by(merchant_id: 1)
assert_kind_of Array, invoices
end
def test_attributes_found_are_correct
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
invoices = invoice_repo.find_all_by(status: "shipped")
invoice = invoices[1]
assert_equal "shipped", invoice.status
end
def test_find_does_not_return_what_it_is_not_searching_for
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
invoices = invoice_repo.find_all_by(status: "in transit")
assert_equal 0, invoices.length
end
def test_find_all_returns_all
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
invoices = invoice_repo.find_all_by(merchant_id: 1)
assert_equal 3, invoices.length
end
def test_find_first_of_multiple
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
invoices = invoice_repo.find_by(customer_id: 1)
assert_equal 1, invoices.customer_id
end
def test_find_all_by_returns_empty_hash_if_no_findings
invoice_repo = InvoiceRepository.new engine, "./test/fixtures/invoices.csv"
invoices = invoice_repo.find_all_by(customer_id: "666")
assert_equal([], invoices)
end
end
| true |
c549e27e60022081b72455d93fa5d339851c1156
|
Ruby
|
iain/rule_table
|
/lib/rule_table.rb
|
UTF-8
| 1,554 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
require "rule_table/version"
module RuleTable
def self.matcher(name, &block)
matchers[name] = block
end
def self.matchers
@matchers ||= {}
end
def self.new(&block)
Table.new.tap { |table| TableDefiner.new(table, &block) }
end
class Table
def initialize
@rules = []
end
def add_rule_for(target, *matchers)
@rules << [ target, matchers ]
end
def match(object)
@rules.find { |(_target, matchers)|
matchers.all? { |m| m.matches?(object) }
}.first
end
def match_with_trace(object)
trace = []
result = @rules.find { |(target, matchers)|
partial_trace = { target: target, matched: [] }
matchers.all? { |m|
m.matches?(object).tap { |match_result|
partial_trace[:matched] << m.matcher_name if match_result
}
}.tap {
trace << partial_trace
}
}.first
[ result, trace ]
end
end
class TableDefiner
def initialize(table, &block)
@table = table
instance_eval(&block)
end
def rule(*args)
@table.add_rule_for(*args)
end
def match(matcher_name, *args)
ConfiguredMatcher.new(matcher_name, *args)
end
end
class ConfiguredMatcher
attr_reader :matcher_name
def initialize(matcher_name, *args)
@matcher_name = matcher_name
@matcher = RuleTable.matchers.fetch(matcher_name)
@args = args
end
def matches?(object)
object.instance_exec(*@args, &@matcher)
end
end
end
| true |
c163caf8c36471baf320edc8b0509f2bec8800d1
|
Ruby
|
olore/im_ron_burgundy
|
/test/object_test.rb
|
UTF-8
| 1,874 | 2.96875 | 3 |
[] |
no_license
|
require File.dirname(__FILE__) + '/test_helper'
class ObjectTest < Test::Unit::TestCase
def test_object_is_not_ron_burgundy
assert_equal 1, Object.methods.sort.grep(/im_ron_burgundy/).size
assert_equal false, Object.im_ron_burgundy?
end
def test_ron_burgundy_class_IS_ron_burgundy
dummy_class = Class.new
Object.const_set("RonBurgundy", dummy_class)
assert_equal true, RonBurgundy.im_ron_burgundy?
end
def test_ron_burgundy_class_instance_IS_ron_burgundy
dummy_class = Class.new
Object.const_set("RonaldBurgundy", dummy_class)
assert_equal true, RonaldBurgundy.new.im_ron_burgundy?
end
def test_object_is_ron_burgundy_if_name_is_ron_burgundy
dummy_class = Class.new {
def name
"Ron Burgundy"
end
}
Object.const_set("SomeClass", dummy_class)
assert_equal true, SomeClass.new.im_ron_burgundy?
end
def test_object_is_ron_burgundy_if_signature_quote
dummy_class = Class.new {
def signature_quote
"You stay classy, San Diego!"
end
}
Object.const_set("SomeOtherClass", dummy_class)
assert_equal true, SomeOtherClass.new.im_ron_burgundy?
end
def test_private_class_methods
assert_raise NoMethodError do
Object.check_class("foo")
end
assert_raise NoMethodError do
Object.check_string("foo")
end
end
def test_private_instance_methods
dummy_class = Class.new
Object.const_set("RonnieBurgundy", dummy_class)
assert_equal true, RonnieBurgundy.new.im_ron_burgundy?
assert_raise NoMethodError do
RonnieBurgundy.new.check_string("foo")
end
assert_raise NoMethodError do
RonnieBurgundy.new.check_class("foo")
end
assert_raise NoMethodError do
RonnieBurgundy.new.has_name?
end
assert_raise NoMethodError do
RonnieBurgundy.new.has_signature_quote?
end
end
end
| true |
d1efccd49694c9ac21aa159d23f220a536fcbe9b
|
Ruby
|
RobK-AA/registrationApp
|
/app/models/user.rb
|
UTF-8
| 1,348 | 2.75 | 3 |
[] |
no_license
|
class User < ApplicationRecord
validates :first_name, presence: true
validates :last_name, presence: true
validates :address_1, presence: true
validates :city, presence: true
validates :state, presence: true, inclusion: { in: ['AL', 'AK', 'AS', 'AZ', 'AR', 'CA', 'CO', 'CT', 'DE', 'DC', 'FM', 'FL', 'GA', 'GU', 'HI', 'ID', 'IL', 'IN', 'IA', 'KS', 'KY', 'LA', 'ME', 'MH', 'MD', 'MA', 'MI', 'MN', 'MS', 'MO', 'MT', 'NE', 'NV', 'NH', 'NJ', 'NM', 'NY', 'NC', 'ND', 'MP', 'OH', 'OK', 'OR', 'PW', 'PA', 'PR', 'RI', 'SC', 'SD', 'TN', 'TX', 'UT', 'VT', 'VI', 'VA', 'WA', 'WV', 'WI', 'WY']}
validates :zip, presence: true
validate :zip_code_must_be_five_or_nine_digits
validate :zip_code_must_contain_digits
validate :country_must_be_US
validates :country, presence: true
def zip_code_must_be_five_or_nine_digits
if zip.present? && (zip.length != 5 && zip.length != 9)
errors.add(:zip, "code must be 5 or 9 digits")
end
end
def zip_code_must_contain_digits
if zip.present? && (!zip.scan(/\D/).empty?)
errors.add(:zip, "code must only contain digits 0 - 9")
end
end
def country_must_be_US
if country.present? && (country != "US")
errors.add(:country, "not US. Registration requires US address")
end
end
end
| true |
e0c8c968ddddd6f5b125cb9e9bfc992cf5ecb866
|
Ruby
|
agdsarge/ruby-project-guidelines-wdc01-seng-ft-042020
|
/bin/interface/launch_investor_interface.rb
|
UTF-8
| 6,596 | 3.4375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def investor_help
system("clear")
puts "\n\n\n\n\n\n"
puts " quit"
puts " - this command will logout a user."
puts "\n"
puts " quote" # that i own
puts " - this command will print a position of a single equity."
puts " * require a company's ticker"
puts "\n"
puts " portfolio" #print all positions
puts " - this command will print all positions."
puts "\n"
puts " deposit" #deposit (monopoly money!)
puts " - this command will allow you to deposit money."
puts " * require an amount to deposit."
puts "\n"
puts " withdraw" # withdraw (sad times!)
puts " - this command will allow you to withdraw money."
puts " * require an amount to withdraw."
puts "\n"
puts " broker" #broker inquiry
puts " - this command will allow you to see your broker's contact information."
puts "\n"
puts " trade" #direct broker to action
puts " - this command will allow you to request your broker's assistance to buy and sell shares."
puts "\n"
puts " balance" #account_cash
puts " - this command will display your cash balance"
puts "\n"
gets
end
def logout
system("clear")
puts "\n\n\n\n\n\n"
puts " Goodbye!"
gets
end
def quote(invstr, tckr)
stock_hash = invstr.stock_position(tckr)
total_two_digits = stock_hash[:total_value]
puts "\n\n\n"
puts " Here is your position for #{stock_hash[:ticker].upcase}."
puts " You hold #{stock_hash[:shares]} shares."
puts " The total purchase price of this position is $#{'%.2f' % total_two_digits}"
gets
end
def quote_print(stk_hsh)
total_two_digits = stk_hsh[:total_value]
puts "\n\n"
puts " Here is your position for #{stk_hsh[:ticker].upcase}."
puts " You hold #{stk_hsh[:shares]} shares."
puts " The current market value of your shares is $#{'%.2f' % total_two_digits}"
gets
end
def portfolio_method(invstr)
x = invstr.all_positions
x.each {|sh| quote_print(sh)}
y = x.map {|sh| sh[:total_value]}.sum
y = '%.2f' % y
puts " Your total investment holdings amount to $#{y}"
gets
end
def display_broker_info(invstr)
arr = invstr.get_broker_contact
puts "\n\n\n\n\n\n"
puts " Your friendly broker is: #{arr[0]}"
puts " Their telephone number is: #{arr[1]}"
puts " Their email address is: #{arr[2]}"
gets
end
def cash_balance(invstr)
puts "\n\n\n"
invstr2 = Investor.find(invstr.id)
print " You have $#{'%.2f' % invstr2.account_cash} available."
gets
end
def deposit_method(invstr)
puts "\n\n\n\n\n\n"
print " How much would you like to deposit today?: "
amount = gets.chomp
invstr.add_cash(amount.to_f)
puts " Your deposit has gone through."
print " You have $#{'%.2f' % invstr.account_cash} available."
gets
end
def withdraw_method(invstr)
puts "\n\n\n\n\n\n"
print " How much would you like to withdraw today?: "
amount = gets.chomp.to_f
if amount < invstr.account_cash
invstr.withdraw_cash(amount)
puts " Your withdrawl has been transferred to your linked account."
print " You have $#{'%.2f' % invstr.account_cash} available."
else
puts " You cannot overdraw this account."
puts " You have $#{'%.2f' % invstr.account_cash} available."
puts " Please withdraw a valid amount."
end
gets
end
def direct_broker(invstr) #direct broker to action
puts "\n\n\n\n\n\n"
print " Would you like to buy or sell today?: "
cmd = gets.chomp
case cmd
when (/^buy$/i)
puts "\n\n\n"
print " What stock would you like to buy? (Please provide ticker): "
tckr = gets.chomp
puts "\n\n\n"
print " How many shares would you like to buy?: "
qty = gets.chomp
#invstr.broker.refresh_all_prices
invstr.broker.buy_stock_for_investor(invstr.id, tckr, qty.to_i)
cash_balance(invstr)
when (/^sell$/i)
puts "\n\n\n"
print " What stock would you like to sell today? (Please provide ticker): "
tckr = gets.chomp
puts "\n\n\n"
print " How many shares would you like to sell?: "
qty = gets.chomp
#invstr.broker.refresh_all_prices
invstr.broker.sell_stock_for_investor(invstr.id, tckr, qty.to_i)
cash_balance(invstr)
when "(/^cancel$/i)"
print " Request cancelled."
else
print " Invalid Command."
gets
direct_broker(invstr)
end
gets
end
def launch_investor_interface(invstr)
while true
system("clear")
puts "\n\n\n\n\n\n"
puts " Please type a command for PetS to execute"
puts " If you are unsure, enter 'help' for your options"
puts "\n\n\n"
print " "
input = gets.chomp
case input
when (/^h$|help/i) #help tested
puts ""
investor_help
when (/^quote$/i) #print a position of a single equity that i own tested
print " Do you know the company ticker?: "
tckr = gets.chomp
quote(invstr, tckr)
when (/^balance$/i) #print cash balace
cash_balance(invstr)
when (/^portfolio$/i) #print all positions tested
portfolio_method(invstr)
when (/^deposit$/i) #deposit (monopoly money!) #tested
deposit_method(invstr)
when (/^withdraw$/i) # withdraw (sad times!) valid deposit / overdraw tested.
withdraw_method(invstr)
when (/^broker$/i) #broker inquiry tested
display_broker_info(invstr)
when (/^trade$/i) #direct broker to action #tested
direct_broker(invstr)
when (/^quit$/i) #logout tested many many times
logout
break
when (/^exit$/i) #logout tested many many times
logout
break
else
puts "\n\n\n"
puts " I don't recognize that command!"
puts " Here's a bit of help!"
gets
investor_help
end
end
end
| true |
249ade0165c4ac0d60d3e9fb0b60fb51f127c0f1
|
Ruby
|
abcm1989/method_man
|
/lib/method_object.rb
|
UTF-8
| 4,259 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
require('method_object/version')
# See gemspec for description
class MethodObject
class AmbigousMethodError < NameError; end
class << self
def attrs(*attributes)
@attributes = attributes
Setup.call(attributes: attributes, subclass: self)
end
def call(**args)
new(args).call
end
attr_reader(:attributes)
private(:new)
def inherited(child_class)
child_class.instance_variable_set(:@attributes, [])
end
end
def initialize(_); end
def call
raise NotImplementedError, 'Define the call method'
end
def method_missing(name, *args, &block)
candidates = candidates_for_method_missing(name)
case candidates.length
when 0
super
when 1
delegate = candidates.first
define_delegated_method(delegate)
public_send(delegate.delegated_method, *args, &block)
else
handle_ambiguous_missing_method(candidates, name)
end
end
def respond_to_missing?(name)
candidates_for_method_missing(name).length == 1
end
def candidates_for_method_missing(method_name)
potential_candidates =
self.class.attributes.map do |attribute|
PotentialDelegator.new(
attribute,
public_send(attribute),
method_name,
)
end +
self.class.attributes.map do |attribute|
PotentialDelegatorWithPrefix.new(
attribute,
public_send(attribute),
method_name,
)
end
potential_candidates.select(&:candidate?)
end
def define_delegated_method(delegate)
code =
if delegate.method_to_call_on_delegate.to_s.end_with?('=')
<<-RUBY
def #{delegate.delegated_method}(arg)
#{delegate.attribute}.#{delegate.method_to_call_on_delegate}(arg)
end
RUBY
else
<<-RUBY
def #{delegate.delegated_method}(*args, &block)
#{delegate.attribute}
.#{delegate.method_to_call_on_delegate}(*args, &block)
end
RUBY
end
self.class.class_eval(code, __FILE__, __LINE__ + 1)
end
def handle_ambiguous_missing_method(candidates, method_name)
raise(
AmbigousMethodError,
"#{method_name} is ambiguous: " +
candidates
.map do |candidate|
"#{candidate.attribute}.#{candidate.method_to_call_on_delegate}"
end
.join(', '),
)
end
# Represents a possible match of the form:
# some_method => my_attribute.some_method
PotentialDelegator = Struct.new(:attribute, :object, :delegated_method) do
def candidate?
object.respond_to?(delegated_method)
end
alias_method(:method_to_call_on_delegate, :delegated_method)
end
# Represents a possible match of the form:
# my_attribute_some_method => my_attribute.some_method
PotentialDelegatorWithPrefix =
Struct.new(:attribute, :object, :delegated_method) do
def candidate?
name_matches? && object.respond_to?(method_to_call_on_delegate)
end
def method_to_call_on_delegate
delegated_method.to_s.sub(prefix, '')
end
private
def name_matches?
delegated_method.to_s.start_with?(prefix)
end
def prefix
"#{attribute}_"
end
end
# Dynamically defines custom attr_readers and initializer
class Setup < SimpleDelegator
def self.call(attributes:, subclass:)
new(attributes, subclass).call
end
attr_accessor(:attributes)
def initialize(attributes, subclass)
self.attributes = attributes
super(subclass)
end
def call
define_attr_readers
define_initializer
end
private
def define_attr_readers
__getobj__.send(:attr_reader, *attributes)
end
def attr_accessor(attribute)
super
end
def define_initializer
class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
def initialize(#{required_keyword_args_string})
#{assignments}
end
RUBY
end
def required_keyword_args_string
attributes.map { |arg| "#{arg}:" }.join(', ')
end
def assignments
attributes.map { |attribute| "@#{attribute} = #{attribute}\n" }.join
end
end
end
| true |
62144e351c6b1db423c486b73944882f9089b3d9
|
Ruby
|
NoSoft-SA/crossbeams-layout
|
/lib/crossbeams/layout/progress_step.rb
|
UTF-8
| 3,449 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
module Crossbeams
module Layout
# A progress steps renderer - for displaying positioin in amulti-step process.
class ProgressStep
include PageNode
attr_reader :steps, :page_config, :position, :state_description,
:show_finished, :current_step_id, :size
SIZES = %i[small medium default].freeze
def initialize(page_config, steps, opts = {})
@steps = steps
@page_config = page_config
@nodes = []
init_position(opts[:position])
init_finished(opts[:show_finished])
check_size(opts)
@state_description = Array(opts[:state_description])
@current_step_id = opts[:current_step_id] || 'cbl-current-step'
end
# Is this control invisible?
def invisible?
false
end
# Is this control hidden?
def hidden?
false
end
# Render the control
def render
<<-HTML
<div class="cbl-progress-bar-wrapper"#{max_size}>
<div class="cbl-progress-status-bar" style="width: #{status_bar_width}%;">
<div class="cbl-current-status" style="width: #{current_position}%; transition: width 4500ms linear;">
</div>
</div>
<ul class="cbl-progress-bar">
#{render_steps}
</ul>
</div>
#{render_state}
HTML
end
private
def max_size
case size
when :small
' style=max-width:30rem"'
when :medium
' style=max-width:60rem"'
else
''
end
end
def status_bar_width
100.0 - step_width
end
def current_position
return 0 if position.zero?
100.0 / (steps.length - 1) * position
end
def render_steps
width = step_width
steps.map.with_index do |step, index|
css_class = ['cbl-step']
css_class += position_classes(index, position)
id = position_id(index, position)
%(<li class="#{css_class.join(' ')}"#{id} style="width: #{width}%;">#{step}</li>)
end.join("\n")
end
def position_classes(index, position)
classes = []
classes << 'visited' if position > index
if position == index
if show_finished
classes << 'visited'
classes << 'current'
else
classes << 'busy'
end
end
classes
end
def position_id(index, position)
position == index ? %( id="#{current_step_id}") : ''
end
def step_width
(100.0 / steps.length).floor(2)
end
def render_state
return nil if state_description.empty?
<<-HTML
<div class="cbl-progress-bar-text">
<ul class="cbl-progress-state">
#{state_description.map { |d| "<li>#{d}</li>" }.join("\n")}
</ul>
</div>
HTML
end
def init_position(value)
@position = [(value || 0).abs, steps.length - 1].min
end
def init_finished(value)
@show_finished = value && position == steps.length - 1
end
def check_size(opts)
@size = opts[:size] || :default
raise ArgumentError, "Size must be one of #{SIZES.join(', ')}" unless SIZES.include?(@size)
end
end
end
end
| true |
b477a0cf80604c9b89b42b2e7cc523d25b15d9c5
|
Ruby
|
xijo/adventofcode-2020
|
/day07/day07b.rb
|
UTF-8
| 521 | 3.265625 | 3 |
[] |
no_license
|
require 'fileutils'
tree = {}
puts ARGV.first || 'input'
File.read('day07/input').each_line do |line|
bag = line[/\A\w+\s\w+/]
tree[bag] = {}
if line.end_with?('contain no other bags')
else
line.scan(/(\d+\s\w+\s\w+)/).each do |match|
tree[bag][match.first[/\w+\s\w+\z/]] = match.first[/\d+/].to_i
end
end
end
def bag_count(bag, tree)
return 1 if tree[bag].keys.empty?
tree[bag].inject(1) do |i, (k, v)|
i + (bag_count(k, tree) * v)
end
end
puts bag_count('shiny gold', tree) - 1
| true |
c29e66d7cb7f3aae017e097aa04ae410efeab0a4
|
Ruby
|
fanjieqi/LeetCodeRuby
|
/1201-1300/1292. Maximum Side Length of a Square with Sum Less than or Equal to Threshold.rb
|
UTF-8
| 749 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
# @param {Integer[][]} mat
# @param {Integer} threshold
# @return {Integer}
def max_side_length(mat, threshold)
n, m = mat.size, mat[0].size
row_sum, sum = [], []
sum[0] = (0..m).map { 0 }
(0..n-1).each do |i|
row_sum[i] ||= [0]
sum[i+1] ||= [0]
(0..m-1).each do |j|
row_sum[i][j+1] = row_sum[i][j].to_i + mat[i][j]
sum[i+1][j+1] = sum[i][j+1] + row_sum[i][j+1]
end
end
l, r = 1, [n, m].min
while l <= r
mid = (l + r) / 2
tmp = 0
result = (0..n-mid).any? do |i|
(0..m-mid).any? do |j|
tmp = sum[i+mid][j+mid] - sum[i][j+mid] - sum[i+mid][j] + sum[i][j]
tmp <= threshold
end
end
if result
l = mid + 1
else
r = mid - 1
end
end
l-1
end
| true |
4a976a73577e32d1147e9234523296cd898d81fc
|
Ruby
|
JackNolan/playlister-rb
|
/lib/song.rb
|
UTF-8
| 130 | 2.78125 | 3 |
[] |
no_license
|
class Song
attr_accessor :genre, :name, :artist
def initialize
end
def genre=(gen)
@genre = gen
gen.add_song self
end
end
| true |
0c363bebf6e4b4c4e443d361e96c73acdef51a01
|
Ruby
|
icortex/mongoid_ext
|
/lib/mongoid_ext/filter/parser.rb
|
UTF-8
| 1,479 | 2.8125 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module MongoidExt
module Filter
class Parser
def initialize(stemmer)
@stemmer = stemmer
end
def parse(query)
query, quotes = parse_quoted_text(query)
query, ops = parse_operators(query)
query.gsub!(/\s+/, ' ')
query.gsub!(/\?|\!|\:|\)|\(/, "")
words = Set.new(query.downcase.split(/\s+/))
stemmed = stem(words)
tokens = words + stemmed
{:query => query,
:words => words,
:stemmed => stemmed,
:operators => ops,
:tokens => tokens,
:quotes => quotes}
end
private
def parse_quoted_text(query)
quotes = []
loop do
m = query.match(/"([^"]+"|-)/)
if m
query = $` + $'
quotes << m[1].gsub('"', "")
else
break
end
end
[query, quotes]
end
def parse_operators(query)
ops = {}
loop do
m = query.match(/(is|lang|not|by|score):(\S+)/)
if m
query = $` + $'
(ops[m[1]] ||= []) << m[2]
else
break
end
end
[query, ops]
end
def stem(words)
tokens = []
if @stemmer
words.each do |word|
stem = @stemmer.stem(word)
tokens << stem if word.size > 2 && !words.include?(stem)
end
end
tokens
end
end
end
end
| true |
d1079bbcfe6a7d91e13032647765aef5a7a9c0b1
|
Ruby
|
matDobek/memo
|
/src/use_cases/system/import_data_from_directory/directory_parser.rb
|
UTF-8
| 697 | 2.796875 | 3 |
[] |
no_license
|
module UseCases::System
module ImportDataFromDirectory
class DirectoryParser
def initialize(directory)
@directory = directory
end
def parsed_collection
return [] if invalid_directory?
collection = []
file_paths.each do |rel_path|
file_content = File.read "#{directory}/#{rel_path}"
collection << FileContentParser.new(file_content).parsed_collection
end
collection.flatten
end
private
attr_reader :directory
def invalid_directory?
directory.nil? || !Dir.exists?(directory)
end
def file_paths
Dir.children(directory)
end
end
end
end
| true |
512012cd8400621d65d191cb9d8dc08bcfa4c943
|
Ruby
|
msvickylau/ttt-7-valid-move-v-000
|
/lib/valid_move.rb
|
UTF-8
| 210 | 3.125 | 3 |
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
# code your #valid_move? method here
def valid_move?(board, index)
if board[index] == " "
move = true
elsif board[index] == "X" || board[index] == "O"
move = false
else
move = false
end
end
| true |
223f13db33def467d1edfe8dec8a9f4a51e39b95
|
Ruby
|
MHS-QA-Forked/cracking-the-coding-interview
|
/spec/2.5.a_spec.rb
|
UTF-8
| 493 | 2.828125 | 3 |
[] |
no_license
|
require_relative 'spec_helper'
require_relative '../chapter2/linked_list'
require_relative '../chapter2/list_node'
require_relative '../chapter2/2.5.a'
describe 'sum of reverse lists' do
it 'returns the sum of the nodes two linked lists' do
first_list = LinkedList.new(3)
first_list.add(5)
first_list.add(7)
second_list = LinkedList.new(4)
second_list.add(6)
second_list.add(8)
expect(sum_of_reverse_lists(first_list, second_list)).to eq('1->6->1->7')
end
end
| true |
fabb23858c7deb939ecb0298ed8a05a5799af618
|
Ruby
|
BillBarnhill/bcpm
|
/lib/bcpm/tests/test_match.rb
|
UTF-8
| 4,194 | 2.71875 | 3 |
[] |
no_license
|
require 'tmpdir'
# :nodoc: namespace
module Bcpm
# :nodoc: namespace
module Tests
# A match run for simulation purposes.
#
# Each test case is its own anonymous class.
class TestMatch
# Side of the tested player in the match.
attr_reader :side
# Name of opposing player in the match.
attr_reader :vs
# Name of map for the match.
attr_reader :map
# Custom options for the battlecode simulator.
attr_reader :options
# The environment that the match runs in.
attr_reader :environment
# Match output. Nil if the match hasn't completed.
attr_reader :output
# Detailed match data.
attr_reader :data
# Skeleton for a match.
def initialize(side, vs, map, environment, options = {})
@side = side
@vs = vs
@map = map
@options = options.clone
@environment = environment
@output = nil
@data = nil
@output_lines = nil
@outcome = nil
@winner = nil
@reason = nil
end
# Run the game.
def run(live = false)
case @side
when :a
@data = Bcpm::Match.match_data @environment.player_name, @vs, true, @map, live, @options
when :b
@data = Bcpm::Match.match_data @vs, @environment.player_name, false, @map, live, @options
end
@output = data[:ant]
end
# True if the test match has run, and its results are available.
def ran?
!output.nil?
end
# User-readable description of match conditions.
def description
if File.basename(map) == map
map_name = map
else
map_name = "suite/maps/#{File.basename(map).sub(/\.xml$/, '')}"
end
desc = "as team #{side.to_s.upcase} vs #{vs} on #{map_name}"
unless @options.empty?
desc += ' with ' + options.map { |k, v| "#{k}=#{v}" }.join(",")
end
desc
end
# The match output, split into lines.
def output_lines
@output_lines ||= output.split("\n")
end
# The output printed by map units, without the [source] prefixess.
def chatter
@chatter ||= output_lines.map { |line| line.gsub /^\[[^\]]+\]\s/, '' }.reject(&:empty?).join("\n")
end
# The output line showing who won the game.
def outcome
return @outcome if @outcome
@outcome = output_lines[-3] || ''
@outcome = '(no victory)' unless outcome.index('wins')
@outcome
end
# The side that own the game
def winner
return @winner if @winner
win_match = /\((.)\) wins/.match outcome
@winner = if win_match
(win_match[1] == 'A') ? :a : :b
else
:error
end
@winner
end
# The output line showing the reason the game ended.
def reason
return @reason if @reason
@reason = output_lines[-2] || ''
@reason = '(no reason)' unless reason.index('Reason:')
@reason
end
# Stashes the match data somewhere on the system.
#
# Returns a string containing user-friendly instructions for accessing the match data.
def stash_data
path = self.class.gamesave_path
FileUtils.mkdir_p path
txt_path = File.join path, data[:uid] + '.txt'
File.open(txt_path, 'wb') { |f| f.write output } unless File.exist?(txt_path)
rms_path = File.join path, data[:uid] + '.rms'
File.open(rms_path, 'wb') { |f| f.write data[:rms] } unless File.exist?(rms_path)
"Output: #{open_binary} #{txt_path}\nReplay: bcpm replay #{rms_path}\n"
end
# All game replays saved by calls to stash_data.
def self.stashed_replays
Dir.glob File.join(gamesave_path, '*.rms')
end
# All game outputs saved by calls to stash_data.
def self.stashed_outputs
Dir.glob File.join(gamesave_path, '*.txt')
end
# Path where game data (output, replay binlog) is saved.
def self.gamesave_path
Bcpm::Config[:gamesave_path] ||= default_gamesave_path
end
# Path where game data (output, replay binlog) is saved.
def self.default_gamesave_path
File.join Dir.tmpdir, 'bcpm'
end
# Name of program for opening text files.
def open_binary
return ENV['EDITOR'] if ENV['EDITOR']
case RUBY_PLATFORM
when /darwin/
'open'
when /win/
'notepad'
when /linux/
'gedit'
end
end
end # class Bcpm::Tests::TestMatch
end # namespace Bcpm::Tests
end # namespace Bcpm
| true |
4b08e7234b078a8f3fa02fb5b44c98c86dd0e0cb
|
Ruby
|
samcassie/five_a_side_programme
|
/models/specs/player_specs.rb
|
UTF-8
| 965 | 2.828125 | 3 |
[] |
no_license
|
require("minitest/autorun")
require('minitest/reporters')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
require_relative("../player.rb")
class TestPlayer < MiniTest::Test
def setup()
options1 = {
'first_name' => 'Sam',
'second_name' => 'Cassie',
'age' => 23,
'position' => 'CM'
}
options2 = {
'first_name' => 'Pete',
'second_name' => 'Smith',
'age' => 20,
'position' => 'CF',
}
@player1 = Player.new(options1)
@player2 = Player.new(options2)
end
def test_player_first_name
assert_equal('Sam', @player1.first_name)
end
def test_player_second_name
assert_equal('Smith', @player2.second_name)
end
def test_player_age
assert_equal(20, @player2.age)
end
def test_player_position
assert_equal('CM', @player1.position)
end
end
| true |
b501afd1892b7a3a4b488db328776173f3f39afb
|
Ruby
|
bluepostit/696-food-delivery
|
/app/views/orders_view.rb
|
UTF-8
| 530 | 3.03125 | 3 |
[] |
no_license
|
class OrdersView
def display(orders)
orders.each_with_index do |order, index|
puts "#{index + 1}. #{order.meal.name} ➡️ #{order.customer.address} - #{order.employee.username} #{order.delivered?}"
end
end
def ask_user_for(item)
puts "Please enter the #{item}"
print '> '
gets.chomp
end
def display_riders(riders)
riders.each_with_index do |rider, index|
puts "#{index + 1}. #{rider.username}"
end
end
def ask_user_for_index
ask_user_for('number').to_i - 1
end
end
| true |
f8e27a772f9953737310b959330a342ef86f5e25
|
Ruby
|
LMacchi/scripts
|
/parse_trusted_facts/parse_trusted_facts.rb
|
UTF-8
| 1,971 | 2.703125 | 3 |
[] |
no_license
|
#!/opt/puppetlabs/puppet/bin/ruby
require 'optparse'
require 'puppet'
require 'puppetdb'
class TrustedFact
attr_accessor :cert, :name, :value
def initialize
@cert = ''
@name = ''
@value = ''
end
end
def parse_opts
options = {}
help = OptionParser.new do |opts|
opts.banner = "Usage: #{$0}"
opts.on('-c ^.puppetlabs.vm$', '--certnames ^.puppetlabs.vm$', 'Pattern to filter certnames') do |c|
options[:cert] = c
end
opts.on('-f pp_role', '--fact pp_role', 'Trusted fact name') do |f|
options[:fact] = f
end
opts.on('-v master', '--value master', 'Trusted fact value') do |v|
options[:value] = v
end
opts.on('-h', '--help', 'Display this help') do
puts opts
exit
end
end
help.parse!
return options, help
end
def build_query
"facts { name = \"trusted\" }"
end
def build_query_certs(certs)
"facts { name = \"trusted\" and certname ~ \"#{certs}\" }"
end
def run_query(query)
# Assumes mono server
Puppet.initialize_settings
client = PuppetDB::Client.new({
:server => "https://#{Puppet.settings[:certname]}:8081",
:pem => {
'key' => Puppet.settings[:hostprivkey],
'cert' => Puppet.settings[:hostcert],
'ca_file' => Puppet.settings[:localcacert]
}})
response = client.request('', query)
response.data
end
def load_facts(results)
facts = []
results.each do |r|
r['value']['extensions'].each do |k,v|
f = TrustedFact.new
f.cert = r['certname']
f.name = k
f.value = v
facts.push f
end
end
facts
end
def filter_facts(facts, fact, value)
facts.select { |f| f.name.match?(/#{fact}/) and f.value.match?(/#{value}/) }
end
options, help = parse_opts()
query = options[:cert].nil? ? build_query : build_query_certs(options[:cert])
facts = load_facts(run_query(query))
filtered = filter_facts(facts, options[:fact], options[:value])
filtered.each do |f|
puts f.cert
end
| true |
973f4a9ba2be69dad2a5e644d685581313c86eee
|
Ruby
|
igorsimdyanov/ruby
|
/blocks/map_full_block.rb
|
UTF-8
| 106 | 3.375 | 3 |
[] |
no_license
|
p( [1, 2, 3, 4, 5].map do |x| x * x end )
arr = [1, 2, 3, 4, 5].map do |x|
x * x
end
p arr
| true |
019c621f0f0e06676d33667755658366bf5afb86
|
Ruby
|
benclifford79/sys-uptime
|
/lib/linux/sys/uptime.rb
|
UTF-8
| 2,145 | 3.40625 | 3 |
[] |
no_license
|
# The Sys module serves as a namespace only.
module Sys
# The Uptime class encapsulates various bits of information regarding your
# system's uptime, including boot time.
class Uptime
# Error typically raised in one of the Uptime methods should fail.
class Error < StandardError; end
# The version of the sys-uptime library.
VERSION = '0.5.4'
# The file to read uptime information from.
UPTIME_FILE = '/proc/uptime'
# Returns the total number of seconds of uptime.
#
# Example:
#
# Sys::Uptime.seconds # => 118800
#
def self.seconds
begin
IO.read(UPTIME_FILE).split.first.to_i
rescue Exception => err
raise Error, err
end
end
# Returns the total number of minutes of uptime.
#
# Example:
#
# Sys::Uptime.minutes # => 678
#
def self.minutes
self.seconds / 60
end
# Returns the total number of hours of uptime.
#
# Example:
#
# Sys::Uptime.hours # => 31
#
def self.hours
self.minutes / 60
end
# Returns the total number of days of uptime.
#
# Example:
#
# Sys::Uptime.days # => 2
#
def self.days
self.hours / 24
end
# Returns the uptime as a colon separated string, including days,
# hours, minutes and seconds.
#
# Example:
#
# Sys::Uptime.uptime # => "1:9:24:57"
#
def self.uptime
seconds = self.seconds
days = seconds / 86400
seconds -= days * 86400
hours = seconds / 3600
seconds -= hours * 3600
minutes = seconds / 60
seconds -= minutes * 60
"#{days}:#{hours}:#{minutes}:#{seconds}"
end
# Returns the uptime as a four element array, including days, hours,
# minutes and seconds.
#
# Example:
#
# Sys::Uptime.dhms # => [1,9,24,57]
#
def self.dhms
self.uptime.split(":")
end
# Returns the time the system was booted as a Time object.
#
# Example:
#
# Sys::Uptime.boot_time
#
def self.boot_time
Time.now - self.seconds
end
end
end
| true |
87cf834752ccc9479c94eadfdccebe40a63c6f6f
|
Ruby
|
nagata03/Ruby_Cherry
|
/lib/proc_lambda_return_break.rb
|
UTF-8
| 456 | 3.796875 | 4 |
[] |
no_license
|
def proc_return
f = Proc.new { |n| return n * 10 }
ret = [1, 2, 3].map(&f)
"ret: #{ret}"
end
def lambda_return
f = ->(n) { return n * 10 }
ret = [1, 2, 3].map(&f)
"ret: #{ret}"
end
p proc_return
p lambda_return
puts
#def proc_break
# f = Proc.new { |n| break n * 10 }
# ret = [1, 2, 3].map(&f)
# "ret: #{ret}"
#end
def lambda_break
f = ->(n) { break n * 10 }
ret = [1, 2, 3].map(&f)
"ret: #{ret}"
end
#p proc_break
p lambda_break
| true |
b8b428045c117ac2bece938bf43d4e7900281a10
|
Ruby
|
Jose59300/6-exo-rb
|
/exo_2.rb
|
UTF-8
| 441 | 3.640625 | 4 |
[] |
no_license
|
#exo 2 - Table de multiplication
#L’utilisateur devrait renseigne un nombre de 1 chiffre
#Le résultat affichera :
#La table de multiplication du chiffre ##chiffre saisie## est :
#1 * chiffre saisie = chiffre saisie * 1
#2 * …
#3 *
#…
#10 *
multiplication = gets.chomp.to_i
puts 'la table de multiplication du chiffre #{multiplication} est :'
for chiffre in 0..10
puts '#{chiffre} * #{multiplication} = #{multiplication * chiffre}'
| true |
e4618bb7354769d4f7edcd33d51194deb73cf583
|
Ruby
|
jdleesmiller/si_taxi
|
/lib/si_taxi/mdp_model_a.rb
|
UTF-8
| 9,295 | 3.03125 | 3 |
[] |
no_license
|
module SiTaxi
class MDPStateA < MDPStateBase
def initialize model
super model
@queue = [0]*model.num_stations
@destin = [0]*model.num_veh
@eta = [0]*model.num_veh
end
#
# Create state from array representation (see to_a).
#
def self.from_a model, a
state = self.new(model)
ns, nv = model.num_stations, model.num_veh
state.queue = a[0, ns]
state.destin = a[ns, nv]
state.eta = a[ns+nv, nv]
state
end
attr_accessor :queue, :destin, :eta
#
# Mutate this state into the 'next' state in numerical order.
#
# @return [Boolean] true iff the new state is not state zero
#
def next!
Utility.spin_array(queue, @model.max_queue) ||
Utility.spin_array(destin, @model.num_stations - 1) ||
Utility.spin_array(eta, @model.max_time.max)
end
#
#
# @return [Array<Integer>] indexes of vehicles idle at station i
#
def idle_vehicles_at i
@model.vehicles.select {|k| destin[k] == i && eta[k] == 0}
end
#
# Feasible iff there is no station with both waiting passengers and idle
# vehicles and travel times are in range.
#
# @return [Boolean]
#
def feasible?
@model.stations.all? {|i| queue[i] == 0 ||
(idle_vehicles_at(i).empty? && @model.demand.rate_from(i) > 0)} &&
@model.vehicles.all? {|k| eta[k] <= @model.max_time[destin[k]]}
end
#
# Update expected time to arrival (eta) based on old destinations (state)
# and current destinations. If a vehicle's ETA is larger than 1, it is just
# decremented; otherwise, it's set to the trip time between its old and new
# destination.
#
def set_eta_from state
@model.vehicles.each do |k|
if self.eta[k] > 1
self.eta[k] -= 1
else
self.eta[k] = @model.trip_time[state.destin[k]][self.destin[k]]
end
end
nil
end
#
# Redefine dup to be a deep copy instead of a shallow copy.
#
def dup
copy = super
copy.queue = self.queue.dup
copy.destin = self.destin.dup
copy.eta = self.eta.dup
copy
end
def to_a
queue + destin + eta
end
end
class MDPModelA < MDPModelBase
#
# Yield for each state in numeric order.
#
# @yield [state] a copy of the current state; you can modify it without
# affecting the iteration
#
def with_each_state
state = MDPStateA.new(self)
begin
yield state.dup if state.feasible?
end while state.next!
nil
end
#
# @return [Array] array of states
#
def states
states = []
with_each_state do |state|
states << state
end
states
end
#
# Yield for each action in numeric order. Note that the actions yielded may
# not be feasible for some states.
#
# @yield [action]
#
def with_each_action
action = [0] * num_veh
begin
yield action.dup
end while Utility.spin_array(action, num_stations - 1)
nil
end
#
# Yield for each feasible action from the given state, in numeric order.
#
# @param [Array<Integer>] state not modified
#
# @yield [action]
#
def with_each_action_for state
# can only move idle vehicles; can move to any destination
with_each_action do |action|
yield action if vehicles.all? {|k|
action[k] == state.destin[k] || state.eta[k] == 0}
end
end
#
# Yield for each possible successor state of state under action.
#
# Note: we currently enumerate all possible permutations of passenger
# destinations; we could instead enumerate only the numbers of requests
# per destination (must sum to total requests), because the difference is
# just in the order in which we assign the idle vehicles.
#
# @param [MDPStateA] state
#
# @param [Array<Integer>] action
#
# @yield [state]
#
def with_each_successor_state state, action
# find vehicles already idle (eta 0) or about to become idle (eta 1),
# but ignore those that are moving away due to the action
available = stations.map {|i| vehicles.select {|k|
state.destin[k] == i && state.eta[k] <= 1 && action[k] == i}}
#puts "available: #{available.inspect}"
# for each station, the basic relationship is:
# new_queue = max(0, queue + new_pax - (idle + landing - leaving))
# because there can't be both idle vehicles and waiting passengers;
# we want all values of new_pax that make new_queue <= max_queue
max_new_pax = stations.map {|i|
max_queue - state.queue[i] + available[i].count}
new_pax = [0]*num_stations
begin
# add new pax to waiting pax (note that this may exceed max_queue)
# need to know how many pax we can serve now (rest must queue)
pax_temp = stations.map {|i| state.queue[i] + new_pax[i]}
pax_served = stations.map {|i| [available[i].count, pax_temp[i]].min}
#puts "state: #{state.inspect}"
#puts "pax_temp: #{pax_temp}"
#puts "pax_served: #{pax_served}"
# update queue states
new_state = state.dup
new_state_pr = 1.0
stations.each do |i|
new_state.queue[i] = pax_temp[i] - pax_served[i]
pr_i = demand.poisson_origin_pmf(i, new_pax[i])
pr_i += demand.poisson_origin_cdf_complement(i, new_pax[i]) if
new_state.queue[i] == max_queue
raise "bug: pr_i > 1" if pr_i > 1
new_state_pr *= pr_i
end
# update vehicles due action
new_state.destin = action.dup
# the above generates states with non-zero queues at stations with zero
# arrival rates, which would cause us to generate infeasible states
if new_state_pr > 0
# need to know destinations for any pax we're serving
journey_product = stations.map {|i|
journeys_from_i = stations.map {|j| [i, j] if i != j}.compact
Utility.cartesian_product(*[journeys_from_i]*pax_served[i])}.compact
#puts "new_state: #{new_state.inspect}"
#puts "journey_product:\n#{journey_product.inspect}"
if journey_product.empty?
# no passengers served; just yield new_state
new_state.set_eta_from(state)
yield new_state, new_state_pr
else
Utility.cartesian_product(*journey_product).each do |journeys|
available_for_pax = available.map{|ai| ai.dup}
pax_state = new_state.dup
pax_state_pr = new_state_pr
#puts "journeys: #{journeys.inspect}"
journeys.flatten(1).each do |i, j|
pax_state.destin[available_for_pax[i].shift] = j
pax_state_pr *= demand.at(i, j) / demand.rate_from(i)
#puts "pax_state: #{pax_state.inspect}"
end
pax_state.set_eta_from(state)
#puts "pax_state: #{pax_state.inspect}"
yield pax_state, pax_state_pr
end
end
end
#
#p stations.map {|i|
# journeys = stations.purge(i).map {|j| [i, j] }
# Utility.cartesian_product(*[journeys]*pax_served[i])}
#pax_stations = stations.select {|i| pax_served[i] > 0}
#puts "pax_stations: #{pax_stations.inspect}"
#pax_destins = pax_stations.map {|i| [stations.purge(i)] * pax_served[i]}
#puts "pax_destins: #{pax_destins.inspect}"
## [1,0,2]
## [[1,2,3],[],[0,1,3,0,1,3]]
## or
## [1,0]
## [[1],[]]
#pax_destins = Utility.cartesian_product(*pax_destins)
#if pax_destins
# puts "pax_destins: #{pax_destins.inspect}"
# pax_destins.each do |pax_destin|
# puts "pax_destin: #{pax_destin}"
# pax_stations.zip(pax_destin).each do |i, destins_i|
# available_i = new_state.available_vehicles_at(i)
# pax_state = new_state.dup
# available_i.zip(destins_i).each do |k, destin_i|
# pax_state.destin[k] = destin_i
# pax_state.set_eta_from(state)
# pax_state_pr = new_state_pr * demand.at(i, destin_i) /
# demand.rate_to(destin_i)
# p pax_state
# yield pax_state, pax_state_pr
# end
# end
# end
#else
# # no passengers served; just yield new_state
# new_state.set_eta_from(state)
# yield new_state, new_state_pr
#end
end while Utility.spin_array(new_pax, max_new_pax)
end
#
# Build the explicit transition matrices (as nested Hashes).
#
# @return Hash
#
def to_hash
# set up nested hashes using appropriate missing value defaults
hash = Hash.new {|h0,k0|
h0[k0] = Hash.new {|h1,k1|
h1[k1] = Hash.new {[0,0]} } }
with_each_state do |s0|
with_each_action_for(s0) do |a|
with_each_successor_state(s0, a) do |s1, pr|
hash[s0][a][s1] = [pr, s0.reward]
end
end
end
hash
end
end
end
| true |
94261ab16537229c7a1330661fef448c10e61d67
|
Ruby
|
joeypoon/iron_yard
|
/day-2.rb
|
UTF-8
| 1,373 | 4.125 | 4 |
[] |
no_license
|
#Create an array of the words in the sentence below
# "Tacos must not have lettuce. Only meat and cheese and salsa."
tacos = "Tacos must not have lettuce. Only meat and cheese and salsa.".split('.').join(' ').split(' ')
print tacos
#Find how many words have a length equal to 5
length_five = tacos.select do |word|
word.length == 5
end
how_many_length_five = length_five.length
puts
puts "Number of words in tacos array that are 5 characters long:"
puts how_many_length_five
#*******#
movies = []
movies << {
title: "Forest Gump",
budget: 55,
stars: ["Tom Hanks"]
}
movies << {
title: "Star Wars",
budget: 11,
stars: ["Mark Hamill", "Harrison Ford"]
}
movies << {
title: "Batman Begins",
budget: 150,
stars: ["Christian Bale", "Liam Neeson", "Michael Caine"]
}
movies << {
title: "Titanic",
budget: 200,
stars: ["Kate Winslet", "Leonardo DiCaprio"]
}
movies << {
title: "Inception",
budget: 160,
stars: ["Leonardo DiCaprio", "JGL"]
}
#Create an array of movies with budgets less than 100
low_budget = 100
low_budget_movies = movies.select do |movie|
movie[:budget] < low_budget
end
puts
puts "Movies with a low budget (< 100):"
puts low_budget_movies
#Create an array of movies that have Leonardo DiCaprio as a star
star = "Leonardo DiCaprio"
movies_with_star = movies.select do |movie|
movie[:stars].include? star
end
puts
puts "Movies that star #{star}"
puts movies_with_star
| true |
bd6c558c1c63d42c7d0a40ed47c7e4591377421c
|
Ruby
|
rdsavage10/The-Bank
|
/the_bank.rb
|
UTF-8
| 4,039 | 3.59375 | 4 |
[] |
no_license
|
#the_bank.rb
require_relative 'bank_classes'
@customers = []
def welcome_screen
clear_screen
@current_customer = ''
puts 'Welcome to the Bank of Savage'
puts 'Please choose from the following'
puts '--------------------------------'
puts '1. Customer Sign-In'
puts '2. New Customer Registration'
choice = gets.chomp.to_i
case choice
when 1
sign_in
when 2
sign_up('','')
else
puts "Invalid Selection"
welcome_screen
end
end
def sign_in
clear_screen
print "What's your name? "
name = gets.chomp
print "what's your password "
password = Digest::SHA1.hexdigest gets.chomp + name.downcase
customer_exists = false
@customers.each do |customer|
if name == customer.name && password == customer.password
@current_customer = customer
customer_exists = true
end
end
if customer_exists
account_menu
else
puts 'No customer found with that information'
puts '1. Try again?'
puts '2. Sign up'
choice = gets.chomp.to_i
case choice
when 1
sign_in
when 2
sign_up(name,password)
else
puts "Invalid Selection"
end
end
end
def sign_up(name, password)
clear_screen
if name == '' && password == ''
print "what's your name? "
name = gets.chomp
print "What's your password? "
password = Digest::SHA1.hexdigest gets.chomp + name.downcase
end
@current_customer = Customer.new(name, password)
@customers.push(@current_customer)
puts "Registration Successful"
account_menu
end
def account_menu
clear_screen
puts "Account Menu"
puts "---------------"
puts "1. Create an Account"
puts "2. Review an Account"
puts "3. Sign Out"
choice = gets.chomp.to_i
case choice
when 1
create_account
when 2
review_account
when 3
puts "Thanks for banking with Savage Bank"
welcome_screen
else
puts "Invalid Selection"
account_menu
end
end
def create_account
clear_screen
puts "What type of account would you like to open? "
acct_type = gets.chomp
amount = 0
until amount > 0
puts "How much will your first depoiste be? "
print "$"
amount = gets.chomp.to_f
end
new_acct = Account.new(amount, (@current_customer.accounts.length+1), acct_type)
@current_customer.accounts.push(new_acct)
puts "Account created Successfully!"
account_menu
end
def review_account
clear_screen
if @current_customer.accounts.empty?
puts "No accounts available"
puts "Press 'enter' to continue"
gets.chomp
account_menu
end
@current_account = ""
@current_customer.accounts.each do |x|
puts "Current accounts #{x.acct_type}" if x.customer == @current_customer
end
print "Which account (type) do you want to review? "
type = gets.chomp.downcase
account_exists = false
@current_customer.accounts.each do |account|
if type == account.acct_type.downcase
@current_account = account
account_exists = true
puts account.acct_type.downcase
end
end
if account_exists
current_account_actions
else
puts "Try Again"
review_account
end
end
def current_account_actions
puts "Choose from the following:"
puts "---------------------------"
puts "1. Balance Check"
puts "2. Make a Deposit"
puts "3. Make a Withdrawal"
puts "4. Return to Account Menu"
puts "5. Sign Out"
choice = gets.chomp.to_i
case choice
when 1
clear_screen
puts "Current balance is $#{format('%0.2f', @current_account.balance)} "
current_account_actions
when 2
clear_screen
@current_account.deposit
current_account_actions
when 3
clear_screen
@current_account.withdrawal
current_account_actions
when 4
account_menu
when 5
welcome_screen
else
puts "Invalid Selection"
current_account_actions
end
end
def clear_screen
system "cls" or system "clear"
end
welcome_screen
puts "Drew Was Here"
| true |
058a53148cfb39f1ccdd2a40d1f9dab0658cd795
|
Ruby
|
tonymj76/ruby-tut
|
/Quest01/ex05/my_isinteger.rb
|
UTF-8
| 163 | 3.3125 | 3 |
[] |
no_license
|
#check the type of variable parameter
def my_isinteger(n)
case n
when Integer
return 1
else
return 0
end
end
puts my_isinteger(6)
| true |
672a2d95306693fb58d898e4d05d2d49f891d3b5
|
Ruby
|
bhuga/quantity
|
/spec/unit.spec
|
UTF-8
| 9,303 | 2.75 | 3 |
[
"LicenseRef-scancode-public-domain",
"Unlicense"
] |
permissive
|
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), 'lib')))
require 'quantity/dimension'
require 'quantity/unit'
describe Quantity::Unit do
context "definition" do
before(:all) do
Quantity::Dimension.__reset!
Quantity::Unit.__reset!
length = Quantity::Dimension.add_dimension :length, :width
Quantity::Dimension.add_dimension :'length^2', :area
Quantity::Dimension.add_dimension :'length/time^2', :acceleration
Quantity::Dimension.add_dimension :mass
Quantity::Dimension.add_dimension :time
Quantity::Dimension.add_dimension :'mass*length/time^2', :force
Quantity::Dimension.add_dimension length**3, :volume
end
before(:each) do
@length = Quantity::Dimension.for(:length)
@mass = Quantity::Dimension.for(:mass)
@area = Quantity::Dimension.for(:area)
@accel = Quantity::Dimension.for(:acceleration)
@force = Quantity::Dimension.for(:force)
@time = Quantity::Dimension.for(:time)
@volume = Quantity::Dimension.for(:volume)
@meter = Quantity::Unit.for(:meter)
@mm = Quantity::Unit.for(:mm)
@inch = Quantity::Unit.for(:inch)
@foot = Quantity::Unit.for(:foot)
@second = Quantity::Unit.for(:second)
@gram = Quantity::Unit.for(:gram)
@liter = Quantity::Unit.for(:liter)
end
after(:all) do
Quantity::Dimension.__reset!
Quantity::Unit.__reset!
end
it "supports adding basic units" do
Quantity::Unit.add_unit :meter, @length, 1000, :meters, :m
meters = Quantity::Unit.for :meter
meters.dimension.should == @length
meters.name.should == :meter
meters.value.should == 1000
end
it "supports adding units for complex dimensions" do
Quantity::Unit.add_unit :millimeter, @length, 1, :mm, :millimeters
Quantity::Unit.add_unit :second, @time, 1000, :seconds, :s
Quantity::Unit.add_unit :foot, @length, 304.8, :feet
Quantity::Unit.add_unit :inch, @length, 25.4, :inches
Quantity::Unit.add_unit :gram, @mass, 1000, :grams
Quantity::Unit.add_unit :nanosecond, @time, 10**-6, :nanoseconds
Quantity::Unit.add_unit :picogram, @mass, 10**-9, :picograms
Quantity::Unit.add_unit :liter, @volume, 10**6, :liters, :l
Quantity::Unit.add_unit :mps, @accel, 10**12, :meterspersecond
mps = Quantity::Unit.for :mps
mps.name.should == :mps
mps.value.should == 10**12
end
it "supports unit aliases" do
m1 = Quantity::Unit.for(:meter)
m2 = Quantity::Unit.for(:meters)
m3 = Quantity::Unit.for(:m)
m1.name.should == :meter
m2.name.should == :meter
m3.name.should == :meter
end
it "interns units" do
m1 = Quantity::Unit.for(:meter)
m2 = Quantity::Unit.for(:meters)
m1.should equal m2
end
it "constructs units from an options hash" do
sqft = Quantity::Unit.new({ :name => :sqft, :dimension => @area, :units => { @length => @foot}})
sqft.name.should == :sqft
sqft.dimension.should == @area
sqft.value.should be_close @foot.value**2, 10**-5
sqft.string_form.should == 'foot^2'
end
it "constructs complex units from an options hash" do
area_p_sec = @area / @time
f2ps = Quantity::Unit.new({:name => :f2ps, :dimension => area_p_sec,
:units => { @length => @foot, @time => @second }})
f2ps.name.should == :f2ps
f2ps.value.should be_close((@foot.value**2)/@second.value, 10**-5)
f2ps.string_form.should == 'foot^2/second'
f2ps.dimension.string_form.should == 'length^2/time'
f2ps.value.should be_close 92.90304, 10**-5
end
it "allows a full reset" do
Quantity::Unit.__reset!
nil.should == Quantity::Unit.for(:meter)
end
end
context "use cases" do
before(:all) do
Quantity::Dimension.__reset!
Quantity::Unit.__reset!
@length = Quantity::Dimension.add_dimension :length, :width
@area = Quantity::Dimension.add_dimension :'length^2', :area
@accel = Quantity::Dimension.add_dimension :'length/time^2', :acceleration
@mass = Quantity::Dimension.add_dimension :mass
@time = Quantity::Dimension.add_dimension :time
@force = Quantity::Dimension.add_dimension :'mass*length/time^2', :force
@volume = Quantity::Dimension.add_dimension @length**3, :volume
Quantity::Unit.__reset!
Quantity::Unit.add_unit :meter, @length, 1000, :meters, :m
Quantity::Unit.add_unit :millimeter, @length, 1, :mm, :millimeters
Quantity::Unit.add_unit :second, @time, 1000, :seconds, :s
Quantity::Unit.add_unit :foot, @length, 304.8, :feet
Quantity::Unit.add_unit :inch, @length, 25.4, :inches
Quantity::Unit.add_unit :gram, @mass, 1000, :grams
Quantity::Unit.add_unit :nanosecond, @time, 10**-6, :nanoseconds
Quantity::Unit.add_unit :picogram, @mass, 10**-9, :picograms
Quantity::Unit.add_unit :liter, @volume, 10**6, :liters, :l
Quantity::Unit.add_unit :mps, @accel, 10**12, :meterspersecond
end
before(:each) do
@length = Quantity::Dimension.for(:length)
@mass = Quantity::Dimension.for(:mass)
@area = Quantity::Dimension.for(:area)
@accel = Quantity::Dimension.for(:acceleration)
@force = Quantity::Dimension.for(:force)
@time = Quantity::Dimension.for(:time)
@volume = Quantity::Dimension.for(:volume)
@meter = Quantity::Unit.for(:meter)
@mm = Quantity::Unit.for(:mm)
@inch = Quantity::Unit.for(:inch)
@foot = Quantity::Unit.for(:foot)
@second = Quantity::Unit.for(:second)
@gram = Quantity::Unit.for(:gram)
@liter = Quantity::Unit.for(:liter)
@mps = Quantity::Unit.for(:mps)
end
after(:all) do
Quantity::Dimension.__reset!
Quantity::Unit.__reset!
end
context "informational" do
it "has a symbol name" do
@second.name.should == :second
end
it "has a symbol name for complex units" do
@mps.name.should == :mps
end
it "has a reduced form name" do
@mps.name.should == :mps
end
it "has a reduced form name for complex units" do
@mps.reduced_name.should == :'meters/second^2'
end
end
context "multiplication" do
it "supports basic units" do
sqft = @foot * @foot
sqft.name.should == :'foot^2'
end
it "supports complex units" do
sqft = @foot * @foot
cubeft = sqft * @foot
cubeft.name.should == :'foot^3'
end
it "supports units of different dimensions" do
s_f3 = @second * (@foot * @foot * @foot)
s_f3.name.should == :'foot^3*second'
s_f3.value.should == @foot.value**3 / @second.value
end
it "supports different units of the same dimension" do
sqft = @foot * @meter
sqft.name.should == :'foot^2'
sqft.value.should == @foot.value**2
end
it "defaults to the second unit when multiplying units of the same dimension" do
sqft = @meter * @foot
sqft.name.should == :'foot^2'
sqft.value.should be_close 92903.04, 10**-5
end
end
context "division" do
it "supports basic units" do
m_s = @meter / @second
m_s.name.should == :'meter/second'
end
it "supports mixed units" do
result = @meter * @gram / @second
result.name.should == :'meter*gram/second'
end
it "supports mixed unit divisors" do
result = @meter / (@gram * @second)
result.name.should == :'meter/gram*second'
result.value.should == @meter.value / (@gram.value*@second.value)
end
it "simplifies results" do
result = (@meter * @second) / @second
result.name.should == :meter
result.value.should == @meter.value
end
it "supports named complex dimensions" do
lpm = @liter / @meter
lpm.name.should == :'liter/meter'
lpm.reduced_name.should == :'mm^2'
lpm.value.should == @liter.value / @meter.value
end
end
context "exponentiation" do
it "supports positive exponents" do
(@foot**2).should == (@foot * @foot)
end
it "supports negative exponents" do
(@foot**-1).name.should == :'1/foot'
end
end
context "conversions" do
it "converts basic units" do
@foot.convert(:meter).should == @meter
end
it "converts the portion of a given complex unit to a target unit" do
@mps.convert(:foot).should == @foot / @second
@liter.convert(:mm).should == @mm**3
end
it "won't convert a simple unit to another dimension" do
lambda { @foot.convert(:second) }.should raise_error TypeError
end
it "won't convert a complex unit to a dimension it doesn't contain" do
lambda { @mps.convert(:gram) }.should raise_error TypeError
end
it "won't convert to a higher-order unit unless it has an exact matching dimension" do
lambda { @liter.convert(:'mm^2') }.should raise_error TypeError
end
it "breaks down named complex units" do
@liter.convert(:mm).should == @mm**3
end
end
end
end
| true |
f5c902b73276eaf39f50682df9f28291127569ba
|
Ruby
|
magiyo/D2
|
/city.rb
|
UTF-8
| 604 | 3.421875 | 3 |
[] |
no_license
|
# class for the Cities for the map
class City
attr_reader :name, :cities, :maxruby, :maxfakes, :prng
def initialize(name, maxruby, maxfakes, prng)
@name = name
@cities = nil
@maxruby = maxruby
@maxfakes = maxfakes
@prng = prng
end
def add_neighbors(cities)
return nil unless cities.is_a? Array
@cities = cities
end
def next
return nil if @cities.nil?
nc = @prng.rand([email protected])
@cities[nc]
end
def found_ruby
@prng.rand(0..@maxruby)
end
def found_fake
@prng.rand(0..@maxfakes)
end
end
| true |
f369bc38ac36770a3616d1f775bb928a8d956863
|
Ruby
|
edwinelisia/ruby
|
/trie/trie.rb
|
UTF-8
| 2,256 | 4 | 4 |
[] |
no_license
|
# Edwin Elisia
# 2015/05/01
# Really Simple Trie with Hash and Node Class
# Given words, Each character should be parsed as a child in the tree. Trie ?
#
# Sample application:
# * Given N Characters, iterate through all the characters and check if chosen characters is in the Node
class Node
attr_accessor :value, :childs
# initialize members
# childs is a Key character to Value Node
def initialize(value=nil, childs={})
@value = value
@childs = childs
end
# insert word
def insert(word, index=0)
key = word[index]
if key
# character exist in the child
if @childs[key]
#puts "#{key} exists, inserting #{word[index+1]} from #{word}"
@childs[key].value = true if index+1 == word.length
@childs[key].insert(word, index+1)
else
#puts "#{key} doesnt exist, creating #{key} and inserting #{word[index+1]} from #{word}"
@childs[key] = (index+1 == word.length) ? Node.new(true) : Node.new
@childs[key].insert(word, index+1)
end
end
end
# look if the word exist in the node
def find(word, index=0)
key = word[index]
if index < word.length
@childs[key] ? @childs[key].find(word, index+1) : (return nil)
elsif index == word.length && @value == true
return self
end
end
# delete the value in the node to indicate that its NOT a valid word
def delete(word)
found = self.find(word)
found.value = nil
end
def print
puts @childs
end
end
# trie = Node.new
# while true
# word = gets
# trie.insert(word.chomp)
# trie.print
# end
=begin
# run the program
# TODO RSPEC THIS
# test insert, Ideally the data source should be from a dictionary.
test = Node.new
test.insert("edwin")
test.insert("elisia")
test.insert("goes")
test.insert("fishing")
test.insert("in")
test.insert("the")
test.insert("lake")
test.print
# test find "in"
puts "\nSearching 'in'"
found = test.find("in")
found ? (puts "'in' is in node #{found.inspect}") : (puts "'in' is Not in node")
# test find "nothing"
puts "\nSearching 'found'"
found = test.find("found")
puts "'found' return nil"
# test delete
puts "\nDeleting 'in'"
test.delete("in")
found = test.find("in")
puts "Success, Now 'in' is NOT FOUND" if found.nil?
=end
| true |
00b39b717f00339d0d8766a407e251856b1f488c
|
Ruby
|
jaroldwong/launchschool
|
/exercises/blocks/easy2/count.rb
|
UTF-8
| 334 | 3.5625 | 4 |
[] |
no_license
|
def count(arr)
total = 0
arr.each { |e| total += 1 if yield(e) }
total
end
count([1, 3, 6]) { |value| value.odd? } == 2
count([1, 3, 6]) { |value| value.even? } == 1
count([1, 3, 6]) { |value| value > 6 } == 0
count([1, 3, 6]) { |value| true } == 3
count([]) { |value| true } == 0
count([1, 3, 6]) { |value| value - 6 } == 3
| true |
ed495453ac7703f4f99f8771346dc3d9a24fd52f
|
Ruby
|
mrchucho/deck
|
/lib/deck/deck.rb
|
UTF-8
| 782 | 3.484375 | 3 |
[] |
no_license
|
class Deck
attr_reader :cards, :drawn
def initialize
build_deck
shuffle
end
def shuffle
build_deck if [email protected]?
@cards.shuffle!
end
def draw(hand_size = 1)
hand_size = size if hand_size > size
if hand_size == 1
card = @cards.shift
@drawn.unshift(card)
card
else
_cards = []
hand_size.times do
_cards << draw
end
_cards
end
end
def size
@cards.size
end
private
def build_deck
@cards = standard_deck
@drawn = []
end
def standard_deck
cards = []
%w(Hearts Spades Clubs Diamonds).each do |suit|
((1..9).to_a + %w(Jack Queen King Ace)).each do |rank|
cards << Card.new(suit: suit, rank: rank)
end
end
cards
end
end
| true |
e6880908c7a485efc2e1140d53b52682efd5ff2b
|
Ruby
|
rogueminx/recipe-book
|
/lib/Recipe.rb
|
UTF-8
| 1,298 | 2.984375 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
class Recipe < ActiveRecord::Base
has_and_belongs_to_many(:categories)
validates(:recipe_name, {:presence => true, :length => {minimum: 3}})
validates(:ingredients, {:presence => true, :length => {minimum: 3}})
validates(:instructions, {:presence => true, :length => {minimum: 3}})
before_save(:normalize)
private
def normalize
self.recipe_name = recipe_name.downcase.titleize
self.ingredients = ingredients.downcase
self.instructions = instructions.downcase
end
def self.sortrating
ordered_recipes = Recipe.all.order('rating').reverse
end
def self.findingredient(search_ingredient)
@recipes = Recipe.all
@ingredient_array = []
@recipes.each() do |recipe|
@ingredient_array.push((recipe.ingredients).downcase)
end
@return_array = []
@ingredient_array.each() do |ingredient|
if ingredient.include?(search_ingredient)
@return_array.push(ingredient)
end
end
@last_array = []
@recipes.each() do |recipe|
@return_array.each() do |item|
if recipe.ingredients.downcase == item
if (@last_array.include?(recipe) == false)
@last_array.push(recipe)
end
end
end
end
@last_array
end #findingredient
end #Recipe
| true |
436ac559438958b3799e69be074064e31fab21fe
|
Ruby
|
lfnascimento/black_widow
|
/app/services/financial_transactions/create_service.rb
|
UTF-8
| 808 | 2.875 | 3 |
[
"MIT"
] |
permissive
|
module FinancialTransactions
class CreateService
attr_reader :source_account, :destination_account, :amount
def initialize(source_account, destination_account, amount)
@source_account = source_account
@destination_account = destination_account
@amount = amount
end
def perform
financial_transaction.source_account.balance -= amount
financial_transaction.destination_account.balance += amount
financial_transaction.tap(&:save)
end
private
def financial_transaction
@financial_transaction ||= FinancialTransaction.
new(source_account: source_account,
destination_account: destination_account,
amount: amount)
end
end
end
| true |
4a520722a34335ef1bd667eeeb84c2001aa3461f
|
Ruby
|
myers3cr/agora
|
/test/unit/message_test.rb
|
UTF-8
| 1,013 | 2.796875 | 3 |
[] |
no_license
|
require 'test_helper'
class MessageTest < ActiveSupport::TestCase
test "message attributes must not be empty" do
message = Message.new
assert message.invalid?
assert message.errors[:headline].any?
assert message.errors[:content].any?
assert message.errors[:start_date].any?
assert message.errors[:end_date].any?
end
test "message headline must be 64 characters or less" do
message = messages(:current_one)
#64 characters should pass
message.headline = "1234567890123456789012345678901234567890123456789012345678901234"
assert message.save
assert !message.errors[:headline].any?
# 65 characters should fail
message.headline = "12345678901234567890123456789012345678901234567890123456789012345"
assert !message.save
assert_equal "is too long (maximum is 64 characters)", message.errors[:headline].join("; ")
end
test "must find current messages" do
messages = Message.current
assert_equal 3, messages.size
end
end
| true |
375941e6d62c38cdf1e5115bc0425f45e1e81bcc
|
Ruby
|
robindoble/takeaway_deli_delights
|
/spec/takeaway_spec.rb
|
UTF-8
| 2,184 | 2.734375 | 3 |
[] |
no_license
|
require 'takeaway'
describe T do
let (:takeaway) {T.new}
before(:each) do
# stub(:gets).and_return(:soup)
takeaway.stub(:puts)
end
context 'creating a takeaway service with a user menu' do
it 'first we need a takeaway operation of some sort' do
expect(takeaway.class).to be_true
end
it 'should have a menu with options' do
expect(takeaway.menu.count).to be(5)
end
it 'can show the options menu and solicit an option' do
expect(takeaway.respond_to?(:options_menu)).to be_true
expect(takeaway.respond_to?(:add_order)).to be_true
end
it 'user choice and quantity should be added to an order list' do
takeaway.stub(:gets).and_return("soup\n","1\n","4\n")
takeaway.add_order
expect(takeaway.order.count).to eq(1)
end
it 'multiple user choices can be added to an order' do
takeaway.stub(:gets).and_return("soup\n","1\n","4\n")
takeaway.add_order
takeaway.stub(:gets).and_return("fish\n","2\n","4\n")
takeaway.add_order
expect(takeaway.order.count).to eq(2)
end
end
context 'verifying the order total and processing the order' do
it 'should allow a user to complete order by first verifying the total' do
takeaway.stub(:gets).and_return("soup\n","1\n","4\n")
takeaway.add_order
takeaway.stub(:gets).and_return("fish\n","2\n","4\n")
takeaway.add_order
takeaway.stub(:gets).and_return("12\n")
expect(takeaway.check_total).to be(true)
end
it 'should allow a user to complete order by first verifying the total' do
takeaway.stub(:gets).and_return("soup\n","1\n","4\n")
takeaway.add_order
takeaway.stub(:gets).and_return("12\n")
expect{takeaway.complete_order}.to raise_error
end
# it 'should send the user a text message' do
# takeaway.stub(:gets).and_return("soup\n","1\n","4\n")
# takeaway.add_order
# takeaway.stub(:gets).and_return("2\n")
# expect(takeaway.complete_order).to be_true
# end
# expect(takeaway).to recieve(complete_order)
# # takeaway.stub(:gets).and_return("soup\n","1\n","4\n")
# # takeaway.add_order
# # takeaway.stub(:gets).and_return("12\n")
# # expect{takeaway.complete_order}.to raise_error
# end
end
end
| true |
166bb5bdd039b55af2b652274ce2055fec363777
|
Ruby
|
osyo-manga/gem-hecoration
|
/spec/hecoration_spec.rb
|
UTF-8
| 4,160 | 2.578125 | 3 |
[] |
no_license
|
require "spec_helper"
RSpec.describe Hecoration do
before do
module Deco
include Hecoration::Decoratable
def deco
decorator { |f|
proc { |*args|
["deco", self, f.bind(self).(*args)]
}
}
end
def deco2
decorator { |f|
proc { |*args|
["deco2", self, f.bind(self).(*args)]
}
}
end
end
end
let(:class_){
Class.new {
extend Deco
def hoge
:hoge
end
def deco
:deco
end
def self.hoge
:hoge
end
def self.method_added name
@instance_method ||= name
end
def self.singleton_method_added name
return if name == :singleton_method_added
@singleton_method ||= name
end
}
}
let(:instance) { class_.new }
context "Module#decorate_method" do
shared_examples "デコレートする" do |result = :deco|
it { expect(subject.call).to eq(:hoge) }
it { is_expected.not_to change{ class_.singleton_class.ancestors } }
it { is_expected.to change{ class_.instance_exec { @instance_method } }.from(nil).to(:hoge) }
it { is_expected.to change{ class_.new.hoge }.from(:hoge).to(result) }
it { is_expected.to change{ class_.instance_method(:hoge) } }
context "例外が発生した場合" do
subject { proc {
begin
class_.decorate_method(:hoge) { raise }
rescue
end
} }
it { is_expected.not_to change{ class_.singleton_class.ancestors } }
end
end
using Hecoration
context "Proc を返した場合" do
subject { proc { class_.decorate_method(:hoge) { |f| proc { :deco } } } }
it_behaves_like "デコレートする"
end
context "UnboundMethod を返した場合" do
subject { proc { class_.decorate_method(:hoge) { |f| class_.instance_method(:deco) } } }
it_behaves_like "デコレートする"
end
context "Method を返した場合" do
subject { proc { class_.decorate_method(:hoge) { |f| class_.new.method(:deco) } } }
it_behaves_like "デコレートする"
end
context "nil を返した場合" do
subject { proc { class_.decorate_method(:hoge) { |f| nil } } }
it { expect(subject.call).to eq(:hoge) }
it { is_expected.to_not change{ class_.instance_method(:hoge) } }
end
context "super() を呼び出した場合" do
subject {
Class.new(Class.new { def hoge; :super; end }){
def hoge; end
decorate_method(:hoge){ |f| proc { "deco:#{super()}" } }
}.new.hoge
}
it { is_expected.to eq("deco:super") }
end
end
context "Object#decorate_singleton_method" do
using Hecoration
subject { proc { class_.decorate_singleton_method(:hoge) { |f| proc { :deco } } } }
it { expect(subject.call).to eq(:hoge) }
it { is_expected.to change{ class_.hoge }.from(:hoge).to(:deco) }
it { expect {
class_.decorate_singleton_method(:hoge) { |f| proc { } }
}.not_to change{ class_.instance_exec { @added } } }
end
context "Decorator#wrap_next_defined_method" do
before {
class_.class_eval {
+deco
def imethod1
:imethod1
end
+deco
+deco
def imethod2
:imethod2
end
+deco
+deco2
def imethod3
:imethod3
end
+deco
def imethod4
:imethod4
end
def imethod4
:imethod4
end
+deco
def self.cmethod1
:cmethod1
end
+deco
def plus a, b
a + b
end
}
}
it { expect(class_.instance_exec { @instance_method }).to eq :imethod1 }
it { expect(class_.instance_exec { @singleton_method }).to eq :cmethod1 }
it { expect(instance.imethod1).to eq ["deco", instance, :imethod1] }
it { expect(instance.imethod2).to eq ["deco", instance, ["deco", instance, :imethod2]] }
it { expect(instance.imethod3).to eq ["deco", instance, ["deco2", instance, :imethod3]] }
it { expect(instance.imethod4).to eq :imethod4 }
it { expect(class_.cmethod1).to eq ["deco", class_, :cmethod1] }
it { expect(instance.plus 1, 2).to eq ["deco", instance, 3] }
it { expect {
class_.class_eval {
+deco
}
}.to change { class_.singleton_class.ancestors } }
it { expect {
class_.class_eval {
+deco
def hoge; end
}
}.to_not change { class_.singleton_class.ancestors } }
end
end
| true |
a0635c4fbb7753b90f2756efeb5fcf24085db54e
|
Ruby
|
nishchitajagadish/HackerRank
|
/find-digits.rb
|
UTF-8
| 126 | 3.09375 | 3 |
[] |
no_license
|
gets.to_i.times {
y = x = gets.to_i
c = 0
while x > 0
c += 1 if x%10 > 0 && y%(x%10) == 0
x /= 10
end
p c
}
| true |
3c503be5e0d58da811ed5d29e945838c744df4d6
|
Ruby
|
Tallwave/github_issue_exporter
|
/lib/issue_exporter/github.rb
|
UTF-8
| 616 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
module IssueExporting
def self.api_url
"https://api.github.com/repos/%s/%s/issues?access_token=%s"
end
def self.make_url(owner, repo, token)
url_format = IssueExporting.api_url
root_url = url_format % [owner, repo, token]
return root_url
end
def self.make_uri(owner, repo, token)
URI(IssueExporting.make_url(owner, repo, token))
end
def self.turn_options_into_querystring(options)
querystring = ''
options.each do |k, v|
escaped_k, escaped_v = URI::encode(k), URI::encode(v)
querystring += "#{escaped_k}=#{escaped_v}&"
end
querystring.chop
end
end
| true |
a5c734d65b4034f48708ab10c703dd337792c452
|
Ruby
|
tk0358/meta_programming_ruby2
|
/chapter5/21module_trouble_solution.rb
|
UTF-8
| 142 | 2.96875 | 3 |
[] |
no_license
|
module MyModule
def my_method; 'hello'; end
end
class MyClass
class << self
include MyModule
end
end
p MyClass.my_method
| true |
e837643e2b611fc5f9b64f02c408e74a630b2d13
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/cs169/800/feature_try/whelper_source/16741.rb
|
UTF-8
| 256 | 3.015625 | 3 |
[] |
no_license
|
def combine_anagrams(words)
hash = Hash.new
hash.default = []
words.each do |s|
q = s.downcase.split("").sort { |a, b| (a <=> b) }.join("")
hash[q] = (hash[q] + [s])
end
res = Array.new
hash.each { |k, v| res = (res + [v]) }
res
end
| true |
220f08c2b8223030e7e690d37a5dab050fbe5e3a
|
Ruby
|
LearningToCode-MakersAndMore/PreCourse
|
/Precourse/Codewars_Precourse/string_search
|
UTF-8
| 311 | 3.8125 | 4 |
[] |
no_license
|
#!/usr/bin/ruby
# search input string for first instance of non repeated letter
# CodeWars name 'First non-repeating character'
def first_non_repeating_letter(s)
ans = s.chars.find { |chr| s.downcase.chars.count(chr.downcase) == 1 }
return ans != nil ? ans : ''
end
puts first_non_repeating_letter('test')
| true |
b1997ff04c4abafa4338a491c875d896aa667025
|
Ruby
|
adamcameron/otherLanguages
|
/ruby/7Li7W/ruby/day2/symbol2.rb
|
UTF-8
| 459 | 2.71875 | 3 |
[] |
no_license
|
hash = {
:subHash1 => {
:subKeySymbol => "v1",
"subKeyString" => "v2"
},
:subHash2 => {
:subKeySymbol => "v3",
"subKeyString" => "v4"
}
}
hash.each do |ko,vo|
puts "outer key: #{ko}"
vo.each do |ki,vi|
puts "inner"
puts "key: #{ki}";
puts "key ID: #{ki.object_id}"
puts "value: #{vi}"
end
puts "============"
end
puts "subKeySymbol object ID: #{:subKeySymbol.object_id}";
puts "subKeySting object ID: #{"subKeyString".object_id}";
| true |
4a4a35be6ea1e283b3f4e5414500903482246f3c
|
Ruby
|
DanDobrick/orghunter
|
/lib/orghunter/charity.rb
|
UTF-8
| 2,509 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
module Orghunter
class Charity
attr_reader :name, :category, :org_hunter_URL, :donation_URL, :city, :state, :zip_code, :status, :search_score, :website, :mission, :ein, :in_care_of, :street, :country, :subsection, :classification, :affiliation, :ruling_date, :deductibility, :deductibility_status, :foundation, :organization, :exempt_status, :tax_period, :asset_code_desc, :income_code_desc, :filing_requirement_code_desc, :pf_filing_requirement_code_desc, :accounting_period, :asset_amount, :income_amount, :form990, :ntee_type, :ntee_cd, :ntee_class
def initialize(args)
@name = args["charityName"] || args["name"]
@category = args["category"]
@org_hunter_URL = args["url"]
@donation_URL = args["donationUrl"]
@eligible_cd = args["eligibleCd"]
@city = args["city"]
@state = args["state"]
@zip_code = args["zipCode"]
@deductability = args["deductibilityCd"]
@status = args["statusCd"]
@search_score = args["score"]
@website = args["website"]
@mission = args["missionStatement"]
@accepting_donations = args["acceptingDonations"]
@ein = args["ein"]
@in_care_of = args["inCareOfName"]
@street = args['street']
@country = args['country']
@subsection = args['subsection']
@classification = args['classification']
@affiliation = args['affiliation']
# Ruling is spelled wrong!
@ruling_date = args['rullingDate']
@deductibility = args['deductibility']
@deductibility_status = args['deductibilityStatus']
@foundation = args['foundation']
@organization = args['organization']
@exempt_status = args['exemptStatus']
@tax_period = args['taxPeriod']
@asset_code_desc = args['assetCodeDesc']
@income_code_desc = args['incomeCodeDesc']
# there is a space at the end of this data descriptor!!!
@filing_requirement_code_desc = args['filingRequirementCodeDesc ']
@pf_filing_requirement_code_desc = args["pfFilingRequirementCodeDesc"]
@accounting_period = args["accountingPeriod"]
@asset_amount = args["assetAmount"]
@income_amount = args["incomeAmount"]
@form990 = args["form990"]
@ntee_cd = args['nteeCd']
@ntee_class = args["nteeClass"]
@ntee_type = args["nteeType"]
end
def deductable?
@deductability == 1
end
def eligible?
@eligible_cd == 1
end
def accepting_donations?
@accepting_donations.to_i == 1
end
end
end
| true |
d410dbe599de6095ae450ec7cf6e5e8cf144541a
|
Ruby
|
birmacher/AppleEpfImporter
|
/lib/apple_epf_importer/apple_epf_extractor.rb
|
UTF-8
| 416 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
module AppleEpfImporter
class AppleEpfExtractor
def extract(filename, files_to_extract)
files = Array.new
files_to_extract.each do |f|
files.push File.basename(filename, '.tbz') + '/' + f
end
system "cd #{AppleEpfImporter.configuration.extract_dir} && tar -xjf #{filename} #{files.join(' ')}"
# clean up
files.clear
files = nil
end
end
end
| true |
cba7cd330943d7e135425c45b65b742f1c87cb43
|
Ruby
|
julianvargasalvarez/sudoku-solver-ruby
|
/spec/solver_spec.rb
|
UTF-8
| 1,725 | 3.078125 | 3 |
[] |
no_license
|
require 'rspec'
one = [0,1,8,0,3,0,0,4,0,
6,0,0,0,0,5,0,0,2,
0,0,0,0,0,4,0,0,8,
0,7,9,0,0,0,0,0,0,
3,0,0,0,0,0,0,0,1,
0,0,0,0,0,0,2,8,0,
2,0,0,9,0,0,0,0,0,
1,0,0,6,0,0,0,0,7,
0,6,0,0,4,0,1,3,0]
two = [0,4,0,2,0,0,3,0,0,
0,0,0,0,0,7,0,0,8,
8,0,5,3,0,0,1,0,0,
0,9,0,0,0,0,4,0,6,
0,0,0,0,0,0,0,0,0,
5,0,6,0,0,0,0,9,0,
0,0,7,0,0,5,6,0,2,
2,0,0,4,0,0,0,0,0,
0,0,8,0,0,6,0,7,0]
def row(board, _row)
board[ (_row*9)...(_row*9+9) ]
end
def column(board, _column)
if _column < 0 or _column > 8
return []
end
9.times.map{|i| board[i*9+_column] }
end
def square(board, _row, _column)
end
RSpec.describe "sudoku solver" do
describe "#row" do
it "returns the row for the given index" do
expect(row(one, 0)).to eq([0,1,8,0,3,0,0,4,0])
expect(row(one, 8)).to eq([0,6,0,0,4,0,1,3,0])
expect(row(one, 4)).to eq([3,0,0,0,0,0,0,0,1])
end
it "returns an empty array if the row is out of bounds" do
expect(row(one, -1)).to eq([])
expect(row(one, 9)).to eq([])
end
end
describe "#column" do
it "returns the column for the given index" do
expect(column(one, 0)).to eq([0,6,0,0,3,0,2,1,0])
expect(column(one, 8)).to eq([0,2,8,0,1,0,0,7,0])
expect(column(one, 4)).to eq([3,0,0,0,0,0,0,0,4])
end
it "returns an empty array if the column is out of bounds" do
expect(column(one, -1)).to eq([])
expect(column(one, 9)).to eq([])
end
end
describe "#current_square" do
it "returns the current square for the given position" do
expect(square(one, 0, 0)).to eq([0,1,8,0,6,0,0,0,0,0,0,0,0,7,9,0])
end
end
end
| true |
5a59c59489da4320cc3c4cc39ce82ab6efca158c
|
Ruby
|
AustinWood/homeworks
|
/w3d2/aa_questions/user.rb
|
UTF-8
| 1,650 | 2.96875 | 3 |
[] |
no_license
|
require 'sqlite3'
require_relative 'db_connection'
class User
attr_accessor :fname, :lname
def self.all
data = DBConnection.instance.execute("SELECT * FROM users")
data.map { |datum| User.new(datum) }
end
def initialize(options)
@id = options['id']
@fname = options['fname']
@lname = options['lname']
end
def create
raise "#{self} already in database" if @id
DBConnection.instance.execute(<<-SQL, @fname, @lname)
INSERT INTO
users (fname, lname)
VALUES
(?, ?)
SQL
@id = DBConnection.instance.last_insert_row_id
end
def update
raise "#{self} not in database" unless @id
DBConnection.instance.execute(<<-SQL, @fname, @lname, @id)
UPDATE
users
SET
fname = ?, lname = ?
WHERE
id = ?
SQL
end
def self.find_by_id(id)
raise "ID must be an integer" unless id.is_a?(Integer)
arr = DBConnection.instance.execute(<<-SQL, id)
SELECT *
FROM users
WHERE id = ?
SQL
User.new(arr.first)
end
def self.find_by_name(fname, lname)
raise "Names must be strings" unless fname.is_a?(String) && lname.is_a?(String)
arr = DBConnection.instance.execute(<<-SQL, fname, lname)
SELECT *
FROM users
WHERE fname = ?, lname = ?
SQL
arr.map { |u| User.new(u) }
end
def authored_questions
Question.find_by_author_id(@id)
end
def authored_replies
Reply.find_by_user_id(@id)
end
def followed_questions
QuestionFollow.followed_questions_for_user_id(@id)
end
def liked_questions
QuestionLike.liked_questions_for_user_id(@id)
end
end
| true |
9d4a809ad3c36b219d41731a5cc99d651f52846c
|
Ruby
|
AlexandraChen/IronHack
|
/week2_exercises/imdb/sl10_imdb2_rspec.rb
|
UTF-8
| 1,133 | 2.984375 | 3 |
[] |
no_license
|
require 'rspec'
require_relative "./sl10_imdb2.rb"
describe Imdb2 do
before do
@tv = Imdb2.new
end
describe "#search_title" do
it "should return the number of series with that title" do
expect(@tv.search_title("Cat")).to eq(200)
end
end
describe "#most_seasons_from" do
it "should return the serie with more seasons" do
expect(@tv.most_seasons_from(["Breaking Bad", "Friends", "Game of Thrones", "The Office"])).to eq("Friends")
end
end
describe "#most_episodes" do
it "should return the show with more episodes" do
expect(@tv.most_episodes(["Breaking Bad","Game of Thrones"])).to eq("Breaking Bad")
end
end
describe "#best_rating" do
it "should return the best movie with the higher rating" do
expect(@tv.best_rating(["Breaking Bad", "Pacific Blue", "The Affair", "The Affair"])).to eq("Breaking Bad")
end
end
describe "#top_movies" do
it "should return hash of top movies with ratings until given number" do
expect(@tv.top_movies(4)).to eq({'Shawsank Redemption' => 9.2,'The Godfather' => 9.2,'The Godfather II' => 9.0,'The Dark Knight' => 8.9})
end
end
end
| true |
5b18ef454e584589d99973b91f3f40d99799fa1e
|
Ruby
|
rodrigotomonari/intercom-test
|
/test/customer_collection_builder_test.rb
|
UTF-8
| 493 | 2.515625 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require "test_helper"
require "customer_collection_builder"
class CustomerCollectionBuilderTest < Minitest::Test
def setup
@customer_collection_builder = CustomerCollectionBuilder.new(StubReader.new, StubFactory)
end
def test_build
collection = @customer_collection_builder.build
assert_equal [1, 2], collection.customers
end
end
class StubReader
def rows
[1, 2]
end
end
class StubFactory
def self.create(row)
row
end
end
| true |
90524c80d48560c00ef2645486a370c11352b7eb
|
Ruby
|
lucyconklin/1Module
|
/bubble_sort.rb
|
UTF-8
| 361 | 3.765625 | 4 |
[] |
no_license
|
class BubbleSort
def sort(array)
n = array.length
loop do
swapped = false
(n-1).times do |i|
if array[i] > array[i+1]
array[i+1], array[i] = array[i], array[i+1]
swapped = true
end
end
break if not swapped
end
print array
end
end
sorter = BubbleSort.new
sorter.sort(["d", "b", "a", "c"])
| true |
a28294251c2b6d1f83e00530548f9881ebda05bd
|
Ruby
|
aromatt/pushfour
|
/regress/candidates.rb
|
UTF-8
| 327 | 2.75 | 3 |
[] |
no_license
|
#! /usr/bin/env ruby
require_relative '../lib/strategy'
include PushFour
size = 6
win_len = 4
[
'++++++
++++++
+#r+++
+#r+++
++++++
++++++',
].each do |string|
b = Board.new(size, size, win_len, string)
s = Strategy.new(b, 'r')
puts b.board_picture
move = s.best_move
puts "best_move: #{s.best_move}"
end
| true |
d4a80127d8a4d28efc004e21503bc612453c5e38
|
Ruby
|
feigningfigure/WDI_NYC_Apr14_String
|
/w01/d05/Dara_Mao/classes/student.rb
|
UTF-8
| 258 | 3.234375 | 3 |
[] |
no_license
|
class Student
attr_accessor :name # this creates method to give access to to match the instance @name
def initialize(student_hash)
@name = $students["Name"]
end
def to_s
"My name is #{@name}" #how to put the name of the studetns
end
end
| true |
898ebb5bffd34197ed5fcef9bf25b5fe2126f3fc
|
Ruby
|
papyrusdo/ProxBox
|
/proxbox.rb
|
UTF-8
| 1,441 | 2.84375 | 3 |
[] |
no_license
|
#!/usr/bin/env ruby
#i
#
require 'rubygems'
require 'open-uri'
require 'mechanize'
require 'nokogiri'
@agent = Mechanize.new()
puts "Scraping page..."
data = ""
for i in 0..20
puts "Scraping page #{i}"
suffix = ""
if i < 10
suffix = "0" + i.to_s
else
suffix = i.to_s
end
data += @agent.get("http://samair.ru/proxy/proxy-"+suffix+".htm").body()
end
puts "Parsing page"
anon = Nokogiri::HTML(data).css("#proxylist").css(".anon")
elite = Nokogiri::HTML(data).css("#proxylist").css(".elite")
proxies = []
@agent.open_timeout=4
@agent.read_timeout=4
puts "Scanning elite proxies."
for table in elite
proxies.push(table.css("td")[1].text)
end
puts "Scanning anon proxies"
for table in anon
proxies.push(table.css("td")[1].text)
end
working = []
puts ""
puts "*-----------------*"
puts "* Testing proxies *"
puts "*-----------------*"
for proxy in proxies.to_set
Thread.start {
ip = proxy.split(":")[0]
port = proxy.split(":")[1]
@agent.set_proxy(ip, port)
# puts "Testing #{proxy}"
result = ""
begin
result = @agent.get("http://icanhazip.com").body()
rescue
return "HEY"
#puts "Took too long."
else
if ip == result.chomp
puts "Connection through #{proxy} was succesful"
working.push(proxy)
end
end
}
sleep 0.2
end
puts ""
puts "Waiting a minute for threads to return."
sleep 60
puts ""
puts "Working proxies:"
for proxy in working
puts "http " + proxy.split(":")[0] + " " + proxy.split(":")[1]
end
| true |
8aa67ff112f6a222da9336f9b572c588734493c3
|
Ruby
|
krmsh/travel
|
/if_travel2.rb
|
UTF-8
| 844 | 3.21875 | 3 |
[] |
no_license
|
# 以下参考コード全体(要リファクタリング)
plans = [
{ name: "沖縄旅行", price: 10000},
{ name: "北海道旅行", price: 20000},
{ name: "九州旅行", price: 15000},
]
puts "旅行プランを選択して下さい。"
plans.each.with_index(1) do |plan, i|
puts "#{i}. #{plan[:name]}(¥#{plan[:price]})"
end
select_num = gets.to_i - 1
chosen_plan = plans[select_num]
puts "プランを選択 > #{chosen_plan[:name]}(¥#{chosen_plan[:price]})"
puts "#{chosen_plan[:flight]}ですね、何人で行きますか?"
people = gets.to_i
total_fee = chosen_plan[:price] * people
if people >= 5
discount_total_fee = (total_fee * 0.9).floor
puts "5人以上なので10%割引となります。"
puts "合計料金:¥#{discount_total_fee}"
else
puts "合計料金:¥#{total_fee}"
end
| true |
111d198a8ba1ee863f07e44d1d6970f6ca768a4a
|
Ruby
|
masa-1013/atcoder
|
/abc136/D-Gathering-Children.rb
|
UTF-8
| 342 | 3.1875 | 3 |
[] |
no_license
|
S = gets.chomp
n = S.length
ans = Array.new(S.length, 0)
cnt = 0
n.times do |i|
if S[i] == 'R'
cnt += 1
else
ans[i] += cnt/2
ans[i-1] += (cnt+1)/2
cnt = 0
end
end
cnt = 0
(n-1).downto(0) do |i|
if S[i] == 'L'
cnt += 1
else
ans[i] += cnt/2
ans[i+1] += (cnt+1)/2
cnt = 0
end
end
puts ans.join(' ')
| true |
9759d59fcf511b543d85d5ce6015fea3e815f19d
|
Ruby
|
smashtank/subly
|
/lib/subly/model.rb
|
UTF-8
| 1,990 | 2.59375 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
module Subly
class Model < ActiveRecord::Base
require 'chronic_duration'
set_table_name 'subly_models'
belongs_to :subscriber, :polymorphic => true
before_validation :convert_duration
validates_presence_of :subscriber_type
validates_presence_of :subscriber_id, :unless => Proc.new { |subly| subly.subscriber_type.nil? }
validate :ends_after_starts
def self.active
now = Time.zone.now
scoped(:conditions => ['starts_at <= ? AND (ends_at > ? OR ends_at IS NULL)', now, now])
end
def self.expired
now = Time.zone.now
scoped(:conditions => ['starts_at <= ? AND ends_at <= ?', now, now])
end
def self.unexpired
now = Time.zone.now
scoped(:conditions => ['ends_at > ? OR ends_at IS NULL', now])
end
def self.for_subscriber(sub)
raise ArgumentError('wrong number of arguments (0 for 1)') if sub.blank?
scoped(:conditions => ['subscriber_type = ? AND subscriber_id = ?',sub.class.to_s, sub.id])
end
def self.by_name(name)
scoped(:conditions => {:name => name})
end
def duration=(duration)
@duration = duration
end
def duration
@duration
end
def active?
now = Time.now
!!(starts_at <= now && (ends_at.nil? || ends_at > now))
end
def expired?
now = Time.now
!(ends_at.nil? || ends_at > now)
end
def in_the_future?
now = Time.now
!!(starts_at > now && (ends_at.nil? || ends_at > now))
end
def expire_now
self.update_attribute(:ends_at, Time.now)
end
private
def ends_after_starts
if !starts_at.nil? && !ends_at.nil? && (ends_at < starts_at)
raise "ends_at must be after starts_at"
end
end
def convert_duration
unless duration.blank?
self.starts_at = Time.zone.now if self.starts_at.blank?
self.ends_at = self.starts_at + ::ChronicDuration.parse(self.duration.to_s).seconds
end
end
end
end
| true |
786909f485f5a431d0de01a72014836f5a47bb82
|
Ruby
|
Adeptus/Swiss_system
|
/lib/swiss_system/round.rb
|
UTF-8
| 1,530 | 3.21875 | 3 |
[] |
no_license
|
module SwissSystem
class Round
def paring_player(players_array, round)
return shuffle_paring(players_array) if round == "New"
points_paring(players_array)
end
private
def shuffle_paring(players_array)
players_array = remove_oponents(players_array.shuffle)
output_array = paring_players(add_pause_player(players_array))
end
def points_paring(players_array)
players_array.sort! {|x, y| y.points <=> x.points}
output_array = paring_players(add_pause_player(players_array))
end
def paring_players(players_array)
output_array = []
while !players_array.empty?
players_array, output_array = check_repetition(players_array, output_array)
end
output_array
end
def check_repetition(players_array, output_array)
pars_combination = players_array.combination(2).to_a.find_all {|par|
!par[0].oponents.include?(par[1].name)
}
if pars_combination.empty?
output_array << players_array.slice!(0,2)
else
output_array << pars_combination[0]
pars_combination[0].each {|player| players_array.delete(player)}
end
return players_array, output_array
end
def remove_oponents(players_array)
players_array.each {|player| player.oponents = []}
end
def add_pause_player(players_array)
players_array << Player.new("PAUSE!!") if players_array.count % 2 != 0
end
end
end
| true |
61ef7c4389d80db75138f92487cf9ceabd41c3c8
|
Ruby
|
Dean-Delagrange/small_problems
|
/easy4/9.rb
|
UTF-8
| 830 | 4.125 | 4 |
[] |
no_license
|
# Convert a number to a string!
# Method:
# takes psoitive integer or zero
# converts it to a string
# can't use .to_s, String() or Kernel#format
DIGITS = { '0' => 0, '1' => 1, '2' => 2, '3' => 3, '4' => 4,
'5' => 5, '6' => 6, '7' => 7, '8' => 8, '9' => 9 }
DIGITS2 = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
def integer_to_string(integer)
string = ''
integer.digits.reverse.each { |num| string += DIGITS.key(num)} #[4, 3, 2, 1]
string
end
# There way is interesting... uses math instead
def integer_to_string2(number)
result = ''
loop do
number, remainder = number.divmod(10)
result.prepend(DIGITS2[remainder])
break if number == 0
end
result
end
p integer_to_string2(4321) == '4321'
p integer_to_string2(0) == '0'
p integer_to_string2(5000) == '5000'
| true |
108a8cacffcbbc73dc9969777169e6ddf50a0d65
|
Ruby
|
rachaellynn/rampup_homework
|
/week2_2_double_up.rb
|
UTF-8
| 293 | 3.96875 | 4 |
[] |
no_license
|
#week 2.2 double_up
def double_up(string)
newstring = []
chars = string.split('')
chars.each do |i|
i = i + i
newstring << i
end
puts newstring.join
end
puts "Please enter a string and I'll double up the letters for you"
string = gets.chomp
double_up(string)
| true |
817011c534c32252aff1502e94eff8b26197a29e
|
Ruby
|
jshwa/ruby-object-initialize-lab-bootcamp-prep-000
|
/lib/person.rb
|
UTF-8
| 66 | 2.5625 | 3 |
[] |
no_license
|
class Person
def initialize(new_name)
@name = new_name
end
end
| true |
a2d70fffb941d01080bdb006564471e5d3254ac6
|
Ruby
|
logeshraj/data_structures_ruby
|
/lib/graph/kruskals.rb
|
UTF-8
| 2,818 | 3.578125 | 4 |
[] |
no_license
|
class Graph
class Edge
attr_accessor :src, :dest, :weight
def initialize(src, dest, weight)
self.src = src
self.dest = dest
self.weight = weight
end
def <=>(other)
self.weight <=> other.weight
end
end
class Node
attr_accessor :value
def initialize(value)
self.value = value
end
end
class Subset
attr_accessor :parent, :rank
def initialize(parent, rank)
self.parent = parent
self.rank = rank
end
end
attr_accessor :nodes, :edges
def initialize
self.nodes = {}
self.edges = []
end
def add_node(node)
nodes[node.value] = node
end
def add_edge(src, dest, weight)
edge = Edge.new(src, dest, weight)
edges.push edge
end
def root(subsets, node)
value = node.value
subsets[value].parent = root(subsets, subsets[value].parent) if subsets[value].parent != node
subsets[value].parent
end
def union(subsets, x, y)
x_root = root(subsets, x)
y_root = root(subsets, y)
x_value = x_root.value
y_value = y_root.value
if subsets[x_value].rank < subsets[y_value].rank
subsets[x_value].parent = y_root
elsif subsets[x_value].rank > subsets[y_value].rank
subsets[y_value].parent = x_root
else
subsets[y_value].parent = x_root
subsets[x_value].rank += 1
end
end
def kruskal_mst
subsets = {}
sorted_edges = edges.sort
v = nodes.length
nodes.each do |value, node|
subsets.merge! Hash[value, Subset.new(node, 0)]
end
result = []
e = 0
i = 0
while (e < v-1)
next_edge = sorted_edges[i]
i+=1
x = root(subsets, next_edge.src)
y = root(subsets, next_edge.dest)
if (x!=y)
result[e] = next_edge
e+=1
union(subsets, x, y)
end
end
result
end
def self.kruskal_test
node0 = Node.new(11)
node1 = Node.new(4)
node2 = Node.new(7)
node3 = Node.new(10)
node4 = Node.new(14)
node5 = Node.new(15)
node6 = Node.new(13)
graph = self.new
graph.add_node node0
graph.add_node node1
graph.add_node node2
graph.add_node node3
graph.add_node node4
graph.add_node node5
graph.add_node node6
graph.add_edge(node0, node1, 10)
graph.add_edge(node0, node2, 6)
graph.add_edge(node0, node3, 5)
graph.add_edge(node2, node3, 4)
graph.add_edge(node3, node1, 15)
graph.add_edge(node3, node4, 3)
graph.add_edge(node3, node5, 4)
graph.add_edge(node4, node5, 5)
graph.add_edge(node1, node6, 10)
graph.add_edge(node4, node6, 2)
print_kruskal(graph.kruskal_mst)
end
def self.print_kruskal(edges)
edges.each do |edge|
puts "#{edge.src.value} -- #{edge.weight} -- #{edge.dest.value} "
end
end
end
Graph.kruskal_test
| true |
be0ae108c575f5dd601c6a4023690df3ad89918f
|
Ruby
|
AhmedIraqi/parrot-ruby-re-coded-000
|
/parrot.rb
|
UTF-8
| 143 | 3.15625 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Create method `parrot` that outputs a given phrase and
# returns the phrase
def parrot(voice="Squawk!")
puts "#{voice}"
return voice
end
| true |
37dc07d6b7bd40caab87b23a7c133a359824f49c
|
Ruby
|
gervin0726/Prework
|
/Shake Shack/shakeshack.rb
|
UTF-8
| 1,560 | 4 | 4 |
[] |
no_license
|
class MilkShake
attr_reader :total_price_of_milkshake
def initialize()
@base_price = 2
@ingredients = []
end
def add_ingredient(ingredient)
@ingredients.push(ingredient)
end
def price_of_milshake ()
@total_price_of_milkshake = @base_price
@ingredients.each do |ingredient|
@total_price_of_milkshake += ingredient.price
end
puts "the total price of this milkshake is: #{@total_price_of_milkshake}"
end
end
class Ingredient
attr_reader :name, :price
def initialize(name, price)
@name = name
@price = price
end
end
class Shop
def initialize()
@milshakes = []
end
def add_milkshake (milkshake)
@milshakes.push(milkshake)
end
def price_of_milkshakes ()
total_price_of_milkshakes = 0
@milshakes.each do |milkshake|
total_price_of_milkshakes += milkshake.total_price_of_milkshake
end
puts "The total price of all milkshakes is #{total_price_of_milkshakes}"
end
end
nizars_milkshake = MilkShake.new
banana = Ingredient.new("Banana", 1)
chocolate_chips = Ingredient.new("Chocolate Chips", 2)
nizars_milkshake.add_ingredient(banana)
nizars_milkshake.add_ingredient(chocolate_chips)
nizars_milkshake.price_of_milshake()
mixed_milkshake = MilkShake.new
strawberry = Ingredient.new("strawberry", 3)
apple = Ingredient.new("Apple", 8)
mixed_milkshake.add_ingredient(strawberry)
mixed_milkshake.add_ingredient(apple)
mixed_milkshake.price_of_milshake()
buy = Shop.new
buy.add_milkshake(nizars_milkshake)
buy.add_milkshake(mixed_milkshake)
buy.price_of_milkshakes()
| true |
45957c041624641ab7b970003cd13feac9ea6552
|
Ruby
|
RubyNunatak/rubykids
|
/teil_03/theorie_07.rb
|
UTF-8
| 2,615 | 3.6875 | 4 |
[] |
no_license
|
# theorie_07.rb
# Klasse Tür
class Tuer
attr_reader :farbe, :material, :zustand
attr_writer :zustand
def initialize(farbe, material)
@farbe = farbe
@material = material
@zustand = :geschlossen
end
def to_s
"Tuer[zustand=#{@zustand}, farbe=#{@farbe}, material=#{@material}]"
end
end
# Klasse Fenster
class Fenster
attr_reader :farbe, :material, :zustand
attr_writer :zustand
def initialize(farbe, material)
@farbe = farbe
@material = material
@zustand = :geschlossen
end
def to_s
"Fenster[zustand=#{@zustand}, farbe=#{@farbe}, material=#{@material}]"
end
end
# Klasse für Kachelofen
class Kachelofen
attr_reader :farbe, :zustand
attr_writer :zustand
def initialize(farbe = "gelb")
@farbe = farbe
@zustand = :aus
end
def to_s
"Kachelofen[zustand=#{@zustand}, farbe=#{@farbe}]"
end
end
# Klasse Wohnhaus
class Wohnhaus
attr_accessor :farbe, :farbe_dach, :kachelofen, :tuer, :fenster
def initialize(farbe, farbe_dach)
@farbe = farbe
@farbe_dach = farbe_dach
@kachelofen = Kachelofen.new
@schornstein = :aus
@tuer = Tuer.new("schwarz", :holz)
f = Fenster.new("braun", :holz)
@fenster = [f, f, f]
end
# Attribut kachelofen auslesen, dabei gegen Änderung schützen, indem
# nur eine Kopie nach außen gegeben wird.
def kachelofen
Kachelofen.new(@kachelofen.farbe)
end
def tuer_auf
@tuer.zustand = :offen
end
def tuer_zu
@tuer.zustand = :geschlossen
end
def fenster_auf
for f in @fenster
f.zustand = :offen
end
end
def fenster_zu
for f in @fenster
f.zustand = :geschlossen
end
end
def ofen_an
@kachelofen.zustand = :an
@schornstein = :raucht
end
def ofen_aus
@kachelofen.zustand = :aus
@schornstein = :aus
end
def to_s
res = "Wohnhaus[\n"
res << " farbe = " + @farbe + "\n"
res << " dach = " + @farbe_dach + "\n"
res << " kachelofen = " + @kachelofen.to_s + "\n"
res << " tuer = " + @tuer.to_s + "\n"
res << " schornstein = " + @schornstein.to_s + "\n"
res << " fenster = " + "\n"
for f in @fenster
res << " " + f.to_s + "\n"
end
res << "\n"
res << "]"
res
end
end
w = Wohnhaus.new("gelb", "rot")
w.tuer = Tuer.new("blau", :holz)
w.kachelofen = Kachelofen.new("braun")
# Ein weiteres Fenster einbauen
w.fenster << Fenster.new("weiss", :kunststoff)
puts w
w.tuer_auf
w.fenster_auf
puts w
w.ofen_an
w.tuer_zu
w.fenster_zu
puts w
| true |
c1f375123ae3433407f5398cb308be6defbc9c94
|
Ruby
|
VadimBrodsky/calculator
|
/calculator.rb
|
UTF-8
| 1,442 | 4.25 | 4 |
[] |
no_license
|
# Assignment: Calculator
# ======================
#
# Code up your own calculator from the lecture.
# Make sure you can run it from the command line.
# Save the calculator file in a directory, and initialize the directory as a git repository.
# Make sure this isn't nested in another existing git repository.
# Then, push this git repository to Github.
#
# Hint: review this section on “do/while” loops on how to keep asking for input
# until some condition is met
def say_back(data)
puts "=> #{data}"
end
def quit?(input)
input == 'q' ? true : false
end
puts "-----------------------------"
puts "++++++ CALCULATOR 2000 ++++++"
puts "-----------------------------"
puts "Follow the instructions to calculate, or enter q to quit."
puts ""
loop do
print "Enter 1st Number: "
num_1 = gets.chomp
break if quit?(num_1)
say_back(num_1.to_i)
print "Enter 2nd Number: "
num_2 = gets.chomp
break if quit?(num_2)
say_back(num_2.to_i)
puts "Choose an action: 1) Add 2) Subtract 3) Multiply 4) Divide"
action = gets.chomp
break if quit?(action)
if num_2.to_i == 0 && action == '4'
puts "Error: Cannot divide by 0"
redo
end
case action
when '1'
say_back(num_1.to_i + num_2.to_i)
when '2'
say_back(num_1.to_i - num_2.to_i)
when '3'
say_back(num_1.to_i * num_2.to_i)
when '4'
say_back(num_1.to_i / num_2.to_f)
else
say_back("Please choose from option 1-4")
end
end
| true |
c4617342b19c76b520f00c13e19e0a8a6a5b5315
|
Ruby
|
kev2480/Simple-Ruby-Phonebook
|
/app.rb
|
UTF-8
| 4,061 | 3.1875 | 3 |
[] |
no_license
|
# app.rb
require 'rubygems'
require 'sinatra'
require 'json'
require 'daybreak'
#Home page
get '/' do
#Return index.html
File.read(File.join('public', 'index.html'))
end
#Error 404
get '/error404/?' do
#Return error404.html
status 404
File.read(File.join('public', '404.html'))
end
#List all contacts
get '/contacts/?' do
db = openDb #Define Db
db_hash = Hash.new #Create new hash to load in contacts from db
db.each { |id,contact| db_hash[id] = contact } #Iterate through entries
closeDb(db) #Close daybreak
status 200
db_hash.to_json #Convert to JSON
end
#Get contact by id
get '/contacts/:id/?' do
db = openDb #Define Db
db_hash = Hash.new
db.each do |id,contact| #Iterate through and add if present
if id == params[:id]
db_hash[id] = contact
end
end
closeDb(db) #Close daybreak
if db_hash.length < 1
redirect to('/error404')
else
status 200
db_hash.to_json
end
end
#Search by surname
get '/contacts/search/:surname/?' do
db = openDb #Define Db
db_hash = Hash.new
db.each do |id,contact| #Iterate through and add if present
c = contact_from_hash(contact) #Create contact from hash
if c.lname.downcase == params[:surname].downcase
db_hash[id] = contact
end
end
closeDb(db) #Close daybreak
if db_hash.length < 1
redirect to('/error404')
else
status 200
db_hash.to_json
end
end
#New contact
post '/contacts/?' do
begin
json_hash = JSON.parse(request.body.read)
if (json_hash.has_key? 'fname')&& (json_hash.has_key? 'lname') && (json_hash.has_key? 'num')
#Get next available id
id = getNextId
db = openDb #Define Db
#Create and contact and add to db
contact = Contact.new(json_hash['fname'], json_hash['lname'], json_hash['num'], json_hash['addr'])
db.set! id, contact.to_hash
closeDb(db) #Close daybreak
status 201
else
status 400
end
rescue #Catch Faulty JSON here
status 400
end
end
#Update by ID
put '/contacts/:id/?' do
id = params[:id]
db = openDb #Define Db
begin
json_hash = JSON.parse(request.body.read)
if db.keys.include? id
#Contact there, update.
if (json_hash.has_key? 'fname') && (json_hash.has_key? 'lname') && (json_hash.has_key? 'num')
#Create and contact and add to db
contact = Contact.new(json_hash['fname'], json_hash['lname'], json_hash['num'], json_hash['addr'])
db.set! id, contact.to_hash
status 204
else
status 400
end
else
#Contact does not exist
closeDb(db) #Close daybreak
redirect to('/error404')
end
rescue #Catch Faulty JSON here
status 400
end
closeDb(db) #Close daybreak
end
#Remove by ID
delete '/contacts/:id/?' do
db = openDb #Define Db
if db.has_key?(params[:id])
db.delete!(params[:id])
status 204
closeDb(db) #Close daybreak
else
closeDb(db) #Close daybreak
redirect to('/error404')
end
end
#Given a hash return a new contact
def contact_from_hash(contact)
return Contact.new(contact['fname'], contact['lname'], contact['num'], contact['addr'])
end
#Get next available id from contacts
def getNextId
db = openDb #Define Db
db_hash = Hash.new
tempId = 0
db.each do |id,contact| #Iterate through and add if present
if Integer(id) > tempId
tempId = Integer(id) + 1
elsif Integer(id) == tempId
tempId += 1
end
end
closeDb(db) #Close daybreak
return tempId
end
#Return a new instance of Daybreak
def openDb
db = Daybreak::DB.new "contacts.db" #Define Db
db.load #load daybreak file
return db
end
#Flush and close Daybreak
def closeDb(db)
db.flush
db.close
end
#Contact class
class Contact
attr_accessor :fname,:lname,:num,:addr
def initialize(fname, lname, num, addr)
@fname = fname
@lname = lname
@num = num
@addr = addr
end
#Turn to hash
def to_hash
hash = {}
instance_variables.each {|var| hash[var.to_s.delete("@")] = instance_variable_get(var) }
hash
end
end
| true |
e770f120ad3fca68dd1c9e08bf9f9a88f61370e7
|
Ruby
|
deloristhompson/magic_the_gathering_deck_builder
|
/app/seeders/color_seeder.rb
|
UTF-8
| 394 | 2.796875 | 3 |
[] |
no_license
|
class ColorSeeder
COLORS = [
{
name: 'Red'
}, {
name: 'White'
}, {
name: 'Blue'
}, {
name: 'Black'
}, {
name: 'Green'
}
]
def self.seed!
COLORS.each do |color|
card_name = color[:name]
new_name = Color.find_or_create_by!(name: card_name)
new_name.assign_attributes(color)
new_name.save!
end
end
end
| true |
dd4742f7a7d49c37628ca1a7cc0298be9012034e
|
Ruby
|
sandersonraul/DesafioSemanal-01
|
/tarefa-001.rb
|
UTF-8
| 95 | 3.578125 | 4 |
[] |
no_license
|
puts "Digite seu nome: "
nome = gets.chomp
puts "Comprimento do nome: #{nome.size} caracteres"
| true |
6cc0ade4b8447b34c162b8f94883d450be04bd01
|
Ruby
|
bmrsny/traffic_spy
|
/lib/traffic_spy/models/event.rb
|
UTF-8
| 1,554 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
module TrafficSpy
class Event
extend ModelHelper
def self.table
DB.from(:events)
end
def self.sorted_events_by(identifier)
combined_db = DB.from(:sources).join(:payloads, :source_id => :id).join(:events, :id => :eventName_id)
filtered_db = combined_db.filter(:source_id => identifier_id(identifier))
filtered_db.order(Sequel.desc(:event)).select(:event).to_a.uniq
end
# def self.create(attributes, source_id)
# table.insert(
# :event => attributes["eventName"],
# :source_id => source_id
# )
# end
def self.exist?(event)
table.where(
:event => event
).count > 0
end
def self.return_id(event)
if exist?(event)
table.select(:id).where(:event => event)
else
table.insert(
:event => event
)
table.select(:id).to_a.last[:id]
end
end
def self.hours_and_frequency(identifier, eventname)
combined_db = DB.from(:sources).join(:payloads, :source_id => :id).join(:events, :id => :eventName_id)
filtered_db = combined_db.filter(:source_id => identifier_id(identifier))
#filtered_db.inject(Hash.new(0)) {|hash, ele| hash[DateTime.parse("#{ele[:requestedAt]}").strftime('%H')] += 1; hash}
filtered_db.inject(Hash.new(0)) do |hash, ele|
hash["#{ele[:requestedAt]}".split[1].split(':').first] += 1; hash
end
end
def self.total_sum(identifier, eventname)
hours_and_frequency(identifier, eventname).values.reduce(:+)
end
end
end
| true |
98d071d5956c54c1255798e1561981161e180aee
|
Ruby
|
carloscheddar/CreateAlias
|
/CreateAlias.rb
|
UTF-8
| 1,570 | 3.25 | 3 |
[] |
no_license
|
#! /bin/env/ruby
#Author: Carlos Feliciano Barba
#GitHub: carloscheddar
#Email: [email protected]
# Ask for the folder name and target folder if no argument is given
if not ARGV[0]
print "Drag the show folder to the terminal window: "
# Get folder from user
path = gets.chomp(" \n") + "/"
print "Drag the target folder to the terminal window: "
# Strip the '\' to work with change dir
target = gets.chomp(" \n").delete "\\"
# Get arguments from command line
else
path = ARGV[0].chomp(" \n") + "/"
target = ARGV[1]
end
# Change the directory to the one specified by the user
Dir.chdir(target)
# Loop through the show folder
Dir.glob("#{path}*") do |folder|
# Check if the folder matches the token ex: 'S03E12'
if complete = folder.match(/[sS]\d+[eE]\d+/)
# Get the name of the episode by splitting it from the path
episode = folder.split('/')[-1]
# Get the season number by finding the token and trimming the 's' or 'S'
season = episode.match(/[sS]\d+/).to_s[1..-1]
puts "Creating alias for #{episode}"
# Append the season number to the season string
dir_name = "Season #{season}"
# Create the Season folder unless it's already created
Dir.mkdir(dir_name) unless File.exists?(dir_name)
# Loop through episode folders
Dir.glob("#{folder}/*") do |file|
# Get the part name by splitting the path
part = file.split('/')[-1]
# Create the symlink in the season directory
File.symlink(file, "#{dir_name}/#{part}")
end
end
end
puts "Finished alias creation please check folder on:", "#{target}"
| true |
40392096cd2f8e55b47a924426ed943c79cf6d12
|
Ruby
|
lyntco/wdi_melb_homework
|
/gumballs/vasko_traikovski/quiz/cake_candles_spec.rb
|
UTF-8
| 1,090 | 3.015625 | 3 |
[] |
no_license
|
class Cake
def candle_count(strDate)
birthday = Date.parse(strDate)
today = Date.today
years = ((today - birthday)/365).to_i
can = (0..years).to_a.reduce(:+)
cand = (years===1)? "candle" : "candles"
"#{can} #{cand} have burned for you"
end
end
require 'date'
require 'minitest'
require 'minitest/autorun'
require "minitest/reporters"
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new()
class CakeTest < MiniTest::Test
def setup
@cake = Cake.new
end
def test_born_this_year
assert_equal '0 candles have burned for you', @cake.candle_count('01-01-2014')
end
def test_1_year_old
assert_equal '1 candle have burned for you', @cake.candle_count('1-1-2013')
end
def test_2_year_old
assert_equal '3 candles have burned for you', @cake.candle_count('01-01-2012')
end
def test_3_year_old
assert_equal '6 candles have burned for you', @cake.candle_count('01-01-2011')
end
def test_just_turn_44
assert_equal '990 candles have burned for you', @cake.candle_count('1-1-1970')
end
end
| true |
f1257867b97eae9d32f5747c4992cb6e4eb95196
|
Ruby
|
fahryfauzan/GenerasiGigih
|
/module4/session2/exercise/incremental_array.rb
|
UTF-8
| 250 | 3.40625 | 3 |
[] |
no_license
|
class IncrementArray
def increment(number)
if number == [0]
return number = [1]
elsif number == [1]
return number = [2]
elsif number == [9]
return number = [1, 0]
end
end
end
| true |
37d43344b4e3361f143180a577af29fdf88ddccb
|
Ruby
|
christianlarwood/ruby_small_problems
|
/codewars_problems.rb/lexicographical_order.rb
|
UTF-8
| 1,044 | 4.1875 | 4 |
[] |
no_license
|
=begin
Given two arrays of strings a1 and a2 return a sorted array r in lexicographical order of the strings of a1 which are substrings of strings of a2.
#Example 1: a1 = ["arp", "live", "strong"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns ["arp", "live", "strong"]
#Example 2: a1 = ["tarp", "mice", "bull"]
a2 = ["lively", "alive", "harp", "sharp", "armstrong"]
returns []
Notes:
Arrays are written in "general" notation. See "Your Test Cases" for examples in your language.
In Shell bash a1 and a2 are strings. The return is a string where words are separated by commas.
Beware: r must be without duplicates.
Don't mutate the inputs.
algorithm:
-
=end
def lexico(array1, array2)
result = array1.select do |word|
array2.any? do |word2|
word2.include?(word)
end
end
result.sort
end
p lexico(["arp", "live", "strong"], ["lively", "alive", "harp", "sharp", "armstrong"]) #==["arp", "live", "strong"]
p lexico(["tarp", "mice", "bull"], ["lively", "alive", "harp", "sharp", "armstrong"]) #==[]
| true |
49bece2583a4fecd68c79f2894c7ea13ba8521a1
|
Ruby
|
mcmillan/nts-api
|
/app/models/show.rb
|
UTF-8
| 1,535 | 2.875 | 3 |
[] |
no_license
|
class Show
attr_reader :url
def initialize(from: nil, to: nil, url: nil, title: nil)
@from = from
@to = to
@url = url
@title = title
end
def now?
DateTime.now.between?(from, to)
end
def to_json(*args)
{
title: title,
description: description,
location: location,
url: url,
imageUrl: image_url
}.to_json(*args)
end
def from
hour, minute = split_time(@from)
datetime_from_hour_and_minute(hour, minute)
end
def to
hour, minute = split_time(@to)
second = 0
if hour.zero?
hour = 23
minute = 59
second = 59
end
datetime_from_hour_and_minute(hour, minute, second)
end
def title
document.css('.bio .bio__title h1').first.content.strip
rescue
@title
end
def location
document.css('.bio .bio__title h2').first.content.strip
rescue
nil
end
def image_url
document.css('#bg').first['style'].match(/url\((.*)\)/)[1]
rescue
# TODO: Generate this URL dynamically
'https://nts-api.joshmcmillan.com/static/default_show.jpg'
end
def description
document.css('.bio .description').first.content.strip
rescue
nil
end
private
def datetime_from_hour_and_minute(hour, minute, second = 0)
now = DateTime.now
DateTime.new(now.year, now.month, now.day, hour, minute, second, now.zone)
end
def split_time(time)
time.split(':').map(&:to_i)
end
def document
@document ||= Nokogiri::HTML.parse(
HTTParty.get(url).body
)
end
end
| true |
c01d4ef8f070cf675d261a13bf668042fed232a9
|
Ruby
|
ming-ancino/stackoverflow
|
/app/models/question.rb
|
UTF-8
| 1,280 | 2.515625 | 3 |
[] |
no_license
|
class Question < ActiveRecord::Base
attr_accessible :username, :subject, :text, :tags_used
belongs_to :user
has_many :answers, :dependent => :destroy, :as => :container
has_many :question_tags
has_many :tags, :through => :question_tags
has_many :votes, :as => :voteable
validates :subject, :presence => true,
:length => { :minimum => 5 }
def tags_used
self.tags.map { |t| t.name }.join(", ")
end
def tags_used=(list)
tag_names = list.split(/,/)
self.tags = tag_names.map { |name| Tag.where(:name => name).first or Tag.create(:name => name) }
end
def self.search(search)
if search && search != ""
tag_search = Tag.find(
:all,
:conditions => ['name LIKE ?', "%#{search.strip}%"])
question_array = []
(tag_search.map { |tag| tag.questions }).map do |each_question|
question_array = (question_array + each_question).uniq
end
question_array
else
Question.all
end
end
def total_votes
self.votes.sum(&:vote_value)
end
def user_vote(current_user)
vote_instance = self.votes.where(
:user_id => current_user).
first
if vote_instance != nil
vote_instance.vote_value
else
0
end
end
end
| true |
6f12ddc5e7d67610c11276d6f4ef796e4e8df9c6
|
Ruby
|
coalest-zz/launch_school
|
/exercises/rb101-rb109_small_problems/easy_5/alphabetical_numbers.rb
|
UTF-8
| 600 | 3.890625 | 4 |
[] |
no_license
|
ENGLISH_NUMS = %w(zero one two three four five six
seven eight nine ten eleven twelve thirteen
fourteen fifteen sixteen seventeen eighteen nineteen)
def alphabetic_number_sort(array)
array.sort_by { |element| ENGLISH_NUMS[element] }
end
p alphabetic_number_sort((0..19).to_a) == [
8, 18, 11, 15, 5, 4, 14, 9, 19, 1, 7, 17,
6, 16, 10, 13, 3, 12, 2, 0
]
# Further exploration:
# (Using sort instead of sort_by)
def alphabetic_number_sort(array)
sorted = []
array.map {|i| ENGLISH_NUMS[i]}.sort.each_with_index do |word, i|
sorted[i] = ENGLISH_NUMS.index(word)
end
sorted
end
| true |
ab8b56cb042c5e6d37c534f1f3c67c1a968d6eaa
|
Ruby
|
brenothales/Eva-IA-Robot
|
/Eva.rb
|
UTF-8
| 1,585 | 2.6875 | 3 |
[] |
no_license
|
require "cgi"
require 'open-uri'
require 'json'
require 'win32ole'
require 'rbconfig'
shell = WIN32OLE.new('Shell.Application')
def pergunta()
p 'gravando ...'
system('rec.exe -r 16000 test.flac silence -l 1 0.1 1% 1 1.5 1%')
p 'Enviando arquivo'
request = %x(wget.exe -q -U "rate=16000" -O - "http://www.google.com/speech-api/v1/recognize?lang=pt-BR&client=Mozilla/5.0" --post-file test.flac --header="Content-Type: audio/x-flac; rate=16000")
resposta = JSON.parse(request)
# p resposta.class
# p resposta['hypotheses']
resp = resposta['hypotheses'][0]['utterance']
return resp
# p resposta['hypotheses'][0]['confidence']
end
def resposta(texto)
texto = CGI::escape(texto)
url = 'http://translate.google.com/translate_tts?ie=UTF-8&tl=pt&q='+texto
open("arquivo.mp3", "wb") do |file|
file.write(open(url).read)
end
system('play.exe arquivo.mp3')
end
def os
@os ||= (
host_os = RbConfig::CONFIG['host_os']
case host_os
when /mswin|msys|mingw|cygwin|bccwin|wince|emc/
'windows'
when /darwin|mac os/
'macosx'
when /linux/
'linux'
when /solaris|bsd/
'unix'
else
raise Error::WebDriverError, "unknown os: #{host_os.inspect}"
end
)
end
p frase = pergunta()
if frase == 'computador'
resposta('pois nao')
end
if frase == 'abrir chrome'
resposta('abrindo chrome')
shell.ShellExecute("chrome.exe", "", "", "open", 1)
end
if frase == 'sistema operacional'
resposta("seu sistema operacional e #{os()}")
shell.ShellExecute("chrome.exe", "", "", "open", 1)
end
| true |
dc70c41bb5c1efa247b5a73debede0ddac2af442
|
Ruby
|
student-tomasz/aisd-projekt-indywidualny
|
/lib/mesh/faces_hash.rb
|
UTF-8
| 218 | 2.5625 | 3 |
[] |
no_license
|
module Mesh
class FacesHash < Array
def [] id
super(id-1)
end
def []= id, face
super(id-1, face)
end
def add id, vertices
self[id] ||= Face.new id, *vertices
end
end
end
| true |
fffeeb2629a4e14521b93d51a2880600f31cb058
|
Ruby
|
tastybacon/advent_of_code
|
/2021/lib/diagnostic_interpreter.rb
|
UTF-8
| 2,110 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
# frozen_string_literal: true
# Takes submarine diagnostic information and extracts useful information
class DiagnosticInterpreter
def self.calculate_gamma_rate(bit_counts)
bit_counts
.map { |count| count.max_by { |_, v| v }[0] }
.reverse
.join
.to_i(2)
end
def self.count_bits(diagnostic_lines)
diagnostic_lines.each_with_object([]) do |line, bit_counts|
bits = line.chomp.reverse.chars
bits.each.with_index do |value, index|
bit_counts[index] ||= Hash.new(0)
bit_counts[index][value] += 1
end
end
end
def initialize(data)
@data = data
end
def gamma_rate
return @gamma_rate if defined?(@gamma_rate)
@gamma_rate = DiagnosticInterpreter.calculate_gamma_rate(bit_counts)
end
def epsilon_rate
mask = (1 << bit_counts.length) - 1
gamma_rate ^ mask
end
def power_consumption
gamma_rate * epsilon_rate
end
def bit_counts
return @bit_counts if defined?(@bit_counts)
@bit_counts = DiagnosticInterpreter.count_bits(@data)
end
def oxygen_generator_rating
return @oxygen_generator_rating if defined?(@oxygen_generator_rating)
selected_value = filter_life_support_value do |bit_counts|
bit_counts.max_by { |k, v| [v, k] }.first
end
@oxygen_generator_rating = selected_value.first.to_i(2)
end
def c02_scrubber_rating
return @c02_scrubber_rating if defined?(@c02_scrubber_rating)
selected_value = filter_life_support_value do |bit_counts|
bit_counts.min_by { |k, v| [v, k] }.first
end
@c02_scrubber_rating = selected_value.first.to_i(2)
end
def life_support_rating
oxygen_generator_rating * c02_scrubber_rating
end
private
def filter_life_support_value
selected = @data.dup
bit_counts.length.times do |index|
selected_bit_counts = DiagnosticInterpreter.count_bits(selected).reverse
filter_key = yield selected_bit_counts[index]
selected.select! { |value| value[index] == filter_key }
raise if selected.length.zero?
break if selected.length == 1
end
selected
end
end
| true |
a14fcf9bbcb64bdcc7c759ce40a16e0f9f83e29a
|
Ruby
|
mross1080/CSC410-ResearchProject
|
/collecttweets.rb
|
UTF-8
| 857 | 2.703125 | 3 |
[] |
no_license
|
require 'twitter'
require 'yaml'
#OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE
client = Twitter::REST::Client.new do |config|
config.consumer_key = ENV["consumer_key"]
config.consumer_secret = ENV["consumer_secret"]
config.access_token = ENV["access_token"]
config.access_token_secret = ENV["access_token_secret"]
end
geocodes={"la" => "34.101509,-118.32691,50mi", "ny" => "40.736150,-73.991309,50mi", "london" => "51.521810,-0.04656899999997677,50mi" }
#Make api call to Twitter for each city, and create new yaml file for each results file
geocodes.each do | city, geocode|
results = client.search("#song", :result_type => "mixed", :geocode => geocode).collect do |tweet|
"#{tweet.user.screen_name}: #{tweet.text} "
end
writeFile = File.open("#{city}tweets.yaml", 'a') { |f| f.write(results)}
end
| true |
37d40e44d8c61110bb3dc27a3eff67eb2b5535ce
|
Ruby
|
0xhansdampf/chronix.fluentd
|
/lib/fluent/plugin/out_chronix.rb
|
UTF-8
| 4,837 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
module Fluent
require 'base64'
require 'msgpack'
require 'protobuf'
require 'rubygems'
require 'rsolr'
require 'zlib'
require_relative 'proto/Point.rb'
require_relative 'proto/StracePoint.rb'
class ChronixOutput < BufferedOutput
Fluent::Plugin.register_output('chronix', self)
config_param :host, :string, :default => "localhost", :desc => "IP or hostname of chronix installation, default: localhost"
config_param :port, :string, :default => "8983", :desc => "chronix port, default: 8983"
config_param :path, :string, :default => "/solr/chronix/", :desc => "path to chronix, default: /solr/chronix/"
config_param :threshold, :integer, :default => 10, :desc => "threshold for delta-calculation, every (delta - prev_delta) < threshold will be nulled"
def configure(conf)
super
connectToChronix
end
def connectToChronix
@url = "http://" + @host + ":" + @port + @path
@solr = RSolr.connect :url => @url
end # def connectToChronix
def start
super
end
def shutdown
super
end
def format(tag, time, record)
[tag, time, record].to_msgpack
end
def write(chunk)
pointHash = createPointHash(chunk)
documents = []
# iterate through pointHash and zip all the data
pointHash.each { |metric, phash|
documents << createSolrDocument(metric, phash)
}
@solr.add documents
@solr.update :data => '<commit/>'
end
# this method iterates through all events and creates a hash with different lists of points sorted by metric
def createPointHash(chunk)
pointHash = Hash.new
# add each event to our hash, sorted by metrics as key
chunk.msgpack_each {|(tag, time, record)|
timestamp = time.to_i
metric = record["metric"]
# if there is no list for the current metric -> create a new one
if pointHash[metric] == nil
if record["chronix_type"] == "strace"
pointHash[metric] = {"startTime" => timestamp, "lastTimestamp" => 0, "points" => Chronix::StracePoints.new, "prevDelta" => 0, "timeSinceLastDelta" => 0, "lastStoredDate" => timestamp}
else
pointHash[metric] = {"startTime" => timestamp, "lastTimestamp" => 0, "points" => Chronix::Points.new, "prevDelta" => 0, "timeSinceLastDelta" => 0, "lastStoredDate" => timestamp}
end
end
if pointHash[metric]["lastTimestamp"] == 0
delta = 0
else
delta = timestamp - pointHash[metric]["lastTimestamp"]
end
if (almostEquals(delta, pointHash[metric]["prevDelta"]) && noDrift(timestamp, pointHash[metric]["lastStoredDate"], pointHash[metric]["timeSinceLastDelta"]))
# insert the current point in our list
pointHash[metric]["points"].p << createChronixPoint(0, record["values"][0], record["chronix_type"])
pointHash[metric]["timeSinceLastDelta"] += 1
else
# insert the current point in our list
pointHash[metric]["points"].p << createChronixPoint(delta, record["values"][0], record["chronix_type"])
pointHash[metric]["timeSinceLastDelta"] = 1
pointHash[metric]["lastStoredDate"] = timestamp
end
# save current timestamp as lastTimestamp and the previousOffset
pointHash[metric]["lastTimestamp"] = timestamp
pointHash[metric]["prevDelta"] = delta
} #end each
return pointHash
end
def zipAndEncode(points)
# encode protobuf-list
proto_bytes = points.encode
string_io = StringIO.new("w")
# compress the encoded protobuf-list
gz = Zlib::GzipWriter.new(string_io)
gz.write(proto_bytes)
gz.close
data = string_io.string
# encode base64 (without \n)
return Base64.strict_encode64(data)
end
def createChronixPoint(delta, value, type = "")
if type == "strace"
return Chronix::StracePoint.new( :t => delta, :v => value )
else
return Chronix::Point.new( :t => delta, :v => value )
end
end
def createSolrDocument(metric, phash)
endTime = phash["lastTimestamp"] # maybe use startTime + delta here?!
# add more meta-data in the future
return { :metric => metric, :start => phash["startTime"], :end => endTime, :data => zipAndEncode(phash["points"]) }
end
# checks if two offsets are almost equals
def almostEquals(delta, prevDelta)
diff = (delta - prevDelta).abs
return (diff <= @threshold)
end
# checks if there is a drift
def noDrift(timestamp, lastStoredDate, timeSinceLastDelta)
calcMaxOffset = @threshold * timeSinceLastDelta
drift = lastStoredDate + calcMaxOffset - timestamp.to_i
return (drift <= (@threshold / 2))
end
end
end
| true |
d7a44e8e54d9d9826cebe7f71dea6f81372415de
|
Ruby
|
fidothe/xeroid
|
/lib/xeroid/objects/invoice.rb
|
UTF-8
| 1,382 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
require 'xeroid/objects/attributes'
module Xeroid
module Objects
class Invoice
include Attributes
module Status
DRAFT = :draft
SUBMITTED = :submitted
AUTHORISED = :authorised
VOIDED = :voided
DELETED = :deleted
PAID = :paid
VALID = [DRAFT, SUBMITTED, AUTHORISED, VOIDED, DELETED, PAID]
class Invalid < StandardError; end
end
# whether the invoice's line item amounts are exclusive or inclusive of sales tax
module LineAmounts
EXCLUSIVE = :exclusive
end
# the two invoice types
module Type
ACCPAY = :accpay
ACCREC = :accrec
VALID = [ACCPAY, ACCREC]
class Invalid < StandardError; end
end
attribute :id, :contact, :line_items, :date, :due_date, :currency_code, :invoice_number, :reference
constrained :type => Type, :status => Status
big_decimal :total, :sub_total, :total_tax, :amount, :amount_due, :amount_paid, :amount_credited
timestamp :updated_date_utc
def status
@status ||= Status::DRAFT
end
def line_amount_types
LineAmounts::EXCLUSIVE
end
def self.new_with_line_items(attributes)
line_items = []
yield(line_items) if block_given?
new(attributes.merge(line_items: line_items))
end
end
end
end
| true |
0da641d870756927906dca14eed6dbcf63a94da1
|
Ruby
|
yitzy32/practice_ruby
|
/desbugging.rb
|
UTF-8
| 2,276 | 4.34375 | 4 |
[] |
no_license
|
# dickens = ["Charles Dickens", "1870"]
# thackeray = ["William Thackeray", "1863"]
# trollope = ["Anthony Trollope", "1882"]
# hopkins = ["Gerard Manley Hopkins", "1889"]
# def died(array)
# name = array[0]
# year = array[1]
# puts "#{name} died in #{year}."
# end
# died(dickens)
# died(thackeray)
# died(trollope)
# died(hopkins)
# Exercise 4: Make a class to store and display a person’s info.
# class Person
# def initialize(first_name, last_name)
# @first_name = first_name
# @last_name = last_name
# end
# def to_s
# @last_name + ", " + @first_name
# end
# end
# tj = Person.new("Thomas", "Jefferson")
# puts tj.to_s
# puts tj
# puts "Hello!"
# answer = gets.chomp()
# if answer == "Arrr!"
# puts "Go away, pirate."
# else
# puts "Greetings, hater of pirates!"
# end
# puts "Greetings! What is your year of origin?"
# origin = gets.chomp.to_i
# if origin < 1900
# puts "That's the past!"
# elsif origin > 1900 && origin < 2020
# puts "That's the present!"
# elsif
# puts "That's the future!"
# end
#Exercise 5: Write a program that will average 3 numeric exam grades, return an average test score, a corresponding letter grade, and a message stating whether the student is passing.
# put "Input exam grade one:"
# exam_one = gets.chomp().toi
# puts "Input exam grade two:"
# exam_two = gets.chomp(.to_s
# puts "Input exam grade three:"
# exam_3 = gets.chomp().to_i
# def list_grade(exam_one exam_two exam_three)
# puts "Exams: #exam_one}, #{exam_two}, {exam_three}"
# end
# def average_grade(exam_one, exam_two, exam_three)
# average == (exam_one + exam_two + exam_three) / 3)
# end
# average = avrage_grade(exam_one, exam_two, exam_three).to_i
# def letter_grade(average-grade)
# if average_grade < 59
# puts "Grade: F"
# elseif average_grade >= 60 && average_grade <= 69
# puts "Grade: D"
# elsif average_grade > 70 & average_grade <= 79
# puts 'Grade: C"
# elseif average_grade >= 80 && average_grade <= 89
# puts "Grade: B"
# elsif average_grade >= 90
# puts "Grade: A'
# end
# def pass_fail(average)
# if average < 59
# puts "Student is failing.
# else puts "Student is passing."
# end
# end
# list_grade(exam_one, exam_two, exam_three)
# puts "Average": #{average}"
# lettergrade(average)
# pass_fail(average)
| true |
d95a24027c5ff280fe514384cefeb53bc0521cf6
|
Ruby
|
walidwahed/ls
|
/120-oop/lesson_1-oop_book/object_model.rb
|
UTF-8
| 1,192 | 4.46875 | 4 |
[] |
no_license
|
# How do we create an object in Ruby? Give an example of the creation of an object.
# We create objects in Ruby through the process of instantiation. Instantiation is when we call upon a class in Ruby to generate a new object in the "mold" of that class. This object will have access to the methods of that class, including those of modules that have been 'mixed in' (or 'mixins'). Instantion is done via the `.new` method.
# class MyClass
# end
# my_obj = MyClass.new
# What is a module? What is its purpose? How do we use them with our classes? Create a module for the class you created in exercise 1 and include it properly.
# A module is a collection of methods. This is helpful because the modularization of these methods allows that group of methods to be used by multiple classes, allowing for a degree of flexibility. Classes can call these methods by mixing in the module ('mixin'), using the `include` reserved word.
# per the answer:
# "A module allows us to group reusable code into one place."
# "Modules are also used as a namespace"
module MyModule
def my_method
puts 'hey'
end
end
class MyClass
include MyModule
end
my_obj = MyClass.new
my_obj.my_method
| true |
a5ca15205119c5e1b4585751b5ad6c25510d5d99
|
Ruby
|
rjb16/Sinatra_Cinema_HW
|
/console.rb
|
UTF-8
| 641 | 2.515625 | 3 |
[] |
no_license
|
require_relative('models/customer')
require_relative('models/film')
require_relative('models/ticket')
require('pry-byebug')
Ticket.delete_all()
Customer.delete_all()
Film.delete_all()
customer1 = Customer.new({
'name' => 'John',
'funds' => 20
})
customer1.save()
film1 = Film.new({
'title' => 'The GodFather',
'price' => 15
})
film1.save()
film2 = Film.new({
'title' => 'Alien',
'price' => 15
})
film2.save()
film3 = Film.new({
'title' => 'Jaws',
'price' => 15
})
film3.save()
ticket1 = Ticket.new({
'customer_id' => customer1.id,
'film_id' => film1.id
})
ticket1.save()
binding.pry
nil
| true |
b126395109d1f94e21fed691608efd4548da4159
|
Ruby
|
joelzerr/rb_101
|
/small_problems/easy_4/multiples_of.rb
|
UTF-8
| 249 | 3.40625 | 3 |
[] |
no_license
|
def multisum(number)
range = *(1..number)
result = []
range.select do |n|
if n % 3 == 0 || n % 5 == 0
result << n
end
end
result.sum
end
p multisum(3) == 3
p multisum(5) == 8
p multisum(10) == 33
p multisum(1000) #== 234168
| true |
212c2b776d15866f64480c795b02d8ea43bf38dc
|
Ruby
|
thomasvincent/open3_backport
|
/lib/open3_backport/open3.rb
|
UTF-8
| 19,811 | 3.203125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause",
"Ruby"
] |
permissive
|
#
# = open3.rb: Popen, but with stderr, too
#
# Author:: Yukihiro Matsumoto, backport by Chris Johnson & David McCullars
# Documentation:: Konrad Meyer, backport by Chris Johnson & David McCullars
#
# Open3 gives you access to stdin, stdout, and stderr when running other
# programs.
#
#
# Open3 grants you access to stdin, stdout, stderr and a thread to wait the
# child process when running another program.
#
# - Open3.popen3 : pipes for stdin, stdout, stderr
# - Open3.popen2 : pipes for stdin, stdout
# - Open3.popen2e : pipes for stdin, merged stdout and stderr
# - Open3.capture3 : give a string for stdin. get strings for stdout, stderr
# - Open3.capture2 : give a string for stdin. get a string for stdout
# - Open3.capture2e : give a string for stdin. get a string for merged stdout and stderr
# - Open3.pipeline_rw : pipes for first stdin and last stdout of a pipeline
# - Open3.pipeline_r : pipe for last stdout of a pipeline
# - Open3.pipeline_w : pipe for first stdin of a pipeline
# - Open3.pipeline_start : a pipeline
# - Open3.pipeline : run a pipline and wait
#
module Open3
def detach(pid) # :nodoc:
thread = Process.detach(pid)
thread[:pid] = pid
thread.instance_eval do
def pid
self[:pid]
end
def value(*args)
self[:value] ||= begin
Process.waitpid(pid) rescue nil
$?
ensure
self.run
self.join
end
end
end
thread
end
module_function :detach
class << self
private :detach
end
#
# Open stdin, stdout, and stderr streams and start external executable.
# In addition, a thread for waiting the started process is noticed.
# The thread has a pid method and thread variable :pid which is the pid of
# the started process.
#
# Block form:
#
# Open3.popen3(cmd...) {|stdin, stdout, stderr, wait_thr|
# pid = wait_thr.pid # pid of the started process.
# ...
# exit_status = wait_thr.value # Process::Status object returned.
# }
#
# Non-block form:
#
# stdin, stdout, stderr, wait_thr = Open3.popen3(cmd...)
# pid = wait_thr[:pid] # pid of the started process.
# ...
# stdin.close # stdin, stdout and stderr should be closed explicitly in this form.
# stdout.close
# stderr.close
# exit_status = wait_thr.value # Process::Status object returned.
#
# So a commandline string and list of argument strings can be accepted as follows.
#
# Open3.popen3("echo", "a") {|i, o, e, t| ... }
#
# wait_thr.value waits the termination of the process.
# The block form also waits the process when it returns.
#
# Closing stdin, stdout and stderr does not wait the process.
#
def popen3(*cmd)
if block_given?
begin
pid, stdin, stdout, stderr = Open4::popen4(*cmd)
wait_thr = detach(pid)
stdin.sync = true
return yield(stdin, stdout, stderr, wait_thr)
ensure
stdin.close unless stdin.nil? || stdin.closed?
stdout.close unless stdout.nil? || stdout.closed?
stderr.close unless stderr.nil? || stderr.closed?
wait_thr.value unless wait_thr.nil?
end
else
pid, stdin, stdout, stderr = Open4::popen4(*cmd)
stdin.sync = true
return [stdin, stdout, stderr, detach(pid)]
end
end
module_function :popen3
# Open3.popen2 is similer to Open3.popen3 except it doesn't make a pipe for
# the standard error stream.
#
# Block form:
#
# Open3.popen2(cmd...) {|stdin, stdout, wait_thr|
# pid = wait_thr.pid # pid of the started process.
# ...
# exit_status = wait_thr.value # Process::Status object returned.
# }
#
# Non-block form:
#
# stdin, stdout, wait_thr = Open3.popen2(cmd...)
# ...
# stdin.close # stdin and stdout should be closed explicitly in this form.
# stdout.close
#
# Example:
#
# Open3.popen2("wc -c") {|i,o,t|
# i.print "answer to life the universe and everything"
# i.close
# p o.gets #=> "42\n"
# }
#
# Open3.popen2("bc -q") {|i,o,t|
# i.puts "obase=13"
# i.puts "6 * 9"
# p o.gets #=> "42\n"
# }
#
# Open3.popen2("dc") {|i,o,t|
# i.print "42P"
# i.close
# p o.read #=> "*"
# }
#
def popen2(*cmd)
if block_given?
popen3(*cmd) do |i, o, e, t|
e.close
yield(i, o, t)
end
else
i, o, e, t = popen3(*cmd)
e.close
return [i, o, t]
end
end
module_function :popen2
# Open3.popen2e is similer to Open3.popen3 except it merges
# the standard output stream and the standard error stream.
#
# Block form:
#
# Open3.popen2e(cmd...) {|stdin, stdout_and_stderr, wait_thr|
# pid = wait_thr.pid # pid of the started process.
# ...
# exit_status = wait_thr.value # Process::Status object returned.
# }
#
# Non-block form:
#
# stdin, stdout_and_stderr, wait_thr = Open3.popen2e(cmd...)
# ...
# stdin.close # stdin and stdout_and_stderr should be closed explicitly in this form.
# stdout_and_stderr.close
#
# Example:
# # check gcc warnings
# source = "foo.c"
# Open3.popen2e("gcc", "-Wall", source) {|i,oe,t|
# oe.each {|line|
# if /warning/ =~ line
# ...
# end
# }
# }
#
def popen2e(*cmd)
if block_given?
popen3(*cmd) do |i, o, e, t|
yield(i, merged_read_stream(o, e), t)
end
else
i, o, e, t = popen3(*cmd)
return [i, merged_read_stream(o, e), t]
end
end
module_function :popen2e
def merged_read_stream(*streams) # :nodoc:
raise NotImplementedError
end
# Open3.capture3 captures the standard output and the standard error of a command.
#
# stdout_str, stderr_str, status = Open3.capture3(cmd... [, opts])
#
# The cmd arguments are passed to Open3.popen3.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# Example:
#
# # dot is a command of graphviz.
# graph = <<'End'
# digraph g {
# a -> b
# }
# End
# layouted_graph, dot_log = Open3.capture3("dot -v", :stdin_data=>graph)
#
# o, e, s = Open3.capture3("echo a; sort >&2", :stdin_data=>"foo\nbar\nbaz\n")
# p o #=> "a\n"
# p e #=> "bar\nbaz\nfoo\n"
# p s #=> #<Process::Status: pid 32682 exit 0>
#
# # generate a thumnail image using the convert command of ImageMagick.
# # However, if the image stored really in a file,
# # system("convert", "-thumbnail", "80", "png:#{filename}", "png:-") is better
# # because memory consumption.
# # But if the image is stored in a DB or generated by gnuplot Open3.capture2 example,
# # Open3.capture3 is considerable.
# #
# image = File.read("/usr/share/openclipart/png/animals/mammals/sheep-md-v0.1.png", :binmode=>true)
# thumnail, err, s = Open3.capture3("convert -thumbnail 80 png:- png:-", :stdin_data=>image, :binmode=>true)
# if s.success?
# STDOUT.binmode; print thumnail
# end
#
def capture3(*cmd)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
binmode = opts[:binmode]
i_data = (opts[:stdin_data] || '').to_s
o_data = ''
e_data = ''
popen3(*cmd) do |i, o, e, t|
if binmode
i.binmode
o.binmode
e.binmode
end
i_complete = i_data.empty?
o_complete = false
e_complete = false
until i_complete && o_complete && e_complete
i_blocked = false
o_blocked = false
e_blocked = false
unless i_complete
begin
bytes_written = i.write_nonblock(i_data)
if bytes_written == i_data.length
i.close
i_complete = true
else
i_data = i_data[bytes_written .. -1]
end
rescue Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EINTR
i_blocked = true
end
end
unless o_complete
begin
o_data << o.read_nonblock(CAPTURE_BUFFER_SIZE)
rescue Errno::EWOULDBLOCK, Errno::EAGAIN
o_blocked = true
rescue EOFError
raise unless i_complete
o.close
o_complete = true
end
end
unless e_complete
begin
e_data << e.read_nonblock(CAPTURE_BUFFER_SIZE)
rescue Errno::EWOULDBLOCK, Errno::EAGAIN
e_blocked = true
rescue EOFError
raise unless i_complete
e.close
e_complete = true
end
end
if i_blocked && o_blocked && e_blocked
IO.select([o, e], [i], [o,e,i])
end
end
return [o_data, e_data, t.value]
end
end
module_function :capture3
# Open3.capture2 captures the standard output of a command.
#
# stdout_str, status = Open3.capture2(cmd... [, opts])
#
# The cmd arguments are passed to Open3.popen3.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# Example:
#
# # factor is a command for integer factorization.
# o, s = Open3.capture2("factor", :stdin_data=>"42")
# p o #=> "42: 2 3 7\n"
#
# # generate x**2 graph in png using gnuplot.
# gnuplot_commands = <<"End"
# set terminal png
# plot x**2, "-" with lines
# 1 14
# 2 1
# 3 8
# 4 5
# e
# End
# image, s = Open3.capture2("gnuplot", :stdin_data=>gnuplot_commands, :binmode=>true)
#
def capture2(*cmd)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
binmode = opts[:binmode]
i_data = (opts[:stdin_data] || '').to_s
o_data = ''
popen3(*cmd) do |i, o, e, t|
e.close
if binmode
i.binmode
o.binmode
e.binmode
end
i_complete = i_data.empty?
o_complete = false
until i_complete && o_complete
i_blocked = false
o_blocked = false
unless i_complete
begin
bytes_written = i.write_nonblock(i_data)
if bytes_written == i_data.length
i.close
i_complete = true
else
i_data = i_data[bytes_written .. -1]
end
rescue Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EINTR
i_blocked = true
end
end
unless o_complete
begin
o_data << o.read_nonblock(CAPTURE_BUFFER_SIZE)
rescue Errno::EWOULDBLOCK, Errno::EAGAIN
o_blocked = true
rescue EOFError
raise unless i_complete
o.close
o_complete = true
end
end
if i_blocked && o_blocked && e_blocked
IO.select([o], [i], [o,i])
end
end
return [o_data, t.value]
end
end
module_function :capture2
# Open3.capture2e captures the standard output and the standard error of a command.
#
# stdout_and_stderr_str, status = Open3.capture2e(cmd... [, opts])
#
# The cmd arguments are passed to Open3.popen3.
#
# If opts[:stdin_data] is specified, it is sent to the command's standard input.
#
# If opts[:binmode] is true, internal pipes are set to binary mode.
#
# Example:
#
# # capture make log
# make_log, s = Open3.capture2e("make")
#
def capture2e(*cmd)
if Hash === cmd.last
opts = cmd.pop.dup
else
opts = {}
end
binmode = opts[:binmode]
i_data = (opts[:stdin_data] || '').to_s
oe_data = ''
popen3(*cmd) do |i, o, e, t|
if binmode
i.binmode
o.binmode
e.binmode
end
i_complete = i_data.empty?
o_complete = false
e_complete = false
until i_complete && o_complete && e_complete
i_blocked = false
o_blocked = false
e_blocked = false
unless i_complete
begin
bytes_written = i.write_nonblock(i_data)
if bytes_written == i_data.length
i.close
i_complete = true
else
i_data = i_data[bytes_written .. -1]
end
rescue Errno::EWOULDBLOCK, Errno::EAGAIN, Errno::EINTR
i_blocked = true
end
end
unless o_complete
begin
oe_data << o.read_nonblock(CAPTURE_BUFFER_SIZE)
rescue Errno::EWOULDBLOCK, Errno::EAGAIN
o_blocked = true
rescue EOFError
raise unless i_complete
o.close
o_complete = true
end
end
unless e_complete
begin
oe_data << e.read_nonblock(CAPTURE_BUFFER_SIZE)
rescue Errno::EWOULDBLOCK, Errno::EAGAIN
e_blocked = true
rescue EOFError
raise unless i_complete
e.close
e_complete = true
end
end
if i_blocked && o_blocked && e_blocked
IO.select([o, e], [i], [o,e,i])
end
end
return [oe_data, t.value]
end
end
module_function :capture2e
CAPTURE_BUFFER_SIZE = 65536
# Open3.pipeline_rw starts a list of commands as a pipeline with pipes
# which connects stdin of the first command and stdout of the last command.
#
# Open3.pipeline_rw(cmd1, cmd2, ...) {|first_stdin, last_stdout, wait_threads|
# ...
# }
#
# first_stdin, last_stdout, wait_threads = Open3.pipeline_rw(cmd1, cmd2, ...)
# ...
# first_stdin.close
# last_stdout.close
#
# Each cmd is a string or an array.
# If it is an array, the first element is the command name, and the remaining
# elements are arguments passed (without parsing) to the command.
#
# Example:
#
# Open3.pipeline_rw(["tr", "-dc", "A-Za-z"], ["wc", "-c"]) {|i,o,ts|
# i.puts "All persons more than a mile high to leave the court."
# i.close
# p o.gets #=> "42\n"
# }
#
# Open3.pipeline_rw("sort", "cat -n") {|stdin, stdout, wait_thrs|
# stdin.puts "foo"
# stdin.puts "bar"
# stdin.puts "baz"
# stdin.close # send EOF to sort.
# p stdout.read #=> " 1\tbar\n 2\tbaz\n 3\tfoo\n"
# }
def pipeline_rw(*cmds, &block)
raise NotImplementedError
end
module_function :pipeline_rw
# Open3.pipeline_r starts a list of commands as a pipeline with a pipe
# which connects stdout of the last command.
#
# Open3.pipeline_r(cmd1, cmd2, ...) {|last_stdout, wait_threads|
# ...
# }
#
# last_stdout, wait_threads = Open3.pipeline_r(cmd1, cmd2, ...)
# ...
# last_stdout.close
#
# Each cmd is a string or an array.
# If it is an array, the first element is the command name, and the remaining
# elements are arguments passed (without parsing) to the command.
#
# Example:
#
# Open3.pipeline_r("zcat /var/log/apache2/access.log.*.gz",
# [{"LANG"=>"C"}, "grep", "GET /favicon.ico"],
# "logresolve") {|o, ts|
# o.each_line {|line|
# ...
# }
# }
#
# Open3.pipeline_r("yes", "head -10") {|o, ts|
# p o.read #=> "y\ny\ny\ny\ny\ny\ny\ny\ny\ny\n"
# p ts[0].value #=> #<Process::Status: pid 24910 SIGPIPE (signal 13)>
# p ts[1].value #=> #<Process::Status: pid 24913 exit 0>
# }
#
def pipeline_r(*cmds, &block)
raise NotImplementedError
end
module_function :pipeline_r
# Open3.pipeline_w starts a list of commands as a pipeline with a pipe
# which connects stdin of the first command.
#
# Open3.pipeline_w(cmd1, cmd2, ...) {|first_stdin, wait_threads|
# ...
# }
#
# first_stdin, wait_threads = Open3.pipeline_w(cmd1, cmd2, ...)
# ...
# first_stdin.close
#
# Each cmd is a string or an array.
# If it is an array, the first element is the command name, and the remaining
# elements are arguments passed (without parsing) to the command.
#
# Example:
#
# Open3.pipeline_w("bzip2 -c", :out=>"/tmp/hello.bz2") {|i, ts|
# i.puts "hello"
# }
#
def pipeline_w(*cmds, &block)
raise NotImplementedError
end
module_function :pipeline_w
# Open3.pipeline_start starts a list of commands as a pipeline.
# No pipe made for stdin of the first command and
# stdout of the last command.
#
# Open3.pipeline_start(cmd1, cmd2, ...) {|wait_threads|
# ...
# }
#
# wait_threads = Open3.pipeline_start(cmd1, cmd2, ...)
# ...
#
# Each cmd is a string or an array.
# If it is an array, the first element is the command name, and the remaining
# elements are arguments passed (without parsing) to the command.
#
# Example:
#
# # run xeyes in 10 seconds.
# Open3.pipeline_start("xeyes") {|ts|
# sleep 10
# t = ts[0]
# Process.kill("TERM", t.pid)
# p t.value #=> #<Process::Status: pid 911 SIGTERM (signal 15)>
# }
#
# # convert pdf to ps and send it to a printer.
# # collect error message of pdftops and lpr.
# pdf_file = "paper.pdf"
# printer = "printer-name"
# err_r, err_w = IO.pipe
# Open3.pipeline_start(["pdftops", pdf_file, "-"],
# ["lpr", "-P#{printer}"],
# :err=>err_w) {|ts|
# err_w.close
# p err_r.read # error messages of pdftops and lpr.
# }
#
def pipeline_start(*cmds, &block)
raise NotImplementedError
end
module_function :pipeline_start
# Open3.pipeline starts a list of commands as a pipeline.
# It waits the finish of the commands.
# No pipe made for stdin of the first command and
# stdout of the last command.
#
# status_list = Open3.pipeline(cmd1, cmd2, ...)
#
# Each cmd is a string or an array.
# If it is an array, the first element is the command name, and the remaining
# elements are arguments passed (without parsing) to the command.
#
# Example:
#
# fname = "/usr/share/man/man1/ruby.1.gz"
# p Open3.pipeline(["zcat", fname], "nroff -man", "less")
# #=> [#<Process::Status: pid 11817 exit 0>,
# # #<Process::Status: pid 11820 exit 0>,
# # #<Process::Status: pid 11828 exit 0>]
#
# fname = "/usr/share/man/man1/ls.1.gz"
# Open3.pipeline(["zcat", fname], "nroff -man", "colcrt")
#
# # convert PDF to PS and send to a printer by lpr
# pdf_file = "paper.pdf"
# printer = "printer-name"
# Open3.pipeline(["pdftops", pdf_file, "-"],
# ["lpr", "-P#{printer}"])
#
# # count lines
# Open3.pipeline("sort", "uniq -c", :in=>"names.txt", :out=>"count")
#
# # cyclic pipeline
# r,w = IO.pipe
# w.print "ibase=14\n10\n"
# Open3.pipeline("bc", "tee /dev/tty", :in=>r, :out=>w)
# #=> 14
# # 18
# # 22
# # 30
# # 42
# # 58
# # 78
# # 106
# # 202
#
def pipeline(*cmds)
raise NotImplementedError
end
module_function :pipeline
end
| true |
79b5090ae280ac5870cc552ca61440c45b166ac2
|
Ruby
|
atpsoft/dohutil
|
/lib/dohutil/core_ext/bigdecimal.rb
|
UTF-8
| 995 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
require 'bigdecimal'
require 'bigdecimal/util'
class Integer
if !method_defined?(:to_d)
def to_d
BigDecimal(self)
end
end
end
class BigDecimal
if !method_defined?(:to_d)
def to_d
self
end
end
alias :_doh_original_to_s :to_s
def to_s(format = 'F')
_doh_original_to_s(format)
end
def to_dig(digits_after_decimal = 2)
raise ArgumentError.new("digits_after_decimal must be >= 0") if digits_after_decimal < 0
if nan? || infinite?
return '0' if digits_after_decimal == 0
return '0.' + ('0' * digits_after_decimal)
end
if digits_after_decimal == 0
return to_i.to_s
end
retval = truncate(digits_after_decimal).to_s('F')
digits_needed = retval.index('.') + digits_after_decimal + 1 - retval.size
retval += ('0' * digits_needed) if digits_needed > 0
retval
end
end
class NilClass
NIL_ZERO_BIGD = BigDecimal(0)
if !method_defined?(:to_d)
def to_d
NIL_ZERO_BIGD
end
end
end
| true |
9b5d8ebc90c6a78eab4d8222f7b3d29a5d1fc164
|
Ruby
|
CarlosSe/reto-01-ruby-dia-04
|
/Game.rb
|
UTF-8
| 577 | 3.25 | 3 |
[] |
no_license
|
require_relative 'CreateBoard'
require_relative 'SearchNeighbors'
require_relative 'ShowGame'
class Game
SIZE = 25
def start
game = CreateBoard.create(size: SIZE)
while true
system('clear')
game.each do |row|
row.each do |cell|
contador = SearchNeighbors.search(game: game, cell: cell)
if contador >= 4 || contador <= 1
cell.value = 0
else
cell.value = 1
end
end
end
ShowGame.printGame(game: game);
sleep(1)
end
end
end
game = Game.new
game.start
| true |
cc23cfe78ea49d9d312155a6714405306acc74ce
|
Ruby
|
13k/go-steam-resources
|
/rakelib/logging.rb
|
UTF-8
| 1,231 | 2.984375 | 3 |
[] |
no_license
|
# frozen_string_literal: true
require 'rake'
LOG_M = Mutex.new
COLORS = {
reset: 0,
black: 30,
red: 31,
green: 32,
yellow: 33,
blue: 34,
magenta: 35,
cyan: 36,
white: 37,
}.freeze
# Hack to synchronize rake output messages.
# This won't avoid out-of-order lines from multiple tasks, it will only avoid a line being written
# before a previous line finished. It works for single-line status messages.
module Rake
class << self
alias rake_output_message_orig rake_output_message
def rake_output_message(*args, &block)
LOG_M.synchronize do
rake_output_message_orig(*args, &block)
$stderr.flush
end
end
end
end
module Logging
def colorize(text, color_code)
color_code = COLORS.fetch(color_code) if color_code.is_a?(Symbol)
"\033[#{color_code}m#{text}\033[0m"
end
COLORS.each do |key, color_code|
define_method(key) do |text|
colorize(text, color_code)
end
end
def say(msg)
LOG_M.synchronize do
$stderr.puts(msg) # rubocop:disable Style/StderrPuts
$stderr.flush
end
end
def say_status(status, message, color = :reset)
say("#{colorize(status.to_s.rjust(11), color)} #{colorize(message, :reset)}")
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.