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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
a59debb129daee6b3f3ec6ed18c32d80d2691f46 | Ruby | chenghaow/ComStock | /resources/measures/simulation_settings/tests/measure_test.rb | UTF-8 | 11,649 | 2.609375 | 3 | [
"BSD-2-Clause"
] | permissive | # ComStock™, Copyright (c) 2020 Alliance for Sustainable Energy, LLC. All rights reserved.
# See top level LICENSE.txt file for license terms.
# insert your copyright here
require 'openstudio'
require 'openstudio/measure/ShowRunnerOutput'
require 'minitest/autorun'
require_relative '../measure.rb'
require 'fileutils'
class SimulationSettingsTest < Minitest::Test
def test_defaults
# create an instance of the measure
measure = SimulationSettings.new
# create runner with empty OSW
osw = OpenStudio::WorkflowJSON.new
runner = OpenStudio::Measure::OSRunner.new(osw)
# load the test model
translator = OpenStudio::OSVersion::VersionTranslator.new
path = "#{File.dirname(__FILE__)}/example_model.osm"
model = translator.loadModel(path)
assert(!model.empty?)
model = model.get
# get arguments
arguments = measure.arguments(model)
argument_map = OpenStudio::Measure.convertOSArgumentVectorToMap(arguments)
# create hash of argument values.
# If the argument has a default that you want to use, you don't need it in the hash
args_hash = {}
# using defaults values from measure.rb for other arguments
# populate argument with specified hash value if specified
arguments.each do |arg|
temp_arg_var = arg.clone
if args_hash.key?(arg.name)
assert(temp_arg_var.setValue(args_hash[arg.name]))
end
argument_map[arg.name] = temp_arg_var
end
# run the measure
measure.run(model, runner, argument_map)
result = runner.result
# show the output
show_output(result)
# assert that it ran correctly
assert_equal('Success', result.value.valueName)
# Timestep
assert_equal(4, model.getTimestep.numberOfTimestepsPerHour, 'Timestep is wrong')
# Daylight savings
dst_control = model.getRunPeriodControlDaylightSavingTime
start_dst = dst_control.getString(1).get
end_dst = dst_control.getString(2).get
assert_equal('2nd Sunday in March', start_dst, 'DST start wrong')
assert_equal('1st Sunday in November', end_dst, 'DST end wrong')
# Run period
run_period = model.getRunPeriod
assert_equal(1, run_period.getBeginMonth, 'Run period begin month wrong')
assert_equal(1, run_period.getBeginDayOfMonth, 'Run period begin day wrong')
assert_equal(12, run_period.getEndMonth, 'Run period end month wrong')
assert_equal(31, run_period.getEndDayOfMonth, 'Run period end day wrong')
# Translate to IDF to check start day of week
ft = OpenStudio::EnergyPlus::ForwardTranslator.new
idf = ft.translateModel(model)
# Year
yr_desc_idf = idf.getObjectsByType('RunPeriod'.to_IddObjectType)[0]
assert_equal('2009', yr_desc_idf.getString(3).get)
assert_equal('2009', yr_desc_idf.getString(6).get)
assert_equal('Thursday', yr_desc_idf.getString(7).get, 'Day of week for start day is wrong') # start day 1/1/2009 is a Thursday
# save the model to test output directory
output_file_path = "#{File.dirname(__FILE__)}//output/test_defaults.osm"
model.save(output_file_path, true)
end
def test_chosen_start_and_mid_year_start_day
# create an instance of the measure
measure = SimulationSettings.new
# create runner with empty OSW
osw = OpenStudio::WorkflowJSON.new
runner = OpenStudio::Measure::OSRunner.new(osw)
# load the test model
translator = OpenStudio::OSVersion::VersionTranslator.new
path = "#{File.dirname(__FILE__)}/example_model.osm"
model = translator.loadModel(path)
assert(!model.empty?)
model = model.get
# get arguments
arguments = measure.arguments(model)
argument_map = OpenStudio::Measure.convertOSArgumentVectorToMap(arguments)
# create hash of argument values.
# If the argument has a default that you want to use, you don't need it in the hash
args_hash = {
'calendar_year' => 0,
'jan_first_day_of_wk' => 'Tuesday', # 2002 starts on a Tuesday
'begin_month' => 4,
'begin_day' => 10
}
# using defaults values from measure.rb for other arguments
# populate argument with specified hash value if specified
arguments.each do |arg|
temp_arg_var = arg.clone
if args_hash.key?(arg.name)
assert(temp_arg_var.setValue(args_hash[arg.name]))
end
argument_map[arg.name] = temp_arg_var
end
# run the measure
measure.run(model, runner, argument_map)
result = runner.result
# show the output
show_output(result)
# assert that it ran correctly
assert_equal('Success', result.value.valueName)
# Timestep
assert_equal(4, model.getTimestep.numberOfTimestepsPerHour, 'Timestep is wrong')
# Run period
run_period = model.getRunPeriod
assert_equal(4, run_period.getBeginMonth, 'Run period begin month wrong')
assert_equal(10, run_period.getBeginDayOfMonth, 'Run period begin day wrong')
assert_equal(12, run_period.getEndMonth, 'Run period end month wrong')
assert_equal(31, run_period.getEndDayOfMonth, 'Run period end day wrong')
# Translate to IDF to check start day of week
ft = OpenStudio::EnergyPlus::ForwardTranslator.new
idf = ft.translateModel(model)
# Year
run_period_idf = idf.getObjectsByType('RunPeriod'.to_IddObjectType)[0]
assert_equal('2002', run_period_idf.getString(3).get) # 2002 is closest year to 2009 where Jan 1st falls on a Tuesday
assert_equal('2002', run_period_idf.getString(6).get)
assert_equal('Wednesday', run_period_idf.getString(7).get, 'Day of week for start day is wrong') # start day 4/10/2002 is a Friday
# save the model to test output directory
output_file_path = "#{File.dirname(__FILE__)}//output/test_chosen_start_and_mid_year_start_day.osm"
model.save(output_file_path, true)
end
def test_actual_2012
# create an instance of the measure
measure = SimulationSettings.new
# create runner with empty OSW
osw = OpenStudio::WorkflowJSON.new
runner = OpenStudio::Measure::OSRunner.new(osw)
# load the test model
translator = OpenStudio::OSVersion::VersionTranslator.new
path = "#{File.dirname(__FILE__)}/example_model.osm"
model = translator.loadModel(path)
assert(!model.empty?)
model = model.get
# get arguments
arguments = measure.arguments(model)
argument_map = OpenStudio::Measure.convertOSArgumentVectorToMap(arguments)
# create hash of argument values.
# If the argument has a default that you want to use, you don't need it in the hash
args_hash = {
'calendar_year' => 2012,
'begin_month' => 1,
'begin_day' => 1,
'end_month' => 12,
'end_day' => 30
}
# using defaults values from measure.rb for other arguments
# populate argument with specified hash value if specified
arguments.each do |arg|
temp_arg_var = arg.clone
if args_hash.key?(arg.name)
assert(temp_arg_var.setValue(args_hash[arg.name]))
end
argument_map[arg.name] = temp_arg_var
end
# run the measure
measure.run(model, runner, argument_map)
result = runner.result
# show the output
show_output(result)
# assert that it ran correctly
assert_equal('Success', result.value.valueName)
# Timestep
assert_equal(4, model.getTimestep.numberOfTimestepsPerHour, 'Timestep is wrong')
# Daylight savings
dst_control = model.getRunPeriodControlDaylightSavingTime
start_dst = dst_control.getString(1).get
end_dst = dst_control.getString(2).get
assert_equal('2nd Sunday in March', start_dst, 'DST start wrong')
assert_equal('1st Sunday in November', end_dst, 'DST end wrong')
# Run period
run_period = model.getRunPeriod
assert_equal(1, run_period.getBeginMonth, 'Run period begin month wrong')
assert_equal(1, run_period.getBeginDayOfMonth, 'Run period begin day wrong')
assert_equal(12, run_period.getEndMonth, 'Run period end month wrong')
assert_equal(30, run_period.getEndDayOfMonth, 'Run period end day wrong')
# Translate to IDF to check start day of week
ft = OpenStudio::EnergyPlus::ForwardTranslator.new
idf = ft.translateModel(model)
# Year
yr_desc_idf = idf.getObjectsByType('RunPeriod'.to_IddObjectType)[0]
assert_equal('2012', yr_desc_idf.getString(3).get)
assert_equal('2012', yr_desc_idf.getString(6).get)
assert_equal('Sunday', yr_desc_idf.getString(7).get, 'Day of week for start day is wrong') # start day 1/1/2012 is a Sunday
# save the model to test output directory
output_file_path = "#{File.dirname(__FILE__)}//output/test_actual_2012.osm"
model.save(output_file_path, true)
end
def test_actual_2012_mid_year_start_day_no_dst
# create an instance of the measure
measure = SimulationSettings.new
# create runner with empty OSW
osw = OpenStudio::WorkflowJSON.new
runner = OpenStudio::Measure::OSRunner.new(osw)
# load the test model
translator = OpenStudio::OSVersion::VersionTranslator.new
path = "#{File.dirname(__FILE__)}/example_model.osm"
model = translator.loadModel(path)
assert(!model.empty?)
model = model.get
# get arguments
arguments = measure.arguments(model)
argument_map = OpenStudio::Measure.convertOSArgumentVectorToMap(arguments)
# create hash of argument values.
# If the argument has a default that you want to use, you don't need it in the hash
args_hash = {
'enable_dst' => false,
'calendar_year' => 2012,
'jan_first_day_of_wk' => 'Tuesday',
'begin_month' => 2,
'begin_day' => 11,
'end_month' => 12,
'end_day' => 30
}
# using defaults values from measure.rb for other arguments
# populate argument with specified hash value if specified
arguments.each do |arg|
temp_arg_var = arg.clone
if args_hash.key?(arg.name)
assert(temp_arg_var.setValue(args_hash[arg.name]))
end
argument_map[arg.name] = temp_arg_var
end
# run the measure
measure.run(model, runner, argument_map)
result = runner.result
# show the output
show_output(result)
# assert that it ran correctly
assert_equal('Success', result.value.valueName)
# Timestep
assert_equal(4, model.getTimestep.numberOfTimestepsPerHour, 'Timestep is wrong')
# Run period
run_period = model.getRunPeriod
assert_equal(2, run_period.getBeginMonth, 'Run period begin month wrong')
assert_equal(11, run_period.getBeginDayOfMonth, 'Run period begin day wrong')
assert_equal(12, run_period.getEndMonth, 'Run period end month wrong')
assert_equal(30, run_period.getEndDayOfMonth, 'Run period end day wrong')
# Translate to IDF to check start day of week
ft = OpenStudio::EnergyPlus::ForwardTranslator.new
idf = ft.translateModel(model)
# Year
run_period_idf = idf.getObjectsByType('RunPeriod'.to_IddObjectType)[0]
assert_equal('2012', run_period_idf.getString(3).get)
assert_equal('2012', run_period_idf.getString(6).get)
assert_equal('Saturday', run_period_idf.getString(7).get, 'Day of week for start day is wrong') # start day 2/11/2012 is a Saturday
# Daylight savings
dst_control_idfs = idf.getObjectsByType('RunPeriodControl:DaylightSavingTime'.to_IddObjectType)
assert_equal(0, dst_control_idfs.size, 'Found unexpected RunPeriodControl:DaylightSavingTime object')
assert_equal('No', run_period_idf.getString(9).get)
# save the model to test output directory
output_file_path = "#{File.dirname(__FILE__)}//output/test_mid_year_start_day_no_dst.osm"
model.save(output_file_path, true)
end
end
| true |
1a93bfc9d9c7b949608c66db043e72c157986f03 | Ruby | Strausssa/StarFighterGame | /laser.rb | UTF-8 | 328 | 3.46875 | 3 | [] | no_license |
class Laser
SPEED = 10
attr_reader :x, :y
def initialize(x,y,angle)
@image = Gosu::Image.new("media/laser.png")
@x = x
@y = y
@angle = angle
end
def draw
@image.draw_rot(@x,@y, 1, @angle)
end
def move
@x += Gosu::offset_x(@angle, SPEED)
@y += Gosu::offset_y(@angle, SPEED)
end
end
| true |
dcd1c383f0b737c41619a4fd849028e45bbe7ac2 | Ruby | jamesm2013/speaking-grandma-onl01-seng-pt-012220 | /grandma.rb | UTF-8 | 191 | 2.578125 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive |
def speak_to_grandma
IF phase == "I LOVE YOU TO GRANDMA!"
return "I LOVE YOU TOO PUMPKIN!"
elsif PHASE == phase.DOWNCASE
"NO, NOT SINCE 1938!"
ELSE "HUH?! SPEAK UP, SONNY!"
end
end | true |
1fe56cb9c5b4becb4b952404c18d26c1211ea2e9 | Ruby | karino-minako/paiza_mihon | /level-up-exerise-books-2.rb | UTF-8 | 496 | 3.453125 | 3 | [] | no_license | # 入力される値
# 入力は以下のフォーマットで与えられます。
# a
# b
# 入力値最終行の末尾に改行が1つ入ります。
# 文字列は標準入力から渡されます。 標準入力からの値取得方法はこちらをご確認ください
# 期待する出力
# aとbを掛け算した数値を出力して下さい。
# 最後は改行し、余計な文字、空行を含んではいけません。
line = readlines.map(&:to_i)
puts line[0] * line[1] | true |
684a7a9cb4a2c2149629f5481fc1600f47ee6466 | Ruby | roberthead/head_music | /lib/head_music/style/guidelines/limit_octave_leaps.rb | UTF-8 | 526 | 2.5625 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
# Module for style guidelines.
module HeadMusic::Style::Guidelines; end
# A counterpoint guideline: Use a maximum of one octave leap.
class HeadMusic::Style::Guidelines::LimitOctaveLeaps < HeadMusic::Style::Annotation
MESSAGE = "Use a maximum of one octave leap."
def marks
return if octave_leaps.length <= 1
octave_leaps.map do |leap|
HeadMusic::Style::Mark.for_all(leap.notes)
end
end
private
def octave_leaps
melodic_intervals.select(&:octave?)
end
end
| true |
70d605caf3bd4cc709fa1fa4fc71a9aef8a4760c | Ruby | msimon42/flash_cards | /test/round_test.rb | UTF-8 | 899 | 3.171875 | 3 | [] | no_license | require 'minitest/autorun'
require 'minitest/pride'
require_relative '../lib/round'
require_relative '../lib/card'
require_relative '../lib/deck'
require_relative '../lib/turn'
class RoundTest < Minitest::Test
def setup
@card1 = Card.new("Test", "Test", :test)
@card2 = Card.new("test", "test", :other_test)
@cards = [@card1, @card2]
@deck = Deck.new(@cards)
@round = Round.new(@deck)
end
def test_existence
assert_instance_of Round, @round
end
def test_start
assert_nil nil, @round.start
end
def test_take_turn
assert_equal "Correct", @round.take_turn('Test', @card1)
end
def test_get_score
assert_equal 50, @round.get_score(1,2)
end
def test_get_score_by_cat
@round.take_turn('Test', @card1)
@round.take_turn('hello', @card2)
assert_equal ["Test: 100.0%", "Other Test: 0.0%"], @round.get_score_by_category
end
end
| true |
c81c1b022cdd299db5ef7bf7610f869a6ff07bbd | Ruby | SeanEmmers/OOD_challenge_one | /lib/secret_diary.rb | UTF-8 | 350 | 2.953125 | 3 | [] | no_license | require_relative 'key'
class SecretDiary
attr_reader :key, :diary
def initialize
@diary = ""
@key = Key.new
end
def add_entry(diary_entry)
fail 'Diary is locked' if key.locked? == true
@diary << diary_entry
'Entry Added'
end
def get_entries
fail 'Diary is locked' if key.locked? == true
@diary
end
end
| true |
63d5321dcec71c84a9d8d068f4f363b1dd280264 | Ruby | abcalvo/MC30-status-service | /mc30.rb | UTF-8 | 1,259 | 2.90625 | 3 | [
"MIT"
] | permissive | require 'nokogiri'
require 'open-uri'
require 'json'
class MC30
MC30_URL = 'http://mc30.es/'
# Parse traffic data and returns JSON
def self.status
doc = Nokogiri::HTML(open(MC30_URL))
traffic_data = doc.css('.trafico')
# Parse HTML, and get only the cars in tunnel:
# COCHES CIRCULANDO TÚNEL: 2583 => 2583 (regexp \d+)
total_cars_in_tunnel =
traffic_data.css('.width60.trafico_fechas .width60 h4').text
.match(/\d+/)
# Parse HTML, and get only the cars in MC30:
# TOTAL CALLE 30: 13070 => 13070 (regexp \d+$)
total_cars_in_mc30 =
traffic_data.css('.width60.trafico_fechas .width40 h4').text
.match(/\d+$/)
# Parse HTML, and get last update
time = Time.parse(traffic_data.css('.width40.trafico_fechas p > text()').text)
last_update = DateTime.parse(time.to_s)
# Parse HTML, and get the traffic alerts
alerts = Array.new
traffic_data.css('#slides p').each do |slide|
alerts << slide.text
end
data = {
last_update: last_update,
total_cars_in_tunnel: total_cars_in_tunnel,
total_cars_in_mc30: total_cars_in_mc30,
alerts: alerts
}
JSON.pretty_generate(data)
end
end
| true |
996595d6c5a5c2ff1a3e9241cf94108216594b55 | Ruby | caromedellin/phase-0 | /week-5/5-nums-to-st/my_solution.rb | UTF-8 | 1,741 | 4.34375 | 4 | [
"MIT"
] | permissive |
# Numbers to Commas Solo Challenge
# I spent [] hours on this challenge.
# Complete each step below according to the challenge directions and
# include it in this file. Also make sure everything that isn't code
# is commented in the file.
# 0. Pseudocode
# What is the input?
# What is the output? (i.e. What should the code return?)
# What are the steps needed to solve the problem?
# 1. Initial Solution
def separate_comma (random_num)
new_num = random_num.to_s.split ('')
i = 4
while i <= (new_num.length)
new_num.insert(-i, ",")
i += 4
end
puts new_num.join.to_s
end
# 2. Refactored Solution
# I can't think on a better way to refactor this, I still have to research more methods
# 3. Reflection
#What was your process for breaking the problem down? What different approaches did you consider?
#I knew I had to make it into an array and then split it and every 4 elements insert a comma in a way that did not replace the element
#Was your pseudocode effective in helping you build a successful initial solution?
# Yes it was because I'm not familiar with the ruby methods, getting there
#What Ruby method(s) did you use when refactoring your solution? What difficulties did you have implementing it/them? Did it/they significantly change the way your code works? If so, how?
# I haven0t been able to find a method that does what I want it too, the built in ruby methods seam to iterate over every element and I can't make them skip elements
#How did you initially iterate through the data structure?
# I wanted to use a for loop but I couldn't make it work
#Do you feel your refactored solution is more readable than your initial solution? Why?
# I personally liked my solution but I can be improved
| true |
19d5048be791ab7310c183591b5d8d345eab42e0 | Ruby | noku/university | /IPP/Lab#2/fafurl | UTF-8 | 2,664 | 3.09375 | 3 | [] | no_license | #!/usr/bin/env ruby
require 'optparse'
require 'singleton'
require 'json'
require 'time'
module Fafuri
# Defines the available parameters for the class
IPPStruct = Struct.new(:command, :headers, :list, :post, :argv, :verbose, :data)
class IPP
include Singleton
# Initialize the IPP and set defaults:
@@options = IPPStruct.new
@@options.command = "curl"
@@options.headers = ""
@@options.list = nil
@@options.verbose = false
@@options.post = false
@@options.argv = nil
@@options.data = {"data" => {} }
# Pass any other calls (getters/setters of to the IPP
# on to options as a way to easily set/get attribute values
def self.method_missing(method, *args, &block)
if @@options.respond_to?(method)
@@options.send(method, *args, &block)
else
super(method, *args)
end
end
def self.result
res = ""
res << options.command
res << " -v" if options.verbose
options_list << " -X POST" if options.post
options_list << " -d \"#{format_data}\"" unless options.data["data"].empty?
res << (options_list << " #{options.argv}").join(" \\\n ")
end
def self.data key, value
options.data["data"][key] = value
end
def self.options_list
options.list ||= options.headers.split(/;\s?/).map { |h| " -H \"#{format_header(h)}\"" }
end
def self.format_header hdr
hdr.gsub(/:\s?/, ": ")
end
def self.format_data
JSON.pretty_generate(options.data).gsub(/"/, '\"').split("\n").join(" \\\n ")
end
def self.options
@@options
end
private_class_method :options, :format_data, :format_header, :options_list
end
class OptParser
def self.parse(args)
IPP.argv = args.last
opts = OptionParser.new do |parser|
parser.separator ""
parser.separator "Specific options:"
parser.on("-h", "--headers HEADERS", "Headers") { |headers| IPP.headers = headers }
parser.on("-v", "--verbose", "Run verbosely") { |verbose| IPP.verbose = verbose }
parser.on("-p", "--post", "With post") { |post| IPP.post = post }
parser.on("-f", "--faf STRING", "Faf param") { |faf| IPP.data "faf", faf }
parser.on("-hl", "--hello STRING", "Hello param") { |hello| IPP.data "hello", hello }
parser.on("-y", "--you STRING", "you") { |you| IPP.data "you", you }
parser.on("-he", "--hey STRING", "hey") { |hey| IPP.data "hey", hey }
parser.on("-t", "--time STRING", "time") { |time| IPP.data "time", Time.now.strftime("%H:%M") }
end
opts.parse!(args)
end
end
end
Fafuri::OptParser.parse(ARGV)
puts Fafuri::IPP.result
| true |
1b4c26f556f3bbcf0f691ee185c3b90db3d79ca1 | Ruby | yixia-team/giphy-dumper | /main.rb | UTF-8 | 2,089 | 3.09375 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
require 'rubygems'
require 'bundler/setup'
require "open-uri"
require 'active_support'
require 'active_support/core_ext' # to_query support
#require 'byebug'
if ARGV.length == 0
puts """At least one keyword should be given.
Example: ./main.rb cat dog anime:200
Exit now."""
abort # An unsuccessful exit.
end
ARGV.each_with_index do |original_keyword, i|
log_suffix = "[#{i+1}/#{ARGV.length}] "
puts log_suffix + "Now searching keyword: #{original_keyword}"
# Parse argv.
if original_keyword.include? ":"
keyword, limit = original_keyword.split(":")
else
keyword = original_keyword
limit = 25
end
# Load offset from file.
offset_file = "./incoming/#{keyword}/.offset"
offset = 0
offset = File.new(offset_file, "r").gets.to_i if File.exists?(offset_file)
# Init local directory.
directory = "./incoming/#{keyword}/"
system 'mkdir', '-p', directory
keyword = keyword.gsub "+", " " # for to_query
# WARNING: using public API key in this case, should be replaced with your own.
query ={ api_key: "dc6zaTOxFJmzC" , q: keyword.strip, limit: limit, offset: offset }
search_url = "http://api.giphy.com/v1/gifs/search?" + query.to_query
puts log_suffix + "Search URL: #{search_url}"
# Get list.
res = JSON.parse(open(search_url).read)["data"]
res = res.map do |r|
{url: r["images"]["original"]["url"], filename: r["id"] + ".gif"}
end
# Download.
res.each_with_index do |target, j|
if File.exists?(directory + target[:filename])
puts log_suffix + "[#{j+1}/#{res.length}] #{target[:filename]} exists. Skipped."
next
end
print log_suffix + "[#{j+1}/#{res.length}] Now downloading #{directory + target[:filename]} ...... "
open(target[:url]) do |f|
File.open(directory + target[:filename], "wb") do |file|
file.puts f.read
end
end
print "DONE.\n"
end
# Write offset count into .offset file.
File.open(offset_file, "w") { |file| file.puts offset + limit }
puts log_suffix + "Keyword #{keyword} finished.\n"
end
puts "\n\nALL DONE. ENJOY!!!"
exit
| true |
418dca588b751adbcf0c18d332fdce450ea2766e | Ruby | yuzu-r/maigo-bot | /src/classes/train.rb | UTF-8 | 2,538 | 3.15625 | 3 | [] | no_license | require_relative '../lib/maigodb'
class Train
attr_accessor :route, :conductor, :show_boss
def initialize
# route is an array of _id from registered raids/eggs
@route = []
@conductor = nil
@show_boss = false
end
def show
if @route.count == 0
return "Nowhere. Aw."
else
raid_string = ""
@route.each_with_index do |r, i|
raid = get_raid(r)
first_mark = i == 0 ? '**' : ''
next_mark = i == @route.count - 1 ? '' : "\n >> "
raid_boss = @show_boss && raid['boss'] ? '(' + raid['boss'] + ') ' : ''
raid_string += first_mark + raid['gym'] + ' (' + raid['despawn_time'].strftime("%-I:%M") + ')' + ' ' + raid_boss + first_mark + next_mark
end
return raid_string
end
end
def count
return @route.count
end
def list
if @route.count == 0
return 'There are no stops on the route. Add some!'
else
list = ""
@route.each_with_index do |r, i|
raid = get_raid(r)
numbering = (i+1).to_s + ') '
raid_boss = raid['boss'] ? '(' + raid['boss'] + ') ' : ''
despawn_time = '(' + raid['despawn_time'].strftime("%-I:%M") + ')'
list += numbering + raid['gym'] + ' ' + raid_boss + despawn_time + "\n"
end
return list
end
end
def skip(route_index)
# reminder: route_index starts at 1
if @route.count > 0 && route_index <= @route.count && route_index > 0
@route.delete_at(route_index - 1)
return "Skipping a stop... the route is now #{self.show}."
else
return "Could not find that stop to skip."
end
end
def set(raid_index, raids)
raid_array = raid_index.split(',').map{ |i| i.to_i }
# raid index starts at 1, raids starts at 0
raid_array.each do |r_index|
if r_index > raids.count
next
end
raid = raids[r_index-1]['_id']
# ignore the raid if it already in the route
if !@route.include?(raid)
@route.push raid
end
end
return "The route is now #{self.show}"
end
def stop
@route = []
return "The route has been destroyed. Use `set` to define a new route."
end
def first
if @route.first
raid = get_raid(@route.first)
return raid
else
return nil
end
end
def next
if @route
@route.shift
return self.show
else
return nil
end
end
def insert(insert_before, raid_id)
if insert_before > @route.count
# assume user wants to stick it at the end
@route.push raid_id
else
# insert_before is 1-based, not 0-based
@route.insert(insert_before-1, raid_id)
end
return self.show
end
def toggle_boss
@show_boss = !@show_boss
return @show_boss
end
end | true |
a0d65a1a59aa69c5e1b2b21f417d4f16448f1222 | Ruby | sachinsaxena1996/cambridge | /array_map.rb | UTF-8 | 290 | 3.640625 | 4 | [] | no_license | class ArrayMap < Array
def new
super
end
def my_map(&block)
result = []
if !block.nil?
each { |element|
result << block.call(element)
}
end
result
end
end
new_array = ArrayMap.new([2, 100, 10, 4])
new_array = new_array.my_map {|element|
element + 1
}
p new_array
| true |
7db0539f24b2825af2937b9709be229f6883faae | Ruby | kirbyk/spending | /lib/tasks/addPlaidCategories.rake | UTF-8 | 1,141 | 2.578125 | 3 | [] | no_license | require 'unirest'
desc 'adds plaid categories into the DB'
task :addPlaidCategories => :environment do
responses = Unirest.get 'https://tartan.plaid.com/categories'
responses.body.each do |cat|
if Category.find_by( plaid_id: cat['_id']).present?
next
end
high = cat['hierarchy']
if high.length == 1
c = CategoryOne.create name: high.last, plaid_id: cat['_id']
elsif high.length == 2
parent_name = high[0]
c = CategoryTwo.create plaid_id: cat['_id'], name: high.last,
parent_name: parent_name
elsif high.length == 3
parent_name = high[1]
c = CategoryThree.create plaid_id: cat['_id'], name: high.last,
parent_name: parent_name
end
end
CategoryTwo.all.each do |cat|
p = CategoryOne.find_by name: cat.parent_name
cat.parent_id = p.id
p.child_id = cat.id
cat.save
p.save
end
CategoryThree.all.each do |cat|
p = CategoryTwo.find_by name: cat.parent_name
cat.parent_id = p.id
p.child_id = cat.id
cat.save
p.save
end
Category.all.each do |cat|
ap cat
end
end
| true |
4a4df626362c80fe42badf9929e2fa516f94a497 | Ruby | doggerel/rails | /lucky_numbers/vendor/plugins/luckynumbers/lib/luckynumbers.rb | UTF-8 | 406 | 2.625 | 3 | [
"MIT"
] | permissive | module Luckynumbers
module InstanceMethods
def lucky_number
id.to_i % 10
end
def self.include(base)
base.extend ClassMethods
end
end
module ClassMethods
def find_by_lucky_number(number)
find(:all, :conditions => ["id % 10 = ? ", number])
end
end
module ActsMacro
def acts_as_lucky(options = {})
send :include, InstanceMethods
end
end
end
| true |
9413275d48a9c3f254929f9d65bc93d17ea434ee | Ruby | bechirsegni/Feed-Data | /count.rb | UTF-8 | 546 | 3.140625 | 3 | [] | no_license | require 'json'
def words(file)
frequency = Hash.new(0)
input_file = File.open(file, 'r')
output_file = File.open("#{file}frequency.txt", 'w')
input_file.read.downcase.scan(/\b[a-z]{3,16}\b/) {|word| frequency[word] = frequency[word] + 1}
frequency.keys.sort.each{|key| output_file.print key,' => ',frequency[key], "\n"}
return frequency
end
def json(data, filename)
sorted = data.sort_by {|_key, value| value}.reverse.to_h
final_data = sorted.to_json
File.open("#{filename}.json","w") do |f|
f.write(final_data)
end
end
| true |
b4803fe26b61484a71e09a21699f3811a8e61b6a | Ruby | RyN21/backend_module_0_capstone | /day_2/exercises/iteration.rb | UTF-8 | 1,132 | 4.34375 | 4 | [] | no_license | # In the below exercises, write code that achieves
# the desired result. To check your work, run this
# file by entering the following command in your terminal:
# `ruby day_2/exercises/iteration.rb`
# Example: Write code that iterates through a list of animals
# and print each animal:
animals = ["Zebra", "Giraffe", "Elephant"]
animals.each do |animal|
p animal
end
# Write code that iterates through a list of animals and prints
# "The <animal> is awesome!" for each animal:
animals.each do |animal|
p "The #{animal} is awesome!"
end
# Write code that stores an array of foods in a variable,
# then iterates over that array to print
# "Add <food> to shopping list" for each food item:
foods = ["corn", "rice", "beans", "soup", "bread"]
foods.each do |foods|
p "Add #{foods} to the shopping list"
end
# Write code that stores an array of numbers in a variable,
# then iterates over that array to print doubles of each number:
numbers = [1, 2, 5, 7, 12, 15, 21, 21, 2, 577, 34, 75, 577]
numbers.each do |numbers|
p numbers & numbers
end
p numbers & numbers
p numbers.uniq
# not sure how to just call out the doubles
| true |
5e9e870074f2883f723fc697895cde63bbe0e1ff | Ruby | LoveMyData/onkaparinga | /scraper.rb | UTF-8 | 3,107 | 2.625 | 3 | [] | no_license | require 'scraperwiki'
require 'mechanize'
def is_valid_year(date_str, min=2004, max=DateTime.now.year)
if ( date_str.scan(/^(\d)+$/) )
if ( (min..max).include?(date_str.to_i) )
return true
end
end
return false
end
unless ( is_valid_year(ENV['MORPH_PERIOD'].to_s) )
ENV['MORPH_PERIOD'] = DateTime.now.year.to_s
end
puts "Getting data in year `" + ENV['MORPH_PERIOD'].to_s + "`, changable via MORPH_PERIOD environment"
base_url = "http://pathway.onkaparinga.sa.gov.au/ePathway/Production/Web/"
comment_url = "mailto:mail@onkaparinga.sa.gov.au"
# get the right cookies
agent = Mechanize.new
agent.user_agent_alias = 'Mac Safari'
page = agent.get base_url + "default.aspx"
# get to the page I can enter DA search
page = agent.get base_url + "GeneralEnquiry/EnquiryLists.aspx?ModuleCode=LAP"
# local DB lookup if DB exist and find out what is the maxDA number
sequences = {1=>1, 6=>6000, 8=>8000};
sql = "select council_reference from data where `council_reference` like '%/#{ENV['MORPH_PERIOD']}'"
results = ScraperWiki.sqliteexecute(sql) rescue false
if ( results )
results.each do |result|
maxDA = result['council_reference'].gsub!("/#{ENV['MORPH_PERIOD']}", '')
case maxDA.to_i
when (6000..7999)
if maxDA.to_i > sequences[6]
sequences[6] = maxDA.to_i
end
when (8000..9999)
if maxDA.to_i > sequences[8]
sequences[8] = maxDA.to_i
end
else
if maxDA.to_i > sequences[1]
sequences[1] = maxDA.to_i
end
end
end
end
sequences.each do |index, sequence|
i = sequence
error = 0
continue = true
while continue do
form = page.form
form.field_with(:name=>'ctl00$MainBodyContent$mGeneralEnquirySearchControl$mTabControl$ctl04$mFormattedNumberTextBox').value = i.to_s + '/' + ENV['MORPH_PERIOD'].to_s
button = form.button_with(:value => "Search")
list = form.click_button(button)
table = list.search("table.ContentPanel")
unless ( table.empty? )
error = 0
tr = table.search("tr.ContentPanel")
record = {
'council_reference' => tr.search('a').inner_text,
'address' => tr.search('span')[3].inner_text,
'description' => tr.search('span')[2].inner_text.gsub("\n", '. ').squeeze(' '),
'info_url' => base_url + 'GeneralEnquiry/' + tr.search('a')[0]['href'],
'comment_url' => comment_url,
'date_scraped' => Date.today.to_s,
'date_received' => Date.parse(tr.search('span')[1].inner_text).to_s,
}
if (ScraperWiki.select("* from data where `council_reference`='#{record['council_reference']}'").empty? rescue true)
puts "Saving record " + record['council_reference'] + ", " + record['address']
# puts record
ScraperWiki.save_sqlite(['council_reference'], record)
else
puts 'Skipping already saved record ' + record['council_reference']
end
else
error += 1
end
# increase i value and scan the next DA
i += 1
if error == 10
continue = false
end
end
end
| true |
a15a50bf1a7f67f97d74554c473ac3179d7fcaa0 | Ruby | daa5417/RubyClass | /comparison.rb | UTF-8 | 50 | 2.765625 | 3 | [] | no_license | puts 1 > 2
puts 1 < 2
puts 5 >= 5
puts 5 <= 4 | true |
fd88b68623a3f59bcb1711f207ed1deccaf517bb | Ruby | ObaldThePedro/looping-while-until-london-web-051319 | /lib/until.rb | UTF-8 | 139 | 2.609375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def using_until(phrase)
levitation_force = 6
#your code here
until levitation_force == 10
puts phrase
levitation_force += 1
end
| true |
a5b5170697b5e55865762cf6a071d0b4e0ad8b10 | Ruby | radixhound/mockserver | /mockserver-client-ruby/lib/mockserver/model/header.rb | UTF-8 | 866 | 2.546875 | 3 | [
"Apache-2.0"
] | permissive | # encoding: UTF-8
require 'hashie'
require_relative './array_of'
#
# A class to model headers in payloads.
# @author:: Nayyara Samuel (mailto: nayyara.samuel@opower.com)
#
module MockServer::Model
# A class that only stores strings
class Strings < ArrayOf
def child_class
String
end
end
# Model for header
class Header < Hashie::Dash
include Hashie::Extensions::MethodAccess
include Hashie::Extensions::IgnoreUndeclared
include Hashie::Extensions::Coercion
property :name, required: true
property :values, default: Strings.new([])
coerce_key :name, String
coerce_key :values, Strings
end
# A collection that only stores headers
class Headers < ArrayOf
def child_class
Header
end
end
# DSL methods for header
module DSL
def header(key, *value)
Header.new(name: key, values: value)
end
end
end
| true |
e25be4adf7e49eda1cb21f9cab38312258956636 | Ruby | kimihito/whitehall | /db/data_migration/20130225142023_add_detailed_guidance_categories_for_dcms.rb | UTF-8 | 965 | 2.53125 | 3 | [] | no_license | [
['Development of the arts, sport and heritage for local communities', 'Guidance and relevant data for local authorities, private investors and grant-making bodies.', 'housing/local-councils', 'Local councils and services'],
['Understanding and asserting your statutory rights', 'Duties of government and local authorities to uphold equality and provide services to citizens.', 'citizenship/government', 'Living in the UK, government and democracy']
].each do |row|
title, description, parent_tag, parent_title = row
unless category = MainstreamCategory.where(title: title).first
category = MainstreamCategory.create(
title: title,
slug: title.parameterize,
parent_tag: parent_tag,
parent_title: parent_title,
description: description
)
if category
puts "Mainstream category '#{category.title}' created"
end
else
puts "Mainstream category '#{category.title}' already exists, skipping"
end
end
| true |
817aed0ad4f58a4addd896f15cfeb100977a9b21 | Ruby | cmoran92/dwolla-ruby | /examples/oauth.rb | UTF-8 | 855 | 2.578125 | 3 | [
"MIT"
] | permissive | # Include the Dwolla gem
require 'rubygems'
require 'pp'
require 'sinatra'
require 'dwolla'
# Include any required keys
require './_keys.rb'
# Instantiate a new Dwolla User client
Dwolla::api_key = @api_key
Dwolla::api_secret = @api_secret
# Constants...
redirect_uri = 'http://localhost:4567/oauth_return'
# STEP 1:
# Create an authentication URL
# that the user will be redirected to
get '/' do
authUrl = Dwolla::OAuth.get_auth_url(redirect_uri)
"To begin the OAuth process, send the user off to <a href=\"#{authUrl}\">#{authUrl}</a>"
end
# STEP 2:
# Exchange the temporary code given
# to us in the querystring, for
# a never-expiring OAuth access token
get '/oauth_return' do
code = params['code']
token = Dwolla::OAuth.get_token(code, redirect_uri)
"Your never-expiring OAuth access token is: <b>#{token}</b>"
end
| true |
c4d731d6f713c29adaa82059424bc3d07426933c | Ruby | Darkcodelab/ruby-cookbook | /array_selection.rb | UTF-8 | 433 | 3.765625 | 4 | [] | no_license | array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
#selecting elements that satsify a given criteria
array.select { |a| a > 1 }
#Rejecting element that satisfy a given criteria
array.reject { |a| a < 3 }
array.drop_while { |a| a>5 }
#select and reject are Non-Destructive Selection. However if you add ! to the end of select or reject it will alter the original array
#Destructive Selection
arr.delete_if { |a| a<2}
arr.keep_if { |a| a<2}
| true |
51b00ba5b664d37d0b649967a0345e2623417a6a | Ruby | David24m/cinema-sql | /models/screenings.rb | UTF-8 | 1,508 | 2.96875 | 3 | [] | no_license | require_relative("../db/sql_runner")
class Screening
attr_reader :id
attr_accessor :film_times, :availability
def initialize( options )
@id = options['id'].to_i
@film_times = options['film_times']
@availability = options['availability']
end
def save()
db = PG.connect({ dbname: "cinema", host: "localhost"})
sql = "INSERT INTO screenings
(
film_times,
availability
)
VALUES
(
$1, $2
)
RETURNING id"
values = [@film_times, @availability]
screenings = SqlRunner.run( sql,values ).first
@id = screenings['id'].to_i
end
def Screening.all()
db = PG.connect({ dbname: "cinema", host: "localhost"})
sql = "SELECT * FROM screenings"
values = []
screenings = SqlRunner.run(sql, values)
result = screenings.map { |screening| Screening.new (screening)}
return result
end
def Screening.delete_all()
db = PG.connect({ dbname: "cinema", host: "localhost"})
sql = "DELETE FROM screenings"
values = []
SqlRunner.run(sql, values)
end
def delete()
db = PG.connect({ dbname: "cinema", host: "localhost"})
sql "DELETE FROM screenings
WHERE id = $1"
values = [@id]
SqlRunner.run(sql, values)
end
def update()
db= PG.connect({ dbname: "cinema", host: "localhost"})
sql = "UPDATE screenings
SET (film_times, availability)
=
($1, $2)
WHERE id = $3
"
values = [@film_times, @availability]
SqlRunner.run(sql, values)
end
end
| true |
f5bf6a18e5d0184b1dbbcb205d306883565ad342 | Ruby | bobbert/age13chargen | /db/seeds.rb | UTF-8 | 4,708 | 2.515625 | 3 | [] | no_license | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rake db:seed (or created alongside the db with db:setup).
#
# Examples:
#
# cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }])
# Mayor.create(name: 'Emanuel', city: cities.first)
srd_path = Dir.glob(Rails.root.to_s + "/db/srd_core.json").first
srd = JSON.parse(open(srd_path).read, :symbolize_names=>true)
srd_lookup = {}
reverse_lookup = {}
# creating defaults
top_keys = [:tiers, :ability_scores, :point_buys, :levels, :races, :character_classes, :powers, :talents, :feats]
top_keys.each do |top_key|
srd[top_keys] ||= []
srd_lookup[top_key] = {}
end
fields = {
tiers: [:name, :multiplier],
ability_scores: [:name, :abbrev],
point_buys: [:ability_score, :cost],
levels: [:level, :hpMultiplier, :abilityBonuses],
races: [:name, :alternateName, :abilityBonuses],
character_classes: [:name, :baseHp, :recoveryDie, :basePd, :baseMd, :defaultAc, :numTalents,
:numBackgrounds, :default1hWeaponDie, :default2hWeaponDie, :defaultThrownDie, :defaultBowDie,
:shieldPenalty, :meleeMissDmg, :rangedMissDmg, :abilityBonuses, :powersByLevel],
powers: [:name, :type, :attacktype, :usage, :description],
talents: [:name, :type, :description],
feats: [:name, :description, :prereq]
}
assign_to_reverse_lookup = lambda do |type, key, value|
reverse_lookup[type] ||= {}
reverse_lookup[type][key] = value
end
create_and_assign_to_srd_lookup = lambda do |clazz, clazz_obj, key_field|
record_name = clazz.to_s.underscore.pluralize.to_sym
if (fields[record_name])
# creating new ActiveModel record with only valid fields
clean_fields_obj = clazz_obj.slice(*fields[record_name])
record = clazz.new clean_fields_obj
srd_lookup[record_name][clazz_obj[key_field]] = record
end
end
#------------------------#
# seeding ActiveModel records without embedding
srd[:ability_scores].each do |ability_score_obj|
ability_score = AbilityScore.create! ability_score_obj
end
srd[:point_buys].each do |point_buy_obj|
point_buy = PointBuy.create! point_buy_obj
end
# seeding ActiveModel records that embed or are embedded by other records, in order from children to parents.
# Child records (Tier, Level, Feat, Power, Talent) get saved to SRD lookup object
# Parent records (CharacterClass, Race) get persisted to Mongo.
srd[:tiers].each do |tier_obj|
create_and_assign_to_srd_lookup.call(Tier, tier_obj, :name)
end
srd[:levels].each do |level_obj|
level_obj[:tier] = srd_lookup[:tiers][level_obj[:tier]] if level_obj[:tier] # Level -> Tier
create_and_assign_to_srd_lookup.call(Level, level_obj, :level)
end
srd[:feats].each do |feat_obj|
feat_obj[:tier] = srd_lookup[:tiers][feat_obj[:tier]] if feat_obj[:tier] # Feat -> Tier
create_and_assign_to_srd_lookup.call(Feat, feat_obj, :name)
end
srd[:talents].each do |talent_obj|
talent_obj[:tier] = srd_lookup[:talents][talent_obj[:tier]] if talent_obj[:tier] # Talent -> Tier
create_and_assign_to_srd_lookup.call(Talent, talent_obj, :name)
end
srd[:powers].each do |power_obj|
power_obj[:level] = srd_lookup[:powers][power_obj[:level]] if power_obj[:level] # Power -> Level
# power_obj[:feat] = srd_lookup[:powers][power_obj[:feat]] if power_obj[:feat] # Power -> Feat
create_and_assign_to_srd_lookup.call(Power, power_obj, :name)
end
srd[:races].each do |race_obj|
create_and_assign_to_srd_lookup.call(Race, race_obj, :name)
end
srd[:character_classes].each do |character_class_obj|
create_and_assign_to_srd_lookup.call(CharacterClass, character_class_obj, :name)
end
# performing child-parent associations
# Race -> Feat association: create association from JSON data, then embed feat into race
filtered_feats = srd_lookup[:feats].select {|featname, feat| (feat.prereq || {})[:race] }
feats_for_race = filtered_feats.each_with_object({}) {|kv, memo| memo[(kv[1].prereq || {})[:race]] = kv[1] }
srd[:races].each do |race_json_obj|
race_name = race_json_obj[:name]
race_obj = srd_lookup[:races][race_name]
race_obj.feats << feats_for_race[race_name]
end
# Power -> Feat association: create association from JSON data, then embed feat into race
filtered_feats = srd_lookup[:feats].select {|featname, feat| (feat.prereq || {})[:type] == 'Talent' }
srd[:talents].each do |talent_json_obj|
talent_name = talent_json_obj[:name]
talent_obj = srd_lookup[:talents][talent_name]
talent_obj.feats << filtered_feats[talent_name]
end
# saving root-level records
srd_lookup[:races].values.each {|race_obj| race_obj.save! }
srd_lookup[:character_classes].values.each {|character_class_obj| character_class_obj.save! }
| true |
3f4917b04a704c2852ea46fc34c02979147cf250 | Ruby | taskrabbit/smyte | /spec/config_spec.rb | UTF-8 | 2,176 | 2.515625 | 3 | [
"MIT"
] | permissive | require 'spec_helper'
describe "config" do
let (:config) { Smyte::Config.new }
describe "setters" do
it "gets and sets logger" do
config.logger.should == nil
config.logger = "log"
config.logger.should == "log"
end
end
describe "API keys" do
it "should freak out if not set" do
lambda{
config.api_key
}.should raise_error("Smyte api_key not set")
lambda{
config.api_secret
}.should raise_error("Smyte api_secret not set")
lambda{
config.webhook_secret
}.should raise_error("Smyte webhook_secret not set")
end
it "should use the one set" do
config.api_key = "a"
config.api_secret = "c"
config.webhook_secret = "d"
config.api_key.should == "a"
config.api_secret.should == "c"
config.webhook_secret.should == "d"
end
end
describe "Enablement" do
it "should default to true" do
config.enabled.should == true
config.enabled?.should == true
end
it "should be able to be set to boolean" do
config.enabled = false
config.enabled.should == false
config.enabled = true
config.enabled.should == true
end
it "should be able to be set to truthy stuff" do
config.enabled = "false"
config.enabled.should == false
config.enabled = "true"
config.enabled.should == true
config.enabled = 0
config.enabled.should == false
config.enabled = 1
config.enabled.should == true
end
end
describe "Integration" do
it "should connect through core class" do
Smyte.api_key = "test"
Smyte.api_key.should == "test"
lambda{
Smyte.api_secret
}.should raise_error("Smyte api_secret not set")
Smyte.api_secret = "secret"
Smyte.api_secret.should == "secret"
Smyte.webhook_secret = "hook"
Smyte.webhook_secret.should == "hook"
Smyte.logger.should == nil
Smyte.logger = "log"
Smyte.logger.should == "log"
Smyte.enabled?.should == true
Smyte.enabled.should == true
Smyte.enabled = false
Smyte.enabled?.should == false
end
end
end | true |
a686c985ba8e6599e70ae2fa4135509e17bcaf41 | Ruby | dtk/dtk-server | /lib/common_dsl/diff/qualified_key.rb | UTF-8 | 3,382 | 2.5625 | 3 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | #
# Copyright (C) 2010-2016 dtk contributors
#
# This file is part of the dtk project.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
module DTK
class CommonDSL::Diff
class QualifiedKey < ::DTK::DSL::QualifiedKey
# If this refers to element under a node than node object wil be returned; otherwise nil will be returned
# if component is asembly level
def self.parent_node?(qualified_key, assembly_instance)
if parent_key_elements = qualified_key.parent_key_elements?
if node_name = node_name_if_node?(parent_key_elements.last)
assembly_instance.get_node?([:eq, :display_name, node_name]) ||
fail(Error, "Unexpected that assembly '#{assembly_instance.display_name}' does not have a node with name '#{node_name}'")
end
end
end
# TODO: DTK-2938; think below shoudl be written in terms of parent_node? or its subfunctions node_name_if_node?(
# if node attribute returns [node_name, attribute_name]; otherwise returns nil
def self.is_node_attribute?(qualified_key)
key_elements = qualified_key.key_elements
if key_elements.size == 2 and key_elements[0].type.to_sym == :node and key_elements[1].type.to_sym == :attribute
node_name = key_elements[0].key
attribute_name = key_elements[1].key
[node_name, attribute_name]
end
end
ParentComponentInfo = Struct.new(:component_name, :node_name)
def parent_component_info
parent_key_elements = parent_key_elements? || fail("Unexpected that (#{self.inspect}) has no parent")
component_key_element = parent_key_elements.last
fail "Unexpected that parent_key_elements.last is not a component" unless component_key_element[:type] == :component
component_name = component_key_element[:key]
node_name = nil
if parent_key_elements.size > 1
node_key_element = parent_key_elements.last(2)[0]
node_name = node_name_if_node?(node_key_element) || fail("Unexpected that node_key_element is not a node")
end
ParentComponentInfo.new(component_name, node_name)
end
def parent_key_elements?
if key_elements.size > 1
key_elements[0..key_elements.size-2]
end
end
private
def self.node_name_if_node?(key_element)
if key_element[:type] == :node
key_element[:key]
elsif node_name = node_name_if_node_component?(key_element)
node_name
end
end
def node_name_if_node?(key_element)
self.class.node_name_if_node?(key_element)
end
def self.node_name_if_node_component?(key_element)
if key_element[:type] == :component
NodeComponent.node_name_if_node_component?(key_element[:key])
end
end
end
end
end
| true |
5936fb7dde2ea7b13afd409ad6f865d9e02fc14f | Ruby | Estelle-B262/Morpion0 | /Morpion2/lib/app/Player.rb | UTF-8 | 137 | 2.890625 | 3 | [] | no_license | class Player
attr_accessor :nom, :symbole
def initialize(nom,symbole)
@nom = nom
@symbole = symbole
end
end | true |
e5e6d11f1a2f7ef7d0f33d1f3e3815e14c24c19c | Ruby | pironim/hashozaur | /lib/hashozaur/camel_back_keys_hash.rb | UTF-8 | 1,012 | 3.296875 | 3 | [
"MIT"
] | permissive | module Hashozaur
class CamelBackKeysHash
def self.convert(object)
new.to_camelback_keys(object)
end
# Recursively converts Rubyish snake_case hash keys to camelBack JSON-style
# hash keys suitable for use with a JSON API.
def to_camelback_keys(object)
case object
when Array
object.map { |v| to_camelback_keys(v) }
when Hash
Hash[object.map { |k, v| [camelize_key(k), to_camelback_keys(v)] }]
else
object
end
end
private
def camelize_key(k)
if k.is_a? Symbol
camelize_back(k.to_s).to_sym
elsif k.is_a? String
camelize_back(k)
else
k
end
end
def camelize_back(snake_word)
word = camelize(snake_word)
if word != snake_word
word[0].downcase + word[1..-1]
else
snake_word
end
end
def camelize(snake_word)
snake_word.to_s.gsub(/\/(.?)/) { "::" + $1.upcase }.gsub(/(^|_)(.)/) { $2.upcase }
end
end
end
| true |
a55439ae93648721658ea113964db14e64aaaca0 | Ruby | omghax/einstein | /lib/einstein.rb | UTF-8 | 778 | 2.71875 | 3 | [
"MIT"
] | permissive | # Add ./lib to the load path.
$:.unshift File.dirname(__FILE__)
require 'einstein/parser.racc.rb'
require 'einstein/parser.rex.rb'
require 'einstein/expression'
require 'einstein/version'
module Einstein
# Raised when an undefined variable is referenced.
class ResolveError < StandardError # :nodoc:
end
# Parse the given +expression+ and return the AST as an instance of
# Einstein::Expression.
def self.parse(expression)
Expression.new(Parser.new.scan_str(expression))
end
# Evaluate the given +expression+ with the given +scope+. Any variables
# used by the +expression+, but undeclared in the +scope+, will cause a
# Einstein::ResolveError to be raised.
def self.evaluate(expression, scope = {})
parse(expression).evaluate(scope)
end
end
| true |
b3e6303627c497cfe02bb06d102292e295b0d879 | Ruby | Zrp200/chargen | /lib/types/normal.rb | UTF-8 | 712 | 3.390625 | 3 | [] | no_license | require 'simple-random'
class Normal
def initialize
@random_generator = SimpleRandom.new
@random_generator.set_seed
end
def handle(options)
extract_options(options)
if (!@min.nil? && !@max.nil?) && (@min > @max)
fail "Minimum #{@min} is greater than Maximum #{@max}."
end
value = @random_generator.normal(@mean, @std_dev).round
apply_limits(value)
end
private
def extract_options(options)
@mean = options['mean']
@std_dev = options['std_dev']
@min = options['min']
@max = options['max']
end
def apply_limits(value)
value = (@min && value < @min) ? @min : value
value = (@max && value > @max) ? @max : value
value
end
end
| true |
cc6225166a3b66542abeb5f9f897a8c6ae1f6063 | Ruby | TDobbert/App-Academy | /Ruby/poker/lib/card.rb | UTF-8 | 156 | 2.984375 | 3 | [] | no_license | class Card
attr_reader :card_value, :card_suit
def initialize(card_value, card_suit)
@card_value = card_value
@card_suit = card_suit
end
end
| true |
046ecaf051e46f70915b5f5ebc3576e8c87bd51e | Ruby | koremori/movies | /imdb.rb | UTF-8 | 3,453 | 3.59375 | 4 | [] | no_license | # frozen_string_literal: true
require 'csv'
require 'ostruct'
require 'date'
def reading_file(file_path) # => String
default_path = '/home/koremori/documents/rubycode/movies.txt'
File.exist?(file_path) ? File.read(file_path) : File.read(default_path)
end
def normalizing_movie_data(raw_data) # => multidimensional Array with Strings
CSV.parse(raw_data, col_sep: '|')
end
def movie_to_ostruct(movies) # => Array with OpenStruct
movies.map do |movie|
OpenStruct.new(link: movie[0],
title: movie[1],
shoot_year: movie[2].to_i,
origin: movie[3],
release_date: normalizing_dates(movie[4]),
genre: movie[5],
duration: movie[6].to_i,
rating: rating_calculation(movie[7]),
director: movie[8],
cast: movie[9])
end
end
def normalizing_dates(date)
datemod = case date.size
when 4
"#{date}-01-01"
when 7
"#{date}-01"
else
date
end
Date.parse(datemod)
end
def finding_movies(movies, title)
movies.select { |movie| movie[:title].include?(title) }
end
def sorted_by_duration(movies)
movies.sort_by { |movie| movie[:duration] }.reverse
end
def sorted_by_year(movies)
movies.sort_by { |movie| movie[:shoot_year] }
end
def sorted_by_last_name(movies)
movies.sort_by { |movie| movie[:director].split.last }.uniq { |movie| movie[:director] }
end
def sorted_by_genre(movies, genre)
movies.select { |movie| movie[:genre].include?(genre) }
end
def sorted_by_origin(movies, country)
movies.reject { |movie| movie[:origin].include?(country) }
end
def sorted_by_month(movies)
movies.sort_by { |date| date[:release_date].mon }
end
def counted_by_months(movies)
sorted_by_month(movies).each_with_object(Hash.new(0)) { |date, hash| hash[date[:release_date].strftime('%B')] += 1 }
end
def rating_calculation(rating)
'*' * ((rating.to_f - 8) * 10).round
end
def render_movie(movie)
puts "#{movie[:title]} #{movie[:rating]}"
end
def render_hash_movies(movie)
puts "#{movie[:title]} (#{movie[:release_date]}; #{movie[:genre]}) - #{movie[:duration]} min"
end
def render_directors(movie)
puts movie[:director].split.last
end
def render_with_dates(key, value)
puts "#{key}: #{value}"
end
movies_data = reading_file(ARGV.first.to_s) # ARRAY -> string
movies_array = normalizing_movie_data(movies_data) # string -> array with subarrays
movies_struct = movie_to_ostruct(movies_array) # array with subarrays -> array with OpenStruct
year_sorted_struct = sorted_by_year(movies_struct) # array with openstruct
puts "Movies which contain \"Max\" in title: \n"
finding_movies(movies_struct, 'Max').each { |movie| render_movie(movie) }
puts "5 longest movies: \n"
sorted_by_duration(movies_struct).first(5).each { |movie| render_hash_movies(movie) }
puts "10 comedies sorted by year: \n"
sorted_by_genre(year_sorted_struct, 'Comedy').first(10).each { |movie| render_hash_movies(movie) }
puts "Movies filmed outside USA: \n"
sorted_by_origin(year_sorted_struct, 'USA').each { |movie| render_hash_movies(movie) }
puts "All directors in alphabetic order: \n"
sorted_by_last_name(movies_struct).each { |movie| render_directors(movie) }
puts "Movies released overall in each month: \n"
counted_by_months(movies_struct).each { |key, value| render_with_dates(key, value) }
| true |
9bfe5939edc5dda214e2d28c9dc522811017e450 | Ruby | madelynrr/bloody_hogwarts | /spec/features/courses/index_spec.rb | UTF-8 | 792 | 2.671875 | 3 | [] | no_license | require 'rails_helper'
RSpec.describe "a user can visit course index page" do
it "shows all course names and number of students enrolled in each course" do
daad = Course.create(name: "Defense Against the Dark Arts")
muggles = Course.create(name: "Muggle Studies")
student_1 = Student.create(name: "Hermione Granger", age: 13, house: "Gryffindor")
student_2 = Student.create(name: "Harry Potter", age: 13, house: "Gryffindor")
student_3 = Student.create(name: "Ron Weasley", age: 11, house: "Gryffindor")
daad.students << student_1
daad.students << student_2
daad.students << student_3
muggles.students << student_1
visit '/courses'
expect(page).to have_content("Defense Against the Dark Arts: 3")
expect(page).to have_content("Muggle Studies: 1")
end
end
| true |
88e21482bc4f759c3546472a1c84e7d4cd86a7d6 | Ruby | MichaelA26/W1-Weekend-HW | /day_2/mini_lab.rb | UTF-8 | 256 | 3.5 | 4 | [] | no_license | def add(first_number, second_number)
return first_number + second_number
end
p add(2, 3)
def popdense(population, area)
return population / area
end
p popdense(5373000, 77933)
p "The population density of Mauritius is: #{popdense(5373000, 77933)}"
| true |
62f699c79a15c85bfb365861d0a1066daf734544 | Ruby | shelbipinkney/reverse-each-word-v-000 | /reverse_each_word.rb | UTF-8 | 323 | 2.9375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | def reverse_each_word(sentence)
sentence.split(" ").reverse.join(" ")
sentence.split(" ").collect do |word|
word.reverse
end.join(" ")
end
#string=""
#sentence.split(" ").reverse.join(" ")
#sentence.collect do |sentence| string<<"#{string}"
#string.collect do |sentence| string<<"#{string}"
| true |
11a50750952ace7ec95f9818a7bd5d551460cd2c | Ruby | pjotrp/bioruby-logger-plugin | /lib/bio/log/loggercli.rb | UTF-8 | 3,771 | 2.671875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'singleton'
module Bio
module Log
class LoggerPlusGlobal
include Singleton
attr_accessor :outputter_type, :trace
end
module CLI
# Parse and store global logger type
def CLI::logger name
LoggerPlusGlobal.instance.outputter_type = case name
when 'stderr' then :stderr
when 'stdout' then :stdout
else
{:file => { :filename => name }}
end
end
# Parse and store trace options
def CLI::trace s
level = nil
sub_level = nil
filter = nil
opts = {}
# ---- split fields
a = s.split(':')
if a.last =~ /^=(\d+)$/
# ---- set exact filter
filter = "sub_level==#{$1}"
a.pop
elsif a.last =~ /^=/
# ---- set filter
filter = $'
a.pop
elsif a.last =~ /^\d+$/
# ---- the last field is the sub level
sub_level = a.pop.to_i
# ---- The fore-last field is the level
level = a.pop.downcase
else
level = a.pop.downcase
end
# ---- If there is another field it contains logger name(s)
# otherwise it is a global
outputter =
if a.size == 2
a.shift
end
if a.size == 0
a = [:default] # global
else
a = a[0].split(',') # one or more logger name(s)
end
# ---- update every logger
a.each do | type |
opts[type] = {}
opts[type][:level] = level if level
opts[type][:sub_level] = sub_level if sub_level
opts[type][:filter] = filter if filter
opts[type][:outputter_name] = outputter if outputter
# p [type,opts[type]]
end
# ---- Set the globals
LoggerPlusGlobal.instance.trace ||= {}
LoggerPlusGlobal.instance.trace = LoggerPlusGlobal.instance.trace.merge(opts)
end
def CLI::configure logname = nil
include Bio::Log
type = LoggerPlusGlobal.instance.outputter_type
trace = LoggerPlusGlobal.instance.trace
trace ||= {}
default = {}
default = trace[:default] if trace[:default]
trace[logname] ||= {} if logname
trace.each do | name, opts |
# p [name, opts]
next if name == :default
logger_type = type
logger_type = default[:outputter_name] if default[:outputter_name]
logger_type = opts[:outputter_name] if opts[:outputter_name]
logger = LoggerPlus[name]
raise "Unknown logger <#{name}>" if logger == nil
logger.outputters =
case logger_type
when 'stderr', :stderr then logger.outputters = Outputter.stderr
when nil, 'stdout', :stdout then logger.outputters = Outputter.stdout
else
# p [name, logger_type]
FileOutputter.new(name, logger_type[:file])
end
set_levels(logger, default) if default
set_levels(logger, opts)
filter = default[:filter]
filter = opts[:filter] if opts[:filter]
if filter
# p filter
filter2 = "logger.filter { |level,sub_level,msg| #{filter} }"
# p filter2
eval(filter2)
end
end
end
private
def CLI::set_levels logger, opts
logger.level = case opts[:level]
when 'debug' then DEBUG
when 'info' then INFO
when 'warn' then WARN
when 'error' then ERROR
when 'fatal' then FATAL
end if opts[:level]
logger.sub_level = opts[:sub_level] if opts[:sub_level]
end
end
end
end
| true |
1419f721bbac6b4bf08d5e20119d32d08841eb69 | Ruby | thughes24/week1 | /calculator.rb | UTF-8 | 841 | 4.25 | 4 | [] | no_license | require 'pry'
def say(arg)
puts "=> Please Enter a #{arg}: "
end
begin
say('number')
num1 = gets.chomp
num1_converted = num1.to_i
end until num1_converted >= 0
begin
say('second number')
num2 = gets.chomp
num2_converted = num2.to_i
end until num2_converted >=0
begin
puts "Enter 1 to Add, 2 to Subtract, 3 to Multiply or 4 to Divide"
op = gets.chomp
end until op == "1" || op == "2" || op == "3" || op == "4"
case op
when "1"
puts "#{num1_converted} + #{num2_converted} = #{num1_converted + num2_converted}"
when "2"
puts "#{num1_converted} - #{num2_converted} = #{num1_converted - num2_converted}"
when "3"
puts "#{num1_converted} x #{num2_converted} = #{num1_converted * num2_converted}"
when "4"
puts "#{num1_converted} / #{num2_converted} = #{num1_converted.to_f / num2_converted.to_f}"
end | true |
91b4d53d3bdf562372ecbc05298cdaeceec2d358 | Ruby | andrewstyll/adventOfCode | /2016/santa14.rb | UTF-8 | 1,982 | 3.4375 | 3 | [] | no_license | #! /usr/bin/env ruby
require 'digest'
NUMHASHES = 64
INPUTSALT = "qzyelonm"
#INPUTSALT = "abc"
hashHash = Hash.new
def getHash(salt, hashHash)
if(hashHash.key?(salt))
return hashHash[salt]
else
string = Digest::MD5.hexdigest(salt)
hashHash[salt] = string
return string
end
end
def findHashes(hashHash)
n = 0
index = -1
while(n < NUMHASHES)
#make or get a hash of triples
index += 1
salt = INPUTSALT + index.to_s
hash = getHash(salt, hashHash)
val = hash.match(/(.)\1\1/)
if(val != nil)
string = val[0][0]*5
i = index
(i+1..i+1000).each do |j|
salt = INPUTSALT + j.to_s
hash = getHash(salt, hashHash)
if hash.match(string)
n += 1
break
end
end
end
end
puts index
end
def getHash2(salt, hashHash)
if(hashHash.key?(salt))
return hashHash[salt]
else
stretchSalt = salt
string = ""
(0...2017).each do |n|
string = Digest::MD5.hexdigest(stretchSalt)
stretchSalt = string.downcase
end
hashHash[salt] = string
return string
end
end
def findHashes2(hashHash)
n = 0
index = -1
while(n < NUMHASHES)
#make or get a hash of triples
index += 1
salt = INPUTSALT + index.to_s
hash = getHash2(salt, hashHash)
val = hash.match(/(.)\1\1/)
if(val != nil)
string = val[0][0]*5
i = index
(i+1..i+1000).each do |j|
salt = INPUTSALT + j.to_s
hash = getHash2(salt, hashHash)
if hash.match(string)
n += 1
break
end
end
end
end
puts index
end
findHashes(hashHash)
findHashes2(hashHash)
| true |
908b030052d8d670a15872b6f93ab5c5a427970c | Ruby | sanjsanj/object-calisthenics-beach-volleyball-edition | /lib/team.rb | UTF-8 | 264 | 3 | 3 | [] | no_license | class Team
def initialize
@player_list = []
end
def add player
player_list << player
end
def valid?
player_list.count >= 7 && player_list.count <= 10
end
def roster
player_list.dup
end
private
attr_reader :player_list
end
| true |
12e6371085fc803df0061e3f571a5b28ff2c6304 | Ruby | BlaireAramenko/finstagram | /app/models/finstagram_post.rb | UTF-8 | 664 | 2.703125 | 3 | [] | no_license | class FinstagramPost < ActiveRecord::Base
belongs_to :user
has_many :comments
has_many :likes
validates_presence_of :user
validates :photo_url, :user, presence: true
def humanized_time_ago
time_ago_in_seconds = Time.now - self.created_at
time_ago_in_minutes = time_ago_in_seconds / 60
if time_ago_in_minutes >= 60
"#{(time_ago_in_minutes / 60).to_i} hours ago"
else
"#{time_ago_in_minutes.to_i} minutes ago"
end
end
# New Stuff Start
def like_count
self.likes.size
end
def comment_count
self.comments.size
end
# New Stuff End
end
| true |
a3d8ea7260e3e1616c75f0cecc4308220baa390a | Ruby | askareija/resi-tracking-api | /app/services/tracking_service.rb | UTF-8 | 2,023 | 2.546875 | 3 | [] | no_license | # frozen_string_literal: true
class TrackingService
def self.track(*args, &block)
new(*args, &block).execute
end
def initialize(no_resi, expedition_type, user)
@no_resi = no_resi
@expedition_type = expedition_type
@user = user
@track_history = TrackHistory.new(noresi: @no_resi, expedition_type: @expedition_type, user: @user)
end
def execute
uri = URI('https://jagoresi.com/cek-resi/')
res = Net::HTTP.post_form(uri, 'resi' => @no_resi, 'cek' => '', 'jasa' => @expedition_type.delete("\n"))
doc = Nokogiri::HTML(res.body)
receipt = {}
# Parsing general information
table_info = doc.search('div .table-striped')
if table_info.empty?
@track_history.status = 'NOT FOUND'
@track_history.save
return nil
else
receipt[:no_resi] = table_info.first.search('tr')[0].search('td')[2].try(:text)
receipt[:status] = table_info.first.search('tr')[1].search('td')[2].try(:text)
receipt[:expedition_type] = table_info.first.search('tr')[2].search('td')[2].try(:text)
receipt[:date] = table_info.first.search('tr')[3].search('td')[2].try(:text)
receipt[:sender] = (table_info.first.search('tr')[4].search('td')[2].try(:text) rescue nil)
receipt[:origin] = (table_info.first.search('tr')[5].search('td')[2].try(:text) rescue nil)
receipt[:recipient] = (table_info.first.search('tr')[6].search('td')[2].try(:text) rescue nil)
receipt[:recipient_address] = (table_info.first.search('tr')[7].search('td')[2].try(:text) rescue nil)
receipt[:details] = []
doc.search('table tbody').first.search('tr').each_with_index do |row, i|
detail = {}
detail[:date] = Time.zone.parse(row.search('td')[0].try(:text))
detail[:city] = row.search('td')[1].try(:text)
detail[:description] = row.search('td')[2].try(:text)
receipt[:details] << detail
end
@track_history.status = receipt[:status]
@track_history.save
return receipt
end
end
end
| true |
809baa881f5860bc14f1f21fbf10fcd7122dd833 | Ruby | abe-06/libraryapi | /test/models/book_test.rb | UTF-8 | 4,144 | 2.765625 | 3 | [] | no_license | require 'test_helper'
class BookTest < ActiveSupport::TestCase
test "should not save a book without a title" do
book = Book.new
book.author = "test author"
book.collection = "test collection"
book.description = "test description"
book.genre = "test genre"
book.price = 100
book.isbn = 1234567897
assert_not book.save, "Book saved without title"
end
test "should not save a book without an author" do
book = Book.new
book.title = "test title"
book.collection = "test collection"
book.description = "test description"
book.genre = "test genre"
book.price = 100
book.isbn = 1234567897
assert_not book.save, "Book saved without an author"
end
test "should not save a book without an collection" do
book = Book.new
book.title = "test title"
book.author = "test author"
book.description = "test description"
book.genre = "test genre"
book.price = 100
book.isbn = 1234567897
assert_not book.save, "Book saved without a collection"
end
test "should not save a book without an isbn number" do
book = Book.new
book.title = "test title"
book.author = "test author"
book.collection = "test collection"
book.description = "test description"
book.genre = "test genre"
book.price = 100
assert_not book.save, "Book saved without an isbn number"
end
test "should not save a book without a price" do
book = Book.new
book.title = "test title"
book.author = "test author"
book.collection = "test collection"
book.description = "test description"
book.genre = "test genre"
book.isbn = 1234567897
assert_not book.save, "Book saved without price"
end
test "should not save a book without a description" do
book = Book.new
book.title = "test title"
book.author = "test author"
book.collection = "test collection"
book.genre = "test genre"
book.price = 100
book.isbn = 1234567897
assert_not book.save, "Book saved without a description"
end
test "should not save a book without a genre" do
book = Book.new
book.title = "test title"
book.author = "test author"
book.collection = "test collection"
book.description = "test description"
book.price = 100
book.isbn = 1234567897
assert_not book.save, "Book saved without genre"
end
test "should not save a book with an isbn number length different to 10 or 13" do
book = Book.new
book.title = "test title"
book.author = "test author"
book.collection = "test collection"
book.description = "test description"
book.genre = "test genre"
book.price = 100
book.isbn = 123
assert_not book.save, "Book saved with an isbn numer length different from 10 or 13"
end
test "should not save a two books with the same title and author" do
book1 = Book.new
book1.title = "test title"
book1.author = "test author"
book1.collection = "test collection"
book1.description = "test description"
book1.genre = "test genre"
book1.price = 100
book1.isbn = 1234567897
book2 = Book.new
book2.title = "test title"
book2.author = "test author"
book2.collection = "test collection2"
book2.description = "test description2"
book2.genre = "test genre2"
book2.price = 101
book2.isbn = 1234567898
assert_not book1.save && book2.save, "2 Books saved with the same title and author"
end
test "should not save a two books with the same title, author, and collection" do
book1 = Book.new
book1.title = "test title"
book1.author = "test author"
book1.collection = "test collection"
book1.description = "test description"
book1.genre = "test genre"
book1.price = 100
book1.isbn = 1234567897
book2 = Book.new
book2.title = "test title"
book2.author = "test author"
book2.collection = "test collection"
book2.description = "test description2"
book2.genre = "test genre2"
book2.price = 101
book2.isbn = 1234567898
assert_not book1.save && book2.save, "2 Books saved with the same title, author and collection"
end
end
| true |
5a44136136f01802a4538f13ad2e5350fd39d159 | Ruby | diego-asterisk/ttps | /tp2/clases/ej1.rb | UTF-8 | 677 | 3.171875 | 3 | [] | no_license | class VehiculoDeMotor
attr_accessor :llave;
def arrancar
puts @llave
end
def initialize(llave = false)
@llave = llave
end
end
class Auto < VehiculoDeMotor
def arrancar
freno_mano = false
cambio = :punto_muerto
super
end
end
class Moto < VehiculoDeMotor
def arrancar
patada = true
super
end
end
class Lancha < VehiculoDeMotor
end
class Taller
def probar (objeto)
objeto.arrancar
end
end
tito = Taller.new
ford = Auto.new(:mi_llave)
tito.probar(ford)
# una motosierra tiene motor, pero no es un vehiculo, usamos polimorfismo
# o podemos usar mixins con un módulo Motor
# o podemos usar composición
| true |
20c1023f0a4084226440504e4937573612d4d3e7 | Ruby | Nemanicka/pathToFriend | /lib/searchers/twitter.rb | UTF-8 | 1,607 | 2.84375 | 3 | [
"MIT"
] | permissive | #https://api.foursquare.com/v2/venues/search?ll=40.7,-74&client_id=LPOO1Y3SF1IRX04VJZC53XKKQQHCAMIQSB1SQ1BWYDFY1BSV&client_secret=3WL0SL5JODGZDJD1PNVRJPQ4JQAVN2SW42AUBQJIMMXZ3VE2&v=20120609
require "net/http"
require "curb"
require "addressable/uri"
require "json"
require "twitter"
class FoursquareSearcher
def initialize( attributes = {} )
geocode = "50.45025,30.523889, 20km"
@client = Twitter::Streaming::Client.new do |config|
config.consumer_key = "RtZzMs8aNhEsmCs1uqpUc7kbm"
config.consumer_secret = "6IQnIVDRNKKRK2u01DFxBtUT8wrGeu6hxUAWORz4jeNDF3E1fw"
config.access_token = "808599781-6161951XO8DVGE5HzdLvU6C4jb754UVhqRg0GX3R"
config.access_token_secret = "DiW3zMENZ2VuAPkdSPwnhk8zLBrcraEYccAIQw4kgqtpH"
end
# getRESTTweets( geocode );
getStreamTweets( geocode )
# puts curb.url
# curb.http_get()
# parsed_answer = JSON.parse( curb.body_str );
end
def getRESTTweets ( geocode )
clientREST = Twitter::REST::Client.new( @client.credentials )
# clientREST = @client
obj = clientREST.search( "", { :geocode => geocode } )
objh = obj.to_h;
counter = 0
objh[:statuses].each {|x| puts x[:text]; counter+=1 }
puts counter
end
def getStreamTweets( geocode )
# clientStream = Twitter::Streaming::Client.new( @client.credentials )
# puts @client.credentials
#:locations => geocode
@client.filter( { :track => "lol", :location => geocode } ) do |x|
# @client.filter( :track => "lal,lol" ) do |x|
puts x.text if x.is_a?(Twitter::Tweet)
end
end
end
test = FoursquareSearcher.new
| true |
aebbb7ae3479c3f47da6df1c219562493e50bd32 | Ruby | aknuds1/childprocess | /lib/childprocess/abstract_io.rb | UTF-8 | 723 | 2.578125 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | module ChildProcess
class AbstractIO
attr_reader :stderr, :stdout, :stdin
def inherit!
@stdout = STDOUT
@stderr = STDERR
end
def stderr=(io)
if io != :pipe
check_type io
end
@stderr = io
end
def stdout=(io)
if io != :pipe
check_type io
end
@stdout = io
end
#
# @api private
#
def _stdin=(io)
check_type io
@stdin = io
end
def _stdout=(io)
check_type io
@stdout = io
end
def _stderr=(io)
check_type io
@stderr = io
end
private
def check_type(io)
raise SubclassResponsibility, "check_type"
end
end
end
# vim: set sts=2 sw=2 et:
| true |
42455ad1e9c5b80e500dbd4c844bd7c1920ee635 | Ruby | monicamow/contacts_app | /lib/contact_list.rb | UTF-8 | 3,502 | 3.875 | 4 | [] | no_license | # Interfaces between a user and their contact list. Reads from and writes to standard I/O.
class ContactList
# This method is called when no user arguments are given after the 'ruby contact_list.rb' command
def display_menu
puts "Here is a list of available commands: \
\n new - Create a new contact \
\n list - List all contacts \
\n show - Show a contact \
\n search - Search contacts"
end
# TODO: Implement user interaction. This should be the only file where you use `puts` and `gets`.
# REFACT EXPECTED RESULT
# def run_program
# case menu[:command]
# when "list"
# list_command
# when "new"
# new_command
# ....
# end
# end
def run_program
# commands typed by use from terminal
menu = {
command: ARGV[0],
argument: ARGV[1]
}
case menu[:command]
when "list"
Contact.all.each do |contact|
puts "#{contact.id}: #{contact.first_name} (#{contact.email})"
end
when "new"
new_command
when "update"
case menu[:argument]
when /\d/
puts "What is the NEW name of the contact?"
name_input = STDIN.gets.chomp.strip
puts "What is the NEW email of the contact?"
email_input = STDIN.gets.chomp.strip
updated_contact = Contact.find(menu[:argument])
updated_contact.first_name = name_input
updated_contact.email = email_input
updated_contact.save
puts "The contact with ID of #{updated_contact.id} was updated to: \
\n#{updated_contact.first_name} (#{updated_contact.email})"
end
when "show"
case menu[:argument]
when /\d/
found_id = Contact.find(menu[:argument])
if found_id.nil?
puts "not found"
else
puts "ID: #{found_id.id}\nNAME: #{found_id.first_name}\nEMAIL: #{found_id.email}"
end
when nil
puts "You must put what you want to show i.e. 'show 4'"
end
when "search"
case menu[:argument]
when /\w/
search_results = Contact.search(menu[:argument])
if search_results.empty?
puts "not found"
else
search_results.each do |contact|
puts "#{contact.id}: #{contact.first_name} (#{contact.email})"
end
puts "---\n#{search_results.size} records total"
end
when nil
puts "You must put what you want to search for i.e. 'search beyonce'"
end
when "delete"
case menu[:argument]
when /\d/
contact_to_delete = Contact.find(menu[:argument])
if contact_to_delete.nil?
puts "not found"
else
contact_to_delete.destroy(menu[:argument])
end
when nil
puts "You must put what you want to destroy for i.e. 'delete 5'"
end
when nil
display_menu
end
end
private
def new_command
fname, lname, email = get_user_info
contact = Contact.create(first_name: fname, last_name: lname, email: email)
puts contact
end
def get_user_info
puts "What is the first name of the contact?"
fname = STDIN.gets.chomp.strip
puts "What is the last name of the contact?"
lname = STDIN.gets.chomp.strip
puts "What is the email of the contact?"
email = STDIN.gets.chomp.strip
[fname, lname, email]
end
end
| true |
0123b06f3aac375545d5f9c2ac46955b598a75fd | Ruby | zsombor/battleship | /contestants/nelson/lib/probability_board.rb | UTF-8 | 2,417 | 3.796875 | 4 | [] | no_license | # Evaluate the best possible coordinate for of the next bomb. This is
# done via by positioning all remaining enemy ships in all possible
# ways over the board. Then the probability of a hit is computed by
# counting how many times a particular bomb had hit a possible ship
# placement.
#
# If there are hits on the board already, then all adjacent cells get
# a probability boost that is exponentially proportional to the number
# of hits in the possible placement. Cells containing sunk ships are
# ignored. The exponential rule forces a directional kills as ships
# are either horizontal or vertical.
class ProbabilityBoard
def initialize player
@player = player
@board = player.board
@score_board = []
LordNelsonPlayer::GRID_SIZE.times do
@score_board.push(Array.new(LordNelsonPlayer::GRID_SIZE, 0))
end
compute
end
# Positions each remaining enemy ship using every possibly
# placement. The score_board is a matrix where each cell contains
# the damage score for a hit placed at (x, y).
def compute
@board.each_starting_position_and_direction do |x, y, dx, dy|
@player.remaining.each do |length|
placement = generate_placement x, y, dx, dy, length
if placement.length == length
score_placement placement
end
end
end
end
def generate_placement x, y, dx, dy, length
xi, yi = x, y
placement = [[xi, yi]]
(length-1).times do
xi += dx
yi += dy
break unless @board.on?(xi, yi)
if @board.hit_or_unknown?(xi, yi)
placement.push([xi, yi])
end
end
placement
end
def count_hits_in placement
return 0 unless @player.kill_mode?
hits = placement.select { |x, y| @board.hit?(x, y) }.size
end
def score_placement placement
hits = count_hits_in placement
placement.each do |x, y|
if @board.unknown?(x, y)
@score_board[y][x] += 100**hits
end
end
end
# Computes the coordinate with the highest score. If multiple peaks
# are found, a random one is selected.
def best_move
max_score = 0
moves = []
@board.each_starting_position do |x, y|
next unless @board.unknown?(x, y)
if @score_board[y][x] > max_score
max_score = @score_board[y][x]
moves = [[x, y]]
elsif @score_board[y][x] == max_score
moves.push([x, y])
end
end
moves.sample
end
end
| true |
9711ec6a84d17cdb2b007e702682a52c89f0c26f | Ruby | benlund/roc | /test/float_test.rb | UTF-8 | 704 | 2.765625 | 3 | [] | no_license | require File.join(File.dirname(__FILE__), 'roc_test')
class FloatTest < ROCTest
def test_rw
f = Store.init_float(random_key)
assert_nil f.value
assert_equal 0.0, f.to_f
assert_equal 0, f.to_i
f.value = 2.345
assert_equal 2.345, f.value
end
def test_infinite
f = Store.init_float(random_key, (1.0 / 0))
assert_equal 1, f.infinite?
f.value = (-1.0 / 0)
assert_equal -1, f.infinite?
end
def test_delegation
f = Store.init_float(random_key)
num = 2.345
f.value = num
assert_equal (num - 1.0), (f - 1.0)
assert_equal (num + 1.0), (f + 1.0)
assert_equal (num / 0.5), (f / 0.5)
assert_equal (num * 3.2), (f * 3.2)
end
end
| true |
c21e4fd454a469d3386c190a3200a493901f07cb | Ruby | 256hz/recipe-reader-rails | /app/models/fetcher.rb | UTF-8 | 8,940 | 2.984375 | 3 | [] | no_license | require 'httparty'
# Calls the Spoonacular API for recipe search and recipe steps.
# Order of operations:
# SEARCH: search, request_search
# RECIPE:
# get_recipe
# request_recipe
# create_recipe
# create_ingredients
# create_steps
# get_spoon_ids
# associate_step_ingredients
class Fetcher
def self.key
# Returns the API key from the environment
ENV.fetch('SPOONACULAR_API_KEY')
end
def self.recipe_search(query)
responses = request_search(query)
return_search_results(responses['results'])
end
def self.request_search(query)
# Performs Spoonacular(S11r)'s 'complex recipe' search -- simple search seems to be down.
# Returns JSON results that include instructions with step associations.
HTTParty.get(
'https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/recipes/searchComplex' +
"?query=#{query}&instructionsRequired=true",
headers: { 'X-RapidAPI-Host' => 'spoonacular-recipe-food-nutrition-v1.p.rapidapi.com',
'X-RapidAPI-Key' => key }
)
end
def self.return_search_results(responses)
# Searches for recipes from S11r and returns them in a @results hash.
if responses
responses.each_with_object({}) do |response, hash|
hash[response['title']] = { id: response['id'],
image_url: response['image'],
readyInMinutes: response['readyInMinutes'] }
end
else
{ 'None' => 'No recipes found' }
end
end
def self.get_recipe(id)
# Runner method for getting a recipe.
# - gets the recipe from S11r
# - creates a Recipe to associate everything with
# - creates Ingredients & RecipeIngredients joins for this recipe
# - creates Steps & RecipeSteps joins
# - creates StepIngredient joins.
response = request_recipe(id)
# puts response
@recipe = create_recipe(response)
@ingredients = create_ingredients(response, @recipe)
@steps = create_steps(response, @recipe.id, @ingredients)
associate_step_ingredients(@steps)
@recipe
end
def self.request_recipe(id)
# Return a single recipe's instructions and equipment in JSON.
HTTParty.get('https://spoonacular-recipe-food-nutrition-v1.p.rapidapi.com/' +
"recipes/#{id}/information",
headers: { 'X-RapidAPI-Host' => 'spoonacular-recipe-food-nutrition-v1.p.rapidapi.com',
'X-RapidAPI-Key' => key })
end
def self.create_recipe(response)
# Create a new Recipe in the DB.
@recipe = Recipe.create(cuisines: response['cuisines'],
dish_types: response['dishTypes'],
image_url: response['image'],
is_vegetarian: response['vegetarian'],
is_vegan: response['vegan'],
likes: response['aggregateLikes'],
ready_in_minutes: response['readyInMinutes'],
servings: response['servings'],
spoon_id: response['id'],
source_name: response['sourceName'],
source_url: response['sourceUrl'],
title: response['title'])
@recipe
end
def self.create_ingredients(response, recipe)
# Makes Ingredients if they don't already exist. Associates all with the Recipe.
ingredients = []
response['extendedIngredients'].each do |ingred|
# puts "ingredient:", ingred['name'], 'spoon_id:', ingred['id']
@ingred = Ingredient.all.find_by(spoon_id: ingred['id'])
if @ingred.nil? || @recipe.ingredients.map(&:spoon_id).include?(ingred['id'])
@ingred = Ingredient.create!(spoon_id: ingred['id'],
# see filter_name comments below
name: filter_name(ingred['name']),
orig_string: ingred['originalString'],
metric_amount: round_to_fraction(ingred['measures']['metric']['amount']),
metric_unit: ingred['measures']['metric']['unitShort'],
us_amount: round_to_fraction(ingred['measures']['us']['amount']),
us_unit: ingred['measures']['us']['unitShort'],
image_url: ingred['image'])
end
ri = RecipeIngredient.find_or_create_by(recipe_id: recipe.id, ingredient_id: @ingred.id)
# puts 'created recipe_ingredient id:', ri.id
ingredients.push(@ingred)
end
ingredients
end
def self.round_to_fraction(float, denominator = 4)
# The API often returns amounts in long floats, probably as a result of
# automated conversion to/from metric. This rounds to the nearest quarter,
# unless another denominator is specified.
(float * denominator).round.to_f / denominator
end
def self.filter_name(name)
# This is a janky way to remove very common words from the Ingredient name,
# which helps prevent false positives when associating StepIngredients later.
words_to_strip = %w[fresh green red]
words_to_strip.each do |word|
name = name.split.filter { |el| el != word }.join(' ')
end
name
end
def self.create_steps(response, recipe_id, ingredients)
# Creates Steps from the response and associates ingredents & recipe.
# If the step has equipment, it creates it below in create_equipment.
# I don't like that the create_equipment call is coupled this function,
# good refactor target.
steps = []
response['analyzedInstructions'][0]['steps'].each do |step|
# puts "Step ingredients:", step['ingredients']
# puts "Step ingredient Spoon IDs:", step['ingredients'].map{|i| i['id'].to_s}
step_spoon_ids = get_spoon_ids(step['step'], ingredients)
@step = Step.create!(recipe_id: recipe_id,
step_no: step['number'],
text: step['step'],
spoon_ids: step_spoon_ids)
create_equipment(step['equipment'], recipe_id, @step.id) if step['equipment']
steps.push(@step)
end
steps
end
def self.create_equipment(equipment, recipe_id, step_id)
# Takes a list of equipment from the Step created above, creates each one,
# and joins it with the step and recipe.
# puts 'creating equipment'
# puts equipment, recipe_id, step_id
equipment.each do |item|
# puts 'item:', item
@equip = Equipment.find_by(spoon_id: item['id'])
if @equip.nil?
# puts 'equipment not found, creating:', item['id'], item['name'], item['image']
@equip = Equipment.create!(spoon_id: item['id'],
name: item['name'],
image_url: item['image'])
# puts 'equip created:', @equip
end
RecipeEquipment.find_or_create_by!(equipment_id: @equip.id, recipe_id: recipe_id)
StepEquipment.create!(equipment_id: @equip.id, step_id: step_id)
end
end
def self.get_spoon_ids(text, ingredients)
# Sometimes, the API returns different ingredients in the step than it does in
# the Recipe's extendedIngredients field (e.g., cherry jam vs. raspberry).
# This searches the ingredients list for word matches, i.e., cherry jam
# would match rasbperry jam due to the common word 'jam'. Very janky in that
# this causes problems with multiple types of the same ingredient, but that
# isn't super common.
spoon_ids = []
# puts "Searching: #{text}"
ingredients.each do |i|
# puts "Looking for: #{i.name}"
# Checks for an exact match in the ingredients list.
if text.downcase.include?(i.name)
spoon_ids << i.spoon_id
# puts "found, inserting: #{i.name}, #{i.spoon_id}"
else
split_name = i.name.downcase.split
split_name.each do |word|
spoon_ids << i.spoon_id if text.include?(word) && !spoon_ids.include?(i.spoon_id)
# puts "found, inserting: #{i.name}, #{i.spoon_id}"
end
end
end
# puts "spoon_ids: #{spoon_ids}"
spoon_ids
end
def self.associate_step_ingredients(steps)
# Finally, we can associate the Steps with their Ingredients.
steps.each do |step_i|
# puts "Associating #{step_i} with ids: #{step_i['spoon_ids']}"
next if step_i['spoon_ids'] == []
# puts " Step spoon_ids: #{ step_i['spoon_ids'] } "
step_i['spoon_ids'].each do |spoon_id|
ingred = Ingredient.all.find_by(spoon_id: spoon_id)
# puts "found ingredient: #{ingred.name}"
# puts "making StepIngredient with step_id: #{step_i.id}, ingred_id: #{ingred.id}"
StepIngredient.create!(step_id: step_i.id, ingredient_id: ingred.id)
end
end
end
end
| true |
c471a41cff0e910fcf569ab26f5bfba1188bd4fd | Ruby | KevinLai76/parrot-ruby-dumbo-web-060319 | /parrot.rb | UTF-8 | 160 | 3.53125 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Create method `parrot` that outputs a given phrase and
# returns the phrase
def parrot(str = "Squawk!")
phrase = "#{str}"
puts phrase
return phrase
end | true |
d8c6811df97c688de857d49fd08add03083266cc | Ruby | JuanPabloSolano1/Hackerrank_Ruby | /Extra_long_factorials.rb | UTF-8 | 144 | 3.0625 | 3 | [] | no_license | number = 30
array = [*1..number -1]
new_array = array.reverse()
count = number
new_array.each do |element|
count *= element
end
print count
| true |
aa4d0c1442062b6be17cd85805e8a011cc998812 | Ruby | botanicus/dm-notifications | /lib/dm-notifications.rb | UTF-8 | 2,221 | 2.515625 | 3 | [] | no_license | # encoding: utf-8
require "mq"
module NotificationsMixin
def self.included(base)
unless base.instance_method_defined?(:name)
raise RuntimeError.new("#{base} has to respond to #name method!")
end
end
# followers fanout
def create_followers_fanout
self.followers_fanout(no_declare: false)
end
def followers_fanout(options = nil)
@followers_fanout_options ||= begin
{durable: true, no_declare: true}
end
options = @followers_fanout_options.merge(options)
@followers_fanout ||= begin
MQ.fanout("#{self.name}_followers", options)
end
end
# notifications queue
def create_notifications_queue
self.notifications_queue(no_declare: false)
end
def notifications_queue(options = nil)
@notifications_queue_options ||= begin
{durable: true, no_declare: true}
end
options = @notifications_queue_options.merge(options)
@notifications_queue ||= begin
MQ.queue("#{self.name}_notifications", options)
end
end
end
# for User
module ProducerMixin
def publish(notification)
data = encode_notification(notification)
self.followers_fanout.publish(data)
end
# @api plugin
# Redefine this method in order to customize what is published, so for example you might want to push just raw SQL statements and run them directly on the worker(s), so you won't need to create bunch of objects just to call #save on them.
def encode_notification(notification)
notification.attributes.to_json
end
end
# class User
#
# has (0..n), :followers, self, through: :friendships, via: :target, notifications: true
# end
# class Friendship
# belongs_to :source, User, notifications: true
# end
module NotificationsConsumerMixin
include NotificationsMixin
def self.included(base)
base.after(:save) do
self.create_followers_fanout
self.create_notifications_queue
end
base.after(:destroy) do
self.destroy_followers_fanout
self.destroy_notifications_queue
end
end
end
class Notification
include DataMapper::Resource
property :message, Text
belongs_to :user
belongs_to :subject, model: User
end
# + bind
follower.notifications_queue.bind(user.followers_fanout)
| true |
b809351283f7f30c13024a3d466d5726fd5b8bae | Ruby | pomidorus/Full-Stack-Engineer-Ruby | /core_api/app/services/marvel_data_saver.rb | UTF-8 | 1,049 | 3.21875 | 3 | [] | no_license | class MarvelDataSaver
YEAR_REG = /[(](\d+)[)]/
NUMBER_REG = /#\d+/
NEGATIVE_NUMBER_REG = /#-\d+/
YEAR_NUMBER_REG = /[(]\d+[)]\s+#\d+/
def save(data)
data[:data][:results].map &method(:create_comic)
rescue NoMethodError
puts "Data #{data.inspect} is broken for parsing"
end
private
def create_comic(hash)
Comic.find_or_create_by!(comic_params(hash))
rescue NoMethodError
puts "Hash #{hash} is broken for parsing"
end
def comic_params(hash)
{
comic_id: hash[:id].to_i,
title: clear_title(hash[:title]),
year: year_from_title(hash[:title]),
issue_number: hash[:issueNumber].to_i,
thumbnail_url: "#{hash[:thumbnail][:path]}.#{hash[:thumbnail][:extension]}",
characters: hash[:characters][:items].map{|e| e[:name]}.join(', ')
}
end
def year_from_title(string)
string.match(YEAR_REG)[1].to_i unless string.match(YEAR_REG).nil?
end
def clear_title(string)
string.gsub(YEAR_REG, '').gsub(NUMBER_REG, '').gsub(NEGATIVE_NUMBER_REG, '').strip
end
end
| true |
40ba3b1d982f8beffb7e1577b710fa27867f5960 | Ruby | eoneill/sassdoc | /lib/sassdoc.rb | UTF-8 | 3,973 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | require 'fileutils'
require 'json'
module Sassdoc
@docs = {}
def self.parse(read)
if File.exist? read
if File.directory? read and Dir.chdir(read)
# loop through each scss file in the directory
Dir.glob('**/*.s[ac]ss').each do |f|
self.parse_docs(f)
end
else
self.parse_docs(read)
end
end
return @docs
end
def self.init(read, options)
pwd = FileUtils.pwd()
json = self.parse(ARGV[0] || '.').to_json
if options[:stdout]
puts json
else
Dir.chdir(pwd)
@json_filename = 'sassdoc.json'
dir = options[:destination]
FileUtils.mkdir_p dir
json_file = File.join(dir, @json_filename)
FileUtils.touch json_file
File.open(json_file, "w") {|file| file.puts json}
if options[:viewer]
# copy over viewer files
FileUtils.cp_r(File.join(File.dirname(__FILE__), '..', 'viewer', '.'), dir)
settings = {}
settings[:viewer] = options[:scm] if options[:scm]
settings[:docs] = @json_filename
settings = settings.to_json
%w(index.html tmpl/view.tmpl).each do |src|
src = File.join(dir, src)
text = File.read(src)
File.open(src, "w") {|file| file.puts text.gsub(/\{SASSDOC_TITLE\}/, options[:name]).gsub(/\{SASSDOC_SETTINGS\}/, settings)}
end
end
end
end
private
def self.parse_doc(description)
data = {}
name_matcher = /^\$([a-zA-Z0-9\-\_]+)/
type_matcher = /^\{([a-zA-Z0-9\|\*]+)\}/
# get the name
name = description.match(name_matcher)
description = description.sub(name_matcher, '').lstrip
data[:name] = name[0] if name
# get the type
type = description.match(type_matcher)
description = description.sub(type_matcher, '').lstrip
data[:type] = type[1] if type
# if it had a name or a type, then set description as a child, otherwise it's the value
if name or type
data[:description] = description
else
data = description
end
data
end
def self.parse_block(block)
data = {}
tag_matcher = /^\@([a-zA-Z0-9]+)/
tag = 'overview'
block.each do |doc|
tmp = doc.match(tag_matcher)
if tmp
# need to strip off the new tag
tag = tmp[1]
doc = self.parse_doc doc.sub(tag_matcher, '').strip
end
if data[tag]
data[tag].push(doc)
else
data[tag] = [doc]
end
end
if data and (data['function'] or data['mixin'])
return {
:method => (data['function'] || data['mixin'])[0],
:data => data
}
else
if data and data['category']
return data
end
return nil
end
end
# self.parse
def self.parse_docs(file)
doc = false
first_block = true
doc_block = []
linenum = nil
ln = 0
category = nil
IO.foreach(file) do |block|
ln = ln + 1
# we're only interested in lines that are using Sass comments, so ignore the others
if block.start_with? '//'
doc = true
linenum = ln unless linenum
doc_block.push block.gsub(/^(\/)*/, '').strip
else
if doc
tmp = self.parse_block(doc_block)
if tmp
if tmp['category']
category = tmp['category'][0]
else
# store the source
tmp[:data][:source] = file.to_s
# store the line number
tmp[:data][:linenum] = linenum
# get the category
cat = tmp[:data]['category'] || category || file.to_s.gsub(/\.s[ac]ss/,'').gsub('_','')
tmp[:data]['category'] = cat unless tmp[:data]['category']
# push it onto docs
@docs[cat] = {} unless @docs[cat]
@docs[cat][tmp[:method]] = tmp[:data]
end
end
doc_block = []
end
linenum = nil
doc = false
end
end
end
end
| true |
4283c855b4eb93bfcbd50919a253fda4f3b3796a | Ruby | jugyo/ncurses_test | /vi_ui.rb | UTF-8 | 2,791 | 2.921875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
require 'ncurses'
require 'g'
module CommandLine
def self.extended(base)
base.instance_eval do
@position = 0
@text = ''
@prompt = ':'
end
end
attr_reader :text, :position
def char_widths
@char_widths ||= []
@char_widths
end
def clear_text
@text = ''
redraw
end
def cursor_position
y = x = []
getyx(y, x)
x.last
end
def move_left(i = 1)
return false if @position <= @prompt.size
@position -= i
move(0, @position)
end
def move_right(i = 1)
return false if @position >= @text.size
@position += i
move(0, @position)
end
def add_char(char)
text << char
@position += 1
redraw
end
def del_char(pos = nil)
pos ||= @position
array = text.split(//)
array.delete_at(pos)
@text = array.join
redraw
end
def backspace
del_char if move_left
end
def redraw
clear
move(0, 0)
text.each_byte do |char|
addch(char)
end
move(0, @position)
end
end
begin
screen = Ncurses.initscr
Ncurses.cbreak
Ncurses.noecho
Ncurses.start_color
Ncurses.init_pair(1, Ncurses::COLOR_WHITE, Ncurses::COLOR_BLACK)
Ncurses.init_pair(2, Ncurses::COLOR_BLACK, Ncurses::COLOR_WHITE)
lines = Ncurses.LINES
cols = Ncurses.COLS
status = Ncurses.newwin(1, cols, lines - 2, 0)
status.bkgd(Ncurses.COLOR_PAIR(2))
status.refresh
command = Ncurses.newwin(1, cols, lines - 1, 0)
command.extend(CommandLine)
command.refresh
list = Ncurses.newwin(lines - 2, cols, 0, 0)
list.bkgd(Ncurses.COLOR_PAIR(1))
list.scrollok(true)
('a'..'z').each do |i|
list.addstr(("#{i}" * 100) + "\n")
end
list.refresh
Ncurses.keypad(list, true)
Ncurses.keypad(command, true)
loop do
ch = list.getch
case ch
when Ncurses::KEY_DOWN, 'j'[0]
list.scrl(1)
when Ncurses::KEY_UP, 'k'[0]
list.scrl(-1)
when ':'[0]
##################################
# command mode
#
command.move(0, 0)
command.add_char(':'[0])
command.move(0, 1)
command.refresh
loop do
cch = command.getch
case cch
when Ncurses::KEY_BACKSPACE
command.backspace
when 330 # delete
command.del_char
when 27 # escape
break
when 10 # enter
break
when Ncurses::KEY_DOWN
when Ncurses::KEY_UP
when Ncurses::KEY_RIGHT
command.move_right
when Ncurses::KEY_LEFT
command.move_left
else
command.add_char(cch)
end
command.refresh
end
command.clear
command.refresh
end
list.refresh
end
rescue => e
g "#{e}\n#{e.backtrace.join("\n")}"
ensure
Ncurses.endwin
end
| true |
6a1be035a7c791e96785d94601fb69e8f845b862 | Ruby | simongregory/glued | /lib/glued/bootstrap.rb | UTF-8 | 5,960 | 2.671875 | 3 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | # encoding: utf-8
# Bootstrap decoder.
#
# The boostrap files describe the segments and fragments that form
# the media file.
#
class Bootstrap
attr_reader :boxes
def initialize(data)
@reader = F4VIO.new(data)
@boxes = []
scan
end
# Top level
AFRA = 'afra' # Fragment random access for HTTP streaming
ABST = 'abst' # Bootstrap info for HTTP streaming
MOOV = 'moov' # Container for structural metadata
MOOF = 'moof' # Movie Fragment
MDAT = 'mdat' # Moovie data container
# Inside ABST
ASRT = 'asrt' # Segment run table box
AFRT = 'afrt' # Fragment runt table box
def segments
@boxes.first.segments
end
def fragments
@boxes.first.segment_run_tables.first.run_entry_table.first.fragments_per_segment
end
private
def scan
# Scan for 'boxes' in the stream see spec 1.3 F4V box format
until @reader.eof?
box = make_box_header
case box.type
when ABST
@boxes << make_bootstrap_box(box)
when AFRA
@boxes << box
when MDAT
@boxes << box
else
break
end
end
fail 'Computer says no' if @boxes.empty?
@boxes
end
def make_box_header
pos = @reader.pos
size = @reader.int32
type = @reader.four_cc
# For boxes over 4GB the size is moved after the type
size = @reader.int64 if size == 1
Header.new(pos, size, type)
end
def make_bootstrap_box(header)
# 2.11.2 Bootstrap Info box
b = BootstrapBox.new
b.header = header
b.version = @reader.byte
b.flags = @reader.int24
b.bootstrap_info_version = @reader.int32
plu = @reader.byte
b.profile = plu >> 6
b.live = (plu & 0x20) ? 1 : 0
b.update = (plu & 0x01) ? 1 : 0
b.time_scale = @reader.int32
b.current_media_time = @reader.int64
b.smpte_timecode_offset = @reader.int64
b.movie_identifier = @reader.string
b.servers = @reader.byte_ar
b.quality = @reader.byte_ar
b.drm_data = @reader.string
b.metadata = @reader.string
b.segments = @reader.byte
b.segment_run_tables = []
b.segments.times { b.segment_run_tables << make_asrt_box(make_box_header) }
fail 'There should be at least one segment entry' if b.segment_run_tables.empty?
b.fragments = @reader.byte
b.fragment_run_tables = []
b.fragments.times { b.fragment_run_tables << make_afrt_box(make_box_header) }
fail 'There should be at least one fragment entry' if b.fragment_run_tables.empty?
b
end
def make_asrt_box(header)
# 2.11.2.1 Segment Run Table box
fail "Unexpected segment run table box header '#{header.type}' instead of '#{ASRT}'" unless header.type == ASRT
b = RunTableBox.new
b.header = header
b.version = @reader.byte
b.flags = @reader.int24
b.quality_segment_url_modifiers = @reader.byte_ar
table = []
runs = @reader.int32
runs.times do
first_segment = @reader.int32
fragments_per_segment = @reader.int32
table << SegmentRunEntry.new(first_segment, fragments_per_segment)
end
b.run_entry_table = table
b
end
def make_afrt_box(header)
# 2.11.2.2 Fragment Run Table box
fail "Unexpected fragment run table box header '#{header.type}' instead of '#{AFRT}'" unless header.type == AFRT
b = RunTableBox.new
b.header = header
b.version = @reader.byte
b.flags = @reader.int24
b.time_scale = @reader.int32
b.quality_segment_url_modifiers = @reader.byte_ar
table = []
runs = @reader.int32
runs.times do
f = FragmentRunEntry.new
f.first_fragment = @reader.int32
f.first_fragment_timestamp = @reader.int64
f.fragment_duration = @reader.int32
f.discontinuity_indicator = @reader.byte if f.fragment_duration == 0
table << f
end
b.run_entry_table = table
b
end
end
class Header < Struct.new(:pos, :size, :type)
# pos, starting position within the byte stream
# size, number of bytes within the box
# type, descriptive type for the bytes stored in the box
end
class BootstrapBox < Struct.new(:header,
:version,
:flags,
:bootstrap_info_version,
:profile,
:live,
:update,
:time_scale,
:current_media_time,
:smpte_timecode_offset,
:movie_identifier,
:servers,
:quality,
:drm_data,
:metadata,
:segments,
:segment_run_tables,
:fragments,
:fragment_run_tables)
end
class SegmentRunEntry < Struct.new(:first_segment, :fragments_per_segment)
end
class FragmentRunEntry < Struct.new(:first_fragment,
:first_fragment_timestamp,
:fragment_duration,
:discontinuity_indicator)
end
# For Segment and Fragment boxes
class RunTableBox < Struct.new(:header,
:version,
:flags,
:time_scale,
:quality_segment_url_modifiers,
:run_entry_table)
end
| true |
bccb0d21961702593fbb49b6ecc875c0271c1f1c | Ruby | glowf/precourse | /workbook/IntermediateQuestions/Quiz1/Ex7.rb | UTF-8 | 242 | 3.421875 | 3 | [] | no_license | def fib(first_num, second_num,limit)
while second_num < limit
sum = first_num + second_num
first_num = second_num
second_num = sum
end
sum
end
result = fib(0, 1,15)
puts "result is #{result}"
#limit was outside the scope
| true |
d5f8ce5cc7da099ce5a1bcde1bf74ff4667c3cf5 | Ruby | miyakz1192/neutron_tools | /rabbitmq/model.rb | UTF-8 | 3,272 | 2.921875 | 3 | [] | no_license | require 'rabbitmq/http/client'
require 'json'
require 'ostruct'
module RabbitModel
class Model < OpenStruct
end
class Channel < Model
end
class Queue < Model
end
class Consumer < Model
end
class Binding < Model
end
class Host < Model
#== source_port_process
#this method returns process that opens tcp connection
#that source port is port(argument)
#params1::source_port. tcp source port number.
def find_process_by_tcp_sport_num(tcp_sport_num)
temp = self.lsof.detect{|lsof| lsof["whole"] =~ /#{tcp_sport_num}->/}
return nil unless temp
temp = self.ps.detect{|ps| ps["pid"] == temp["pid"]}
return nil unless temp
return temp["cmd"]
end
end
class ModelContainer
#== read
#this methods read from json file from rabbit_mq_data(default).
#and eliminate first key(ex: bindings) and set
#@#{self.class.name.downcase} (ex: @bindings)
def load
data = open(open_file_name, "r") do |io|
JSON.load(io)
end[models_name]
build_models(data)
self
end
protected
def model_name
"#{self.class.name}".gsub(/Container|RabbitModel::/,"")
end
def models_name
"#{model_name.downcase}s"
end
def build_models(data)
eval("@#{models_name} = data.map{|d| #{model_name}.new(d)}")
#example: @channels = data.map{|d| Channel.new(d)}
end
def open_file_name
"rabbit_mq_data/#{models_name}.json"
end
end
class ChannelContainer < ModelContainer
def find_by_id(id)
@channels.detect{|c| c.id == id}
end
#==inject_process
#inject process info from Hosts(class) info to channels info
#this method assumes that ip address in channels info is host name
#params1::hosts. Hosts object
#return::self
def inject_process(host_container)
@channels.each do |ch|
host = host_container.find_by_channel(ch)
next unless host
ch.cmd = host.find_process_by_tcp_sport_num(ch.port)
end
self
end
end
class ConsumerContainer < ModelContainer
def find_channel_by_queue_name(queue_name)
con = @consumers.select{|c| c.queue_name == queue_name}
if con.size == 1
return con.first.channel
elsif con.size == 0
return Channel.new({ip: "NOIP", port: "NOPORT"})
elsif con.size > 1
puts "WARNING: connection sizes then 1(#{con.size})"
return con.first.channel
end
end
#==inject_channels
#inject channels(class) info to consumers info
#params1::channels, Channels object
#return::self
def inject_channels(channel_container)
@consumers.each do |co|
channel = channel_container.find_by_id(co.id)
next unless channel
co.channel = channel
end
end
end
class BindingContainer < ModelContainer
#== find_queues_by_exchange_name
#params1::ex_name. exchange name
#return::array of string. queue name string array
def find_queue_names_by_exchange_name(ex_name)
@bindings.map{|b| b.destination if b.source == ex_name}.compact
end
def exchange_names
res = @bindings.map{|b| b.source}.uniq
res.delete("")
res
end
end
class QueueContainer < ModelContainer
def find_by_name(queue_name)
@queues.detect{|q| q.name == queue_name}
end
end
class HostContainer < ModelContainer
def find_by_channel(ch)
@hosts.detect{|h| h.name == ch.ip}
end
end
end
| true |
e0520e3ebf4f98cf24138a96ccaff74d11e5a693 | Ruby | aravindmp1/hash | /rep.rb | UTF-8 | 364 | 3.6875 | 4 | [] | no_license | class Array
def initialize(string)
@string=string
end
def array
array=string.split
l=array.length
n=l-1
for i in 0..n
m=0
a=array[i]
array.each do |x|
if x==a
m+=1
end
end
puts "#{array[i]}=#{m}"
end
end
end
string1=gets
b=Array.new(string1)
b.array
| true |
049eb0c5be07f438708928d7fdc98d457ad70d71 | Ruby | zseero/Misc | /Haxor.rb | UTF-8 | 1,350 | 3.6875 | 4 | [] | no_license | def lotsOfNums
while true
puts Random.rand(0..(10000 ** 15))
end
end
def binary
while true
printf(Random.rand(0..1).to_s)
end
end
class Stream
def initialize count, width
@width = width
@sprites = []
count.times do @sprites << Random.rand(0..@width) end
end
def update
@sprites.map! do |sprite|
sprite += Random.rand((-1)..(1))
sprite = @width if sprite < 0
sprite = 0 if sprite > @width
sprite
end
end
def draw
s = ''
@width.times do |i|
if @sprites.include?(i)
s += '1'
else
s += '0'
end
end
puts s
end
end
def stream
printf "Stream Count: "
hack = Stream.new(gets.chomp.to_i, 60)
while true
hack.update
hack.draw
sleep 0.02
end
end
class Part
attr_accessor :time
def initialize(time)
@time = time
end
def update
@time -= 1 if @time > 0
end
def to_s
if @time > 0
'1'
else
'0'
end
end
end
def matrix
nums = []
printf "Width: "
width = gets.chomp.to_i - 1
width.times do
nums << Part.new(0)
end
while true
nums.map! do |num|
num.update
num
end
5.times do
index = Random.rand(0...width)
rI = index + 1
rI = 0 if rI >= width
lI = index - 1
lI = 0 if lI >= width
if nums[rI].time == 0 && nums[lI].time == 0
nums[index].time = Random.rand(0..20)
end
end
puts nums.join('')
sleep 0.02
end
end
matrix | true |
efd6fd25c8442490adf2fbb8a853fd0c0b328d8a | Ruby | hortencia718/programming-univbasics-nds-nested-arrays-iteration-lab-part-2-nyc04-seng-ft-071220 | /lib/iteration_with_loops.rb | UTF-8 | 1,019 | 3.5625 | 4 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | require 'pry'
def find_min_in_nested_arrays(src)
new_array =[]
count = 0
while count < src.length do
inner_count = 0
low_value = 100
while inner_count < src[count].length do # checking if the inner count is one less than the inner array.
if src[count][inner_count] < low_value # compare
low_value = src[count][inner_count]
end
inner_count += 1 # for loop only keeping adding until loop is done !
end
new_array << low_value
count += 1 # loop for outter array, or first while loop
end
new_array
end
# src will be an array of arrays of integers
# Produce a new Array that contains the smallest number of each of the nested arrays
# do that takes in an "one argument" of an AOArrays that contains sets of numbers"
# it "returns the smallest numbers from each set in a new Array" do
# expect(find_
# find_min_in_nested_arrays([19, 21, 24, 26, 30, 34, 37, 39, 40, 45, 48, 50, 55, 60, 63, 59, 49, 45, 40, 39, 34, 32, 25, 18]) | true |
0e7cd161a40820467e213d82e5fe55e9a95b03ff | Ruby | donjego/DevBootcamp | /test.rb | UTF-8 | 2,411 | 4.03125 | 4 | [] | no_license | vogels = [
{"name" => "Havik", "price" => 200},
{"name" => "Adelaar", "price" => 500},
{"name" => "Merel", "price" => 100},
{"name" => "Parkietje", "price" => 50}
]
def choose_bird_type
puts "Fill in the item number of the bird you want to buy (1-4)"
bird_type = gets.chomp.to_i
if bird_type <0 || bird_type >3
puts "U heeft geen geldige invoer gegeven. Kies item 0, 1, 2 of 3"
return choose_bird_type
end
return bird_type
end
def choose_number_of_birds
number_of_birds = gets.chomp.to_i
if number_of_birds <0
puts "U heeft geen geldige invoer gegeven. Kies het aantal vogels dat u wilt bestellen."
return choose_number_of_birds
end
if number_of_birds >9
puts "Zo veel van deze soort vogels hebben we helaas niet op voorraad. We hebben er nog 9 over."
puts "Hoe veel van deze soort vogels wilt u bestellen?"
return choose_number_of_birds
end
return number_of_birds
end
def choose_to_continue_or_quit
continue_or_quit = gets.chomp.to_i
if continue_or_quit < 1 || continue_or_quit > 2
puts "U heeft geen geldige invoer gegeven. Kies aub 1 om af te rekenen of 2 om meer te bestellen"
return choose_to_continue_or_quit
end
if continue_or_quit == 1
puts "U wordt nu doorgeleid naar de betalingspagina. Dank u wel!"
return continue_or_quit
end
if continue_or_quit == 2
puts "U wordt nu weer doorverwezen naar de shop"
return choose_bird_type
end
end
def process(vogels)
puts "Good morning Sir. Here is our list of birds:"
#puts "*" * 80
index = 0
while index < vogels.length
puts "#{index} #{vogels[index]["name"]}"
index += 1
end
bird_type = choose_bird_type
puts "You have selected #{vogels[bird_type]["name"]}"
puts "Een #{vogels[bird_type]["name"]} kost #{vogels[bird_type]["price"]} euro per stuk"
puts "Hoe veel #{vogels[bird_type]["name"]}s wilt u bestellen?"
number_of_birds = choose_number_of_birds
puts "Wat leuk dat u #{number_of_birds} van #{vogels[bird_type]["name"]}s wilt bestellen!"
totaalprijs = number_of_birds * vogels[bird_type]["price"]
puts "Dat kost u dan in totaal: #{totaalprijs} euro"
puts "Typ 1 als u wilt afrekenen of typ 2 als u meer vogels wilt bestellen"
continue_or_quit = choose_to_continue_or_quit
if continue_or_quit == 1
#puts "*" * 80
puts "Welkom bij de betalingpagina. Hoe wilt u betalen?"
end
end
process(vogels)
| true |
52b23162a7a937b9e8d0bf8696640567454d63ba | Ruby | dshcheung/WDI_HK_11 | /06-ruby/ruby-oop-classes/examples/rpg.rb | UTF-8 | 1,532 | 3.96875 | 4 | [] | no_license | class Human
attr_writer :weapon
def initialize hp, mp
@hp = hp
@mp = mp
end
def attack
if @weapon.nil?
"I punch enemy with my fists."
else
"I attack with my #{@weapon}."
end
end
def defend
"I block attacks with my bare arms."
end
end
class Knight < Human
attr_writer :shield
def initialize hp, mp, shield=nil
super hp, mp
@shield = shield
end
def defend
if @shield.nil?
super
else
"I defend with my #{@shield}"
end
end
end
class Mage < Human
def initialize hp, mp
super
@magic = nil
end
def learn magic
@magic = magic
end
def cast
if @magic.nil? || @mp.zero?
"Nothing happen."
else
@mp -= 10
"I cast #{@magic} to my enemy."
end
end
def attack
cast
end
def defend
if @mp.zero?
super
else
@mp -= 10
"I cast a protective spell."
end
end
end
puts "Peasant's moves"
peasant = Human.new 50, 10
p peasant.attack
peasant.weapon = :stick
p peasant.attack
p peasant.defend
puts
puts "Knight 1's moves"
knight1 = Knight.new 100, 10, :big_shield
p knight1.attack
p knight1.defend
knight1.weapon = :big_sword
p knight1.attack
puts
puts "Knight 2's moves"
knight2 = Knight.new 100, 10
knight2.weapon = :long_sword
p knight2.attack
p knight2.defend
knight2.shield = :round_shield
p knight2.defend
puts
puts "Mage's moves"
mage = Mage.new 70, 50
p mage.cast
mage.learn :fire
p mage.cast
p mage.defend
5.times { p mage.attack }
p mage.defend
puts
| true |
d1f8d64ee95a604abf14349231efd0a05220fb5f | Ruby | Xiaohong-Deng/ticketee | /app/models/state.rb | UTF-8 | 331 | 2.546875 | 3 | [] | no_license | class State < ActiveRecord::Base
# should I set a class variable @@default and update it
# each time make_default is called to get a better performance?
def self.default
find_by(default: true)
end
def to_s
name
end
def make_default!
State.update_all(default: false)
update!(default: true)
end
end
| true |
efb660c582ee36b9905a0e83f82555c60042ab78 | Ruby | Jewgonewild/project-yves | /lib/bmark.rb | UTF-8 | 3,127 | 3.390625 | 3 | [] | no_license | require 'benchmark'
# open Integer class adding the methods
class Integer
def one_bits
self.to_s(2).chars.inject(0) {|sum, c| c == "1" ? sum + 1 : sum}
end
def three_bits
sum = 0
self.to_s(2).each_char {|c| sum += 1 if c == "1" }
sum
end
def count_bits
self.to_s(2).count("1")
end
def count_arr
self.to_s(2).chars.count("1")
end
def del_size
self.to_s(2).delete('0').size
end
def mod_div
n = 0; a = self
while a > 0 do
n += 1 if a % 2 == 1
a = a/2
end
end
def mod_mult
n = 0; a = self
while a >= 1 do
n += 1 if a % 2 == 1
a = a * 0.5
end
end
def bin_bits
i = self; ret = 0
while i > 0
ret += i & 1
i = i >> 1
end
ret
end
end
# benchmark run n times fo int1 and int2
n = 100000; int1 = 10000; int2 = 10000000
puts [ "-"*30,"Ruby:", RUBY_VERSION, " Run ",n," times for integers ",int1, " and ", int2, "-"*30].join
Benchmark.bmbm(5) do |x|
x.report("one for #{int1}") {n.times {int1.one_bits}}
x.report("three for #{int1}") {n.times {int1.three_bits}}
x.report("count for #{int1}") {n.times {int1.count_bits}}
x.report("count-arr for #{int1}") {n.times {int1.count_arr}}
x.report("del_size for #{int1}") {n.times {int1.del_size}}
x.report("mod_div for #{int1}") {n.times {int1.mod_div}}
x.report("mod_mult for #{int1}") {n.times {int1.mod_mult}}
x.report("bin for #{int1}") {n.times {int1.bin_bits}}
x.report("one for #{int2}") {n.times {int2.one_bits}}
x.report("three for #{int2}") {n.times {int2.three_bits}}
x.report("count for #{int2}") {n.times {int2.count_bits}}
x.report("count-arr for #{int2}") {n.times {int2.count_arr}}
x.report("del_size for #{int2}") {n.times {int2.del_size}}
x.report("mod_div for #{int2}") {n.times {int2.mod_div}}
x.report("mod_mult for #{int2}") {n.times {int2.mod_mult}}
x.report("bin for #{int2}") {n.times {int2.bin_bits}}
end
#user system total real
#one for 10000 0.550000 0.000000 0.550000 ( 0.551101)
#three for 10000 0.440000 0.000000 0.440000 ( 0.446126)
#count for 10000 0.070000 0.000000 0.070000 ( 0.066558)
#count-arr for 10000 0.370000 0.000000 0.370000 ( 0.368766)
#del_size for 10000 0.150000 0.000000 0.150000 ( 0.148929)
#mod_div for 10000 0.120000 0.000000 0.120000 ( 0.122377)
#mod_mult for 10000 0.350000 0.000000 0.350000 ( 0.346107)
#bin for 10000 0.170000 0.000000 0.170000 ( 0.167473)
#one for 10000000 0.900000 0.000000 0.900000 ( 0.907838)
#three for 10000000 0.770000 0.000000 0.770000 ( 0.774772)
#count for 10000000 0.100000 0.000000 0.100000 ( 0.104776)
#count-arr for 10000000 0.560000 0.000000 0.560000 ( 0.566864)
#del_size for 10000000 0.220000 0.000000 0.220000 ( 0.217357)
#mod_div for 10000000 0.190000 0.000000 0.190000 ( 0.191047)
#mod_mult for 10000000 0.590000 0.000000 0.590000 ( 0.591380)
#bin for 10000000 0.280000 0.000000 0.280000 ( 0.278790)
#
| true |
16508e86bb7a9ce6d3a5623ee504ccf911f96e96 | Ruby | KarthikJagadish/LearningRuby | /freeCodeCamp.org/Ruby/6BuildingCalculator.rb | UTF-8 | 549 | 4.75 | 5 | [] | no_license | puts "Enter a number: "
num1 = gets.chomp() # gets.chomp().to_f / gets.chomp().to_i
puts "Enter another number"
num2 = gets.chomp() # gets.chomp().to_f / gets.chomp().to_i
puts (num1 + num2) # if num1 = 2 and num2 = 5, Ruby would just print out 25 - as it will treat the user input as strings, no matter what number the user inputs
# ^ concatinating the strings
puts (num1.to_i + num2.to_i) # converting user input to integer using .to_i and adding them
puts (num1.to_f + num2.to_f) # converting user input to float using .to_f and adding them
| true |
a03e8a0918195d0f430fe606240f9f773c41aa18 | Ruby | lishulongVI/leetcode | /ruby/647.Palindromic Substrings(回文子串).rb | UTF-8 | 2,301 | 4.03125 | 4 | [
"MIT"
] | permissive | =begin
<p>
Given a string, your task is to count how many palindromic substrings in this string.
</p>
<p>
The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.
</p>
<p><b>Example 1:</b><br />
<pre>
<b>Input:</b> "abc"
<b>Output:</b> 3
<b>Explanation:</b> Three palindromic strings: "a", "b", "c".
</pre>
</p>
<p><b>Example 2:</b><br />
<pre>
<b>Input:</b> "aaa"
<b>Output:</b> 6
<b>Explanation:</b> Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".
</pre>
</p>
<p><b>Note:</b><br>
<ol>
<li>The input string length won't exceed 1000.</li>
</ol>
</p><p>给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。</p>
<p>具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> "abc"
<strong>输出:</strong> 3
<strong>解释:</strong> 三个回文子串: "a", "b", "c".
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> "aaa"
<strong>输出:</strong> 6
<strong>说明:</strong> 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>输入的字符串长度不会超过1000。</li>
</ol>
<p>给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。</p>
<p>具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。</p>
<p><strong>示例 1:</strong></p>
<pre>
<strong>输入:</strong> "abc"
<strong>输出:</strong> 3
<strong>解释:</strong> 三个回文子串: "a", "b", "c".
</pre>
<p><strong>示例 2:</strong></p>
<pre>
<strong>输入:</strong> "aaa"
<strong>输出:</strong> 6
<strong>说明:</strong> 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
</pre>
<p><strong>注意:</strong></p>
<ol>
<li>输入的字符串长度不会超过1000。</li>
</ol>
=end
# @param {String} s
# @return {Integer}
def count_substrings(s)
end | true |
acffa2235b29419fe60c8875b7ffa9fc4064c24f | Ruby | Kysariin/learn-co-sandbox | /aboutme.rb | UTF-8 | 710 | 4.0625 | 4 | [] | no_license | # fill in the blank of a method vvvvvvv
# def aboutme(your_name, your_place, your_age, your_fun)
# puts "Your name is #{your_name}"
# puts "You grew up in #{your_place}"
# puts "You are #{your_age} years old"
# puts "Your favorite food is #{your_fun}"
# end
# aboutme("Kate", "St. Paul", "14", "sushi")
# this is a get.chomp attempt at a method vvvvvv
# puts "What is your name?"
# #your_name = gets.chomp
# def say_hello(your_name)
# puts "Hello, #{your_name}!"
# end
# say_hello(your_name)
# using multiple variables with a default below vvvvvv
# def sayhi(your_name, my_name = "Kate", last_name)
# puts "Hello, #{your_name}, my name is #{my_name} #{last_name}!"
# end
# sayhi("Karl", "Harris")
| true |
363f481d1ca79f3e7044e148428e526219f7c489 | Ruby | simonjamain/designexporter | /helpers/anteriorityCheck | UTF-8 | 838 | 2.9375 | 3 | [] | no_license | #!/usr/bin/env ruby
# encoding: utf-8
require 'optparse'
files = {}
optionParser = OptionParser.new do|options|
options.banner = "Usage: anteriorityCheck [options]\nReturn 1 if specified anteriority is not met"
options.on('-o', '--old OLD_FILE', 'mandatory : specify which file should be older than the other' ) do |oldFile|
files[:old] = oldFile
end
options.on('-n', '--new OLD_FILE', 'mandatory : specify which file should be newer than the other' ) do |newFile|
files[:new] = newFile
end
options.on_tail( '-h', '--help', 'Display this screen' ) do
puts options
exit
end
end
optionParser.parse!
raise OptionParser::MissingArgument if files[:old].nil?
raise OptionParser::MissingArgument if files[:new].nil?
exit 1 if File.mtime(files[:old]) > File.mtime(files[:new])
| true |
54f2a181af0d623eb23cbbad1cd04bf299d18f3e | Ruby | hkee/sinatra-board | /app.rb | UTF-8 | 1,671 | 2.59375 | 3 | [] | no_license | gem 'json', '~> 1.6'
require 'sinatra'
require 'sinatra/reloader'
require 'bcrypt'
require './model.rb'
before do
p '***************************'
p params
p '***************************'
end
get '/' do # routing, '/' 경로로 들어왔을 때
send_file 'index.html' # index.html 파일을 보내줘
end
get '/lunch' do # '/lunch' 경로로 들어왔을 때
@lunch = ["멀캠20층", "바스버거", "소고기"]
erb :lunch # views폴더 안에 있는 lunch.erb를 보여줘
end
# 게시글을 모두 보여주는 곳
get '/posts' do
@posts = Post.all
erb :'posts/posts'
end
# 게시글을 쓸 수 있는 곳
get '/posts/new' do
erb :'posts/new'
end
get '/posts/create' do
@title = params[:title]
@body = params[:body]
Post.create(title: @title, body: @body)
erb :'posts/create'
end
get '/posts/:id' do
# 게시글 id를 받아서
@id = params[:id]
# db에서 찾는다
@post = Post.get(@id)
erb:'posts/show'
end
get '/posts/destroy/:id' do
Post.get(params[:id]).destroy
# erb :'posts/destroy'
redirect '/posts'
end
# 값을 받아서 뿌려주기 위한 용도
get '/posts/edit/:id' do
@id = params[:id]
@post = Post.get(@id)
erb :'posts/edit'
end
get '/posts/update/:id' do
@id = params[:id]
Post.get(@id).update(title: params[:title], body: params[:body])
redirect '/posts/'+@id
end
get '/users/new' do
erb :"users/new"
end
get '/users/create' do
if params[:pwd] !=params[:pwd_confirm]
redirect '/'
else
User.create(name: params[:name],email: params[:email],password: Bcrpyt::password.create(params[:pwd]))
end
erb :"users/create"
end
get '/users' do
@users=User.all
erb:"users/users"
end
| true |
16558b1aa47ff7accfc596de00c5a63c102024d3 | Ruby | JosefHartsough/COVID-19-Prediction | /jupyter/graph_data/convert_areas.rb | UTF-8 | 1,720 | 2.90625 | 3 | [
"MIT"
] | permissive | #!/usr/bin/env ruby
ARGV.each do|a|
puts "Argument: #{a}"
if File.exist?(a)
contents = File.read(a);
bak = a + '.bak'
File.rename(a, bak)
contents = contents.lines.to_a
contents = contents.map do | line |
line = line.chomp! + "\n"
unmodified_line = line
line.gsub!(" ", "_") if line.include?(" ")
line.gsub!(",", "_") if line.include?(",")
line.gsub!("__", "_") if line.include?("__")
line.chomp!
line = "\'" + line + "\',\n"
line
end
states = [
"Alabama", "Alaska", "American Samoa", "Arizona", "Arkansas", "California", "Colorado",
"Connecticut", "Delaware", "Florida", "Georgia", "Guam", "Hawaii",
"Idaho", "Illinois", "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland",
"Massachusetts", "Michigan", "Minnesota", "Mississippi",
"Missouri", "Montana", "Nebraska", "Nevada", "New_Hampshire", "New_Jersey", "New_Mexico",
"New_York", "North_Carolina", "North_Dakota", "Ohio",
"Oklahoma", "Oregon", "Pennsylvania", "Puerto_Rico", "Rhode_Island", "South_Carolina",
"South_Dakota", "Tennessee", "Texas", "Virgin_Islands", "Utah", "Vermont", "Virginia",
"Washington", "West_Virginia", "Wisconsin", "Wyoming"
]
content_states = {}
states.each do |state|
content_states[state] = contents.select{|entry| entry.include?(state)}
end
content_states.each do |k, v|
v = v.join("")
text = k + ".txt"
File.open(text, 'w') {|file| file.write(v) }
end
# Convert from array to string
contents = contents.join("")
# Write the modified contents to the file.
File.open(a, 'w') {|file| file.write(contents) }
end
end
| true |
679b357ecb39b6efef0aef68b9293c1ed9f50040 | Ruby | hulkfu/ruby-study | /params.rb | UTF-8 | 511 | 3.71875 | 4 | [] | no_license | def my_method( a='Testing', b='this', c='feature' )
puts "#{a} #{b} #{c}"
end
my_method
my_method( 'Trying out' )
my_method( 'Testing', 'this great' )
def hello(*params)
params.each do |param|
puts param
end
puts params
end
hello "hi","d"
##
# 最后一个参数可以是hash
def hi(options={})
name = options[:name]
age = options[:age]
sex = options[:sex] || 'securet'
puts "I am #{name}, I am #{age} and my sex is #{sex}"
end
hi(name:"Jim", age:18, sex:"male")
hi name:"Bill", age:18 | true |
66f9ff64de8dc4099380914c82089c3da946cf85 | Ruby | twarbelow/backend_module_0_capstone | /day_4/exercises/methods.rb | UTF-8 | 928 | 4.65625 | 5 | [] | no_license | # In the below exercises, write code that achieves
# the desired result. To check your work, run this
# file by entering the following command in your terminal:
# `ruby day_4/exercises/methods.rb`
# Example: Write a method that when called will print your name:
def print_name
p "Taija Warbelow"
end
print_name
# Write a method that takes a name as an argument and prints it:
def print_name(name)
p "#{name}"
end
print_name("Albus Dumbledore")
# Write a method that takes in 2 numbers as arguments and prints
# their sum. Then call your method:
def sum(a, b)
puts a + b
end
sum(3, 4)
# Write a method that takes in two strings as arguments and prints
# a concatenation of those two strings. Example: The arguments could be
# (man, woman) and the end result might output: "When Harry Met Sally".
# Then call your method:
def together(part_1, part_2)
p "#{part_1} #{part_2}"
end
together("Roses are red,", "and violets are blue.")
| true |
1705be30e86fee07730591b8c732e9f115329318 | Ruby | Kotauror/Tic_Tac_Toe_8th_Light | /lib/Computer.rb | UTF-8 | 1,680 | 3.46875 | 3 | [] | no_license | require_relative 'player'
require_relative 'board'
class Computer < Player
def elaborate_move(board, opponent_sign)
sleep(1)
position = pick_5_when_possible(board)
if position == nil then
position = pick_winning_position(board)
if position == nil then
position = block_opponent(board, opponent_sign)
if position == nil then
position = pick_corner(board)
if position == nil then
position = random_move(board)
end
end
end
end
return position
end
def pick_5_when_possible(board)
return "5" if board.available_numbers.include?("5")
end
def pick_winning_position(board)
board.available_numbers.each { |available_cell|
board.put_sign_on_board(self.sign, available_cell)
if board.is_game_won?
best_move = available_cell
board.put_sign_on_board(available_cell, available_cell)
return best_move
else
board.put_sign_on_board(available_cell, available_cell)
end
}
return nil
end
def block_opponent(board, opponent_sign)
board.available_numbers.each { |available_cell|
board.put_sign_on_board(opponent_sign, available_cell)
if board.is_game_won?
best_move = available_cell
board.put_sign_on_board(available_cell, available_cell)
return best_move
else
board.put_sign_on_board(available_cell, available_cell)
end
}
return nil
end
def pick_corner(board)
board.values.find { |num|
num == "1" || num == "3" || num == "7" || num == "9"
}
end
def random_move(board)
board.available_numbers.sample
end
end
| true |
512888504516a4caa23be569192f77c412a2fd5e | Ruby | raresdragusSV/RailsAntipatterns | /01_Models/04_Duplicate_Code_Duplication/02_Write_a_Plugin/models/car.rb | UTF-8 | 286 | 2.703125 | 3 | [] | no_license | class Car < ActiveRecord::Base
validates_presence_of :direction, :speed
def turn(new_direction)
self.direction = new_direction
end
def brake
self.speed = 0
end
def accelerate
self.speed = [speed + 10, 100].min
end
# Other, car-related activities ...
end
| true |
25539de13a8c8b9bc698d6d981880aa24f071c64 | Ruby | Tonyjlum/prime-ruby-prework | /prime.rb | UTF-8 | 125 | 3 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | # Add code here!
def prime?(num)
return false if num < 2
(2...num).each {|el| return false if num % el == 0}
true
end
| true |
309342bf0f5d6f95f8672f7cf6dd6f05aeeb3e5f | Ruby | Roeck/ruby-music-library-cli-v-000 | /lib/music_library_controller.rb | UTF-8 | 3,027 | 3.546875 | 4 | [
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] | permissive | class MusicLibraryController
attr_accessor :path
def initialize(path = './db/mp3s')
@path = path
path_import = MusicImporter.new(path)
path_import.import
end
def call
input = ""
puts "Welcome to your music library!"
until input == "exit"
puts "To list all of your songs, enter 'list songs'."
puts "To list all of the artists in your library, enter 'list artists'."
puts "To list all of the genres in your library, enter 'list genres'."
puts "To list all of the songs by a particular artist, enter 'list artist'."
puts "To list all of the songs of a particular genre, enter 'list genre'."
puts "To play a song, enter 'play song'."
puts "To quit, type 'exit'."
puts "What would you like to do?"
input = gets.strip
case input
when 'list songs'
list_songs
when 'list artists'
list_artists
when 'list genres'
list_genres
when 'list artist'
list_songs_by_artist
when 'list genre'
list_songs_by_genre
when 'play song'
play_song
end
end
end
def list_songs
sorted_songs = Song.all.sort_by { |s| s.name }
i = 0
sorted_songs.each { |s| puts "#{i += 1}. #{s.artist.name} - #{s.name} - #{s.genre.name}"}
end
def list_artists
sorted_artists = Artist.all.sort_by {|a| a.name}
i = 0
sorted_artists.each {|obj| puts "#{i += 1}. #{obj.name}"} #{obj.songs[0].name} - #{obj.songs[0].genre.name}"} /*/// oops.. tried to add songs and genres /////*/
end
def list_genres
sorted_genres = Genre.all.sort_by {|g| g.name}
i = 0
sorted_genres.each {|g| puts "#{i += 1}. #{g.name}"}
end
def list_songs_by_artist
puts "Please enter the name of an artist:"
input = gets.strip
if Artist.find_by_name(input)
artist= Artist.find_by_name(input)
array = artist.songs.sort { |a, b| a.name <=> b.name }
array.each_with_index do |val,index|
puts "#{index+1}. #{val.name} - #{val.genre.name}"
end
end
end
def list_songs_by_genre
puts "Please enter the name of a genre:"
input = gets.chomp
if Genre.find_by_name(input)
genre= Genre.find_by_name(input)
array = genre.songs.sort { |a, b| a.name <=> b.name }
array.each_with_index do |val,index|
puts "#{index+1}. #{val.artist.name} - #{val.name}"
end
end
end
def play_song
puts "Which song number would you like to play?"
list = Song.all.sort_by {|x| x.name}
input = gets.strip
if input.to_i <= list.length && input.to_i > 0
puts "Playing #{list[input.to_i - 1].name} by #{list[input.to_i - 1].artist.name}"
end
end
end
| true |
faa653489af8219892d0263721dce545c79f622c | Ruby | kopylovvlad/hamdown_core | /lib/hamdown_core/cli.rb | UTF-8 | 551 | 2.578125 | 3 | [
"MIT"
] | permissive | # frozen_string_literal: true
require 'optparse'
require_relative 'version'
module HamdownCore
module Cli
def self.call(argv)
file_name = OptionParser.new.tap do |parser|
parser.version = VERSION
end.parse!(argv).first
if file_name.nil? || file_name.size == 0
puts 'Error: No file.'
puts 'Use it like: "exe/hamdown_core path_to/file.hd > output.html"'
return nil
end
content = File.open(file_name, 'r').read
output = Engine.call(content)
puts output
end
end
end
| true |
fc35af653c5c3f4905258d6ae68f4b0f51a16fac | Ruby | jhartwell/ironruby | /Tests/Experiments/Scope/LocalsAndClosures.rb | UTF-8 | 914 | 3.546875 | 4 | [] | no_license | def visibility
x = 1
1.times { |i|
z = x + i
1.times { |j|
w = z + j
}
puts w rescue puts $!
}
puts z rescue puts $!
end
def init
5.times { |i|
if i == 0
x = 1
else
x = (x.nil? ? 0 : x) + 2
end
puts x
}
end
def closure
p = []
2.times { |i|
p << lambda {
puts i
}
}
p[0][]
p[1][]
end
def closure_binding
p = []
2.times { |i|
p << binding
}
eval('puts i', p[0])
eval('puts i', p[1])
end
def module_scope
eval('
$p = []
$i = 0
while $i < 2
module M
x = $i
$p << binding
end
$i += 1
end
')
eval('puts x', $p[0])
eval('puts x', $p[1])
end
visibility
puts '---'
init
puts '---'
closure
puts '---'
closure_binding
puts '---'
module_scope
puts '---'
puts 'done' | true |
cdeeebefeb66174d7d9c7680df852c6f52db4df5 | Ruby | philipecasarotte/TiAna | /vendor/plugins/restful-authorization/generators/authorized_generator_helpers.rb | UTF-8 | 1,003 | 2.53125 | 3 | [
"MIT"
] | permissive | module AuthorizedGeneratorHelpers
def insert_content_after(filename, regexp, content_for_insertion, options = {})
content = File.read(filename)
options[:unless] ||= lambda {false }
# already have the function? Don't generate it twice
unless options[:unless].call(content)
# find the line that has the model declaration
lines = content.split("\n")
found_line = nil
0.upto(lines.length-1) {|line_number|
found_line = line_number if regexp.match(lines[line_number])
}
if found_line
# insert the rest of these lines after the found line
lines.insert(found_line+1, content_for_insertion)
content = lines * "\n"
File.open(filename, "w") {|f| f.puts content }
return true
end
else
return false
end
end
def render_template(name)
template = File.read( File.join( File.dirname(__FILE__), "authorized/templates", name))
ERB.new(template, nil, "-").result(binding)
end
end | true |
612c53c779425da4b76aad7b6498e5ddf1bde55d | Ruby | gamboltok/rubybeginner | /nasledovanie.rb | UTF-8 | 265 | 3.59375 | 4 | [] | no_license | class Car
def color_and_fuel(color, fuel)
@color = color
@fuel = fuel
puts "color is #{color}, fuel is #{fuel}"
puts
end
end
class Boat < Car
end
boat = Boat.new
puts "#{boat.color_and_fuel("black", 100)}" | true |
c04da9206c0fb2ee93a42da760676e23c69e0bf9 | Ruby | pekellogg/ttt-9-play-loop | /bin/play | UTF-8 | 239 | 3.4375 | 3 | [] | no_license | #!/usr/bin/env ruby
require_relative "../lib/play"
# initialize board, welcome user, display empty board
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
puts "Welcome to Tic Tac Toe!"
display_board(board)
# begin game
play(board)
| true |
cd502236129a9eb2d49c2c080335a9d0283cc8f1 | Ruby | Kyodex/Parsing | /all_incubator.rb | UTF-8 | 433 | 2.53125 | 3 | [] | no_license | require "nokogiri"
require"open-uri"
def get_all_incubator (web_site)
page = Nokogiri::HTML(open(web_site))
for i in (1..30)
page.xpath("//tr[#{i}]/td[1]/strong").each do |incubator|
inc = incubator.text
puts inc
end
end
end
get_all_incubator("https://lentreprise.lexpress.fr/creation-entreprise/etapes-creation/le-palmares-des-incubateurs-d-entreprise-dans-les-ecoles-de-commerce_1524810.html")
| true |
77bff4577aa282cd8d0aa30f5e9624249761ed56 | Ruby | hadarhaviv/budget_system | /Account.rb | UTF-8 | 1,164 | 3.265625 | 3 | [] | no_license | require "json"
require "./FileUtilities.rb"
class Account
attr_accessor :records
attr_reader :balance
def initialize(name, balance)
@name = name
@balance = balance
@records = get_records
end
def get_records
if !FileUtilities.load("records").nil?
FileUtilities.load("records")[:records]
else
[]
end
end
def deposit(amount, description)
@balance += amount
record = {
type: "income",
description: description,
amount: amount
}
@records = @records.push(record)
FileUtilities.save("records", {"records" => records})
FileUtilities.save("user", {"name" => @name, "balance" => @balance})
end
def withdraw(amount, description)
@balance -= amount
record = {
type: "expanse",
description: description,
amount: amount
}
@records = @records.push(record)
FileUtilities.save("records", {"records" => records})
FileUtilities.save("user", {"name" => @name, "balance" => @balance})
end
def list_records(search_query = "")
@records.any? ? @records.select { |record| record[:description].include? search_query } : []
end
end
| true |
af3ec1ab85478d2bdc24afcdf20c6eef3df14312 | Ruby | 1tsGurpreet/Website-Analysis-Project | /cse-135.site/public_html/cgi-bin/ruby-general-request-echo.rb | UTF-8 | 680 | 2.8125 | 3 | [] | no_license | #!/usr/bin/ruby
require 'cgi'
cgi = CGI.new
print cgi.header
print "<html>"
print "<head>"
print "<title>General Request Echo</title>"
print "</head>"
print "<body>"
print "<h1>General Request Echo</h1>"
print "<b> Protocol: </b>"
print(ENV["SERVER_PROTOCOL"])
print "<br></br>"
print "<b> Method: </b>"
print(ENV["REQUEST_METHOD"])
print "<br></br>"
print "<b> Query String: </b>"
print(ENV["QUERY_STRING"])
print "<br></br>"
print "<b> Parsed Query: </b>"
print(CGI::parse(ENV["QUERY_STRING"]))
print "<br></br>"
print "<b> Message Body: </b>"
for i in cgi.keys do
print i
print(" = ")
print cgi[i]
print("<br></br>")
end
print "</body>"
print "</html>"
| true |
64fad7a84dc7130bdb43e4213d68fb2ada12a0c3 | Ruby | sharon-tickell/thing | /app/lib/pennsic.rb | UTF-8 | 489 | 2.71875 | 3 | [] | no_license | class Pennsic
def self.year
Time.now.year - 1972 + 1
end
def self.as
'LI'
end
def self.calendar_year
Time.now.year
end
def self.dates
(Date.parse('2016-07-29')..Date.parse('2016-08-14')).to_a
end
def self.dates_formatted
dates.map(&:to_s)
end
def self.class_dates
(Date.parse('2016-08-01')..Date.parse('2016-08-12')).to_a.map(&:to_s)
end
def self.class_times
[ '9am to Noon', 'Noon to 3pm', '3pm to 6pm', 'After 6pm' ]
end
end
| true |
4d6e642a6c491cae882819b22acdb95a43bd14b8 | Ruby | pzol/monadic | /lib/monadic/try.rb | UTF-8 | 517 | 2.953125 | 3 | [
"MIT"
] | permissive | module Monadic
## Wrap a block or a predicate to always return Success or Failure.
## It will catch StandardError and return as a Failure.
def Try(arg = nil, &block)
begin
predicate = arg.is_a?(Proc) ? arg.call : arg
return Either(block.call) if block_given? && predicate.nil?
return Either(predicate).class.unit(block.call) if block_given? # use predicate for Success/Failure and block for value
return Either(predicate)
rescue => error
Failure(error)
end
end
end
| true |
5b0741be6903697aed43d097fc351125377a7d39 | Ruby | danielacodes/ruby-exercises | /moving_average.rb | UTF-8 | 470 | 4.15625 | 4 | [] | no_license | # Program which takes array and range and
# returns new array which contains moving average
def moving_average(array,range)
average = Array.new
sum = 0
array.each_with_index do |a,i|
sum += a
if (i>=range)
sum -= array[i-range]
end
if (i<range)
average << (sum/(i+1))
else
average << (sum/range)
end
end
puts "[#{average.join(',')}]"
end
my_array = [1,2,3,4,5,6]
my_range = 3
moving_average(my_array,my_range)
| true |
2437cff68d375ad7d51b85d3cf2e6d3ea1b5bee3 | Ruby | meetcleo/postgres_to_redshift | /lib/postgres_to_redshift/column.rb | UTF-8 | 2,069 | 2.609375 | 3 | [
"MIT"
] | permissive | module PostgresToRedshift
class Column
DEFAULT_PRECISION = 19 # 99_999_999_999_999_999.99
DEFAULT_SCALE = 2
CAST_TYPES_FOR_COPY = {
'text' => 'CHARACTER VARYING(65535)',
'json' => 'CHARACTER VARYING(65535)',
'jsonb' => 'CHARACTER VARYING(65535)',
'bytea' => 'CHARACTER VARYING(65535)',
'money' => "DECIMAL(#{DEFAULT_PRECISION},#{DEFAULT_SCALE})",
'oid' => 'CHARACTER VARYING(65535)',
'ARRAY' => 'CHARACTER VARYING(65535)',
'USER-DEFINED' => 'CHARACTER VARYING(65535)',
'uuid' => 'CHARACTER VARYING(36)',
'interval' => 'CHARACTER VARYING(65535)'
}.freeze
def initialize(attributes:)
@attributes = attributes
end
def name
attributes['column_name']
end
def name_for_copy
if needs_type_cast?
case data_type
when 'numeric'
precision = (numeric_precision || DEFAULT_PRECISION).to_i + 1 # number of digits + the dot
scale = numeric_scale || DEFAULT_SCALE
%[CAST(RIGHT(ROUND("#{name}", #{scale})::text, #{precision}) AS #{data_type_for_copy}) AS #{name}]
else
%[CAST("#{name}" AS #{data_type_for_copy}) AS #{name}]
end
else
%("#{name}")
end
end
def data_type
attributes['data_type']
end
def numeric_scale
attributes['numeric_scale']
end
def numeric_precision
attributes['numeric_precision']
end
def not_null?
attributes['is_nullable'].to_s.downcase == 'no'
end
def data_type_for_copy
type = CAST_TYPES_FOR_COPY[data_type] || data_type
handle_additional_type_attributes(type)
end
private
attr_reader :attributes
def handle_additional_type_attributes(type)
case type
when 'numeric'
precision = numeric_precision || DEFAULT_PRECISION
scale = numeric_scale || DEFAULT_SCALE
"#{type}(#{precision},#{scale})"
else
type
end
end
def needs_type_cast?
data_type != data_type_for_copy
end
end
end
| true |
bfa3b82b4025df21503f680e0a98116dc86f08f7 | Ruby | namusyaka/sinatra-bind | /test/bind_test.rb | UTF-8 | 2,354 | 2.546875 | 3 | [
"MIT"
] | permissive | $:.unshift(File.dirname(__FILE__))
require 'helper'
describe Sinatra::Bind do
describe "basic usage" do
it "can define a route" do
mock_app do
def hello; "Hello World" end
on "/", to: :hello
end
get '/'
assert_equal 'Hello World', last_response.body
end
it "can define a route correctly even if path contains named params" do
mock_app do
def show(id, type); "id: #{id}, type: #{type}" end
on "/show/:id/:type", to: :show
end
get '/show/1234/frank'
assert_equal 'id: 1234, type: frank', last_response.body
end
it "should support instance variable sharing" do
mock_app do
before("/foo"){ @a = "hey" }
def hey; @a end
on "/foo", to: :hey
end
get '/foo'
assert_equal 'hey', last_response.body
end
it "can define a filter" do
mock_app do
def bar; @b = "bar" end
def show_bar; @b end
on "/bar", to: :bar, type: :before
on "/bar", to: :show_bar
end
get '/bar'
assert_equal 'bar', last_response.body
end
end
describe "compatbility with sinatra" do
it "can use route options" do
mock_app do
require 'json'
def hello; JSON.dump(:a => "b") end
on "/", to: :hello, provides: :json
end
get "/"
assert_equal "application/json", last_response.headers["Content-Type"]
assert_equal '{"a":"b"}', last_response.body
end
it "should add the HEAD route if the GET route is added" do
mock_app do
def hello; "hello world" end
on "/", to: :hello
end
head "/"
assert_equal 200, last_response.status
end
it "should invoke the :route_added hook when route is added" do
module RouteAddedTest
@routes, @procs = [], []
def self.routes ; @routes ; end
def self.procs ; @procs ; end
def self.route_added(verb, path, proc)
@routes << [verb, path]
@procs << proc
end
end
app = mock_app do
register RouteAddedTest
def hello; "hello world" end
on "/", to: :hello
end
assert_equal RouteAddedTest.routes, [["GET", "/"], ["HEAD", "/"]]
assert_equal RouteAddedTest.procs, [app.send(:instance_method, :hello)] * 2
end
end
end
| true |
5e20e547bcc197c418e6205fd57cbd41c9ab48a6 | Ruby | outragedpinkracoon/advent_of_code_2020 | /day_9/part_2_spec.rb | UTF-8 | 772 | 2.984375 | 3 | [] | no_license | # frozen_string_literal: true
require 'rspec'
require_relative 'part_2'
RSpec.describe do
it 'returns the correct value when the sample is exactly the answer set' do
input = File.readlines('sample_3.txt')
expect(Part2.run(input, 127)).to eq([62])
end
it 'returns the correct value when it has to iterate one extra time' do
input = File.readlines('sample_4.txt')
expect(Part2.run(input, 127)).to eq([62])
end
it 'returns the correct value from the sample data' do
input = File.readlines('sample_5.txt')
expect(Part2.run(input, 127)).to eq([62])
end
it 'returns the correct value from the actual data' do
input = File.readlines('actual.txt')
expect(Part2.run(input, 105_950_735)).to eq([13_826_915, 211_901_470])
end
end
| true |
567bc49d617ae59bc87b8139ee4f72ae852bc3ab | Ruby | bfitch/Dollars | /app/models/current_period.rb | UTF-8 | 438 | 2.875 | 3 | [] | no_license | class CurrentPeriod < Struct.new(:schedule)
def as_range
Range.new(*dates)
end
def dates
[start.to_date, stop.to_date]
end
private
def start
Occurence.new schedule.previous_occurrence(today)
end
def stop
Occurence.new schedule.next_occurrence(today)
end
def today
@today ||= Time.now
end
class Occurence < Struct.new(:time)
def to_date
Date.parse(time.to_s)
end
end
end
| true |
db638ebe051c43b6396f78c58ce83013b26155c2 | Ruby | madking55/ruby_exercises | /command-query/exercises/kid.rb | UTF-8 | 361 | 3.359375 | 3 | [] | no_license | class Kid
attr_reader :grams_of_sugar_eaten
def initialize
@grams_of_sugar_eaten = 0
@hyperactive = false
end
def eat_candy
@grams_of_sugar_eaten += 5
end
def hyperactive?
@hyperactive = true if @grams_of_sugar_eaten >= 60
@hyperactive ? "OK, now the kid is hyperactive." : "Not hyperactive yet..."
@hyperactive
end
end | true |
f58890beb1eadefeedfb340d30b816643ef97e10 | Ruby | SamaNaEz/Infix-to-Postfix-Converter-and-Calculator | /calculator.rb | UTF-8 | 1,169 | 3.6875 | 4 | [
"MIT"
] | permissive | class Calculator_v2
attr_reader :oper
def initialize
@oper = {
'+' => 1,
'-' => 1,
'*' => 2,
'/' => 2,
'%' => 3,
'**' => 3
}
end
def infix_to_postfix(infix)
stack = []
postfix = []
stack_value = 0
infix_value = 0 # not necessary
infix.split.each_with_index do |v, idx|
postfix.push(v) if v =~ /[0-9]/
stack.push(v) if v == '('
if oper.include?(v)
stack_value = oper.fetch(stack.last, stack_value)
infix_value = oper[v]
postfix.push(stack.pop) if stack_value >= infix_value
stack.push v
elsif v == ')'
postfix.push(stack.pop) while stack.last != '('
stack.pop
end
end
(postfix + stack.reverse).join ' '
end
def eval_postfix(str_val)
stack_int = []
str_val.split.each do |chr|
stack_int.push(chr.to_f) if chr =~ /[0-9]/
if oper.include?(chr)
x = stack_int.pop
y = stack_int.pop
stack_int.push(y.send(chr, x))
end
end
stack_int.pop
end
def calculate(str_val)
conv = infix_to_postfix(str_val)
eval_postfix(conv)
end
end
| true |
099a79b75b27f2038be4b34027c77c75817a7e63 | Ruby | themarshallproject/pony | /app/lib/merge_tag.rb | UTF-8 | 205 | 2.859375 | 3 | [
"MIT"
] | permissive | class MergeTag
def self.recognize(text)
re = /\*\|([A-Z_0-9:]+)\|\*/
# the first capture group is the tag name, so &:first unwraps `[val]` to `val`
text.scan(re).map(&:first).uniq
end
end
| true |
0c2628b1b4b55760df5312cb3efc52fe176890fd | Ruby | unifide/unifide | /www/json_reply.rb | UTF-8 | 5,612 | 2.859375 | 3 | [] | no_license | require 'json'
require 'model'
class JSONReply
def self.write_project(user, project_name, hm)
project = Project.find_by_short_name project_name
if !project.nil?
#The project exists
if user_can_write_project? user, project
#The user can write to the project
yield project
else
hm[:errors] = [@@error_messages[:write_permission]]
end
else
hm[:errors] = [@@error_messages[:no_project]]
end
end
def self.access_project(user, project_name, hm)
project = Project.find_by_short_name project_name
if !project.nil?
#The project exists
if user_can_see_project? user, project
#The user can access the project
yield project
else
hm[:errors] = [@@error_messages[:permission]]
end
else
hm[:errors] = [@@error_messages[:no_project]]
end
end
def self.write_unit_type(user, project_name, type_name, hm)
self.write_project user, project_name, hm do |project|
unit_type = UnitType.find_by_name type_name
yield project, unit_type
end
end
def self.access_unit_type(user, project_name, type_name, hm)
self.access_project user, project_name, hm do |project|
unit_type = UnitType.find_by_name type_name
if !unit_type.nil?
yield project, unit_type
else
hm[:errors] = [@@error_messages[:no_unit_type]]
end
end
end
def self.write_unit(user, project_name, type_name, name, hm)
self.write_unit_type user, project_name, type_name, hm do |project, unit_type|
if !unit_type.nil?
unit = find_unit project, unit_type, name
yield project, unit_type, unit
else
hm[:errors] = [@@errors[:no_unit_type]]
end
end
end
def self.access_unit(user, project_name, type_name, name, hm)
self.access_unit_type user, project_name, type_name, hm do |project, unit_type|
#The unit type exists
unit = find_unit project, unit_type, name
if !unit.nil?
yield project, unit_type, unit
else
hm[:errors] = [@@error_messages[:no_unit]]
end
end
end
def self.get_units(user)
hm = {:success => true}
hm[:units] = {}
get_visible_projects(user).each do |p|
hm[:units][p.short_name] = p.units.collect {|unit| unit.value}
end
hm.to_json
end
def self.get_project_units(user, project_name)
hm = {:success => false}
self.process_project(user, project_name, hm) do |project|
hm[:success] = true
hm[:units] = project.units.collect {|unit| unit.value}
end
hm.to_json
end
def self.get_units_of_type(user, project_name, type_name)
hm = {:success => false}
self.process_unit_type(user, project_name, type_name, hm) do |project, type|
hm[:success] = true
hm[:units] = type.units.collect {|unit| unit.value}
end
hm.to_json
end
def self.get_unit(user, project_name, type_name, name, depth)
hm = {:success => false}
self.access_unit(user, project_name, type_name, name, hm) do |project, unit_type, unit|
#Let's make a hash!
hm[:success] = true
hm[:depth] = depth
units = unit.get_neighbours depth
assocs = Association.get_relationships(units)
hm[:units] = {}
#units =>
Project.where(:id => units.collect{|u| u.project_id}).each do |p|
hm[:units][p.short_name] = {}
#<project> =>
UnitType.where(:id => units.collect {|u| u.unit_type_id}).each do |ut|
hm[:units][p.short_name][ut.name] = []
#<unit type> => [list of units]
units.select {|u| u.project.short_name == p.short_name and u.unit_type_id == ut.id}.each do |u|
as = {}
#<association type> => [unit IDs]
AssociationType.where(:id => assocs.select {|a| a.from_id == u.id }.collect {|a| a.association_type_id}).each do |at|
as[at.name] = u.from_associations.select {|a| a.association_type_id == at.id }.collect{|a| units.index(a.to)}
end
tus = {}
#<text unit type> => [content]
u.text_units.each do |tu|
tus[tu.text_unit_type.name] = tu.text
end
#[id,name,associations,content]
hm[:units][p.short_name][ut.name] << [units.index(u), u.value, as, tus]
end
end
end
end
hm.to_json
end
def self.create_unit(user, project_name, type, name)
hm = {:success => false}
self.write_unit(user, project_name, type, hm) do |project, type, unit|
if unit.nil?
unit = Unit.new(:project_id => project.id, :unit_type_id => type.id, :value => name)
if unit.save
hm[:success] = true;
end
else
hm[:errors] = [@@error_messages[:unit_exists]]
end
end
hm.to_json
end
private
@@error_messages = {
:unit_exists => "The unit already exists",
:no_project => "The project does not exist",
:no_unit_type => "The unit type does not exist",
:no_unit => "The unit does not exist",
:permission => "The user does not have permission to access the project",
:write_permission => "The user does not have permission to write to the project"
}
def self.user_can_write_project?(user, project)
!user.nil? and !project.project_users.select {|pu| pu.user_id == user.id}.empty?
end
def self.user_can_see_project?(user, project)
(project.public? or (!user.nil? and !project.project_users.select {|pu| pu.user_id == user.id}.empty?))
end
def self.get_visible_projects(user)
if user.nil?
return Project.where(:public => true)
else
return user.projects & Project.where(:public => true)
end
end
def self.find_unit(project, type, name)
Unit.where(:value => name, :unit_type_id => type.id, :project_id => project.id).first
end
end
| true |
e6cfc135bebe180b6303f82e8cac7ab91bc7337e | Ruby | cannaryo/reallen | /src/calc_coverage.rb | UTF-8 | 1,529 | 2.8125 | 3 | [
"MIT"
] | permissive | #! /usr/bin/ruby
#
# calc_coverage.rb
#
# Copyright (c) 2016 - Ryo Kanno
#
# This software is released under the MIT License.
# http://opensource.org/licenses/mit-license.php
#
require "optparse"
Version="1.1.2"
banner = "Usage: calcCoverage.rb [option] <input BED file> <original BAM file>\n+calculate coverage at each position\n"
out_file="tmp.cov.csv"
tmp_file="cov_tmp.bed"
sam_comm="samtools"
opt = OptionParser.new(banner)
opt.on("-o file","output file (default: tmp.bed)") {|v| out_file=v}
opt.on("--tmp file", "temporary file (default: cov_tmp.bed)") {|v| tmp_file=v}
opt.on("--samtools command", "command for Samtools (default: samtools)") {|v| sam_comm=v}
opt.parse!(ARGV)
exit if(ARGV.size < 2)
printf("\ncalcCoverage.rb %s\n",Version)
printf("input=%s, BAM=%s\n", ARGV[0],ARGV[1])
if(File.exist?(tmp_file))
STDERR.printf("Cannot write %s\n",tmp_file)
STDERR.printf("File exist\n")
exit
end
str=sam_comm+" bedcov "+ARGV[0]+" "+ARGV[1]+" > "+tmp_file
system(str)
data_all=Array.new
File.open(tmp_file).each_line do |s|
d=s.split(" ")
next if d.size < 6
data_all.push([d[0], d[1].to_i, d[2].to_i, d[3], d[4],d[5].to_f/(d[2].to_i - d[1].to_i)])
end
data_all.sort!{ |a,b| a[0] == b[0] ? a[2] <=> b[2] : a[0] <=> b[0] }
File.open(out_file,"w") do |fp|
fp.printf("Chromosome,Start,End,ID,Score,Coverage\n")
data_all.each do |d|
fp.printf("%s,%d,%d,%s,%s,%.2f\n", d[0],d[1],d[2],d[3],d[4],d[5])
end
end
printf("%d records were written in %s\n", data_all.size, out_file);
File.delete(tmp_file)
| true |
25f28813e8a4075c3de68fa6f2d53a1514594272 | Ruby | Br-ribeiro/Teste_e_Qualidade_de_Software | /modulo_para_numero/2018-1/elisson/moeda_spec.rb | UTF-8 | 1,754 | 3.109375 | 3 | [] | no_license | require_relative '../../moeda'
describe 'Moeda' do
include Moeda
describe '#numero_para_moeda' do
context 'usando valores padrões' do
it "formata corretamente um inteiro" do
expect(numero_para_moeda(2000)).to eq('R$2.000,00')
end
it "formata corretamente um float" do
expect(numero_para_moeda(2000.00)).to eq('R$2.000,00')
end
it "formata corretamente uma string" do
expect(numero_para_moeda('2000')).to eq('R$2.000,00')
end
it "usa delimitadores para números muito grandes" do
expect(numero_para_moeda(2000000000)).to eq('R$2.000.000.000,00')
end
it "não tem delimitadores para números pequenos" do
expect(numero_para_moeda(200)).to eq('R$200,00')
end
end
context 'usando opções customizadas' do
it 'permite a mudança da :unidade' do
expect(numero_para_moeda(2000, unidade: '$')).to eq('$2.000,00')
end
it 'permite a mudança da :precisao' do
expect(numero_para_moeda(2000, precisao: 1)).to eq('R$2.000,0')
end
it 'esconde o separador se a :precisao é 0' do
expect(numero_para_moeda(2000, precisao: 0)).to eq('R$2.000')
end
it 'permite a mudança do :delimitador' do
expect(numero_para_moeda(2000, delimitador: ',')).to eq('R$2,000,00')
end
it 'permite a mudança do :separador' do
expect(numero_para_moeda(2000, separador: '.')).to eq('R$2.000.00')
end
it 'formata corretamente usando múltiplas opções' do
expect(numero_para_moeda(2000, unidade: '$', precisao: 3,
delimitador: ',', separador: '.'))
.to eq('$2,000.000')
end
end
end
end
| true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.