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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
b580850509bf6a719b6045c198ae0d2f424f4f5c | Ruby | maximefriess/Emerald | /app/writers/csv_parser.rb | UTF-8 | 1,457 | 3.0625 | 3 | [] | no_license | require 'csv'
class CsvParser
def initialize(filepath)
@raw_parsed = []
csv_options = { headers: :first_row }
CSV.foreach(filepath, csv_options) do |row|
if row['Accomodation Rev']
revenue = row['Accomodation Rev'].gsub(/[ €]/, '').to_f
else
revenue = row['Accomodation Rev']
end
if row['Average Night rate 2']
avg = row['Average Night rate 2'].gsub(/[ €]/, '').to_f
else
avg = row['Average Night rate 2']
end
@raw_parsed << {
name: row['Properties'],
year: row[row.headers.first],
month: row['Mois'],
revenue: revenue,
occupancy_ratio: row['Occpancy Ratio'].to_f,
average_night_rate: avg
}
end
end
def create_bookings
Booking.destroy_all
@raw_parsed.each do |booking|
if Listing.find_by(name: booking[:name])
booking = Booking.new(
listing_id: Listing.find_by(name: booking[:name]).id,
year: booking[:year],
month: booking[:month],
revenue: booking[:revenue],
occupancy_ratio: booking[:occupancy_ratio],
average_night_rate: booking[:average_night_rate]
)
booking.save!
end
end
end
def all_listings
csv_listing_names = []
@raw_parsed.each do |booking|
csv_listing_names << booking[:name]
end
csv_listing_names = csv_listing_names.uniq
csv_listing_names
end
end
| true |
55fa0c2364cf1713f0ed650a65c3f295dd19c750 | Ruby | wardymate/codewars-kata | /statistics_algorithm_calculate_mean/lib/meaner.rb | UTF-8 | 127 | 3.03125 | 3 | [] | no_license | class Meaner
def calc_mean(input)
return 0 if input.length == 0
input.map{|e|e.to_f}.inject(:+)/input.size
end
end | true |
560be44aeb6942baa42025f13717380c6994ac18 | Ruby | watkajtys/weatherBot | /mattBot.rb | UTF-8 | 1,640 | 3.265625 | 3 | [] | no_license | require_relative "weather"
require 'socket'
class Bot
attr_accessor :server, :msg
def initialize
@current_reporter = WeatherReporter.new
@forecast_reporter = WeatherReporter.new
@temp_reporter = WeatherReporter.new
@server = 'chat.freenode.net' #in runner
@port = '6667'
@nick = 'BetterWeatherBot'
@channel = '#bitmaker'
@response_prompt = 'privmsg #bitmaker :'
@callings = ['current', 'forecast', 'temperature']
end
def respond
responses = {
['current'] => current,
['forecast'] => forecast,
['temperature'] => temp
}
until server.eof? do
@msg = @server.gets.downcase
puts msg
matched_keyword = []
wasCalled = false
@callings.each do |c|
if msg.include? c
matched_keyword << c
wasCalled = true
end
end
if msg.include? @response_prompt and wasCalled
server.puts "PRIVMSG #{@channel} : #{responses[matched_keyword]}"
elsif msg.include? "ping"
server.puts "PRIVMSG #{@channel}" + msg.gsub("ping", "PONG")
end
end
end
def current
@current_reporter.get_conditions
end
def forecast
@forecast_reporter.get_forecast_today
end
def temp
@temp_reporter.get_temperatures_week
end
def server_connect
@server = TCPSocket.open(@server,@port)
server.puts "USER WeatherBot 0 * WeatherBot"
server.puts "NICK #{@nick}"
server.puts "JOIN #{@channel}"
server.puts "PRIVMSG #{@channel} :Hi, I'm WeatherBot. Ask me CURRENT for the current conditions, FORECAST for the forcast today, or TEMPERATURE for the temperature for the next three days!!"
end
end
weatherBot = Bot.new
weatherBot.server_connect
weatherBot.respond
| true |
0ae5b6aef28557a20ca2b36cb835f53a40aa3bf2 | Ruby | jamillosantos/tfprog2012.1 | /lib/geasy/lib/geasy/numeric.rb | UTF-8 | 110 | 3.53125 | 4 | [] | no_license |
class Numeric
def radians
self / 180.0 * Math::PI
end
def degrees
(self / Math::PI) * 180.0
end
end | true |
244989d433ee5cb1dbc9ba0c8a000c8a9c6efc41 | Ruby | thePegasusai/theme-check | /test/parsing_helpers_test.rb | UTF-8 | 1,037 | 2.671875 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require "test_helper"
class ParsingHelpersTest < Minitest::Test
include ThemeCheck::ParsingHelpers
def test_outside_of_strings
chunks = []
outside_of_strings("1'\"2'3\"4\"") { |chunk| chunks << chunk }
assert_equal(["1", "3"], chunks)
end
def test_outside_of_strings_with_empty_string
chunks = []
outside_of_strings("one: '.', '' | two: ',', '.'") { |chunk| chunks << chunk }
assert_equal(["one: ", ", ", " | two: ", ", "], chunks)
chunks = []
outside_of_strings("1'' '2'3") { |chunk| chunks << chunk }
assert_equal(["1", " ", "3"], chunks)
end
def test_outside_of_strings_with_newline
chunks = []
outside_of_strings(<<~CONTENTS) { |chunk| chunks << chunk }
next: '<i class="icon icon--right-t"></i><span class="icon-fallback__text">Next Page</span>',
previous: '<i class="icon icon--left-t"></i><span class="icon-fallback__text">Previous Page</span>'
CONTENTS
assert_equal(["next: ", ",\nprevious: ", "\n"], chunks)
end
end
| true |
c261e9cbfd8f54d25b594a4c6d6acb2a3e84e73e | Ruby | jduckett/duck_test | /test/unit/platforms/listener_test.rb | UTF-8 | 17,081 | 2.703125 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # this set of tests was causing all types of problems, because, it is writing to files.
# need to refactor how it should be simulating a file being changed
#require 'test_helper'
#require 'digest/sha1'
#class ClientObject
#def listener_event(event)
#return "triggered"
#end
#end
#class ListenerTestObject
#include DuckTest::Platforms::Listener
#def write_random_string(file_spec)
#file = nil
#begin
#file = File.open(file_spec, "w")
#file.write (0...250).map{ ('a'..'z').to_a[rand(26)] }.join
#rescue Exception => e
#puts e
#puts e.backtrace.join("\n")
#ensure
#file.close if file
#end
#end
#end
#class ListenerTest < ActiveSupport::TestCase
###################################################################################
#def setup
#@test_object = ListenerTestObject.new
#end
###################################################################################
#test "dir_list should be an empty array by default" do
#assert @test_object.dir_list.kind_of?(Array), "expected value: Array actual value: #{@test_object.dir_list.class.name}"
#assert @test_object.dir_list.blank?, "expected value: [] actual value: #{@test_object.dir_list}"
#end
###################################################################################
#test "file_list should be an empty array by default" do
#assert @test_object.file_list.kind_of?(Hash), "expected value: Hash actual value: #{@test_object.file_list.class.name}"
#assert @test_object.file_list.blank?, "expected value: {} actual value: #{@test_object.file_list}"
#end
###################################################################################
#test "self.stop should be false by default" do
#assert !@test_object.stop, "expected value: false actual value: #{@test_object.stop}"
#end
###################################################################################
#test "should set the value of self.stop" do
#assert !@test_object.stop, "expected value: false actual value: #{@test_object.stop}"
#@test_object.stop = true
#assert @test_object.stop, "expected value: true actual value: #{@test_object.stop}"
#end
###################################################################################
#test "should set listener event block" do
#assert @test_object.block.blank?, "expected value: nil actual value: #{@test_object.block}"
#@test_object.listener_event {|event| puts event}
#assert @test_object.block.kind_of?(Proc), "expected value: Proc.new actual value: #{@test_object.block}"
#end
###################################################################################
#test "should trigger listener event" do
#client_object = ClientObject.new
#@test_object.listener_event {|event| client_object.listener_event(event)}
#value = @test_object.call_listener_event(WatchEvent.new(self, "test.rb", :update))
#assert value.eql?("triggered"), "expected value: triggered actual value: #{value}"
#end
###################################################################################
#test "should watch a directory via watch_file_spec method" do
#file_spec = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full).first
#@test_object.watch_file_spec(file_spec)
#assert @test_object.dir_list.include?(file_spec), "should be found in dir_list: #{file_spec}"
#assert !@test_object.file_list[file_spec].blank?, "should be found in file_list: #{file_spec}"
#end
###################################################################################
#test "should watch a directory via watch method" do
#file_spec = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full).first
#@test_object.watch(file_spec)
#assert @test_object.dir_list.include?(file_spec), "should be found in dir_list: #{file_spec}"
#assert !@test_object.file_list[file_spec].blank?, "should be found in file_list: #{file_spec}"
#end
###################################################################################
#test "should watch a file via watch_file_spec method" do
#file_spec = TestFiles.file_spec("bike_test")
#@test_object.watch_file_spec(file_spec)
#assert !@test_object.dir_list.include?(file_spec), "should be found in dir_list: #{file_spec}"
#assert !@test_object.file_list[file_spec].blank?, "should be found in file_list: #{file_spec}"
#end
###################################################################################
#test "should watch a file via watch method" do
#file_spec = TestFiles.file_spec("bike_test")
#@test_object.watch(file_spec)
#assert !@test_object.dir_list.include?(file_spec), "should be found in dir_list: #{file_spec}"
#assert !@test_object.file_list[file_spec].blank?, "should be found in file_list: #{file_spec}"
#end
###################################################################################
#test "directory status should be watched" do
#file_spec = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full).first
#@test_object.watch(file_spec)
#assert @test_object.watched?(file_spec), "file should be watched: #{file_spec}"
#end
###################################################################################
#test "directory status should NOT be watched" do
#file_spec = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full).first
#assert !@test_object.watched?(file_spec), "file should NOT be watched: #{file_spec}"
#end
###################################################################################
#test "directory status should NOT be changed if NOT watched" do
#file_spec = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full).first
#assert !@test_object.changed?(file_spec), "directory should NOT be changed if NOT watched: #{file_spec}"
#end
###################################################################################
#test "directory status should NOT be changed" do
#file_spec = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full).first
#@test_object.watch(file_spec)
#assert !@test_object.changed?(file_spec), "directory should NOT be changed: #{file_spec}"
#end
###################################################################################
## not sure the importantance of this test.
## really don't like using sleep in a test. if it causes a real problem, then, remove it
#test "directory status SHOULD be changed" do
#file_spec = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full).first
#@test_object.watch(file_spec)
#assert !@test_object.changed?(file_spec), "directory should NOT be changed at this point: #{file_spec}"
#sleep(0.5)
#FileUtils.touch(file_spec)
#assert @test_object.changed?(file_spec), "directory SHOULD be changed: #{file_spec}"
#end
###################################################################################
#test "file status should be watched" do
#file_spec = TestFiles.file_spec("bike_test")
#@test_object.watch(file_spec)
#assert @test_object.watched?(file_spec), "file should be watched: #{file_spec}"
#end
###################################################################################
#test "file status should NOT be watched" do
#file_spec = TestFiles.file_spec("bike_test")
#assert !@test_object.watched?(file_spec), "file should NOT be watched: #{file_spec}"
#end
###################################################################################
#test "file status should NOT be changed if NOT watched" do
#file_spec = TestFiles.file_spec("bike_test")
#assert !@test_object.changed?(file_spec), "file should NOT be changed if NOT watched: #{file_spec}"
#end
###################################################################################
#test "file status should NOT be changed" do
#file_spec = TestFiles.file_spec("bike_test")
#@test_object.watch(file_spec)
#assert !@test_object.changed?(file_spec), "file should NOT be changed: #{file_spec}"
#end
###################################################################################
#test "file status SHOULD be changed" do
#file_spec = TestFiles.file_spec("bike_test")
#@test_object.watch(file_spec)
#assert !@test_object.changed?(file_spec), "file should NOT be changed at this point: #{file_spec}"
#@test_object.write_random_string(file_spec)
#assert @test_object.changed?(file_spec), "file SHOULD be changed: #{file_spec}"
#end
###################################################################################
#test "should update directory spec attributes" do
#file_spec = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full).first
#@test_object.update_file_spec(file_spec)
#file_object = @test_object.file_list[file_spec]
#assert file_object, "file_object should not be nil"
#assert @test_object.watched?(file_spec), "file should be watched: #{file_spec}"
#assert file_object[:mtime].eql?(File.mtime(file_spec).to_f), "#{file_object[:mtime]} does not match: #{File.mtime(file_spec).to_f}"
#assert file_object[:is_dir], "SHOULD be a directory: #{file_spec}"
#end
###################################################################################
#test "should update file spec attributes" do
#file_spec = TestFiles.file_spec("bike_test")
#@test_object.update_file_spec(file_spec)
#file_object = @test_object.file_list[file_spec]
#assert file_object, "file_object should not be nil"
#assert @test_object.watched?(file_spec), "file should be watched: #{file_spec}"
#assert file_object[:mtime].eql?(File.mtime(file_spec).to_f), "#{file_object[:mtime]} does not match: #{File.mtime(file_spec).to_f}"
#assert file_object[:sha].eql?(Digest::SHA1.file(file_spec).to_s), "#{file_object[:sha]} does not match: #{Digest::SHA1.file(file_spec).to_s}"
#assert !file_object[:is_dir], "should not be a directory: #{file_spec}"
#end
###################################################################################
#test "should update ALL file spec attributes" do
## get a list of files, write a random string to all of them, then, watch all of them
#list = TestFiles.find_files(dirs: {dir: :test, pattern: /^unit/}, path: :full)
#list.each {|file_spec| @test_object.write_random_string(file_spec)}
#list.each {|file_spec| @test_object.watch(file_spec)}
## none of them should have changed yet
#list.each {|file_spec| assert !@test_object.changed?(file_spec), "file should NOT be changed yet: #{file_spec}"}
## now, write a random string to all of them again
#list.each {|file_spec| @test_object.write_random_string(file_spec)}
## all of them should have changed
#list.each {|file_spec| assert @test_object.changed?(file_spec), "file should be changed after write_random_string: #{file_spec}"}
## update the attributes for all files being watched
#@test_object.update_all
## none of them should been considered changed now
#list.each {|file_spec| assert !@test_object.changed?(file_spec), "file should NOT be changed again: #{file_spec}"}
#end
###################################################################################
#test "should find nothing unless files have changed" do
#dirs = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full)
#files = TestFiles.find_files(dirs: {dir: :test, pattern: /^unit/, path: :full}, pattern: :all, path: :full)
#dirs.each {|item| @test_object.watch(item)}
#files.each {|item| @test_object.watch(item)}
#list = @test_object.refresh
#assert list.blank?, "Nothing has changed, therefore, changed list should be blank"
#end
###################################################################################
#test "should find two changed files" do
#dirs = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full)
#files = TestFiles.find_files(dirs: {dir: :test, pattern: /^unit/, path: :full}, pattern: :all, path: :full)
#dirs.each {|item| @test_object.watch(item)}
#files.each {|item| @test_object.watch(item)}
#list = @test_object.refresh
#assert list.blank?, "Nothing has changed, therefore, changed list should be blank"
#@test_object.write_random_string(files.first)
#@test_object.write_random_string(files.last)
#list = @test_object.refresh
#assert list.length == 2, "expected value: 2 actual list of changed files: #{list.length}"
#end
###################################################################################
#test "should find multiple changed files" do
#dirs = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full)
#files = TestFiles.find_files(dirs: {dir: :test, pattern: /^unit/, path: :full}, pattern: :all, path: :full)
#dirs.each {|item| @test_object.watch(item)}
#files.each {|item| @test_object.watch(item)}
#list = @test_object.refresh
#assert list.blank?, "Nothing has changed, therefore, changed list should be blank"
#@test_object.write_random_string(files.first)
#@test_object.write_random_string(files.last)
#list = @test_object.refresh
#assert list.length == 2, "expected value: 2 actual list of changed files: #{list.length}"
#files.each {|item| @test_object.write_random_string(item)}
#list = @test_object.refresh
#assert list.length == files.length, "expected value: #{files.length} actual list of changed files: #{list.length}"
#end
###################################################################################
#test "should find a new directory" do
#dirs = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full)
#files = TestFiles.find_files(dirs: {dir: :test, pattern: /^unit/, path: :full}, pattern: :all, path: :full)
#dirs.each {|item| @test_object.watch(item)}
#files.each {|item| @test_object.watch(item)}
#file_spec = "#{File.dirname(files.first)}/new_dir"
#FileUtils.mkdir(file_spec)
#buffer = @test_object.dir_list.length
#list = @test_object.refresh
#assert @test_object.dir_list.length == (buffer + 1), "expected value: #{buffer + 1} actual list of changed files: #{@test_object.dir_list.length}"
#FileUtils.rmdir(file_spec)
#end
###################################################################################
#test "should recognize a directory has been deleted" do
#dirs = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full)
#files = TestFiles.find_files(dirs: {dir: :test, pattern: /^unit/, path: :full}, pattern: :all, path: :full)
#dirs.each {|item| @test_object.watch(item)}
#files.each {|item| @test_object.watch(item)}
#file_spec = "#{File.dirname(files.first)}/new_dir"
#FileUtils.mkdir(file_spec)
#buffer = @test_object.dir_list.length
#list = @test_object.refresh
#assert @test_object.dir_list.length == (buffer + 1), "expected value: #{buffer + 1} actual list of changed files: #{@test_object.dir_list.length}"
#FileUtils.rmdir(file_spec)
#list = @test_object.refresh
#assert @test_object.dir_list.length == buffer, "expected value: #{buffer} actual list of changed files: #{@test_object.dir_list.length}"
#end
###################################################################################
#test "should find a new file" do
#dirs = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full)
#files = TestFiles.find_files(dirs: {dir: :test, pattern: /^unit/, path: :full}, pattern: :all, path: :full)
#dirs.each {|item| @test_object.watch(item)}
#files.each {|item| @test_object.watch(item)}
#file_spec = "#{File.dirname(files.first)}/new_file.rb"
#FileUtils.touch(file_spec)
#@test_object.write_random_string(file_spec)
#list = @test_object.refresh
#assert list.length == 1, "expected value: 1 actual list of changed files: #{list.length}"
#FileUtils.rm(file_spec)
#end
###################################################################################
#test "should find a file has been deleted" do
#dirs = TestFiles.find_dirs(dir: :test, pattern: /^unit/, path: :full)
#files = TestFiles.find_files(dirs: {dir: :test, pattern: /^unit/, path: :full}, pattern: :all, path: :full)
#dirs.each {|item| @test_object.watch(item)}
#files.each {|item| @test_object.watch(item)}
#file_spec = "#{File.dirname(files.first)}/new_file.rb"
#FileUtils.touch(file_spec)
#@test_object.write_random_string(file_spec)
#buffer = @test_object.file_list.length
#list = @test_object.refresh
#assert @test_object.file_list.length == (buffer + 1), "expected value: #{buffer + 1} actual list of changed files: #{@test_object.file_list.length}"
#FileUtils.rm(file_spec)
#list = @test_object.refresh
#assert @test_object.file_list.length == buffer, "expected value: #{buffer} actual list of changed files: #{@test_object.file_list.length}"
#end
#end
| true |
29002024138c2ff805400581512cb24c31238b44 | Ruby | hoshinotsuyoshi/euler | /lib/euler045.rb | UTF-8 | 623 | 3.453125 | 3 | [] | no_license | # coding: utf-8
class Euler045
@pentas = { 1 => 1 }
class << self
# 五角数のみメモ化する
# 配列よりハッシュのほうが早い
def pentas(x)
@pentas[x] || (@pentas[x] = ((x * (3 * x - 1)) / 2).to_i)
end
def hexas(x)
x * (2 * x - 1)
end
def penta?(x)
while x > @pentas[@pentas.keys.max]
@tmp = @pentas.keys.max + 1
pentas @tmp
end
@pentas.clear
pentas @tmp
!!(@pentas.values.index x)
end
def solve
n = 1
while hexas(n) <= 40_755 || !penta?(hexas n); n += 1; end
hexas n
end
end
end
| true |
d3fbc04ed3a217d5b4cc1b1158e6f3822ecb5e2f | Ruby | codeAligned/aa-prep-work | /pre-course/01-ruby_monk/00-ruby_primer/143-palindrome.rb | UTF-8 | 525 | 4.3125 | 4 | [] | no_license | # Problem Statement
# Given a sentence, return true if the sentence is a palindrome.
#
# You are supposed to write a method palindrome? to accomplish this task.
#
# Note Ignore whitespace and cases of characters.
#
# Example:
# Given "Never odd or even" the method should return true
#
# https://rubymonk.com/learning/books/1-ruby-primer/problems/143-palindrome
def palindrome?(sentence)
downcase_stripped_sentence = sentence.downcase.gsub(" ", "")
downcase_stripped_sentence == downcase_stripped_sentence.reverse
end
| true |
62200f740c9623e5e0fcbd4eeb3d1e24ece02285 | Ruby | DTF919/ttt-10-current-player-ruby-intro-000 | /lib/current_player.rb | UTF-8 | 276 | 3.375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def turn_count(board)
counter = 0
board.each {|position| counter += 1 if position != " "}
return counter
end
def current_player(board)
counter = 0
board.each{|position| counter += 1 if position != " "}
x_or_o = counter % 2 == 0 ? "X" : "O"
return x_or_o
end
| true |
a21541738825cb1c66baf84819050cd0e1589601 | Ruby | robertmarsal/moodle | /test/test_client.rb | UTF-8 | 1,113 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'test_helper'
require 'moodle/client'
class ClientTest < Test::Unit::TestCase
# Test initialization with hash
def test_initialize_with_hash
client = Moodle::Client.new({
:username => 'test_username',
:password => 'test_password',
:domain => 'test_domain',
:protocol => 'test_protocol',
:service => 'test_service',
:format => 'test_format',
:token => 'test_token'
})
assert_equal 'test_username', client.username
assert_equal 'test_password', client.password
assert_equal 'test_domain', client.domain
assert_equal 'test_protocol', client.protocol
assert_equal 'test_service', client.service
assert_equal 'test_format', client.format
assert_equal 'test_token', client.token
end
# Test obtaining a token
def test_obtain_token
client = Moodle::Protocol::Rest.new
client.stubs(:request).returns('{"token" : "12345"}')
moodle_client = Moodle::Client.new({:token => 'dummy', :domain => 'test'})
moodle_client.stubs(:client).returns(client)
assert_equal '12345', moodle_client.obtain_token()
end
end | true |
fefcdfba23652d2383a470a8e5d9aa8b1f415631 | Ruby | hadleynet/quality-measure-engine | /lib/qme/map/map_reduce_executor.rb | UTF-8 | 6,051 | 2.59375 | 3 | [] | no_license | module QME
module MapReduce
# Computes the value of quality measures based on the current set of patient
# records in the database
class Executor
include DatabaseAccess
# Create a new Executor for a specific measure, effective date and patient population.
# @param [String] measure_id the measure identifier
# @param [String] sub_id the measure sub-identifier or null if the measure is single numerator
# @param [Hash] parameter_values a hash that may contain the following keys: 'effective_date' the measurement period end date, 'test_id' an identifier for a specific set of patients
def initialize(measure_id, sub_id, parameter_values)
@measure_id = measure_id
@sub_id = sub_id
@parameter_values = parameter_values
determine_connection_information
end
# Examines the patient_cache collection and generates a total of all groups
# for the measure. The totals are placed in a document in the query_cache
# collection.
# @return [Hash] measure groups (like numerator) as keys, counts as values
def count_records_in_measure_groups
patient_cache = get_db.collection('patient_cache')
query = {'value.measure_id' => @measure_id, 'value.sub_id' => @sub_id,
'value.effective_date' => @parameter_values['effective_date'],
'value.test_id' => @parameter_values['test_id']}
query.merge!(filter_parameters)
result = {:measure_id => @measure_id, :sub_id => @sub_id,
:effective_date => @parameter_values['effective_date'],
:test_id => @parameter_values['test_id'], :filters => @parameter_values['filters']}
aggregate = patient_cache.group({cond: query,
initial: {population: 0, denominator: 0, numerator: 0, antinumerator: 0, exclusions: 0, considered: 0},
reduce: "function(record,sums) { for (var key in sums) { sums[key] += (record['value'][key] || key == 'considered') ? 1 : 0 } }"}).first
aggregate ||= {population: 0, denominator: 0, numerator: 0, antinumerator: 0, exclusions: 0}
aggregate.each {|key, value| aggregate[key] = value.to_i}
result.merge!(aggregate)
# need to time the old way agains the single query to verify that the single query is more performant
# %w(population denominator numerator antinumerator exclusions).each do |measure_group|
# patient_cache.find(query.merge("value.#{measure_group}" => true)) do |cursor|
# result[measure_group] = cursor.count
# end
# end
result.merge!(execution_time: (Time.now.to_i - @parameter_values['start_time'].to_i)) if @parameter_values['start_time']
get_db.collection("query_cache").save(result, safe: true)
result
end
# This method runs the MapReduce job for the measure which will create documents
# in the patient_cache collection. These documents will state the measure groups
# that the record belongs to, such as numerator, etc.
def map_records_into_measure_groups
qm = QualityMeasure.new(@measure_id, @sub_id)
measure = Builder.new(get_db, qm.definition, @parameter_values)
records = get_db.collection('records')
records.map_reduce(measure.map_function, "function(key, values){return values;}",
:out => {:reduce => 'patient_cache'},
:finalize => measure.finalize_function,
:query => {:test_id => @parameter_values['test_id']})
end
# This method runs the MapReduce job for the measure and a specific patient.
# This will create a document in the patient_cache collection. This document
# will state the measure groups that the record belongs to, such as numerator, etc.
def map_record_into_measure_groups(patient_id)
qm = QualityMeasure.new(@measure_id, @sub_id)
measure = Builder.new(get_db, qm.definition, @parameter_values)
records = get_db.collection('records')
records.map_reduce(measure.map_function, "function(key, values){return values;}",
:out => {:reduce => 'patient_cache'},
:finalize => measure.finalize_function,
:query => {:patient_id => patient_id, :test_id => @parameter_values['test_id']})
end
def filter_parameters
results = {}
conditions = []
if(filters = @parameter_values['filters'])
if (filters['providers'] && filters['providers'].size > 0)
providers = filters['providers'].map {|provider_id| BSON::ObjectId(provider_id) if provider_id }
conditions << provider_queries(providers, @parameter_values['effective_date'])
end
if (filters['races'] && filters['races'].size > 0)
conditions << {'value.race.code' => {'$in' => filters['races']}}
end
if (filters['ethnicities'] && filters['ethnicities'].size > 0)
conditions << {'value.ethnicity.code' => {'$in' => filters['ethnicities']}}
end
if (filters['genders'] && filters['genders'].size > 0)
conditions << {'value.gender' => {'$in' => filters['genders']}}
end
end
results.merge!({'$and'=>conditions}) if conditions.length > 0
results
end
def provider_queries(provider_ids, effective_date)
{'$or' => [provider_query(provider_ids, effective_date,effective_date), provider_query(provider_ids, nil,effective_date), provider_query(provider_ids, effective_date,nil)]}
end
def provider_query(provider_ids, start_before, end_after)
{'value.provider_performances' => {'$elemMatch' => {'provider_id' => {'$in' => provider_ids}, 'start_date'=> {'$lt'=>start_before}, 'end_date'=> {'$gt'=>end_after} } }}
end
end
end
end
| true |
44b154603cc1298fae79b395337723e26ba77167 | Ruby | collabnix/dockerlabs | /vendor/bundle/ruby/2.6.0/gems/octokit-4.22.0/lib/octokit/organization.rb | UTF-8 | 408 | 2.609375 | 3 | [
"Apache-2.0",
"MIT"
] | permissive | module Octokit
# GitHub organization class to generate API path urls
class Organization
# Get the api path for an organization
#
# @param org [String, Integer] GitHub organization login or id
# @return [String] Organization Api path
def self.path org
case org
when String
"orgs/#{org}"
when Integer
"organizations/#{org}"
end
end
end
end
| true |
c758a32e0cb73b45816eb1850291f11e4fce27e7 | Ruby | marceltheshell/algorithm_practice | /quicksort.rb | UTF-8 | 529 | 3.359375 | 3 | [] | no_license | def quicksort(arr)
def divide(left, right, arr)
#base case
if right<=left
return
end
#recursive case
pivot = right
wall = left
for curr in left..right-1
if arr[curr] < arr[pivot]
arr[curr], arr[wall] = arr[wall], arr[curr]
wall += 1
end
end
arr[wall], arr[pivot] = arr[pivot], arr[wall]
divide(left, pivot-1, arr)
divide(pivot+1, right, arr)
end
divide(0, arr.length-1, arr)
return arr
end
quicksort([0, 7, 4, 3, 6, 5]) | true |
00bca19555064b8acefb535c24f52a5822766f8d | Ruby | nanokana/first_app | /hello_module.rb | UTF-8 | 429 | 3.6875 | 4 | [] | no_license | # -*- coding: utf-8 -*-
module HelloModule #module文
Version = "1.0" #定義の定義
def hello(name) #メソッドの定義
puts "Hello, #{name}."
end
module_function :hello #helloをモジュール関数として公開する
end
p HelloModule::Version #=> "1.0"
HelloModule.hello("Alice") #=> Hello,Alice.
include HelloModule # インクルードしてみる
p Version #=> "1.0"
hello("Alice") #=> Hello, Alice.
| true |
b0f5237a1860783b413f93d141fa8bdf98f588b1 | Ruby | mdudzinski/sugarcube | /lib/cocoa/sugarcube-nscoder/nscoder.rb | UTF-8 | 1,371 | 3.0625 | 3 | [
"BSD-2-Clause"
] | permissive | # Hash-like access for NSCoder. Converts the `key` argument to a String,
# because Symbols can mess things up.
class NSCoder
def [] key
self.decodeObjectForKey(key.to_s)
end
def []= key, value
self.encodeObject(value, forKey: key.to_s)
end
def key?(key)
self.containsValueForKey(key.to_s)
end
def bool(key)
self.decodeBoolForKey(key.to_s)
end
def double(key)
self.decodeDoubleForKey(key.to_s)
end
def float(key)
self.decodeFloatForKey(key.to_s)
end
def int(key)
self.decodeIntegerForKey(key.to_s)
end
def set(key, toBool: value)
self.encodeBool(value, forKey: key.to_s)
self
end
def set(key, toDouble: value)
self.encodeDouble(value, forKey: key.to_s)
self
end
def set(key, toFloat: value)
self.encodeFloat(value, forKey: key.to_s)
self
end
def set(key, toInt: value)
self.encodeInteger(value, forKey: key.to_s)
self
end
end
class NSCoder
def self.archive(root)
NSKeyedArchiver.archivedDataWithRootObject(root)
end
def self.archive(root, to_file: file)
NSKeyedArchiver.archivedRootObject(root, toFile: file)
end
def self.unarchive(data_or_file)
if data_or_file.is_a?(NSData)
NSKeyedUnarchiver.unarchiveObjectWithData(data_or_file)
else
NSKeyedUnarchiver.unarchiveObjectWithFile(data_or_file)
end
end
end
| true |
d570acfb4130bad9b42593f19713271dba1bfbb9 | Ruby | mdub/wikiwah | /lib/wikiwah/subst.rb | UTF-8 | 995 | 2.8125 | 3 | [] | no_license | #!/usr/bin/env ruby
module WikiWah
# Subst handles text-transformation using a series of regular-expression
# substitutions. It encapsulates a number of "patterns", and associated
# blocks. Each block is invoked with a MatchData object when it's
# associated pattern matches, and is expected to return a replacement
# string.
#
# The difference between using Subst and applying a series of gsub's is
# that replacement values are protected from subsequent transformations.
class Subst
def initialize
@transforms = []
end
def add_transformation(regexp, &proc)
@transforms << [regexp, proc]
end
def transform(s)
s = s.dup
store = []
@transforms.each do |transform|
(regexp, proc) = *transform
s.gsub!(regexp) {
store << proc.call($~)
"\001#{store.size - 1}\002"
}
end
s.gsub!(/\001(\d+)\002/) {
store[$1.to_i]
}
s
end
end
end
| true |
ae0f9aa0661412e8fc0ea0c5fda0f7703dfed71b | Ruby | markmccanna1/Mars-Rover | /spec/grid_spec.rb | UTF-8 | 431 | 2.78125 | 3 | [] | no_license | require 'grid'
describe 'Grid' do
let(:north) { Direction.new("N", 0, 1) }
let(:south) { Direction.new("S", 0, -1) }
let(:grid) { Grid.new( {size: [5, 5], directions: [north, south] } ) }
describe '#size' do
it 'has a size' do
expect( grid.size ).to eq [5, 5]
end
end
describe '#find_direction' do
it 'finds a direction' do
expect(grid.find_direction("N")).to eq north
end
end
end | true |
4b0c2674cff84d7d40e7dcacc0d2a4ca2f1e8d33 | Ruby | reynoldscem/AdventOfCode | /Day03/2.rb | UTF-8 | 793 | 3.390625 | 3 | [] | no_license | #!/usr/bin/ruby
begin
input = File.open(ARGV[0]).read
rescue
puts 'Valid input file from AdventOfCode required as first argument.'
else
robo_turn = false
grid = {}
grid[[0, 0]] = 2
Indices = Struct.new(:row_ind, :col_ind)
santa = Indices.new(0, 0)
robo_santa = Indices.new(0, 0)
input.split('').each do |char|
row_ind, col_ind = (robo_turn ? robo_santa : santa).to_a
case char
when '^'
row_ind += 1
when 'v'
row_ind -= 1
when '>'
col_ind += 1
when '<'
col_ind -= 1
end
grid[[row_ind, col_ind]] ||= 0
grid[[row_ind, col_ind]] += 1
this_santa = robo_turn ? robo_santa : santa
this_santa[:row_ind] = row_ind
this_santa[:col_ind] = col_ind
robo_turn = !robo_turn
end
puts grid.values.length
end
| true |
e6cc0ba93d9adc0d2e2eb0ed0f1d98485dcb6ae0 | Ruby | omotenko/ruby_app | /spec/cart_spec.rb | UTF-8 | 700 | 2.5625 | 3 | [] | no_license | require "rspec"
require_relative "..\\app\\item"
require_relative "..\\app\\antique_item"
require_relative "..\\app\\virtual_item"
require_relative "..\\app\\item_container"
require_relative "..\\app\\cart"
describe Cart do
describe "managing items" do
it "add items into cart" do
cart = Cart.new("Oleg")
item1 = Item.new(name:"kettle",price:200)
item2 = Item.new(name:"car",price:100)
cart.add_items(item1,item2)
cart.items.should include(item1,item2)
end
it "removes items from itself"
end
it "counts items in itself"
it "places order using all the items that were added into the cart"
it "clears itself off the items after an order is placed"
end | true |
7211b787da03ab33f973132c6cc55c87eebf64a0 | Ruby | Matt-Weiss/market_1901 | /lib/market.rb | UTF-8 | 1,203 | 3.59375 | 4 | [] | no_license | class Market
attr_reader :name, :vendors
def initialize(name)
@name = name
@vendors = []
end
def add_vendor(vendor)
@vendors << vendor
end
def vendor_names
vendors.collect do |vendor|
vendor.name
end
end
def vendors_that_sell(item)
vendors.select do |vendor|
vendor.check_stock(item) != 0
end
end
def sorted_item_list
items = []
vendors.each do |vendor|
vendor.inventory.each do |item, quantity|
items << item
end
end
items.uniq.sort
end
def total_inventory
total_inventory = Hash.new {|hash, key| hash[key] = 0}
vendors.each do |vendor|
vendor.inventory.each do |item, quantity|
total_inventory[item] += quantity
end
end
total_inventory
end
def sell(item, quantity)
if total_inventory[item] < quantity
false
else
vendors.each do |vendor|
if vendor.inventory[item] >= quantity
vendor.inventory[item] -= quantity
elsif (vendor.inventory[item] != 0) && (vendor.inventory[item] < quantity)
quantity -= vendor.inventory[item]
vendor.inventory[item] = 0
end
end
end
end
end
| true |
2967622e95e5d416e9755d37a09d4aa9b07e0ed2 | Ruby | MrPowers/battleship | /main.rb | UTF-8 | 1,020 | 3.8125 | 4 | [] | no_license | require_relative "ship.rb"
require_relative "battleship.rb"
require_relative "board.rb"
class Main
def go
board = Board.new
battleship = Battleship.new
ships = []
game_ships = [["Aircraft carrier", 5]]#, ["Battleship", 4], ["Submarine", 3], ["Destroyer", 3], ["Patrol Boat", 2]]
game_ships.each do |ship, size|
puts "Where would you like to put your #{ship} (enter a #{size} element array of positions)"
positions = eval(gets.chomp)
this_ship = Ship.new(ship, size, positions)
ships.push(this_ship)
end
battleship.place_ships_on_board(board, ships)
p board
5.times do
puts "Enter a move"
move = eval(gets.chomp)
battleship.turn(move, ships, board)
battleship.place_ships_on_board(board, ships)
p board
end
end
end
m = Main.new
m.go
# [[1, 1], [1, 2], [1, 3], [1, 4], [1, 5]]
# [["B", 1], ["B", 2], ["B", 3], ["B", 4], ["B", 5]]
# [["C", 1], ["C", 2], ["C", 3], ["C", 4]]
# [["D", 1], ["D", 2], ["D", 3]]
# [["E", 1], ["E", 2], ["E", 3]]
# [["F", 1], ["F", 2]] | true |
e48c690bd635591a5f0d16090cf167b1a8c192c8 | Ruby | jay-menorca/ruby_fundamentals1 | /exercise3.rb | UTF-8 | 321 | 3.734375 | 4 | [] | no_license | #Exercise 3 : Jay Menorca
class FriendlyGuyImpl
@@buddyName = "buddy"
def askName
puts "What's your name?"
@@buddyName = gets.chomp
end
def greetBack
puts "hi there #@@buddyName!"
end
regularGuy = FriendlyGuyImpl.new
# regularGuy = new.FriendlyGuyImpl("buddy")
regularGuy.askName
regularGuy.greetBack
end
| true |
bfa349f34a75b9364448e2b1dc85affc0f20e5c2 | Ruby | andrewarrow/chibrary.com | /spec/service/call_number_service_spec.rb | UTF-8 | 3,326 | 2.640625 | 3 | [] | no_license | require_relative '../rspec'
require_relative '../../service/call_number_service'
module Chibrary
describe CallNumberService do
def spec_cns
CallNumberService.new CNSTestRunIdService.new, CNSTestSequenceIdService.new
end
describe "#next!" do
# only sends queries + commands to self, nothing to test
end
# Only used internally by CNS, but vital:
describe "#version" do
it "doesn't change without someone thinking about this" do
expect(spec_cns.version).to eq(0)
end
end
describe "#consume_sequence_id!" do
it "commands a sequence id" do
sis = double('SequenceIdService')
sis.should_receive(:consume_sequence_id!).and_return(3)
cns = CallNumberService.new CNSTestRunIdService.new, sis
expect(cns.consume_sequence_id!).to eq(3)
end
it "delegates on sequence exhaustion" do
sis = double('SequenceIdService')
cns = CallNumberService.new CNSTestRunIdService.new, sis
sis.should_receive(:consume_sequence_id!).and_raise(SequenceIdExhaustion)
cns.should_receive(:sequence_exhausted!)
sis.should_receive(:consume_sequence_id!)
cns.consume_sequence_id!
end
end
describe "#sequence_exhausted!" do
it "advances run_id and resets sequence_id" do
ris = double('ris')
ris.should_receive(:next!)
sis = double('sis')
sis.should_receive(:reset!)
cns = CallNumberService.new ris, sis
cns.sequence_exhausted!
end
end
describe "#format_ids_to_call" do
it "combines and shuffles ids" do
expect(spec_cns.format_ids_to_call(0, 99, 345)).to eq('2VznWE2i')
end
it 'is always 8 characters, even with 0 bits' do
expect(spec_cns.format_ids_to_call(0, 0, 0)).to eq('00000000')
expect(spec_cns.format_ids_to_call(0, 0, 1)).to eq('00bVJxYW')
end
end
describe "#combine" do
it "creates a string of bits" do
expect(spec_cns.combine(0, 99, 345)).to eq('00000000000000000000000000110001100000101011001')
end
end
describe "#stable_bitstring_shuffle" do
it "shuffles bitstrings stably" do
expect(spec_cns.stable_bitstring_shuffle('00000000000000000000000000110001100000101011001')).to eq('00010000000111100001000000010010000000000010000')
end
it "always shuffles the same way" do
cns = spec_cns
expect(cns.stable_bitstring_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJK')).to eq('3fkq6pn0gFiKGwvy1c7Cxo2aeB5Hdtrzl8I49uAjDJEhmbs')
end
end
describe 'SHUFFLE_TABLE' do
it 'does not change' do
# While this looks like an awful test, it's vital to ensure call number
# generation doesn't change - if it had a different shuffle order to
# bits, it would start generating duplicate CallNumbers.
# As far as I can imagine now, it's straightforward to increase
# CALL_NUMBER_BITS, just make sure the new SHUFFLE_TABLE is the right
# length. Nothing else needs to be changed because a longer call number
# will never dupe a shorter one.
expect(CALL_NUMBER_BITS).to eq(47)
expect(CallNumberService::SHUFFLE_TABLE).to eq([3, 15, 20, 26, 6, 25, 23, 0, 16, 41, 18, 46, 42, 32, 31, 34, 1, 12, 7, 38, 33, 24, 2, 10, 14, 37, 5, 43, 13, 29, 27, 35, 21, 8, 44, 4, 9, 30, 36, 19, 39, 45, 40, 17, 22, 11, 28])
end
end
end
end # Chibrary
| true |
81ade6e6c00c4bfa0dc9063648c1d72a9d64111b | Ruby | Dennis-Kluge/InstantAmbient | /AmbientConnector/lib/AmbientConnector.rb | UTF-8 | 2,571 | 2.6875 | 3 | [] | no_license | require "AmbientConnector/version"
require "java"
require "jar/bluecove-2.1.1.jar"
require "json"
require "socket"
require "optparse"
module AmbientConnector
import "javax.bluetooth.UUID"
import "javax.bluetooth.RemoteDevice"
import "javax.microedition.io.StreamConnectionNotifier"
import "javax.microedition.io.Connector"
import "java.io.BufferedReader"
import "java.io.IOException"
import "java.io.InputStream"
import "java.io.InputStreamReader"
import "java.io.OutputStream"
import "java.io.OutputStreamWriter"
import "java.io.PrintWriter"
class SPPServer
def initialize(options)
puts "Connecting to brain at #{options[:host]} on port #{options[:port]}"
@options = options
end
def start_server
uuid = UUID.new("1101", true)
connection_string = "btspp://localhost:#{uuid};name=AmbientConnector";
loop do
connection_notifier = Connector.open(connection_string)
#start connection
connection = connection_notifier.accept_and_open();
input_stream = connection.open_input_stream
output_stream= connection.open_output_stream();
puts "Connection opened"
# get device info
device = RemoteDevice.get_remote_device(connection)
puts "Remote device address: #{device.get_bluetooth_address()}"
puts "Remote device name: #{device.get_friendly_name(true)}"
buffered_reader = BufferedReader.new(InputStreamReader.new(input_stream))
configuration = buffered_reader.read_line
#send response
print_writer= PrintWriter.new(OutputStreamWriter.new(output_stream))
if handle_configuration(configuration)
print_writer.write("ACCEPT")
else
print_writer.write("ERROR")
end
print_writer.write("ACCEPT")
print_writer.flush
print_writer.close
connection_notifier.close
end
end
def handle_configuration(configuration)
#is configuration valid?
begin
valid_configuration = JSON.parse(configuration)
rescue
return false
end
# add connector information to JSON
valid_configuration[:connector] = "AmbientConnector"
json_configuration = JSON.generate(valid_configuration)
puts json_configuration
send_configuration(json_configuration)
true
end
def send_configuration(configuration)
puts "Sending configuration to brain"
socket = TCPSocket.open(@options[:host], @options[:port])
socket.write(configuration)
socket.flush
socket.close
end
end
end
| true |
00ddfe662359324317ee085eef8935b5fd1f591a | Ruby | hunterbmiller/advent-of-code | /day1/solution.rb | UTF-8 | 461 | 3.5625 | 4 | [] | no_license | def calculate_fuel(mass)
(mass / 3.0).floor - 2
end
def fuel_sum(mass)
fuel = calculate_fuel(mass)
return 0 unless fuel.positive?
fuel + fuel_sum(fuel)
end
def part1(masses)
masses.inject(0) { |sum, mass| sum + calculate_fuel(mass.to_i) }
end
def part2(masses)
masses.inject(0) { |sum, mass| sum + fuel_sum(mass.to_i) }
end
masses = File.read('input.txt').split
puts "Part 1 Solution: #{part1(masses)}"
puts "Part 2 Solution: #{part2(masses)}"
| true |
73dc379cd9f7b96a0b9acad31edfda5fe2503da8 | Ruby | Tricktionary/Shop-GraphQL-API | /app/graphql/resolvers/create_product.rb | UTF-8 | 1,350 | 2.75 | 3 | [] | no_license | class Resolvers::CreateProduct < GraphQL::Function
description "Create a product record in the database\n
ARGUMENTS \n\n
- title(required): An ID that represents the cart we want to add products to \n
- price(required): An ID for the product that you would like to be added to the cart \n
- quantity(required): The number of the product you want to add to your cart \n\n
ERROR IF \n\n
- The cart_id passed in is not valid \n
- The price passed in is less than 0 \n
- The quantity given is less than 0 \n
- The title give is an empty stringn
"
argument :title, !types.String
argument :price, !types.Float
argument :inventory_count, !types.Int
type Types::ProductType
def call(_obj, args, _ctx)
#Validation
if args[:price] >= 0
if args[:inventory_count] > 0
if !args[:title].eql? ""
product = Product.create(title: args[:title], price: args[:price], inventory_count: args[:inventory_count])
product
else
GraphQL::ExecutionError.new("Cannot create a product with an empty string as a title")
end
else
GraphQL::ExecutionError.new("The inventory given must be greater than or equal to 0")
end
else
GraphQL::ExecutionError.new("The price given is not valid must be greater than 0 or equal to 0")
end
end
end | true |
1d3a432470351975a433f4850b9189a7ab025c98 | Ruby | jeffmjwong/Notelist-app | /notes-folder/testing.rb | UTF-8 | 302 | 2.71875 | 3 | [] | no_license | require 'test/unit'
def add_gst(amount)
amount + (amount*0.1) # => pass
end
def add_vat(amount)
amount + (amount*0.1) # => fail
end
class OurTest < Test::Unit::TestCase
def test_add_gst
assert_equal(220, add_gst(200))
end
def test_add_vat
assert_equal(115, add_vat(100))
end
end
| true |
8dbc0f7afc7d92488623a213284561ae9eccfe01 | Ruby | kosmaks/rumouse | /lib/rumouse/x11.rb | UTF-8 | 2,487 | 2.5625 | 3 | [
"MIT"
] | permissive | require 'ffi'
module X11
extend FFI::Library
ffi_lib 'X11'
attach_function :XOpenDisplay, [ :char ], :pointer
attach_function :XWarpPointer, [ :pointer, :ulong, :ulong, :int, :int, :uint, :uint, :int, :int ], :int
attach_function :XFlush, [:pointer], :int
attach_function :XCloseDisplay, [:pointer], :int
attach_function :XDefaultRootWindow, [ :pointer ], :ulong
attach_function :XQueryPointer, [:pointer, :ulong, :pointer, :pointer, :pointer, :pointer, :pointer, :pointer, :pointer], :bool
attach_function :XWidthOfScreen, [:pointer], :int
attach_function :XHeightOfScreen, [:pointer], :int
attach_function :XDefaultScreenOfDisplay, [:pointer], :pointer
end
module Xtst
extend FFI::Library
ffi_lib 'Xtst'
attach_function :XTestFakeButtonEvent, [:pointer, :uint, :bool, :int], :int
end
class RuMouse
def press x, y, button = 1
display = X11.XOpenDisplay(0)
root = X11.XDefaultRootWindow(display)
move x,y
Xtst::XTestFakeButtonEvent(display, button, true, 0)
X11.XFlush(display)
X11.XCloseDisplay(display)
end
def release x, y, button = 1
display = X11.XOpenDisplay(0)
root = X11.XDefaultRootWindow(display)
move x,y
Xtst::XTestFakeButtonEvent(display, button, false, 0)
X11.XFlush(display)
X11.XCloseDisplay(display)
end
def click x, y, button = 1, n = 1
n.times do
press x, y, button
release x, y, button
end
end
def move x, y
display = X11.XOpenDisplay(0)
root = X11.XDefaultRootWindow(display)
X11.XWarpPointer(display, 0, root, 0, 0, 0, 0, x, y)
X11.XFlush(display)
X11.XCloseDisplay(display)
end
def position
display = X11.XOpenDisplay(0)
root = X11.XDefaultRootWindow(display)
win_root_ptr = FFI::MemoryPointer.new :pointer
win_child_ptr = FFI::MemoryPointer.new :pointer
r_x = FFI::MemoryPointer.new :pointer
r_y = FFI::MemoryPointer.new :pointer
win_x = FFI::MemoryPointer.new :pointer
win_y = FFI::MemoryPointer.new :pointer
mark_ptr = FFI::MemoryPointer.new :pointer
X11.XQueryPointer(display, root, win_root_ptr, win_child_ptr, r_x, r_y, win_x, win_y, mark_ptr)
X11.XCloseDisplay(display)
{ x: win_x.read_int32, y: win_y.read_int32 }
end
def screen_size
display = X11.XOpenDisplay(0)
screen = X11.XDefaultScreenOfDisplay(display)
x = X11.XWidthOfScreen(screen)
y = X11.XHeightOfScreen(screen)
X11.XCloseDisplay(display)
{x: x, y: y}
end
end | true |
a68a5b0ef539e43fce6a8dbb763acbfaaf54111c | Ruby | vladiangelov/crawley-volley | /app/models/player.rb | UTF-8 | 721 | 3.09375 | 3 | [] | no_license | # frozen_string_literal: true
# Class for a player
class Player < ApplicationRecord
validates :first_name, presence: true
validates :last_name, presence: true
validates :team, presence: true
validates :position, presence: true
validates :shirt_number, presence: true
def full_name
"#{first_name} #{last_name}"
end
# rubocop:disable Layout/LineLength
def home_page_description
"#{full_name} is part of our #{team == 'Men' ? "men's team" : "ladies' team"}. #{first_name} plays on the #{position.downcase} position, using shirt number #{shirt_number}. If you want to find out more about all the players in the different teams, please click below."
end
# rubocop:enable Layout/LineLength
end
| true |
574657f264b8f4d1592794a132aeb9e3d2f3c690 | Ruby | studentinsights/studentinsights | /app/models/student_voice_completed_survey.rb | UTF-8 | 2,449 | 2.640625 | 3 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | # A survey that a student completed.
class StudentVoiceCompletedSurvey < ApplicationRecord
belongs_to :student
belongs_to :student_voice_survey_upload
validates :student, presence: true
validates :student_voice_survey_upload, presence: true
validates :form_timestamp, presence: true
# added 9/6/2018
def self.columns_for_form_v2
{
form_timestamp: "Timestamp",
first_name: "First name",
student_lasid: "Local ID number", # this line is the diff
proud: "I am proud that I....",
best_qualities: "My best qualities are....",
activities_and_interests: "My activities and interests outside of school are....",
nervous_or_stressed: "I get nervous or stressed in school when....",
learn_best: "I learn best when my teachers...."
}
end
def self.columns_for_form_v1_deprecated
{
form_timestamp: "Timestamp",
first_name: "First name",
student_lasid: "ID number that starts with 111....",
proud: "I am proud that I....",
best_qualities: "My best qualities are....",
activities_and_interests: "My activities and interests outside of school are....",
nervous_or_stressed: "I get nervous or stressed in school when....",
learn_best: "I learn best when my teachers...."
}
end
# Take only the most recent survey from the most recent upload
def self.most_recent_fall_student_voice_survey(student_id)
most_recent_upload = StudentVoiceSurveyUpload
.where(completed: true)
.order(created_at: :desc)
.limit(1)
.first
return nil if most_recent_upload.nil?
most_recent_survey = most_recent_upload.student_voice_completed_surveys
.where(student_id: student_id)
.order(form_timestamp: :desc)
.limit(1)
.first
return nil if most_recent_survey.nil?
most_recent_survey
end
# Flatten into text, for displaying to the user
def flat_text(options = {})
columns = options.fetch(:columns, StudentVoiceCompletedSurvey.columns_for_form_v2)
prompt_keys_to_include = options.fetch(:prompt_keys_to_include, [
:proud,
:best_qualities,
:activities_and_interests,
:nervous_or_stressed,
:learn_best
])
lines = []
prompt_keys_to_include.each do |prompt_key|
prompt_text = columns[prompt_key]
response_text = self[prompt_key]
lines << "#{prompt_text}\n#{response_text}\n"
end
lines.join("\n").strip
end
end
| true |
7b59dfc8988a4f29e319dcea7a2caee4e44194ee | Ruby | roberthead/head_music | /lib/head_music/style/guidelines/avoid_overlapping_voices.rb | UTF-8 | 1,346 | 2.8125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# Module for style guidelines.
module HeadMusic::Style::Guidelines; end
# A counterpoint guideline
class HeadMusic::Style::Guidelines::AvoidOverlappingVoices < HeadMusic::Style::Annotation
MESSAGE = "Avoid overlapping voices. Maintain the high-low relationship between voices even for adjacent notes."
def marks
overlappings
end
private
def overlappings
overlappings_of_lower_voices + overlappings_of_higher_voices
end
def overlappings_of_lower_voices
overlappings_for_voices(lower_voices, :>)
end
def overlappings_of_higher_voices
overlappings_for_voices(higher_voices, :<)
end
def overlappings_for_voices(voices, comparison_operator)
[].tap do |marks|
voices.each do |a_voice|
overlapped_notes = overlappings_with_voice(a_voice, comparison_operator)
marks << HeadMusic::Style::Mark.for_each(overlapped_notes)
end
end.flatten.compact
end
def overlappings_with_voice(other_voice, comparison_operator)
voice.notes.drop(1).select do |note|
preceding_note = other_voice.note_preceding(note.position)
following_note = other_voice.note_following(note.position)
preceding_note&.pitch&.send(comparison_operator, note.pitch) ||
following_note&.pitch&.send(comparison_operator, note.pitch)
end
end
end
| true |
567f4946ef1fe72c8798e4451b17dcc3c1ac3011 | Ruby | georges-2000/pyramide | /pyramide.rb | UTF-8 | 397 | 3.609375 | 4 | [] | no_license | puts 'Bon donc tu veux construire une pyramide ? de combien d\'étages ?'
print '> '
nbFloor = gets.chomp.to_i
if nbFloor.to_i <= 1
puts "C'est pas une pyramide ça !"
if 1.is_a? Integer
puts "Et fait on te demande le nombre d\'étages"
end
else
nbFloor.downto(1) do |suite|
(suite - 1).times do
print ' '
end
(nbFloor - suite + 1).times do
print '#'
end
puts ''
end
end | true |
ad3f5940a5496f2a4ae89f9322fee104b7cb089b | Ruby | Geek24/ruby_practice | /strings.rb | UTF-8 | 1,298 | 4.15625 | 4 | [] | no_license | full_name = "Chris Edwards"
first_name = "Chris"
last_name = "Edwards"
puts "#{full_name}"
# How many vowels?
puts "Vowels: " + full_name.count("aeiou").to_s
puts "Consonants: " + full_name.count("^aeiou").to_s
puts full_name.start_with?("Edwards")
puts "Index: " + full_name.index("Edwards").to_s
# Does it equal?
puts "#{first_name} == #{last_name}: " + ("#{first_name}" == "#{last_name}").to_s
puts first_name.equal?first_name
# Strip white space
full_name = " " + full_name
full_name = full_name.lstrip # strip white space to the left
full_name = full_name.rstrip # strip white space to the right
full_name = full_name.strip # strip all white space
# Formatting
puts full_name.rjust(20, '.')
puts full_name.ljust(20, '.')
puts full_name.center(20, '.')
puts full_name.chop
puts full_name.chomp('ds')
puts full_name.delete('a') #deletes every occurance of
# Make an array from string
name_array = full_name.split(//) #split every new character
puts name_array
name_array = full_name.split(/ /)
puts name_array
# Escape sequences
# \\ Backslash
# \' Single-quote
# \" Double-quote
# \a Bell
# \b Backspace
# \f Formfeed
# \n Newline
# \r Carriage
# \t Tab
# \v Vertical tab
# ALSO:
# printf "%s for string, %d for integer, %f for float. Just like in C\n", max.name, max.bark()
| true |
0bbb523e5ee508b046aff5ef40934a5052be697c | Ruby | niquepa/crackingcode | /Others/mergeSort.rb | UTF-8 | 919 | 4.0625 | 4 | [] | no_license |
def merge(left, right)
# puts "merge: left:#{left} right:#{right}"
arr = []
while(left.length > 0 && right.length > 0)
if left[0] < right[0]
arr.push(left.shift)
else
arr.push(right.shift)
end
end
# puts "****** arr: #{arr} left:#{left} right:#{right}"
arr.concat(left) if left.length > 0
arr.concat(right) if right.length > 0
# puts "****** arr: #{arr}"
return arr
end
def mergeSort(arrayToSort)
# puts "---- arrayToSort:#{arrayToSort}"
return arrayToSort if arrayToSort.length < 2
middle = (arrayToSort.length / 2).floor
left = arrayToSort.slice(0,middle)
right = arrayToSort.slice(middle,arrayToSort.length-1)
# puts "mergeSort: middle:#{middle} left:#{left} right:#{right}"
merge(mergeSort(left), mergeSort(right))
end
array = [10, 15, 2, 5, 17, 9, 14, 11, 6, 19, 4, 20, 1, 18, 3, 7, 13, 8, 12, 16]
puts mergeSort(array.slice(0,array.length-1)).inspect | true |
382b5d838b200c75998ae6ac98434d86d4cd5d7c | Ruby | jgendrano/blackjack | /spec/lib/blackjack_spec.rb | UTF-8 | 3,868 | 3.640625 | 4 | [] | no_license | require "pry"
require_relative '../../lib/blackjack'
require_relative '../../lib/deck'
require_relative '../../lib/card'
require_relative '../../lib/hand'
describe Deck do
let(:deck) { Deck.new }
describe "#build_deck" do
it "builds a deck of 52 cards" do
expect(deck.cards.size).to eq 52
end
end
it "creates unique cards" do
expect(deck.cards.uniq.size).to eq 52
end
it "shuffles deck aftering being built" do
expect(deck.cards.shuffle).to_not eq deck.cards
end
describe "#deal" do
it "takes a card out of the deck array and returns it" do
expect(deck.cards.pop.class).to eq(Card)
expect(deck.cards.uniq.size).to eq 51
end
end
end
describe Card do
let(:card) { Card.new("3", "♠") }
let(:card_1) { Card.new("K", "♦") }
let(:card_2) { Card.new("Q", "♣") }
let(:card_3) { Card.new("J", "♠") }
let(:card_4) { Card.new("A", "♥") }
describe "#new" do
it "is an instance of the Card class" do
expect(card.class).to eq(Card)
end
end
describe "#initialize" do
it "shows the rank and suit of the card" do
expect(card.rank).to eq("3")
expect(card.suit).to eq("♠")
expect(card_1.rank).to eq("K")
expect(card_1.suit).to eq("♦")
end
end
describe "#is_ace?" do
it "checks to see if a card is an ace" do
expect(card.is_ace?).to eq false
expect(card_1.is_ace?).to eq false
expect(card_2.is_ace?).to eq false
expect(card_3.is_ace?).to eq false
expect(card_4.is_ace?).to eq true
end
end
describe "#is_face?" do
it "checks to see if a card is a face card" do
expect(card.is_face?).to eq false
expect(card_1.is_face?).to eq true
expect(card_2.is_face?).to eq true
expect(card_3.is_face?).to eq true
expect(card_4.is_face?).to eq false
end
end
end
describe Hand do
let(:hand_initialize) { Hand.new }
let(:hand) { Hand.new(:card) }
let(:scoringHand) { Hand.new(Card.new("A", "♥")) }
let(:opponentHand) { Hand.new(Card.new("K", "♥")) }
describe "#new" do
it "is an instance of the Hand class" do
expect(hand_initialize.class).to eq(Hand)
end
end
describe "#initialize" do
it "checks to see if the initialize method creates an empty array" do
expect(hand_initialize.current_hand).to eq []
end
end
describe "#add_card" do
it "adds a card to the hand" do
expect(hand_initialize.add_card(:card_1)).to eq [:card_1]
expect(hand_initialize.add_card(:card_2)).to eq [ :card_1, :card_2]
end
end
describe "#score" do
it "tests the score of a blackjack hand" do
scoringHand.add_card(Card.new("A", "♥"))
expect(scoringHand.score).to eq 11
scoringHand.add_card(Card.new("5", "♠"))
expect(scoringHand.score).to eq 16
scoringHand.add_card(Card.new("J", "♠"))
expect(scoringHand.score).to_not eq 26
expect(scoringHand.score).to eq 16
scoringHand.add_card(Card.new("A", "♥"))
expect(scoringHand.score).to_not eq 37
expect(scoringHand.score).to_not eq 27
expect(scoringHand.score).to eq 17
end
end
describe "#compare_score" do
it "tests to see if the Dealer & Player tie" do
expect(scoringHand.compare_score(scoringHand)).to eq "Dealer and Player tie"
end
it "tests to see if Player wins" do
scoringHand.add_card(Card.new("J", "♠"))
opponentHand.add_card(Card.new("8", "♥"))
expect(scoringHand.compare_score(opponentHand)).to eq "Player wins"
end
it "tests to see if Dealer wins" do
scoringHand.add_card(Card.new("7", "♠"))
opponentHand.add_card(Card.new("9", "♥"))
expect(scoringHand.compare_score(opponentHand)).to eq "Dealer wins"
end
end
# describe blackjack do
# it "creates a new deck of cards" do
#
# end
end
| true |
a4fe32b8aeb712f1ab9735541535822c5fce29f1 | Ruby | steviepinero/Homework | /votersim.rb | UTF-8 | 1,271 | 3.109375 | 3 | [] | no_license | require './Voter.rb'
require './candidate.rb'
require './Vmenu.rb'
def choice
attr_accessor :choice
choice = gets.chomp
end
def test_voter
name = "Ashlynn"
politics = "Independant"
v = Voter.new(name, politics)
raise "Wrong name" unless v.name == name
raise "Wrong politics" unless v.politics == politics
v
end
voter = test_voter
def test_candidate(voter)
name = "Bill"
party = "Republican"
c = Candidate.new(name, party)
raise "wrong name" unless c.name == name
raise "Wrong party" unless c.party == party
# c.convinced?(voter)
end
def test_campaign
campaign = Campaign.new voters, candidates
winner = campaign.run
puts winner.name winner.party
end
test_candidate(voter)
voters = [
Voter.new("Vinnie", "Progressive"),
Voter.new("Eric", "Libertarian"),
Voter.new("Aaron", "Conservative"),
Voter.new("Ashlynn", "Independant"),
Voter.new("Dylan", "Democrat"),
]
candidates = [
Candidate.new("Billy", "Republican"),
Candidate.new("Karla", "Democrat"),
Candidate.new("Carol", "Republican"),
Candidate.new("Gerry", "Republican"),
Candidate.new("Kevin", "Republican"),
]
# voters += candidates
#
# candidates.each do |c|
# c.votes = c.stump(voters)
#
# end
# winner = #The Candidate with the most votes
| true |
a97f4f10c55eca023d77f0ae594c7b3a076d9e23 | Ruby | tpluss/bri1-ex2 | /main.rb | UTF-8 | 6,310 | 2.734375 | 3 | [] | no_license | #coding: utf-8
require 'csv'
require 'digest'
require 'mechanize'
# Парсер каталога продукции сайта http://piknikvdom.ru
# Записывает заданное количество товаров в файл и подсчитывает статистику.
# Если все загруженные товары находятся в одной категории - добирает столько же.
#
# Разделителем CSV-файла является знак \t.
# Формат каталога:
# Раздел | Подраздел | Наименование | Адрес карточки | Адрес картинки | Хэш
class PiknikParser
MAIN_URL = 'http://www.piknikvdom.ru'
PRODUCTS_URL = MAIN_URL + '/products'
SECTBLOCK_SEL = 'div.section'
SECTLINK_SEL = 'span.h3 > a.category-image'
SUBSECT_SEL = 'p.categories-wrap > span > a'
GOODSCARD_SEL = 'a.product-image'
NEXTPAGE_SEL = 'a.pager-next'
GOODSIMG_SEL = 'div.prettyphoto'
CSV_SEP = "\t"
CAT_PATH = './catalog.txt'
IMG_PATH = './img'
def initialize(path=nil, sep=nil, img_dir=nil)
@path ||= CAT_PATH
@sep ||= CSV_SEP
@img_dir ||= IMG_PATH
Dir.mkdir(@img_dir) unless Dir.exists?(@img_dir)
@catalog_file = CSV.open(@path, 'a+', {:col_sep => @sep})
# Чтобы не дёргать каждый раз файл, создадим массив хэшей, который будет
# индикатором наличия объекта в каталоге.
@saved = @catalog_file.readlines.collect{|r| r[5]}
@goods_qnt = 1000
@parsed = 0
self.parse
self.stat
end
def parse
@mechanize = Mechanize.new
@mechanize.user_agent_alias = 'Windows Chrome'
img_saver = Mechanize.new # Отдельный инстанс нужен: segafult в nokogiri.so
catalog_page = @mechanize.get(PRODUCTS_URL)
catalog_page.search(SECTBLOCK_SEL).each do |sect_block|
sect_title = sect_block.at(SECTLINK_SEL).attributes['title'].to_s
puts "Works on #{ sect_title }"
sect_block.search(SUBSECT_SEL).each do |subsect_url|
subsect_title = subsect_url.text
puts " Parse #{ subsect_title }"
subsect_goods = self.get_subsect_goods(subsect_url.attributes['href'])
subsect_goods.each do |goods|
return if @parsed == @goods_qnt
href = goods.attributes['href'].to_s
name = goods.at('img').attributes['alt'].to_s
hash = Digest::SHA256.hexdigest(sect_title + subsect_title + name)
next if @saved.index(hash)
unless goods.attributes['style'].to_s.index('no_photo')
goods_card = img_saver.get(MAIN_URL + goods.attributes['href'])
img_url = goods_card.at(GOODSIMG_SEL).attributes['href'].to_s
img_path = "#{ @img_dir }/#{ hash }#{ File.extname(img_url) }"
img_saver.get(MAIN_URL + img_url).save(img_path)
end
@catalog_file << [sect_title, subsect_title, name, href, img_url, hash]
puts " #{ name }"
@parsed += 1
@saved.push(hash)
end
end
end
end
# Собирает все ссылки на товары по категории
# ??? Такой подход не очень нравится, так как придётся обойти все страницы
# раздела, а потом считать хэш: товары в каталоге могут дублироваться.
def get_subsect_goods(subsect_href)
subsect_page = @mechanize.get(subsect_href)
res = subsect_page.search(GOODSCARD_SEL)
next_link = subsect_page.at(NEXTPAGE_SEL)
if next_link
href = next_link.attributes['href']
#puts " Next page #{ MAIN_URL + href }"
res += self.get_subsect_goods(MAIN_URL + href)
end
res
end
def get_row_by_hash(hash)
return [] unless @saved.index(hash)
@catalog_file.pos = 0
@catalog_file.readlines.select{|r| r[5] == hash}[0]
end
def stat
puts "Catalog contains #{ @saved.size } goods."
return if @saved.size.zero?
# Буфер к этому моменту не всегда записан в файл: пишем вручную
@catalog_file.flush
# Смещаем каретку на начало, чтобы не открывать заново
@catalog_file.pos = 0
data = @catalog_file.readlines
catalog = Hash[data.collect{|r| [r[0], {:qnt => 0}]}]
data.each do |r|
catalog[r[0]][r[1]] = [] unless catalog[r[0]][r[1]]
catalog[r[0]][r[1]].push(r.drop(2))
catalog[r[0]][:qnt] += 1
end
catalog.each do |cat, cat_data|
puts "#{ cat }: #{ cat_data.delete(:qnt) }"
cat_data.each do |subcat, subcat_data|
puts " #{ subcat }: #{ subcat_data.size }"
end
end
img_list = Dir.glob(@img_dir + '/*.{jpg,jpeg,gif,png}') # с запасом
return if img_list.empty?
puts "#{ img_list.count } of #{ @saved.size } "\
"(#{ 100 * img_list.count / @saved.size }%) goods have image."
img_size_list = img_list.map{|path| File.size(path)}
img_file_info = Proc.new {|size|
f_name = File.basename(img_list[img_size_list.index(size)])
file = {
:size => size,
:hash => f_name.split('.')[0],
:name => f_name,
:goods => self.get_row_by_hash(f_name.split('.')[0])[2]
}
}
min_f = img_file_info.call(img_size_list.min)
max_f = img_file_info.call(img_size_list.max)
average = img_size_list.inject{|sum, el| sum += el}
to_kb = Proc.new {|size| '%.2fKB.' %(size.to_f/1024)}
puts "Average: #{ to_kb.call(average.to_f/img_list.count) }"
puts "Min file #{ min_f[:name] } for #{ min_f[:goods] }: "\
"#{ to_kb.call(min_f[:size]) }"
puts "Max file #{ max_f[:name] } for #{ max_f[:goods] }: "\
"#{ to_kb.call(max_f[:size]) }"
if catalog.values.size == 1 && catalog.values[0].values.size == 1
puts "All goods from one subcategory. Restart!"
@parsed = 0
self.parse
end
end
end
cp = PiknikParser.new | true |
c479f4b2519d0eb45c8630d34304fbd4ec986131 | Ruby | demileee/methods_reinf | /exercise.rb | UTF-8 | 100 | 3.09375 | 3 | [] | no_license | def word_counter(string)
count = string.split
puts count.count
end
word_counter("hi whats up")
| true |
305b92ea687c15458cf6384061e1a574e3be8145 | Ruby | jturello/clockangle_rspec | /spec/clockangle_spec.rb | UTF-8 | 1,012 | 3.984375 | 4 | [] | no_license | require('rspec')
require('clock_angle')
# require("pry")
describe('String#clock_angle') do
it('is equal to 0.0 degrees when time equals 12:00') do
expect("12:00".clock_angle()).to(eq(0.0))
end
it('is equal to 180.0 degrees when time equals 6:00') do
expect("6:00".clock_angle()).to(eq(180.0))
end
it('is equal to 82.5 degrees when time equals 12:15') do
expect("12:15".clock_angle()).to(eq(82.5))
end
it('is equal to 165.0 degrees when time equals 12:15') do
expect("12:30".clock_angle()).to(eq(165.0))
end
end
# time/60
# write a method that tells us, given a certain time, the distance between the minute and hour hands on an analog clock. For example, 12 o'clock would return 0º and 6 o'clock would return 180º.
#
# Always return the smaller distance and be as precise as possible. Make sure to think about the object class of the input - all form inputs from params are strings. In order to convert a String to a Float, you need to use the String#to_f() method.
| true |
0ec1b256ee8c199551c9093302ff53b59654b182 | Ruby | zenhacks/manzuo-site | /source/why-us-en.html.rb | UTF-8 | 2,496 | 2.59375 | 3 | [] | no_license | ---
title: Manzuoapp - Why Us
---
<header class="page-header">
<h1 class="page-title">7 Reasons You'll Love ManZuo in Your Restaurant</h1>
</header>
<section id="why-us">
<% markdown_filter do %>
## No need to use expensive and antiquated pagers
Your host uses an iPad™ to run the ManZuo App. This inexpensive, easy-to-use, touch-screen tablet replaces the old pager base station, and customer cell phones replace clunky pagers.
## Increased chance your guests will accept a long wait
With text message notification, tell your guest to "Wait where you want". Guests are more likely to accept a long wait if they are given more freedom to explore the local neighborhood while waiting. Cell phones have a limitless range whereas restaurant pagers keep patrons on-site.
## No crowded entrance or waiting area
Guests walk around more with text notification. This means they will wait outside, in your bar, at the bookstore across the street, etc... A congestion-free entrance is easier to navigate and, no longer seeing a long wait line, passers-by are more likely to approach the host stand.
## No looking for patrons or shouting out names
With ManZuo and text notification, guests return to your host stand, not the other way around. In large restaurants, noisy places, or just with a crowd of patrons that refuse to pay attention to your host, text notification recalls guests to be seated.
## Unlike restaurant buzzers, ManZuo automatically starts a mobile dialogue with your guests
Give your guests further instructions, such as to stop going shopping, or to text back if plans have changed.
Get your guests talking about food and drink before they go shopping or are seated, and drive more sales in your restaurant.
## Keep all hosts and managers updated about wait list and available tables, anywhere
Everyone can use FullSeats together. Use any iPad™, iPhone™ or iPod™ with the FullSeats App, and all devices sync. A manager on the floor can assign a table to a waiting party. The front host automatically sees where the waiting party will go. In busy restaurants, the host focuses on recording parties while another notifies guests. Even check on your restaurant when you are not there.
## Thank guests and automatically build a text marketing list
After dining, patrons receive an automated thank-you text. Patrons are invited to opt-in to your text-followers list to receive future text marketing campaigns and help you drive more business.
<% end %>
</section>
| true |
b92677268a367e7efbf398c893cef5740f86d08c | Ruby | escowles/testdrive | /demo0.rb | UTF-8 | 680 | 2.53125 | 3 | [] | no_license | require 'active_fedora'
require 'launchy'
class TestObject < ActiveFedora::Base
property :title, predicate: ::RDF::DC11.title
property :creator, predicate: ::RDF::DC11.creator
contains 'ds1'
end
# create an object and set a property and datastream content
obj = TestObject.new( title: ["Oh, the Places You'll Go!"], creator: ["Dr. Seuss"] )
obj.ds1.content = "Congratulations! Today is your day. You're off to Great Places! You're off and away!"
obj.ds1.original_name = 'oh the places youll go.txt'
obj.save
puts "#{ActiveFedora.fedora.host}#{ActiveFedora.fedora.base_path}/#{obj.id}"
Launchy.open( "#{ActiveFedora.fedora.host}#{ActiveFedora.fedora.base_path}/#{obj.id}")
| true |
c199a0b66173d19ad310f3c04d2900f2b65a3ada | Ruby | sfaiferek/ttt-with-ai-project-v-000 | /lib/game.rb | UTF-8 | 1,493 | 3.890625 | 4 | [] | no_license | class Game
WIN_COMBINATIONS = [
[0,1,2], # Top row
[3,4,5], # Middle row
[6,7,8], # Bottom row
[0,3,6], # Left col
[1,4,7], # Middle col
[2,5,8], # Right col
[0,4,8], # Diag Right
[2,4,6] # Diag Left
]
attr_accessor :board, :player_1, :player_2
def initialize(player_1 = Players::Human.new("X"), player_2 = Players::Human.new("O"), board = Board.new)
@player_1 = player_1
@player_2 = player_2
@board = board
end
def current_player
if @board.turn_count % 2 == 0
return @player_1
else
return @player_2
end
end
def won?
WIN_COMBINATIONS.detect do |combo|
combo.all? { |i| board.cells[i] == 'X' } || combo.all? { |i| board.cells[i] == 'O' }
end
end
def draw?
if !won? && board.full?
return true
else
return false
end
end
def over?
won? || draw?
end
def winner
if WIN_COMBINATIONS.detect do |combo|
combo.all? { |i| board.cells[i] == 'X' }
end
return "X"
elsif WIN_COMBINATIONS.detect do |combo|
combo.all? { |i| board.cells[i] == 'O' }
end
return "O"
else
nil
end
end
def turn
move = current_player.move(board)
if board.valid_move?(move)
board.update(move, current_player)
else
puts "try again"
turn
end
end
def play
while !over?
turn
end
puts "Congratulations #{winner}!" if won?
puts "Cat's Game!" if draw?
winner
end
end
| true |
510c23968c33d8a430b73ea74b3dd36a181b429b | Ruby | killinit/cms | /bin/migrate_files.rb | UTF-8 | 1,437 | 2.640625 | 3 | [
"MIT"
] | permissive | require 'bundler/setup'
require 'optparse'
require 'base64'
require 'ostruct'
require 'nokogiri'
require 'hippo_xml_parser'
require 'fog'
require 'pry'
require_relative '../lib/hippo_file_parser'
require_relative '../lib/rackspace_cdn'
options = OpenStruct.new
OptionParser.new do |opts|
opts.on('--file [XML FILE]', 'Pass the Hippo xml asset file') do |filename|
file = File.expand_path(filename)
if File.exist? file
options.file = File.read(file)
else
puts "File #{file} does not exist. :S"
end
end
opts.on('-u [RACKSPACE USERNAME]', '--username', 'Pass the rackspace username') do |username|
options.username = username
end
opts.on('-k [RACKSPACE API KEY]', '--key', 'Pass the rackspace key') do |key|
options.key = key
end
opts.on('-b [RACKSPACE BUCKET NAME]', '--bucket', 'Pass the rackspace bucket name') do |bucket|
options.bucket = bucket
end
opts.on('-h', '--help', 'Show this message') do
puts opts
exit
end
end.parse!
if !options.file.nil? && options.username && options.key && options.bucket
files = HippoFileParser.parse(options.file)
puts "Uploading #{files.size} files."
rackspace = RackSpaceCDN.new(options)
rackspace.upload(files)
puts 'Done.'
puts
puts 'Files in the bucket:'
rackspace.list_files
else
puts 'Usage:'
puts 'ruby bin/migrate_files -u rackspace_username -k rackspace_key -b bucket_name -f hippo_file.xml'
end
| true |
8576ba0e6a89a7f4f0b66e3967435c83065ccbb3 | Ruby | JayZonday/module-one-final-project-guidelines-nyc-web-031218 | /lib/Command_Line_Interface.rb | UTF-8 | 18,240 | 3.53125 | 4 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | #|||||||||||BOROUGH METHODS||||||||||||||||
require 'colorize'
require 'date'
def get_borough(name)
Location.all.select do |loc|
loc.name.downcase == name.downcase
end
end
def num_of_crimes(name)
get_borough(name).length
end
def most_dangerous_borough
count = {}
bor = Location.all.map {|loc| loc.name}.uniq
bor.each do |bor|
count[bor] = num_of_crimes(bor)
end
cust_border2
x = count.max_by{|k,v| v}
puts "The most dangerous borough in NYC is currently #{x[0].capitalize}, with a crime total of #{x[1]}".colorize(:white)
cust_border2
end
def least_dangerous_borough
count = {}
bor = Location.all.map {|loc| loc.name}.uniq
bor.each do |bor|
count[bor] = num_of_crimes(bor)
end
cust_border2
x = count.min_by{|k,v| v}
puts "The safest borough in NYC is currently #{x[0].capitalize}, with a crime total of #{x[1]}".colorize(:white)
cust_border2
end
def type_of_crimes_borough(name)
typ = Hash.new(0)
get_borough(name).each do |loc|
loc.crimes.each do |cr|
typ[cr.offense] += 1
end
end
header_border
puts "These are the frequent crime types in your borough:".colorize(:white)
header_border
spacer
spacer
header_border
typ.each do |k,v|
if k
puts ("#{k}:".capitalize.colorize(:yellow)) + (" #{v}".colorize(:white))
header_border
end
end
spacer
spacer
end
def freq_crime_spots(name)
typ = Hash.new(0)
get_borough(name).each do |loc|
typ[loc.scene_of_crime] +=1
end
header_border
puts "These are the frequent crime spots in your borough:".colorize(:white)
header_border
spacer
spacer
header_border
typ.each do |k,v|
if k
puts ("#{k}:".capitalize.colorize(:yellow)) + (" #{v}".colorize(:white))
header_border
end
end
spacer
spacer
end
def freq_crime_level(name)
typ = Hash.new(0)
get_borough(name).each do |loc|
loc.crimes.each do |cr|
typ[cr.severity] += 1
end
end
header_border
puts "These are the crime level frequencies in your borough:".colorize(:white)
header_border
spacer
spacer
header_border
typ.each do |k,v|
puts ("#{k}:".capitalize.colorize(:yellow)) + " #{v}"
header_border
end
spacer
spacer
end
def freq_crime_type_by_month(name, month)
arr = grab_months
typ = arr.each_with_object({}){|month, hash| hash[month] = Hash.new(0)}
get_borough(name).each do |loc|
loc.crimes.each do |cr|
num = cr.date_of_crime.split("-")[1]
month = convert_num_to_month(num.to_i)
typ[month][cr.offense] += 1
end
end
header_border
puts "These are the crime type rates by month in your borough:".colorize(:white)
header_border
typ
end
def print_crime_by_months(name, month)
if name
typ = freq_crime_type_by_month(name, month)
else
typ = nyc_crime_freq_by_month
end
month_hash = typ.select{|k,v| k.downcase == month.downcase}
month_hash.each do |k,v|
equals_border
puts k.colorize(:white)
equals_border
v.each do |k,v|
puts "#{k.capitalize.colorize(:yellow)}: #{v}" if k
dash
end
end
header_border
puts "Type another month. Otherwise, type anything else to exit.".colorize(:white)
header_border
month = gets.chomp
if name
print_crime_by_months(name, month) if month_valid?(month)
else
print_crime_by_months(name = nil, month) if month_valid?(month)
end
end
def grab_months
arr = Crime.all.map do |cr|
cr.date_of_crime.split("-")[1].to_i
end.uniq.sort
arr.map do |m|
convert_num_to_month(m)
end
end
#||||||||||||||||||CityWide Methods |||||||||||||||||||||||||||||
def nyc_crime_level
typ = Hash.new(0)
Crime.all.map do |c|
typ[c.severity] += 1
end
header_border
puts "These are the crime level frequencies in NYC:".colorize(:white)
header_border
spacer
spacer
typ.each do |k,v|
if k
puts "#{k}:".capitalize.colorize(:yellow)
puts "#{v}"
header_border
end
end
spacer
spacer
end
def nyc_freq_crime_spots
typ = Hash.new(0)
Location.all.map do |loc|
typ[loc.scene_of_crime] += 1
end
header_border
puts "These are the crime hot-spots in NYC:".colorize(:white)
header_border
spacer
spacer
header_border
typ.each do |k,v|
if k
puts ("#{k}:".capitalize.colorize(:yellow)) + " #{v}"
header_border
end
end
spacer
spacer
end
def nyc_freq_crime_type
typ = Hash.new(0)
Crime.all.map do |c|
typ[c.offense] += 1
end
header_border
puts "These are the frequent types of crimes committed in NYC:".colorize(:white)
header_border
spacer
spacer
header_border
typ.each do |k,v|
if k
puts ("#{k}:".capitalize.colorize(:yellow)) + " #{v}"
header_border
end
end
spacer
spacer
end
def nyc_crime_freq_by_month
arr = grab_months
typ = arr.each_with_object({}){|month, hash| hash[month] = Hash.new(0)}
Location.all.each do |loc|
loc.crimes.each do |cr|
num = cr.date_of_crime.split("-")[1]
month = convert_num_to_month(num.to_i)
typ[month][cr.offense] += 1
end
end
header_border
puts "These are the crime type rates by month in NYC:".colorize(:white)
header_border
spacer
spacer
typ
end
#|||||||||||| CLI-FORMAT/DESIGN methods|||||||||||||||||||||||||||
def dash
puts "------------------------------------"
end
def equals_border
puts "======================================"
end
def sub_dash
puts "--------------------"
end
def header_border
puts "==========================================================="
end
def cust_border
puts "=================================================================="
end
def cust_border2
puts "==================================================================================="
end
def title_border
puts "++++-------^v^--^v^v^-^v^--------------^v^v^----------^v^--^v^v^-^v^---------++++"
end
def spacer
puts " "
end
def creater_border
puts "<><><><><><><><><><><><><><><><><><><><><><>><><>"
end
#|||||||||||||||HELPER/CHECKER METHODS||||||||||||||||||
def borough_input_valid?(input)
(1..5).include?(input.to_i)
end
def borough_name_valid?(name)
name.downcase == "brooklyn" || name.downcase == "manhattan" || name.downcase == "queens" || name.downcase == "staten island" || name.downcase == "bronx"
end
def city_input_valid?(input)
(1..6).include?(input.to_i)
end
def month_valid?(input)
grab_months.include?(input.capitalize)
end
def convert_num_to_month(num)
Date::MONTHNAMES[num]
end
#||||||||||||||MAIN APP METHODS||||||||||||||||||||||
def greet
spacer
puts "
++++----------^v^--^v^v^-^v^-----------^v^v^v^----------^v^--^v^v^-^v^-------------++++
| _ _ _______ ___ _______ _______ __ __ _______ |
| | | _ | || || | | _|| || |_| || | |
| | || || || ___|| | | | | _ || || ___| |
| | || |___ | | | | | | | || || |___ |
| | || ___|| |___ | | | |_| || || ___| |
| | _ || |___ | || |_ | || ||_|| || |___ |
| |__| |__||_______||_______||_______||_______||_| |_||_______| |
| _______ _______ |
| | || | |
| |_ _|| _ | |
| | | | | | | |
| | | | |_| | |
| | | | | |
| |___| |_______| |
| _ |
| _| |_ |
| |_ + _| |
| |_| |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~| _ |
| _| |_ |
| |_ + _| |
| |_| |
| __ _ __ __ ________ |
| | | | || | | || __| |
| | |_| || |_| || | |
| | || || | |
| | _ ||_ _|| | |
| | | | | | | | |__ |
| |_| |__| |___| |________| |
| |
| _______ _______ _______ _______ _______ __ __ __ _ _______ _______ |
| | || _ || || || || | | | | | | || || | |
| | _____|| |_| || ___|| ___||_ _|| |_| | | |_| || ___||_ _| |
| | |_____ | || |___ | |___ | | | | | || |___ | | |
| |_____ || || ___|| ___| | | |_ _| | _ || ___| | | |
| _____| || _ || | | |___ | | | | | | | || |___ | | |
| |_______||__| |__||___| |_______| |___| |___| |_| |__||_______| |___| |
| |
| ++++--------^v^--^v^v^-^v^-----------^v^v^v^----------^v^--^v^v^-^v^-------------++++|
"
spacer
spacer
end
def main_menu
puts "
__ __ _______ ___ __ _ __ __ _______ __ _ __ __
| |_| | _ | | | | | | |_| | | | | | | | |
| | |_| | | |_| |____| | ___| |_| | | | |
| | | | |____| | |___| | |_| |
| | | | _ | | | ___| _ | |
| ||_|| | _ | | | | | | ||_|| | |___| | | | |
|_| |_|__| |__|___|_| |__| |_| |_|_______|_| |__|_______|"
spacer
message = [
"What would you like to do?:".colorize(:yellow),
"1 : Check Criminal Activity by Borough".colorize(:white),
"2 : Check Criminal Activity by City-Wide".colorize(:white),
"3 : Exit".colorize(:white)
]
header_border
puts message
header_border
puts "Please enter one of the numbered commands:"
dash
menu_input
end
def menu_input
input = gets.chomp
case input
when "1"
sub_menu_boroughs
when "2"
sub_menu_city
when "3"
exit_menu
else
puts "Please enter one of the valid commands: #{input} is NOT a command!"
menu_input
end
end
def exit_menu
spacer
cust_border
puts "
_______ _______ _______ __ __ __ __ _______ ______ _______ _______ _______ ______
| | | _ | | | | | | | | | || _ | | | |
| _____|_ _| |_| | |_| | | | | | _ | _ | |_| |_ _| ___| _ |
| |_____ | | | | | | |_| | |_| | | | | | | | | |___| | | |
|_____ | | | | |_ _| | | ___| |_| | | | | | ___| |_| |___
_____| | | | | _ | | | | | | | | _ | | | | |___| |_ |
|_______| |___| |__| |__| |___| |_______|___| |______||__| |__| |___| |_______|______| | |
_______ _______ _______ __ __ _______ _______ _______ _______ ____ \/
| || || _ || | | | | || _ || || | | |
| _____||_ _|| |_| || |_| | | _____|| |_| || ___|| ___| | |
| |_____ | | | || | | |_____ | || |___ | |___ | |
|_____ | | | | ||_ _| |_____ || || ___|| ___| |____|
_____| | | | | _ | | | _____| || _ || | | |___ ____
|_______| |___| |__| |__| |___| |_______||__| |__||___| |_______| |____|"
spacer
spacer
cust_border
puts "We thank you for your visit, we hope you found this".colorize(:white)
puts "information useful today & most importantly; Stay Safe Out There!!".colorize(:white)
cust_border
creater_border
puts "-From your creators of NYC SafeNet: Helen & Joe".colorize(:yellow)
creater_border
end
#|||||BOROUGH MENUS|||||
def sub_menu_boroughs
message = [
"_______ _______ ______ _______ __ __ _______ __ __ __ __ _______ __ _ __ __
| _ || || _ | | || | | || || | | | | |_| || || | | || | | |
| |_| || _ || | || | _ || | | || ___|| |_| | ____ | || ___|| |_| || | | |
| || | | || |_||_ | | | || |_| || | __ | ||____|| || |___ | || |_| |
| _ | | |_| || __ || |_| || || || || | | || ___|| _ || |
| |_| || || | | || || || |_| || _ | | ||_|| || |___ | | | || |
|_______||_______||___| |_||_______||_______||_______||__| |__| |_| |_||_______||_| |__||_______|",
spacer,
"What would you like to do?:".colorize(:yellow),
"1 : View number of crimes".colorize(:white),
"2 : View the breakdown of crime types".colorize(:white),
"3 : View the hot-spot crime areas".colorize(:white),
"4 : View the breakdown in severity of crimes".colorize(:white),
"5 : View the monthly breakdown of types of crimes".colorize(:white),
"6 : Exit Sub-Menu".colorize(:white),
]
puts message
puts "Please enter one of the numbered commands:"
dash
input = gets.chomp
sub_dash
if input == "6"
main_menu
elsif !borough_input_valid?(input)
puts "Please enter one of the valid commands: #{input} is NOT a command!"
sub_menu_boroughs
else
menu_input_borough(input)
end
end
def menu_input_borough(input)
header_border
puts "Please name the borough:"
header_border
name = gets.chomp
dash
spacer
spacer
if !borough_name_valid?(name)
puts "Please enter a valid borough name."
menu_input_borough(input)
else
case input
when "1"
spacer
spacer
x = num_of_crimes(name)
cust_border
puts "#{name.capitalize} has a crime total of #{x}.".colorize(:yellow)
cust_border
when "2"
spacer
spacer
type_of_crimes_borough(name)
when "3"
spacer
spacer
freq_crime_spots(name)
when "4"
spacer
spacer
freq_crime_level(name)
when "5"
spacer
spacer
message = [dash,
"Type in the month you want to view:".colorize(:yellow),
dash
]
puts message
month = gets.chomp
if month_valid?(month)
print_crime_by_months(name, month)
else
puts "That is not a valid month."
end
when "6"
spacer
main_menu
end
spacer
sub_menu_boroughs
end
end
#|||||CITY-WIDE MENUS|||||
def sub_menu_city
message = ["
_______ ___ _______ __ __ _ _ ___ ______ _______ __ __ _______ __ _ __ __
| | | | | | | | | _ | | | || | | |_| | | | | | | | |
| _| |_ _| |_| |____| || || | | _ | ___| | | ___| |_| | | | |
| | | | | | | |____| | | | | | |___ | | |___| | |_| |
| | | | | | |_ _| | | | |_| | ___| | | ___| _ | |
| |_| | | | | | | _ | | | |___ | ||_|| | |___| | | | |
|_______|___| |___| |___| |__| |__|___|______||_______| |_| |_|_______|_| |__|_______|",
spacer,
"What would you like to do?:".colorize(:yellow),
"1 : View breakdown of crime types".colorize(:white),
"2 : View hot-spot crime areas".colorize(:white),
"3 : View breakdown in severity of crimes".colorize(:white),
"4 : View monthly breakdown of types of crimes".colorize(:white),
"5 : Current Most Dangerous Borough".colorize(:white),
"6 : Current Safest Borough".colorize(:white),
"7 : Exit Sub-Menu".colorize(:white)]
puts message
header_border
puts "Please enter one of the numbered commands:"
dash
menu_input_city
end
def menu_input_city
input = gets.chomp
if input == "7"
main_menu
elsif !city_input_valid?(input)
puts "Please enter one of the valid commands: #{input} is NOT a command!"
menu_input_city
else
case input
when "1"
spacer
nyc_freq_crime_type
when "2"
spacer
nyc_freq_crime_spots
when "3"
spacer
spacer
nyc_crime_level
when "4"
spacer
spacer
message = [dash,
"Type in the month you want to view:".colorize(:yellow),
dash
]
puts message
month = gets.chomp
if month_valid?(month)
print_crime_by_months(name = nil, month)
else
puts "That is not a valid month."
end
when "5"
spacer
spacer
most_dangerous_borough
when "6"
spacer
spacer
least_dangerous_borough
when "7"
spacer
main_menu
end
spacer
sub_menu_city
end
end
#|||||||||||||RUNS THE ENTIRE APP IN CONSOLE with "ruby ./bin/run.rb" ||||||||||||||||||||||
def runner
greet
main_menu
end
| true |
58c15c56c63f41a462d9be7e42941689933187b5 | Ruby | sneako/ruby-erlang-etf | /lib/erlang/etf/bit_binary.rb | UTF-8 | 1,901 | 2.859375 | 3 | [
"MIT"
] | permissive | module Erlang
module ETF
#
# | 1 | 4 | 1 | Len |
# | --- | --- | ---- | ---- |
# | 77 | Len | Bits | Data |
#
# This term represents a bitstring whose length in bits is not a
# multiple of 8 (created using the bit syntax in R12B and later).
# The `Len` field is an unsigned 4 byte integer (big endian).
# The `Bits` field is the number of bits that are used in the last
# byte in the data field, counting from the most significant bit
# towards the least significant.
#
# (see [`BIT_BINARY_EXT`])
#
# [`BIT_BINARY_EXT`]: http://erlang.org/doc/apps/erts/erl_ext_dist.html#BIT_BINARY_EXT
#
class BitBinary
include Erlang::ETF::Term
UINT8 = Erlang::ETF::Term::UINT8
UINT32BE = Erlang::ETF::Term::UINT32BE
HEAD = (UINT32BE + UINT8).freeze
class << self
def [](term)
term = Erlang.from(term) if not term.kind_of?(Erlang::Bitstring)
return new(term)
end
def erlang_load(buffer)
size, bits, = buffer.read(5).unpack(HEAD)
data = buffer.read(size)
if size > 0
data.setbyte(-1, data.getbyte(-1) >> (8 - bits))
end
return new(Erlang::Bitstring[data, bits: bits])
end
end
def initialize(term)
raise ArgumentError, "term must be of type Erlang::Bitstring" if not term.kind_of?(Erlang::Bitstring) and not term.kind_of?(Erlang::Binary)
@term = term
end
def erlang_dump(buffer = ::String.new.force_encoding(BINARY_ENCODING))
buffer << BIT_BINARY_EXT
buffer << [@term.bytesize, @term.bits].pack(HEAD)
buffer << Erlang::ETF::Term.binary_encoding(@term.data)
if @term.bytesize > 0
buffer.setbyte(-1, buffer.getbyte(-1) << (8 - @term.bits))
end
return buffer
end
end
end
end
| true |
d44f3dc199ccec473ef7c56d277105dd8ddc122a | Ruby | gooch/RDialogy | /lib/rdialogy/form.rb | UTF-8 | 1,958 | 3.03125 | 3 | [
"MIT"
] | permissive | require File.dirname(__FILE__) + '/base'
require File.dirname(__FILE__) + '/form_field'
module RDialogy
class Form < Base
# Valid options are:
# * :text - Title of the widget
# * :width
# * :height
# * :form_height - Number of items to display in the list
# * :items - Array of FormField
#
# Returns <b>Hash</b>
#
# From the man page
#
# The form dialog displays a form consisting of labels and fields, which are positioned on a scrollable window
# by coordinates given in the script. The field length flen and input-length ilen tell how long the
# field can be. The former defines the length shown for a selected field, while the latter defines the per‐
# missible length of the data entered in the field.
#
# - If flen is zero, the corresponding field cannot be altered. and the contents of the field determine the
# displayed-length.
#
# - If flen is negative, the corresponding field cannot be altered, and the negated value of flen is used as
# the displayed-length.
#
# - If ilen is zero, it is set to flen.
#
# Use up/down arrows (or control/N, control/P) to move between fields. Use tab to move between windows.
def self.run(options={})
keys = options[:items].map(&:label_text)
super options, true do |input|
result = Hash.new
input.split("\n").each do |item|
result[keys.shift] = item
end
result
end
end
private
def self.args(options={})
options[:items] ||= []
options[:form_height] ||= options[:items].count
options[:items].map! do |item|
[
:label_text, :label_x, :label_y,
:item_text, :item_x, :item_y,
:label_length, :item_length
].map do |m|
item.send(m)
end
end
super + [options[:form_height]] + options[:items].flatten
end
# Maps to the appropriate dialog argument
def self.command
'form'
end
end
end
| true |
720ace8cd9155f70ec80ba9a748a47d6dd402b50 | Ruby | tsathishkumar/NQueens-in-Ruby | /n_queens.rb | UTF-8 | 1,595 | 3.734375 | 4 | [] | no_license | class NQueens
def initialize
@count=0
end
def find_n_queens(board,col)
already_visited = board.select{|cell| board[col][cell] == "X"}.keys[0]
if !already_visited.nil?
board[col][already_visited] = "-"
end
possible = possible_position(board,col)
if possible > 0
board[col][possible] = "X"
if col + 1 <= 8
find_n_queens(board,col + 1)
else
@count=@count+1
board.values.each{|c| puts c.values.join(' ')}
puts
[1,2,3,4,5,6,7,8].each{|row| board[col][row]="."}
find_n_queens(board,col - 1)
end
elsif col-1 > 0
[1,2,3,4,5,6,7,8].each{|row| board[col][row]="."}
find_n_queens(board,col - 1)
end
@count
end
def possible_position(board,col)
queens_in_prev_cols = board.entries.select{|entry| entry[1].values.include? "X"}.map{|entry| [entry[0],entry[1].select{|cell| entry[1][cell] == "X"}.keys[0]]}
free_positions = board[col].select{|cell| board[col][cell] != "-"}.map{|free|[col,free[0]]}
if free_positions.nil? or free_positions.empty?
return 0
end
if queens_in_prev_cols.empty?
return free_positions[0][1]
else
possible_pos = free_positions.select{|n| queens_in_prev_cols.select{|l| (l[0]-n[0] == 0 or l[1]-n[1]==0 or ((l[0]-n[0]).abs==(l[1]-n[1]).abs))}.empty?}
end
if possible_pos.empty?
return 0
else
return possible_pos[0][1]
end
end
end
a = {}
[1,2,3,4,5,6,7,8].each{|c| a[c] = {1=>".", 2=>".", 3=>".", 4=>".", 5=>".", 6=>".", 7=>".", 8=>"."}}
puts NQueens.new.find_n_queens(a,1)
| true |
f9c0a20635e63fed6c1f5bf0b7baeee6178de75d | Ruby | jeanetterosario88/triangle-classification-onl01-seng-pt-032320 | /lib/triangle.rb | UTF-8 | 984 | 3.28125 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | class Triangle
attr_accessor :sideone, :sidetwo, :sidethree
def initialize(sideone, sidetwo, sidethree)
@sideone = sideone
@sidetwo = sidetwo
@sidethree = sidethree
end
def kind
if sideone + sidetwo > sidethree && sideone + sidethree > sidetwo && sidetwo + sidethree > sideone && sideone > 0 && sidetwo > 0 && sidethree > 0
return :equilateral if sideone == sidetwo && sidetwo == sidethree
return :isosceles if sideone == sidetwo && sidetwo != sidethree || sidetwo == sidethree && sideone != sidethree || sideone == sidethree && sidetwo != sidethree
return :scalene if sideone != sidetwo && sidetwo != sidethree && sidethree != sideone
else
begin
raise TriangleError
end
end
end
class TriangleError < StandardError
def message
"this shape is not a Triangle!"
end
end
end
| true |
4aa2aa50c3abf9dcb5d173c42a1ea161bbf64ad1 | Ruby | DanielLChang/AppAcademy | /w2/w2d2/chess/pieces/piece.rb | UTF-8 | 519 | 3.484375 | 3 | [] | no_license | require 'colorize'
class Piece
attr_accessor :color, :board, :pos
def initialize(color, board, pos)
@color = color
@board = board
@pos = pos
end
def to_s
symbol
end
def empty?()
@color.nil?
end
def dup_board
@board.dup
end
def valid_moves
all_moves = self.moves
all_moves.reject { |move| move_into_check?(move) }
end
def move_into_check?(end_pos)
new_board = @board.dup
new_board.move_piece(pos, end_pos)
new_board.in_check?(@color)
end
end
| true |
10db66c50ee0c352ae870c0fd69dc7849d518a00 | Ruby | adamahrens/RailsRecipes | /test/models/chef_test.rb | UTF-8 | 1,756 | 2.6875 | 3 | [] | no_license | # == Schema Information
#
# Table name: chefs
#
# id :integer not null, primary key
# name :string
# email :string
# created_at :datetime not null
# updated_at :datetime not null
# password_digest :string
# admin :boolean default(FALSE)
#
require 'test_helper'
class ChefTest < ActiveSupport::TestCase
def setup
@chef = Chef.new(name: 'Leroy Jenkins', email: 'leroy.jenkins@apps.com', password: 'password1234', password_confirmation: 'password1234')
end
test 'chef password should be present' do
@chef.password = ' '
@chef.password_confirmation = ' '
assert_not @chef.valid?
end
test 'chef password should meet minimum of five' do
pass = '!' * 4
@chef.password = pass
@chef.password_confirmation = pass
assert_not @chef.valid?
end
test 'chef name should be present' do
assert @chef.valid?
@chef.name = ''
assert_not @chef.valid?
@chef.name = ' '
assert_not @chef.valid?
end
test 'chef email should be present' do
assert @chef.valid?
@chef.email = ''
assert_not @chef.valid?
@chef.email = ' '
assert_not @chef.valid?
end
test 'chef name should be less than 31 characters' do
@chef.name = 'a' * 31
assert_not @chef.valid?
@chef.name = 'a' * 30
assert @chef.valid?
end
test 'chef email should be correct format' do
assert @chef.valid?
@chef.email = 'adfasdf'
assert_not @chef.valid?
@chef.email = 'asdfasd.asdfas.@dsfsdfsdfds.ccccssd@'
assert_not @chef.valid?
end
test 'chef email should be unique' do
other_chef = Chef.new(name: 'Duplicate Jenkins', email: 'leroy.jenkins@apps.com')
@chef.save
assert_not other_chef.valid?
end
end
| true |
d1a4a1c31baec92ccb9b4ac017525d17ab47a61b | Ruby | Tobiuo1022/Learning | /cherry/lib/tempo.rb | UTF-8 | 306 | 3.03125 | 3 | [] | no_license | class Tempo
include Comparable
attr_reader :bpm
def initialize(bpm)
@bpm = bpm
end
def <=>(other)
if other.is_a?(Tempo)
@bpm <=> other.bpm
else
nil
end
end
# override
def inspect()
"#{@bpm}bpm"
end
end
| true |
d24f56bee69233de8cc6f57c3fbfc1045c41785b | Ruby | tobiaszwalczak/Todo-CLI | /lib/todo/show.rb | UTF-8 | 384 | 2.703125 | 3 | [
"MIT"
] | permissive | #encoding:utf-8
def show
error(:nofile) unless File.exist?("TODO")
puts Rainbow("\n Your TODO list:").blue.bright()+" (#{Dir.pwd}/TODO)\n\n"
File.read("TODO").each_line do |line|
if line[0,1] == "#"
line.sub!("#", "")
line.sub!("\n", "")
puts " » "+ Rainbow(line +" ✔").green.bright
else
puts " » "+ line
end
end
puts "\n"
end | true |
8e260eea1bf6eb7409332997e6f39c23a402acd7 | Ruby | meghanstovall/open_mic_1911 | /lib/open_mic.rb | UTF-8 | 454 | 3.359375 | 3 | [] | no_license | class OpenMic
attr_reader :location, :date, :performers
def initialize(attributes)
@location = attributes[:location]
@date = attributes[:date]
@performers = []
end
def welcome(user)
@performers << user
end
def repeated_jokes?
jokes1 = @performers[0].jokes
jokes2 = @performers[1].jokes
if jokes1.include?(jokes2[0]) || jokes1.include?(jokes2[1])
return true
else
return false
end
end
end
| true |
c5c13c2cfeed14f91088cd2c6debfe7f7154bda6 | Ruby | fredemmott/sidewalk | /lib/sidewalk/uri_match.rb | UTF-8 | 829 | 2.609375 | 3 | [
"ISC"
] | permissive | module Sidewalk
# Information on a +URI+ +=>+ {Controller} match.
#
# These are generated by {UriMapper}.
class UriMatch
# The URL path, divided into regexp-matches.
#
# The URI map is a tree; this tells you what was matched at each level
# of the tree.
attr_reader :parts
# Any named captures from the match.
attr_reader :parameters
# What the URL maps to.
#
# This should be an instance of {Controller}, or a +Proc+.
attr_reader :controller
def initialize parts = [], parameters = {}, controller = nil
unless parts.is_a?(Array) && parameters.is_a?(Hash)
raise ArgumentError.new(
'Sidewalk::UriMatch([parts], {parameters}, controller)'
)
end
@parts, @parameters, @controller = parts, parameters, controller
end
end
end
| true |
2da8aeaf58d6dd9efd7c8691b85dabbe990d499a | Ruby | jason20194/save-terminus | /save_terminus.rb | UTF-8 | 2,361 | 3.640625 | 4 | [] | no_license | # frozen_string_literal: true
# gems
require 'tty-prompt'
require 'tty-font'
require 'pry'
require 'colorize'
# requiring files
require_relative 'stage1'
require_relative 'stage2'
require_relative 'stage3'
require_relative 'final_boss'
require_relative 'gameover'
require_relative 'winner'
def main_menu(prompt, health)
health = 100
font = TTY::Font.new(:standard)
puts `clear`
puts font.write('SAVE TERMINUS').yellow
main_menu_option = prompt.select('Choose an option?', %w[Play About Quit])
while main_menu_option != 'Quit'
if main_menu_option == 'Play'
puts `clear`
puts 'Hello and welcome. To begin, please enter your name'
print '> '
user_name = gets.chomp
while user_name == ""
puts "Sorry I did not get your name. Please try again"
print '> '
user_name = gets.chomp
end
puts `clear`
puts "Hello #{user_name}. Welcome to the world of Terminus, where you must save the world from ending by defeating the evil king Ganondorf, who has reversed time on this world. Survive through the story and Ganondorfs minions and you will be able to reach him. Defeat the evil king in order to save your world. Decision making is crucial in this game, as choosing the wrong decisions can lead to health loss, and may even cause death. You will start off with 100 health. Once your health reaches 0 it is game over. So plan every move very carefully! Please press enter to continue"
health = StageOne.run(health)
return over if health == 0
health = StageTwo.run(health)
return over if health == 0
health = StageThree.run(health)
return over if health == 0
health = FinalBoss.run(health)
if health == 0
over
else
winner
end
main_menu_option = prompt.select('Choose an option?', %w[Play About Quit])
elsif main_menu_option == 'About'
puts 'Ganondorf has put a curse on the world Terminus where time is reversed. To prevent the worlds destruction you must defeat Ganondorf in order to reverse the time back to normal. Make decisions every stage and survive all 3 stages to reach the final stage where you will fight Ganondorf to decide the fate of Terminus.'
# loop back to main menu
main_menu_option = prompt.select('Choose an option?', %w[Play About Quit])
end
end
end
| true |
aa15a123c4d82bbc0b24efd92ba11a8e9e75eae1 | Ruby | johnrails/ruby_stuff | /hash.rb | UTF-8 | 390 | 3.5625 | 4 | [] | no_license | # make a ruby hash respond to . notation
# example person = {name: "John", age:"37}
# person.name # "John"
#
# source http://www.goodercode.com/wp/convert-your-hash-keys-to-object-properties-in-ruby/
class ::Hash
def method_missing(name)
return self[name] if key? name
self.each { |k,v| return v if k.to_s.to_sym == name }
super.method_missing name
end
end
| true |
493be35f6cab618259829b9f7ed2c017a0ff647d | Ruby | zmitton/boggle | /app/helpers/boggle_classes.rb | UTF-8 | 9,431 | 3.078125 | 3 | [] | no_license | class BoggleBoard
attr_accessor :grid, :found_words, :r_index, :c_index, :score
def initialize (string = "4")
@board_string = string
@found_words = []
@covered_ground = []
@score = 0
build_board(string)
end
def build_board(string)
if string.length == 16
@grid = [
[Die.new("aeegmu", 0, 0, string[0]) ,Die.new("aegmnn", 0, 1, string[1]) ,Die.new("afirsy", 0, 2, string[2]) ,Die.new("bjkqxz", 0, 3, string[3]) ],
[Die.new("ceiilt", 1, 0, string[4]) ,Die.new("aaeeee", 1, 1, string[5]) ,Die.new("ceipst", 1, 2, string[6]) ,Die.new("adennn", 1, 3, string[7]) ],
[Die.new("dhlnor", 2, 0, string[8]) ,Die.new("dhlnor", 2, 1, string[9]) ,Die.new("eiiitt", 2, 2, string[10]) ,Die.new("emottt", 2, 3, string[11]) ],
[Die.new("fiprsy", 3, 0, string[12]) ,Die.new("gorrvw", 3, 1, string[13]) ,Die.new("iprrry", 3, 2, string[14]) ,Die.new("nootuw", 3, 3, string[15]) ]
]
elsif string.length == 25
@grid = [
[Die.new("aeegmu", 0, 0, string[0]), Die.new("aegmnn", 0, 1, string[1]), Die.new("afirsy", 0, 2, string[2]), Die.new("bjkqxz", 0, 3, string[3]), Die.new("ccenst", 0, 4, string[4])],
[Die.new("ceiilt", 1, 0, string[5]), Die.new("aaeeee", 1, 1, string[6]), Die.new("ceipst", 1, 2, string[7]), Die.new("adennn", 1, 3, string[8]), Die.new("dhhlor", 1, 4, string[9])],
[Die.new("dhlnor", 2, 0, string[10]), Die.new("dhlnor", 2, 1, string[11]), Die.new("eiiitt", 2, 2, string[12]), Die.new("emottt", 2, 3, string[13]), Die.new("ensssu", 2, 4, string[14])],
[Die.new("fiprsy", 3, 0, string[15]), Die.new("gorrvw", 3, 1, string[16]), Die.new("iprrry", 3, 2, string[17]), Die.new("nootuw", 3, 3, string[18]), Die.new("ooottu", 3, 4, string[19])],
[Die.new("aaafrs", 4, 0, string[20]), Die.new("ceilpt", 4, 1, string[21]), Die.new("aafirs", 4, 2, string[22]), Die.new("ddhnot", 4, 3, string[23]), Die.new("aeeeem", 4, 4, string[24])]
]
elsif string == 5
@grid = [
[Die.new("aeegmu", 0, 0), Die.new("aegmnn", 0, 1), Die.new("afirsy", 0, 2), Die.new("bjkqxz", 0, 3), Die.new("ccenst", 0, 4)],
[Die.new("ceiilt", 1, 0), Die.new("aaeeee", 1, 1), Die.new("ceipst", 1, 2), Die.new("adennn", 1, 3), Die.new("dhhlor", 1, 4)],
[Die.new("dhlnor", 2, 0), Die.new("dhlnor", 2, 1), Die.new("eiiitt", 2, 2), Die.new("emottt", 2, 3), Die.new("ensssu", 2, 4)],
[Die.new("fiprsy", 3, 0), Die.new("gorrvw", 3, 1), Die.new("iprrry", 3, 2), Die.new("nootuw", 3, 3), Die.new("ooottu", 3, 4)],
[Die.new("aaafrs", 4, 0), Die.new("ceilpt", 4, 1), Die.new("aafirs", 4, 2), Die.new("ddhnot", 4, 3), Die.new("aeeeem", 4, 4)]
]
else
@grid = [
[Die.new("aeegmu", 0, 0) ,Die.new("aegmnn", 0, 1) ,Die.new("afirsy", 0, 2) ,Die.new("bjkqxz", 0, 3) ],
[Die.new("ceiilt", 1, 0) ,Die.new("aaeeee", 1, 1) ,Die.new("ceipst", 1, 2) ,Die.new("adennn", 1, 3) ],
[Die.new("dhlnor", 2, 0) ,Die.new("dhlnor", 2, 1) ,Die.new("eiiitt", 2, 2) ,Die.new("emottt", 2, 3) ],
[Die.new("fiprsy", 3, 0) ,Die.new("gorrvw", 3, 1) ,Die.new("iprrry", 3, 2) ,Die.new("nootuw", 3, 3) ]
]
end
end
def take_turn
roll
evaluate_board
end
def total_score
@score = @found_words.uniq.inject(0) do |sum, word|
case
when word.length == 3 || word.length == 4
points = 1
when word.length == 5
points = 2
when word.length == 6
points = 3
when word.length == 7
points = 5
when word.length > 7
points = 11
else
points = 0
end
points + sum
end
@score
end
def to_s
output_string = ""
@grid.each do |row|
row.each do |die|
output_string << die.top
end
output_string << "\n"
end
output_string
end
def to_html
output_string = ""
@grid.each do |row|
row.each do |die|
output_string << die.top
end
output_string << "</br>"
end
output_string
end
def to_flat_s
output_string = ""
@grid.each do |row|
row.each do |die|
output_string << die.top
end
end
output_string
end
def roll
@grid.shuffle!
@grid.each_with_index do |row, r_index|
row.shuffle!
row.each_with_index do |die, c_index|
die.roll(r_index, c_index)
end
end
@board_string = ""
loop_board { |die| @board_string << die.top}
end
def loop_board
@grid.each do |row|
row.each do |die|
yield die
end
end
end
def evaluate_board
loop_board do |die|
@c_index = die.c_index
@r_index = die.r_index
@score = 0
@current_word = die.top
@covered_ground = ["#{@r_index}#{@c_index}"]
find_words
end
total_score
@found_words.sort!.uniq!
end
def find_words #recursive
return nil if !binary_is_word_path? || ($end_time && Time.now > $end_time)
@found_words << @current_word if binary_is_valid_word? && !@found_words.include?(@current_word)
#Traverse in each direction, and recurse
n
ne
e
se
s
sw
w
nw
end
#Uses database of Terms
# def is_valid_word?
# if Term.where(word: "#{@current_word}").length != 0 && @current_word.length > 2
# puts "WORD: #{@current_word}"
# return true
# end
# false
# end
# def is_word_path?
# Term.where("word LIKE (?)", "#{@current_word}%").length != 0
# end
#database free version
def binary_is_valid_word?
return false if @current_word.length < 3
@current_word.downcase
low_i = 0
i = $terms.length / 2
high_i = $terms.length - 1
while low_i <= high_i
i = (high_i + low_i)/2
if $terms[i].downcase == @current_word
# puts "i:#{i}, low_i:#{low_i}, high_i:#{high_i}, #{$terms[i]}"
return true
elsif @current_word < $terms[i].downcase
high_i = i - 1
elsif @current_word > $terms[i].downcase
low_i = i + 1
end
end
return false
end
def binary_is_word_path?
@current_word.downcase
low_i = 0
i = $terms.length / 2
high_i = $terms.length - 1
while low_i <= high_i
i = (high_i + low_i)/2
if $terms[i][0..@current_word.length - 1].downcase == @current_word
# puts "i:#{i}, low_i:#{low_i}, high_i:#{high_i}, #{$terms[i][0..@current_word.length - 1]}"
return true
elsif @current_word < $terms[i].downcase
high_i = i - 1
elsif @current_word > $terms[i].downcase
low_i = i + 1
end
end
# puts "i:#{i}, low_i:#{low_i}, high_i:#{high_i}, #{$terms[i][0..@current_word.length - 1]}"
return false
end
def n
return nil if @r_index == 0 || @covered_ground.include?("#{@r_index - 1}#{@c_index}")
@r_index -= 1
@covered_ground << "#{@r_index}#{@c_index}"
@current_word += "#{@grid[@r_index][@c_index].top}"
find_words
@r_index += 1
@covered_ground.pop
@current_word = @current_word[0...-1]
end
def ne
return nil if @r_index == 0 || @c_index + 1 >= @grid.length|| @covered_ground.include?("#{@r_index - 1}#{@c_index + 1}")
@r_index -= 1
@c_index += 1
@covered_ground << "#{@r_index}#{@c_index}"
@current_word += "#{@grid[@r_index][@c_index].top}"
find_words
@r_index += 1
@c_index -= 1
@covered_ground.pop
@current_word = @current_word[0...-1]
end
def e
return nil if @c_index + 1 >= @grid.length || @covered_ground.include?("#{@r_index}#{@c_index + 1}")
@c_index += 1
@covered_ground << "#{@r_index}#{@c_index}"
@current_word += "#{@grid[@r_index][@c_index].top}"
find_words
@c_index -= 1
@covered_ground.pop
@current_word = @current_word[0...-1]
end
def se
return nil if @r_index + 1 >= @grid.length || @c_index + 1 >= @grid.length || @covered_ground.include?("#{@r_index + 1}#{@c_index + 1}")
@r_index += 1
@c_index += 1
@covered_ground << "#{@r_index}#{@c_index}"
@current_word += "#{@grid[@r_index][@c_index].top}"
find_words
@r_index -= 1
@c_index -= 1
@covered_ground.pop
@current_word = @current_word[0...-1]
end
def s
return nil if @r_index + 1 >= @grid.length || @covered_ground.include?("#{@r_index + 1}#{@c_index}")
@r_index += 1
@covered_ground << "#{@r_index}#{@c_index}"
@current_word += "#{@grid[@r_index][@c_index].top}"
find_words
@r_index -= 1
@covered_ground.pop
@current_word = @current_word[0...-1]
end
def sw
return nil if @r_index + 1 >= @grid.length || @c_index == 0 || @covered_ground.include?("#{@r_index + 1}#{@c_index - 1}")
@r_index += 1
@c_index -= 1
@covered_ground << "#{@r_index}#{@c_index}"
@current_word += "#{@grid[@r_index][@c_index].top}"
find_words
@r_index -= 1
@c_index += 1
@covered_ground.pop
@current_word = @current_word[0...-1]
end
def w
return nil if @c_index == 0 || @covered_ground.include?("#{@r_index}#{@c_index - 1}")
@c_index -= 1
@covered_ground << "#{@r_index}#{@c_index}"
@current_word += "#{@grid[@r_index][@c_index].top}"
find_words
@c_index += 1
@covered_ground.pop
@current_word = @current_word[0...-1]
end
def nw
return nil if @c_index == 0 || @r_index == 0 || @covered_ground.include?("#{@r_index - 1}#{@c_index - 1}")
@r_index -= 1
@c_index -= 1
@covered_ground << "#{@r_index}#{@c_index}"
@current_word += "#{@grid[@r_index][@c_index].top}"
find_words
@r_index += 1
@c_index += 1
@covered_ground.pop
@current_word = @current_word[0...-1]
end
end
class Die
attr_accessor :top, :r_index, :c_index
def initialize (sides, r_index, c_index, top = nil)
@sides = sides.chars
@top = top ? top : @sides[0]
set_position(r_index, c_index)
end
def roll(r_index, c_index)
@top = @sides.sample
set_position(r_index, c_index)
end
def set_position(r_index, c_index)
@r_index = r_index
@c_index = c_index
self
end
end | true |
2471db557b0bc54c6726302d940c406d2d4b7860 | Ruby | johanesteves/sinatra-mvc-lab-v-000 | /models/piglatinizer.rb | UTF-8 | 554 | 3.859375 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class PigLatinizer
def to_pig_latin(sentence)
split_sentence = sentence.split(" ")
split_sentence.collect {|word| self.piglatinize(word)}.join(" ")
end
def piglatinize(text)
vowels = ["A","E", "I", "O", "U", "a", "e", "i", "o", "u"]
first_letter = text[0]
if vowels.include?(first_letter)
result_text = text + "way"
else
split_text = text.split("")
vowel_index = split_text.index {|letter| vowels.include?(letter) }
result_text = split_text.rotate(vowel_index).join("") + "ay"
end
end
end
| true |
af44c420053184b099ec87d9ae15aa231b393579 | Ruby | petacube/xml2db | /phase2/type_clustering/data_profile_miner.rb | UTF-8 | 5,454 | 3.15625 | 3 | [] | no_license | # Mines features about the data within a specific column. Generates
# output intended to be used in order to cluster attributes with
# similar data profiles
class DataProfileMiner
# Base functionality shared among all profilers
class BaseProfiler
def self.applicable?(obj)
raise NotImplemented
end
def process(obj)
# By default this is a no-op
end
def results
raise NotImplemented
end
end
# A profiler designed for attributes that are strings
class StringProfiler < BaseProfiler
def initialize
@lengths = Hash.new(0) # maps length -> # of times seen
@n_numerical = 0 # count of numerical characters ever seen
@n_whitespace = 0 # count of amount of whitespace seen
@n_punctuation = 0
end
def self.applicable?(obj)
obj.is_a?(String)
end
def process(str)
@lengths[str.length] += 1
@n_numerical += str.count("0-9")
@n_whitespace += str.count(" ")
@n_punctuation += str.count("!.\"',?")
end
def results
results = AttributeProfile.new
results.length_min = @lengths.keys.min
results.length_max = @lengths.keys.max
results.length_mean = lengths_mean
results.num_ratio = @n_numerical.to_f / lengths_sum
results.punc_ratio = @n_punctuation.to_f / lengths_sum
results.white_ratio = @n_whitespace.to_f / lengths_sum
results.length_var = lengths_var
results.klass = String
results
end
private
def lengths_mean
lengths_sum.to_f / n_lengths
end
def lengths_sum
sum = 0
@lengths.each do |length, freq|
sum += freq * length
end
sum
end
def n_lengths
@lengths.values.inject(:+)
end
def lengths_var
m = lengths_mean
sum = 0
@lengths.each do |length, freq|
sum += freq * (length - m)**2
end
sum.to_f / (n_lengths - 1)
end
end
# A profiler for numeric types. Right now it just records the class,
# but may be extended to more complex operations in the future
class NumericProfiler < BaseProfiler
def initialize
@klass = nil
end
def self.applicable?(obj)
obj.is_a? Numeric
end
def process(obj)
# Handle case where klass is known
if @klass
if !(obj.class <= @klass)
raise "Multiple classes seen within a single column"
else
return
end
end
# Infer klass from object -- use only one Integer type
if obj.is_a?(Integer)
@klass = Integer
else
@klass = obj.class
end
end
def results
results = AttributeProfile.new
results.klass = @klass
results
end
end
# Profiles boolean objects -- really just records their class
class BooleanProfiler < BaseProfiler
PSUEDO_CLASS = "boolean"
def self.applicable?(obj)
obj.is_a?(TrueClass) || obj.is_a?(FalseClass)
end
def results
results = AttributeProfile.new
results.klass = PSUEDO_CLASS
results
end
end
# Profiles boolean objects -- really just records their class
class DateProfiler < BaseProfiler
PSUEDO_CLASS = "date"
def self.applicable?(obj)
obj.is_a?(Date) || obj.is_a?(DateTime)
end
def results
results = AttributeProfile.new
results.klass = PSUEDO_CLASS
results
end
end
# Maps supported classes to their profiler
SUPPORTED_PROFILERS = [StringProfiler, NumericProfiler, BooleanProfiler, DateProfiler]
def initialize(attr)
@attr = attr.to_sym #the attr to profile
@profiler = nil #the profiler in use
end
# Runs the query and pumps the results into the core logic of the profiler
def process
start = Time.now
puts "Beginning #{@attr}"
begin
Sequel.postgres(CONFIG[:db_hash]) do |db|
db.fetch(query).use_cursor.each do |row|
process_element(row[@attr])
end
end
rescue Sequel::DatabaseError
$stderr.puts "DB ERROR IN #{@attr}"
end
write_results
puts "Time elapsed: #{Time.now.to_i - start.to_i} seconds for #{@attr}"
end
# If a profiler has been instantiated, it checks that the data type
# belongs and then passes it down to the lower layer
#
# If it's the first data element, an appropriate profiler is created
def process_element(data)
if data.nil?
return
elsif @profiler && @profiler.class.applicable?(data)
@profiler.process(data)
return
elsif @profiler && !@profiler.class.applicable?(data)
raise ArgumentError, "Inconsistent class provided to profiler"
end
# Initialize the profiler
profiler_idx = SUPPORTED_PROFILERS.index { |p| p.applicable?(data) }
if profiler_idx.nil?
raise ArgumentError, "Unprofilable type: #{data.class}"
else
@profiler = SUPPORTED_PROFILERS[profiler_idx].new
process_element(data)
end
end
def results
if @profiler
r = @profiler.results
r.name = @attr
else
r = AttributeProfile.new
r.name = @attr
r.string = NilClass
end
r
end
def write_results
File.open("profiles/#{@attr}", "w") do |f|
f.write(results.serialize)
end
end
private
# The base query to load data into the profiler
def query
<<-SQL
SELECT #{@attr} FROM #{CONFIG[:tbl_name]};
SQL
end
end
| true |
c681bb3f97f11b46f7211bae4ee9b82ed57ef2a6 | Ruby | VijayEluri/aspen | /lib/aspen/netty_proxy.rb | UTF-8 | 3,575 | 2.59375 | 3 | [
"MIT"
] | permissive | require 'java'
require File.dirname(__FILE__) + '/aspenj.jar'
import com.github.kevwil.aspen.RackProxy
import com.github.kevwil.aspen.RackUtil
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.channels.Channels
import org.jboss.netty.channel.ChannelHandlerContext
import org.jboss.netty.buffer.ChannelBuffers
import org.jboss.netty.buffer.ChannelBufferInputStream
import org.jboss.netty.handler.codec.http.DefaultHttpResponse
import org.jboss.netty.handler.codec.http.HttpResponseStatus
import org.jboss.netty.handler.codec.http.HttpVersion
require 'stringio'
require 'aspen/version'
module Aspen
class RackParseError < RuntimeError; end
# implementation of RackProxy interface from Java side
# @author Kevin Williams
# @since 1.0.0
# @version 1.0.0
class NettyProxy
# implement RackProxy interface
# @todo stay on top of JRuby interface use, in case behavior changes
include RackProxy
# create new instance of NettyProxy
# @param #call(env) a Ruby Object which responds to :call(env)
# @return [Array]an array of [Integer (status code), Hash (headers), and Object responding to #each returning Strings]
def initialize( app )
@app = app
end
# process an incoming message which has been received on the socket
# this method does most of the heavy lifting of translating Netty classes and behaviors into Rack
# @param [ChannelHandlerContext] the Netty context for message handling
# @param [HttpRequest] the Netty request object
# @return [HttpResponse] the Netty response
# @todo handle chunking, keep-alive, content-encoding, etc.
def process( cxt, req )
env = {}
RackUtil.parse_headers( cxt, req, env )
env["SCRIPT_NAME"] = "" if env["SCRIPT_NAME"] == "/"
env.delete "PATH_INFO" if env["PATH_INFO"] == ""
env["SERVER_PORT"] = "80" unless env["SERVER_PORT"]
data = req.content.to_string("UTF-8").to_s
rack_input = StringIO.new( data )
rack_input.set_encoding( Encoding::BINARY ) if rack_input.respond_to?( :set_encoding )
env.update( {"rack.version" => ::Aspen::VERSION::RACK,
"rack.input" => rack_input,
"rack.errors" => $stderr,
"rack.multithread" => true,
"rack.multiprocess" => false,
"rack.run_once" => false,
"rack.url_scheme" => "http",
} )
# g "about to call #{@app.class} class"
# g env.inspect if Logging.debug?
result = @app.call(env)
# g result.inspect
status, headers, body = result
#status, headers, body = @app.call(env)
# g body.inspect if (Logging.debug? and body)
# g status.inspect if (Logging.debug? and status)
# raise RackParseError, "status is a #{status.class} class, not an integer" unless status.is_a?(Integer)
status = 200 unless status.is_a?(Integer)
unless body.nil?
raise RackParseError, "body doesn't respond to :each and return strings because it is a(n) #{body.class}" unless body.respond_to?(:each)
end
resp = DefaultHttpResponse.new( HttpVersion::HTTP_1_1, HttpResponseStatus.value_of( status ) )
headers.each do |k,vs|
vs.each { |v| resp.add_header k, v.chomp } if vs
end if headers
out_buf = ChannelBuffers.dynamic_buffer
body.each do |line|
out_buf.write_bytes ChannelBuffers.copied_buffer( line, "UTF-8" )
end if body
resp.content = out_buf
# g resp.inspect if Logging.debug?
resp
end
end
end | true |
3b906f92233c9150b53069ace5c2145b5455b2de | Ruby | pact-foundation/pact-support | /lib/pact/matchers/embedded_diff_formatter.rb | UTF-8 | 1,277 | 2.65625 | 3 | [
"MIT"
] | permissive | require 'pact/shared/active_support_support'
require 'rainbow'
module Pact
module Matchers
class EmbeddedDiffFormatter
include Pact::ActiveSupportSupport
EXPECTED = /"EXPECTED([A-Z_]*)":/
ACTUAL = /"ACTUAL([A-Z_]*)":/
attr_reader :diff, :colour
def initialize diff, options = {}
@diff = diff
@colour = options.fetch(:colour, false)
end
def self.call diff, options = {colour: Pact.configuration.color_enabled}
new(diff, options).call
end
def call
to_s
end
def to_hash
diff
end
def to_s
colourise_message_if_configured fix_json_formatting(diff.to_json)
end
def colourise_message_if_configured message
if colour
colourise_message message
else
message
end
end
def colourise_message message
message.split("\n").collect{| line | colourise(line) }.join("\n")
end
def colourise line
line.gsub(EXPECTED){|match| coloured_key match, :red }.gsub(ACTUAL){ | match | coloured_key match, :green }
end
def coloured_key match, colour
'"' + Rainbow(match.downcase.gsub(/^"|":$/,'')).send(colour) + '":'
end
end
end
end | true |
f5afee289198161d13f78297ca395e8fe9264bf4 | Ruby | puyo/exercises | /ruby/orion.rb/lib/moo/galaxy.rb | UTF-8 | 615 | 3.015625 | 3 | [] | no_license | require 'moo/star'
require 'moo/vector2d'
module Moo
class Galaxy
def initialize(opts = {})
@width = 0.0
@height = 0.0
@stars = []
@races = []
end
def create_predefined
# static for now
@width = 20.0
@height = 20.0
@stars = [
sol = Star.new('Sol', :position => pos(9, 9)),
tai = Star.new('Tai', :position => pos(11, 12)),
]
@races = [
]
end
def advance_turn
@races.each {|race| race.advance_turn } # grow colonies, etc.
@stars.each {|star| star.advance_turn } # rotate planets
end
end
end
| true |
670c5eb44fe88ddbb07d6e89284cc606fd14db14 | Ruby | sergIlov/video_trimmer_api | /lib/video_trimmer_emulator.rb | UTF-8 | 198 | 2.671875 | 3 | [] | no_license | # Emulator
class VideoTrimmerEmulator
def initialize(_url, _start_time, _end_time)
end
def trim
# sleep(Random.rand(20.seconds..2.minutes))
sleep 3
[true, false].sample
end
end
| true |
46c77941db7c5dc09509b5ae06aff6f5755f10af | Ruby | densitypop/group-nation | /lib/data_loader.rb | UTF-8 | 1,180 | 2.71875 | 3 | [] | no_license | require 'forgery'
class DataLoader
def create_person
f = InternetEnabledPersonForgery
Person.create :first_name => f.first_name,
:last_name => f.last_name,
:email => f.email_address
f.reset
end
def create_group
f = GroupForgery
Group.create :name => f.name,
:city => f.city,
:state => f.state,
:zip => f.zip,
:active => group_active_state,
:organizer => group_organizer
end
def self.method_missing(method, *args)
if method.to_s =~ /^load_/
model_name = method.to_s.gsub(/^load_/, '').singularize
model_class = model_name.classify.constantize
model_class.delete_all
number_of_objects = args[0]
number_of_objects.times do
self.new.send "create_#{model_name}"
end
end
end
private
def group_active_state
return false if Group.find_all_by_active(false).length < 5
true
end
def group_organizer
p = nil
begin
p = Person.first :order => 'rand()'
end while Group.find_all_by_organizer_id(p.id).length > 3
p
end
end
| true |
d5da3a4f5edc0d7c607e7066902d17278821c627 | Ruby | hanamimastery/episodes | /013/before/bin/install | UTF-8 | 4,982 | 2.703125 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
# frozen_string_literal: true
require 'find'
require 'tempfile'
require 'fileutils'
require 'pathname'
require 'open3'
class Installer
class << self
def call(app_name)
return unless rename_app(app_name)
install_readme
bundle_install
generate_cli_binstub
self_destruct
puts 'Your app is ready to go!'
end
private
def rename_app(app_name)
if /[A-Z]/.match(app_name)
puts 'Capital letters can lead to unexpected results.'
puts "Underscore your app name instead (i.e. #{app_name.downcase})."
return false
end
rename_file_contents(app_name)
rename_file_names(app_name)
end
def rename_file_contents(app_name)
dash_name = app_name.tr('_', '-')
snake_name = app_name.tr('-', '_')
camel_name = camelize(snake_name)
title_name = titleize(snake_name)
replacements = {
'AppPrototype' => camel_name,
'app-prototype' => dash_name,
'app_prototype' => snake_name,
'App Prototype' => title_name
}
find_files_for_gsub.each do |fname|
file_edit(fname, replacements)
end
end
def rename_file_names(app_name)
files, dirs = find_files_for_rename.partition { |f| File.file? f }
files.each do |orig_name|
new_name = orig_name.sub('app_prototype', app_name)
FileUtils.mv(orig_name, new_name, force: true, verbose: true) unless orig_name == new_name
end
dirs.reverse.each do |orig_name|
new_name = orig_name.sub('app_prototype', app_name)
FileUtils.mv(orig_name, new_name, force: true, verbose: true) unless orig_name == new_name
end
end
def find_files_for_gsub(d = Pathname(__dir__).parent)
files_or_dirs = []
Find.find(d) do |path|
if File.directory?(path)
if File.basename(path) == '.git'
Find.prune
else
next
end
else
next if path == File.expand_path(__FILE__)
if block_given?
yield path
else
files_or_dirs << path
end
end
end
return files_or_dirs unless block_given?
end
def find_files_for_rename(d = Pathname(__dir__).parent)
files_and_dirs = []
Find.find(d) do |path|
regexp = /app_prototype/
bname = File.basename(path)
if File.directory?(path)
case bname
when '.git'
Find.prune
when regexp
if block_given?
yield path
else
files_and_dirs << path
end
else
next
end
else
next unless bname =~ regexp
if block_given?
yield path
else
files_and_dirs << path
end
end
end
files_and_dirs unless block_given?
end
def file_edit(filename, replacements)
puts "changing filename #{filename}"
tempfile = Tempfile.new
File.open(filename).each do |line|
replacements.each do |proto_name, new_name|
line = line.gsub(proto_name, new_name)
end
tempfile.puts line
end
tempfile.fdatasync unless RUBY_PLATFORM =~ /mswin|mingw|windows/
tempfile.close
if RUBY_PLATFORM =~ /mswin|mingw|windows/
# FIXME: apply perms on windows
else
stat = File.stat(filename)
FileUtils.chown stat.uid, stat.gid, tempfile.path
FileUtils.chmod stat.mode, tempfile.path
end
FileUtils.mv tempfile.path, filename
end
def bundle_install
puts 'Running bundle install - this may take a few minutes'
shell 'bundle install'
end
def generate_cli_binstub
shell 'bundle binstubs hanami-cli'
end
def install_readme
FileUtils.mv('README.app.md', 'README.md')
rescue StandardError
nil
end
def self_destruct
FileUtils.rm('.github/FUNDING.yml', force: true, verbose: true)
FileUtils.rm('rm bin/install', force: true, verbose: true)
end
def camelize(string)
result = string.sub(/^[a-z\d]*/) { Regexp.last_match(0).capitalize }
result.gsub(%r{(?:_|(/))([a-z\d]*)}) { "#{Regexp.last_match(1)}#{Regexp.last_match(2).capitalize}" }
end
def titleize(underscored_string)
result = underscored_string.tr('_', ' ')
result.gsub(/\b('?[a-z])/) { Regexp.last_match(1).capitalize }
end
def shell(command, _env = {})
Open3.popen2e(command) do |_stdin, stdout_err, wait_thr|
while line = stdout_err.gets
puts line
end
exit_status = wait_thr.value
raise "#{command} failed with status #{exit_status}\n" unless exit_status.success?
end
end
end
end
project_name = ARGV[0]
raise "Please provide a snake_cased project name, e.g.\n\n./bin/install my_app" unless project_name
Installer.call(project_name)
| true |
4f620ca788acb3b911960fcf0988bd872a9c6d34 | Ruby | amcvega/pdf-cell | /test/pdf_cell_test.rb | UTF-8 | 1,931 | 2.546875 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'rubygems'
require 'pdf/writer'
require '../lib/pdf_cell'
require 'active_support'
pdf = PDF::Writer.new
biodata = PDF::Cell::Base.new(pdf)
biodata.build :width => 500, :font_size => 8 do
header "Crew File #245: Jack Black (2/M of MV Nautilus)", :shaded => true,
:font_size => 15
desc "The Context"
cell :width => 375 do
cell :width => 125 do
text "<b>Given Name</b>"
text "Jack"
end
cell :width => 125 do
text "<b>Middle Name</b>"
text "James"
end
cell :width => 125 do
text "<b>Family Name</b>"
text "Black"
end
cell :width => 250 do
text "<b>Address</b>"
text "#124 Main Street"
end
cell :width => 125 do
text "<b>Contact No</b>"
text "123-456-789"
end
cell :width => 125 do
text "<b>Date of Birth</b> 1985-01-01"
end
cell :width => 125 do
text "<b>Age</b> 22"
end
cell :width => 125 do
text "<b>Birthplace</b> New Jersey"
end
cell :width => 125 do
text "<b>Nationality</b> English"
end
cell :width => 125 do
text "<b>Civil Status</b> Married"
end
cell :width => 125 do
text "<b>Eye Color</b> Blue"
end
cell :width => 125 do
text "<b>Weight</b> 125"
end
cell :width => 125 do
text "<b>Height</b> 123"
end
cell :width => 125 do
text "<b>SSS No.</b> asdfa"
end
cell :width => 125 do
text "<b>TIN</b> asdfa"
end
cell :width => 125 do
text "<b>Shoe Size</b> aasdf"
end
cell :width => 375 do
text "<b>Name of Spouse</b> Gina Black"
end
cell :width => 375, :height => 50 do
text "<b>Spouse's Contact No / Address</b>"
text "123-9876"
end
end
cell :width => 125, :height => 125 do
text "Photo Here"
end
end
pdf.save_as("biodata_result.pdf")
| true |
f0ef1b62fb0ad490713ed53cd690ee1b16792bd1 | Ruby | vise890/dbc_prep_exercises | /pj_euler/20.rb | UTF-8 | 222 | 3.984375 | 4 | [] | no_license | def factorial(n)
if n == 1
return 1
else
return n * factorial(n-1)
end
end
def digit_sum(n)
sum = 0
n.to_s.each_char do |char|
sum += char.to_i
end
return sum
end
puts digit_sum(factorial(100))
| true |
cb6e9691028c3f493a6afbd9836b70eb7100708a | Ruby | ColinOsborn/ruby_exercises | /flatten_test.rb | UTF-8 | 319 | 2.609375 | 3 | [] | no_license | require 'pry'
require 'minitest/autorun'
require 'minitest/pride'
require_relative 'flatten'
class CustomArrayTest < Minitest::Test
def test_setup
assert CustomArray.class
end
def test_we_can_flatten_this_array
c = CustomArray.new([[1,2],[3,[4,5]]])
assert_equal [1,2,3,4,5], c.flatten
end
end
| true |
fb392fb5b21158409e4634f224c054d409c50658 | Ruby | JustinData/GA-WDI-Work | /w01/d03/Nichol/temperature.rb | UTF-8 | 1,152 | 5.09375 | 5 | [] | no_license | # ### Celsius Temperature Converter
# - This should be done in a new file called temperature.rb
# - Write `convert_to_fahrenheit` and `convert_to_kelvin` methods that will each take a temperature in Celsius as a parameter and return the converted temperature.
# - Once you have these methods written, a program that does the following:
# - The user should be asked to enter a temperature in Celsius
# - The user should be asked to enter if they want to convert the temperature to Fahrenheit or Kelvin
# - After these have been entered, the user should be told what the converted temperature is
def convert_to_fahrenheit(tempc)
tempf = (tempc * 9/5) + 32
return tempf
end
def convert_to_celsius(tempf)
tempc = (tempf - 32) * 5/9
return tempc
end
def convert_to_kelvin(tempc)
tempk = tempc + 273.15
return tempk
end
puts "enter a temp in celsius"
tempc = gets.chomp.to_f
puts "convert to kelvin or Fahrenheit?"
targetunit = gets.chomp.downcase
if targetunit == "f"
convertedtemp = convert_to_fahrenheit(tempc)
elsif targetunit == "k"
convertedtemp = convert_to_kelvin(tempc)
end
puts "your converted temperature is #{convertedtemp}"
| true |
4ad3ba9e26c1d06bd929f702b06a25170d934946 | Ruby | ThiagoRodrigues/mars-rover-challenge | /lib/orientation.rb | UTF-8 | 1,339 | 3.484375 | 3 | [] | no_license |
class Orientation
COMPASS = {
"N" => "NorthFaced",
"E" => "EastFaced",
"S" => "SouthFaced",
"W" => "WestFaced"
}.freeze
def self.get_orientation(instance_key)
if COMPASS.has_key?(instance_key)
return Kernel.const_get(COMPASS[instance_key]).new
end
raise InvalidOrientationError.new("Invalid instance_key")
end
def move_foward; end
def turn_left; end
def turn_right; end
end
# Subclasses of Orientation
#
# North, East, South and West Facets could moviment the Rover
# based on it(Rover) actual coords
#
class NorthFaced < Orientation
def turn_left
[0, 0, "W"]
end
def turn_right
[0, 0, "E"]
end
def move_foward
[0, 1, "N"]
end
end
class EastFaced < Orientation
def turn_left
[0, 0, "N"]
end
def turn_right
[0, 0, "S"]
end
def move_foward
[1, 0, "E"]
end
end
class SouthFaced < Orientation
def turn_left
[0, 0 , "E"]
end
def turn_right
[0, 0 , "W"]
end
def move_foward
[0, -1, "S"]
end
end
class WestFaced < Orientation
def turn_left
[0, 0 , "S"]
end
def turn_right
[0, 0 , "N"]
end
def move_foward
[-1, 0, "W"]
end
end
class InvalidOrientationError < StandardError
attr_reader :message
def initialize(msg)
@message = msg
super("InvalidOrientationError")
end
end
| true |
a2ac53227db3502fb0b6359d9a3582eb4ccafa01 | Ruby | JC-LL/rive | /lib/rive/runner.rb | UTF-8 | 1,959 | 2.84375 | 3 | [] | no_license | require "optparse"
require_relative "iss"
module Rive
class Runner
def self.run *arguments
new.run(arguments)
end
def run arguments
args = parse_options(arguments)
iss=Iss.new
iss.options = args
begin
filename=args[:file]
if iss.options[:disassemble]
iss.load(filename)
iss.disassemble
elsif iss.options[:run]
iss.load(filename)
iss.run(filename)
else
raise "need a rive file : rive [options] <file>"
end
rescue Exception => e
puts e unless iss.options[:mute]
raise
return false
end
end
def header
puts "rive (#{VERSION}) / Ruby RISCV simulator - (c) JC Le Lann 2020"
end
private
def parse_options(arguments)
parser = OptionParser.new
no_arguments=arguments.empty?
options = {}
parser.on("-h", "--help", "Show help message") do
puts parser
exit(true)
end
parser.on("-p", "--parse", "parse only") do
options[:parse_only]=true
end
parser.on("-d", "dissassemble") do
options[:disassemble] = true
end
parser.on("-r", "run") do
options[:run] = true
end
parser.on("--start ADDR", "start address") do |addr|
options[:start_address] = addr
end
parser.on("--memsize SIZE", "memory size") do |size|
options[:memsize] = size.to_i
end
parser.on("--vv", "verbose") do
options[:verbose] = true
end
parser.on("--mute","mute") do
options[:mute]=true
end
parser.on("-v", "--version", "Show version number") do
puts VERSION
exit(true)
end
parser.parse!(arguments)
options[:file]=arguments.shift #the remaining file
header unless options[:mute]
if no_arguments
puts parser
end
options
end
end
end
| true |
a0ce0e83447f685462102756389a7ea9c31fc364 | Ruby | rintaun/yard-sequel | /lib/yard-sequel/errors.rb | UTF-8 | 1,444 | 2.90625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module YardSequel
# The standard error for the plugin. All other errors inherit from this.
# @author Kai Moschcau
Error = Class.new ::StandardError
# Error that is raised if anything goes wrong with parsing any AstNode.
# @author Kai Moschcau
class AstNodeParseError < Error
# @return [YARD::Parser::Ruby::AstNode] the AstNode that caused the Error.
attr_accessor :ast_node
# @param [#to_s] message The message of the Error.
# @param [YARD::Parser::Ruby::AstNode] ast_node The AstNode that caused the
# Error.
def initialize(message = nil, ast_node = nil)
@ast_node = ast_node
super message
end
# @return [String] the message of the Error, with the location info of the
# AstNode prepended, if it exists.
def message
return super unless @ast_node
[[ast_node_file, ast_node_line].compact.join(':'), super]
.compact.join(': ')
end
private
# @note This disables $stderr while getting the attribute.
# @return [String, nil] the file name of the AstNode.
def ast_node_file
return unless @ast_node
stderr = $stderr
$stderr = StringIO.new
file_name = @ast_node.file
$stderr = stderr
file_name
end
# @return [String, nil] the line number of the AstNode.
def ast_node_line
return unless @ast_node && @ast_node.has_line?
@ast_node.line
end
end
end
| true |
fb25db32b4eebad6e7c76b9fdba6cfd5e0365e7e | Ruby | JVThomas/sinatra-basic-routes-lab-v-000 | /app.rb | UTF-8 | 273 | 2.578125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | require_relative 'config/environment'
class App < Sinatra::Base
get '/name' do
"My name is Justin Thomas"
end
get '/hometown' do
"My hometown is Woodside, NY"
end
get '/favorite-song' do
"My favorite song is 'Learn to Fly' by the Foo Fighters"
end
end
| true |
6d4be371c8042e31bde422aa58ce03897f38d9ec | Ruby | PenneyGadget/module_3_assessment | /app/services/best_buy_service.rb | UTF-8 | 523 | 2.53125 | 3 | [] | no_license | class BestBuyService
attr_reader :connection
def initialize
@connection = Faraday.new(:url => "https://api.bestbuy.com") do |faraday|
faraday.adapter Faraday.default_adapter
faraday.params["apiKey"] = ENV["BEST_BUY_KEY"]
faraday.params["format"] = "json"
end
end
def find_products(product)
parse(connection.get("/v1/products(longDescription=#{product}*)?pageSize=15"))[:products]
end
private
def parse(response)
JSON.parse(response.body, symbolize_names: true)
end
end
| true |
a59aaca647c661c4ff080c365ecc26b4e1806d31 | Ruby | fadiTill/debugging-with-pry-onl01-seng-pt-012120 | /lib/pry_debugging.rb | UTF-8 | 35 | 2.765625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def plus_two(num)
num + 2
5
end
| true |
bacd01de2cce7b8542fa435437c2b161f61d81ca | Ruby | marcottelab/phamily | /lib/tasks/load_genes.rake | UTF-8 | 830 | 2.53125 | 3 | [] | no_license | #load_genes.rake
def batch_insert_genes species, arr
gene_data = arr.collect{|a| "('#{species}', '#{a}')"}
sql = "INSERT INTO genes (original_id, species) VALUES " + gene_data.join(", ") + ";"
ActiveRecord::Base.connection.execute sql
end
namespace :db do
namespace :phenologs do
desc "load genes from phenologs.org tables"
task :load_genes => :environment do
DATA_DIR = Rails.root + "data/"
Dir.foreach(DATA_DIR) do |file|
next unless file =~ /^genes\.[A-Z][a-z]$/
sp = file[6..8]
raise(Error, "Species not recognizable") unless sp =~ /^[A-Z][a-z]$/
genes = []
f = File.new("#{DATA_DIR}#{file}", "r")
while line = f.gets
line.chomp!
genes << line
end
batch_insert_genes(sp, genes)
end
end
end
end
| true |
7f567cd2352282eeab1cf0677ac4112df3c41df0 | Ruby | Tolia/typograph | /lib/typograph/processor.rb | UTF-8 | 1,189 | 2.6875 | 3 | [
"MIT"
] | permissive | # encoding: utf-8
module Typograph
class Processor
DEFAULTS = {}
SAFE_BLOCKS = [
['<pre[^>]*>','</pre>'],
['<style[^>]*>','</style>'],
['<script[^>]*>','</script>'],
['<!--','-->'],
['<code[^>]*>','</code>']
]
def initialize(options={})
@adapter = Adapter.new options
@russian_grammar = Processors::RussianGrammar.new options
@quotes = Processors::Quotes.new options
end
def safe_blocks
@pattern ||= begin
pattern = SAFE_BLOCKS.map do |val|
val.join('.*?')
end.join('|')
Regexp.new("(#{pattern}|<[^>]*[\\s][^>]*>)", Regexp::IGNORECASE | Regexp::MULTILINE)
end
end
def process(str)
str = @adapter.normalize(str)
@safe_blocks = {}
str.gsub!(safe_blocks) do |match|
key = "<#{@safe_blocks.length}>"
@safe_blocks[key] = match
key
end
str = @quotes.process str
str = @russian_grammar.process str
if @safe_blocks
str.gsub! /(<\d>)/ do |match|
@safe_blocks[match]
end
end
@safe_blocks = {}
str
end
end
end | true |
ea82552ad1103555579d5090c5fb74dd27ea2cb6 | Ruby | BearCub29/Gossip_project | /lib/view.rb | UTF-8 | 384 | 2.5625 | 3 | [] | no_license | class View
attr_accessor :author , :content , :controller
def create_gossip
puts "Quel est ton nom petite fouine?"
@author = gets.chomp
puts "Quel est ton Gossip?"
@content = gets.chomp
return params = { @author => @content}
end
def index_gossips
@controller = Controller.new
puts @controller.index_gossips
end
end
| true |
1955247d224518655032f2ed1b1eec5b21e78e43 | Ruby | Adria1988/ProgrammingExercises | /Ruby/TicTacToe/tic_tac_toe_v2/test3.rb | UTF-8 | 621 | 3.3125 | 3 | [] | no_license | require_relative 'board'
require_relative 'human_player'
class Game
def initialize(player_1_mark,player_2_mark)
@player_1 = HumanPlayer.new(player_1_mark)
@player_2 = HumanPlayer.new(player_2_mark)
@current_player = @player_1
@board = Board.new
end
def switch_turn
@current_player = if @current_player == @player_1
@player_2
else
@player_1
end
end
def play
p '---'
while @board.empty_positions? == false
@board.print
@current_player.get_position
end
end
p play
end
| true |
997d7e792566d44bb48e4a9caca94a0f7bc8be3d | Ruby | rvmiller/useragent-generator | /lib/useragent/config.rb | UTF-8 | 533 | 2.5625 | 3 | [
"MIT",
"Apache-2.0"
] | permissive | require 'yaml'
module UserAgent
class Config
@@props = Hash.new
def self.parse(entity, key)
# Lazy-load the props for the entity we need.
# An entity can be an os type, a device, manufacturer,
# pretty much anything that has properties we don't
# want to hard-code in a class
#
@@props[entity] ||= load_props(entity)
@@props[entity][key]
end
def self.load_props(entity)
YAML.load_file(File.join(File.dirname(__FILE__), "config/#{entity}.yml"))
end
end
end | true |
228dd610b69e4c03766910778244eb7637f3bac2 | Ruby | dgtm/meeting-planner | /lib/scheduler.rb | UTF-8 | 1,714 | 2.953125 | 3 | [
"MIT"
] | permissive | class Scheduler
class << self
def schedulable_time
{ starts_at: Time.parse("09:00"), ends_at: Time.parse("17:00") }
end
def restricted_timeframe
# @note Could be extended to an array in future for added flexibility
{ starts_at: Time.parse('12:00'), ends_at: Time.parse('13:00') }
end
# @param [Time] starts
# @param [Time] ends
# @return [Boolean]
# @note ActiveSupport has a better method Range#operlaps?(time_range) that can replace this method
def falls_during_restricted_time?(starts, ends)
restricted_time_range = (Scheduler.restricted_timeframe[:starts_at] + 1)..(Scheduler.restricted_timeframe[:ends_at] - 1)
# If the start or end time of the meeting is during lunch
# e.g between 12:01 to 12:59
falls_in_range = restricted_time_range === starts || restricted_time_range === ends
# Meetings that are supposed to start at say, 12:40 and last 2 hours
extends_within_range = (starts < restricted_time_range.first && ends > restricted_time_range.last)
return true if falls_in_range || extends_within_range
end
def schedule(rooms, new_meeting)
# Find all rooms that can hold a meeting of this duration
available_rooms = rooms.select{|room| room.can_hold_a_meeting?(new_meeting.duration)}
puts "No room can hold #{new_meeting.title}" && return if available_rooms.empty?
# Find the best-fit room depending on which is free at earliest possible time
earliest_available_rooms = available_rooms.sort { |room_a, room_b| room_a.next_free_at <=> room_b.next_free_at }
selected_room = earliest_available_rooms.first
selected_room.add(new_meeting)
end
end
end
| true |
fb40a9e1dc58d2285bbcabed45602551a0c0682a | Ruby | devindreszer/wdi_1_ruby_lab_methods | /lab1.rb | UTF-8 | 546 | 3.640625 | 4 | [] | no_license |
class String
def toonify(accent)
case accent
when :daffy
self.gsub('S','Th').gsub('s','th')
when :elmer
self.gsub('R', 'W').gsub('r', 'w')
when :tom
self.gsub('R', 'Ah').gsub('r', 'ah')
else
self
end
end
end
puts "Dark dock".toonify(:tom)
ACCENTS = {
daffy: ['s', 'th']
elmer: ['r', 'w']
tom: ['ar', 'ah']
}
def toonify(accent, sentence)
if ACCENTS.key?(accent)
sentence.gsub(*ACCENTS[accent])
else
sentence
end
end
puts toonify(:tom, "Park your car at Harvard Yard")
| true |
9be1361ab836981f5b0f011dd7e3da36668496a1 | Ruby | eby12/hopheads | /app/models/brewery.rb | UTF-8 | 652 | 2.953125 | 3 | [] | no_license | class Brewery < ActiveRecord::Base
attr_accessible :name
has_many :beers
has_many :posts
has_many :comments, dependent: :destroy
has_one :location
before_save :title_case
#validates :name length: {minimum: 5}, presence: true, uniqueness: true
#This method title cases all saved entries for brewery to make them singular and have no off-cased brewery names.
def title_case
articles = %w{a and the of}
self.name = self.name.downcase.split(" ")
self.name.each do |word|
unless articles.include?(word)
word.capitalize!
end
end
self.name.first.capitalize!
self.name = self.name.join(" ")
end
end
| true |
3794e2afa4bbb1a86baf33cedbb595080ed2adf3 | Ruby | kamanfi/Algorithms_Ruby | /Dijkstra.rb | UTF-8 | 753 | 3.34375 | 3 | [] | no_license | require_relative 'Wgraph.rb'
def dijkstra(graph)
cost ={}
parent ={}
traversed=[]
order=[]
neighbor = graph.neighbor
#populate initial tables
neighbor.each do |e|
cost[e] =[e.edge(graph)]
parent[e.name] =graph.name
traversed=[e.name]
end
p cost.values
end
def find_lowest_cost(cost)
end
# construct simple Weighted Graph
ghana = Wgraph.new(:ghana, 0)
nigeria = Wgraph.new(:nigeria, 25)
mali = Wgraph.new(:mali, 30)
egypt = Wgraph.new(:egypt ,4)
sudan = Wgraph.new(:sudan, 21)
timbuktu = Wgraph.new(:timbuktu, 3)
ghana.add_neighbor(nigeria, mali,)
nigeria.add_neighbor(mali, egypt, timbuktu)
mali.add_neighbor(nigeria,egypt,sudan)
egypt.add_neighbor(sudan)
sudan.add_neighbor(timbuktu)
p ghana.edge(nigeria)
dijkstra(ghana) | true |
314a251c2c94316d74ea2f786186ab3b46d7a4d6 | Ruby | MPalhidai/Algorithms | /exercism/ruby/complete/isogram/isogram.rb | UTF-8 | 248 | 3.4375 | 3 | [] | no_license | class Isogram
def self.isogram?(string)
hash = Hash.new(0)
output = true
string.chars.each do |char|
char.downcase!
hash[char] += 1
output = false if hash[char] > 1 && /\w/.match(char)
end
output
end
end
| true |
8d71b9cd72c25657fbcfe6ecae21cdabe8de4f8d | Ruby | My-Dead-Projects/bytecode_interpreter | /bct.rb | UTF-8 | 1,381 | 2.828125 | 3 | [] | no_license | OUT = File.open("prog.bc", "w")
module Translator
module Preprocessor
class Methods
def self.comment(line, pos)
line[0, pos]
end
end
Keychars = {
"#" => Methods.method(:comment)
}
end
module Encoder
Keywords = {
"stor" => 0x01,
"mult" => 0x13,
"debug"=> 0x60
}
end
def self.translate(line, line_num = nil)
preprocess = lambda do
index = 0
line.each_char do |c|
if Preprocessor::Keychars.has_key? c
line = Preprocessor::Keychars[c].call(line, index)
end
index += 1
end
end
parse = lambda do
line = line.split
(1..line.length-1).each do |i|
if line.length > 1 and line[i][0] == "r"
line[i] = Integer(line[i][1..-1])
end
end
(1..line.length-1).each do |i|
line[i] = Integer(line[i])
end
end
encode = lambda do
for tok in line
if tok.class == Fixnum
OUT.print tok.chr
elsif tok.class == String
OUT.print Encoder::Keywords[tok].chr
end
end
end
line.chomp!
begin
preprocess.()
parse.()
encode.()
end
end
end
if __FILE__ == $0
iter = 0
ARGF.each_line do |line|
Translator.translate(line, iter+=1)
end
end
| true |
0d59b70cf82bd591003cfc117839e5a4ff469aaa | Ruby | jaheyeva/intro_to_ruby | /lesson3/homework.rb | UTF-8 | 127 | 3.109375 | 3 | [] | no_license | number = rand(10)
number.times do
puts number * number
number = number + 1
break if number == 0
end
puts "the loop is done!" | true |
638dd1794a97a64b9eee252a6584c38117078bf6 | Ruby | boshnessy/Example_Exercises | /factory/manager.rb | UTF-8 | 1,790 | 4.4375 | 4 | [] | no_license | # A manager can do EVERYTHING an employee can do, and also send reports
class Employee
attr_reader :first_name, :last_name, :salary
attr_writer :first_name
def initialize(input_options)
@first_name = input_options[:first_name]
@last_name = input_options[:last_name]
@salary = input_options[:salary]
@active = input_options[:active]
end
def print_info
p "#{@first_name} #{@last_name} makes $#{@salary} per year."
end
def give_annual_raise
@salary = @salary * 1.05
end
end
employee1 = Employee.new({:first_name => "Majora", :last_name => "Carter", :salary => 80000, :active => true})
employee2 = Employee.new(first_name: "Danilo", last_name: "Campos", salary: 70000, active: false)
class Manager < Employee # Take everything in employee class and throw it in manager class
# attr_reader :first_name, :last_name, :salary
# attr_writer :first_name
# def initialize(input_options)
# @first_name = input_options[:first_name]
# @last_name = input_options[:last_name]
# @salary = input_options[:salary]
# @active = input_options[:active]
# end
# def print_info
# p "#{first_name} #{last_name} makes $#{salary} per year."
# end
# def give_annual_raise
# @salary = @salary * 1.05
# end
def initialize(input_options)
super
@employees = input_options[:employees]
end
def send_report
p "going to send that report....."
p "sent that report"
end
end
manager1 = Manager.new({:first_name => "Manny", :last_name => "Williams", :salary => 100000, :active => true, employees: [employee1, employee2]}) # adding employees to manager class --> need to initialize w/o overriding initialize method from employee class --> super method(line 48)
manager1.print_info
manager1.send_report
p manager1 | true |
0153c9271571e5cc5711b7a607f7afb3b9799a83 | Ruby | vinhloc30796/introduction-to-programming | /swap.rb | UTF-8 | 665 | 4.5625 | 5 | [] | no_license | # swap.rb
=begin
Given a string of words separated by spaces, write a method
that takes this string of words and returns a string in which
the first and last letters of every word is swapped.
You may assume that every word contains at least one letter,
and that the string will always contain at least one word.
You may also assume that each string contains nothing but
words and spaces.
=end
def swap(string)
string.split(' ').map { |word| (word.size == 1)? word : word[-1] + word[1..word.size - 2] + word[0]}.join(' ')
end
puts swap('Oh what a wonderful day it is') == 'hO thaw a londerfuw yad ti si'
puts swap('Abcde') == 'ebcdA'
puts swap('a') == 'a' | true |
13dd42aca9e5e510ed3c64886eec8d72aeff1083 | Ruby | aceimdevelopment/instrumenapp | /app/models/record.rb | UTF-8 | 655 | 2.59375 | 3 | [] | no_license | class Record < ApplicationRecord
enum state: [:preinscrito, :inscrito, :aprobado, :aplazado]
belongs_to :student, foreign_key: 'user_id'
belongs_to :evaluation
validates_uniqueness_of :user_id, scope: [:evaluation_id], message: 'ya se encuentra inscrito en la evaluación seleccionada.'
before_validation :set_default_state
def alert_type
aux = ''
if self.aplazado?
aux = 'danger'
elsif self.aprobado?
aux = 'primary'
elsif self.inscrito?
aux = 'success'
else
aux = 'default'
end
return aux
end
protected
def set_default_state
self.state ||= :preinscrito
end
end
| true |
acadbc414b2b2f1c21066d83ed2249f3a087cbfb | Ruby | dumclibrary/medspace | /lib/tasks/migrate_medspace_data.rake | UTF-8 | 2,172 | 2.734375 | 3 | [] | no_license | # frozen_string_literal: true
namespace :import do
desc "Import data from Medspace export"
task medspace: :environment do
import_data
exit 0 # Make sure extra args aren't misinterpreted as rake task args
end
task medspace_collections: :environment do
import_collections
exit 0 # Make sure extra args aren't misinterpreted as rake task args
end
# helpers
def import_data
options = options(ARGV)
puts "Importing records using options: #{options}"
directory = options[:directory]
xml_files = File.join(directory, "*.xml")
works = Image.all.size + Document.all.size + ExternalObject.all.size
Dir.glob(xml_files).each do |file|
Medspace::Importer.import(file, directory)
end
new_works = Image.all.size + Document.all.size + ExternalObject.all.size
puts "Import complete: #{new_works - works} created."
end
def import_collections
options = options(ARGV)
puts "Importing collections using options: #{options}"
directory = options[:directory]
xml_files = File.join(directory, "*.xml")
collections = Collection.all.size
Dir.glob(xml_files).each do |file|
Medspace::CollectionImporter.import(file)
end
new_collections = Collection.all.size
puts "Import complete: #{new_collections - collections} created."
end
# Read the options that the user supplied on the command line.
def options(args)
require 'optparse'
user_inputs = {}
opts = OptionParser.new
opts.on('-i DIRECTORY', '--directory', '(required) The directory of xml files you want to import') do |directory|
user_inputs[:directory] = directory
end
opts.on('-h', '--help', 'Print this help message') do
puts opts
exit 0
end
args = opts.order!(ARGV) {}
opts.parse!(args)
required_options = [:directory]
missing_options = required_options - user_inputs.keys
missing_options.each { |o| puts "Error: Missing required option: --#{o}" }
# If any required options are missing, print the usage message and abort.
if !missing_options.blank?
puts ""
puts opts
exit 1
end
user_inputs
end
end
| true |
ff416787a178c47d0bc0462173dbb30c92bed5e1 | Ruby | oneworldcoders/emmanuel_tic-tac-toe | /lib/language.rb | UTF-8 | 496 | 3.0625 | 3 | [] | no_license | module TicTacToe
class Language
def initialize(lang='en', language_data=JSON.parse(File.read(File.join(File.dirname(__FILE__), 'language.json'))))
@lang = lang
@language_data = language_data
end
def set_language(key)
@lang = @language_data['language']["#{key}"]
end
def get_language
@lang
end
def get_string(key)
@language_data[@lang][key]
end
end
end
| true |
83ec5a9749f47f6e130e485cca1feb902d83ed34 | Ruby | 5ecured/ls | /101_programming_foundations/lesson_one/101-109_small_problems/easy-3/counting_number_characters.rb | UTF-8 | 151 | 3.6875 | 4 | [] | no_license | puts "Please write a word or multiple words"
answer = gets.chomp
total = answer.delete(' ').length
puts "There are #{total} characters in #{answer}"
| true |
7493f10a315212f004d4a8a4322eee4a8afa0f36 | Ruby | excid3/paddle_pay | /lib/paddle_pay/util.rb | UTF-8 | 796 | 2.859375 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
module PaddlePay
module Util
class << self
def convert_hash_keys(value)
case value
when Array
value.map { |v| convert_hash_keys(v) }
when Hash
Hash[value.map { |k, v| [underscore_key(k), convert_hash_keys(v)] }]
else
value
end
end
def convert_class_to_path(class_name)
class_name.split("::").map { |v| to_snake_case(v) }.join("/")
end
private
def underscore_key(k)
to_snake_case(k.to_s).to_sym
end
def to_snake_case(string)
string.gsub(/::/, "/")
.gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
.gsub(/([a-z\d])([A-Z])/, '\1_\2')
.tr("-", "_")
.downcase
end
end
end
end
| true |
54f002a53a7c60997384378fad8e27c98a260557 | Ruby | crywolfe/vitals-platform-code-test-gw | /update_quality.rb | UTF-8 | 1,732 | 3.4375 | 3 | [] | no_license | require 'award'
# inherit from Award Struct
# "Blue First", increases in quality as the expiration date approaches; Quality increases by 2 when there are 10 days or less left, and by 3 where there are 5 days or less left, but quality value drops to 0 after the expiration date.
# "Blue First" awards actually increase in quality the older they get
class BlueFirst < Award
def update_quality
decrease_expiry
increase_quality
increase_quality if expired?
end
end
# "Blue Compare", similar to "Blue First", increases in quality as the expiration date approaches; Quality increases by 2 when there are 10 days or less left, and by 3 where there are 5 days or less left, but quality value drops to 0 after the expiration date.
class BlueCompare < Award
def update_quality
decrease_expiry
if expired?
self.quality = 0
else
increase_quality
if self.quality > 50
self.quality = 50
end
end
end
def increase_quality
self.quality += 1
if expires_in < 10 && expires_in >= 5
self.quality += 1
end
if expires_in < 5
self.quality += 2
end
end
end
# "Blue Distinction Plus", being a highly sought distinction, never decreases in quality. "Blue Distinction Plus", being highly sought, its quality is 80 and it never alters.
class BlueDistinctionPlus < Award
def update_quality
self.quality = 80
end
def decrease_expiry
self.expires_in -= 1
end
end
# "Blue Star" awards should lose quality value twice as fast as normal awards.
class BlueStar < Award
def decrease_quality
self.quality -= 2 unless self.quality == 0
end
end
def update_quality(awards)
awards.each do |award|
award.update_quality
end
end
| true |
d28b632c3b88082f6d36109bc955b771c4f35de9 | Ruby | shirley1chu/slack-cli | /lib/channel.rb | UTF-8 | 1,001 | 2.875 | 3 | [] | no_license | require "dotenv"
require "HTTParty"
require "pry"
require_relative "recipient"
Dotenv.load
module Slack
class Channel < Recipient
CHANNEL_URL = "https://slack.com/api/channels.list"
@query = { token: KEY }
attr_reader :slack_id, :name, :topic, :member_count
def initialize(slack_id:, name:, topic:, member_count:)
@slack_id = slack_id
@name = name
@topic = topic
@member_count = member_count
end
def self.list
response = self.get(CHANNEL_URL, query: @query)
# binding.pry
channels = response["channels"].map do |channel|
id = channel["id"]
name = channel["name"]
topic = channel["topic"]["value"]
member_count = channel["num_members"]
self.new(slack_id: id, name: name, topic: topic, member_count: member_count)
end
return channels
end
def details
return "slack_id: #{slack_id}, name: #{name}, topic: #{topic}, member_count: #{member_count}"
end
end
end
| true |
fc76360296f01080160ff8275578eb0fa3b043eb | Ruby | osaut/pindare | /example/model_simeoni.rb | UTF-8 | 1,693 | 2.546875 | 3 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"BSD-2-Clause"
] | permissive | #encoding: utf-8
($:.unshift File.expand_path(File.join( File.dirname(__FILE__), '../lib' ))).uniq!
require 'pindare'
# Modèle EDO de croissance basé sur Predictive Pharmacokinetic-Pharmacodynamic Modeling of Tumor Growth Kinetics in Xenograft Models after Administration of Anticancer Agents. (2004). Predictive Pharmacokinetic-Pharmacodynamic Modeling of Tumor Growth Kinetics in Xenograft Models after Administration of Anticancer Agents, 1–8.
#
class Model_Simeoni < Model
include TimeIntegrator
def post_initialize
@name="Modèle simple de croissance"
@vars=@vars0
end
# Intégration
#
# @param [Float] tps Temps final de l'intégration
def integrate(tps, progress=false)
t=0.0
dt=0.0005
hist_TumorMass={}
ctr=0
num_iters=tps/dt
while(t<tps)
# Sauvegarde éventuelle des observables
save_observables t, dt if instants
@vars=ts_RK4(t, @vars, dt)
# Calcul des numids
@numids[:PFS]=t unless (@vars<=@vars0) or @numids.has_key?(:PFS)
# Sauvegarde de l'historique
if ctr.modulo(200)==0
hist_TumorMass[t]=vars
end
# Incrément des compteurs
t+=dt; ctr+=1
end
@numids[:FTV]=vars
@numids[:PFS]=t unless @numids.has_key?(:PFS)
end
attr_reader :params, :numids
private
attr_reader :instants, :saved_obs, :vars
# Fonction principale d'évolution (y'=func(y))
#
def func(t, v)
lambda0=params[:lambda0]
psi=params[:psi]
lambda0*v/(1.0+(lambda0/params[:lambda1]*v)**psi)**(1.0/psi)
end
end
pmap={psi: 1.0, lambda0: 1.0, lambda1: 1.0}
w_init=1.0
model=Model_Simeoni.new(pmap, w_init)
model.integrate(20.0)
#puts model.numids
| true |
9e2e5090aafd7d513486da5c2b138fde6b34bc0a | Ruby | scepa991/simple-math-prework | /lib/math.rb | UTF-8 | 302 | 3.15625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def addition(num1, num2)
4 + 5
end
def subtraction(num1, num2)
10 - 5
end
def division(num1, num2)
50 / 2
end
def multiplication(num1, num2)
4 * 30
end
def modulo(num1, num2)
34 % 5
end
def square_root(num)
9
end
def order_of_operation(num1, num2, num3, num4)
7 + ((43 * 23)/ 84)
end
| true |
c6a97668ae189bb72408666c92c19733a97a096a | Ruby | AdipSearch/thehackingproject | /S3/D03/trainings/superheros.rb | UTF-8 | 401 | 3.953125 | 4 | [] | no_license | class Person
attr_accessor :name, :age
def initialize(name, age)
@name = name
@age = age
end
def to_s
puts @name
puts @age
end
end
class Superhero < Person
def initialize(name, age, superpower)
@name = name
@age = age
@superpower = superpower
end
def to_s
puts @superpower
end
end
jill = Person.new("Jill", 10)
bob = Superhero.new("Bob", 20, "Flies")
jill.to_s
bob.to_s | true |
f6699a66dec68a22a9c5acf99b4786262c60562b | Ruby | oieioi/sokoban | /app/models/question.rb | UTF-8 | 2,717 | 3.25 | 3 | [] | no_license | class Question < ApplicationRecord
belongs_to :user
validates :name, presence: true
validates :map, presence: true
validate :validate_map
before_validation :sanitize_map
# TODO enum
TILES = {
empty: 'e',
new_line: 'n',
player: 'p',
box: 'b',
right_place: 'r',
wall: 'w',
}.freeze
def map2array
@arrayed_map ||= map.split('')
.reduce([[]]) { |result, string|
if string == TILES[:new_line]
result << []
else
result.last << string
end
result
}
end
def tile(x:, y:, **)
line = map2array[y]
line.try(:[], x)
end
def up_point(x:, y:, **)
{x: x, y: y - 1}
end
def down_point(x:, y:, **)
{x: x, y: y + 1}
end
def right_point(x:, y:, **)
{x: x + 1, y: y}
end
def left_point(x:, y:)
{x: x - 1, y: y}
end
def player_point
x = nil
y = map2array.index { |line| x = line.index(TILES[:player]) }
{x: x, y: y}
end
%w[up down right left].each do |direction|
define_method "move_#{direction}!" do
if send("player_can_move_#{direction}?")
current_player = {movable: TILES[:empty]}.merge player_point
new_player = {movable: TILES[:player]}.merge send("#{direction}_point", player_point)
replace!(current_player)
replace!(new_player)
elsif send("player_can_push_#{direction}?")
current_player = {movable: TILES[:empty]}.merge player_point
box = {movable: TILES[:player]}.merge send("#{direction}_point", current_player)
new_box = {movable: TILES[:box]}.merge send("#{direction}_point", box)
replace!(current_player)
replace!(box)
replace!(new_box)
else
nil
end
end
# その方向に進めるか
define_method "player_can_move_#{direction}?" do
tile = tile(send("#{direction}_point", player_point))
return tile == TILES[:empty]
end
# 押せるか
define_method "player_can_push_#{direction}?" do
tile = tile(send("#{direction}_point", player_point))
# boxの上がempty, right_placeならok
if tile == TILES[:box]
next_tile = tile(send("#{direction}_point", send("#{direction}_point", player_point)))
result = [TILES[:empty], TILES[:right_place]].include?(next_tile)
return result
end
false
end
end
def replace!(x:, y:, movable:)
map = map2array
map[y][x] = movable
map
end
def show
map2array.each {|line|
line.each {|tile| print tile}
puts ''
}
nil
end
private
def validate_map
# TODO
return true
end
def sanitize_map
map.gsub!(/\r/, '')
.gsub!(/\n/, 'n')
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.