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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
86ebc076621f02cd71d830fd098204a726ed847d
|
Ruby
|
troynt/AdventOfCode2018
|
/challenges/12/plant_pot.rb
|
UTF-8
| 755
| 3.171875
| 3
|
[] |
no_license
|
class PlantPot
attr_accessor(
:state,
:next,
:prev,
:next_state,
:location
)
def initialize(state, location: nil)
@state = state
@location = location
end
def state_with_neighbors
self_with_neighbors.map(&:state).map {|x| !x.nil? && x == true ? '#' : '.'}.join ''
end
def self_with_neighbors
ret = []
5.times {ret << PlantPot.new(false)}
if prev
ret[1] = prev
ret[0] = prev.prev unless prev.prev.nil?
end
ret[2] = self
if self.next
ret[3] = self.next
ret[4] = self.next.next unless self.next.next.nil?
end
ret
end
def has_plant?
state
end
def to_i
has_plant? ? location : 0
end
def to_s
has_plant? ? '#' : '.'
end
end
| true
|
815a6ed65f9a8fac912c12793c9b324f67c666e6
|
Ruby
|
smellman/chiba_5374_generator
|
/make_data.rb
|
UTF-8
| 1,907
| 2.78125
| 3
|
[] |
no_license
|
# coding: utf-8
require 'csv'
sites = %w(hanamigawa midori mihama tyuuou wakaba)
# for target.csv
use_target = %w(可燃ごみ びん・缶・ペットボトル 古紙・布類 不燃ごみ・有害ごみ(危険物))
target_header = %w(label name notice furigana)
base_target_csv = 'chiba_target.csv'
# for area_days.csv
area_days_header = %w(地名 センター 可燃ごみ びん・缶・ペットボトル 古紙・布類 不燃ごみ・有害ごみ(危険物))
sites.each do |site|
site_dir = "../chiba-#{site}.5374"
# make target.csv
target_output_csv = "#{site_dir}/data/target.csv"
CSV.open(target_output_csv, 'w') do |csv|
csv << target_header
CSV.foreach(base_target_csv) do |row|
if use_target.include? row[0]
csv << row
end
end
end
# make area_days.csv
area_days_input_csv = "./chiba_#{site}_area.csv"
area_days_output_csv = "#{site_dir}/data/area_days.csv"
found_notice = false
CSV.open(area_days_output_csv, 'w') do |csv|
csv << area_days_header
count = 0
CSV.foreach(area_days_input_csv) do |row|
count = count + 1
next if count == 1
add_row = Array.new
row.each_with_index do |value, index|
if value == "※"
found_notice = true
end
if index == 0
add_row << value
add_row << ""
next
end
v = value.split('・')
if v.count == 1
add_row << value
next
end
if v[0] =~ /[0-5]/
base = v[1][1..-1]
ret = base + v[0]
ret = ret + " "
ret = ret + base + v[1][0]
add_row << ret
else
ret = "#{v[0]} #{v[1]}"
add_row << ret
end
end
csv << add_row
end
end
if found_notice
p "#{area_days_output_csv} で※が見つかりました。内容を確認してください"
end
end
| true
|
cf0ae781b93a08e2fea3cfa1b3d074fc811dd4e6
|
Ruby
|
jake-webber-au/toy_robot
|
/Table.rb
|
UTF-8
| 245
| 3.140625
| 3
|
[] |
no_license
|
require_relative './errors.rb'
class Table
def initialize(x = 5, y= 5)
@x = x
@y = y
end
def check_boundary(x,y)
if !x.between?(0,@x) || !y.between?(0,@y)
raise RobotOutOfBounds.new
end
return true
end
end
| true
|
08bf772aee93afd99eca95f32ba24ca6cfded246
|
Ruby
|
exchai93-zz/student-directory
|
/directory_ex12.rb
|
UTF-8
| 2,779
| 4.53125
| 5
|
[] |
no_license
|
# loading procedure is going to be the reverse of what we've done to save the data to the file
# 1. open file for reading
# 2. read contents of the file
# 3. iterate over all lines
# 4. split every line at the comma
# 5. put a new hash into the array @students
# 6. close the file
@students = [] # an empty array accessible to all methods
def input_students
puts "Please enter the names of the students"
puts "To finish, just hit return twice"
# get the first name
name = gets.chomp
# while the name is not empty, repeat this code
while !name.empty? do
# add the student hash to the array
@students << {name: name, cohort: :november}
puts "Now we have #{@students.count} students"
# get another name from the user
name = gets.chomp
end
end
def interactive_menu
loop do
print_menu
process(gets.chomp)
end
end
# extract the code that prints the menu into its own method
def print_menu
puts "1. Input the students"
puts "2. Show the students"
# add one more menu item to save the students
puts "3. Save the list to students.csv"
puts "4. Load the list from students.csv"
puts "9. Exit" # 9 because we'll be adding more items
end
# extract the code that prints the students into a method
def show_students
print_header
print_students_list
print_footer
end
def save_students
file = File.open("students.csv", "w")
@students.each do |student|
student_data = [student[:name], student[:cohort]]
csv_line = student_data.join(",")
file.puts csv_line
end
file.close
end
# loading data from the file
def load_students
# open file for reading
file = File.open("students.csv", "r")
# read all lines into an array and interate over it
file.readlines.each do |line|
# on every interation discard the trailing new line char from the line
# split it at the comma (this gives us an array with two elements)
# assign it to the name and cohort varibales
name, cohort = line.chomp.split(',')
# create a new hash and put it into the array of students
# converting a string from the file to a symbol
@students << {name: name, cohort: cohort.to_sym}
end
# close the file
file.close
end
def process(selection)
case selection
when "1"
input_students
when "2"
show_students
when "3"
save_students
when "4"
load_students
when "9"
exit
else
puts "I don't know what you mean, try again"
end
end
def print_header
puts "The students of my cohort at Makers Academy"
puts "-------------"
end
def print_students_list
@students.each do |student|
puts "#{student[:name]} (#{student[:cohort]} cohort)"
end
end
def print_footer
puts "Overall, we have #{@students.count} great students."
end
interactive_menu
| true
|
59c2e7016aeacc209399d8cf9bfaa7af117bfb7d
|
Ruby
|
justinnnnnnnn/aaclasswork
|
/w4d4/first tdd projects/lib/00_first_tdd.rb
|
UTF-8
| 941
| 3.6875
| 4
|
[] |
no_license
|
def my_uniq(a)
banana = []
a.map do |el|
banana << el if !banana.include?(el)
end
banana
end
def two_sum(arr)
pairs = []
arr.each_with_index do |el1, i1|
arr.each_with_index do |el2, i2|
if arr[i1] + arr[i2] == 0 && i2 > i1
pairs << [i1, i2]
end
end
end
pairs
end
def my_transpose(arr)
rotated = Array.new(arr.length) {Array.new(arr.length)}
arr.each_with_index do |row, i1|
row.each_with_index do |el2, i2|
rotated[i1][i2] = arr[i2][i1]
end
end
rotated
end
def stock_picker(days)
trade_possibilites = Hash.new()
days.each_with_index do |el1, i1|
days.each_with_index do |el2, i2|
if i1 < i2
trade_possibilites[[i1,i2]] = el2 - el1
end
end
end
trade_possibilites.sort_by{|k, v| v}[-1][0]
end
p stock_picker([8, 2, 4, 5, 6, 7, 3, 1])
| true
|
bbcef4e0b5819c203d1b7d95753aa44b9c8e1d7e
|
Ruby
|
iamianami/ian_calculator
|
/ian_calculator.rb
|
UTF-8
| 1,271
| 3.90625
| 4
|
[] |
no_license
|
# def say(msg)
# puts "------#{msg}------"
# end
# say("Please type your first number")
# number1 = gets.chomp.to_i
# say("Please type your second number ")
# number2 = gets.chomp.to_i
# say("Choose 1)add 2)sub 3)multi 4) divided")
# operation = gets.chomp.to_i
# if operation == 1
# result = number1 + number2
# elsif operation == 2
# result = number1 - number2
# elsif operation == 3
# result = number1 * number2
# elsif operation == 4
# result = number1 / number2.to_f
# else
# puts "Please type the number,not thing else"
# end
# puts "The total is #{result}"
begin
puts "Enter your first number"
number1 = gets.chomp.to_i
puts "Enter your second number"
number2 = gets.chomp.to_i
puts "Choose 1)add,2)sub,3)multi,4)divided,please type the number"
operation = gets.chomp.to_i
if operation == 1
puts number1 + number2
elsif operation == 2
puts number1 - number2
elsif operation == 3
puts number1 * number2
elsif operation == 4
puts number1 / number2.to_f
else
puts "Please choose a number to active the operation"
end
puts "Do you want to count something again? (y/n)"
end until gets.chomp.downcase == "n"
#Finally ,I figured it out...
| true
|
c0a36cf998b3f2bb27b7dc2ccd0f4bb9dee8993a
|
Ruby
|
fadhlinahamdan/webhook-shopify-ruby
|
/app.rb
|
UTF-8
| 4,108
| 2.53125
| 3
|
[] |
no_license
|
require 'rubygems'
require 'base64'
require 'openssl'
require 'sinatra'
require 'active_support/security_utils'
require 'shopify_api'
require 'rails'
require 'sendgrid-ruby'
include SendGrid
require 'twilio-ruby'
# The Shopify app's shared secret, viewable from the Partner dashboard
# webhook string
SHARED_SECRET = '86b895992ac3377d945d29a232e84746ab59e58430b5ecca9ac3db34e73148ab'
API_KEY = 'af5dbb553f3e90d76eb99f253d285a69'
PASSWORD = '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'
SHOP_NAME = 'kain-kain-store'
# Shopify API gem setup
shop_url = "https://#{API_KEY}:#{PASSWORD}@#{SHOP_NAME}.myshopify.com"
ShopifyAPI::Base.site = shop_url
ShopifyAPI::Base.api_version = '2021-07'
helpers do
# Compare the computed HMAC digest based on the shared secret and the request contents
# to the reported HMAC in the headers
def verify_webhook(data, hmac_header)
calculated_hmac = Base64.strict_encode64(OpenSSL::HMAC.digest('sha256', SHARED_SECRET, data))
ActiveSupport::SecurityUtils.secure_compare(calculated_hmac, hmac_header)
end
end
# Respond to HTTP POST requests sent to this web service
# PRODUCT UPDATE
post '/webhook/product_update' do
request.body.rewind
data = request.body.read
verified = verify_webhook(data, env["HTTP_X_SHOPIFY_HMAC_SHA256"])
unless verified
return [403, 'Authorization failed. Provided hmac was #{hmac_header}']
end
# Output 'true' or 'false'
puts "Webhook verified: #{verified}"
json_data = JSON.parse data
# Find product and add 'Updated' tag
product = ShopifyAPI::Product.find(json_data['id'].to_i)
product_title = json_data['title']
puts "Product: #{product_title}"
product.tags += ', Updated'
product.save
# Always let Shopify know that we have received the webhook
return [200, 'Webhook successfully received']
end
# ORDER PAYMENT
# A webhook will be sent every time an order has been paid
# Send email / SMS when the order has been marked as paid
post '/webhook/order_payment' do
request.body.rewind
data = request.body.read
verified = verify_webhook(data, env["HTTP_X_SHOPIFY_HMAC_SHA256"])
unless verified
return [403, 'Authorization failed. Provided hmac was #{hmac_header}']
end
# Output 'true' or 'false'
puts "Webhook verified: #{verified}"
json_data = JSON.parse data
# Find order and check financial status
order_number = json_data['order_number']
financial_status = json_data['financial_status']
puts "Order: #{order_number}"
puts "Payment status: #{financial_status}"
# Check if customer registered using email or phone number for order updates
contact_email = json_data['contact_email']
phone = json_data['phone']
if contact_email
# puts "Customer email: #{email}"
# Send email using Twilio Sendgrid
from = Email.new(email: 'fadhlina@synomus.io')
to = Email.new(email: contact_email)
subject = 'Your payment has been received'
content = Content.new(type: 'text/html', value: 'Hi! This is from Kain Kain Store. Your payment has been received. Thank you for shopping with us!') # get value from email.liquid
mail = Mail.new(from, subject, to, content)
sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
response = sg.client.mail._('send').post(request_body: mail.to_json)
puts response.status_code
puts response.body
puts response.headers
else phone
# puts "Customer phone number: #{phone}"
# Send SMS using Twilio
account_sid = 'AC3d1d141e02281cde6f86b7e9371ec70d'
auth_token = 'a77ddec81338da65616b9b0c2c6becad'
client = Twilio::REST::Client.new(account_sid, auth_token)
from = '+12018176607' # Your Twilio number
to = phone # Your mobile phone number
client.messages.create(
from: from,
to: to,
body: "Hi! This is Kain Kain Store. Your payment has been received. Thank you for shopping with us!"
)
end
# Always let Shopify know that we have received the webhook
return [200, 'Webhook successfully received']
end
# Respond to HTTP GET request
get '/' do
"Welcome to Shopify Webhook App! 🎉"
end
| true
|
9c002e4c1960164ec61c2a640edaae7e283470fb
|
Ruby
|
dhan0406/ride-share-rails
|
/test/models/passenger_test.rb
|
UTF-8
| 2,505
| 2.734375
| 3
|
[] |
no_license
|
require "test_helper"
# file replaced with one sent by Jared
describe Passenger do
let (:new_passenger) {
Passenger.new(name: "Kari", phone_num: "111-111-1211")
}
it "can be instantiated" do
# Assert
expect(new_passenger.valid?).must_equal true
end
it "will have the required fields" do
# Arrange
new_passenger.save
passenger = Passenger.first
[:name, :phone_num].each do |field|
# Assert
expect(passenger).must_respond_to field
end
end
describe "relationships" do
it "can have many trips" do
# Arrange
new_passenger.save
new_driver = Driver.create(name: "Waldo", vin: "ALWSS52P9NEYLVDE9")
trip_1 = Trip.create(driver_id: new_driver.id, passenger_id: new_passenger.id, date: Date.today, rating: 5, cost: 1234)
trip_2 = Trip.create(driver_id: new_driver.id, passenger_id: new_passenger.id, date: Date.today, rating: 3, cost: 6334)
# Assert
expect(new_passenger.trips.count).must_equal 2
new_passenger.trips.each do |trip|
expect(trip).must_be_instance_of Trip
end
end
end
describe "validations" do
it "must have a name" do
# Arrange
new_passenger.name = nil
# Assert
expect(new_passenger.valid?).must_equal false
expect(new_passenger.errors.messages).must_include :name
expect(new_passenger.errors.messages[:name]).must_equal ["can't be blank"]
end
it "must have a phone number" do
# Arrange
new_passenger.phone_num = nil
# Assert
expect(new_passenger.valid?).must_equal false
expect(new_passenger.errors.messages).must_include :phone_num
expect(new_passenger.errors.messages[:phone_num]).must_equal ["can't be blank"]
end
end
# Tests for methods you create should go here
describe "custom methods" do
describe "request a ride" do
# Your code here
end
describe "complete trip" do
# Your code here
end
# You may have additional methods to test here
describe 'total_charged' do
it "should correctly return total amount charged for passenger" do
new_passenger = Passenger.create(name: "Pass", phone_num: "1234567")
new_driver = Driver.create(name: "Kari", vin: "123")
new_trip_1 = Trip.create(date: Time.now, driver_id: new_driver.id, passenger_id: new_passenger.id, cost: 1000)
new_trip_2 = Trip.create(date: Time.now, driver_id: new_driver.id, passenger_id: new_passenger.id, cost: 1000)
expect(new_passenger.total_charged).must_equal 20.0
end
end
end
end
| true
|
71d058479a47abe743c999e046e5dfd5c047cffb
|
Ruby
|
Damnedlag/Ruby-exercises
|
/03_simon_says/simon_says.rb
|
UTF-8
| 896
| 4.15625
| 4
|
[] |
no_license
|
#write your code here
def echo(thing)
thing
end
def shout(thing)
thing.upcase
end
def repeat(*arr)
array = *arr
if !array[1]
array << 2
end
solution = (array[0] + ' ') * array[1]
solution.chomp(' ')
end
def start_of_word(word, num)
i = 1
solution = word[0]
while i < num
solution = solution + word[i]
i = i + 1
end
solution
end
def first_word(str)
str.split[0]
end
def titleize(str)
small_words = %w[on the and over] # %w(foo bar) is a shortcut for ["foo", "bar"]. Meaning it's a notation to write an array of strings separated by spaces instead of commas and without quotes around them.
str.split(' ').map.with_index do |w, i| # http://www.zenspider.com/ruby/quickref.html#types
unless (small_words.include? w) and (i > 0)
w.capitalize
else
w
end
end.join(' ')
end
| true
|
246d8c1fed3c415cba17c6a40088b3dff8e0aff1
|
Ruby
|
bethsecor/tealeaf-intro-to-programming
|
/Workbook/Easy/Quiz3/exercise3.rb
|
UTF-8
| 210
| 2.609375
| 3
|
[] |
no_license
|
# Tealeaf Academy Prep Course
# Intro to Programming Workbook
# Easy Questions - Quiz 3
# Exercise 3
flintstones = %w(Fred Barney Wilma Betty BamBam Pebbles)
flintstones << "Dino"
flintstones.push("Dino","Hoppy")
| true
|
e4129e9642fd72d26e63b6305b5c4eedb2256c01
|
Ruby
|
codeauslander/actualize-class
|
/intro_to_apis/reddit_app.rb
|
UTF-8
| 914
| 3.171875
| 3
|
[] |
no_license
|
require 'unirest'
looking_up_words= true
while looking_up_words
url = "https://www.reddit.com/r/programming/.json"
response = Unirest.get(url).body
posts = response['data']['children']
print "Please enter the post number from 0 to #{posts.length}: "
number = gets.chomp.to_i
puts
permalinks = []
posts.each do |post|
permalinks << post['data']['permalink']
end
url_comments = "https://www.reddit.com" + permalinks[number] + ".json"
puts "Here are the comments for the post"
puts url_comments
comments = Unirest.get(url_comments).body
comments = comments[1]['data']['children']
index = 1
comments.each do |comment|
puts "-" * 50
puts "#{index}). #{comment['data']['body']}"
index += 1
end
puts
puts "Press enter to keep going or enter q to Quit"
command = gets.chomp
system 'clear'
if command == 'q'
looking_up_words = false
end
end
| true
|
f3967c8af1b514726020d3761a0455c51e50bc0b
|
Ruby
|
fastmode/badges-and-schedules-v-000
|
/conference_badges.rb
|
UTF-8
| 1,183
| 4.34375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
attendees = ["Edsger", "Ada", "Charles", "Alan", "Grace", "Linus", "Matz"]
def badge_maker(name)
"Hello, my name is #{name}."
end
#This will create array of all the attendess with the welcome message.
def batch_badge_creator(attendees)
badges = []
attendees.each do |attendee|
badges << badge_maker(attendee)
end
badges
end
#This will create array detailing the room assignment to each attendee
def assign_rooms(attendees)
room_assignment = []
attendees.each_with_index do |attendee, room|
room_assignment << "Hello, #{attendee}! You'll be assigned to room #{room+1}!"
end
room_assignment
end
#This can be also used with the .map method which creates an array, so no need to specify a new array then enter it again to return it.
#def assign_rooms(attendees)
# attendees.each_with_index.map do |attendee, room|
# "Hello, #{attendee}! You'll be assigned to room #{room+1}!"
# end
#end
#This will call other methods to pull their arrays and puts them out.
def printer(attendees)
batch_badge_creator(attendees).each do |attendee|
puts attendee
end
assign_rooms(attendees).each do |attendee|
puts attendee
end
end
printer(attendees)
| true
|
3d93f1862ec5984ae14e51539100b91c4b7d2fc7
|
Ruby
|
inbabbini/ttps_ruby_2015
|
/Practicas/Practica3/exceptions/e4.rb
|
UTF-8
| 421
| 3.484375
| 3
|
[] |
no_license
|
# retry
# retry sirve para, justamente, volver a ejecutar el bloque en el cual
# se encuentra, desde la sentencia begin (es decir, desde el principio)
begin
#dangerous code
rescue Exception
puts 'Something broke'
#do something to fix problems
retry
end
# Ejemplo boludo:
num = 0
begin
if num == 5
'ok'
else
raise RuntimeError
end
rescue RuntimeError
puts 'catched!'
num += 1
retry
end
| true
|
b54ab468bc40c9d517ddee9a50ecb44b1dab4e23
|
Ruby
|
TDA/Ruby-GithubAPI
|
/language_dictionary_generator.rb
|
UTF-8
| 1,542
| 3.1875
| 3
|
[] |
no_license
|
require 'json'
#language_dictionary_generator
File.open('/Users/schandramouli/PycharmProjects/GithubAPI/languages_data_sorted.json') do |file|
data = file.readlines
data_string = ""
data.each {|line| data_string += line.chomp}
language_data = JSON.parse(data_string)
# set the LoC for all the languages to 0
languages = Hash.new(0)
# now cycle through the list, and add the lines to the respective langs
# remember, LoC for JS is to be modded by 10 whenever it goes over 10k cuz jQuery
language_data.each do |key, value|
value = JSON.parse(value)
# puts value
value.each do |lang, loc|
if lang.equal?("JavaScript")
loc %= 10
end
languages[lang] += loc
end
end
# this sorts by value, yay! minus for descending
languages = Hash[languages.sort_by { |key, value| -value}]
puts languages
File.write('./language_usage_data.json', JSON.pretty_unparse(languages))
# now to find frequency of usage of a language, ala how
# many projects with that language.
frequency = Hash.new(0)
language_data.each do |key, value|
value = JSON.parse(value)
# puts value
value.each do |lang, loc|
frequency[lang] += 1
end
end
# this sorts by value, yay! minus for descending
# frequency = Hash[frequency.sort_by { |key, value| key}.reverse]
# does the same as -value, but more verbose
frequency = Hash[frequency.sort_by { |key, value| value}.reverse]
puts frequency
File.write('./language_frequency_data.json', JSON.pretty_unparse(frequency))
end
| true
|
a5856c467b598560b06adde93205f08e1c4835bf
|
Ruby
|
k2works/ruby-design-pattern
|
/factory/duck_pond.rb
|
UTF-8
| 284
| 2.96875
| 3
|
[] |
no_license
|
require './pond'
#
# == アヒル@池クラス
#
# Author:: k2works
# Version:: 1.0.0
# License:: Ruby License
#
class DuckPond < Pond
def new_organism(type, name)
if type == :animal
Duck.new(name)
else
raise "Unknown organism type: #{type}"
end
end
end
| true
|
bd623103c7b1867ad301bfe909753b7b2fd9ace5
|
Ruby
|
NotReady/memo
|
/ruby/chapter2/2-2-2b.rb
|
UTF-8
| 405
| 4.09375
| 4
|
[] |
no_license
|
# 引数と戻り値をもつメソッド
# 戻り値は最終行の式結果
def triangle(base, height)
return nil if base == 0 || height == 0
result = base * height / 2.0
result
end
area = triangle(11, 9)
puts "面積は#{area}です。"
area = triangle 11, 9 #=> 呼び出しの小かっこは省略可能
puts "面積は#{area}です。"
area = triangle 0, 1
puts "面積は#{area}です。"
| true
|
9812eae5483f4db37ee7ed48af71404ba9472aaf
|
Ruby
|
ElaErl/Challenges-1
|
/Easy1/perfect_number.rb
|
UTF-8
| 266
| 3.5
| 4
|
[] |
no_license
|
class PerfectNumber
def self.classify(num)
raise RuntimeError if num < 0
sum = 0
1.upto(num-1) {|n| sum += n if num % n == 0}
case
when sum == num then 'perfect'
when sum < num then 'deficient'
else 'abundant'
end
end
end
| true
|
a3767cf60b376667025f127f3edabd99b65cd4b4
|
Ruby
|
ericak11/project_euler
|
/number_6_squares.rb
|
UTF-8
| 855
| 4.03125
| 4
|
[] |
no_license
|
# ############################## sum of square difference - #6 ###########################
# The sum of the squares of the first ten natural numbers is,
# 12 + 22 + ... + 102 = 385
# The square of the sum of the first ten natural numbers is,
# (1 + 2 + ... + 10)2 = 552 = 3025
# Hence the difference between the sum of the squares of
# the first ten natural numbers and the square of the sum is 3025 − 385 = 2640.
# Find the difference between the sum of the squares of the first one
# hundred natural numbers and the square of the sum.
to_ten_array = (1..10).to_a
numbers_array = (1..100).to_a
sum_of_squares = 0
sum_squared = 0
numbers_array.each do |num|
sum_of_squares = sum_of_squares + (num * num)
end
numbers_array.each do |num|
sum_squared = sum_squared + num
end
puts (sum_squared * sum_squared) - sum_of_squares # ANSWER - 25164150
| true
|
68bf2db8f961b46c66a54cd74198449a9504ecb0
|
Ruby
|
KlotzAndrew/algorithms
|
/lib/graph/depth_first_search.rb
|
UTF-8
| 939
| 3.5
| 4
|
[] |
no_license
|
class DepthFirstSearch
def traverse(adjacency_list, node)
@result = []
@stack = []
@traversed_graph = []
adjacency_list.length.times do
@traversed_graph << [false, nil]
end
search_nodes adjacency_list, node
@traversed_graph
end
private
def search_nodes(adjacency_list, node)
return if @result.include? node
@traversed_graph[node][0] = true
@traversed_graph[node][1] = @stack.last
@result << node
@stack << node
adjacent_nodes = find_adjacent_nodes adjacency_list, node
available_nodes = filter_unvisited_nodes adjacent_nodes
available_nodes.each do |available_node|
search_nodes(adjacency_list, available_node)
end
@stack.pop
@result
end
def filter_unvisited_nodes(adjacent_nodes)
adjacent_nodes.delete_if {|node| @result.include? node }
end
def find_adjacent_nodes(adjacency_list, node)
adjacency_list[node]
end
end
| true
|
f8b1aea68afaab25d669151f6eb071018206288f
|
Ruby
|
JasonP77/programming-univbasics-nds-nds-to-insight-with-methods-dc-web-012720
|
/lib/nds_extract.rb
|
UTF-8
| 718
| 3.171875
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'directors_database'
# Find a way to accumulate the :worldwide_grosses and return that Integer
# using director_data as input
def gross_for_director(director_data)
total = 0
i = 0
while i < director_data[:movies].length do
total += director_data[:movies][i][:worldwide_gross]
i += 1
end
return total
end
# Write a method that, given an NDS creates a new Hash
# The return value should be like:
#
# { directorOne => allTheMoneyTheyMade, ... }
def directors_totals(nds)
result = {}
i = 0
while i < nds.length do
arr = nds[i]
result[arr[:name]] = gross_for_director(arr)
i += 1
end
return result
end
pp directors_database
| true
|
9fcf5fcaaf417034f34ee7a040e3e551500ae35b
|
Ruby
|
itsolutionscorp/AutoStyle-Clustering
|
/all_data/exercism_data/ruby/word-count/eb71d15b94994b0bacbd53f47600f5db.rb
|
UTF-8
| 307
| 3.421875
| 3
|
[] |
no_license
|
class Words
attr_reader :words
def initialize(string)
@words = normalize_input(string)
end
def count
words.each_with_object(Hash.new(0)) do |word, hash|
hash[word] += 1
end
end
private
def normalize_input(string)
string.downcase.gsub(/\W+/, ' ').split(" ")
end
end
| true
|
0569967dc9b0e3979c1ad1e47bc215442c0bc759
|
Ruby
|
alphagov-mirror/tv-radio-fillers-reporting-dashboard
|
/tests/helpers/csv_parser_radio_test.rb
|
UTF-8
| 1,811
| 2.6875
| 3
|
[] |
no_license
|
require_relative '../../app/helpers/csv_parser_radio.rb'
require_relative '../../app/models/transmission.rb'
require 'test/unit'
require 'csv'
class CsvParserRadioTest < Test::Unit::TestCase
DATE_FORMAT = '%d-%b-%y'
SAMPLE_FILE_FULL_PATH = "tests/helpers/csv_samples/radio_fillers_sample.csv"
def setup
Mongoid.load!("mongoid.yml", :test)
Transmission.delete_all
@csv_parser = CsvParserRadio.new
end
def teardown
Transmission.delete_all
end
def test_parse_row
sample_row = ["CB00003030 Dance On 30s", "Absolute 70s", "2767", "17-Jan-13", "21:34"]
filler = @csv_parser.parse_row(sample_row)
assert !filler.nil?
assert filler.type == "radio"
assert filler.date.strftime('%d/%m/%Y') == DateTime.new(2013, 01, 17).strftime('%d/%m/%Y')
assert filler.time_of_day == sample_row[4]
assert filler.station_name == sample_row[1]
assert filler.impact == sample_row[2]
assert filler.filler_name == sample_row[0]
end
def test_parse_row_too_few_rows
invalid_row = ["Absolute 70s", "2767", "17-Jan-13", "21:34"]
exception = assert_raise(ArgumentError) { @csv_parser.parse_row(invalid_row) }
assert_equal("Too few rows", exception.message)
end
def test_parse_row_invalid_date
invalid_row = ["CB00003030 Dance On 30s", "Absolute 70s", "2767", "01/31/2013", "21:34"]
exception = assert_raise(ArgumentError) { @csv_parser.parse_row(invalid_row) }
assert_equal("Could not parse date: #{invalid_row[3]}", exception.message)
end
def test_parse_radio_sample_file
CsvParserRadioTest.load_sample_file
fillers = Transmission.where(type: "radio")
assert fillers.count == 12
end
def self.load_sample_file
CsvParserRadio.new.parse_file(SAMPLE_FILE_FULL_PATH)
end
end
| true
|
48839ae7f90eb263eaf8e20dfbcc87eec843e0c3
|
Ruby
|
MihirKale89/Ruby_code
|
/TimeProcessor/lib/time_processor.rb
|
UTF-8
| 1,995
| 3.921875
| 4
|
[] |
no_license
|
=begin
Without using any built-in date or time functions, write a function or method
that accepts two mandatory arguments: the first argument is a 12-hour time
string with the format "[H]H:MM {AM|PM}", and the second argument is a (signed)
integer. The second argument is the number of minutes to add to the time of day
represented by the first argument. The return value should be a string of the
same format as the first argument. For example, AddMinutes("9:13 AM", 200)
would return "12:33 PM". The exercise isn't meant to be too hard or take very
long; we just want to see how you code. Please use Ruby to
complete the assessment and include any test cases that you write.
=end
class TimeProcessor
def self.add_minutes(time, minutes)
return time if minutes == 0
time = time.split(' ')
meridiem = time.last
time = time.first.split(':')
hour = time.first.to_i
minute = time.last.to_i
hour, minute, meridiem = process_minutes(hour, minute, minutes, meridiem)
"#{hour}:#{minute} #{meridiem}"
end
def self.process_minutes(hour, minute, minutes, meridiem)
# Handling adding over 24 hours and handling negative case.
minutes = minutes < 0 ? minutes.abs%(24*60)*-1 : minutes%(24*60)
hour = 0 if hour == 12 && meridiem == 'AM'
hour +=12 if hour !=12 && meridiem == 'PM'
sum = (hour*60+minute + minutes)%(24*60)
# Handling going into the previous or next day
sum = (24*60)-(sum.abs) if sum < 0
sum = sum-(24*60) if sum > (24*60)
hour = (sum/60)%12
minute = sum%60<10 ? "0#{sum%60}":"#{sum%60}"
[hour == 0 ? 12:hour, minute, (sum/60)<12 ? 'AM':'PM']
end
end
tp = TimeProcessor
p tp.add_minutes("9:13 AM", 200)
p tp.add_minutes("9:13 AM", -10)
p tp.add_minutes("9:13 AM", 1441)
p tp.add_minutes("9:13 AM", -1441)
p tp.add_minutes("12:05 AM", -10)
p tp.add_minutes("12:05 AM", -5)
p tp.add_minutes("11:55 PM", 10)
p tp.add_minutes("11:55 AM", 10)
p tp.add_minutes("11:55 AM", 5)
p tp.add_minutes("12:05 PM", -1450)
| true
|
99786877d828de548c60d1f0e9a9e8d3413cb4fd
|
Ruby
|
hogeline/weather-analysis
|
/getaverage.rb
|
UTF-8
| 752
| 2.953125
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
# coding: utf-8
require 'fileutils'
array = Array.new
ARGV.each_with_index do |file, i|
array[i] = Array.new(13, 0.0)
count = Array.new(13, 0.0)
array[i][0] = file.to_i
open(file+'.csv', 'r:utf-8') do |f|
f.each do |line|
fields = line.chomp.split(',')
date = fields[0].chomp.split('/')
array[i][date[1].to_i] += fields[3].to_f
count[date[1].to_i] += 1
end
for j in 1..12
array[i][j] /= count[j]
end
end
end
print " :"
ARGV.each do |file|
printf(" %d\t", file)
end
print ': 平均' + "\n"
for i in 1..12
printf("%2d月:", i)
avg = 0
for j in 0...ARGV.size
printf(" %0.2f\t", array[j][i])
avg += array[j][i]
end
printf(": %.2f\n", avg/ARGV.size)
end
| true
|
d5d0e23430420c3ba97a3e40cb83d906d516b567
|
Ruby
|
covaithe/project_euler
|
/lib/permutations.rb
|
UTF-8
| 907
| 3.8125
| 4
|
[] |
no_license
|
class Permutations
def self.of(list, n)
raise "The list is nil" if list.nil?
raise "There are not that many items in the list" if n > list.size
raise "Cannot pick #{n} items from a list" if n < 0
return [] if n == 0
return [ list ] if n == list.size
result = []
indexes = (0..n-1).to_a
loop do
result << choose_values(list, indexes)
break unless increment_index(indexes, list.size - 1)
end
result
end
private
def self.choose_values(list, indexes)
indexes.map { |i| list[i] }
end
def self.increment_index(indexes, max)
i = indexes.length - 1
while i >= 0
if indexes[i] >= max #can't increment this one
i -= 1
max -= 1
else
indexes[i] += 1
1.upto(indexes.length-i-1) do |j|
indexes[i+j] = indexes[i] + j
end
return true
end
end
false
end
end
| true
|
08c142a841b6986e553939a03d35ca8f47c85822
|
Ruby
|
willcannings/impromptu
|
/lib/impromptu/resource.rb
|
UTF-8
| 9,370
| 2.765625
| 3
|
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
module Impromptu
# Resources represent the modules or classes that are tracked by
# Impromptu and which can be lazy loaded. You should never create
# resources yourself - use component definitions to define folders
# of files which will implement resources.
class Resource
attr_reader :name, :base_symbol, :files, :children, :parent, :preload
def initialize(name, parent)
@name = name.to_sym
@parent = parent
@base_symbol = @name.base_symbol
@files = OrderedSet.new
@children = {}
@reference = nil
@namespace = false
@dont_undef = self.loaded? # existing constants, such as 'String', should never be unloaded
@preload = false # true if any folder defining this resource is marked to be preloaded
@implicitly_defined = true
end
# Override eql? so two resources with the same name will be
# considered equal by ordered set. Names are fully namespaced
# so will always be unique.
def eql?(other)
other.name == @name
end
# Override hash so two resources with the same name will result
# in the same hash value. Names are fully namespaced so will
# always be unique.
def hash
@name.hash
end
# Indicate whether this resource needs to be preloaded
def preload=(preload)
@preload = preload
end
# True if this resource needs to be preloaded before other files
# are automatically loaded on demand
def preload?
@preload
end
# Attempts to retrieve a reference to the object represented by
# this resource. If the resource is unloaded, nil is returned.
def reference
return Object if root?
return nil unless @parent && @parent.reference
@reference ||= @parent.reference.const_get(@base_symbol)
end
# Reload the implementation of this resource from all files being
# tracked for this resource. Call this method if you are manually
# managing file tracking, and need to guarantee all files for this
# resource have been loaded. It is normally unecessary to call this
# if you rely on the autoloader and reloader.
def reload
@parent.reload unless @parent.loaded?
if @implicitly_defined
unload
Object.module_eval "module #{@name}; end"
else
@files.first.reload
end
reload_preloaded_resources
end
# Unload the resource by undefining the constant representing it.
# Any resources contained within this resource will also be
# unloaded. This allows the resource to be garbage collected. If
# the resource is a class, you can define a class method called
# 'descendants' that returns an array of references to subclasses.
# Any subclasses known to Impromptu will also be unloaded, just as
# namespaced children are. This prevents subclasses holding a
# reference to a stale version of a super class.
def unload
return unless loaded?
# unload namespaced children
@children.each_value(&:unload)
# unload descendants if they can be reloaded by impromptu
if reference.respond_to? :descendants
reference.descendants.each do |descendant|
resource = Impromptu.root_resource.child(descendant.name.to_sym)
resource.unload unless resource.nil?
end
end
# remove from the parent's descendants list
if reference.respond_to?(:superclass) && reference.superclass.respond_to?(:descendants)
reference.superclass.descendants.delete(reference)
end
unless @dont_undef
@parent.reference.send(:remove_const, @base_symbol)
@reference = nil
end
end
# Start tracking a file which implements this resource. If the
# file has already been added it won't be added a second time.
# This method does not load the added file, so the definition
# of the resource will be incomplete until reload is called.
def add_file(file)
@files << file
@implicitly_defined = false
end
# Un-track a file implementing this resource. If the file was
# never tracked, no error is raised. This does not reload the
# resource, so the resource will be based on a stale definition
# if it was previously loaded.
def remove_file(file)
@files.delete(file)
@implicitly_defined = true if @files.size == 0 && namespace?
end
# True if no files have been associated with this resource. In
# this case, loading the resource will be achieved by creating
# a blank module with the name of the resource. If any files
# have been associated, they will be loaded instead, and this
# method will return false.
def implicitly_defined?
@implicitly_defined
end
# True if this resource represents a module acting as a
# namespace.
def namespace?
@namespace
end
# Mark a resource as representing a module acting as a
# namespace.
def namespace!
@namespace = true
end
# True if this resource is the parent of any resources.
def children?
!@children.empty?
end
# Add a child resource to this resource. This does not load the
# resource. This should only be called by get_or_create_child.
def add_child(resource)
@children[resource.base_symbol] = resource
end
# Remove a reference to a child resource. This does not unload
# the object, but is called automatically by unload on its parent
# resource.
def remove_child(resource)
@children.delete(resource.base_symbol)
end
# In most instances, this method should only be called on the
# root resource to traverse the resource tree and retrieve or
# create the specified resource. Name must be a symbol.
def get_or_create_child(name)
return nil unless name.is_a?(Symbol)
current = self
name.each_namespaced_symbol do |name|
# attempt to get the current resource
child_resource = current.child(name.base_symbol)
# create the resource if needed
if child_resource.nil?
child_resource = Resource.new(name, current)
current.add_child(child_resource)
end
# the next current resource is the one we just created or retrieved
current = child_resource
end
# after iterating through the name, current will be the resulting resource
current
end
# Walks the resource tree and returns the resource corresponding
# to name (which must be a symbol and can be namespaced). If the
# resource doesn't exist, nil is returned
def child(name)
return nil unless name.is_a?(Symbol)
return @children[name.without_leading_colons.to_sym] if name.unnested?
# if the name is nested, walk the resource tree to return the
# resource under this branch. rerturn nil if we reach a
# branch which doesn't exist
nested_symbols = name.nested_symbols
top_level_symbol = nested_symbols.first
further_symbols = nested_symbols[1..-1].join('::').to_sym
return nil unless @children.has_key?(top_level_symbol)
@children[top_level_symbol].child(further_symbols)
end
# Walks the resource tree to determine if the resource referred
# to by name (which must be a symbol, and may be namespaced) is
# known by Impromptu.
def child?(name)
!self.child(name).nil?
end
# Unload and remove all references to this resource.
def remove
unload
@parent.remove_child(self) if @parent
end
# True if this resource is the root resource referring to Object.
def root?
@parent.nil?
end
# True if this resource exists as a constant in its parent.
# This does not guarantee that every file implementing this
# resource has been loaded, however, so an incomplete instance
# may exist. If you rely on the autoloader and reloader this
# will not occur.
def loaded?
return true if root?
return false unless @parent && @parent.loaded? && @parent.reference
parent.reference.constants.include?(@base_symbol)
end
# Mark this resource as having been loaded before Impromptu if the
# resource is already defined.
def mark_dont_undef
@dont_undef = self.loaded?
@children.each_value(&:mark_dont_undef)
end
# Loads this resource if it is an extension of an existing class
# or module (such as an object in the standard library). Should
# only be called on app startup by Impromptu itself. Recurses to
# this resource's children as well.
def load_if_extending_stdlib
reload if loaded? && !self.root?
@children.each_value(&:load_if_extending_stdlib)
end
# Loads this resource, and any child resources, if the resource is
# marked as requiring preloading, and the resource is not currently
# loaded. This loading may happen multiple times during the application
# life cycle depending on whether parent resources are reloaded and so on.
def reload_preloaded_resources
reload if !loaded? && preload?
@children.each_value(&:reload_preloaded_resources)
end
end
end
| true
|
05d4deaee223fee00bc0ab08d843c77cf39809f0
|
Ruby
|
douglasf/base
|
/bin/web.watchr.rb
|
UTF-8
| 1,363
| 2.828125
| 3
|
[] |
no_license
|
require "fileutils"
# @key is pre compiled file type.
# @value is
# :compiler, what compiler to use, the compiler must print result to stdout
# :ending, the file ending to use after compilation
@settings = {
"less" => {
:compiler => "lessc",
:ending => "css"
},
"haml" => {
:compiler => "haml",
:ending => "html"
},
"coffee" => {
:compiler => "coffee -cs",
:ending => "js"
}
}
# Compiles "file" with appropriate compiler according to @settings.
def compile_file file
ending = file.split(".").last
out = "publish/#{file.reverse.sub(ending.reverse, @settings[ending][:ending].reverse).reverse}" # lol
unless File.exist?(out)
new_file = true
FileUtils.makedirs(File.dirname out)
FileUtils.touch out
end
if File.mtime(file) > File.mtime(out) or new_file
replace = File.read(file).gsub(/\<baseup (.*)\>/) { File.read("modules/#{$1}") }
result = `echo \'#{replace}\' | #{@settings[ending][:compiler]} > #{out}`
puts "WATCHR: Wrote to #{out}" if $?.success?
end
end
# Starts a watchr method if no arguments are given,
# if argument "-c file" is given it compiles the single file.
arg = ARGV.shift
unless arg == "-c"
watch( ".*\.(#{@settings.keys.join("|")})" ) {|md|
compile_file md[0]
}
puts "Starting to watch #{@settings.keys.join(", ")}"
else
compile_file ARGV.shift
end
| true
|
c6c1a0190ac8072ae119c19c672dcf820ac3dc78
|
Ruby
|
collinschaafsma/pedal
|
/lib/pedal/presenter.rb
|
UTF-8
| 296
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
module Pedal
class Presenter
attr_reader :subject
def initialize(subject)
@subject = subject
end
# Proxy to the Builder, adds itself to the scope
# so we can access the @subject
def build(&block)
Pedal::Builder.build(scope: self, &block)
end
end
end
| true
|
f21415f73d030e47972a537d83f4804e8bc3b97d
|
Ruby
|
Claire7514/exo_ruby
|
/exo_09.rb
|
UTF-8
| 88
| 2.8125
| 3
|
[] |
no_license
|
user_name = gets.chomp
name = gets.chomp
puts "Bonjour " + user_name + " " + name + "!"
| true
|
69b4423eab0cb21ed64ebd039e473b436131ec57
|
Ruby
|
bhserna/guests
|
/lib/invitations.rb
|
UTF-8
| 740
| 2.765625
| 3
|
[] |
no_license
|
module Invitations
def self.save_record(list_id, invitation, store)
store.create(
list_id: list_id,
invitation_id: invitation["id"].to_i,
raw_data: invitation)
end
def self.update_record(list_id, invitation, store)
record = store.find_for_list_by_invitation_id(list_id, invitation["id"])
store.update(record[:id],
list_id: list_id,
invitation_id: invitation["id"].to_i,
raw_data: invitation)
end
def self.delete_record(list_id, invitation_id, store)
record = store.find_for_list_by_invitation_id(list_id, invitation_id)
store.delete(record[:id])
end
def self.fetch_records(list_id, store)
store.find_for_list(list_id).map { |record| record[:raw_data] }
end
end
| true
|
1ae8296f86427228acd3513c5fe601974e1237fd
|
Ruby
|
JonathanUriel/RailsWeb
|
/blog/app/controllers/articles_controller.rb
|
UTF-8
| 2,116
| 2.984375
| 3
|
[] |
no_license
|
class ArticlesController < ApplicationController
#Variables con "@" sirven para manipular esa variable ya sea
#vistas o controladores, la variable sin @ solo se puede usar
#en el controlador, en el cual fue declarada
#GET /articles
def index
#Todos los registros
@article = Article.all #Trae todos los datos de la BD
end
#GET /articles/:id
def show
#Encontrar registro por ID
@article = Article.find(params[:id])
#where
#Article.where("id = ? OR|AND title = ? ",params[:id],params[:title])
#sean diferente
#Article.where.not("id = ?",params[:id])
end
#GET /articles/new
def new
#Se manda un objeto(articulo) basio
@article = Article.new
end
#POST /articles
def create
#Se inserta el objeto en la BD
#sintaxis: new ("campo" params["formulario"]["Campo"])
#@article = Article.new(title: params[:article][:title], body: params[:article][:body])
#Manera corta de hacer un insert del Objeto a la BD
@article = Article.new(article_params)
#Create llama automaticamente al metodo save
#@article = Article.create(title: params[:article][:title], body: params[:article][:body])
#@article.valid? es el articulo valido
#@article.invalid? es el articulo invalido
#Guardar en BD
if @article.save
#redireccionamiento
redirect_to @article
else
render :new
end
end
def edit
#Se manda el objeto(articulo) al formulario
@article = Article.find(params[:id])
end
#PUT /articles/:id
def update
#Update
#Actualiza el objeto en la BD
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render :edit
end
end
#delete "/articles/:id" destroy
def destroy
#Delete
#Busca el Articulo en la Bd
@article = Article.find(params[:id])
#Destroy elimina el objeto de la BD
@article.destroy
#Se redirecciona a la pagina
redirect_to articles_path
end
#------------------------------------------------------------------
#Metodos privados
private
def article_params
#Campos que se permitiran para la creacion del objeto
params.required(:article).permit(:title,:body)
end
end
| true
|
2142bd3df573c0dded9f5ce903498dcbe5cc3a97
|
Ruby
|
bogdanovich/cadence-ruby
|
/examples/workflows/branching_workflow.rb
|
UTF-8
| 404
| 2.828125
| 3
|
[
"Apache-2.0"
] |
permissive
|
require 'activities/random_number_activity'
require 'activities/hello_world_activity'
class BranchingWorkflow < Cadence::Workflow
def execute
random_number = RandomNumberActivity.execute!(max: 100)
if random_number > 50
HelloWorldActivity.execute!('top half')
else
HelloWorldActivity.execute!('bottom half')
end
return "Number picked was: #{random_number}"
end
end
| true
|
6a9a5a678f622c9d8ac46686ad386bab0f675964
|
Ruby
|
rohanphillips/activerecord-tvland-online-web-sp-000
|
/app/models/actor.rb
|
UTF-8
| 358
| 2.515625
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Actor < ActiveRecord::Base
has_many :shows, through: :characters
has_many :characters
def full_name
self.first_name + " " + self.last_name
end
def list_roles
collection = []
self.characters.joins(:show).each{|item|
collection << (item.name + " - " + item.show.name)
}
collection
end
end
| true
|
722a5a7d1158fd6fbcda30017ccc9bec38b15298
|
Ruby
|
jeik0210/prueba_capistrano
|
/app/models/user.rb
|
UTF-8
| 305
| 2.59375
| 3
|
[] |
no_license
|
class User < ActiveRecord::Base
belongs_to :editorial
before_save :up_full_name
def full_name
paternal.to_s + " " + maternal.to_s + " " + name.to_s
end
def up_full_name
self.name = self.name.upcase
self.paternal = self.paternal.upcase
self.maternal = self.maternal.upcase
end
end
| true
|
e5e71c9bf9b4dedbbfaa01eb86cedcb58418d7aa
|
Ruby
|
reasonset/installed-font-list-html
|
/installed-font-list-html.rb
|
UTF-8
| 3,659
| 2.609375
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/ruby
require 'erb'
ERB_TEMPLATE = <<EOF
<html>
<head>
<title>Installed Fonts (<%= ([modename] + optionname).join(",") %>)</title>
<style>
p { margin-left: 40px; }
section {
margin-top: 15px;
border-top: #339 solid 2px;
}
</style>
</head>
<body>
<h1>Installed Fonts (<%= ([modename] + optionname).join(",") %>)</h1>
<% fonts.keys.sort.each do |k| %>
<section style="font-family: "<%= k %>";">
<h2><%= k %> (<%= fonts[k][:fullname] %>)</h2>
<p>The quick brown fox jumps over the lazy dog</p>
<% if fonts[k][:monospace] %>
<p>[monospace] 1lI|/\ 0O 6b 9g -=^~_ .,:; *+ ()[]{}<></p>
<% end %>
<% if fonts[k][:kana] %>
<p>[kana] いろはにほへと ちりぬるを </p>
<% end %>
<% if fonts[k][:hani] %>
<p>[hani] 吾輩は猫である。名前は未だ無い。</p>
<% end %>
</section>
<% end %>
</body>
</html>
EOF
OPTIONS = []
fonts = Hash.new
modename = "All Installed"
optionname = []
outfile = nil
argv = []
ARGV.each do |i|
if i =~ /^-/
$'.scan(/(.)/) {|c| argv.push("-" + $1) }
else
argv.push i
end
end
p argv
while arg = argv.shift
break if arg == "--"
case arg.strip
when "-d"
OPTIONS.push :list_dual
when "-m"
OPTIONS.push :list_mono
when "-j"
OPTIONS.push :req_kana
optionname |= ["かな必須"]
when "-H"
OPTIONS.push :req_hani
optionname |= ["漢字必須"]
when "-o"
outfile = argv.shift
when "-h"
STDERR.puts "Usage:"
STDERR.puts " installed-font-list-html.rb [-m|-d] [-H] [-j] [-o outfile]"
end
end
if outfile
STDOUT.reopen(File.open(outfile, "w"))
end
STDERR.puts "building list.........."
fontlist = nil
if((OPTIONS & [:list_dual, :list_mono]).length > 1)
STDERR.puts "-d, -m options are able to turn on only one of them."
exit 1
end
if OPTIONS.include?(:list_mono)
modename = "Monospace"
IO.popen(["fc-list", ":mono", ":", "family", "fullname", "spacing", "capability"], "r") do |io|
fontlist = io.each.map {|i| i.split(":", 2)}
end
elsif OPTIONS.include?(:list_dual)
modename = "Monospace + Dualspace"
IO.popen(["fc-list", ":dual", ":", "family", "fullname", "spacing", "capability"], "r") do |io|
fontlist = io.each.to_a
end
IO.popen(["fc-list", ":mono", ":", "family", "fullname", "spacing", "capability"], "r") do |io|
fontlist |= io.each.to_a
end
fontlist = fontlist.map {|i| i.split(":", 2)}
else
IO.popen(["fc-list", ":", "family", "fullname", "spacing", "capability"], "r") do |io|
fontlist = io.each.map {|i| i.split(":", 2)}
end
end
fontlist.each do |fl|
infoline = {fullname: nil, kana: false, hani: false, monospace: false}
family = fl[0].split(",")
capability = ""
fullname = ""
if fl[1] =~ /\bfullname=(.*?)(?::|$)/
infoline[:fullname] = $1.gsub('\\', '')
end
if fl[1] =~ /\bspacing=(.*?)\b/
spacing = $1
unless(spacing == "0" || spacing.casecmp?("proportional"))
infoline[:monospace] = true
end
infoline[:spacing] = spacing
end
if fl[1] =~ /\bcapability=(.*)$/
capability = $1.gsub('\\', '')
end
infoline[:kana] = true if capability.include?("otlayout:kana")
infoline[:hani] = true if capability.include?("otlayout:hani")
next if OPTIONS.include?(:req_kana) && ! infoline[:kana]
next if OPTIONS.include?(:req_hani) && ! infoline[:hani]
family.each do |i|
fonts[i.gsub('\\', '')] = infoline
end
STDERR.puts(infoline[:fullname] || family.first)
end
STDERR.puts "Generating HTML..............."
ERB.new(ERB_TEMPLATE).run(binding)
| true
|
08533550ada040ba7229c175d6dab15e3f6e606e
|
Ruby
|
tylergreason/pokemon_backend
|
/db/seeds.rb
|
UTF-8
| 2,538
| 3.015625
| 3
|
[] |
no_license
|
require 'faker'
# Pokemon.delete_all
User.delete_all
Team.delete_all
# reset all pokemon types
# natures
# only seed natures if Nature.all is empty
if Nature.all.count == 0
natures = PokeApi.get(:nature).results
natures.each do |nature|
name = nature.name
Nature.find_or_create_by(name:name)
end
end
# types
# only seed types if Type.all is empty
if Type.all.count == 0
types = PokeApi.get(:type).results
types.each do |type|
name = type.name
Type.find_or_create_by(name:name)
end
end
700.times do |time|
pokemon_number = time+1
if Pokemon.find_by(number: pokemon_number) == nil
fetch_pokemon = PokeApi.get(pokemon: pokemon_number)
name = fetch_pokemon.name.capitalize
number = fetch_pokemon.id
image_url = fetch_pokemon.sprites.front_default
new_pokemon = Pokemon.find_or_create_by(name:name,number:number,image_url:image_url)
# nature
new_pokemon.natures << Nature.all.sample
# types
fetch_pokemon.types.each do |type|
new_pokemon.types << Type.find_or_create_by(name: type.type.name)
end
# abilities
abilities = fetch_pokemon.abilities
abilities.each do |result|
new_ability = Ability.find_or_create_by(name:result.ability.name)
new_pokemon.abilities << new_ability
end
# moves
moves = fetch_pokemon.moves
moves.each do |result|
new_move = Move.find_or_create_by(name: result.move.name)
new_pokemon.moves << new_move
end
end
end
# user
new_user = User.create(email:'test@mail.com', password:'test')
# create a new team, then give that team to the test user
4.times do
new_team = Team.create(name: Faker::Team.name, description: "Desc: " + Faker::Lorem.sentence(word_count: 3), user_id: User.all.sample.id)
3.times do
random_pokemon = Pokemon.all.sample
if !new_team.pokemons.include?(random_pokemon)
new_team.pokemons << Pokemon.all.sample
end
end
new_user.teams << new_team
end
# make 4 of each pokemon's moves active
Pokemon.all.each do |pokemon|
# make each move not active
PokemonMove.where(pokemon_id: pokemon.id, active:true).each {|pokemonMove|
pokemonMove.active = false
pokemonMove.save
}
4.times do |time|
if pokemon.moves[time] != nil
pokemon.set_move_active(pokemon.moves[time])
end
end
end
| true
|
16aced0ae01cf9e539877ead3d81dee6ea12bff2
|
Ruby
|
kupolak/codewars
|
/Ruby/7 KYU/Nickname Generator.rb
|
UTF-8
| 159
| 3.046875
| 3
|
[] |
no_license
|
def nickname_generator(name)
if name.length >= 4
/\A[auieoAUIEO]\z/.match(name[2]) ? name[0..3] : name[0..2]
else
"Error: Name too short"
end
end
| true
|
2b22f4f2eb68a8a6afef82f95624fca7970fa364
|
Ruby
|
reneeknox/prime-ruby-online-web-pt-071519
|
/prime.rb
|
UTF-8
| 483
| 3.734375
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def prime?(integer) # 11
if integer < 2
false
else
a = (2..integer - 1).to_a
# [3,4,5,6,7,8,9]
# a = [3,4,5,6,7,8,9,10]
# integer % n == 0 is prime
# [].none? # None of the numbers prior to integer are divisible by integer
# Madeline told me this is a good idea to include; I read that it passes each element of the collection to the block.
# This helps us iterate over the range.
a.none?{|n| integer % n == 0 } #true
end
end
| true
|
89826b68188ab75e503c6a7caabeaa8dd4d3a6c1
|
Ruby
|
Artforge/has_many_translations
|
/lib/has_many_translations/control.rb
|
UTF-8
| 1,805
| 2.6875
| 3
|
[] |
no_license
|
module HasManyTranslations
module Control
def self.included(base) # :nodoc:
base.class_eval do
include InstanceMethods
# alias_method_chain :create_translation?, :control
# alias_method_chain :update_translation?, :control
end
end
module InstanceMethods
def force_update
with_translation_flag(:force_update) do
yield if block_given?
save
end
end
def force_update!
with_translation_flag(:force_update) do
yield if block_given?
update_translations!
end
end
def force_update?
!!@force_update
end
def skip_translation
with_translation_flag(:skip_translation) do
yield if block_given?
save
end
end
def skip_translation!
with_translation_flag(:skip_translation) do
yield if block_given?
save!
end
end
def skip_translation?
!!@skip_translation
end
private
# Used for each control block, the +with_version_flag+ method sets a given variable to
# true and then executes the given block, ensuring that the variable is returned to a nil
# value before returning. This is useful to be certain that one of the control flag
# instance variables isn't inadvertently left in the "on" position by execution within the
# block raising an exception.
def with_translation_flag(flag)
begin
instance_variable_set("@#{flag}", !instance_variable_get("@#{flag}"))
yield
# ensure
# instance_variable_set("@#{flag}", nil)
end
end
end
end
end
| true
|
5c6141454f1e0349a5bb009539c44248fa73c788
|
Ruby
|
shoehead0125/crawler-study
|
/chapter-1/sbcr-sample/sbcr1.rb
|
UTF-8
| 491
| 2.9375
| 3
|
[] |
no_license
|
#! /usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'pry'
require 'cgi'
def parse(page_source)
dates = page_source.scan(
%r!(\d+)年 ?(\d+)月 ?(\d+)日<br />!)
url_titles = page_source.scan(
%r!^<a href="(.+?)">(.+?)</a><br />!)
url_titles.zip(dates).map { |(aurl, atitle), ymd|
[
CGI.unescapeHTML(aurl),
CGI.unescapeHTML(atitle),
# splat 可変長引数
Time.local(*ymd),
]
}
end
x = parse(open('samplepage.html', &:read))
puts x[0, 2]
| true
|
ead40f498e599c58f6d5d9380e3b0c201f70a7e8
|
Ruby
|
mvz/ripper_ruby_parser
|
/test/samples/loops.rb
|
UTF-8
| 378
| 3.140625
| 3
|
[
"MIT"
] |
permissive
|
# Loop samples
def for_samples
for foo in bar
end
for foo, bar in baz
end
for foo, in bar
end
end
# begin..end in conditions
#
def while_until_samples
while begin foo end
bar
end
until begin foo end
bar
end
while begin foo end do
bar
end
until begin foo end do
bar
end
foo while begin bar end
foo until begin bar end
end
| true
|
acbb70446386aad295f8f93d882f70d221e3d874
|
Ruby
|
dafoxia/mumble-ruby
|
/lib/mumble-ruby/packet_data_stream.rb
|
UTF-8
| 3,408
| 3.171875
| 3
|
[
"MIT"
] |
permissive
|
module Mumble
class PacketDataStream
def initialize(data=nil)
@data = data || 0.chr * 8192
@data = @data.split ''
@pos = 0
@ok = true
@capacity = @data.size
end
def valid
@ok
end
def size
@pos
end
def left
@capacity - @pos
end
def append(val)
if @pos < @capacity
@data[@pos] = val.chr
skip
else
@ok = false
end
end
def append_block(data)
len = data.size
if len < left
@data[@pos, len] = data.split('')
skip len
else
@ok = false
end
end
def get_block(len)
if len < left
ret = @data[@pos, len]
skip len
else
@ok = false
ret = []
end
ret
end
def get_next
if @pos < @capacity
ret = @data[@pos].ord
skip
else
ret = 0
@ok = false
end
ret
end
def rewind
@pos = 0
end
def skip(len=1)
len < left ? @pos += len : @ok = false
end
def put_int(int)
if !(int & 0x8000000000000000).zero? && (~int < 0x100000000)
int = ~int
puts int
if int <= 0x3
# Shortcase for -1 to -4
append(0xFC | int)
else
append(0xF8)
end
end
if int < 0x80
# Need top bit clear
append(int)
elsif int < 0x4000
# Need top two bits clear
append((int >> 8) | 0x80)
append(int & 0xFF)
elsif int < 0x200000
# Need top three bits clear
append((int >> 16) | 0xC0)
append((int >> 8) & 0xFF)
append(int & 0xFF)
elsif int < 0x10000000
# Need top four bits clear
append((int >> 24) | 0xE0)
append((int >> 16) & 0xFF)
append((int >> 8) & 0xFF)
append(int & 0xFF)
elsif int < 0x100000000
# It's a full 32-bit integer.
append(0xF0)
append((int >> 24) & 0xFF)
append((int >> 16) & 0xFF)
append((int >> 8) & 0xFF)
append(int & 0xFF)
else
# It's a 64-bit value.
append(0xF4)
append((int >> 56) & 0xFF)
append((int >> 48) & 0xFF)
append((int >> 40) & 0xFF)
append((int >> 32) & 0xFF)
append((int >> 24) & 0xFF)
append((int >> 16) & 0xFF)
append((int >> 8) & 0xFF)
append(int & 0xFF)
end
end
def get_int
v = get_next
int = 0
if (v & 0x80) == 0x00
int = v & 0x7F
elsif (v & 0xC0) == 0x80
int = (v & 0x3F) << 8 | get_next
elsif (v & 0xF0) == 0xF0
x = v & 0xFC
if x == 0xF0
int = get_next << 24 | get_next << 16 | get_next << 8 | get_next
elsif x == 0xF4
int = get_next << 56 | get_next << 48 | get_next << 40 | get_next << 32 |
get_next << 24 | get_next << 16 | get_next << 8 | get_next
elsif x == 0xF8
int = get_int
int = ~int
elsif x == 0xFC
int = v & 0x03
int = ~int
else
@ok = false
int = 0
end
elsif (v & 0xF0) == 0xE0
int = (v & 0x0F) << 24 | get_next << 16 | get_next << 8 | get_next
elsif (v & 0xE0) == 0xC0
int = (v & 0x1F) << 16 | get_next << 8 | get_next
end
return int
end
end
end
| true
|
b6c04964c0a96fdf8abc3f0bd92bdd09af4c35f9
|
Ruby
|
kunks001/boris_bikes
|
/boris_bikes.rb
|
UTF-8
| 278
| 3.640625
| 4
|
[] |
no_license
|
# class Person
# def initialize(name)
# @name = name
# @bike = 0
# end
# def name
# @name
# end
# def id
# end
# def bike
# @bike
# end
# def gets_bike
# @bike +=1
# end
# def returns_bike
# @bike -=1
# end
# end
| true
|
c0d3c4b9f2fe9690ecffa5651868569e774919a8
|
Ruby
|
skunath/STAT
|
/phoneme.rb
|
UTF-8
| 6,887
| 2.9375
| 3
|
[] |
no_license
|
class Phoneme
def initialize(args)
@cskip = -10.0
@csub = 35.0
@cexp = 45.0
@cvowel = 10.0
@epsilon = 0.0
@character = args[:character]
@type = args[:type] # vowel, consonant, diacritic
@manner = args[:manner]
@place = args[:place]
@high = args[:high]
@back = args[:back]
@round = args[:round]
@long = args[:long]
@syllabic = args[:syllabic]
@nasal = args[:nasal]
@retroflex = args[:retroflex]
@voice = args[:voice]
@lateral = args[:lateral]
@aspirated = args[:aspirated]
#
#
@features = {}
@features[:manner] = args[:manner]
@features[:place] = args[:place]
@features[:high] = args[:high]
@features[:back] = args[:back]
@features[:round] = args[:round]
@features[:long] = args[:long]
@features[:syllabic] = args[:syllabic]
@features[:nasal] = args[:nasal]
@features[:retroflex] = args[:retroflex]
@features[:voice] = args[:voice]
@features[:lateral] = args[:lateral]
@features[:aspirated] = args[:aspirated]
end
def character()
return @character
end
def vowel()
return @type == "vowel"
end
def vowel_cost()
return @cvowel
end
def alter_feature(name, value)
if !@features[name].nil?
if @features[name].class == String
@features[name] = value
else
@features[name] = @features[name] + value
end
else
@features[name] = value
end
end
def combine_features(phoneme_2)
for feature in phoneme_2.features
self.alter_feature(feature[0], feature[1])
end
end
#@vowel a single vowel object
#@pasofalkjf alksfja lskfja sf
def self.vowel(vowel)
# Runs a subprocess and applies handlers for stdout and stderr
# Params:
# +vowel+:: command line string to be executed by the system
if vowel.vowel()
return @cvowel
end
return 0.0
end
def to_s
@character
end
def set_character(full_character)
@character = full_character
end
def consonant()
return @type == "consonant"
end
def sound_type()
return @type
end
def round()
return @round
end
def long()
return @long
end
def manner()
return Manner[@manner]
end
def high()
return High[@high].to_f
end
def back()
return Back[@back]
end
def place()
return Place[@place]
end
def syllabic()
return @syllabic
end
def nasal()
return @nasal
end
def retroflex
return @retroflex
end
def voice
return @voice
end
def lateral
return @lateral
end
def aspirated
return @aspirated
end
def features
features = []
for pair in @features.to_a
features << pair if !pair[1].nil?
end
return features
end
def vowel_compare(compare_vowel)
diff = 0.0
# roundness comparison
roundness_diff = (self.round() - compare_vowel.round()).to_f.abs * Salience["round"]
# length comparison
length_diff = (self.long() - compare_vowel.long()).to_f.abs * Salience["long"]
# backness comparison
backness_diff = (self.back() - compare_vowel.back()).to_f.abs * Salience["back"]
# height comparison
height_diff = (self.high() - compare_vowel.high()).to_f.abs * Salience["high"]
# manner comparison
manner_diff = (self.manner() - compare_vowel.manner()).to_f.abs * Salience["manner"]
diff = diff + roundness_diff + length_diff + backness_diff + height_diff + manner_diff
return diff.round(5);
end
def consonant_compare(compare_consonant)
diff = 0.0
# manner comparison
manner_diff = (self.manner() - compare_consonant.manner()).to_f.abs * Salience["manner"]
# place comparison
place_diff = (self.place() - compare_consonant.place()).to_f.abs * Salience["place"]
# syllabic comparison
syllabic_diff = (self.syllabic() - compare_consonant.syllabic()).to_f.abs * Salience["syllabic"]
# nasal comparison
nasal_diff = (self.nasal() - compare_consonant.nasal()).to_f.abs * Salience["nasal"]
# retroflex comparison
retroflex_diff = (self.retroflex() - compare_consonant.retroflex()).to_f.abs * Salience["retroflex"]
# voice comparison
voice_diff = (self.voice() - compare_consonant.voice()).to_f.abs * Salience["voice"]
# lateral comparison
lateral_diff = (self.lateral() - compare_consonant.lateral()).to_f.abs * Salience["lateral"]
# aspirated comparison
aspirated_diff = (self.aspirated() - compare_consonant.aspirated()).to_f.abs * Salience["aspirated"]
diff = manner_diff + place_diff + syllabic_diff + nasal_diff + retroflex_diff + voice_diff + lateral_diff + aspirated_diff
return diff.round(5)
end
def mixed_compare(other_phoneme)
vowel, consonant = nil
if self.vowel()
vowel = self
consonant = other_phoneme
else
vowel = other_phoneme
consonant = self
end
# begin computing diff
diff = 0.0
# syllabic comparison
#syllabic_diff = (consonant.syllabic() - vowel.syllabic()).to_f.abs * Salience["syllabic"]
# nasal comparison
#nasal_diff = (consonant.nasal() - vowel.nasal()).to_f.abs * Salience["nasal"]
# retroflex comparison
#retroflex_diff = (consonant.retroflex() - vowel.retroflex()).to_f.abs * Salience["retroflex"]
# manner comparison
manner_diff = (consonant.manner() - vowel.manner()).to_f.abs * Salience["manner"]
# place comparison
place_diff = (consonant.place() - 0.0).to_f.abs * Salience["place"]
# voice comparison
voice_diff = (consonant.voice() - 0.0).to_f.abs * Salience["voice"]
# lateral comparison
lateral_diff = (consonant.lateral() - 0.0).to_f.abs * Salience["lateral"]
# aspirated comparison
aspirated_diff = (consonant.aspirated() - 0.0).to_f.abs * Salience["aspirated"]
diff = manner_diff + place_diff + voice_diff + lateral_diff + aspirated_diff
return diff.round(5)
end
def self.total_diff(phoneme_1, phoneme_2)
# must be two phonemes coming in... alphabets will be different
# This function determines the actual difference between two characters/phonemes
# based on the features it knows of of the character/phoneme.
# Notes:
# This should probably create an on the fly hash when the class is instantiated to memoize
# previous diff calculations...It should speed things up.
first_string_vowel = phoneme_1.vowel()
second_string_vowel = phoneme_2.vowel()
if !first_string_vowel && !second_string_vowel
# case where both characters/phonemes are consonants
return phoneme_1.consonant_compare(phoneme_2)
elsif first_string_vowel && second_string_vowel
# case where only vowels are passed
return phoneme_1.vowel_compare(phoneme_2)
else
# Mixed case with a vowel and a consonant
return phoneme_1.mixed_compare(phoneme_2)
end
end
end
| true
|
b076f8978f2f51233968c40cafb911da7ea22421
|
Ruby
|
sujankh/SimPlParser
|
/simplparser.rb
|
UTF-8
| 655
| 3.1875
| 3
|
[] |
no_license
|
#!/usr/bin/ruby
require_relative './lexer'
require_relative './parser'
def getTokenKind()
$tokenizer.getTokenKind()
end
def getTokenText()
$tokenizer.getTokenText()
end
#consume token
def nextToken()
$tokenizer.nextToken()
end
def parseProgram()
inputFile = ARGV[0]
begin
$tokenizer.readFile(inputFile)
nextToken() #initialize the lexer to put the cursor to current token
parseStatements()
nextToken() #consume EOF
puts "End Of File"
puts "Successful parse."
rescue ParseError => e
puts "Syntax error:"
puts e.message
end
end
#start parser program
$tokenizer = Tokenizer.new
parseProgram()
| true
|
cfe0c4cb1d8f7b017e7b337507fa9a30f4e7a645
|
Ruby
|
DavidPAdams/nlr
|
/Lesson_1_hw/calculator.rb
|
UTF-8
| 148
| 3.015625
| 3
|
[] |
no_license
|
def add(a,b)
a + b
end
def subtract(c,d)
c - d
end
def multiply2(e,f)
e * f
end
def divide2(g,h)
h != 0 ? g/h : "undefined"
end
| true
|
435e0a014017addf59e0d5837188a3436b5a6bd5
|
Ruby
|
dbirtwell/RubyLearning_32
|
/Week_7/rubyprograms/lesson7exercise3.rb
|
UTF-8
| 1,509
| 4.65625
| 5
|
[] |
no_license
|
# lesson7exercise3.rb
# David Birtwell
=begin
Week 7 Exercise 3.
Write a method called month_days, that determines the number of days in a
month. Usage:
days = month_days(5) # 31 (May)
days = month_days(2, 2000) # 29 (February 2000)
Remember, you could use the Date class here. Read the online documentation
for the Date class. You must account for leap years in this exercise.
=end
require 'date'
# Default the year to current year if not passed in
def month_days(month_num, year=Time.now.year)
# Steps:
# 1) Set the date to the 1st day of the next month for which we want to
# count the number of days.
# 2) Roll back a day, which takes us to the end of the month
# 3) Return that day of the mmonht (end of month day == number of days in
# the month
#
# The code snipprt below shifts/increments the month of the date 1 month.
# date >> 1
#
# The below snippet subtracts one day from the date. In our case, this rolls
# back the date to the previous day (subtracts one day).
# Note - This automativcally handes leap year.
# date - 1
#
# returns the day of the date
# date.day
((Date.new(year, month_num, 1) >> 1) - 1).day
end
days = month_days(5) # 31 (May)
puts "Days: #{days}"
days = month_days(2, 2000) # 29 (February 2000)
puts "Days: #{days}"
days = month_days(6) # 30 (June)
puts "Days: #{days}"
days = month_days(12) # 31 (December)
puts "Days: #{days}"
days = month_days(1, 2008) # 1 (January 2008)
puts "Days: #{days}"
| true
|
b01cbb60fbaea909777bd1791b0921f794220ee2
|
Ruby
|
ruben/smalltalk-best-practice-patterns
|
/3-behaviour/2-messages/3-intention_revealing_message/1-paragraph_editor.rb
|
UTF-8
| 372
| 3.515625
| 4
|
[] |
no_license
|
# How do you communicate your intent when the implementation is simple?
#
# Send a message to “self.” Name the message so it communicates what is to be done rather than how it is to be done.
# Code a simple method for the message.
# We highlight a rectangle (WHAT) by reversing it (HOW)
class ParagraphEditor
def highlight rectangle
reverse rectangle
end
end
| true
|
2b9dfea91af9ec88509bd6b28c4b25310574dbfa
|
Ruby
|
avescodes/botfly
|
/lib/botfly/callback_context.rb
|
UTF-8
| 1,629
| 2.765625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
module Botfly
class CallbackContext
def initialize(caller, params)
setup_params(params)
@caller = caller
end
def method_missing(name, *args)
@caller.send(name,*args) if name.to_s.scan(/^setup/).empty?
end
private
# OK, so. Get the instance's eigenclass, then, call the private method define_method - thus created the method called #{name} that returns value. Basically attr_reader but for any generic variable.
def expose(name, value)
(class<<self;self;end).send(:define_method,name,proc{value})
end
def setup_params(params)
params.each do |name,value|
send(:"setup_#{name}", value)
end
end
def setup_roster_item(roster_item)
expose(:roster_item, roster_item)
end
def setup_message(message)
expose(:message, message)
expose(:body, message.body)
expose(:chat_state, message.chat_state)
expose(:subject, message.subject)
expose(:type, message.type)
expose(:from, message.from)
expose(:to, message.to)
end
def setup_presence(presence, pre = '')
expose(:"#{pre}presence", presence)
expose(:"#{pre}from", presence.from)
expose(:"#{pre}show", presence.show)
expose(:"#{pre}priority", presence.priority)
expose(:"#{pre}status", presence.status)
expose(:"#{pre}type", presence.type)
end
def setup_old_presence(presence); setup_presence(presence, 'old_') end
def setup_time(time); expose(:time, time) end
def setup_nick(nick); expose(:from, nick); end
def setup_text(text); expose(:text, text); expose(:body, text); end
end
end
| true
|
70b038d2f1ea28c74e0ab5ee01e3adace44c24cc
|
Ruby
|
takahiro825/furima-28705
|
/spec/models/user_spec.rb
|
UTF-8
| 5,697
| 2.734375
| 3
|
[] |
no_license
|
require 'rails_helper'
describe User do
before do
@user = FactoryBot.build(:user)
end
describe 'ユーザー登録' do
context 'ユーザー登録がうまくいくとき' do
it "nicknameとemail、passwordとpassword_confirmation、family_name、first _name、family_name_kana、first _name_kana、birthdayが存在すれば登録できる" do
expect(@user).to be_valid
end
it "emailは@が存在すれば登録できる" do
@user.email = "ffgdsm64@khj.com"
expect(@user).to be_valid
end
it "passwordが6文字以上でであれば登録できる" do
@user.password = "000000"
@user.password_confirmation = "000000"
expect(@user).to be_valid
end
it "passwordが半角英数字混同であれば登録できる" do
@user.password = "abc123"
@user.password_confirmation = "abc123"
expect(@user).to be_valid
end
it "ユーザー名の苗字は全角で入力すれば登録できる" do
@user.family_name = "後藤"
expect(@user).to be_valid
end
it "ユーザー名の名前は全角で入力すれば登録できる" do
@user.first_name = "貴裕"
expect(@user).to be_valid
end
it "ユーザー名の苗字のフリガナは全角(カタカナ)で入力すれば登録できる" do
@user.family_name_kana = "ゴトウ"
expect(@user).to be_valid
end
it "ユーザー名の名前のフリガナは全角(カタカナ)で入力すれば登録できる" do
@user.first_name_kana = "タカヒロ"
expect(@user).to be_valid
end
end
context 'ユーザー登録がうまくいかないとき' do
it "nicknameが空だと登録できない" do
@user.nickname = ""
@user.valid?
expect(@user.errors.full_messages).to include("Nickname can't be blank")
end
it "emailが空では登録できない" do
@user.email = ""
@user.valid?
expect(@user.errors.full_messages).to include("Email can't be blank")
end
it "重複したemailが存在する場合登録できない" do
@user.save
another_user = FactoryBot.build(:user)
another_user.email = @user.email
another_user.valid?
expect(another_user.errors.full_messages).to include("Email has already been taken")
end
it "emailには@が存在しない場合登録できない" do
@user.email = "fgfdug42354ff"
@user.valid?
expect(@user.errors.full_messages).to include("Email is invalid")
end
it "passwordが空では登録できない" do
@user.password = ""
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it "passwordが5文字以下であれば登録できない" do
@user.password = "00000"
@user.password_confirmation = "00000"
@user.valid?
expect(@user.errors.full_messages).to include("Password is too short (minimum is 6 characters)")
end
it "passwordが存在してもpassword_confirmationが空では登録できない" do
@user.password_confirmation = ""
@user.valid?
expect(@user.errors.full_messages).to include("Password confirmation doesn't match Password")
end
it "password_confirmationが存在してもpasswordが空では登録できない" do
@user.password = ""
@user.valid?
expect(@user.errors.full_messages).to include("Password can't be blank")
end
it "family_nameが空では登録できない" do
@user.family_name = ""
@user.valid?
expect(@user.errors.full_messages).to include("Family name can't be blank")
end
it "first_nameが空では登録できない" do
@user.first_name = ""
@user.valid?
expect(@user.errors.full_messages).to include("First name can't be blank")
end
it "family_name_kanaが空では登録できない" do
@user.family_name_kana = ""
@user.valid?
expect(@user.errors.full_messages).to include("Family name kana can't be blank")
end
it "first_name_kanaが空では登録できない" do
@user.first_name_kana = ""
@user.valid?
expect(@user.errors.full_messages).to include("First name kana can't be blank")
end
it "ユーザー名の苗字は全角で入力しなければ登録できない" do
@user.family_name = "ssss"
@user.valid?
expect(@user.errors.full_messages).to include("Family name is invalid")
end
it "ユーザー名の名前は全角で入力しなければ登録できない" do
@user.first_name = "aaaa"
@user.valid?
expect(@user.errors.full_messages).to include("First name is invalid")
end
it "ユーザー名の苗字のフリガナは全角(カタカナ)で入力しなければ登録できない" do
@user.family_name = "たたたた"
@user.valid?
expect(@user.errors.full_messages).to include()
end
it "ユーザー名の名前のフリガナは全角(カタカナ)で入力しなければ登録できない" do
@user.first_name_kana = "おおおお"
@user.valid?
expect(@user.errors.full_messages).to include("First name kana is invalid")
end
it "birthdayが空では登録できない" do
@user.birthday = ""
@user.valid?
expect(@user.errors.full_messages).to include("Birthday can't be blank")
end
end
end
end
| true
|
83b6236399857bfa000814239d608205f72daf6e
|
Ruby
|
Zoratoostar/Exercise_9
|
/cargo_train.rb
|
UTF-8
| 170
| 2.625
| 3
|
[] |
no_license
|
class CargoTrain < Train
def hitch_carriage(car)
super(car) if car.is_a?(FreightWagon)
end
def to_s
"#{unique_number}_cargo_#{carriages.count}"
end
end
| true
|
4db89e62b28142104ae898e29ade0cd4b4eb8bc1
|
Ruby
|
yoshida-eth0/async_enum
|
/lib/enumerator/async.rb
|
UTF-8
| 2,086
| 2.96875
| 3
|
[] |
no_license
|
class Enumerator
class Async < Enumerator
class Lockset
def initialize
@semaphores = Hash.new do |locks, key|
locks[key] = Mutex.new
end
end
def lock(key = :__default__, &thread_unsafe_block)
@semaphores[key].synchronize(&thread_unsafe_block)
end
alias_method :evaluate, :instance_exec
end
def initialize(enum, pool_size = nil)
@enum = enum
@pool_size = pool_size
@lockset = Lockset.new
end
def to_a
@enum.to_a
end
def sync
@enum
end
alias_method :to_enum, :sync
def size
@enum.size
end
def each(&work)
raise_error('each') unless block_given?
if @pool_size
threads = @pool_size.times.map do
Thread.new do
loop do
@enum.any? ? evaluate(*@enum.next, &work) : break
end
end
end
threads.each(&:join)
@enum.rewind
else
unlimited_threads(&work).each(&:join)
end
self
end
def with_index(start = 0, &work)
@enum = @enum.with_index(start)
if block_given?
each(&work)
else
self
end
end
def with_object(obj, &work)
@enum = @enum.with_object(obj)
if block_given?
each(&work); obj
else
self
end
end
def map(&work)
raise_error('map') unless block_given?
if @pool_size
outs = []
with_index do |item, index|
outs[index] = evaluate(item, &work)
end
outs
else
unlimited_threads(&work).map(&:value)
end
end
private
def evaluate(*args, &work)
@lockset.instance_exec(*args, &work)
end
def unlimited_threads(&work)
@enum.map do |*args|
Thread.new{ evaluate(*args, &work) }
end
end
def raise_error(method)
raise ArgumentError, "tried to call async #{method} without a block"
end
end
end
| true
|
5ab454070399ce5448d45bc7b1048b04361bfc4b
|
Ruby
|
loushark/battle
|
/spec/player_spec.rb
|
UTF-8
| 316
| 2.625
| 3
|
[] |
no_license
|
require 'player'
describe Player do
let(:player) { Player.new("Crazy Teaspoon") }
it 'initializes a name on a new player instance' do
expect(player.name).to eq("Crazy Teaspoon")
end
it 'initializes a deafult hitpoint value on a new player instance' do
expect(player.hitpoints).to eq(60)
end
end
| true
|
1c98fa3bf47ba4e84d90afacef8c7f210ee2b28a
|
Ruby
|
pychap/Launch_school_101
|
/lesson_3/medium_1.rb
|
UTF-8
| 1,834
| 3.828125
| 4
|
[] |
no_license
|
require 'pry'
# stoneage_rock = "The Flintstones Rock!"
# n = 23
# 10.times do
# # n = n += 1
# puts stoneage_rock.center(n += 1)
# end
# 10.times {|num| puts (" " * num) + stoneage_rock}
# statement = "The Flintstones Rock!"
# flintstones_hash = {}
# letters = ('A'..'Z').to_a + ('a'..'z').to_a
# letters.each do | letter |
# letter_frequency = statement.scan(letter).count
# flintstones_hash[letter] = letter_frequency if letter_frequency > 0
# end
# p flintstones_hash
# puts "the value of 40 + 2 is " + "#{(40 + 2)}"
# def titleize word
# split_apart = word.split(//)
# upper_cased = []
# split_apart.each do |letter|
# upper_cased << letter.upcase
# end
# final = upper_cased.join
# puts final
# end
# titleize("Now is the time for all good men to come to the aid of their party!")
munsters = {
"Herman" => { "age" => 32, "gender" => "male" },
"Lily" => { "age" => 30, "gender" => "female" },
"Grandpa" => { "age" => 402, "gender" => "male" },
"Eddie" => { "age" => 10, "gender" => "male" },
"Marilyn" => { "age" => 23, "gender" => "female"}
}
# "age_group" => "adult"
# munsters[key_counter].merge!({:"age_group" => "adult"})
# key[counter] == [['new_key' => 'new_value']]
# need to use map
# loop
# def sort_munsters(age)
# case age
# when age == 0..17 then "kid"
# when age == 17..65 then "adult"
# when age > 65 then "senior"
# else
# false
# end
# age
# end
# # now add to the munsters hash
# munsters.each+ do |key, value|
# sort_munsters(value:("age", =>))
# key[:key] << value.merge!([-1, "age_group" => "age"])
# end
# the REAL answer
munsters.each do |name, details|
case details["age"]
when 0...18
details["age_group"] = "kid"
when 18...65
details["age_group"] = "adult"
else
details["age_group"] = "senior"
end
end
p munsters
| true
|
fa59bf57da8f5a0febc23ea56fc64b089091c658
|
Ruby
|
DanielVartanov/isp-logs-parser
|
/lib/traffic_splitter.rb
|
UTF-8
| 380
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
class TrafficSplitter
def self.split_traffic!(traffic)
hosts = traffic.daily.internal.highest_twenty_hosts +
traffic.nightly.internal.highest_twenty_hosts +
traffic.daily.world.highest_twenty_hosts +
traffic.nightly.world.highest_twenty_hosts
hosts.sort! { |left, right| right.amount_of_traffic <=> left.amount_of_traffic }
hosts[0..19]
end
end
| true
|
ba8f9b57f2d9dc4e3e1d90ede3382b3029aadce0
|
Ruby
|
slbug/test_img
|
/app/models/image.rb
|
UTF-8
| 439
| 2.546875
| 3
|
[] |
no_license
|
class Image < ActiveRecord::Base
validates :title, :presence => true, :length => { :minimum => 3 }
validates :url, :presence => true, :length => { :minimum => 10 }
before_save :ensure_uid
private
def ensure_uid
if uid.blank?
allowed_symbols = ('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a
self.uid = (0...5).collect { allowed_symbols[Kernel.rand(allowed_symbols.length)] }.join
end
end
end
| true
|
a154896e0969d98155f169a98c77c8c8131824ea
|
Ruby
|
mizuhoiimori/rubybook
|
/private.rb
|
UTF-8
| 166
| 3.171875
| 3
|
[] |
no_license
|
class Cafe
def staff
makanai
end
private
def makanai
"店員スペシャルメニュー"
end
end
cafe = Cafe.new
puts cafe.staff
puts cafe.makanai
| true
|
b73ce11b5edde4c06e1f2c904e6608b3ef0a827d
|
Ruby
|
RichardCharman/takeaway-challenge
|
/spec/customer_spec.rb
|
UTF-8
| 799
| 2.734375
| 3
|
[] |
no_license
|
require 'customer'
describe Customer do
it { expect(subject).to respond_to(:show_menu) }
describe '#ordering' do
it 'should take an order for food with 2 arguments' do
expect(subject).to respond_to(:order_item).with(2).argument
end
it { expect(subject).to respond_to(:view_order) }
it 'should display correct order' do
subject.order_item("burger", 2)
expect(subject.view_order).to eq [{"burger"=>4}, {"burger"=>4}]
end
it 'should give correct price' do
subject.order_item("burger", 2)
expect(subject.order_price).to eq ("The cost for your order is £8.0")
end
it 'should raise an error if placing empty order' do
expect{subject.place_order}.to raise_error "You haven't ordered any food"
end
end
end
| true
|
2e09106b0fa5478524f95e5cd61da1987aba2e62
|
Ruby
|
biancaguzenski/basic-algorithms-and-data-structures
|
/Others/is_palindrome.rb
|
UTF-8
| 617
| 3.53125
| 4
|
[] |
no_license
|
require "test/unit/assertions"
include Test::Unit::Assertions
def to_char(string)
string = string.downcase.chars
string = string.keep_if {|c| c =~ /[abcdefghijklmnopqrstuvwxyz]/ }.join
is_palindrome(string)
end
def is_palindrome(string)
i = string.size-1
reversed = ""
while i >= 0
reversed << string[i]
i -= 1
end
reversed == string ? true : false
end
assert_equal to_char("abba"), true
assert_equal to_char("abbas"), false
assert_equal to_char("tattarrattat"), true
assert_equal to_char("Was it a palindrome?"), false
assert_equal to_char("No lemon, no melon"), true
| true
|
7640ea18727d0ca0f1884b9755e7d45b92e9588a
|
Ruby
|
sithobog/seo_tool
|
/lib/seo/user.rb
|
UTF-8
| 1,032
| 2.609375
| 3
|
[] |
no_license
|
require 'sequel'
require 'bcrypt'
module Seo
class User
attr_accessor :id
DB = Sequel.connect(:adapter => 'postgres', :host => 'localhost',
:database => 'warden_test', :user => 'tester', :password => 'test_password')
def initialize(id, username, password, ip)
@id = id
@username = username
@password = password
@ip = ip
create_table
end
def authenticate(attempted_password)
if @password == attempted_password
true
else
false
end
end
def self.get(id)
DB.from(:users).where(:id => id).all
end
def self.get_by_name(name)
DB.from(:users).where(:username => name).all
end
def add_user(name,password)
users = DB.from(:users)
users.insert.(:username => name, :password => password)
end
def create_table
DB.create_table? :users do
primary_key :id
String :username
String :password
Inet :user_ip
end
end
end
end
| true
|
239a53c5500c6187dc4a0644b3d836edb2aafeb8
|
Ruby
|
liyijie/span_report
|
/app/span_report/logfile/csv_file_operate.rb
|
UTF-8
| 4,027
| 2.71875
| 3
|
[] |
no_license
|
# encoding: utf-8
module SpanReport::Logfile
class CsvReader
###################################################
# 这里传入的files并不是普通的文件名,而是封装的结构
##################################################
def initialize(files, is_temp=false)
@files = files
@is_temp = is_temp
end
def parse(processors)
@files.each do |fileinfo|
filename = fileinfo.filename
puts "process log #{filename}"
if @is_temp
parse_temp_file filename, processors
else
parse_one_file filename,processors
end
end
end
private
def parse_one_file filename, processors
line_index = 0
head_info = []
File.foreach(filename) do |line|
line = line.chop
contents = line.split ','
if line_index == 0
contents.each do |item|
head_info << item
end
else
data_map = {}
contents.each_with_index do |item, i|
next if item.to_s.empty?
data_map[head_info[i].to_s] = item
end
time = data_map["time"]
ue = data_map["ue"]
data_map.map do |key, value|
key = key.encode('utf-8')
value = value.encode('utf-8')
end
point_data = SpanReport::Simulate::PointData.new time, ue, data_map
point_data.expand_data
next if (point_data.rsrp.to_f <= -140) || !point_data.valid?
# 调用每个处理器处理数据
processors.each do |process|
# begin
process.process_pointdata point_data
# rescue Exception => e
# puts "process data error:#{e.backtrace}"
# next
# end
end
end
line_index += 1
end
end
def parse_temp_file filename, processors
line_index = 0
File.foreach(filename) do |line|
if line_index == 0
line_index += 1
next
end
line = line.chop
contents = line.split ','
data_map = {}
data_map["time"] = contents[0]
data_map["ue"] = "1"
data_map["lontitute"] = contents[3]
data_map["latitude"] = contents[4]
data_map["scell_pci"] = contents[5]
data_map["scell_freq"] = "1890"
data_map["scell_rsrp"] = contents[6]
data_map["scell_sinr"] = 0
(0..7).each do |i|
data_map["ncell_pci_#{i}"] = contents[7 + 2*i]
data_map["ncell_freq_#{i}"] = "1890"
data_map["ncell_rsrp_#{i}"] = contents[8 + 2*i]
end
time = data_map["time"]
ue = data_map["ue"]
point_data = SpanReport::Simulate::PointData.new time, ue, data_map
point_data.expand_data
# 调用每个处理器处理数据
processors.each do |process|
# begin
process.process_pointdata point_data
# rescue Exception => e
# puts "process data error:#{e.backtrace}"
# next
# end
end
line_index += 1
end
end
end
class CsvWriter
def initialize resultfile
@export_datas = []
open_file resultfile
end
def add_data pointdata
@export_datas << pointdata
write_result
end
def << pointdata
add_data pointdata
end
def close_file
flush
@file.close if @file
end
private
def open_file result_file
# puts "output csv file is:#{result_file}"
result_file = result_file.encode 'gbk'
@file = File.new(result_file, "w")
@file.puts head_string
end
def write_result
if @export_datas.size > 100
flush
end
end
def flush
@export_datas.each do |pointdata|
@file.puts pointdata.to_s.encode 'gbk'
end
@export_datas.clear
end
def head_string
SpanReport::Simulate::PointData.head_string
end
end
end
| true
|
710f5273f61dc58c0fb0b13300a706c306711ca9
|
Ruby
|
tsunagun/cheats
|
/webapi/yahoo/assistsearch.rb
|
UTF-8
| 1,068
| 2.90625
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
# Yahoo Web APIを使って関連検索ワードの取得を行うスクリプト
class Yahoo
# ライブラリ読み込み
require 'pp'
require 'open-uri'
require 'nokogiri'
require 'cgi'
# Yahoo Web APIのアプリケーションIDをyahoo_key.txtから読み込む
load 'yahoo_key.txt'
# APIへのリクエストURLを生成する
def self.make_request_url(query)
base_uri = "http://search.yahooapis.jp/AssistSearchService/V1/webunitSearch?"
params = [
"appid=" + YAHOO_KEY,
"query=" + CGI.escape(query)
].join("&")
url = base_uri + params
end
# 入力文字列の形態素解析結果を取得
def self.assistsearch(input)
results_path = "/xmlns:ResultSet/xmlns:Result"
request_url = self.make_request_url(input)
parser = Nokogiri::XML(open(request_url))
results = parser.xpath(results_path, parser.namespaces)
results.map do |result| result.text end
end
end
# queryの漢字変換候補を求める
query = ARGV[0] || "大学"
pp Yahoo.assistsearch(query)
| true
|
8c03794f02fdea2f7956f361af6bbdd3e8173987
|
Ruby
|
angelv8a8/SP1Ruby
|
/Tarea1/Tarea1.rb
|
UTF-8
| 5,708
| 3.546875
| 4
|
[] |
no_license
|
module Tarea1
def atoi(str)
valor = 0
digitos = str.split("")
digitosC = digitos.count
digitosC -= 1
mul = 1
digitosC.downto(0) do | i |
case digitos[i]
when "0"
valor = valor
when "1"
valor += 1 * mul
when "2"
valor += 2*mul
when "3"
valor += 3*mul
when "4"
valor += 4*mul
when "5"
valor += 5*mul
when "6"
valor += 6*mul
when "7"
valor += 7*mul
when "8"
valor += 8*mul
when "9"
valor += 9*mul
else
puts "Error, digito invalido " + digitos[i]
return
end
mul = mul*10
end
return valor
end
def char_count( s, c)
letras = s.split("");
contador = 0
if c.to_s.size > 1
puts "ERROR: El segundo parametro debe ser un caracter"
return nil
end
letrasC = letras.count
0.upto(letrasC - 1) do | i |
if c == letras[i]
contador += 1
end
end
return contador
end
def sort(elArray, is_asc)
resultado = Array.new
#puts elArray
0.upto(elArray.count - 1) do |i|
if is_asc
indexMenor = getMayor(elArray)
else
indexMenor = getMenor(elArray)
end
#puts "menor " + indexMenor.to_s
palabraMenor = elArray.delete_at(indexMenor)
resultado.insert(0,palabraMenor)
end
return resultado
end
def getMayor(array)
index = 0;
mayor = array[0]
0.upto(array.count - 1 ) do | i |
#puts "It " + i.to_s
if array[i] >= mayor
mayor = array[i]
index = i
end
end
return index
end
def getMenor(array)
index = 0;
menor = array[0]
0.upto(array.count - 1 ) do | i |
if array[i] <= menor
menor = array[i]
index = i
end
end
return index
end
def hanoi(height,fromPole, toPole, withPole)
height_i = height.to_i
if height_i >= 1
hanoi(height_i-1,fromPole.to_i,withPole.to_i,toPole.to_i)
moveDisk(fromPole.to_i,toPole.to_i)
hanoi(height_i-1,withPole.to_i,toPole.to_i,fromPole.to_i)
end
end
def moveDisk(fp,tp)
puts "Mover disco de " + fp.to_i.to_s + " a " + tp.to_i.to_s
end
def cuenta_palabras (frase)
hash = Hash.new(0)
palabras = frase.to_s.split(" ")
puts "Tamaño " + palabras.count.to_s
c_palabras = palabras.count
0.upto(c_palabras -1) do | i |
#puts palabras[i].to_s + " " + hash[palabras[i].to_s].to_s
hash[palabras[i].to_s] = hash[palabras[i].to_s] + 1
end
return hash
end
def palindromo?(x)
tam = x.to_s.size
valid = true;
0.upto(x.size-1) do | i |
str = x[i].concat(" ").concat(x[tam-i-1])
if x[i] != x[tam-i-1]
valid = false;
break;
end
end
return valid
end
class Dessert
@@desserts = 0
def name=(value)
@value = value
end
def name
@name
end
def calories=(value)
@calories = value
end
def calories
@calories
end
def initialize(name, calories)
@name = name
@calories = calories
@size = nil
@@desserts += 1
end
def healthy?
if @calories < 200
return true
end
return false
end
def delicious?
return true
end
def count
return @@desserts
end
def to_s
# YOUR CODE HERE
end
end
class JellyBean < Dessert
def flavor=(value)
@flavor = value
end
def flavor
@flavor
end
def initialize(name, calories, flavor)
super(name, calories)
@flavor = flavor
end
def delicious?
if @flavor == "black licorice"
return false
end
return super
end
end
end
module Action
@@distance = 0;
def jump(vel)
@@distance = rand(vel.to_i) + 2
puts "I jumped forward #{@@distance} feet!"
end
end
class Rabbit
include Action
attr_reader :name, :velocidad
def initialize(name)
@name = name
@velocidad = 8
end
def run()
distInicial = 0
start = Time.now
while distInicial < 33 do
jump(@velocidad)
distInicial += @@distance
end
puts (Time.now - start).to_s + " segundos"
end
end
class Cricket
include Action
#include Date
attr_reader :name, :velocidad
def chirp()
0.upto(10 + rand(90)) do | i |
puts i.to_s + " Chirp... chirp!!!"
end
end
def initialize(name)
@name = name
@velocidad = 4
end
def run()
distInicial = 0
start = Time.now
while distInicial < 33 do
jump(@velocidad)
distInicial += @@distance
end
puts (Time.now - start).to_s + " segundos"
end
end
class Computer
include Tarea1
@@users = {}
@fileDir
def initialize username, password
@username = username
@password = password
@fileDir = Hash.new
@files = {}
end
def insert (name)
if @fileDir[name] == 0
puts "Error, el archivo ya existe"
else
@fileDir[name] = Time.now.to_s
end
end
def ls (sort)
keys = @fileDir.keys
if sort.to_s == "asc"
keys = Tarea1.sort(keys,true)
else
keys = Tarea1.sort(keys,false)
end
0.upto(keys.count-1) do | i |
puts keys[i] + "\t" + @fileDir[keys[i]]
end
puts "End of List"
end
end
| true
|
085048caa650229e2bfe0a807d3ab35698a28855
|
Ruby
|
eriese/risqueFactr
|
/app/models/partner.rb
|
UTF-8
| 1,489
| 2.5625
| 3
|
[] |
no_license
|
# == Schema Information
#
# Table name: partners
#
# id :integer not null, primary key
# user_id :integer
# pref_id :integer
# name :string(255)
# frequency :string(255)
# familiarity :integer
# exclusivity :string(255)
# created_at :datetime not null
# updated_at :datetime not null
#
class Partner < ActiveRecord::Base
attr_accessible :user_id, :pref_id, :name, :frequency, :familiarity, :exclusivity, :pref_attributes
belongs_to :user
has_many :encounters
belongs_to :pref
accepts_nested_attributes_for :pref
validates :user_id, :name, :presence => true
def most_recent
self.encounters_by_date.first
end
def encounters_by_date
self.encounters.order("took_place DESC")
end
def risk
@risk = 0
case self.exclusivity
when "exclusive"
@risk += 1
when "only having sex with known others"
@risk += 2
when "not exclusive with disclosure of other partners"
@risk += 3
when "not exclusive, no disclosure of other partners"
@risk += 4
end
@risk += 10 - self.familiarity
return @risk
end
def pronoun
if self.pref_id
return self.pref.pronoun
else
return nil
end
end
def at_risk(disease)
if self.most_recent
if disease.risk_window(self.user)
return disease.risk_window(self.user) < self.most_recent.took_place
else
return true
end
else
return false
end
end
end
| true
|
621b7828249eceb670d5c8d180e2d654e0037a90
|
Ruby
|
mattcrowe5/prime-ruby-prework
|
/prime.rb
|
UTF-8
| 239
| 3.828125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def prime?(number)
if number == 0 || number == 1 || number == -1
return false
end
x = 2
stop = number/x
while x <= stop
if number % x == 0
return false
end
x+=1
stop = number/x
end
return true
end
| true
|
2c0d7194c26d2c4c281000aff8eda7b9ea5af79a
|
Ruby
|
pongsanti/mcotv3
|
/lib/util/record_op.rb
|
UTF-8
| 214
| 3.046875
| 3
|
[] |
no_license
|
class RecordOp
def initialize(array, skip)
@array = array
@skip = skip
end
def split
return [], [] if @array.empty?
return @array[0, @skip] || [], @array[@skip, @array.length] || []
end
end
| true
|
37d71161e4e43ca08ad17d28f7e45a215b8f8a17
|
Ruby
|
SVRourke/pantry_backend
|
/test/models/user_test.rb
|
UTF-8
| 1,588
| 2.828125
| 3
|
[] |
no_license
|
require "test_helper"
class UserTest < ActiveSupport::TestCase
def setup
@good_user = User.create(name: 'sam', email: 's@s.com', password: 'pass')
@email_user = User.new(name: 'sam', password: 'pass')
@password_user = User.new(name: 'sam', email: 's@s.com')
@lists = [
List.create(name: "list one"),
List.create(name: "list two"),
List.create(name: "list three")
]
@lists.each { |l| l.contributors.push(@good_user) }
@users = [
User.new(name: "a", email: "1A@b.c", password: "passsword"),
User.new(name: "b", email: "2A@b.c", password: "passsword"),
User.new(name: "c", email: "3A@b.c", password: "passsword")
]
@users.each {|u| @good_user.friends.push(u)}
end
test "user can be created" do
assert @good_user.valid?, "Valid User does not save"
end
test "user invalid without email" do
assert_not @email_user.valid?, "Able to save User without email"
end
test "user invalid without password" do
assert_not @password_user.valid?, "Able to save user without password"
end
test "user can have multiple lists" do
assert @good_user.lists.count > 1, "list relationship needs to be two ways"
end
test "user can leave a list" do
@good_user.leave_list(@lists.first)
assert @good_user.lists.count < 3, "issue with #leave_list"
end
test "user can have many friends" do
assert @good_user.friends.count > 1
end
test "user can remove a friend" do
@good_user.unfriend(@users.first)
assert @good_user.friends.count < 3
end
end
| true
|
caee6c35cc9c1eb3a1fc4dea0efd0ff4f028b20c
|
Ruby
|
denalibalser/compost_cli
|
/lib/cli.rb
|
UTF-8
| 2,782
| 3.875
| 4
|
[
"MIT"
] |
permissive
|
#our CLI Controller, welcoming the user and dealing with user input
class CLI
def start
list_boroughs
select_boroughs
list_addresses
select_address
collection_day
go_compost
end
def list_boroughs
puts "Welcome! Composting is an easy way to reduce waste. However, urban composting can be hard, we're here to help simplify it for New Yorkers!"
puts "There are compost drop-off locations in all five boroughs:"
borough_arr = Borough.list_borough_names
puts borough_arr.each_with_index(1) do |borough, index|
"#{index}. #{borough.name}"
end
select_borough(borough_arr)
end
def select_borough(borough_arr)
input = nil
while input != "exit"
puts "Please select a borough 1 - 5 from which you would like to find a compost drop-off location or type 'exit' to exit:"
input = gets.strip.downcase
input = input.to_i
if input > 0 && input < 5
the_borough = borough_arr[input-1].name.strip
puts "Here is the list of compost drop-off locations for #{the_borough.upcase}:"
list_addresses(the_borough)
elsif input.downcase == "exit"
go_compost
else
puts "Invalid Input. Please enter the number of the borough in which you would like to find a compost drop-off location or type 'exit' to exit:"
end
end
end
def list_addresses(the_borough)
puts "Please select the number that corresponds with the compost drop-off address you would like more information on or type 'list' to return to the list of boroughs or type 'exit' to exit:"
addresses_arr = Address.list_addresses(the_borough)
puts addresses_arr.each_with_index(1) do |address, index|
"#{index}. #{address.name}, #{address.location}"
end
select_address(addresses_arr)
end
def select_address(addresses_arr)
input = nil
while input != "exit"
input = gets.strip.downcase
input = input.to_i
if input > 0
chosen_address = addresses_arr[input-1].name.upcase
puts "Here are the days and hours of operation for #{chosen_address}:"
collection_day(chosen_address)
elsif input == "exit"
go_compost
elsif input == "list"
list_boroughs
else
puts "Invalid Input. Please select the number that corresponds with the compost drop-off address you would like more information on or type 'list' to return to the list of boroughs or type 'exit' to exit:"
end
end
end
def collection_day(chosen_address)
collection_days = CollectionDay.new(chosen_address)
puts collection_days.address_info
end
def go_compost
puts "Now get out there and start composting New York!"
exit
end
end
| true
|
0db8d3c1f1065294feba0a034401ca400c4c537e
|
Ruby
|
Nitemaeric/coding-lessons
|
/ruby/1-programming-fundamentals/oop.rb
|
UTF-8
| 341
| 3.796875
| 4
|
[] |
no_license
|
class Me
attr_accessor :age
attr_writer :name
attr_reader :story
def initialize(name = nil, age, story: nil)
@age = age
@name = name
@story = story
end
def name(addon = '')
"#{@name} is #{story} #{addon}"
end
def do_something(&block)
puts "hi"
block.call(20) if block
puts "someting"
end
end
| true
|
4a17d313d24e22f7c26ce0799eabdffe910b3f08
|
Ruby
|
chrisrobertspdx/flatiron-store-project-v-000
|
/app/models/cart.rb
|
UTF-8
| 930
| 2.6875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
class Cart < ActiveRecord::Base
belongs_to :user
has_many :line_items
has_many :items, through: :line_items
def add_item(item_id)
existing = self.line_items.detect{|l| l.item_id == item_id.to_i}
if !existing
#self.line_items << Line_Item.new({item_id: item_id, cart_id: self.cart_id, quantity: 1})
self.line_items.new({item_id: item_id, quantity: 1})
#self.save
else
existing.quantity += 1
existing.save
#this is awkward
existing
end
end
def total
self.line_items.reduce(0) {|sum,i|
sum + (i.item.price * i.quantity)
}
end
def checkout
self.line_items.each {|e|
e.item.inventory -= e.quantity
e.item.save
}
self.status = "submitted"
self.save
#binding.pry
end
end
| true
|
6f36509fc3a963edb7333c26db43a0692c48a919
|
Ruby
|
coderjonny/myrubyscripts
|
/meta.rb
|
UTF-8
| 3,643
| 3.890625
| 4
|
[] |
no_license
|
class Test
def one
@var = 99
two
end
def two
puts @var
end
end
p t = Test.new
p t.one
class Test
puts "In the definition of class Test"
puts "self = #{self}"
puts "Class of self = #{self.class}"
end
class Test
@var = 99
def self.value_of_var
@var
end
end
puts Test.value_of_var
animal = "cat"
puts animal.upcase.reverse
def animal.speak
puts "Then #{self} says miaow"
end
animal.speak
puts animal.upcase
class Dave
def self.class_method_one
puts "Class method one"
end
def Dave.class_method_one
puts "Class method one overwritten using self!?"
end
def Dave.class_method_two
puts "Class method two"
end
end
Dave.class_method_one
Dave.class_method_two
class Test
@var = 99
def self.var
@var
end
def self.var=(value)
@var = value
end
end
puts "\n\n\noriginal value = #{Test.var}"
Test.var = "cat"
puts "New value = #{Test.var}"
animal = "dog"
class << animal
def speak
puts "The #{self} says woof!"
end
end
animal.speak
animal = "dog"
def animal.speak
puts "the #{self} says woof!"
end
singleton = class << animal
def lie
puts "The #{self} lies down!"
end
self #<<return singleton class object
end
animal.speak
animal.lie
puts "\n\n\nsingleton class object is #{singleton}"
puts "it defines methods #{singleton.instance_methods - 'cat'.methods}"
print <<-okay
Ruby alreadu has attr_accessor, which defines getter and setter methods.
normally, thought, these are defined as instance methods and hence will access
values stored in instances of a class. To make them work with class-level
instance variable, we have to invoke attr_accessor in the singleton class:
okay
class Test
@var = 99
class << self
attr_accessor :var
end
end
puts "Original value = #{Test.var}"
Test.var = "cat"
puts "New value = #{Test.var}"
#Inheritance and Visibility
class Base
def a_method
puts "Got here"
end
private :a_method
end
class Derived1 < Base
public :a_method
end
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#same shit as this
#class Derived1 < Base
# def a_method(*)
# super
# end
# public :a_method
#end
class Derived2 < Base
end
pub = Derived1.new
pub.a_method
pub.a_method
module Logger
def log(msg)
STDERR.puts Time.now.strftime("%H:%M:%S: ") + "#{self} (#{msg})"
end
end
class Song
include Logger
end
class Album
include Logger
end
s = Song.new
s.log("created")
module Mod
def greeting
"Hello"
end
end
class Example
include Mod
end
ex = Example.new
puts "before, change, greeting is #{ex.greeting}"
module Mod
def greeting
"hi"
end
end
puts "after change, greeting is #{ex.greeting}"
puts "\n\nextend method useful when adding the instance methods to
a particular object. you do this using Object#extend."
module Humor
def tickle
"#{self} says hee, hee!"
end
end
obj = "Grouchy"
obj.extend Humor
puts obj.tickle
H = "sleepy"
H.extend Humor
puts H.tickle
#adding a module's methods at the class level:
module Humor
def tickle
"#{self} says hee, hee!"
end
end
class Grouchy
extend Humor
end
puts Grouchy.tickle
#Metaprogramming Class-level Macros
class Example
def self.add_logging
def log(msg)
STDERR.puts Time.now.strftime("%H:%M:%S: ") + "#{self}(#{msg})"
end
end
add_logging
end
ex = Example.new
ex.log("hello")
class Logger
def self.add_logging
def log(msg)
STDERR.puts Time.now.strftime("%H:%M:%S: ") + "#{self} (#{msg})"
end
end
end
class Example < Logger
add_logging
end
ex = Example.new
ex.log("hello")
| true
|
6098e883352425e7ee7a6c395ed153f919d73f5f
|
Ruby
|
AlexanderCleasby/ruby-objects-has-many-lab-online-web-pt-102218
|
/lib/artist.rb
|
UTF-8
| 415
| 3.328125
| 3
|
[
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class Artist
attr_accessor :name, :songs
@@library =[]
def initialize(name)
@name=name
@songs=[]
end
def add_song(song)
song.artist=self
@songs.push(song)
@@library.push(song)
end
def add_song_by_name(songname)
newsong = Song.new(songname)
self.add_song(newsong)
end
def self.song_count
@@library.length
end
end
| true
|
1206f4061c920671861c00f632e58775b2dfd8c3
|
Ruby
|
eljefesun/assignment_ruby_warmup
|
/anagram-testing.rb
|
UTF-8
| 384
| 3.28125
| 3
|
[] |
no_license
|
# # Note: "pears" doesn't appear in the output
# > anagrams("pears")
# # => ["APERS","APRES","ASPER","PARES","PARSE","PRASE","PRESA","RAPES","REAPS","SPARE","SPEAR"]
# > anagrams("zygote")
# #=> []
words = %w[cars scar for four creams scream racs]
anagrams = words.group_by { |word| word.chars.sort }.values
# => [["cars", "scar", "racs"], ["for"], ["four"], ["creams", "scream"]]
| true
|
96015b5ee01cea46a737835e3fc0585d0eb8b6f4
|
Ruby
|
billgloff/data-engineering
|
/data_normalizer/app/services/import_service.rb
|
UTF-8
| 837
| 3.046875
| 3
|
[] |
no_license
|
require 'csv'
class ImportService
attr_accessor :total_amount_gross
def initialize(file)
@file = file
@total_amount_gross = 0.0
end
def parse
CSV.parse(@file, headers: true, col_sep: "\t").each do |row|
customer_name, item_description, item_price = row[0], row[1], row[2].to_f
purchase_count, merchant_address, merchant_name = row[3].to_i, row[4], row[5]
merchant = Merchant.find_or_create_by(name: merchant_name, address: merchant_address)
customer = Customer.find_or_create_by(name: customer_name)
item = Item.find_or_create_by(description: item_description, price: item_price, count: purchase_count, merchant: merchant)
Purchase.find_or_create_by(customer: customer, item: item)
@total_amount_gross += item_price.to_f
end
end
end
| true
|
7ec192cf66f3d7abff5173a3bb9de72e78202f9f
|
Ruby
|
rashmiagar/some_programs
|
/are_anagrams.rb
|
UTF-8
| 626
| 3.734375
| 4
|
[] |
no_license
|
module AreAnagrams
def self.are_anagrams?(string_a, string_b)
if string_a.length != string_b.length
false
elsif
hash_string_a = Hash.new
string_a.downcase.each_char{|chr|
if hash_string_a.has_key?(chr)
hash_string_a[chr] += 1
else
hash_string_a[chr] = 1
end
}
string_b.downcase.each_char{|chr|
if hash_string_a[chr] != nil && hash_string_a[chr] > 0
hash_string_a[chr] -= 1
else
return false
end
}
return true
end
end
end
puts AreAnagrams.are_anagrams?('orchestra', 'carthorse')
| true
|
5b02f0e0bb7ad0d9f1d630e589c7fb2a6025e6ce
|
Ruby
|
LogaJ/CukeSalad
|
/Examples/Calculator/features/lib/alternative/roles/calculating_web_user.rb
|
UTF-8
| 2,002
| 2.96875
| 3
|
[] |
no_license
|
# To run with this version of the Calculating Individual:
# cucumber --profile alternative
require 'web_calculator'
require 'capybara'
require 'capybara/dsl'
Capybara.app = WebCalculator
Capybara.default_driver = :rack_test
module CalculatingIndividual
# Uses a Browser to perform its tasks
include Capybara
# This is not a page object. It is a WebUser, specialised to our application
# See the comments in the 'enter' and 'press' method for an explanation of why
def switch_on_the_calculator
visit '/'
end
def enter value
fill_in 'number', :with => value
# Because the calculator is a simple web_app with only
# one page we can put the id for the field here. In a more complex web-app
# we would pass in the id of the thing to enter
# The task would express the action as: enter( :the_number, "10")
# Because we can change the id used in our application,
# we would just change the id in the application to be 'the_number'.
# If we were on a project where we could not change the id
# in the application we would write an 'ApplicationExpert'
# to map :the_number to the id for the field 'number'. Our CalculatingIndividual
# would ask the ApplicationExpert for the id of the symbol :the_number
# See 'press' below for am explanation of how an ApplicationExpert
# would work
end
def press operator
click_button operator.to_s
# Here, our 'operator' happens to also match the id for the button.
# If we were on a project where we could not choose what the id
# was for buttons, we would write an ApplicationExpert to map
# the symbol used in the task to the symbol for that button.
# The ApplicationExpert would only need to know what page it
# was on to find a mappings class (or yml file) for the fields on that page.
end
def look_at_the_display
find_field('display').value.to_i
end
def is_the_calculator_ready?
page.body.should =~ /Calculator is Ready!/
end
end
| true
|
ca7a91c4a3b8001d0981aa19dbd7eda13b3067ba
|
Ruby
|
jsiny/101_programming_foundations
|
/exercises/12_medium_2/ex_04.rb
|
UTF-8
| 2,134
| 4.34375
| 4
|
[] |
no_license
|
def balanced_1?(string)
has_opening = 0
has_closing = 0
string.chars.each do |char|
has_opening += 1 if char == '('
has_closing += 1 if char == ')'
break if has_closing > has_opening
end
has_opening == has_closing
end
p balanced_1?('What (is) this?') == true
p balanced_1?('What is) this?') == false
p balanced_1?('What (is this?') == false
p balanced_1?('((What) (is this))?') == true
p balanced_1?('((What)) (is this))?') == false
p balanced_1?('Hey!') == true
p balanced_1?(')Hey!(') == false
p balanced_1?('What ((is))) up(') == false
puts '--------'
# Shorter method
def balanced_2?(string)
parentheses = 0
string.each_char do |char|
parentheses += 1 if char == '('
parentheses -= 1 if char == ')'
break if parentheses < 0
end
parentheses.zero?
end
p balanced_2?('What (is) this?') == true
p balanced_2?('What is) this?') == false
p balanced_2?('What (is this?') == false
p balanced_2?('((What) (is this))?') == true
p balanced_2?('((What)) (is this))?') == false
p balanced_2?('Hey!') == true
p balanced_2?(')Hey!(') == false
p balanced_2?('What ((is))) up(') == false
puts '--------'
# Further Exploration
DIFFERENT_PAIRS = [%w(( )), %w([ ]), %w({ })].freeze
QUOTES = ['\'', '\"'].freeze
def extended_balance?(string)
result = []
DIFFERENT_PAIRS.each do |pair|
result << balanced?(string, pair)
end
QUOTES.each do |quote|
result << balanced_with_quote?(string, quote)
end
result.all? { |element| element == true }
end
def balanced?(string, pair)
duo = 0
string.each_char do |char|
duo += 1 if char == pair[0]
duo -= 1 if char == pair[1]
break if duo < 0
end
duo.zero?
end
def balanced_with_quote?(string, quote)
string.chars.count { |char| char == quote }.even?
end
p extended_balance?('hey {') == false
p extended_balance?('hello (madam) I will be {your} guide') == true
p extended_balance?("hello (madam) I'll be {your} guide") == false
p extended_balance?('hello (madam') == false
p extended_balance?('} next {') == false
p extended_balance?("I 'love' you") == true
p extended_balance?('I "would" love to meet ya') == true
| true
|
fee458ef5658aad7d2329dfd5f2ba43b77cfe3b6
|
Ruby
|
heavenchou/cbwork-bin
|
/xml2epub/unicode_service.rb
|
UTF-8
| 453
| 2.875
| 3
|
[] |
no_license
|
require 'Unihan2'
class UnicodeService
def initialize
@u2 = Unihan2.new
end
def level1?(code)
return false if code.nil?
# Unicode 3.0 以內 在 mobile 可以正確顯示
v = @u2.ver(code)
raise CbetaError.new(500), "Unihan2.ver 回傳 nil, code: #{code}" if v.nil?
v <= 3
end
def level2?(code)
return false if code.nil?
# Unicode 10 以內 在 desktop 有字型可以顯示
@u2.ver(code) <= 10
end
end
| true
|
5d3d6bc419bc9554c23f0ffdd6e489b3a770b25b
|
Ruby
|
mpeiros/mediocritter
|
/app/models/user.rb
|
UTF-8
| 947
| 2.625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
class User < ActiveRecord::Base
has_many :comments
has_many :searches
has_many :favorites
has_many :favorited_tweets, through: :favorites, source: :tweet
validates_presence_of :email, :username, :password_hash
validates_uniqueness_of :email, :username
def password
@password ||= BCrypt::Password.new(password_hash)
end
def password=(new_password)
@password = BCrypt::Password.create(new_password)
self.password_hash = @password
end
def self.authenticate(email, password)
if @user = User.find_by(email: email)
@user.password == password ? @user : nil
end
end
def favorited?(tweet)
self.favorited_tweets.each do |fav_tweet|
if fav_tweet.tweet_time == tweet.tweet_time && fav_tweet.text == tweet.text
return true
end
end
false
end
def sort_favorited_tweets
self.favorited_tweets.sort_by { |fav_tweet| fav_tweet.favorited_at(self.id) }.reverse
end
end
| true
|
86bb9490fcff1198db279cd6dc9a8681b761e3ba
|
Ruby
|
evelynnkaplan/matrix_convert_to_zero
|
/lib/matrix_convert_to_zero.rb
|
UTF-8
| 1,550
| 4.09375
| 4
|
[] |
no_license
|
# Updates the input matrix based on the following rules:
# Assumption/ Given: All numbers in the matrix are 0s or 1s
# If any number is found to be 0, the method updates all the numbers in the
# corresponding row as well as the corresponding column to be 0.
# Time complexity: O(n*m) where n is the length of the matrix and m is the length of the longest array within the matrix.
# For both loops, the outer will run n times and the inner will run m times.
# Space complexity: O(n+m) where n is the length of the matrix and m is the length of the longest array within the matrix.
# The maximum number of values in the outer_indexes array will be equal to n and the maximum number of values in the
# inner_indexes array will be equal to m.
def matrix_convert_to_zero(matrix)
outer_indexes = []
inner_indexes = []
matrix.each_with_index do |arr, outer_index|
arr.each_with_index do |num, inner_index|
if num == 0
if !outer_indexes.include?(outer_index)
outer_indexes << outer_index
end
if !inner_indexes.include?(inner_index)
inner_indexes << inner_index
end
end
end
end
matrix.each_with_index do |arr, outer_index|
if outer_indexes.include?(outer_index)
arr.each_with_index do |num, inner_index|
if num == 1
arr[inner_index] = 0
end
end
end
arr.each_with_index do |num, inner_index|
if inner_indexes.include?(inner_index) && num == 1
arr[inner_index] = 0
end
end
end
return matrix
end
| true
|
d7a179bfa72eb98eb17c6415186dbabd9fac9bfa
|
Ruby
|
smernick/square_array-001-prework-web
|
/square_array.rb
|
UTF-8
| 333
| 4.125
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def square_array(array)
new_array = [] #defines a new array
array.each do |number| #tells program to iterate throught the array
new_array << (number**2) #tells program to square each number and add it to the back of the new_array
end
return new_array #returns the value of the new_array at the end of the iteration.
end
| true
|
082002b598742027165abc6e74d82ba343c9976f
|
Ruby
|
jamensky/programming-univbasics-4-building-nested-hashes-online-web-prework
|
/intro_to_ruby_hashes_lab.rb
|
UTF-8
| 1,254
| 2.671875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
def base_hash
hash = {:railroads => {} }
end
def monopoly_with_second_tier
hash = {:railroads => {} }
hash[:railroads][:pieces] = 4
return hash
end
def monopoly_with_third_tier
hash = {:railroads => {} }
hash[:railroads][:pieces] = 4
hash[:railroads][:rent_in_dollars] = {:one_piece_owned => 25, :two_pieces_owned => 50, :three_pieces_owned => 100, :four_pieces_owned => 200}
hash[:railroads][:names] = {:reading_railroad => {}, :pennsylvania_railroad => {}, :b_and_o_railroad => {}, :shortline_railroad => {} }
return hash
end
def monopoly_with_fourth_tier
hash = {:railroads => {} }
hash[:railroads][:pieces] = 4
hash[:railroads][:rent_in_dollars] = {:one_piece_owned => 25, :two_pieces_owned => 50, :three_pieces_owned => 100, :four_pieces_owned => 200}
hash[:railroads][:names] = {:reading_railroad => {}, :pennsylvania_railroad => {}, :b_and_o_railroad => {}, :shortline_railroad => {} }
hash[:railroads][:names][:reading_railroad]["mortgage_value"] = "$100"
hash[:railroads][:names][:pennsylvania_railroad]["mortgage_value"] = "$200"
hash[:railroads][:names][:b_and_o_railroad]["mortgage_value"] = "$400"
hash[:railroads][:names][:shortline_railroad]["mortgage_value"] = "$800"
return hash
end
| true
|
28b7e5e7e1cdd8cca1c0e1ca33523566024e324c
|
Ruby
|
TwiceNo/Patterns
|
/1/projecteuler40.rb
|
UTF-8
| 523
| 3.5625
| 4
|
[] |
no_license
|
def get_digit(n)
curr_block = 0
curr_upper = 0
prev_upper = 0
while curr_upper < n
prev_upper = curr_upper
curr_upper += 9 * 10 ** curr_block
curr_block += 1
end
offset = n - prev_upper - 1
sequence = 1
while sequence * curr_block < offset
sequence += 1
end
fraction = ""
for i in prev_upper + 1..prev_upper + 1 + sequence do
fraction += i.to_s
end
return fraction.split(//)[offset].to_i
end
def product()
res = 1
for i in 0..7 do
res *= get_digit(10 ** i)
end
return res
end
puts product()
| true
|
8928f80734828e3a26073de7d7dc4b0409c1b73e
|
Ruby
|
sgeorgi/pageflow
|
/app/helpers/pageflow/files_helper.rb
|
UTF-8
| 597
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
module Pageflow
module FilesHelper
def file_format(file)
file.format.presence || '-'
end
def file_dimensions(file)
if file.width && file.height
"#{file.width} x #{file.height}px"
else
"-"
end
end
def file_duration(file)
if file.duration_in_ms
total_seconds = file.duration_in_ms / 1000
seconds = total_seconds % 60
minutes = (total_seconds / 60) % 60
hours = total_seconds / (60 * 60)
format("%02d:%02d:%02d", hours, minutes, seconds)
else
"-"
end
end
end
end
| true
|
ac61ab9e1d574456ea1d95bec66e67724e509a85
|
Ruby
|
mixophrygian/Text-Adventure
|
/text_adventure.rb
|
UTF-8
| 8,294
| 4.03125
| 4
|
[] |
no_license
|
#How to play this file! Open the command line, type "irb" then type "load 'text_adventure.rb'" whenever you want to play! The game will quit itself if you win or lose. Load the file again to replay.
class Dungeon
attr_accessor :player
def initialize(player_name)
@player = Player.new(player_name)
@rooms = []
end
def add_room(reference, name, description, connections, eat_description, eatlethal, play_description, playlethal, win)
@rooms << Room.new(reference, name, description, connections, eat_description, eatlethal, play_description, playlethal, win)
end
def start(location)
@player.location = location
show_current_description
puts "\n"
end
def show_current_description
puts find_room_in_dungeon(@player.location).full_description
puts "\nWhat would you like to do next? Select \"Eat\", \"Play\", \"Explore\" or Exit\n"
end
def show_eat_description
puts "\n" + find_room_in_dungeon(@player.location).eat_description
end
def show_play_description
puts "\n" + find_room_in_dungeon(@player.location).play_description
end
def find_room_in_dungeon(reference)
@rooms.detect{ |room| room.reference == reference}
end
def find_room_in_direction(direction)
find_room_in_dungeon(@player.location).connections[direction]
end
def prompt(selection)
unless selection == "eat" || selection =="play" || selection =="explore" || selection == "exit" || @player.dead === true
puts "\nSelect Eat, Play, Explore or Exit\n"
selection = gets.chomp.downcase
end
case selection
when "explore"
puts "\nWhich direction? North, South, East or West.\n"
direction = gets.chomp.downcase
unless direction == "north" || direction == "south" || direction == "east" || direction == "west" || direction == "exit"
puts "\nSelect a valid drection, north south east or west.\n"
direction = gets.chomp.downcase
end
go(direction.to_sym)
when "eat"
show_eat_description
if(find_room_in_dungeon(@player.location).eatlethal)
puts "GAME OVER #{@player.name}"
@player.dead = true
else
puts "\n What would you like to do next? Select \"Eat\", \"Play\", or \"Explore\" or Exit\n"
end
when "play"
show_play_description
if(find_room_in_dungeon(@player.location).playlethal)
puts "GAME OVER #{@player.name}"
@player.dead = true
elsif (find_room_in_dungeon(@player.location).win)
puts "YOU WON, #{@player.name}!"
@player.won = true
else
puts "\n What would you like to do next? Select \"Eat\", \"Play\", or \"Explore\" or Exit\n"
end
when "exit"
puts "Goodbye breakfast-naut"
@player.dead = true
else
puts "Invalid selection. Say again?"
end
end
def go(direction)
if find_room_in_direction(direction) != nil
puts "You go #{direction.to_s} and find yourself in... \n\n"
@player.location = find_room_in_direction(direction)
show_current_description
else
puts "\nYou try to go #{direction} but soon reach a magnetic forcefield and must turn around"
end
end
class Player
attr_accessor :name, :location, :dead, :won
def initialize(name)
@name = name
@dead = false
@won = false
end
end
class Room
attr_accessor :reference, :name, :description, :connections, :eat_description, :eatlethal, :play_description, :playlethal, :win
def initialize(reference, name, description, connections, eat_description, eatlethal, play_description, playlethal, win)
@reference = reference
@name = name
@description = description
@connections = connections
@eat_description = eat_description
@eatlethal = eatlethal
@play_description = play_description
@playlethal = playlethal
@win = win
end
def full_description
@name + "\n\nYou are in " + @description
end
end
end
puts "\nWelcome to
\n==BREAKFAST GALAXY QUEST== \n\n"
puts "Player, what is your name?"
player_name = gets.chomp
new_game = Dungeon.new(player_name)
# initalizing locations
new_game.add_room(:pancakenebula, "THE PANCAKE NEBULA", "a hazy region just north of Orion's griddle contain billions of pancake asteroids of all sizes. They are as fluffy as they are delicious.", {:south => :orionsgriddle, :north => :baconbelt, :east => :celestialcrepes, :west => :browndwarfbagels}, "These pancakes are delicious! The are perfectly browned with a hint of space-spice. Uh oh. You are now addicted to spice.", false, "You try playing with the pancakes a little too violently and a medium-sized cake spins out of control, thwaping you on the helmet causing you to lose consciousness briefly.", false, false)
new_game.add_room(:orionsgriddle, "ORION'S GRIDDLE", "an area in which mysterious magnetism between the angle of nearby stars combined with a fortunate shipwreck of egg cargo has resulted in a seemingly neverending supply of perfectly cooked, zero-gravity formed scrambled eggs.", {:north => :pancakenebula}, "You take a bite and the eggs are magnificent! You didn't know scrambled eggs could be so good!", false, "You attempt to play with the eggs but they form a face on your plate that looks distinctly disapproving. All the other space-diners stop and stare. The space-record-needle swerves off the tracks. You have committed an intergalactic space crime. The burliest chef comes out of the kitchen and the last thing you remember is a frying pan quickly approaching your face plate...", true, false)
new_game.add_room(:baconbelt, "THE BACON BELT", "a vast expanse of bacon strips in ring formation that spans the entire circumfrence of Breakfast-Saturn, the Bacon belt rings vary in crispyness according to their proximity to the celestial body. For well-done, try the outermost ring!.", {:south => :pancakenebula}, "You choose bacon on the crispier side and have fallen into a trance, a bacon-trance. You start imagining moving to the bacon belt, permanently.", false, "You try playing with bacon but run out of ideas, fast. Zero-gravity isn't very conducive to bacon art.", false, false)
new_game.add_room(:celestialcrepes, "CELESTIAL CREPES", "a mysterious location in which crepes are as delicious as they are dangerous. These massive, moon-sized crepes are edible and benign until they reach maturity, at which time they gain sentience and the ability to swallow breakfast-nauts whole, like a venus fly trap would swallow an unassuming gnat. Their jam, accordingly, is dangerous to harvest and commands a great price in the intergalactic cafeteria.", {:west => :pancakenebula}, "You carefully select a crepe with your space fork, but you selected wrong! This medium-size crape expands in size drastically as its delicious-looking jaws open wide to eat YOU for breakfast! Death by crepes.", true, "Instead of attempting to eat these beautiful creatures you tickle one with your fork. It smiles in friendship and the crepes form a space-sofa to carry you as their new space emperor.", false, true)
new_game.add_room(:browndwarfbagels, "BROWN DWARF BAGELS", "a zone formerly occuped by a star that went brown dwarf and thus did not achieve sufficient energy to explode. An enterprising breakfast-naut by the name of Hans saw the opportunity here to open a planet-sized delicatessen, harnessing the area's natural toasty-ness. They are famous for their bagels and brag a 'bagel event horizon' radius of 50 miles!", {:east => :pancakenebula}, "You attempt to eat a brown dwarf bagel...and succeed! Space lox and celestial cream cheese appear out of nowhere to make your space bagel more delicious.", false, "You try playing with your bagel but the bagel takes it too seriously and turns into a bready-black hole, engulfing you, the entire restaurant and the full galaxy, without even chewing. As a result the bagel is slightly bigger, but no one is around to notice.", true, false)
#end intializing locations
puts "\n#{new_game.player.name}, you have just completed your one THOUSANDTH illustrious space mission and
have been awarded one round-trip hyper-space voyage to the ==BREAKFAST GALAXY==. The hyper-space arrival doc is located directly in...\n\n"
new_game.start(:pancakenebula)
selection = gets.chomp.downcase
while(selection != "exit")
new_game.prompt(selection)
if new_game.player.dead || new_game.player.won
break
else
selection = gets.chomp.downcase
end
end
| true
|
de5cf0029aa89b1427a56ff9d7c136c7bf2c11d4
|
Ruby
|
Elazp/Online_week1
|
/Ejercicio2_Fruta_Solución.rb
|
UTF-8
| 1,376
| 3.984375
| 4
|
[] |
no_license
|
require 'pry'
class ShoppingCart
@@prices_list = {
:apple => 10,
:orange => 5,
:grape => 15,
:banana => 20,
:watermelon => 50
}
def initialize
@cart = Hash.new 0
end
def get_item_price item
@@prices_list[item]
end
def add_item_to_cart item
@cart[item] += 1
end
def show
shopping_cart_calculated = calculate_shopping_cart
shopping_cart_calculated.each_with_index do |(key,value),index|
puts "#{index+1}: #{key} => #{@cart[key]} items #{value}€"
end
end
def calculate_shopping_cart
calculated_cart = {}
@cart.each do |key,value|
calculated_cart[key] = get_item_price(key) * value
end
calculated_cart
end
def get_cost
shopping_cart_calculated = calculate_shopping_cart
shopping_cart_calculated.reduce(0) {|sum, (key, val)| sum += val}
#shopping_cart_calculated.values.reduce(:+)
end
end
shopping_cart = ShoppingCart.new
shopping_cart.add_item_to_cart :apple
shopping_cart.add_item_to_cart :apple
shopping_cart.add_item_to_cart :orange
shopping_cart.add_item_to_cart :orange
shopping_cart.add_item_to_cart :orange
shopping_cart.add_item_to_cart :grape
shopping_cart.add_item_to_cart :grape
shopping_cart.add_item_to_cart :grape
shopping_cart.add_item_to_cart :grape
shopping_cart.add_item_to_cart :banana
shopping_cart.show
puts "The cost of your shopping cart is #{shopping_cart.get_cost}€"
| true
|
8ca76452bae77847d1d42080a02ad539496bafe5
|
Ruby
|
pravsingh/Algorithm-Implementations
|
/Insertion_Sort/Ruby/mitogh/insertion_sort.rb
|
UTF-8
| 206
| 3.515625
| 4
|
[
"MIT"
] |
permissive
|
def insertion_sort(arr = [])
arr.each_with_index do |element, i|
j = i
while(j > 0 and (prev = arr[j-1]) > element) do
arr[j] = prev
j -= 1
end
arr[j] = element
end
end
| true
|
86421313bbbda763dd01bf7efb319fc070c71490
|
Ruby
|
romero-c-raul/ruby-basics
|
/strings/pr2.rb
|
UTF-8
| 80
| 2.625
| 3
|
[] |
no_license
|
puts 'It\'s now 12 o\'clock.'
# These are the same
puts "It's now 12 o'clock."
| true
|
86fd793fb46cf29e2bf427d912f0104b45f7d46c
|
Ruby
|
sp0gg/katas_and_exercises
|
/ruby/lib/codility/tape_equilibrium.rb
|
UTF-8
| 453
| 3.265625
| 3
|
[] |
no_license
|
class TapeEquilibrium
def self.solution a
#add all together.
sum = a.reduce :+
puts "sum #{sum}"
left = a[0]
right = sum - left
puts "l #{left} r #{right}"
min_diff = (right-left).abs
puts "mindiff #{min_diff}"
#run p through entire array.
1.upto(a.size-2) do |i|
left += a[i]
right -= a[i]
diff = (right-left).abs
min_diff = diff if min_diff > diff
end
p min_diff
end
end
| true
|
7afb4ceac6dbcc6255d39137928781efb8ef40f4
|
Ruby
|
duong110397/learn-ruby
|
/300-children-exercises/array-exercises/ex6.rb
|
UTF-8
| 172
| 2.75
| 3
|
[] |
no_license
|
=begin
Thay the cac gia tri am co trong mang bang 0
=end
arr = 10.times.map{rand(-10..10)}
negativ = []
arr.each{|a| negativ.push(a < 0 ? 0 : a)}
puts negativ.inspect
| true
|
2378154ff94fdb670a5309a8d97b329053706307
|
Ruby
|
emmabeynon/rps-challenge
|
/spec/game_spec.rb
|
UTF-8
| 3,617
| 2.890625
| 3
|
[] |
no_license
|
require 'game'
describe Game do
subject(:game) { described_class.new(player_1, player_2)}
let(:player_1) { double :player_1, weapon: :rock }
let(:player_2) { double :player_2, weapon: :scissors }
describe 'default' do
it 'accepts two players' do
expect(game.player_1).not_to be_nil
expect(game.player_2).not_to be_nil
end
end
describe '#outcome' do
it 'returns the outcome of the two weapons' do
expect(game.outcome).to eq :win
end
it 'returns Draw when Rock and Rock are played' do
allow(player_1).to receive(:weapon) {:rock}
allow(player_2).to receive(:weapon) {:rock}
expect(game.outcome).to eq :draw
end
it 'returns Lose when Rock and Paper are played' do
allow(player_1).to receive(:weapon) {:rock}
allow(player_2).to receive(:weapon) {:paper}
expect(game.outcome).to eq :lose
end
it 'returns Win when Rock and Scissors are played' do
allow(player_1).to receive(:weapon) {:rock}
allow(player_2).to receive(:weapon) {:scissors}
expect(game.outcome).to eq :win
end
it 'returns Draw when Paper and Paper are played' do
allow(player_1).to receive(:weapon) {:paper}
allow(player_2).to receive(:weapon) {:paper}
expect(game.outcome).to eq :draw
end
it 'returns Win when Paper and Scissors are played' do
allow(player_1).to receive(:weapon) {:paper}
allow(player_2).to receive(:weapon) {:scissors}
expect(game.outcome).to eq :lose
end
it 'returns Draw when Scissors and Scissors are played' do
allow(player_1).to receive(:weapon) {:paper}
allow(player_2).to receive(:weapon) {:paper}
expect(game.outcome).to eq :draw
end
it 'returns Draw when Spock and Spock are played' do
allow(player_1).to receive(:weapon) {:spock}
allow(player_2).to receive(:weapon) {:spock}
expect(game.outcome).to eq :draw
end
it 'returns Win when Spock and Rock are played' do
allow(player_1).to receive(:weapon) {:spock}
allow(player_2).to receive(:weapon) {:rock}
expect(game.outcome).to eq :win
end
it 'returns Lose when Spock and Paper are played' do
allow(player_1).to receive(:weapon) {:spock}
allow(player_2).to receive(:weapon) {:paper}
expect(game.outcome).to eq :lose
end
it 'returns Win when Spock and Scissors are played' do
allow(player_1).to receive(:weapon) {:spock}
allow(player_2).to receive(:weapon) {:scissors}
expect(game.outcome).to eq :win
end
it 'returns Lose when Spock and Lizard are played' do
allow(player_1).to receive(:weapon) {:spock}
allow(player_2).to receive(:weapon) {:lizard}
expect(game.outcome).to eq :lose
end
it 'returns Lose when Lizard and Rock are played' do
allow(player_1).to receive(:weapon) {:lizard}
allow(player_2).to receive(:weapon) {:rock}
expect(game.outcome).to eq :lose
end
it 'returns Win when Lizard and Paper are played' do
allow(player_1).to receive(:weapon) {:lizard}
allow(player_2).to receive(:weapon) {:paper}
expect(game.outcome).to eq :win
end
it 'returns Lose when Lizard and Scissors are played' do
allow(player_1).to receive(:weapon) {:lizard}
allow(player_2).to receive(:weapon) {:scissors}
expect(game.outcome).to eq :lose
end
it 'returns Draw when Lizard and Lizard are played' do
allow(player_1).to receive(:weapon) {:lizard}
allow(player_2).to receive(:weapon) {:lizard}
expect(game.outcome).to eq :draw
end
end
end
| true
|
8d720dd72fa3e5d80b152165b2b6cc963602d1a2
|
Ruby
|
charlesduan/photobook
|
/test/test_layout.rb
|
UTF-8
| 2,066
| 2.671875
| 3
|
[
"MIT"
] |
permissive
|
require 'photobook'
require 'minitest/autorun'
require_relative 'helper'
class TestLayout < Minitest::Unit::TestCase
include TestHelper
def test_new
try_cases(
[ 1, 'h', 1, [ :h ] ],
[ 2, 'hlvpa*', 6, [ :h, :h, :v, :v, :a, :a ] ],
[ 1, 'hhhh', 4, [ :h, :h, :h, :h ] ]
) do |pages, pat, exp_used, exp_pat|
pp = Photobook::Layout.new(
'test layout',
'pages' => pages,
'pattern' => pat,
)
assert_equal('test layout', pp.name)
assert_equal(pages, pp.pages_used)
assert_equal(exp_used, pp.photos_used)
assert_equal(exp_pat, pp.pattern)
end
end
def make_photos(orient)
count = 0
return orient.split('').map { |x|
count += 1
Photobook::Photo.new("Photo #{count}", x.to_sym)
}
end
def test_match_fail
try_cases(
[ 'v', '' ],
[ 'v', 'h' ],
[ 'v', 'vv' ],
[ 'a', '' ],
[ 'a', 'hv' ],
) do |pat, orient|
photos = make_photos(orient)
pp = Photobook::Layout.new('test layout', 'pattern' => pat)
assert_nil(pp.match(photos), 'Match not expected')
end
end
def test_match_success
try_cases(
[ 'h', 'h', '1' ],
[ 'v', 'v', '1' ],
[ 'a', 'h', '1' ],
[ 'a', 'v', '1' ],
[ 'aa', 'hv', '12' ],
[ 'ah', 'hh', '12' ],
[ 'ah', 'hv', '21' ],
[ 'ah', 'vh', '12' ],
[ 'aaav', 'vvhh', '1342' ],
[ 'aaavh', 'vvvhh', '12435' ],
[ 'aaavh', 'vvhhh', '13425' ],
[ 'vhaaa', 'hhhvv', '41235' ],
[ 'vvvhhh', 'hhhvvv', '456123' ]
) do |pat, orient, exp|
photos = make_photos(orient)
pp = Photobook::Layout.new('test layout', 'pattern' => pat)
res = pp.match(photos)
refute_nil(res, "Match expected but not found")
assert_instance_of(Array, res)
assert_equal(exp.length, res.count)
res.zip(exp.split('')).each do |res_photo, exp_photo|
assert_instance_of(Photobook::Photo, res_photo)
assert_equal("Photo #{exp_photo}", res_photo.name)
end
end
end
end
| true
|
64bcb50deadf3c0e8ced8898130504bc02e4657f
|
Ruby
|
jaredonline/Ruby-Prolog-Solutions
|
/spec/01.Lists/03.kth_element_spec.rb
|
UTF-8
| 840
| 3.28125
| 3
|
[] |
no_license
|
require '01.Lists/03.kth_element'
describe LinkedList do
before do
@list = LinkedList.new(1)
@list.next = LinkedList.new(2)
@list.next.next = LinkedList.new(3)
@list.next.next.next = LinkedList.new(4)
end
context 'OO' do
[1, 2, 3, 4].each_with_index do |element, index|
index += 1 # Prolog wants the first element to be 1; Ruby wants it to be 0
it "should return #{element} for the index #{index}" do
@list[index].value.should == element
end
end
end
context 'functional' do
[1, 2, 3, 4].each_with_index do |element, index|
index += 1 # Prolog wants the first element to be 1; Ruby wants it to be 0
it "should return #{element} for the index #{index}" do
functional_kth_element(@list, index).value.should == element
end
end
end
end
| true
|
edd9c752ca9790f83ac9e3ce2ca63760f8b340df
|
Ruby
|
kalkrishnan/PhatStatsServer
|
/lib/news/news_factory.rb
|
UTF-8
| 1,399
| 2.796875
| 3
|
[] |
no_license
|
require 'set'
require 'mechanize'
require 'json'
require 'lib/util/word_count'
require_relative 'news'
class NewsFactory
def initialize()
@news = Set.new
@wordCount = WordCount.new
end
def get_top_news
if(!@news.empty?)
json_news
elsif
build_news_repo
end
end
def build_news_repo url
json_news = JSON.parse(get_rss_feed url)
json_news["entry"].each do |entry|
@news.add(News.new(entry["title"],entry["summary"],entry["creator"],entry["images"]))
end
get_json_news
end
def build_player_news_repo url
json_news = JSON.parse(get_rss_feed url)
json_news["channel"]["item"].first(9).each do |entry|
url = entry["link"].split("url=")[1]
if(url.include? "com")
url = url[0...url.index("com/")+3]
elsif(url.include? "ca")
url = url[0...url.index("ca/")+3]
end
@news.add(News.new(entry["title"],entry["description"]["content"], url, nil))
end
get_json_news
end
def get_json_news
String news = "[{\"topic\":\"news\",\"items\":[";
i = 0;
@news.each{|news_entry|
news = news + news_entry.to_json+ ",";
}
news = news[0..-2] +"]}]"
end
def get_rss_feed(url)
rss = open(url).read
js = XmlSimple.xml_in rss, { 'ForceArray' => false, 'KeyToSymbol' => true}
JSON.pretty_generate(js)
end
end
| true
|
4f379f53b07533075fd868da1e459168b33d6f30
|
Ruby
|
aijoskobi/class_two
|
/hr/hr.rb
|
UTF-8
| 949
| 3.828125
| 4
|
[] |
no_license
|
require 'employee'
require 'salaried_employee'
require 'hourly_employee'
class HumanResources
def initialize()
@employee_list = []
@employee_list << HourlyEmployee.new("George", "Monkey", 10)
@employee_list << HourlyEmployee.new("Sally", "Summers", 12)
@employee_list << HourlyEmployee.new("Thomas", "Tank", 18)
@employee_list << SalariedEmployee.new("Dora", "el Exlorer", 40000)
end
def run_payroll(week, hours)
puts "\nFor week #{week} payroll"
@employee_list.each do |employee|
print_employee_paycheck(employee, hours)
end
end
def print_employee_list
@employee_list.each { |employee| puts employee }
end
private
def print_employee_paycheck(employee, hours)
puts "#{employee.fname} will be paid #{employee.pay(hours)}"
end
end
# hr = HumanResources.new
# hr.employee_list
#
# hr.run_payroll("one", 40)
# hr.run_payroll("two", 32)
# hr.run_payroll("three with overtime", 45)
| true
|
fbd437980082b1a548971cb6d49e01418d7131b3
|
Ruby
|
La-Pulga/Learn-Ruby-the-Hard-way
|
/ex19bis.rb
|
UTF-8
| 418
| 4.28125
| 4
|
[] |
no_license
|
def kiss_away(kiss1, kiss2)
puts " I'd like to give you a kiss #{kiss1}"
puts "Me too! #{kiss2}"
puts "We can't do it both"
puts "Yeah we can!\n"
end
puts "-------How many ways are there to do this?-------"
kiss_away(':*', "xxx")
puts "--------------Using variables-------------"
kiss1 = ":*"
kiss2 = "xxx"
kiss_away(kiss1, kiss2)
puts "--------Doing maths with love-------------"
kiss_away(kiss1 * 3, kiss2)
| true
|
897cff2c8ae89145646f73de400c814f9ae6dead
|
Ruby
|
helenndoo/collections_practice-v-000
|
/collections_practice.rb
|
UTF-8
| 1,173
| 4.40625
| 4
|
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
#1 array of integers and returns a copy of array in ascending order
def sort_array_asc(array)
array.sort do |a, b|
a <=> b
end
end
#2 same, but in descending order
def sort_array_desc(array)
array.sort do |b, a|
a <=> b
end
end
#3 ascending order by length
def sort_array_char_count(array)
array.sort_by do |word|
word.length
end
end
#4 swap 2nd and 3rd elements
def swap_elements(array)
element1 = array[1]
element2 = array[2]
array = [array[0], array[2], array[1]]
end
#5 reverse array
def reverse_array(array)
array.reverse
end
#6 takes array of strings and replaces 3rd character in each
# --- with dollar sign ke$ha style jesus
def kesha_maker(array)
array.each do |string|
string[2] = "$"
end
end
#7 find A using start_with
def find_a(array)
array.select do |word|
word[0] == "a" #= changes, == finds
end
end
#8 adds all intergers together and returns sum
def sum_array(array)
array.inject do |a, b|
a += b #a = a + b
end
end
#9 add s to each word except for 2nd element
def add_s(array)
array.each_with_index.collect do |word, index|
if index == 1
word
else
word << "s"
end
end
end
| true
|
28b7eab9395d29129975907f8c9581c2b373771c
|
Ruby
|
kimdcottrell/sombra
|
/script/arg_guesses/numani_flights/test_flightboard.rb
|
UTF-8
| 664
| 2.984375
| 3
|
[] |
no_license
|
#!/usr/bin/env ruby
require_relative '../../../module/data_dump'
DataDump::FLIGHT_LIST.each do |fl|
abbr = fl[:flight_abbr]
num = fl[:flight_num]
time_raw = fl[:time]
time = time_raw.split(":")
time[0].rjust(2,'0')
time[1].rjust(2,'0')
##XOR num by zerofilled time
print (num[0].to_i ^ time[0].to_i).chr
print (num[1].to_i ^ time[1].to_i).chr
print (num[2].to_i ^ time[2].to_i).chr
print (num[3].to_i ^ time[3].to_i).chr
##XOR abbr by num
# print (abbr[0].hex ^ num[0..1].to_i).chr
# print (abbr[1].hex ^ num[2..3].to_i).chr
##XOR num by abbr
# print (num[0..1].to_i ^ abbr[0].hex).chr
# print (num[2..3].to_i ^ abbr[1].hex).chr
end
| true
|
2fc72f45a48108a34da39f702e7c593e0535c722
|
Ruby
|
atjohnfeng/aa_homework
|
/W3D5/map.rb
|
UTF-8
| 750
| 2.984375
| 3
|
[] |
no_license
|
class Map
def initialize
@map = []
end
def set(key, value)
map.each_with_index do |defin|
if defin[0] == key
defin[1] == value
return true
end
end
map << [key, value]
self
end
def get(key)
map.each_with_index do |defin,i|
if defin[0] == key
return map[i][1]
end
end
end
def delete(key)
map.each_with_index do |defin,i|
if defin[0] == key
map.delete_at(i)
end
end
end
def show
map.dup
end
def inspect
"#Map:#{self.object_id}"
end
private
attr_reader :map
end
| true
|
44778d4ff6e044f898189d54c93498362fa82e11
|
Ruby
|
jasondegraw/AFN2017
|
/scripts/buildAFNtest.rb
|
UTF-8
| 68,222
| 2.65625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
require 'openstudio'
#
#
# +-------------------------------------------------------------+
# | Surface_15 |
# | |
# | |
# | north_space |
# | north_zone |
# | Surface_14 Surface_16 |
# | Floor: Surface_19 |
# | Roof: Surface_20 |
# | |
# | |
# | Surface_17 Surface_18 |
# +------------------------------+------------------------------+
# | Surface_3 | Surface_11 |
# | | |
# | west_space | east_space |
# | west_zone | east_zone |
# | | |
# | Surface_2 Surface_4 | Surface_10 Surface_9 |
# | | |
# | Floor: Surface_5 | Floor: Surface_12 |
# | Roof: Surface_6 | Roof: Surface_13 |
# | | |
# | Surface_1 | Surface_8 |
# +------------------------------+------------------------------+
#
#
#
#
#
#
#
class SurfaceVisitor
attr_reader :summary
def initialize(model)
setup(model)
run(model)
shutdown(model)
end
def setup(model)
end
def run(model)
allsurfs = model.getSurfaces()
@surfs = []
for surf in allsurfs do
if !@surfs.include?(surf) then
other = surf.adjacentSurface()
if !other.empty?() then
if !@surfs.include?(other.get()) then
# This is an interior surface
stype = surf.surfaceType()
@surfs << surf
if stype == 'Floor' then
interiorFloor(model, surf, other.get())
elsif stype == 'RoofCeiling' then
interiorRoofCeiling(model, surf, other.get())
else
interiorWall(model, surf, other.get())
end
end
else
# This is an exterior surface
@surfs << surf
exteriorSurface(model, surf)
end
end
end
end
def interiorFloor(model, surface, adjacentSurface)
end
def interiorWall(model, surface, adjacentSurface)
end
def interiorRoofCeiling(model, surface, adjacentSurface)
end
def exteriorSurface(model, surface)
end
def shutdown(model)
@summary = 'Visited ' + @surfs.size().to_s() + ' surfaces'
end
end
class SurfaceNetworkBuilder < SurfaceVisitor
def initialize(model, interiorCrack, exteriorCrack, scaleByArea=false)
@interiorCrack = interiorCrack
if interiorCrack == nil then
@interiorCrack = OpenStudio::Model::AirflowNetworkCrack.new(model, 1.0) # Need to fix multiplier!
end
@exteriorCrack = exteriorCrack
if interiorCrack == nil then
@exteriorCrack = OpenStudio::Model::AirflowNetworkCrack.new(model, 1.0) # Need to fix multiplier!
end
@scaleByArea = scaleByArea
super(model)
end
def interiorFloor(model, surface, adjacentSurface)
if !surface.outsideBoundaryCondition().start_with?('Ground') then
# Create a surface linkage
link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@interiorCrack)
end
end
def interiorRoofCeiling(model, surface, adjacentSurface)
# Create a surface linkage
link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@interiorCrack)
end
def interiorWall(model, surface, adjacentSurface)
# Create a surface linkage
link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@interiorCrack)
end
def exteriorSurface(model, surface)
# Create an external node
# Create a surface linkage
link = OpenStudio::Model::AirflowNetworkSurface.new(model,surface,@exteriorCrack)
end
end
def addSurfaceCracks(model, intcrack, extcrack, scaledByArea=false)
allsurfs = model.getSurfaces()
surfs = []
for surf in allsurfs do
if !surfs.include?(surf) then
other = surf.adjacentSurface()
if !other.empty?() then
if !surfs.include?(other.get()) then
# This is an interior surface
surfs << surf
end
else
# This is an exterior surface
surfs << surf
end
end
end
puts surfs.size()
#puts extsurfs.size()
end
model = OpenStudio::Model::Model.new()
# Material,A1 - 1 IN STUCCO,Smooth,2.5389841E-02,0.6918309,1858.142,836.8000,0.9000000,0.9200000,0.9200000
stucco = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Smooth", 2.5389841E-02, 0.6918309, 1858.142, 836.8)
stucco.setThermalAbsorptance(0.9)
stucco.setSolarAbsorptance(0.92)
stucco.setVisibleAbsorptance(0.92)
# Material,C4 - 4 IN COMMON BRICK,Rough,0.1014984,0.7264224,1922.216,836.8000,0.9000000,0.7600000,0.7600000
brick = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Rough", 0.1014984, 0.7264224, 1922.216, 836.8)
brick.setThermalAbsorptance(0.9)
brick.setSolarAbsorptance(0.76)
brick.setVisibleAbsorptance(0.76)
# Material,E1 - 3 / 4 IN PLASTER OR GYP BOARD,Smooth,1.905E-02,0.7264224,1601.846,836.8000,0.9000000,0.9200000,0.9200000
wallboard = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Smooth", 1.905E-02, 0.7264224, 1601.846, 836.8)
wallboard.setThermalAbsorptance(0.92)
wallboard.setSolarAbsorptance(0.92)
wallboard.setVisibleAbsorptance(0.9)
# Material,C6 - 8 IN CLAY TILE,Smooth,0.2033016,0.5707605,1121.292,836.8000,0.9000000,0.8200000,0.8200000
tile = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Smooth", 0.2033016, 0.5707605, 1121.292, 836.8)
tile.setThermalAbsorptance(0.82)
tile.setSolarAbsorptance(0.82)
tile.setVisibleAbsorptance(0.9)
# Material,C10 - 8 IN HW CONCRETE,MediumRough,0.2033016,1.729577,2242.585,836.8000,0.9000000,0.6500000,0.6500000
concrete8 = OpenStudio::Model::StandardOpaqueMaterial.new(model, "MediumRough", 0.2033016, 1.729577, 2242.585, 836.8)
concrete8.setThermalAbsorptance(0.65)
concrete8.setSolarAbsorptance(0.65)
concrete8.setVisibleAbsorptance(0.9)
# Material,E2 - 1 / 2 IN SLAG OR STONE,Rough,1.2710161E-02,1.435549,881.0155,1673.600,0.9000000,0.5500000,0.5500000
stone = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Rough", 1.2710161E-02, 1.435549, 881.0155, 1673.6)
stone.setThermalAbsorptance(0.55)
stone.setSolarAbsorptance(0.55)
stone.setVisibleAbsorptance(0.9)
# Material,E3 - 3 / 8 IN FELT AND MEMBRANE,Rough,9.5402403E-03,0.1902535,1121.292,1673.600,0.9000000,0.7500000,0.7500000
membrane = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Rough", 9.5402403E-03, 0.1902535, 1121.292, 1673.6)
membrane.setThermalAbsorptance(0.75)
membrane.setSolarAbsorptance(0.75)
membrane.setVisibleAbsorptance(0.9)
# Material,B5 - 1 IN DENSE INSULATION,VeryRough,2.5389841E-02,4.3239430E-02,91.30524,836.8000,0.9000000,0.5000000,0.5000000
insulation = OpenStudio::Model::StandardOpaqueMaterial.new(model, "VeryRough", 2.5389841E-02, 4.3239430E-02, 91.30524, 836.8)
insulation.setThermalAbsorptance(0.5)
insulation.setSolarAbsorptance(0.5)
insulation.setVisibleAbsorptance(0.9)
# Material,C12 - 2 IN HW CONCRETE,MediumRough,5.0901599E-02,1.729577,2242.585,836.8000,0.9000000,0.6500000,0.6500000
concrete2 = OpenStudio::Model::StandardOpaqueMaterial.new(model, "MediumRough", 5.0901599E-02, 1.729577, 2242.585, 836.8)
concrete2.setThermalAbsorptance(0.65)
concrete2.setSolarAbsorptance(0.65)
concrete2.setVisibleAbsorptance(0.9)
# Material,1.375in-Solid-Core,Smooth,3.4925E-02,0.1525000,614.5000,1630.0000,0.9000000,0.9200000,0.9200000
solidcore = OpenStudio::Model::StandardOpaqueMaterial.new(model, "Smooth", 3.4925E-02, 0.1525, 614.50, 1630.0)
solidcore.setThermalAbsorptance(0.92)
solidcore.setSolarAbsorptance(0.92)
solidcore.setVisibleAbsorptance(0.9)
# WindowMaterial:Glazing,WIN-LAY-GLASS-LIGHT,SpectralAverage,0.0025,0.850,0.075,0.075,0.901,0.081,0.081,0.0,0.84,0.84,0.9
glazing = OpenStudio::Model::StandardGlazing.new(model, "SpectralAverage", 0.0025)
glazing.setSolarTransmittanceatNormalIncidence(0.850)
glazing.setFrontSideSolarReflectanceatNormalIncidence(0.075)
glazing.setBackSideSolarReflectanceatNormalIncidence(0.075)
glazing.setVisibleTransmittanceatNormalIncidence(0.901)
glazing.setFrontSideVisibleReflectanceatNormalIncidence(0.081)
glazing.setBackSideVisibleReflectanceatNormalIncidence(0.08)
glazing.setInfraredTransmittanceatNormalIncidence(0.0)
glazing.setFrontSideInfraredHemisphericalEmissivity(0.84)
glazing.setBackSideInfraredHemisphericalEmissivity(0.84)
glazing.setConductivity(0.9)
materials = OpenStudio::Model::OpaqueMaterialVector.new()
# Construction,DOOR-CON,1.375in-Solid-Core
materials << solidcore
door = OpenStudio::Model::Construction.new(materials)
# Construction,EXTWALL80,A1 - 1 IN STUCCO,C4 - 4 IN COMMON BRICK,E1 - 3 / 4 IN PLASTER OR GYP BOARD
materials.clear()
materials << stucco
materials << brick
materials << wallboard
extwall = OpenStudio::Model::Construction.new(materials)
# Construction,PARTITION06,E1 - 3 / 4 IN PLASTER OR GYP BOARD,C6 - 8 IN CLAY TILE,E1 - 3 / 4 IN PLASTER OR GYP BOARD
materials.clear()
materials << wallboard
materials << tile
materials << wallboard
partition = OpenStudio::Model::Construction.new(materials)
# Construction,FLOOR SLAB 8 IN,C10 - 8 IN HW CONCRETE
materials.clear()
materials << concrete8
floorslab = OpenStudio::Model::Construction.new(materials)
# Construction,ROOF34,E2 - 1 / 2 IN SLAG OR STONE,E3 - 3 / 8 IN FELT AND MEMBRANE,B5 - 1 IN DENSE INSULATION,C12 - 2 IN HW CONCRETE
materials.clear()
materials << stone
materials << membrane
materials << insulation
materials << concrete2
roof = OpenStudio::Model::Construction.new(materials)
# Construction,WIN-CON-LIGHT,WIN-LAY-GLASS-LIGHT
#materials = OpenStudio::Model::StandardGlazingVector.new()
materials = OpenStudio::Model::FenestrationMaterialVector.new()
materials.clear()
materials << glazing
lightwindow = OpenStudio::Model::Construction.new(materials)
points = OpenStudio::Point3dVector.new
# BuildingSurface:Detailed,Surface_1,WALL,EXTWALL80,WEST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,0,0,3.048000,0,0,0,6.096000,0,0,6.096000,0,3.048000
points << OpenStudio::Point3d.new(0, 0, 3.048000)
points << OpenStudio::Point3d.new(0, 0, 0)
points << OpenStudio::Point3d.new(6.096000, 0, 0)
points << OpenStudio::Point3d.new(6.096000, 0, 3.048000)
surface_1 = OpenStudio::Model::Surface.new(points, model)
surface_1.setSurfaceType("WALL")
surface_1.setSunExposure("SunExposed")
surface_1.setWindExposure("WindExposed")
surface_1.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_2,WALL,EXTWALL80,WEST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,0,6.096000,3.048000,0,6.096000,0,0,0,0,0,0,3.048000
points.clear
points << OpenStudio::Point3d.new(0, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(0, 6.096000, 0)
points << OpenStudio::Point3d.new(0, 0, 0)
points << OpenStudio::Point3d.new(0, 0, 3.048000)
surface_2 = OpenStudio::Model::Surface.new(points, model)
surface_2.setSurfaceType("WALL")
surface_2.setSunExposure("SunExposed")
surface_2.setWindExposure("WindExposed")
surface_2.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_3,WALL,PARTITION06,WEST_ZONE,Surface,Surface_17,NoSun,NoWind,0.5000000,4,6.096000,6.096000,3.048000,6.096000,6.096000,0,0,6.096000,0,0,6.096000,3.048000
points.clear
points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 0)
points << OpenStudio::Point3d.new(0, 6.096000, 0)
points << OpenStudio::Point3d.new(0, 6.096000, 3.048000)
surface_3 = OpenStudio::Model::Surface.new(points, model)
surface_3.setSurfaceType("WALL")
surface_3.setSunExposure("NoSun")
surface_3.setWindExposure("NoWind")
surface_3.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_4,WALL,PARTITION06,WEST_ZONE,Surface,Surface_10,NoSun,NoWind,0.5000000,4,6.096000,0,3.048000,6.096000,0,0,6.096000,6.096000,0,6.096000,6.096000,3.048000
points.clear
points << OpenStudio::Point3d.new(6.096000, 0, 3.048000)
points << OpenStudio::Point3d.new(6.096000, 0, 0)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 0)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)
surface_4 = OpenStudio::Model::Surface.new(points, model)
surface_4.setSurfaceType("WALL")
surface_4.setSunExposure("NoSun")
surface_4.setWindExposure("NoWind")
surface_4.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_5,FLOOR,FLOOR SLAB 8 IN,WEST_ZONE,Surface,Surface_5,NoSun,NoWind,1.000000,4,0,0,0,0,6.096000,0,6.096000,6.096000,0,6.096000,0,0
points.clear
points << OpenStudio::Point3d.new(0, 0, 0)
points << OpenStudio::Point3d.new(0, 6.096000, 0)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 0)
points << OpenStudio::Point3d.new(6.096000, 0, 0)
surface_5 = OpenStudio::Model::Surface.new(points, model)
surface_5.setSurfaceType("FLOOR")
surface_5.setSunExposure("NoSun")
surface_5.setWindExposure("NoWind")
surface_5.setViewFactortoGround(1.000000)
# BuildingSurface:Detailed,Surface_6,ROOF,ROOF34,WEST_ZONE,Outdoors,,SunExposed,WindExposed,0,4,0,6.096000,3.048000,0,0,3.048000,6.096000,0,3.048000,6.096000,6.096000,3.048000
points.clear
points << OpenStudio::Point3d.new(0, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(0, 0, 3.048000)
points << OpenStudio::Point3d.new(6.096000, 0, 3.048000)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)
surface_6 = OpenStudio::Model::Surface.new(points, model)
surface_6.setSurfaceType("ROOF")
surface_6.setSunExposure("SunExposed")
surface_6.setWindExposure("WindExposed")
surface_6.setViewFactortoGround(0)
# BuildingSurface:Detailed,Surface_8,WALL,EXTWALL80,EAST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,6.096000,0,3.048000,6.096000,0,0,12.19200,0,0,12.19200,0,3.048000
points.clear
points << OpenStudio::Point3d.new(6.096000, 0, 3.048000)
points << OpenStudio::Point3d.new(6.096000, 0, 0)
points << OpenStudio::Point3d.new(12.19200, 0, 0)
points << OpenStudio::Point3d.new(12.19200, 0, 3.048000)
surface_8 = OpenStudio::Model::Surface.new(points, model)
surface_8.setSurfaceType("WALL")
surface_8.setSunExposure("SunExposed")
surface_8.setWindExposure("WindExposed")
surface_8.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_9,WALL,EXTWALL80,EAST_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,12.19200,0,3.048000,12.19200,0,0,12.19200,6.096000,0,12.19200,6.096000,3.048000
points.clear
points << OpenStudio::Point3d.new(12.19200, 0, 3.048000)
points << OpenStudio::Point3d.new(12.19200, 0, 0)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 0)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)
surface_9 = OpenStudio::Model::Surface.new(points, model)
surface_9.setSurfaceType("WALL")
surface_9.setSunExposure("SunExposed")
surface_9.setWindExposure("WindExposed")
surface_9.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_10,WALL,PARTITION06,EAST_ZONE,Surface,Surface_4,NoSun,NoWind,0.5000000,4,6.096000,6.096000,3.048000,6.096000,6.096000,0,6.096000,0,0,6.096001,0,3.048000
points.clear
points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 0)
points << OpenStudio::Point3d.new(6.096000, 0, 0)
points << OpenStudio::Point3d.new(6.096001, 0, 3.048000)
surface_10 = OpenStudio::Model::Surface.new(points, model)
surface_10.setSurfaceType("WALL")
surface_10.setSunExposure("NoSun")
surface_10.setWindExposure("NoWind")
surface_10.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_11,WALL,PARTITION06,EAST_ZONE,Surface,Surface_18,NoSun,NoWind,0.5000000,4,12.19200,6.096000,3.048000,12.19200,6.096000,0,6.096000,6.096000,0,6.096000,6.096000,3.048000
points.clear
points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 0)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 0)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)
surface_11 = OpenStudio::Model::Surface.new(points, model)
surface_11.setSurfaceType("WALL")
surface_11.setSunExposure("NoSun")
surface_11.setWindExposure("NoWind")
surface_11.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_12,FLOOR,FLOOR SLAB 8 IN,EAST_ZONE,Surface,Surface_12,NoSun,NoWind,1.000000,4,6.096000,0,0,6.096000,6.096000,0,12.19200,6.096000,0,12.19200,0,0
points.clear
points << OpenStudio::Point3d.new(6.096000, 0, 0)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 0)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 0)
points << OpenStudio::Point3d.new(12.19200, 0, 0)
surface_12 = OpenStudio::Model::Surface.new(points, model)
surface_12.setSurfaceType("FLOOR")
surface_12.setSunExposure("NoSun")
surface_12.setWindExposure("NoWind")
surface_12.setViewFactortoGround(1.000000)
# BuildingSurface:Detailed,Surface_13,ROOF,ROOF34,EAST_ZONE,Outdoors,,SunExposed,WindExposed,0,4,6.096000,6.096000,3.048000,6.096000,0,3.048000,12.19200,0,3.048000,12.19200,6.096000,3.048000
points.clear
points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(6.096000, 0, 3.048000)
points << OpenStudio::Point3d.new(12.19200, 0, 3.048000)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)
surface_13 = OpenStudio::Model::Surface.new(points, model)
surface_13.setSurfaceType("ROOF")
surface_13.setSunExposure("SunExposed")
surface_13.setWindExposure("WindExposed")
surface_13.setViewFactortoGround(0)
# BuildingSurface:Detailed,Surface_14,WALL,EXTWALL80,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,0,12.19200,3.048000,0,12.19200,0,0,6.096000,0,0,6.096000,3.048000
points.clear
points << OpenStudio::Point3d.new(0, 12.19200, 3.048000)
points << OpenStudio::Point3d.new(0, 12.19200, 0)
points << OpenStudio::Point3d.new(0, 6.096000, 0)
points << OpenStudio::Point3d.new(0, 6.096000, 3.048000)
surface_14 = OpenStudio::Model::Surface.new(points, model)
surface_14.setSurfaceType("WALL")
surface_14.setSunExposure("SunExposed")
surface_14.setWindExposure("WindExposed")
surface_14.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_15,WALL,EXTWALL80,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,12.19200,12.19200,3.048000,12.19200,12.19200,0,0,12.19200,0,0,12.19200,3.048000
points.clear
points << OpenStudio::Point3d.new(12.19200, 12.19200, 3.048000)
points << OpenStudio::Point3d.new(12.19200, 12.19200, 0)
points << OpenStudio::Point3d.new(0, 12.19200, 0)
points << OpenStudio::Point3d.new(0, 12.19200, 3.048000)
surface_15 = OpenStudio::Model::Surface.new(points, model)
surface_15.setSurfaceType("WALL")
surface_15.setSunExposure("SunExposed")
surface_15.setWindExposure("WindExposed")
surface_15.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_16,WALL,EXTWALL80,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0.5000000,4,12.19200,6.096000,3.048000,12.19200,6.096000,0,12.19200,12.19200,0,12.19200,12.19200,3.048000
points.clear
points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 0)
points << OpenStudio::Point3d.new(12.19200, 12.19200, 0)
points << OpenStudio::Point3d.new(12.19200, 12.19200, 3.048000)
surface_16 = OpenStudio::Model::Surface.new(points, model)
surface_16.setSurfaceType("WALL")
surface_16.setSunExposure("SunExposed")
surface_16.setWindExposure("WindExposed")
surface_16.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_17,WALL,PARTITION06,NORTH_ZONE,Surface,Surface_3,NoSun,NoWind,0.5000000,4,0.000,6.096,3.048,0.000,6.096,0.000,6.096,6.096,0.000,6.096,6.096,3.048
points.clear
points << OpenStudio::Point3d.new(0.000, 6.096, 3.048)
points << OpenStudio::Point3d.new(0.000, 6.096, 0.000)
points << OpenStudio::Point3d.new(6.096, 6.096, 0.000)
points << OpenStudio::Point3d.new(6.096, 6.096, 3.048)
surface_17 = OpenStudio::Model::Surface.new(points, model)
surface_17.setSurfaceType("WALL")
surface_17.setSunExposure("NoSun")
surface_17.setWindExposure("NoWind")
surface_17.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_18,WALL,PARTITION06,NORTH_ZONE,Surface,Surface_11,NoSun,NoWind,0.5000000,4,6.096000,6.096000,3.048000,6.096000,6.096000,0,12.19200,6.096000,0,12.19200,6.096000,3.048000
points.clear
points << OpenStudio::Point3d.new(6.096000, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(6.096000, 6.096000, 0)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 0)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)
surface_18 = OpenStudio::Model::Surface.new(points, model)
surface_18.setSurfaceType("WALL")
surface_18.setSunExposure("NoSun")
surface_18.setWindExposure("NoWind")
surface_18.setViewFactortoGround(0.5000000)
# BuildingSurface:Detailed,Surface_19,FLOOR,FLOOR SLAB 8 IN,NORTH_ZONE,Surface,Surface_19,NoSun,NoWind,1.000000,4,0,6.096000,0,0,12.19200,0,12.19200,12.19200,0,12.19200,6.096000,0
points.clear
points << OpenStudio::Point3d.new(0, 6.096000, 0)
points << OpenStudio::Point3d.new(0, 12.19200, 0)
points << OpenStudio::Point3d.new(12.19200, 12.19200, 0)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 0)
surface_19 = OpenStudio::Model::Surface.new(points, model)
surface_19.setSurfaceType("FLOOR")
surface_19.setSunExposure("NoSun")
surface_19.setWindExposure("NoWind")
surface_19.setViewFactortoGround(1.000000)
# BuildingSurface:Detailed,Surface_20,ROOF,ROOF34,NORTH_ZONE,Outdoors,,SunExposed,WindExposed,0,4,0,12.19200,3.048000,0,6.096000,3.048000,12.19200,6.096000,3.048000,12.19200,12.19200,3.048000
points.clear
points << OpenStudio::Point3d.new(0, 12.19200, 3.048000)
points << OpenStudio::Point3d.new(0, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(12.19200, 6.096000, 3.048000)
points << OpenStudio::Point3d.new(12.19200, 12.19200, 3.048000)
surface_20 = OpenStudio::Model::Surface.new(points, model)
surface_20.setSurfaceType("ROOF")
surface_20.setSunExposure("SunExposed")
surface_20.setWindExposure("WindExposed")
surface_20.setViewFactortoGround(0)
# Set the constructions
surface_1.setConstruction(extwall)
surface_2.setConstruction(extwall)
surface_3.setConstruction(partition)
surface_4.setConstruction(partition)
surface_5.setConstruction(floorslab)
surface_6.setConstruction(roof)
#surface_7.setConstruction(extwall)
surface_8.setConstruction(extwall)
surface_9.setConstruction(extwall)
surface_10.setConstruction(partition)
surface_11.setConstruction(partition)
surface_12.setConstruction(floorslab)
surface_13.setConstruction(roof)
surface_14.setConstruction(extwall)
surface_15.setConstruction(extwall)
surface_16.setConstruction(extwall)
surface_17.setConstruction(partition)
surface_18.setConstruction(partition)
surface_19.setConstruction(floorslab)
surface_20.setConstruction(roof)
# Connect the surfaces together
surface_3.setAdjacentSurface(surface_17)
surface_4.setAdjacentSurface(surface_10)
surface_11.setAdjacentSurface(surface_18)
# Make spaces and thermal zones
west_space = OpenStudio::Model::Space.new(model)
west_zone = OpenStudio::Model::ThermalZone.new(model)
east_space = OpenStudio::Model::Space.new(model)
east_zone = OpenStudio::Model::ThermalZone.new(model)
north_space = OpenStudio::Model::Space.new(model)
north_zone = OpenStudio::Model::ThermalZone.new(model)
# Connect spaces and surfaces
surface_1.setSpace(west_space)
surface_2.setSpace(west_space)
surface_3.setSpace(west_space)
surface_4.setSpace(west_space)
surface_5.setSpace(west_space)
surface_6.setSpace(west_space)
surface_8.setSpace(east_space)
surface_9.setSpace(east_space)
surface_10.setSpace(east_space)
surface_11.setSpace(east_space)
surface_12.setSpace(east_space)
surface_13.setSpace(east_space)
surface_14.setSpace(north_space)
surface_15.setSpace(north_space)
surface_16.setSpace(north_space)
surface_17.setSpace(north_space)
surface_18.setSpace(north_space)
surface_19.setSpace(north_space)
surface_20.setSpace(north_space)
# Connect spaces and zones
west_space.setThermalZone(west_zone)
east_space.setThermalZone(east_zone)
north_space.setThermalZone(north_zone)
puts surface_3.to_s
puts surface_17.to_s
puts surface_3.isNumberofVerticesAutocalculated
addSurfaceCracks(model, nil, nil)
visitor = SurfaceNetworkBuilder.new(model, nil, nil)
puts visitor.summary
puts
zones = model.getAirflowNetworkZones()
puts 'Created ' + zones.size().to_s() + ' AFN zones'
extnodes = model.getAirflowNetworkExternalNodes()
puts 'Created ' + extnodes.size().to_s() + ' AFN external nodes'
surfs = model.getAirflowNetworkSurfaces()
puts 'Created ' + surfs.size().to_s() + ' AFN surfaces'
cracks = model.getAirflowNetworkCracks()
puts 'Created ' + cracks.size().to_s() + ' AFN cracks'
junk = <<-MLS
GlobalGeometryRules,UpperLeftCorner,CounterClockWise,World
FenestrationSurface:Detailed,WINDOW11,WINDOW,WIN-CON-LIGHT,Surface_1,0.5000000,1.0,3,1.00000,0,2.500000,1.00000,0,1.0000000,5.000000,0,1.0000000
FenestrationSurface:Detailed,WINDOW12,WINDOW,WIN-CON-LIGHT,Surface_1,0.5000000,1.0,3,5.00000,0,1.0000000,5.000000,0,2.5000000,1.000000,0,2.500000
FenestrationSurface:Detailed,DoorInSurface_3,DOOR,DOOR-CON,Surface_3,DoorInSurface_17,0.5000000,1.0,4,3.500,6.096000,2.0,3.500,6.096000,0.0,2.500,6.096000,0.0,2.500,6.096000,2.0
FenestrationSurface:Detailed,WINDOW2,WINDOW,WIN-CON-LIGHT,Surface_15,0.5000000,1.0,4,6.000000,12.19200,2.333000,6.000000,12.19200,1.000000,3.000000,12.19200,1.000000,3.000000,12.19200,2.333000
FenestrationSurface:Detailed,DoorInSurface_17,DOOR,DOOR-CON,Surface_17,DoorInSurface_3,0.5000000,1.0,4,2.500,6.096000,2.0,2.500,6.096000,0.0,3.500,6.096000,0.0,3.500,6.096000,2.0
AirflowNetwork:SimulationControl,NaturalVentilation,MultizoneWithoutDistribution,INPUT,ExternalNode,LOWRISE,500,ZeroNodePressures,1.0E-05,1.0E-06,-0.5,0.0,1.0
AirflowNetwork:MultiZone:Zone,WEST_ZONE,NoVent,Temperature,WindowVentSched,0.3,5.0,10.0,0.0,300000.0
AirflowNetwork:MultiZone:Zone,EAST_ZONE,NoVent,1.0,0.0,100.0,0.0,300000.0
AirflowNetwork:MultiZone:Zone,NORTH_ZONE,NoVent,Temperature,WindowVentSched,1.0,0.0,100.0,0.0,300000.0
AirflowNetwork:MultiZone:Surface,Surface_1,CR-1,SFacade,1.0
AirflowNetwork:MultiZone:Surface,Surface_4,CR-1,1.0
AirflowNetwork:MultiZone:Surface,Surface_11,CR-1,1.0
AirflowNetwork:MultiZone:Surface,Surface_15,CR-1,NFacade,1.0
AirflowNetwork:MultiZone:ExternalNode,NFacade,1.524,NFacade_WPCValue
AirflowNetwork:MultiZone:ExternalNode,SFacade,1.524,SFacade_WPCValue,No,Absolute
AirflowNetwork:MultiZone:ReferenceCrackConditions,ReferenceCrackConditions,20.0,101320,0.005
AirflowNetwork:MultiZone:Surface:Crack,CR-1,0.01,0.667,ReferenceCrackConditions
AirflowNetwork:MultiZone:WindPressureCoefficientArray,Every 30 Degrees,0,30,60,90,120,150,180,210,240,270,300,330
AirflowNetwork:MultiZone:WindPressureCoefficientValues,NFacade_WPCValue,Every 30 Degrees,0.60,0.48,0.04,-0.56,-0.56,-0.42,-0.37,-0.42,-0.56,-0.56,0.04,0.48
AirflowNetwork:MultiZone:WindPressureCoefficientValues,SFacade_WPCValue,Every 30 Degrees,-0.37,-0.42,-0.56,-0.56,0.04,0.48,0.60,0.48,0.04,-0.56,-0.56,-0.42
SurfaceConvectionAlgorithm:Inside,TARP
SurfaceConvectionAlgorithm:Outside,DOE-2
HeatBalanceAlgorithm,ConductionTransferFunction
ZoneAirHeatBalanceAlgorithm,AnalyticalSolution
TEST_F(EnergyPlusFixture, TestExternalNodes) {
std::string const idf_objects = delimited_string({
"Version,8.6;",
"Material,",
" A1 - 1 IN STUCCO, !- Name",
" Smooth, !- Roughness",
" 2.5389841E-02, !- Thickness {m}",
" 0.6918309, !- Conductivity {W/m-K}",
" 1858.142, !- Density {kg/m3}",
" 836.8000, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.9200000, !- Solar Absorptance",
" 0.9200000; !- Visible Absorptance",
"Material,",
" C4 - 4 IN COMMON BRICK, !- Name",
" Rough, !- Roughness",
" 0.1014984, !- Thickness {m}",
" 0.7264224, !- Conductivity {W/m-K}",
" 1922.216, !- Density {kg/m3}",
" 836.8000, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.7600000, !- Solar Absorptance",
" 0.7600000; !- Visible Absorptance",
"Material,",
" E1 - 3 / 4 IN PLASTER OR GYP BOARD, !- Name",
" Smooth, !- Roughness",
" 1.905E-02, !- Thickness {m}",
" 0.7264224, !- Conductivity {W/m-K}",
" 1601.846, !- Density {kg/m3}",
" 836.8000, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.9200000, !- Solar Absorptance",
" 0.9200000; !- Visible Absorptance",
"Material,",
" C6 - 8 IN CLAY TILE, !- Name",
" Smooth, !- Roughness",
" 0.2033016, !- Thickness {m}",
" 0.5707605, !- Conductivity {W/m-K}",
" 1121.292, !- Density {kg/m3}",
" 836.8000, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.8200000, !- Solar Absorptance",
" 0.8200000; !- Visible Absorptance",
"Material,",
" C10 - 8 IN HW CONCRETE, !- Name",
" MediumRough, !- Roughness",
" 0.2033016, !- Thickness {m}",
" 1.729577, !- Conductivity {W/m-K}",
" 2242.585, !- Density {kg/m3}",
" 836.8000, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.6500000, !- Solar Absorptance",
" 0.6500000; !- Visible Absorptance",
"Material,",
" E2 - 1 / 2 IN SLAG OR STONE, !- Name",
" Rough, !- Roughness",
" 1.2710161E-02, !- Thickness {m}",
" 1.435549, !- Conductivity {W/m-K}",
" 881.0155, !- Density {kg/m3}",
" 1673.600, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.5500000, !- Solar Absorptance",
" 0.5500000; !- Visible Absorptance",
"Material,",
" E3 - 3 / 8 IN FELT AND MEMBRANE, !- Name",
" Rough, !- Roughness",
" 9.5402403E-03, !- Thickness {m}",
" 0.1902535, !- Conductivity {W/m-K}",
" 1121.292, !- Density {kg/m3}",
" 1673.600, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.7500000, !- Solar Absorptance",
" 0.7500000; !- Visible Absorptance",
"Material,",
" B5 - 1 IN DENSE INSULATION, !- Name",
" VeryRough, !- Roughness",
" 2.5389841E-02, !- Thickness {m}",
" 4.3239430E-02, !- Conductivity {W/m-K}",
" 91.30524, !- Density {kg/m3}",
" 836.8000, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.5000000, !- Solar Absorptance",
" 0.5000000; !- Visible Absorptance",
"Material,",
" C12 - 2 IN HW CONCRETE, !- Name",
" MediumRough, !- Roughness",
" 5.0901599E-02, !- Thickness {m}",
" 1.729577, !- Conductivity {W/m-K}",
" 2242.585, !- Density {kg/m3}",
" 836.8000, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.6500000, !- Solar Absorptance",
" 0.6500000; !- Visible Absorptance",
"Material,",
" 1.375in-Solid-Core, !- Name",
" Smooth, !- Roughness",
" 3.4925E-02, !- Thickness {m}",
" 0.1525000, !- Conductivity {W/m-K}",
" 614.5000, !- Density {kg/m3}",
" 1630.0000, !- Specific Heat {J/kg-K}",
" 0.9000000, !- Thermal Absorptance",
" 0.9200000, !- Solar Absorptance",
" 0.9200000; !- Visible Absorptance",
"WindowMaterial:Glazing,",
" WIN-LAY-GLASS-LIGHT, !- Name",
" SpectralAverage, !- Optical Data Type",
" , !- Window Glass Spectral Data Set Name",
" 0.0025, !- Thickness {m}",
" 0.850, !- Solar Transmittance at Normal Incidence",
" 0.075, !- Front Side Solar Reflectance at Normal Incidence",
" 0.075, !- Back Side Solar Reflectance at Normal Incidence",
" 0.901, !- Visible Transmittance at Normal Incidence",
" 0.081, !- Front Side Visible Reflectance at Normal Incidence",
" 0.081, !- Back Side Visible Reflectance at Normal Incidence",
" 0.0, !- Infrared Transmittance at Normal Incidence",
" 0.84, !- Front Side Infrared Hemispherical Emissivity",
" 0.84, !- Back Side Infrared Hemispherical Emissivity",
" 0.9; !- Conductivity {W/m-K}",
"Construction,",
" DOOR-CON, !- Name",
" 1.375in-Solid-Core; !- Outside Layer",
"Construction,",
" EXTWALL80, !- Name",
" A1 - 1 IN STUCCO, !- Outside Layer",
" C4 - 4 IN COMMON BRICK, !- Layer 2",
" E1 - 3 / 4 IN PLASTER OR GYP BOARD; !- Layer 3",
"Construction,",
" PARTITION06, !- Name",
" E1 - 3 / 4 IN PLASTER OR GYP BOARD, !- Outside Layer",
" C6 - 8 IN CLAY TILE, !- Layer 2",
" E1 - 3 / 4 IN PLASTER OR GYP BOARD; !- Layer 3",
" Construction,",
" FLOOR SLAB 8 IN, !- Name",
" C10 - 8 IN HW CONCRETE; !- Outside Layer",
"Construction,",
" ROOF34, !- Name",
" E2 - 1 / 2 IN SLAG OR STONE, !- Outside Layer",
" E3 - 3 / 8 IN FELT AND MEMBRANE, !- Layer 2",
" B5 - 1 IN DENSE INSULATION, !- Layer 3",
" C12 - 2 IN HW CONCRETE; !- Layer 4",
"Construction,",
" WIN-CON-LIGHT, !- Name",
" WIN-LAY-GLASS-LIGHT; !- Outside Layer",
"Zone,",
" WEST_ZONE, !- Name",
" 0, !- Direction of Relative North {deg}",
" 0, !- X Origin {m}",
" 0, !- Y Origin {m}",
" 0, !- Z Origin {m}",
" 1, !- Type",
" 1, !- Multiplier",
" autocalculate; !- Ceiling Height {m}",
"Zone,",
" EAST_ZONE, !- Name",
" 0, !- Direction of Relative North {deg}",
" 0, !- X Origin {m}",
" 0, !- Y Origin {m}",
" 0, !- Z Origin {m}",
" 1, !- Type",
" 1, !- Multiplier",
" autocalculate; !- Ceiling Height {m}",
"Zone,",
" NORTH_ZONE, !- Name",
" 0, !- Direction of Relative North {deg}",
" 0, !- X Origin {m}",
" 0, !- Y Origin {m}",
" 0, !- Z Origin {m}",
" 1, !- Type",
" 1, !- Multiplier",
" autocalculate; !- Ceiling Height {m}",
"GlobalGeometryRules,",
" UpperLeftCorner, !- Starting Vertex Position",
" CounterClockWise, !- Vertex Entry Direction",
" World; !- Coordinate System",
"BuildingSurface:Detailed,",
" Surface_1, !- Name",
" WALL, !- Surface Type",
" EXTWALL80, !- Construction Name",
" WEST_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 0,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 0,0,0, !- X,Y,Z ==> Vertex 2 {m}",
" 6.096000,0,0, !- X,Y,Z ==> Vertex 3 {m}",
" 6.096000,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_2, !- Name",
" WALL, !- Surface Type",
" EXTWALL80, !- Construction Name",
" WEST_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 0,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 0,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}",
" 0,0,0, !- X,Y,Z ==> Vertex 3 {m}",
" 0,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_3, !- Name",
" WALL, !- Surface Type",
" PARTITION06, !- Construction Name",
" WEST_ZONE, !- Zone Name",
" Surface, !- Outside Boundary Condition",
" Surface_17, !- Outside Boundary Condition Object",
" NoSun, !- Sun Exposure",
" NoWind, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}",
" 0,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}",
" 0,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_4, !- Name",
" WALL, !- Surface Type",
" PARTITION06, !- Construction Name",
" WEST_ZONE, !- Zone Name",
" Surface, !- Outside Boundary Condition",
" Surface_10, !- Outside Boundary Condition Object",
" NoSun, !- Sun Exposure",
" NoWind, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 6.096000,0,0, !- X,Y,Z ==> Vertex 2 {m}",
" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}",
" 6.096000,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_5, !- Name",
" FLOOR, !- Surface Type",
" FLOOR SLAB 8 IN, !- Construction Name",
" WEST_ZONE, !- Zone Name",
" Surface, !- Outside Boundary Condition",
" Surface_5, !- Outside Boundary Condition Object",
" NoSun, !- Sun Exposure",
" NoWind, !- Wind Exposure",
" 1.000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 0,0,0, !- X,Y,Z ==> Vertex 1 {m}",
" 0,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}",
" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}",
" 6.096000,0,0; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_6, !- Name",
" ROOF, !- Surface Type",
" ROOF34, !- Construction Name",
" WEST_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 0,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 0,0,3.048000, !- X,Y,Z ==> Vertex 2 {m}",
" 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 3 {m}",
" 6.096000,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_8, !- Name",
" WALL, !- Surface Type",
" EXTWALL80, !- Construction Name",
" EAST_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 6.096000,0,0, !- X,Y,Z ==> Vertex 2 {m}",
" 12.19200,0,0, !- X,Y,Z ==> Vertex 3 {m}",
" 12.19200,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_9, !- Name",
" WALL, !- Surface Type",
" EXTWALL80, !- Construction Name",
" EAST_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 12.19200,0,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 12.19200,0,0, !- X,Y,Z ==> Vertex 2 {m}",
" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}",
" 12.19200,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_10, !- Name",
" WALL, !- Surface Type",
" PARTITION06, !- Construction Name",
" EAST_ZONE, !- Zone Name",
" Surface, !- Outside Boundary Condition",
" Surface_4, !- Outside Boundary Condition Object",
" NoSun, !- Sun Exposure",
" NoWind, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}",
" 6.096000,0,0, !- X,Y,Z ==> Vertex 3 {m}",
" 6.096001,0,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_11, !- Name",
" WALL, !- Surface Type",
" PARTITION06, !- Construction Name",
" EAST_ZONE, !- Zone Name",
" Surface, !- Outside Boundary Condition",
" Surface_18, !- Outside Boundary Condition Object",
" NoSun, !- Sun Exposure",
" NoWind, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 12.19200,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}",
" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}",
" 6.096000,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_12, !- Name",
" FLOOR, !- Surface Type",
" FLOOR SLAB 8 IN, !- Construction Name",
" EAST_ZONE, !- Zone Name",
" Surface, !- Outside Boundary Condition",
" Surface_12, !- Outside Boundary Condition Object",
" NoSun, !- Sun Exposure",
" NoWind, !- Wind Exposure",
" 1.000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 6.096000,0,0, !- X,Y,Z ==> Vertex 1 {m}",
" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}",
" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}",
" 12.19200,0,0; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_13, !- Name",
" ROOF, !- Surface Type",
" ROOF34, !- Construction Name",
" EAST_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 6.096000,0,3.048000, !- X,Y,Z ==> Vertex 2 {m}",
" 12.19200,0,3.048000, !- X,Y,Z ==> Vertex 3 {m}",
" 12.19200,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_14, !- Name",
" WALL, !- Surface Type",
" EXTWALL80, !- Construction Name",
" NORTH_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 0,12.19200,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 0,12.19200,0, !- X,Y,Z ==> Vertex 2 {m}",
" 0,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}",
" 0,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_15, !- Name",
" WALL, !- Surface Type",
" EXTWALL80, !- Construction Name",
" NORTH_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 12.19200,12.19200,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 12.19200,12.19200,0, !- X,Y,Z ==> Vertex 2 {m}",
" 0,12.19200,0, !- X,Y,Z ==> Vertex 3 {m}",
" 0,12.19200,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_16, !- Name",
" WALL, !- Surface Type",
" EXTWALL80, !- Construction Name",
" NORTH_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 12.19200,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}",
" 12.19200,12.19200,0, !- X,Y,Z ==> Vertex 3 {m}",
" 12.19200,12.19200,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_17, !- Name",
" WALL, !- Surface Type",
" PARTITION06, !- Construction Name",
" NORTH_ZONE, !- Zone Name",
" Surface, !- Outside Boundary Condition",
" Surface_3, !- Outside Boundary Condition Object",
" NoSun, !- Sun Exposure",
" NoWind, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 0.000,6.096,3.048, !- X,Y,Z ==> Vertex 1 {m}",
" 0.000,6.096,0.000, !- X,Y,Z ==> Vertex 2 {m}",
" 6.096,6.096,0.000, !- X,Y,Z ==> Vertex 3 {m}",
" 6.096,6.096,3.048; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_18, !- Name",
" WALL, !- Surface Type",
" PARTITION06, !- Construction Name",
" NORTH_ZONE, !- Zone Name",
" Surface, !- Outside Boundary Condition",
" Surface_11, !- Outside Boundary Condition Object",
" NoSun, !- Sun Exposure",
" NoWind, !- Wind Exposure",
" 0.5000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 6.096000,6.096000,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 6.096000,6.096000,0, !- X,Y,Z ==> Vertex 2 {m}",
" 12.19200,6.096000,0, !- X,Y,Z ==> Vertex 3 {m}",
" 12.19200,6.096000,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_19, !- Name",
" FLOOR, !- Surface Type",
" FLOOR SLAB 8 IN, !- Construction Name",
" NORTH_ZONE, !- Zone Name",
" Surface, !- Outside Boundary Condition",
" Surface_19, !- Outside Boundary Condition Object",
" NoSun, !- Sun Exposure",
" NoWind, !- Wind Exposure",
" 1.000000, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 0,6.096000,0, !- X,Y,Z ==> Vertex 1 {m}",
" 0,12.19200,0, !- X,Y,Z ==> Vertex 2 {m}",
" 12.19200,12.19200,0, !- X,Y,Z ==> Vertex 3 {m}",
" 12.19200,6.096000,0; !- X,Y,Z ==> Vertex 4 {m}",
"BuildingSurface:Detailed,",
" Surface_20, !- Name",
" ROOF, !- Surface Type",
" ROOF34, !- Construction Name",
" NORTH_ZONE, !- Zone Name",
" Outdoors, !- Outside Boundary Condition",
" , !- Outside Boundary Condition Object",
" SunExposed, !- Sun Exposure",
" WindExposed, !- Wind Exposure",
" 0, !- View Factor to Ground",
" 4, !- Number of Vertices",
" 0,12.19200,3.048000, !- X,Y,Z ==> Vertex 1 {m}",
" 0,6.096000,3.048000, !- X,Y,Z ==> Vertex 2 {m}",
" 12.19200,6.096000,3.048000, !- X,Y,Z ==> Vertex 3 {m}",
" 12.19200,12.19200,3.048000; !- X,Y,Z ==> Vertex 4 {m}",
/*"FenestrationSurface:Detailed,",
" WINDOW11, !- Name",
" WINDOW, !- Surface Type",
" WIN-CON-LIGHT, !- Construction Name",
" Surface_1, !- Building Surface Name",
" , !- Outside Boundary Condition Object",
" 0.5000000, !- View Factor to Ground",
" , !- Shading Control Name",
" , !- Frame and Divider Name",
" 1.0, !- Multiplier",
" 3, !- Number of Vertices",
" 1.00000,0,2.500000, !- X,Y,Z ==> Vertex 1 {m}",
" 1.00000,0,1.0000000, !- X,Y,Z ==> Vertex 2 {m}",
" 5.000000,0,1.0000000; !- X,Y,Z ==> Vertex 3 {m}",
"FenestrationSurface:Detailed,",
" WINDOW12, !- Name",
" WINDOW, !- Surface Type",
" WIN-CON-LIGHT, !- Construction Name",
" Surface_1, !- Building Surface Name",
" , !- Outside Boundary Condition Object",
" 0.5000000, !- View Factor to Ground",
" , !- Shading Control Name",
" , !- Frame and Divider Name",
" 1.0, !- Multiplier",
" 3, !- Number of Vertices",
" 5.00000,0,1.0000000, !- X,Y,Z ==> Vertex 2 {m}",
" 5.000000,0,2.5000000, !- X,Y,Z ==> Vertex 3 {m}",
" 1.000000,0,2.500000; !- X,Y,Z ==> Vertex 4 {m}",
"FenestrationSurface:Detailed,",
" DoorInSurface_3, !- Name",
" DOOR, !- Surface Type",
" DOOR-CON, !- Construction Name",
" Surface_3, !- Building Surface Name",
" DoorInSurface_17, !- Outside Boundary Condition Object",
" 0.5000000, !- View Factor to Ground",
" , !- Shading Control Name",
" , !- Frame and Divider Name",
" 1.0, !- Multiplier",
" 4, !- Number of Vertices",
" 3.500,6.096000,2.0, !- X,Y,Z ==> Vertex 1 {m}",
" 3.500,6.096000,0.0, !- X,Y,Z ==> Vertex 2 {m}",
" 2.500,6.096000,0.0, !- X,Y,Z ==> Vertex 3 {m}",
" 2.500,6.096000,2.0; !- X,Y,Z ==> Vertex 4 {m}",
"FenestrationSurface:Detailed,",
" WINDOW2, !- Name",
" WINDOW, !- Surface Type",
" WIN-CON-LIGHT, !- Construction Name",
" Surface_15, !- Building Surface Name",
" , !- Outside Boundary Condition Object",
" 0.5000000, !- View Factor to Ground",
" , !- Shading Control Name",
" , !- Frame and Divider Name",
" 1.0, !- Multiplier",
" 4, !- Number of Vertices",
" 6.000000,12.19200,2.333000, !- X,Y,Z ==> Vertex 1 {m}",
" 6.000000,12.19200,1.000000, !- X,Y,Z ==> Vertex 2 {m}",
" 3.000000,12.19200,1.000000, !- X,Y,Z ==> Vertex 3 {m}",
" 3.000000,12.19200,2.333000; !- X,Y,Z ==> Vertex 4 {m}",
"FenestrationSurface:Detailed,",
" DoorInSurface_17, !- Name",
" DOOR, !- Surface Type",
" DOOR-CON, !- Construction Name",
" Surface_17, !- Building Surface Name",
" DoorInSurface_3, !- Outside Boundary Condition Object",
" 0.5000000, !- View Factor to Ground",
" , !- Shading Control Name",
" , !- Frame and Divider Name",
" 1.0, !- Multiplier",
" 4, !- Number of Vertices",
" 2.500,6.096000,2.0, !- X,Y,Z ==> Vertex 1 {m}",
" 2.500,6.096000,0.0, !- X,Y,Z ==> Vertex 2 {m}",
" 3.500,6.096000,0.0, !- X,Y,Z ==> Vertex 3 {m}",
" 3.500,6.096000,2.0; !- X,Y,Z ==> Vertex 4 {m}",*/
"AirflowNetwork:SimulationControl,",
" NaturalVentilation, !- Name",
" MultizoneWithoutDistribution, !- AirflowNetwork Control",
" INPUT, !- Wind Pressure Coefficient Type",
" ExternalNode, !- Height Selection for Local Wind Pressure Calculation",
" LOWRISE, !- Building Type",
" 500, !- Maximum Number of Iterations {dimensionless}",
" ZeroNodePressures, !- Initialization Type",
" 1.0E-05, !- Relative Airflow Convergence Tolerance {dimensionless}",
" 1.0E-06, !- Absolute Airflow Convergence Tolerance {kg/s}",
" -0.5, !- Convergence Acceleration Limit {dimensionless}",
" 0.0, !- Azimuth Angle of Long Axis of Building {deg}",
" 1.0; !- Ratio of Building Width Along Short Axis to Width Along Long Axis",
"AirflowNetwork:MultiZone:Zone,",
" WEST_ZONE, !- Zone Name",
" NoVent, !- Ventilation Control Mode",
" , !- Ventilation Control Zone Temperature Setpoint Schedule Name",
//" Temperature, !- Ventilation Control Mode",
//" WindowVentSched, !- Ventilation Control Zone Temperature Setpoint Schedule Name",
" 0.3, !- Minimum Venting Open Factor {dimensionless}",
" 5.0, !- Indoor and Outdoor Temperature Difference Lower Limit For Maximum Venting Open Factor {deltaC}",
" 10.0, !- Indoor and Outdoor Temperature Difference Upper Limit for Minimum Venting Open Factor {deltaC}",
" 0.0, !- Indoor and Outdoor Enthalpy Difference Lower Limit For Maximum Venting Open Factor {deltaJ/kg}",
" 300000.0; !- Indoor and Outdoor Enthalpy Difference Upper Limit for Minimum Venting Open Factor {deltaJ/kg}",
"AirflowNetwork:MultiZone:Zone,",
" EAST_ZONE, !- Zone Name",
" NoVent, !- Ventilation Control Mode",
" , !- Ventilation Control Zone Temperature Setpoint Schedule Name",
" 1.0, !- Minimum Venting Open Factor {dimensionless}",
" 0.0, !- Indoor and Outdoor Temperature Difference Lower Limit For Maximum Venting Open Factor {deltaC}",
" 100.0, !- Indoor and Outdoor Temperature Difference Upper Limit for Minimum Venting Open Factor {deltaC}",
" 0.0, !- Indoor and Outdoor Enthalpy Difference Lower Limit For Maximum Venting Open Factor {deltaJ/kg}",
" 300000.0; !- Indoor and Outdoor Enthalpy Difference Upper Limit for Minimum Venting Open Factor {deltaJ/kg}",
"AirflowNetwork:MultiZone:Zone,",
" NORTH_ZONE, !- Zone Name",
" NoVent, !- Ventilation Control Mode",
" , !- Ventilation Control Zone Temperature Setpoint Schedule Name",
//" Temperature, !- Ventilation Control Mode",
//" WindowVentSched, !- Ventilation Control Zone Temperature Setpoint Schedule Name",
" 1.0, !- Minimum Venting Open Factor {dimensionless}",
" 0.0, !- Indoor and Outdoor Temperature Difference Lower Limit For Maximum Venting Open Factor {deltaC}",
" 100.0, !- Indoor and Outdoor Temperature Difference Upper Limit for Minimum Venting Open Factor {deltaC}",
" 0.0, !- Indoor and Outdoor Enthalpy Difference Lower Limit For Maximum Venting Open Factor {deltaJ/kg}",
" 300000.0; !- Indoor and Outdoor Enthalpy Difference Upper Limit for Minimum Venting Open Factor {deltaJ/kg}",
"AirflowNetwork:MultiZone:Surface,",
" Surface_1, !- Surface Name",
" CR-1, !- Leakage Component Name",
" SFacade, !- External Node Name",
" 1.0; !- Window/Door Opening Factor, or Crack Factor {dimensionless}",
"AirflowNetwork:MultiZone:Surface,",
" Surface_4, !- Surface Name",
" CR-1, !- Leakage Component Name",
" , !- External Node Name",
" 1.0; !- Window / Door Opening Factor, or Crack Factor{ dimensionless }",
"AirflowNetwork:MultiZone:Surface,",
" Surface_11, !- Surface Name",
" CR-1, !- Leakage Component Name",
" , !- External Node Name",
" 1.0; !- Window / Door Opening Factor, or Crack Factor{ dimensionless }",
"AirflowNetwork:MultiZone:Surface,",
" Surface_15, !- Surface Name",
" CR-1, !- Leakage Component Name",
" NFacade, !- External Node Name",
" 1.0; !- Window / Door Opening Factor, or Crack Factor{ dimensionless }",
"AirflowNetwork:MultiZone:ExternalNode,",
" NFacade, !- Name",
" 1.524, !- External Node Height{ m }",
" NFacade_WPCValue; !- Wind Pressure Coefficient Values Object Name",
"AirflowNetwork:MultiZone:ExternalNode,",
" SFacade, !- Name",
" 1.524, !- External Node Height{ m }",
" SFacade_WPCValue, !- Wind Pressure Coefficient Values Object Name",
" No, !- Symmetric Wind Pressure Coefficient Curve",
" Absolute; !- Wind Angle Type",
"AirflowNetwork:MultiZone:ReferenceCrackConditions,",
" ReferenceCrackConditions,!- Name",
" 20.0, !- Reference Temperature{ C }",
" 101320, !- Reference Barometric Pressure{ Pa }",
" 0.005; !- Reference Humidity Ratio{ kgWater / kgDryAir }",
"AirflowNetwork:MultiZone:Surface:Crack,",
" CR-1, !- Name",
" 0.01, !- Air Mass Flow Coefficient at Reference Conditions{ kg / s }",
" 0.667, !- Air Mass Flow Exponent{ dimensionless }",
" ReferenceCrackConditions;!- Reference Crack Conditions",
"AirflowNetwork:MultiZone:WindPressureCoefficientArray,",
" Every 30 Degrees, !- Name",
" 0, !- Wind Direction 1 {deg}",
" 30, !- Wind Direction 2 {deg}",
" 60, !- Wind Direction 3 {deg}",
" 90, !- Wind Direction 4 {deg}",
" 120, !- Wind Direction 5 {deg}",
" 150, !- Wind Direction 6 {deg}",
" 180, !- Wind Direction 7 {deg}",
" 210, !- Wind Direction 8 {deg}",
" 240, !- Wind Direction 9 {deg}",
" 270, !- Wind Direction 10 {deg}",
" 300, !- Wind Direction 11 {deg}",
" 330; !- Wind Direction 12 {deg}",
"AirflowNetwork:MultiZone:WindPressureCoefficientValues,",
" NFacade_WPCValue, !- Name",
" Every 30 Degrees, !- AirflowNetwork:MultiZone:WindPressureCoefficientArray Name",
" 0.60, !- Wind Pressure Coefficient Value 1 {dimensionless}",
" 0.48, !- Wind Pressure Coefficient Value 2 {dimensionless}",
" 0.04, !- Wind Pressure Coefficient Value 3 {dimensionless}",
" -0.56, !- Wind Pressure Coefficient Value 4 {dimensionless}",
" -0.56, !- Wind Pressure Coefficient Value 5 {dimensionless}",
" -0.42, !- Wind Pressure Coefficient Value 6 {dimensionless}",
" -0.37, !- Wind Pressure Coefficient Value 7 {dimensionless}",
" -0.42, !- Wind Pressure Coefficient Value 8 {dimensionless}",
" -0.56, !- Wind Pressure Coefficient Value 9 {dimensionless}",
" -0.56, !- Wind Pressure Coefficient Value 10 {dimensionless}",
" 0.04, !- Wind Pressure Coefficient Value 11 {dimensionless}",
" 0.48; !- Wind Pressure Coefficient Value 12 {dimensionless}",
"AirflowNetwork:MultiZone:WindPressureCoefficientValues,",
" SFacade_WPCValue, !- Name",
" Every 30 Degrees, !- AirflowNetwork:MultiZone:WindPressureCoefficientArray Name",
" -0.37, !- Wind Pressure Coefficient Value 1 {dimensionless}",
" -0.42, !- Wind Pressure Coefficient Value 2 {dimensionless}",
" -0.56, !- Wind Pressure Coefficient Value 3 {dimensionless}",
" -0.56, !- Wind Pressure Coefficient Value 4 {dimensionless}",
" 0.04, !- Wind Pressure Coefficient Value 5 {dimensionless}",
" 0.48, !- Wind Pressure Coefficient Value 6 {dimensionless}",
" 0.60, !- Wind Pressure Coefficient Value 7 {dimensionless}",
" 0.48, !- Wind Pressure Coefficient Value 8 {dimensionless}",
" 0.04, !- Wind Pressure Coefficient Value 9 {dimensionless}",
" -0.56, !- Wind Pressure Coefficient Value 10 {dimensionless}",
" -0.56, !- Wind Pressure Coefficient Value 11 {dimensionless}",
" -0.42; !- Wind Pressure Coefficient Value 12 {dimensionless}",
"SurfaceConvectionAlgorithm:Inside,TARP;",
"SurfaceConvectionAlgorithm:Outside,DOE-2;",
"HeatBalanceAlgorithm,ConductionTransferFunction;",
"ZoneAirHeatBalanceAlgorithm,",
" AnalyticalSolution; !- Algorithm" });
ASSERT_FALSE(process_idf(idf_objects));
bool errors = false;
HeatBalanceManager::GetMaterialData(errors); // read material data
EXPECT_FALSE(errors); // expect no errors
HeatBalanceManager::GetConstructData(errors); // read construction data
EXPECT_FALSE(errors); // expect no errors
HeatBalanceManager::GetZoneData(errors); // read zone data
EXPECT_FALSE(errors); // expect no errors
// Magic to get surfaces read in correctly
DataHeatBalance::HeatTransferAlgosUsed.allocate(1);
DataHeatBalance::HeatTransferAlgosUsed(1) = OverallHeatTransferSolutionAlgo;
SurfaceGeometry::CosBldgRotAppGonly = 1.0;
SurfaceGeometry::SinBldgRotAppGonly = 0.0;
SurfaceGeometry::GetSurfaceData(errors); // setup zone geometry and get zone data
EXPECT_FALSE(errors); // expect no errors
CurveManager::GetCurveInput();
EXPECT_EQ( CurveManager::NumCurves, 2 );
AirflowNetworkBalanceManager::GetAirflowNetworkInput();
// Check the airflow elements
EXPECT_EQ( 2u, DataAirflowNetwork::MultizoneExternalNodeData.size() );
EXPECT_EQ( 3u, DataAirflowNetwork::MultizoneZoneData.size() );
EXPECT_EQ( 4u, DataAirflowNetwork::MultizoneSurfaceData.size() );
EXPECT_EQ( 1u, DataAirflowNetwork::MultizoneSurfaceCrackData.size() );
EXPECT_EQ( 2u, DataAirflowNetwork::MultizoneSurfaceStdConditionsCrackData.size() );
EXPECT_EQ( 0.0, DataAirflowNetwork::MultizoneExternalNodeData( 1 ).azimuth );
EXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 1 ).symmetricCurve );
EXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 1 ).useRelativeAngle );
EXPECT_EQ( 1, DataAirflowNetwork::MultizoneExternalNodeData( 1 ).curve );
EXPECT_EQ( 180.0, DataAirflowNetwork::MultizoneExternalNodeData( 2 ).azimuth );
EXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 2 ).symmetricCurve );
EXPECT_FALSE( DataAirflowNetwork::MultizoneExternalNodeData( 2 ).useRelativeAngle );
EXPECT_EQ( 2, DataAirflowNetwork::MultizoneExternalNodeData( 2 ).curve );
// Set up some environmental parameters
DataEnvironment::OutBaroPress = 101325.0;
DataEnvironment::OutDryBulbTemp = 25.0;
DataEnvironment::WindDir = 105.0;
DataEnvironment::OutHumRat = 0.0; // Dry air only
DataEnvironment::SiteTempGradient = 0.0; // Disconnect z from testing
DataEnvironment::SiteWindExp = 0.0; // Disconnect variation by height
DataEnvironment::WindSpeed = 10.0;
// Make sure we can compute the right wind pressure
Real64 rho = Psychrometrics::PsyRhoAirFnPbTdbW( DataEnvironment::OutBaroPress, DataEnvironment::OutDryBulbTemp,
DataEnvironment::OutHumRat );
EXPECT_DOUBLE_EQ( 1.1841123742118911, rho );
Real64 p = AirflowNetworkBalanceManager::CalcWindPressure( DataAirflowNetwork::MultizoneExternalNodeData( 1 ).curve,
1.0, 0.0, 0.0, false, false );
EXPECT_DOUBLE_EQ( -0.56*0.5*1.1841123742118911, p );
// Make sure the reference velocity comes out right
EXPECT_DOUBLE_EQ( 10.0, DataEnvironment::WindSpeedAt( MultizoneExternalNodeData( 1 ).height) );
EXPECT_EQ( 5u, DataAirflowNetwork::AirflowNetworkNodeSimu.size() );
// Run the balance routine, for now only to get the pressure set at the external nodes
AirflowNetworkBalanceManager::CalcAirflowNetworkAirBalance();
EXPECT_DOUBLE_EQ( -0.56*0.5*118.41123742118911, DataAirflowNetwork::AirflowNetworkNodeSimu( 4 ).PZ );
EXPECT_DOUBLE_EQ( -0.26*0.5*118.41123742118911, DataAirflowNetwork::AirflowNetworkNodeSimu( 5 ).PZ );
}
MLS
| true
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.