text stringlengths 10 2.61M |
|---|
class AddWalkupAttributeToVouchers < ActiveRecord::Migration
def self.up
add_column :vouchers, :walkup, :boolean, :null => false, :default => false
purchasemethod_ids = Purchasemethod.walkup_purchasemethods.map(&:id)
walkup_cust_id = Customer.walkup_customer.id
Voucher.find(:all,
:conditions => ['showdate_id > 0 AND customer_id = ? AND category != ? AND purchasemethod_id IN (?)', walkup_cust_id, 'nonticket', purchasemethod_ids]).each do |v|
sd = v.showdate.thedate
if v.sold_on.between?(sd - 2.hours, sd + 2.hours)
v.update_attribute(:walkup, true)
end
end
end
def self.down
remove_column :vouchers, :walkup
end
end
|
require_relative 'base'
module MaterializeComponents
class Badge < Base
# Creates a new instance of a badge
#
# @param [String] content The content to put in a badge
def initialize content
@content = content
@tag = :span
reset_class
end
def reset_class c=nil
@css_class = ['badge']
@css_class << c unless c.nil?
return self
end
# Sets a caption for the badge
#
# @param [String] caption The caption you want to use
# @return [self] Returns a reference to self
def caption caption
attr({'data-badge-caption': caption})
return self
end
private
def output
@content
end
class New < Badge
# Creates a "New" Badge
#
# @param [String] content The content to put in a badge
def initialize content
super
@css_class << 'new'
end
end
end
end
|
# Email validator, takes a single input CSV and writes a CSV valid_emails.csv
# ruby email_regex.rb filename.csv
#
# file MUST be a proper CSV format, with a single first column, with "email" as only header row.
#########
# valid email regex is: \b[a-zA-Z0-9!#$%&'*+-\/=?^_`.{|}~]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b
require 'csv'
# csv_write() Adpated from https://github.com/sendgrid/support_scripts/blob/master/webapi_scripts/v3_unsub-delete.rb
@csv_perm = "a"
def csv_write(csv_file, result_array, headers)
CSV.open(csv_file, @csv_perm, {:force_quotes=>true}) { |csv| result_array.each { |result| csv << [result]}}
end
input = ARGV[0]
email_array = []
# move input CSV to array
CSV.foreach(input, headers: true) do |row|
email_array.push(row[0])
end
size = email_array.length
puts "Total email addresses: #{size}"
#puts email_array.inspect
# remove any empty cells
sizea = email_array.length
puts "Removing nil values"
email_array.delete(nil)
sizeb = email_array.length
size = sizea - sizeb
puts "#{size} nil values removed"
# remove duplicate email
sizea = email_array.length
#lowercase all emails
j=0
while (j<sizea-1) do
#puts "#{email_array[j]}"
email_array[j] = email_array[j].downcase
#puts "#{email_array[j]}"
j=j+1
end
puts "Removing duplicates"
email_array = email_array.uniq
sizeb = email_array.length
size = sizea - sizeb
puts "#{size} duplicate emails removed"
size = email_array.length
#puts size
i=0
bad_count = 0
while (i<size) do
#puts email_array[i]
if !(/\b[a-zA-Z0-9!#$%&'*+-\/=?^_`.{|}~]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b/ =~ email_array[i])
puts "removing bad address: #{email_array[i].inspect}"
email_array.delete_at(i)
bad_count = bad_count + 1
i=i-1 #delete_at() alters size of array and shifts indexing. account for this here
size=size-1
end
#puts i
i=i+1
end
size = email_array.length
puts "#{bad_count} total invalid address removed, new CSV size: #{size}"
#puts email_array.inspect
email_array.insert(0,"email")
#puts email_array.inspect
csv_write("valid_emails.csv", email_array.flatten, "email")
puts "Valid emails written to 'valid_emails.csv'" |
class AddImgVideoFileToTopics < ActiveRecord::Migration
def change
add_column :topics, :img_file_name, :string
add_column :topics, :img_content_type, :string
add_column :topics, :img_file_size, :integer
add_column :topics, :img_updated_at, :datetime
add_column :topics, :video_file_name, :string
add_column :topics, :video_content_type, :string
add_column :topics, :video_file_size, :integer
add_column :topics, :video_updated_at, :datetime
add_column :topics, :file_file_name, :string
add_column :topics, :file_content_type, :string
add_column :topics, :file_file_size, :integer
add_column :topics, :file_updated_at, :datetime
end
end
|
namespace :db do
desc 'Use database_cleaner to erase all data from the db, without dropping it'
task :clean => :environment do
puts "Cleaning...".green
DatabaseCleaner.strategy = :deletion
DatabaseCleaner.clean
puts "Cleaned!".light_green
end
end
|
require 'spec_helper'
describe Idea do
it "should properly classify long expired ideas" do
fresh_idea = FactoryGirl.create(:idea)
week_old_scratched_idea = FactoryGirl.create(:idea, :updated_at => 1.1.weeks.ago, :scratched => true)
month_old_active_idea = FactoryGirl.create(:idea)
month_old_scratched_idea = FactoryGirl.create(:idea, :updated_at => 1.month.ago, :scratched => true)
year_old_active_idea = FactoryGirl.create(:idea, :updated_at => 1.year.ago)
year_old_scratched_idea = FactoryGirl.create(:idea, :updated_at => 1.year.ago, :scratched => true)
Idea.long_expired.include?(fresh_idea).should == false
Idea.long_expired.include?(week_old_scratched_idea).should == true
Idea.long_expired.include?(month_old_active_idea).should == false
Idea.long_expired.include?(month_old_scratched_idea).should == true
Idea.long_expired.include?(year_old_active_idea).should == true
Idea.long_expired.include?(year_old_scratched_idea).should == true
end
end
|
module Fog
module DNS
class Google
##
# Fetches the representation of an existing Project. Use this method to look up the limits on the number of
# resources that are associated with your project.
#
# @see https://developers.google.com/cloud-dns/api/v1/projects/get
class Real
def get_project(identity)
@dns.get_project(identity)
end
end
class Mock
def get_project(_identity)
# :no-coverage:
Fog::Mock.not_implemented
# :no-coverage:
end
end
end
end
end
|
require 'transaction'
require 'account'
describe Transaction do
let(:account) { Account.new }
let(:deposit) { account.deposit(1000) }
let(:withdrawal) { account.withdraw(500) }
it 'creates a new deposit transaction' do
deposit
expect(account.transaction_history.length).to eq(1)
expect(account.transaction_history[0].credit).to eq(1000)
expect(account.transaction_history[0].debit).to eq(nil)
end
it 'creates a new withdrawal transaction' do
withdrawal
expect(account.transaction_history.length).to eq(1)
expect(account.transaction_history[0].credit).to eq(nil)
expect(account.transaction_history[0].debit).to eq(500)
end
it 'adds two decimal places to an integer' do
transaction = Transaction.new(credit: 1000)
expect(transaction.credit).to eq(1000)
end
end
|
require 'spec_helper'
describe UsersController do
let(:user_bart) {FactoryGirl.find_or_create(:user_bart)}
before(:each) do
sign_in user_bart
end
describe 'GET index' do
it 'assigns @users' do
saved_users = [FactoryGirl.find_or_create(:user_bart), FactoryGirl.find_or_create(:user_lisa)]
get :index
assigns(:users).should eq(saved_users)
end
end
end |
module ApplicationHelper
def flass_class(type)
case type
when :success then "success"
when :error then "warning"
when :alert then "warning"
when :notice then ""
else "info"
end
end
end
|
class Staff < ActiveRecord::Base
has_many :staff_tags
has_many :tags, through: :staff_tags
has_many :staff_items
has_many :items, through: :staff_items
end
|
class MemberWallet < ApplicationRecord
belongs_to :member
accepts_nested_attributes_for :member
end
|
# frozen_string_literal: true
module WinrForm
module FormHelper
def winr_form_for(record, *args, &block)
options = args.extract_options!
output = tag(:'winr-form', {}, true)
output << form_for(record, *(args << options.merge(builder: WinrForm::Builder)), &block)
output.safe_concat('</winr-form>')
end
end
end
|
class ChangeTimeStampToContactShares < ActiveRecord::Migration
def change
remove_column :contact_shares, :timestamps, :datetime
add_column :contact_shares, :created_at, :datetime
add_column :contact_shares, :updated_at, :datetime
end
end
|
# == Schema Information
#
# Table name: items
#
# id :bigint(8) not null, primary key
# name :string not null
# item_number :string not null
# description :text
# image_url :string
# product_info :text
# price :decimal(, ) not null
# category_id :integer
# created_at :datetime not null
# updated_at :datetime not null
#
class Item < ApplicationRecord
validates :name, :item_number, :price, presence: true
end
|
class CreateMesocycles < ActiveRecord::Migration
def change
create_table :mesocycles do |t|
t.integer :user_id
t.integer :program_id
t.integer :max_bench
t.integer :max_squat
t.integer :max_deadlift
t.integer :max_ohp
t.timestamps
end
end
end
|
class Actor
extend Creation::ClassMethods
include Creation::InstanceMethods
attr_accessor :name
attr_reader :movies
@@all = []
def initialize(name)
@name = name
@movies = []
@@all << self
end
def add_movie(movie)
if !@movies.include?(movie)
@movies << movie
end
if !movie.actors.include?(self)
movie.actors << self
end
end
def self.all
@@all
end
end |
class UserMailer < ActionMailer::Base
default from: SUPPORT_MAIL
helper :application, :mail
layout 'mail'
def standard(user)
@user = user
mail(:to => user.email)
end
def invite(user)
@user = user
@title = 'Tilbud om undervisning i lumbalpunktur'
mail(:to => user.email, :subject => @title)
end
def new_time_slots(user)
@user = user
@title = 'Husk tilbud om undervisning i lumbalpunktur'
mail(:to => user.email, :subject => @title)
end
alias_method :booking_link, :standard
alias_method :booking_confirmation, :standard
alias_method :booking_reminder, :standard
alias_method :test_taken_confirmation, :standard
end
|
# frozen_string_literal: true
require 'rails_helper'
RSpec.describe Project, type: :model do
it 'does not allow duplicate project names per user' do
user = User.create(
first_name: 'John',
last_name: 'carter',
email: 'john@gmail.com'
)
user.projects.create(
name: 'Test Project'
)
new_project = user.projects.build(
name: 'Test Project'
)
new_project.valid?
expect(new_project.errors[:name]).to include('has already been taken')
end
it 'allows two user to share a project name' do
user = User.create(
first_name: 'joe',
last_name: 'deo',
email: 'joe@gmail.com'
)
user.projects.create(
name: 'Test Project'
)
other_user = User.create(
first_name: 'Jane',
last_name: 'Tester',
email: 'jane@gmail.com'
)
other_project = other_user.projects.build(
name: 'Test Project'
)
expect(other_project).to be_valid
end
end
|
require 'rails_helper'
describe Activity, :type => :model do
let(:key) { "run" }
subject { build_stubbed :activity, key: key }
describe "#run?" do
it "returns true" do
expect(subject).to be_run
end
end
describe "#unknown?" do
let(:key) { "unknown" }
it "returns true" do
expect(subject).to be_unknown
end
end
end
|
module OpenAPIParser::Schemas
class Base
include OpenAPIParser::Parser
include OpenAPIParser::Findable
include OpenAPIParser::Expandable
attr_reader :parent, :raw_schema, :object_reference, :root
# @param [OpenAPIParser::Schemas::Base]
def initialize(object_reference, parent, root, raw_schema)
@raw_schema = raw_schema
@parent = parent
@root = root
@object_reference = object_reference
load_data
after_init
end
# override
def after_init
end
def inspect
@object_reference
end
end
end
|
worker_processes 2
working_directory "/home/deploy/current"
# This loads the application in the master process before forking
# worker processes
# Read more about it here:
# http://unicorn.bogomips.org/Unicorn/Configurator.html
preload_app true
timeout 30
# This is where we specify the socket.
# We will point the upstream Nginx module to this socket later on
listen "/home/deploy/shared/unicorn.sock", :backlog => 64
pid "/home/deploy/shared/unicorn.pid"
# Set the path of the log files inside the log folder of the testapp
stderr_path "/home/deploy/shared/unicorn-stderr.log"
stdout_path "/home/deploy/shared/unicorn-stdout.log"
before_fork do |server, worker|
old_pid = '/home/deploy/shared/unicorn.pid.oldbin'
if File.exists?(old_pid) && server.pid != old_pid
begin
Process.kill("QUIT", File.read(old_pid).to_i)
rescue Errno::ENOENT, Errno::ESRCH
# someone else did our job for us
end
end
end
after_fork do |server, worker|
# Here we are establishing the connection after forking worker
# processes
defined?(ActiveRecord::Base) and
ActiveRecord::Base.establish_connection
end |
require 'psd'
require 'recursive-open-struct'
class PsdParser
def initialize(file_path)
psd_path = File.expand_path file_path
@psd = PSD.new psd_path
end
def parse(type = :hash)
@psd.parse!
return @psd if type == :plain
return RecursiveOpenStruct.new(@psd.tree.to_hash) if type == :hash
return @psd.tree.to_hash.to_json if type == :json
end
end |
require 'spec_helper'
describe "commits/index" do
before(:each) do
assign(:commits, [
stub_model(Commit,
:committer_email => "Committer Email",
:committer_name => "Committer Name",
:html_url => "Html Url",
:repository_id => "Repository",
:sha => "Sha",
:author_name => "Author Name",
:author_email => "Author Email"
),
stub_model(Commit,
:committer_email => "Committer Email",
:committer_name => "Committer Name",
:html_url => "Html Url",
:repository_id => "Repository",
:sha => "Sha",
:author_name => "Author Name",
:author_email => "Author Email"
)
])
end
it "renders a list of commits" do
render
# Run the generator again with the --webrat flag if you want to use webrat matchers
assert_select "tr>td", :text => "Committer Email".to_s, :count => 2
assert_select "tr>td", :text => "Committer Name".to_s, :count => 2
assert_select "tr>td", :text => "Html Url".to_s, :count => 2
assert_select "tr>td", :text => "Repository".to_s, :count => 2
assert_select "tr>td", :text => "Sha".to_s, :count => 2
assert_select "tr>td", :text => "Author Name".to_s, :count => 2
assert_select "tr>td", :text => "Author Email".to_s, :count => 2
end
end
|
require "sub_parser/version"
require "sub_parser/subtitle"
require "sub_parser/timespan"
require "sub_parser/timestamp"
module SubParser
def self.parse subtitles
subtitles
.gsub(/\r/, '')
.split(/\n\n/)
.map { |raw| Subtitle.parse raw }
end
def self.join subtitles
subtitles
.each_with_index
.map { |s, i| "#{i+1}\n#{s}" }
.join("\n\n")
end
end
|
module Api
module V1
class WebhooksController < BaseApiController
skip_before_action :authenticate_from_token!
def index
bot_name_to_class = {
smooch: Bot::Smooch,
keep: Bot::Keep,
fetch: Bot::Fetch
}
unless bot_name_to_class.has_key?(params[:name].to_sym)
render_error('Bot not found', 'ID_NOT_FOUND', 404) and return
end
bot = bot_name_to_class[params[:name].to_sym]
if bot.respond_to?(:should_ignore_request?) && bot.should_ignore_request?(request)
render_success('ignored') and return
end
unless bot.valid_request?(request)
render_error('Invalid request', 'UNKNOWN') and return
end
begin
response = bot&.webhook(request)
render(plain: request.params['hub.challenge'], status: 200) and return if response == 'capi:verification'
rescue Bot::Keep::ObjectNotReadyError => e
render_error(e.message, 'OBJECT_NOT_READY', 425) and return
end
render_success 'success', response
end
end
end
end
|
class ContractsController < ApplicationController
def index
@contracts = Contract.all
render json: @contracts
end
end
|
require 'rails_helper'
feature 'admin user can approve or reject podcast suggestions', js: true do
before do
stub_omniauth
end
scenario 'successfully if they can be found through Itunes Search API' do
PodcastSuggestion.create(suggestion: "the bike shed")
pending_suggestions_count = PodcastSuggestion.where(status: "pending").count
visit root_path
click_link 'Log In'
User.first.update_attributes(role: 1) # to make user an admin
click_link 'My Profile'
first('.suggestions .btn-approve').click
visit user_path(User.first)
new_pending_suggestions_count = PodcastSuggestion.where(status: "pending").count
expect(new_pending_suggestions_count).to eq(pending_suggestions_count - 1)
expect(Podcast.count).to eq(1)
end
scenario 'unsuccessfully if they cant be found through Itunes Search API' do
PodcastSuggestion.create(suggestion: "random test")
pending_suggestions_count = PodcastSuggestion.where(status: "pending").count
visit root_path
click_link 'Log In'
User.first.update_attributes(role: 1) # to make user an admin
click_link 'My Profile'
first('.suggestions .btn-approve').click
visit user_path(User.first)
new_pending_suggestions_count = PodcastSuggestion.where(status: "pending").count
expect(new_pending_suggestions_count).to eq(pending_suggestions_count)
expect(Podcast.count).to eq(0)
end
scenario 'when rejected, a suggestion will no longer appear as pending' do
PodcastSuggestion.create(suggestion: "random test")
pending_suggestions_count = PodcastSuggestion.where(status: "pending").count
visit root_path
click_link 'Log In'
User.first.update_attributes(role: 1) # to make user an admin
click_link 'My Profile'
first('.suggestions .btn-reject').click
visit user_path(User.first)
new_pending_suggestions_count = PodcastSuggestion.where(status: "pending").count
expect(new_pending_suggestions_count).to eq(pending_suggestions_count - 1)
expect(Podcast.count).to eq(0)
expect(page).to_not have_content("random test")
end
end
|
require('minitest/autorun')
require('minitest/reporters')
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
require_relative('../room')
require_relative('../guests')
require_relative('../song')
class RoomTest < Minitest::Test
def setup()
@room = Room.new(10)
end
def test_room_has_price()
assert_equal(10, @room.price)
end
end
|
require 'spec_helper'
describe Employee do
before do
@employee = Employee.new(name: "Example User", email: "employee@example.com")
end
subject { @employee }
it { should respond_to(:name) }
it { should respond_to(:email) }
it { should respond_to(:password_digest) }
end |
#!/usr/bin/env ruby
# this script generates the SQL DDL for the DataMeta DOM model
# Example, from gem root:
# dataMetaMySqlDdl.rb ../../../dataMeta/showCase.dmDom ../../../../../target/sql
%w(dataMetaDom dataMetaDom/mySql dataMetaDom/help).each(&method(:require))
include DataMetaDom, DataMetaDom::MySqlLexer
@source, @target = ARGV
DataMetaDom::helpMySqlDdl __FILE__ unless @source && @target
DataMetaDom::helpMySqlDdl(__FILE__, "DataMeta DOM source #{@source} is not a file") unless File.file?(@source)
DataMetaDom::helpMySqlDdl(__FILE__, "MySQL DDL destination directory #{@target} is not a dir") unless File.directory?(@target)
@parser = Model.new
begin
@parser.parse(@source)
puts @parser.enums.values.join("\n") if $DEBUG
puts @parser.records.values.join("\n") if $DEBUG
genDdl(@parser, @target)
puts "MySQL DDL generated into #{@target}"
rescue Exception => e
$stderr.puts "ERROR #{e.message}; #{@parser.diagn}"
$stderr.puts e.backtrace.inspect
exit 1
end
|
#!/usr/bin/ruby
# This is the main entry point for running SHRDLURN. See
# fig/lib/execrunner.rb for more documentation for how commands are generated.
# There are a bunch of modes that this script can be invoked with, which
# loosely correspond to the modules.
$: << 'fig/lib'
require 'execrunner'
$path = 'plot'
$output = 'plot/output'
$modes = []
def addMode(name, description, func)
$modes << [name, description, func]
end
def codalab(dependencies=nil)
# Set @cl=1 to run job on CodaLab
dependencies ||= l(':fig', ':lib', ':module-classes.txt', ':libsempre')
l(
letDefault(:cl, 0),
sel(:cl,
l(),
l('cl', 'run', dependencies, '---', 'LC_ALL=C.UTF-8'),
nil),
nil)
end
def header(modules='core', codalabDependencies=nil)
l(
codalab(codalabDependencies),
# Queuing system
letDefault(:q, 0), sel(:q, l(), l('fig/bin/q', '-shareWorkingPath', o('mem', '5g'), o('memGrace', 10), '-add', '---')),
# Create execution directory
letDefault(:pooldir, 1),
sel(:pooldir, l(), 'fig/bin/qcreate'),
# Run the Java command...
'java',
'-ea',
'-Dmodules='+modules,
# Memory size
letDefault(:memsize, 'default'),
sel(:memsize, {
'tiny' => l('-Xms2G', '-Xmx4G'),
'low' => l('-Xms5G', '-Xmx7G'),
'default' => l('-Xms8G', '-Xmx10G'),
'medium' => l('-Xms12G', '-Xmx14G'),
'high' => l('-Xms20G', '-Xmx24G'),
'higher' => l('-Xms40G', '-Xmx50G'),
'impressive' => l('-Xms75G', '-Xmx90G'),
}),
# Classpath
'-cp', 'libsempre/*:lib/*',
# Profiling
letDefault(:prof, 0), sel(:prof, l(), '-Xrunhprof:cpu=samples,depth=100,file=_OUTPATH_/java.hprof.txt'),
# Debugging
letDefault(:debug, 0), sel(:debug, l(), l('-Xdebug', '-Xrunjdwp:server=y,transport=dt_socket,suspend=y,address=8898')),
nil)
end
def figOpts; l(selo(:pooldir, 'execDir', 'exec', '_OUTPATH_'), o('overwriteExecDir'), o('addToView', 0)) end
addMode('test', 'Run unit tests for interactive stuff', lambda { |e|
l(
'java', '-ea', '-Xmx12g', '-cp', 'libsempre/*:lib/*',
letDefault(:debug, 0), sel(:debug, l(), l('-Xdebug', '-Xrunjdwp:server=y,transport=dt_socket,suspend=y,address=8898')),
'org.testng.TestNG',
lambda { |e|
if e[:class]
l('-testclass', 'edu.stanford.nlp.sempre.interactive.test.' + e[:class])
else
"./#{$path}/testng.xml"
end
},
nil)
})
addMode('setup', 'run some setup scripts for plotting', lambda { |e| l(
lambda { |e| system 'cd plot && svn checkout https://github.com/vega/vega-lite/trunk/examples/specs'},
lambda { |e| system 'cd plot && svn checkout https://github.com/vega/vega-editor/trunk/data'},
lambda { |e| system 'cd plot && bash makedir.sh'},
nil) })
addMode('trash', 'put int-output into trash with time stamp', lambda { |e| l(
lambda { |e| system 'echo "trashing plot-out with time stamp"'},
lambda { |e| system 'mv plot-out plot-out-trash-`date +%Y-%m-%d.%H:%M:%S`'},
lambda { |e| system 'rm -rf plot-out-trash-*'},
lambda { |e| system 'mkdir -p ./plot-out'},
nil)})
############################################################
# {2016-07-02} [sidaw]: interactive semantic parsing
addMode('plot', 'interactive semantic parsing for plotting', lambda { |e| l(
#rlwrap,
header('core,interactive'),
'edu.stanford.nlp.sempre.Main',
figOpts,
o('server'),
o('masterType', 'edu.stanford.nlp.sempre.interactive.JsonMaster'),
o('Executor', 'interactive.VegaExecutor'),
o('LanguageAnalyzer', 'interactive.DALAnalyzer'),
selo(0, 'Grammar.inPaths', "./#{$path}/plot.grammar"),
o('Params.initWeightsRandomly', false),
o('Grammar.binarizeRules', false),
o('Grammar.useApplyFn', 'interactive.ApplyFn'),
o('Grammar.tags', 'doublestar'),
o('LanguageAnalyzer.lowerCaseTokens', false),
o('Parser.pruneErrorValues', true),
o('Parser', 'FloatingParser'),
o('FloatingParser.defaultIsFloating', false),
o('FloatingParser.useAnchorsOnce', true),
o('FloatingParser.allowCanonicalUtteranceOverride', true),
o('Parser.callSetEvaluation', false),
o('Parser.coarsePrune', false),
o('ParserState.mapToFormula', true),
o('Parser.beamSize', 10000),
o('ParserState.customExpectedCounts', 'None'),
o('Params.l1Reg', 'nonlazy'),
o('Params.l1RegCoeff', 0.0001),
o('Params.initStepSize', 0.5),
o('Params.adaptiveStepSize', true),
#o('Params.stepSizeReduction', 0.25), # o('FeatureExtractor.featureDomains', ':rule'),
o('JsonMaster.intOutputPath', './plot-out/'),
o('InteractiveServer.numThreads', 8),
o('InteractiveServer.maxCandidates', 100),
o('InteractiveServer.queryLogPath', './plot-out/query.jsonl'),
o('InteractiveServer.responseLogPath', './plot-out/response.jsonl'),
o('InteractiveServer.port', 8405),
o('InteractiveServer.isJsonQuery', true),
o('Derivation.showTypes', false),
o('Derivation.showValues', false),
o('Derivation.showRules', false),
o('Derivation.anchoredBonus', 1.0),
o('VegaResources.vegaSchema', "./#{$path}/vega-lite-v2.json"),
o('VegaResources.excludedPaths', 'items', 'vconcat', 'hconcat', 'layer', 'spec', 'repeat'),
o('VegaResources.colorFile', "./#{$path}/css-color-names.json"),
# o('VegaResources.vegaSpecifications', "./#{$path}/templates/population", "./#{$path}/templates/cars", "./#{$path}/templates/stocks"),
o('VegaResources.initialTemplates', "./#{$path}/initial-templates.json"),
# selo(0, 'VegaResources.allVegaJsonPaths', "./#{$path}/vega-lite-paths.txt", "./plot-out/PathInTemplates.txt"),
o('VegaEngine.verbose', 0),
o('VegaExecutor.compileVega', false),
o('JsonFn.maxJoins', 10000), # hack.
# learning stuff
o('Dataset.datasetReader', "interactive.JsonlDatasetReader"),
o('Dataset.inPaths', "train:./plot-data/sampledata.jsonl"),
o('Parser.callSetEvaluation', true),
o('Learner.numParallelThreads', 8),
o('Builder.valueEvaluator', 'interactive.VegaValueEvaluator'),
o('Parser.accuracyTopK', 10),
o('FeatureExtractor.featureComputers', 'FloatingFeatureComputer', 'interactive.VegaFeatureComputer'),
o('FeatureExtractor.featureDomains', 'rule', 'span', 'bigram', 'floatSkip', 'floatRule',
'pathPattern', 'valueType', 'lexPathPattern', 'lexValueType'),
o('Learner.maxTrainIters', 0),
lambda { |e| system 'mkdir -p ./plot-out/'; nil},
lambda { |e| system 'mkdir -p ./plot-out/log/'; nil},
nil) })
############################################################
if ARGV.size == 0
puts "#{$0} @mode=<mode> [options]"
puts
puts 'This is the main entry point for all interactive related modes.'
puts "Modes:"
$modes.each { |name,description,func|
puts " #{name}: #{description}"
}
end
modesMap = {}
$modes.each { |name,description,func|
modesMap[name] = func
}
run!(sel(:mode, modesMap))
|
require 'rails_helper'
RSpec.describe Domain do
before :example do
Setting.ds_algorithm = 2
Setting.ds_data_allowed = true
Setting.ds_data_with_key_allowed = true
Setting.key_data_allowed = true
Setting.dnskeys_min_count = 0
Setting.dnskeys_max_count = 9
Setting.ns_min_count = 2
Setting.ns_max_count = 11
Setting.transfer_wait_time = 0
Setting.admin_contacts_min_count = 1
Setting.admin_contacts_max_count = 10
Setting.tech_contacts_min_count = 0
Setting.tech_contacts_max_count = 10
Setting.client_side_status_editing_enabled = true
create(:zone, origin: 'ee')
create(:zone, origin: 'pri.ee')
create(:zone, origin: 'med.ee')
create(:zone, origin: 'fie.ee')
create(:zone, origin: 'com.ee')
end
context 'with invalid attribute' do
before :example do
@domain = Domain.new
end
it 'should not have any versions' do
@domain.versions.should == []
end
it 'should not have whois body' do
@domain.whois_record.should == nil
end
it 'should not be registrant update confirm ready' do
@domain.registrant_update_confirmable?('123').should == false
end
it 'should not have pending update' do
@domain.pending_update?.should == false
end
it 'should allow pending update' do
@domain.pending_update_prohibited?.should == false
end
it 'should not have pending delete' do
@domain.pending_delete?.should == false
end
it 'should allow pending delete' do
@domain.pending_delete_prohibited?.should == false
end
end
context 'with valid attributes' do
before :example do
@domain = create(:domain)
end
it 'should be valid' do
@domain.valid?
@domain.errors.full_messages.should match_array([])
end
it 'should be valid twice' do
@domain = create(:domain)
@domain.valid?
@domain.errors.full_messages.should match_array([])
end
it 'should validate uniqueness of tech contacts' do
same_contact = create(:contact, code: 'same_contact')
domain = create(:domain)
domain.tech_contacts << same_contact
domain.tech_contacts << same_contact
domain.valid?
domain.errors.full_messages.should match_array(["Tech domain contacts is invalid"])
end
it 'should validate uniqueness of tech contacts' do
same_contact = create(:contact, code: 'same_contact')
domain = create(:domain)
domain.admin_contacts << same_contact
domain.admin_contacts << same_contact
domain.valid?
domain.errors.full_messages.should match_array(["Admin domain contacts is invalid"])
end
it 'should have whois body by default' do
@domain.whois_record.present?.should == true
end
it 'should have whois json by default' do
@domain.whois_record.json.present?.should == true
end
it 'should not be registrant update confirm ready' do
@domain.registrant_update_confirmable?('123').should == false
end
it 'should expire domains' do
Setting.expire_warning_period = 1
Setting.redemption_grace_period = 1
DomainCron.start_expire_period
@domain.statuses.include?(DomainStatus::EXPIRED).should == false
old_valid_to = Time.zone.now - 10.days
@domain.valid_to = old_valid_to
@domain.save
DomainCron.start_expire_period
@domain.reload
@domain.statuses.include?(DomainStatus::EXPIRED).should == true
DomainCron.start_expire_period
@domain.reload
@domain.statuses.include?(DomainStatus::EXPIRED).should == true
end
it 'should start redemption grace period' do
old_valid_to = Time.zone.now - 10.days
@domain.valid_to = old_valid_to
@domain.statuses = [DomainStatus::EXPIRED]
@domain.outzone_at, @domain.delete_at = nil, nil
@domain.save
DomainCron.start_expire_period
@domain.reload
@domain.statuses.include?(DomainStatus::EXPIRED).should == true
end
context 'with time period settings' do
before :example do
@save_days_to_renew = Setting.days_to_renew_domain_before_expire
@save_warning_period = Setting.expire_warning_period
@save_grace_period = Setting.redemption_grace_period
end
after :all do
Setting.days_to_renew_domain_before_expire = @save_days_to_renew
Setting.expire_warning_period = @save_warning_period
Setting.redemption_grace_period = @save_grace_period
end
before :example do
@domain.valid?
end
context 'with no renewal limit, renew anytime' do
before do
Setting.days_to_renew_domain_before_expire = 0
end
it 'should always renew with no policy' do
@domain.renewable?.should be true
end
it 'should not allow to renew after force delete' do
Setting.redemption_grace_period = 1
@domain.schedule_force_delete
@domain.renewable?.should be false
end
end
context 'with renew policy' do
before :example do
@policy = 30
Setting.days_to_renew_domain_before_expire = @policy
end
it 'should not allow renew before policy' do
@domain.valid_to = Time.zone.now.beginning_of_day + @policy.days * 2
@domain.renewable?.should be false
end
context 'ready to renew' do
before { @domain.valid_to = Time.zone.now + (@policy - 2).days }
it 'should allow renew' do
@domain.renewable?.should be true
end
it 'should not allow to renew after force delete' do
Setting.redemption_grace_period = 1
@domain.schedule_force_delete
@domain.renewable?.should be false
end
end
end
end
it 'should set pending update' do
@domain.statuses = DomainStatus::OK # restore
@domain.save
@domain.pending_update?.should == false
@domain.set_pending_update
@domain.pending_update?.should == true
@domain.statuses = DomainStatus::OK # restore
end
it 'should not set pending update' do
@domain.statuses = DomainStatus::OK # restore
@domain.statuses << DomainStatus::CLIENT_UPDATE_PROHIBITED
@domain.save
@domain.set_pending_update.should == nil # not updated
@domain.pending_update?.should == false
@domain.statuses = DomainStatus::OK # restore
end
it 'should set pending delete' do
@domain.nameservers.build(attributes_for(:nameserver))
@domain.nameservers.build(attributes_for(:nameserver))
@domain.statuses = DomainStatus::OK # restore
@domain.save
@domain.pending_delete?.should == false
@domain.set_pending_delete
@domain.save
@domain.statuses.should == ['pendingDelete', 'serverHold']
@domain.pending_delete?.should == true
@domain.statuses = ['serverManualInzone']
@domain.save
@domain.set_pending_delete
@domain.statuses.sort.should == ['pendingDelete', 'serverManualInzone'].sort
@domain.statuses = DomainStatus::OK # restore
end
it 'should not set pending delele' do
@domain.statuses = DomainStatus::OK # restore
@domain.pending_delete?.should == false
@domain.statuses << DomainStatus::CLIENT_DELETE_PROHIBITED
@domain.save
@domain.set_pending_delete.should == nil
@domain.pending_delete?.should == false
@domain.statuses = DomainStatus::OK # restore
end
it 'should notify registrar' do
text = 'Registrant confirmed domain update: testpollmessage123.ee'
domain = create(:domain, name: 'testpollmessage123.ee')
domain.notify_registrar(:poll_pending_update_confirmed_by_registrant)
domain.registrar.notifications.first.text.should == text
end
context 'about registrant update confirm' do
before :example do
@domain.registrant_verification_token = 123
@domain.registrant_verification_asked_at = Time.zone.now
@domain.statuses << DomainStatus::PENDING_UPDATE
end
it 'should be registrant update confirm ready' do
@domain.registrant_update_confirmable?('123').should == true
end
it 'should not be registrant update confirm ready when token does not match' do
@domain.registrant_update_confirmable?('wrong-token').should == false
end
it 'should not be registrant update confirm ready when no correct status' do
@domain.statuses = []
@domain.registrant_update_confirmable?('123').should == false
end
end
context 'about registrant update confirm when domain is invalid' do
before :example do
@domain.registrant_verification_token = 123
@domain.registrant_verification_asked_at = Time.zone.now
@domain.statuses << DomainStatus::PENDING_UPDATE
end
it 'should be registrant update confirm ready' do
@domain.registrant_update_confirmable?('123').should == true
end
it 'should not be registrant update confirm ready when token does not match' do
@domain.registrant_update_confirmable?('wrong-token').should == false
end
it 'should not be registrant update confirm ready when no correct status' do
@domain.statuses = []
@domain.registrant_update_confirmable?('123').should == false
end
end
end
it 'validates domain name' do
d = create(:domain)
expect(d.name).to_not be_nil
invalid = [
'a.ee', "#{'a' * 64}.ee", 'ab.eu', 'test.ab.ee', '-test.ee', '-test-.ee',
'test-.ee', 'te--st.ee', 'õ.pri.ee', 'www.ab.ee', 'test.eu', ' .ee', 'a b.ee',
'Ž .ee', 'test.edu.ee'
]
invalid.each do |x|
expect(build(:domain, name: x).valid?).to be false
end
valid = [
'ab.ee', "#{'a' * 63}.ee", 'te-s-t.ee', 'jäääär.ee', 'päike.pri.ee',
'õigus.com.ee', 'õäöü.fie.ee', 'test.med.ee', 'žä.ee', ' ŽŠ.ee '
]
valid.each do |x|
expect(build(:domain, name: x).valid?).to be true
end
invalid_punycode = ['xn--geaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-4we.pri.ee']
invalid_punycode.each do |x|
expect(build(:domain, name: x).valid?).to be false
end
valid_punycode = ['xn--ge-uia.pri.ee', 'xn--geaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-9te.pri.ee']
valid_punycode.each do |x|
expect(build(:domain, name: x).valid?).to be true
end
end
it 'should not create zone origin domain' do
d = build(:domain, name: 'ee')
d.save.should == false
expect(d.errors.full_messages).to include('Data management policy violation: Domain name is blocked [name]')
d = build(:domain, name: 'bla')
d.save.should == false
expect(d.errors.full_messages).to include('Domain name Domain name is invalid')
end
it 'downcases domain' do
d = Domain.new(name: 'TesT.Ee')
expect(d.name).to eq('test.ee')
expect(d.name_puny).to eq('test.ee')
expect(d.name_dirty).to eq('test.ee')
end
it 'should be valid when name length is exatly 63 in characters' do
d = create(:domain, name: "#{'a' * 63}.ee")
d.valid?
d.errors.full_messages.should == []
end
it 'should not be valid when name length is longer than 63 characters' do
d = build(:domain, name: "#{'a' * 64}.ee")
d.valid?
d.errors.full_messages.should match_array([
"Domain name Domain name is invalid",
"Puny label Domain name is too long (maximum is 63 characters)"
])
end
it 'should not be valid when name length is longer than 63 characters' do
d = build(:domain,
name: "xn--4caaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.ee")
d.valid?
d.errors.full_messages.should match_array([
"Domain name Domain name is invalid",
"Puny label Domain name is too long (maximum is 63 characters)"
])
end
it 'should be valid when name length is 63 characters' do
d = build(:domain,
name: "õäöüšžõäöüšžõäöüšžõäöüšžõäöüšžõäöüšžõäöüšžab123.pri.ee")
d.valid?
d.errors.full_messages.should match_array([
])
end
it 'should not be valid when name length is longer than 63 punycode characters' do
d = build(:domain, name: "#{'ä' * 63}.ee")
d.valid?
d.errors.full_messages.should == [
"Puny label Domain name is too long (maximum is 63 characters)"
]
end
it 'should not be valid when name length is longer than 63 punycode characters' do
d = build(:domain, name: "#{'ä' * 64}.ee")
d.valid?
d.errors.full_messages.should match_array([
"Domain name Domain name is invalid",
"Puny label Domain name is too long (maximum is 63 characters)"
])
end
it 'should not be valid when name length is longer than 63 punycode characters' do
d = build(:domain, name: "#{'ä' * 63}.pri.ee")
d.valid?
d.errors.full_messages.should match_array([
"Puny label Domain name is too long (maximum is 63 characters)"
])
end
it 'should be valid when punycode name length is not longer than 63' do
d = build(:domain, name: "#{'ä' * 53}.pri.ee")
d.valid?
d.errors.full_messages.should == []
end
it 'should be valid when punycode name length is not longer than 63' do
d = build(:domain, name: "#{'ä' * 57}.ee")
d.valid?
d.errors.full_messages.should == []
end
it 'should not be valid when name length is one pynicode' do
d = build(:domain, name: "xn--4ca.ee")
d.valid?
d.errors.full_messages.should == ["Domain name Domain name is invalid"]
end
it 'should not be valid with at character' do
d = build(:domain, name: 'dass@sf.ee')
d.valid?
d.errors.full_messages.should == ["Domain name Domain name is invalid"]
end
it 'should not be valid with invalid characters' do
d = build(:domain, name: '@ba)s(?ä_:-df.ee')
d.valid?
d.errors.full_messages.should == ["Domain name Domain name is invalid"]
end
it 'should be valid when name length is two pynicodes' do
d = build(:domain, name: "xn--4caa.ee")
d.valid?
d.errors.full_messages.should == []
end
it 'should be valid when name length is two pynicodes' do
d = build(:domain, name: "xn--4ca0b.ee")
d.valid?
d.errors.full_messages.should == []
end
it 'does not create a reserved domain' do
create(:reserved_domain, name: 'test.ee')
domain = build(:domain, name: 'test.ee')
domain.validate
expect(domain.errors[:base]).to include('Required parameter missing; reserved>pw element required for reserved domains')
end
it 'manages statuses automatically' do
d = build(:domain)
d.nameservers.build(attributes_for(:nameserver))
d.nameservers.build(attributes_for(:nameserver))
d.save!
expect(d.statuses.count).to eq(1)
expect(d.statuses.first).to eq(DomainStatus::OK)
d.period = 2
d.save
d.reload
expect(d.statuses.count).to eq(1)
expect(d.statuses.first).to eq(DomainStatus::OK)
d.statuses << DomainStatus::CLIENT_DELETE_PROHIBITED
d.save
d.reload
expect(d.statuses.count).to eq(1)
expect(d.statuses.first).to eq(DomainStatus::CLIENT_DELETE_PROHIBITED)
end
with_versioning do
context 'when saved' do
before(:each) do
domain = create(:domain, nameservers_attributes: [attributes_for(:nameserver),
attributes_for(:nameserver)])
end
it 'creates domain version' do
expect(DomainVersion.count).to eq(1)
expect(ContactVersion.count).to eq(3)
expect(NameserverVersion.count).to eq(2)
end
end
end
end
RSpec.describe Domain do
it { is_expected.to alias_attribute(:on_hold_time, :outzone_at) }
it { is_expected.to alias_attribute(:outzone_time, :outzone_at) }
describe 'registrar validation', db: false do
let(:domain) { described_class.new }
it 'rejects absent' do
domain.registrar = nil
domain.validate
expect(domain.errors).to have_key(:registrar)
end
end
describe 'registrant validation', db: false do
let(:domain) { described_class.new }
it 'rejects absent' do
domain.registrant = nil
domain.validate
expect(domain.errors).to have_key(:registrant)
end
end
describe 'period validation', db: false do
let(:domain) { described_class.new }
it 'rejects absent' do
domain.period = nil
domain.validate
expect(domain.errors).to have_key(:period)
end
it 'rejects fractional' do
domain.period = 1.1
domain.validate
expect(domain.errors).to have_key(:period)
end
it 'accepts integer' do
domain.period = 1
domain.validate
expect(domain.errors).to_not have_key(:period)
end
end
describe 'admin contact count validation' do
let(:domain) { described_class.new }
before :example do
Setting.admin_contacts_min_count = 1
Setting.admin_contacts_max_count = 2
end
it 'rejects less than min' do
domain.validate
expect(domain.errors).to have_key(:admin_domain_contacts)
end
it 'rejects more than max' do
(Setting.admin_contacts_max_count + 1).times { domain.admin_domain_contacts << build(:admin_domain_contact) }
domain.validate
expect(domain.errors).to have_key(:admin_domain_contacts)
end
it 'accepts min' do
Setting.admin_contacts_min_count.times { domain.admin_domain_contacts << build(:admin_domain_contact) }
domain.validate
expect(domain.errors).to_not have_key(:admin_domain_contacts)
end
it 'accepts max' do
Setting.admin_contacts_max_count.times { domain.admin_domain_contacts << build(:admin_domain_contact) }
domain.validate
expect(domain.errors).to_not have_key(:admin_domain_contacts)
end
end
describe 'nameserver validation', db: true do
let(:domain) { described_class.new(name: 'whatever.test') }
it 'rejects less than min' do
Setting.ns_min_count = 2
domain.nameservers.build(attributes_for(:nameserver))
domain.validate
expect(domain.errors).to have_key(:nameservers)
end
it 'rejects more than max' do
Setting.ns_min_count = 1
Setting.ns_max_count = 1
domain.nameservers.build(attributes_for(:nameserver))
domain.nameservers.build(attributes_for(:nameserver))
domain.validate
expect(domain.errors).to have_key(:nameservers)
end
it 'accepts min' do
Setting.ns_min_count = 1
domain.nameservers.build(attributes_for(:nameserver))
domain.validate
expect(domain.errors).to_not have_key(:nameservers)
end
it 'accepts max' do
Setting.ns_min_count = 1
Setting.ns_max_count = 2
domain.nameservers.build(attributes_for(:nameserver))
domain.nameservers.build(attributes_for(:nameserver))
domain.validate
expect(domain.errors).to_not have_key(:nameservers)
end
context 'when nameserver is optional' do
before :example do
allow(Domain).to receive(:nameserver_required?).and_return(false)
end
it 'rejects less than min' do
Setting.ns_min_count = 2
domain.nameservers.build(attributes_for(:nameserver))
domain.validate
expect(domain.errors).to have_key(:nameservers)
end
it 'accepts absent' do
domain.validate
expect(domain.errors).to_not have_key(:nameservers)
end
end
context 'when nameserver is required' do
before :example do
allow(Domain).to receive(:nameserver_required?).and_return(true)
end
it 'rejects absent' do
domain.validate
expect(domain.errors).to have_key(:nameservers)
end
end
end
describe '::nameserver_required?' do
before do
Setting.nameserver_required = 'test'
end
it 'returns setting value' do
expect(described_class.nameserver_required?).to eq('test')
end
end
describe '::expire_warning_period', db: true do
before :example do
Setting.expire_warning_period = 1
end
it 'returns expire warning period' do
expect(described_class.expire_warning_period).to eq(1.day)
end
end
describe '::redemption_grace_period', db: true do
before :example do
Setting.redemption_grace_period = 1
end
it 'returns redemption grace period' do
expect(described_class.redemption_grace_period).to eq(1.day)
end
end
describe '#set_server_hold' do
let(:domain) { described_class.new }
before :example do
travel_to Time.zone.parse('05.07.2010')
domain.set_server_hold
end
it 'sets corresponding status' do
expect(domain.statuses).to include(DomainStatus::SERVER_HOLD)
end
it 'sets :outzone_at to now' do
expect(domain.outzone_at).to eq(Time.zone.parse('05.07.2010'))
end
end
describe '#admin_contact_names' do
let(:domain) { described_class.new }
before :example do
expect(Contact).to receive(:names).and_return('names')
end
it 'returns admin contact names' do
expect(domain.admin_contact_names).to eq('names')
end
end
describe '#admin_contact_emails' do
let(:domain) { described_class.new }
before :example do
expect(Contact).to receive(:emails).and_return('emails')
end
it 'returns admin contact emails' do
expect(domain.admin_contact_emails).to eq('emails')
end
end
describe '#tech_contact_names' do
let(:domain) { described_class.new }
before :example do
expect(Contact).to receive(:names).and_return('names')
end
it 'returns technical contact names' do
expect(domain.tech_contact_names).to eq('names')
end
end
describe '#nameserver_hostnames' do
let(:domain) { described_class.new }
before :example do
expect(Nameserver).to receive(:hostnames).and_return('hostnames')
end
it 'returns name server hostnames' do
expect(domain.nameserver_hostnames).to eq('hostnames')
end
end
describe '#primary_contact_emails' do
let(:domain) { described_class.new }
before :example do
expect(domain).to receive(:registrant_email).and_return('registrant@test.com')
expect(domain).to receive(:admin_contact_emails).and_return(%w(admin.contact@test.com admin.contact@test.com))
end
it 'returns unique list of registrant and administrative contact emails' do
expect(domain.primary_contact_emails).to match_array(%w(
registrant@test.com
admin.contact@test.com
))
end
end
describe '#set_graceful_expired' do
let(:domain) { described_class.new }
before :example do
expect(described_class).to receive(:expire_warning_period).and_return(1.day)
expect(described_class).to receive(:redemption_grace_period).and_return(2.days)
expect(domain).to receive(:valid_to).and_return(Time.zone.parse('05.07.2010 10:30'))
domain.set_graceful_expired
end
it 'sets :outzone_at to :valid_to + expire warning period' do
expect(domain.outzone_at).to eq(Time.zone.parse('06.07.2010 10:30'))
end
it 'sets :delete_at to :outzone_at + redemption grace period' do
expect(domain.delete_at).to eq(Time.zone.parse('08.07.2010 10:30'))
end
end
describe '::outzone_candidates', db: true do
before :example do
travel_to Time.zone.parse('05.07.2010 00:00')
create(:zone, origin: 'ee')
create(:domain, id: 1, outzone_time: Time.zone.parse('04.07.2010 23:59'))
create(:domain, id: 2, outzone_time: Time.zone.parse('05.07.2010 00:00'))
create(:domain, id: 3, outzone_time: Time.zone.parse('05.07.2010 00:01'))
end
it 'returns domains with outzone time in the past' do
expect(described_class.outzone_candidates.ids).to eq([1])
end
end
describe '::uses_zone?', db: true do
let!(:zone) { create(:zone, origin: 'domain.tld') }
context 'when zone is used' do
let!(:domain) { create(:domain, name: 'test.domain.tld') }
specify { expect(described_class.uses_zone?(zone)).to be true }
end
context 'when zone is unused' do
specify { expect(described_class.uses_zone?(zone)).to be false }
end
end
describe '#new_registrant_email' do
let(:domain) { described_class.new(pending_json: { new_registrant_email: 'test@test.com' }) }
it 'returns new registrant\'s email' do
expect(domain.new_registrant_email).to eq('test@test.com')
end
end
describe '#new_registrant_id' do
let(:domain) { described_class.new(pending_json: { new_registrant_id: 1 }) }
it 'returns new registrant\'s id' do
expect(domain.new_registrant_id).to eq(1)
end
end
end
|
class Application
attr_reader :team, :name, :conf
attr_accessor :flight
def initialize(team, name, conf)
@team = team
@name = name
@conf = conf
conf.popularity += 1
end
def conf_name
conf.name
end
def to_row
["#{conf.name}#{ ' *' if flight}", name, team]
end
end
|
require 'test_helper'
class GuiFunctionsControllerTest < ActionController::TestCase
setup do
@gui_function = gui_functions(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:gui_functions)
end
test "should get new" do
get :new
assert_response :success
end
test "should create gui_function" do
assert_difference('GuiFunction.count') do
post :create, gui_function: @gui_function.attributes
end
assert_redirected_to gui_function_path(assigns(:gui_function))
end
test "should show gui_function" do
get :show, id: @gui_function.to_param
assert_response :success
end
test "should get edit" do
get :edit, id: @gui_function.to_param
assert_response :success
end
test "should update gui_function" do
put :update, id: @gui_function.to_param, gui_function: @gui_function.attributes
assert_redirected_to gui_function_path(assigns(:gui_function))
end
test "should destroy gui_function" do
assert_difference('GuiFunction.count', -1) do
delete :destroy, id: @gui_function.to_param
end
assert_redirected_to gui_functions_path
end
end
|
require 'quickmr/processor_base'
class Multiplexer < ProcessorBase
def initialize(options)
super
@sequence = 0
@outputs = []
end
def connect(outputs)
@outputs = outputs
log "multiplexing to #{@outputs.length} outputs"
end
private
def on_data(event)
if not event.data
@outputs.each do |output|
output.deliver_message! :data, nil
shutdown!
end
return
end
@outputs[@sequence % @outputs.length].deliver_message! :data, event.data
@sequence += 1
end
end
|
class AddAddressColumnsToEventMasters < ActiveRecord::Migration
def change
add_column :event_masters, :address_one, :string
add_column :event_masters, :address_two, :string
add_column :event_masters, :city, :string
add_column :event_masters, :state, :string
add_column :event_masters, :country, :string
add_column :event_masters, :postal_code, :string
end
end |
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@mail = @user.email
@posts = @user.posts
end
def edit
@user = User.find(params[:id])
redirect_to user_path unless @user == current_user
end
def update
@user = User.find(params[:id])
@user.update user_params
redirect_to user_path
end
def user_params
params.require(:user).permit :avatar
end
end
|
class User < ActiveRecord::Base
has_many :splatts
has_and_belongs_to_many :follows,
class_name: "User",
join_table: :follows,
foreign_key: :follower_id,
association_foreign_key: :followed_id
has_and_belongs_to_many :followed_by,
class_name: "User",
join_table: :follows,
foreign_key: :followed_id,
association_foreign_key: :follower_id
#Imposing validation on the Users' params
validates :name, presence: true
validates :email, uniqueness: true
validates :email, uniqueness: {case_sensitive: false}
validates :password, length: {minimum: 8}
end
|
=begin
class MyTemplateBuilder < Vizier::TemplateBuilder
command_set do
require 'myapp/commands'
MyApp::Commands::setup_commands
end
template_path [""] + %w{etc myapp templates}, %{~ .myapp templates}
end
MyTemplateBuilder.go
=end
require 'valise'
require 'vizier/visitors/base'
module Vizier::Visitors
class TemplateBuilder < Collector
class << self
def command_set
@command_set = yield
end
def get_command_set
@command_set
end
def template_path(*args)
@template_path = args
end
def get_template_path
@template_path
end
def go
churn([self.new(Valise.new(get_template_path, get_command_set))])
end
end
def initialize(valise, node)
super(node)
@valise = valise
end
attr_reader :valise
def open
path = @command_path.dup
template_string = node.template_string
#path = node.template_path
path = []
path[-1] = path[-1] + ".sten"
if template_string.nil?
path[-1] = path[-1] + ".example"
@valise.add_file(path, "")
else
@valise.add_file(path, template_string)
end
super
end
end
end
|
class Station < ActiveRecord::Base
has_many :deliveries
has_many :delivery_areas, dependent: :destroy
has_many :service_stats
has_many :customs, through: :service_stats
accepts_nested_attributes_for :delivery_areas, allow_destroy: true
has_many :apps, dependent: :delete_all, class_name: "MobileApp"
accepts_nested_attributes_for :apps, allow_destroy: true
has_many :secondary_apps, -> { where.not(primary: true) }, class_name: "MobileApp"
accepts_nested_attributes_for :secondary_apps, allow_destroy: true
has_one :primary_app, -> { where(primary: true) }, class_name: "MobileApp"
after_create :create_primary_app
after_update :modify_primary_app, if: :imei_changed?
acts_as_mappable :default_units => :kms,
:default_formula => :sphere,
:distance_field_name => :distance,
:lat_column_name => :latitude,
:lng_column_name => :longitude
scope :match, ->(complete = {}, like = {}) {
tmp = self
complete.each do |k, v|
tmp = tmp.where(k => v) if v.present?
end
like.each do |k, v|
tmp = tmp.where("#{k} like ?", "%#{v}%") if v.present?
end
tmp
}
attr_accessor :create_by_app
validates :service_code, presence: true, format: { with: /\A\d+\z/, message: "只允许数字" }, uniqueness: true, unless: :create_by_app
#delete imei after process old data(generate app instead of imei)
validates_presence_of :zipcode, :contact, :mobile, :address, :province, :city, :district, :latitude, :longitude, :imei
validates :zipcode, format: { with: /\A\d{6}\z/, message: '只能为6位数字' }
validates :mobile, format: { with: /[\d\-]+/, message: '只允许数字和分隔线' }
validates :latitude, numericality: { greater_than_or_equal_to: -90, less_than_or_equal_to: 90, message: '纬度必须为+/-90度之间' }
validates :longitude, numericality: { greater_than_or_equal_to: -180, less_than_or_equal_to: 180, message: '经度必须为+/-180度之间' }
validates_uniqueness_of :mobile, :imei
#todo upgrade to rails 4.2.0, have compatibility problem, be careful(should write test)
#not support for rails 4.0
# enum status: [:init, :active, :inactive] -> 0/1/2
#use simple_enum instead, do not have Station.init methods, not auto save to datavase when use init!
as_enum :status, [:init, :active, :disabled]
attr_accessor :state
def to_s
string = "#{address}\n编号: #{service_code}\n邮编: #{zipcode}\n手机:#{mobile}"
if delivery_areas.any?
string + ("\n宅送覆盖范围:" + delivery_areas.map(&:area).join(';'))
else
string
end
end
def self.human_attribute_name attribute, options = {}
{
service_code: '小站编号',
zipcode: '小站邮编',
contact: '小站负责人',
mobile: '小站电话',
address: '小站地址',
imei: '手机序列号',
extra_imeis: '额外序列号',
free_of_charge: "一直免费",
}[attribute] || super(attribute, options)
end
def full_address
"#{province}#{city}#{district} #{address}"
end
def deliveries_count
by_self + by_station + free_deliveries_count + charged_deliveries_count
end
private
def create_primary_app
apps << MobileApp.new(imei: imei, primary: true)
end
def modify_primary_app
app = apps.where(imei: imei).first
if app.present?
app.primary = true
app.save
if primary_app != app
primary_app.primary = false
primary_app.destroy
end
else
primary_app.imei = imei
primary_app.save
end
end
end
|
module TidyDesktop
# Adds daily tidy desktop job
class Cron
COMMAND = 'crontab'.freeze
def initialize(command)
@command = command
end
def output
"@daily /bin/bash -c '#{@command}'\n"
end
def uninstall!
crontab = current_crontab.delete_if { |a| a.include? @command.to_s }
save_cron(crontab.join, 'r+')
end
def install!
o = current_crontab.push(output)
save_cron(o.join, 'r+')
end
def installed?
`crontab -l`.include? @command
end
private
def save_cron(content, mode)
cmd = COMMAND + ' -'
IO.popen(cmd, mode) do |cron|
cron.write(content)
cron.close_write
end
if $CHILD_STATUS.exitstatus.zero?
else
puts 'Error writing to crontab'
end
end
def current_crontab
`crontab -l`.lines
end
end
end
|
class CreateOfCompaniesTypeOfCompanies < ActiveRecord::Migration
def change
if !table_exists? :of_companies_type_of_companies
create_table :of_companies_type_of_companies do |t|
t.integer :of_company_id
t.integer :type_of_company_id
t.timestamps
end
end
end
end
|
class ChangeTimeTypeInEntries < ActiveRecord::Migration
def change
change_column :account_entries, :time, :decimal
end
end
|
class Item_API < Grape::API
resource "items" do
helpers do
def item_params
ActionController::Parameters.new(params).permit(:description, :name, :price, :image)
end
def save_tags(item,tag_name)
tag = Tag.where(name: tag_name).first_or_create()
table_obj = ItemTag.create(tag_id: tag.id, item_id: item.id)
end
end
desc "get all items"
# /api/tags/
get do
item = Item.includes(:tags)
present item, with: Entities::Item
end
desc "create a document"
params do
requires :name, type: String
requires :price, type: Integer
optional :description, type: String
optional :image, type: String
optional :tags, type: Array
end
post do
item = Item.new(item_params)
if item.save
params[:tags].each do |tag_name|
save_tags(item,tag_name)
end
present item, Entities::Item
else
error!(item.errors.full_messages, 400)
end
end
end
end |
#We've decided to make the joins from (input/output) logical extensions to file format
# normalization paths one to many instead of many to many. So we can get rid of the join
# model and simply store the logical extension ids on the file format normalization path
# model itself.
class AddLogicalExtensionsToFileFormatNormalizationPaths < ActiveRecord::Migration[5.1]
def change
add_column :file_format_normalization_paths, :input_logical_extension_id, :integer
add_column :file_format_normalization_paths, :output_logical_extension_id, :integer
drop_table :file_format_normalization_paths_input_logical_extensions_joins
drop_table :file_format_normalization_paths_output_logical_extensions_joins
end
end
|
require 'app/apis/base_api'
require 'app/models/event'
require 'app/presenters/beer_presenter'
require 'app/presenters/brewery_presenter'
require 'app/presenters/event_presenter'
class EventsAPI < BaseAPI
get { EventsPresenter.new(Event.all, context: self, root: nil).present }
param :id do
let(:event) { Event.from_param(params[:id]) }
get { EventPresenter.new(event, context: self).present }
get :breweries do
BreweriesPresenter.new(event.breweries, context: self, root: nil).present
end
get :beers do
BeersPresenter.new(event.beers, context: self, root: nil).present
end
end
end
|
require_relative '../src/product'
require_relative 'spec_helper'
RSpec.describe Product, type: :model do
describe 'validations' do
subject { Product.new('Mega Coverage', -1, 80) }
it { should validate_presence_of(:name) }
it { should validate_presence_of(:sellIn) }
it { should validate_presence_of(:price) }
end
describe 'update_price' do
context 'when the product is Mega Coverage' do
subject { Product.new('Mega Coverage', -1, 80).update_price }
it 'never decreases price' do
expect(subject.price).to eq(80)
end
it 'never decreases days to sell' do
expect(subject.sellIn).to eq(-1)
end
end
context 'when the product is other than Mega Coverage' do
subject { Product.new('Low Coverage', 5, 7) }
it 'decreases the day to sell by 1' do
expect(subject.update_price.sellIn).to eq(4)
end
end
context 'when the product is Low Coverage or any other' do
it 'decreases price by 1 when has at least one day to sell' do
product = Product.new('Low Coverage', 5, 7)
expect(product.update_price.price).to eq(6)
product = Product.new('Low Coverage', 1, 7)
expect(product.update_price.price).to eq(6)
end
it 'decreases price by 2 when does not have days to sell' do
product = Product.new('Low Coverage', -5, 5)
expect(product.update_price.price).to eq(3)
product = Product.new('Low Coverage', -1, 3)
expect(product.update_price.price).to eq(1)
end
it 'sets price at 0 when it can not stay positive' do
product = Product.new('Low Coverage', -13, 2)
expect(product.update_price.price).to eq(0)
product = Product.new('Low Coverage', 0, 2)
expect(product.update_price.price).to eq(0)
end
end
context 'when the product is Super Sale' do
it 'decreases price by 2 when has many days to sell' do
product = Product.new('Super Sale', 5, 7)
expect(product.update_price.price).to eq(5)
end
it 'does not decrease price when has less than 0 days to sell' do
product = Product.new('Super Sale', -1, 0)
expect(product.update_price.price).to eq(0)
end
context 'when has 0 days to sell' do
it 'decreases price by 4 when price can stay positive' do
product = Product.new('Super Sale', 0, 4)
expect(product.update_price.price).to eq(0)
product = Product.new('Super Sale', 0, 5)
expect(product.update_price.price).to eq(1)
end
it 'sets price at 0 when it can not stay positive' do
product = Product.new('Super Sale', 0, 1)
expect(product.update_price.price).to eq(0)
product = Product.new('Super Sale', 0, 3)
expect(product.update_price.price).to eq(0)
end
end
end
context 'when the product is Full Coverage' do
it 'increases price by 1 when has at least one day left to sell' do
product = Product.new('Full Coverage', 2, 0)
expect(product.update_price.price).to eq(1)
end
it 'increases price by 2 when has less than one day left to sell' do
product = Product.new('Full Coverage', 0, 2)
expect(product.update_price.price).to eq(4)
end
it 'does not allow the price to be greater than 50' do
product = Product.new('Full Coverage', -3, 50)
expect(product.update_price.price).to eq(50)
product = Product.new('Full Coverage', -3, 49)
expect(product.update_price.price).to eq(50)
product = Product.new('Full Coverage', -3, 48)
expect(product.update_price.price).to eq(50)
end
end
context 'when the product is Special Full Coverage' do
it 'increases price by 1 when there are more than 10 days to sell' do
product = Product.new('Special Full Coverage', 13, 12)
expect(product.update_price.price).to eq(13)
product = Product.new('Special Full Coverage', 11, 12)
expect(product.update_price.price).to eq(13)
end
it 'increases price by 2 when there are 6 to 10 days to sell' do
product = Product.new('Special Full Coverage', 10, 12)
expect(product.update_price.price).to eq(14)
product = Product.new('Special Full Coverage', 7, 15)
expect(product.update_price.price).to eq(17)
product = Product.new('Special Full Coverage', 6, 14)
expect(product.update_price.price).to eq(16)
end
it 'increases price by 3 when there are 1 to 5 days to sell' do
product = Product.new('Special Full Coverage', 5, 12)
expect(product.update_price.price).to eq(15)
product = Product.new('Special Full Coverage', 3, 15)
expect(product.update_price.price).to eq(18)
product = Product.new('Special Full Coverage', 1, 14)
expect(product.update_price.price).to eq(17)
end
it 'keeps the price in 50 when days to sell is positive' do
product = Product.new('Special Full Coverage', 1, 49)
expect(product.update_price.price).to eq(50)
product = Product.new('Special Full Coverage', 7, 49)
expect(product.update_price.price).to eq(50)
end
it 'resets price to zero when days to sell is negative' do
product = Product.new('Special Full Coverage', 0, 50)
expect(product.update_price.price).to eq(0)
product = Product.new('Special Full Coverage', -1, 50)
expect(product.update_price.price).to eq(0)
end
end
end
end |
require 'gosu'
module Zindex
Background, Ballons, Player, Clouds, UI = *0..4
end
class GameWindow < Gosu::Window
attr_accessor :background_image, :fonts, :images, :player, :ballons, :timer, :game_over, :clouds
def initialize
super(1200, 900, false)
self.caption = 'Ballons vs Unicorn'
restart
play_song
end
def set_timer
Time.now.to_i + 11
end
def background
self.background_image = game_over ? images[:endscreen] : images[:rainbow]
background_image.draw(0, 0, Zindex::Background)
end
def images
@images ||= {
rainbow: Gosu::Image.new(self, "media/rainbow.jpg", true),
endscreen: Gosu::Image.new(self, "media/endscreen.jpg", true),
}
end
def fonts
@fonts ||= {
normal: Gosu::Font.new(self, Gosu::default_font_name, 20),
big: Gosu::Font.new(self, Gosu::default_font_name, 100)
}
end
def restart
self.game_over = false
self.player = Player.new(self)
self.ballons = []
self.timer = set_timer
self.clouds = [Cloud.new(self, :left), Cloud.new(self, :right)]
end
def update
if want_to_restart?
restart
elsif game_over
return
else
move_player
update_ballons
handle_clouds
end
play_song
end
def handle_clouds
if clouds.any? { |c| c.intersect?(player) }
player.slow_down
else
player.normal_speed
end
end
def update_ballons
player.collect_ballons(ballons)
if rand(100) < 4 && ballons.size < 25
ballons.push(Ballon.new(self))
end
end
def move_player
if button_down?(Gosu::KbLeft) || button_down?(Gosu::GpLeft)
player.turn_left
end
if button_down?(Gosu::KbRight) || button_down?(Gosu::GpRight)
player.turn_right
end
if button_down?(Gosu::KbUp) || button_down?(Gosu::GpButton0)
player.accelerate
end
player.move
end
def want_to_restart?
button_down? Gosu::KbReturn
end
def time_over?
timer <= Time.now.to_i
end
def draw
if time_over?
self.game_over = true
draw_game_over
else
draw_game
move_clouds
end
end
def move_clouds
clouds.each { |c| c.move }
clouds.each { |c| c.draw }
end
def time_left
fonts[:normal].draw(timer - Time.now.to_i, 1175, 2, Zindex::UI, 1.0, 1.0, 0xff5c00a1)
end
def draw_game
time_left
background
player.draw
ballons.each { |ballon| ballon.draw }
fonts[:normal].draw("Score: #{player.score}", 2, 2, Zindex::UI, 1.0, 1.0, 0xff5c00a1)
end
def draw_game_over
background
fonts[:normal].draw("Your score is: #{player.score}", 400, 350, Zindex::UI, 2.0, 2.0, 0xfff72eff)
fonts[:big].draw("Game Over", 320, 400, Zindex::UI, 1.0, 1.0, 0xffffffff)
fonts[:normal].draw("press ESC to exit or hit ENTER to restart", 330, 500, Zindex::UI, 1.0, 1.0, 0xffffffff)
end
def button_down(id)
close if id == Gosu::KbEscape
end
def play_song
Gosu::Song.new(self, 'media/bouncing.mp3').play unless Gosu::Song.current_song
end
end
class Player
attr_accessor :score, :speed
attr_reader :x, :y
def initialize(window)
@image = Gosu::Image::load_tiles(window, "media/unicorn_anim.png", 97, 101, false)
@plopp = Gosu::Sample.new(window, "media/plopp.wav")
@x = @y = @vel_x = @vel_y = @angle = 0.0
@score = 0
normal_speed
place_at(600, 450)
end
def collect_ballons(ballons)
!!ballons.reject! do |ballon|
Gosu::distance(@x, @y, ballon.x, ballon.y) < 60 and kill(ballon)
end
end
def kill(ballon)
self.score += ballon.points
@plopp.play
end
def place_at(x, y)
@x, @y = x, y
end
def turn_left
@angle -= 4.5
end
def turn_right
@angle += 4.5
end
def accelerate
@vel_x += Gosu::offset_x(@angle, 0.5)
@vel_y += Gosu::offset_y(@angle, 0.5)
end
def move
@x += @vel_x
@y += @vel_y
@x %= 1200
@y %= 900
@vel_x *= speed
@vel_y *= speed
end
def normal_speed
self.speed = 0.95
end
def slow_down
self.speed = 0.45
end
def draw
img = @image[Gosu::milliseconds / 100 % @image.size];
img.draw_rot(@x, @y, 1, @angle)
end
end
class Cloud
attr_reader :x, :y, :window, :direction
def initialize(window, direction)
@window = window
@x = 0
@y = rand(800) + 50
@direction = direction
@speed = rand(5)+3
end
def move
if direction == :right
@x += @speed
@x %= 1200 if @x > 1200
else
@x -= @speed
@x %= 1200 if @x < 0
end
end
def intersect?(player)
Gosu::distance(@x, @y, player.x, player.y) < 90
end
def draw
img = Gosu::Image.new(window, "media/cloud.png", true)
img.draw(@x - img.width / 2.0, @y - img.height / 2.0, Zindex::Clouds, 1, 1)
end
end
class Ballon
attr_reader :x, :y, :window, :animation, :type
def initialize(window)
@window = window
@x = rand * 1200
@y = rand * 900
@type = random_type
@animation = animation_from_type
end
def points
{ green: 5, magenta: 1 }[type]
end
def draw
img = animation[Gosu::milliseconds / 100 % animation.size];
img.draw(@x - img.width / 2.0, @y - img.height / 2.0, Zindex::Ballons, 1, 1)
end
private
def animation_from_type
Gosu::Image::load_tiles(window, "media/ballons_#{type}.png", 50, 60, false)
end
def random_type
@room ||= [:magenta, :magenta, :magenta, :magenta, :green]
@room.sample
end
end
window = GameWindow.new
window.show
|
require 'formula'
class Winexe < Formula
url 'http://sourceforge.net/projects/winexe/files/winexe-1.00.tar.gz'
homepage 'http://sourceforge.net/projects/winexe/'
md5 '48325521ddc40d14087d1480dc83d51e'
def patches
# This patch removes second definition of event context, which *should* break the build virtually everywhere,
# but for some reason it only breaks it on OS X.
#
# There are several instructions over the Internet on how to build winexe for OS X, all of them
# share the same patch, so original author is unknown. One of the sources:
#
# http://miskstuf.tumblr.com/post/6840077505/winexe-1-00-linux-macos-windows-7-finally-working
#
{:p1 => 'https://raw.github.com/gist/1294786/winexe.patch'}
end
def install
Dir.chdir "source4" do
system "./autogen.sh"
system "./configure", "--enable-fhs"
system "make basics idl bin/winexe"
bin.install "bin/winexe"
end
end
end
|
require 'spec_helper'
describe Luego::Delegate do
it "should take an object when initialised" do
Luego::Delegate.new("hello")
end
it "should not delegate methods until delegate! is called" do
string = Luego::Delegate.new("hello world")
lambda { string.upcase }.should raise_error NoMethodError
string.delegate!
string.upcase.should == "HELLO WORLD"
end
it "should offer its own methods for handling the delegation" do
d = Luego::Delegate.new(nil)
d.delegating?.should == false
d.delegate!
d.delegating?.should == true
d.undelegate!
d.delegating?.should == false
end
it "should stop delegating when undelegate! is called" do
string = Luego::Delegate.new("hello world")
string.delegate!
string.should be_a String
string.should_not be_a Luego::Delegate
end
it "should be equal to the child object when delegating" do
child = "hello world"
delegate = Luego::Delegate.new(child)
delegate.delegate!
delegate.should === child
delegate.should eql child
delegate.should be_equal child
end
it "should completely delegate all methods" do
s = "hello world"
clone = Luego::Delegate.new(s.dup)
clone.delegate!
s.public_methods.each do |m|
s.should be_a_kind_of clone.method(m).owner # ensure method comes (a superclass of) String
end
end
end
|
# frozen_string_literal: true
# QueryObjectBase
class QueryObjectBase
def initialize(repository)
@repository = repository
end
end
|
class UserReportsController < ApplicationController
def show
@user_report = UserReport.find(params[:id])
end
def edit
@user_report = UserReport.find(params[:id])
@report_options = Report.all.map {|r| [r.name, r.id ]}
end
def update
@user_account = UserAccount.find(params[:id])
@user_report = UserReport.find(params[:id])
@user_report.update_attributes(user_report_params)
if @user_report.save
redirect_to @user_account
end
end
private
def user_report_params
params.require(:user_report).permit(:completed, :completed_at, :picture)
end
end
|
class Client < ApplicationRecord
before_create :create_unique_key
belongs_to :user
has_many :gadgets
validates :name, :presence => true, :uniqueness => {:scope => :user}
def create_unique_key
begin
self.key = SecureRandom.base64(12)
end while self.class.exists?(:key => key)
end
def connected
self.connection_state = true
self.save
ClientConStateChangeBroadcastJob.perform_now self.connection_state, self.name, self.user
end
def disconnected
self.connection_state = false
self.save
ClientConStateChangeBroadcastJob.perform_now self.connection_state, self.name, self.user
end
end
|
class V1::FeedbacksController < ApplicationController
skip_before_action :authenticate_user!, only: [:create]
def index
project = Project.find(params[:project_id])
@feedbacks = project.feedbacks.except_archived.filterable(params[:filter], project)
end
def create
project = Project.find(params[:project_id])
tag = project.tags.find_by!(name: params[:tag])
@feedback = tag.feedbacks.build(feedback_params)
@feedback.project_id = project.id
if @feedback.save
render :new, status: :created
project.team_members.each { |user| user.send_feedback_mail(@feedback) }
else
render json: { message: @feedback.errors }, status: :bad_request
end
end
def archive
project = Project.find(params[:project_id])
archive_tag = project.tags.find_by(name: 'Archive')
feedback = project.feedbacks.find(params[:id])
if feedback.archived?
feedback.update(archived: false)
else
feedback.update(archived: true)
end
end
def destroy
project = Project.find(params[:project_id])
return error('unauthorized') unless team_has_access?(project.team_members)
feedback = project.feedbacks.find(params[:id])
feedback.destroy
end
private
def feedback_params
params.require(:feedback).permit(
:content,
:sender_email,
:page_url,
:device
)
end
end
|
class Kunde
attr_accessor:name
attr_writer :adresse
def initialize(pname)
@name = pname
@kredite = []
end
def set_kredit(pkredit)
@kredite << pkredit
end
def show_kredite
puts "#{@name}, #{@adresse} hat folgende Kredite:"
@kredite.each.with_index(1) do |value, key|
puts "Kredit #{key}: #{value.wert}"
end
end
end
class Kredit
attr_accessor :wert
def initialize(pwert)
@wert = pwert
end
end
# kunde1=Kunde.new("Kim Kunde")
# kunde1.name = "Theo Sommer"
# puts kunde1.name
# kunde1.adresse = "Hermelinweg 11, 22159 Hamburg"
# kredit1=Kredit.new(5000)
# kredit2=Kredit.new(2000)
# kunde1.set_kredit(kredit1)
# kunde1.set_kredit(kredit2)
|
#[5.1]イントロダクション
#配列と同様、ハッシュも使用頻度の高いオブジェクトです。本格的なRubyプログラミングを書く上では避けて通ることはできません。
#また、シンボルは少し変わったデータ型で、最初は文字列と混同してしまうかもしれませんが、こちらも使用頻度が高いデータ型なので、しっかり理解していきましょう。
#---------------------------------------------------------------------------------------------------------------------------------------------------------
#[5.1.1]この章の例題:長さの単位変換プログラム
#この章では長さの単位を変換するプログラムを作成します。このプログラムを通じてハッシュの使い方を学びます。
#長さの単位変換プログラムの仕様は次の通りです。
#・メートル(m)、フィート(ft)、インチ(in)の単位を交互に変換する。
#・第一引数に変換元の長さ(数値)、第二引数に変換元の単位、第三引数に変換後の単位を指定する。
#・メソッドの戻り値は変換後の長さ(数値)とする。端数が出る場合は少数第3位で四捨五入する。
#----------------------------------------------------------------------------------------------------------------------------------------------------------
#[5.1.2]長さの単位変換プログラムの実行例
# EX 実行例(初期バージョン)
convert_length(1, 'm', 'in')
# ==> 39.37
convert_length(15, 'in', 'm')
# ==> 0.38
convert_length(35000, 'ft', 'm')
# ==> 10670.73
#なお、上の実行例は初期バージョンで、実装したらそこから徐々に引数の指定方法を改善していきます。
#---------------------------------------------------------------------------------------------------------------------------------------------------------
#[5.1.3]この章で学ぶこと
# ・ハッシュ
# ・シンボル
#冒頭でも述べた通り、ハッシュもシンボルもRubyプログラムに頻繁に登場するデータ型です。
#この章の内容を理解して、ちゃんと使いこなせるようになりましょう。
#--------------------------------------------------------------------------------------------------------------------------------------------------------- |
class Paper < Theme
name "Paper"
author "DarkPreacher"
homepage "https://github.com/DarkPreacher/tt-rss-theme-paper"
repo "git@github.com:DarkPreacher/tt-rss-theme-paper.git"
screenshot "https://raw.github.com/DarkPreacher/tt-rss-theme-paper/master/paper-previews/paper-combined-auto-expand.jpg"
install do |remote_theme_directory|
remote_theme_directory.upload "stylesheets/paper.css", as: "paper.css"
remote_theme_directory.upload "stylesheets/paper/", as: "paper/"
end
end
|
module Reports
class DeploymentCostReport
attr_reader :costs, :clouds
def initialize(report)
@report = report
@user_currency = @report.user.currency
Time.zone = @report.user.timezone
@deployment = @report.reportable
@costs = []
# Cache all clouds to avoid individual DB calls during calculations
@clouds = {}
Cloud.all.each{|c| @clouds[c.id] = c}
current_date = @report.start_date
while current_date <= @report.end_date
@costs << {:timestamp => current_date,
:year => current_date.strftime("%Y"),
:month => current_date.strftime("%b-%Y"),
:instance_hour => 0.0,
:storage_size => 0.0,
:read_request => 0.0,
:write_request => 0.0,
:transaction => 0.0,
:data_in => 0.0,
:data_out => 0.0,
:additional_cost => 0.0}
current_date += 1.months
end
end
def xml
do_servers_storages_database_resources
do_data_transfers
do_additional_costs
cost = 0.0
deployment = ""
@costs.each do |month|
monthly_cost = (month[:instance_hour] + month[:storage_size] + month[:read_request] + month[:write_request] +
month[:transaction] + month[:data_in] + month[:data_out] + month[:additional_cost]).round(2)
cost += monthly_cost
deployment << "<row>" +
"<year>#{month[:year]}</year>" +
"<month>#{month[:month]}</month>" +
"<instance_hour>#{month[:instance_hour].round(2)}</instance_hour>" +
"<storage_size>#{month[:storage_size].round(2)}</storage_size>" +
"<read_request>#{month[:read_request].round(2)}</read_request>" +
"<write_request>#{month[:write_request].round(2)}</write_request>" +
"<transaction>#{month[:transaction].round(2)}</transaction>" +
"<data_in>#{month[:data_in].round(2)}</data_in>" +
"<data_out>#{month[:data_out].round(2)}</data_out>" +
"<additional_cost>#{month[:additional_cost].round(2)}</additional_cost>" +
"<total>#{monthly_cost}</total>" +
"</row>"
end
require 'money'
require 'money/bank/google_currency'
@deployment.cost = cost.round(2)
@deployment.save
xml = "<deployment>"
xml << "<user_currency>#{Money::Currency.table.select{|k,v| v[:iso_code] == @user_currency}.values.first[:name]} (#{@user_currency})</user_currency>"
xml << "<cost>#{@deployment.cost}</cost>"
xml << "#{deployment}</deployment>"
xml
end
def do_additional_costs
@deployment.additional_costs.all(:include => :patterns).each do |additional_cost|
# Get the values from the patterns
additional_cost_values = get_monthly_values(additional_cost, 'cost')
@costs.each_with_index do |month, i|
month[:additional_cost] += additional_cost_values[i].to_f
end
end
end
# Algorithm:
#data_in_for_clouds = {}
#data_out_for_clouds = {}
#Go through all data links
# get_source/dest_clouds
# if source and target are on diff clouds or either are a remote_node
# add source_to_dest data to source-clouds data_out unless source is remote_node
# add source_to_dest data to desti-clouds data_in unless desti is remote_node
#
# add dest_to_source data to dest-clouds data_out unless desti is remote_node
# add dest_to_source data to source-clouds data_in unless source is remote_node
# end
#
# Get the CCS with cloud_id and cloud_resource_type_id nil
# Go through it and find the data_in/out struct.
# Calculate data_in/data_out costs for each cloud based on tiers
def do_data_transfers
data_transfer = { 'data_in' => {}, 'data_out' => {}}
@deployment.data_links.all(:include => [:sourcable, :targetable, :patterns]).each do |data_link|
src = data_link.sourcable
src_cloud = src.is_a?(RemoteNode) ? 'remote' : src.cloud_id if not src.nil?
dest = data_link.targetable
dest_cloud = dest.is_a?(RemoteNode) ? 'remote' : dest.cloud_id if not dest.nil?
if src_cloud != dest_cloud
src_to_dest_values = get_monthly_values(data_link, 'source_to_target')
dest_to_src_values = get_monthly_values(data_link, 'target_to_source')
# Protect users from creating stupid patterns that set values to less than 0
@costs.each_with_index do |month, i|
src_to_dest_values[i] = 0 if src_to_dest_values[i] < 0
dest_to_src_values[i] = 0 if dest_to_src_values[i] < 0
end
data_transfer['data_in'][src_cloud] ||= Array.new(@costs.length){0}
data_transfer['data_out'][src_cloud] ||= Array.new(@costs.length){0}
data_transfer['data_in'][dest_cloud] ||= Array.new(@costs.length){0}
data_transfer['data_out'][dest_cloud] ||= Array.new(@costs.length){0}
# add src_to_dest data to source-clouds data_out
data_transfer['data_out'][src_cloud] = data_transfer['data_out'][src_cloud].zip(src_to_dest_values).map{|pair| pair.sum}
# add src_to_dest data to dest-clouds data_in
data_transfer['data_in'][dest_cloud] = data_transfer['data_in'][dest_cloud].zip(src_to_dest_values).map{|pair| pair.sum}
# add dest_to_source data to dest-clouds data_out
data_transfer['data_out'][dest_cloud] = data_transfer['data_out'][dest_cloud].zip(dest_to_src_values).map{|pair| pair.sum}
# add dest_to_source data to source-clouds data_in
data_transfer['data_in'][src_cloud] = data_transfer['data_in'][src_cloud].zip(dest_to_src_values).map{|pair| pair.sum}
end
end
# Delete RemoteNode placeholders from hash as they are not clouds
data_transfer.each{|k, v| v.delete('remote')}
data_transfer.each do |k, v|
v.each do |cloud_id, values|
cloud = @clouds[cloud_id]
first_server_type = ServerType.first(:include => [:clouds], :conditions => ["clouds.id = ?", cloud_id])
if first_server_type
price_details = get_price_details(cloud.id, first_server_type.id, k)
unless price_details.empty?
@costs.each_with_index do |month, i|
cost = get_tiered_cost(values[i], price_details[:units], price_details[:tiers])
cost += price_details[:recurring_cost_values][i]
month[k.to_sym] += cost.to_money(cloud.billing_currency).exchange_to(@user_currency).to_f
end
end
end
end
end
end
# Algorithm:
# Calculate the monthly_total usages (value * quantity) of each CloudResourceType in the deployment
# This is the structure of depl_resource_types hash:
# [CloudResourceType.id][Cloud.id][CloudCostStructure.name][:values] = array_of_monthly_totals
# [CloudResourceType.id][Cloud.id][CloudCostStructure.name][:quantity_values] = array_of_monthly_quantity
# Go through all CloudResourceTypes
# Go through all of the Clouds
# Go through all of the CloudCostStructures
# Go through all of the monthly_totals
# Calculate the tiered cost of that month including any recurring_costs for that CloudCostStructure
# Convert the cost from Cloud billing_currency to user_currency and add it to the @costs array for that month
def do_servers_storages_database_resources
depl_resource_types = {}
(@deployment.servers.all(:include => :patterns) + @deployment.storages.all(:include => :patterns) +
@deployment.database_resources.all(:include => :patterns)).each do |resource|
cloud = @clouds[resource.cloud_id]
depl_resource_type_id = case resource.class.to_s
when 'Server'
resource.server_type_id
when 'Storage'
resource.storage_type_id
when 'DatabaseResource'
resource.database_type_id
end
depl_resource_types[depl_resource_type_id] ||= {}
depl_resource_types[depl_resource_type_id][cloud.id] ||= {}
['instance_hour', 'transaction', 'storage_size', 'read_request', 'write_request'].each do |ccs_name|
# Skip this ccs_name if the resource doesn't have it
next unless resource.respond_to?("#{ccs_name}_monthly_baseline")
values = get_monthly_values(resource, ccs_name)
quantity_values = get_monthly_values(resource, 'quantity')
depl_resource_types[depl_resource_type_id][cloud.id][ccs_name] ||= {}
depl_resource_types[depl_resource_type_id][cloud.id][ccs_name][:values] ||= Array.new(@costs.length){0}
depl_resource_types[depl_resource_type_id][cloud.id][ccs_name][:quantity_values] ||= Array.new(@costs.length){0}
@costs.each_with_index do |month, i|
# A month has max number of hours, enforce this in case user patterns accidentally make it go over this value
if ccs_name == 'instance_hour'
hours_in_month = 24 * Time.days_in_month(month[:timestamp].month, month[:timestamp].year)
values[i] = hours_in_month if values[i] > hours_in_month
end
# Protect users from creating stupid patterns that set values to less than 0
values[i] = 0 if values[i] < 0
quantity_values[i] = 0 if quantity_values[i] < 0
depl_resource_types[depl_resource_type_id][cloud.id][ccs_name][:values][i] += (values[i] * quantity_values[i])
depl_resource_types[depl_resource_type_id][cloud.id][ccs_name][:quantity_values][i] += quantity_values[i]
end
end
end
depl_resource_types.each do |depl_resource_type_id, cloud_ids|
cloud_ids.each do |cloud_id, ccs_names|
cloud = @clouds[cloud_id]
ccs_names.each do |ccs_name, values_hash|
price_details = get_price_details(cloud_id, depl_resource_type_id, ccs_name)
unless price_details.empty?
if price_details[:custom_algorithm]
self.send("do_#{price_details[:custom_algorithm]}")
else
@costs.each_with_index do |month, i|
# No need to multiply the quantity again as values[i] already has the total usage
usage = values_hash[:values][i]
cost = get_tiered_cost(usage, price_details[:units], price_details[:tiers])
recurring_cost = price_details[:recurring_cost_values][i] * values_hash[:quantity_values][i]
total_cost = cost + recurring_cost
month[ccs_name.to_sym] += total_cost.to_money(cloud.billing_currency).exchange_to(@user_currency).to_f
end
end
end
end
end
end
end
# Custom algorithm for SQL Azure costs:
# Go though all database_resources in deployment
# Get storage_size, instance_hour and quantity values
# Go through all monthly_values
# Validate values
# Calculate tiered cost
# Calculate recurring cost
# Add total_cost to monthly cost
def do_sql_azure
@deployment.database_resources.all(:include => :patterns).each do |resource|
cloud = @clouds[resource.cloud_id]
price_details = get_price_details(resource.cloud_id, resource.database_type_id, 'storage_size')
storage_size_values = get_monthly_values(resource, 'storage_size')
instance_hour_values = get_monthly_values(resource, 'instance_hour')
quantity_values = get_monthly_values(resource, 'quantity')
@costs.each_with_index do |month, i|
# Protect users from creating stupid patterns that set invalid values
days_in_month = Time.days_in_month(month[:timestamp].month, month[:timestamp].year)
hours_in_month = 24 * days_in_month
instance_hour_values[i] = hours_in_month if instance_hour_values[i] > hours_in_month
instance_hour_values[i] = 0 if instance_hour_values[i] < 0
storage_size_values[i] = 0 if storage_size_values[i] < 0
quantity_values[i] = 0 if quantity_values[i] < 0
if instance_hour_values[i] == 0
cost = 0
else
# Amortize storage_size cost over the days that storage was used in that month
cost = get_tiered_cost(storage_size_values[i], price_details[:units], price_details[:tiers]) *
((instance_hour_values[i] / 24).ceil / days_in_month.to_f)
end
cost *= quantity_values[i]
recurring_cost = price_details[:recurring_cost_values][i] * quantity_values[i]
total_cost = cost + recurring_cost
month[:instance_hour] += total_cost.to_money(cloud.billing_currency).exchange_to(@user_currency).to_f
end
end
end
# Returns a hash that has the custom_algorithm, tiers, units, recurring_costs of the cloud_cost_structure name
# for the specified resource_type in the specified cloud
def get_price_details(cloud_id, cloud_resource_type_id, ccs_name)
results = {}
# Find all CloudCostSchemes in the cloud
ccs = CloudCostScheme.all(
:conditions => ["cloud_id = ? AND cloud_resource_type_id = ?", cloud_id, cloud_resource_type_id],
:include => :cloud_cost_structure) # Don't include tiers as we need to order them and we can't do it here
# Find relevant CloudCostStructures (i.e. they match the name and are still valid)
price_type_ccs = ccs.select{|c| c.cloud_cost_structure.name == ccs_name && c.cloud_cost_structure.valid_until.nil?}.first
if price_type_ccs
price_type_ccs = price_type_ccs.cloud_cost_structure
results[:custom_algorithm] = price_type_ccs.custom_algorithm
results[:tiers] = price_type_ccs.cloud_cost_tiers.order("upto ASC") # Get all the tiers, we'll process them later
price_type_ccs.units =~ /\Aper\.(\d+)\..*\z/i
results[:units] = $1.to_f
results[:recurring_cost_values] = get_monthly_values(price_type_ccs, 'recurring_costs')
end
results
end
# The cost_units is the value of X in the units field, e.g. per.X.requests
def get_tiered_cost(total_usage, cost_units, ordered_tiers)
raise AppExceptions::InvalidParameter.new("ordered_tiers cannot be empty") if ordered_tiers && ordered_tiers.empty?
total_usage = total_usage.to_f # force into float to make sure .ceil works as expected
cost = 0.0
i = 0
while total_usage > 0
usage = total_usage
if ordered_tiers[i].upto
# If total_usage is less than upto then use that, otherwise calculate
# the diff between this tier and the last tier (if there is one)
usage = [total_usage, ordered_tiers[i].upto - (i > 0 ? ordered_tiers[i-1].upto : 0)].min
end
total_usage -= usage
cost += (usage / cost_units).ceil * ordered_tiers[i].cost
i += 1
# Deal with special case when there is no catch-all tier (upto nil), shouldn't happen in practice
return cost if i == ordered_tiers.length
end
cost
end
# Since the resource includes its patterns, this method of getting the patterns is more efficient that
# going through the resource.get_patterns method
def get_sorted_patterns(resource, attribute)
patterns = resource.pattern_maps.select{|pm| pm.patternable_attribute == attribute}
patterns.sort_by{|pm| pm.position}
patterns = patterns.collect{|pm| pm.pattern}
patterns
end
# Helper method to get monthly values for an attribute of resource
def get_monthly_values(resource, attribute)
PatternsEngine.get_pattern_results(resource.send("#{attribute}_monthly_baseline"),
get_sorted_patterns(resource, "#{attribute}_monthly_baseline"),
"Month",@report.start_date, @report.end_date)
end
end
end
|
class AddContentFragmentIdsToSentEmailMessages < ActiveRecord::Migration
def up
add_column :sent_email_messages, :content_fragment_ids, :string
end
def down
remove_column :sent_email_messages, :content_fragment_ids
end
end
|
require File.expand_path(File.join(File.dirname(__FILE__), '..', '..', 'test_helper' ))
class AnExistingForumWithBoards < ActionController::IntegrationTest
def setup
factory_scenario :site_with_forum
login_as :admin
@board = Factory :board, :site => @site, :section => @forum
end
def test_an_admin_creates_a_new_board
# Go to section
get admin_boards_path(@site, @forum)
# Admin clicks link create a new board
click_link 'Create a new board'
assert Board.count == 1
assert_template 'admin/boards/new'
fill_in 'Title', :with => 'Test board'
fill_in 'Description', :with => 'Test board description'
click_button 'Save'
assert Board.count == 2
assert_template 'admin/boards/index'
end
def test_an_admin_edits_a_board
assert Board.count == 1
assert @board.title != 'Test board update'
# Go to section
get admin_boards_path(@site, @forum)
# Admin clicks link to edit board
click_link 'Edit'
assert_template 'admin/boards/edit'
fill_in 'Title', :with => 'Test board update'
fill_in 'Description', :with => 'Test board description'
click_button 'Save'
@board.reload
assert Board.count == 1
assert @board.title == 'Test board update'
assert_template 'admin/boards/index'
end
def test_an_admin_deletes_the_board
assert Board.count == 1
# Go to section
get admin_boards_path(@site, @forum)
# Admin clicks link to delete a board
click_link 'Delete'
assert Board.count == 0
assert_template 'admin/boards/index'
end
end |
require 'uri'
class Params
# use your initialize to merge params from
# 1. query string
# 2. post body
# 3. route params
def initialize(req, route_params = {})
@params = route_params
parse_www_encoded_form(req.body) if req.body
parse_www_encoded_form(req.query_string) if req.query_string
@permitted_keys = []
end
def [](key)
@params[key]
end
def permit(*keys)
@permitted_keys += @params.keys.select { |key| keys.include?(key) }
end
def require(key)
raise AttributeNotFoundError unless @params.keys.include?(key)
end
def permitted?(key)
@permitted_keys.include?(key)
end
def to_s
@params.to_s
end
class AttributeNotFoundError < ArgumentError; end;
private
# this should return deeply nested hash
# argument format
# user[address][street]=main&user[address][zip]=89436
# should return
#
# { "user" => { "address" => { "street" => "main", "zip" => "89436" } } }
def parse_www_encoded_form(www_encoded_form)
decoded_url = URI.decode_www_form(www_encoded_form)
decoded_url.each do |arr|
arr.map! { |el| parse_key(el) }
end
decoded_url.each do |data|
path, value = data
new_params = { path.pop => value.first }
until path.empty?
new_params = { path.pop => new_params }
end
deep_merge(@params, new_params)
end
@params
end
def deep_merge(hash1, hash2)
hash2.each do |key, value|
if hash1.keys.include?(key)
deep_merge(hash1[key], value)
else
hash1[key] = value
end
end
hash1
end
# this should return an array
# user[address][street] should return ['user', 'address', 'street']
def parse_key(key)
key.split('[').map { |k| k.gsub(']', '') }
end
end |
require "spec_helper"
describe Deal do
specify { expect(described_class.constants).to include :State }
context "When asking for the retailer name and logo" do
it "should only query the store service once" do
mock_deal_store = double('store_service_id' => 123, "name" => "Wittner", "_links" => double({'logo' => double({'href' => "http://example.com/wittner.jpg"})}))
StoreService.should_receive(:fetch).with(123).once.and_return("STORE_SERVICE")
StoreService.should_receive(:build).with("STORE_SERVICE").once.and_return(mock_deal_store)
deal = Deal.new(deal_stores:[mock_deal_store])
deal.retailer_logo_url
deal.store_name
end
end
it "should get the store name" do
mock_deal_store = double('store_service_id' => 123, "name" => "Wittner")
StoreService.should_receive(:fetch).with(123).once.and_return("STORE_SERVICE")
StoreService.should_receive(:build).with("STORE_SERVICE").once.and_return(mock_deal_store)
deal = Deal.new(deal_stores:[mock_deal_store])
expect(deal.store_name).to eql("Wittner")
end
it "should get the retailer logo url" do
deal = Deal.new
deal.stub(:store).and_return double(
"has_logo?" => true,
"logo" => "http://example.com/wittner.jpg"
)
expect(deal.logo).to eql("http://example.com/wittner.jpg")
end
describe "#published?" do
subject { deal.published? }
context %q{when deal is neither 'scheduled' nor 'live'} do
let(:deal) { Deal.new state: 'pending_approval' }
it { should_not be_true }
end
context %q{when deal is 'scheduled'} do
let(:deal) { Deal.new state: 'scheduled' }
it { should be_true }
end
context %q{when deal is 'live'} do
let(:deal) { Deal.new state: 'live' }
it { should be_true }
end
end
end
|
class Card
attr_accessor :rank, :suit
def initialize(rank, suit)
self.rank = rank
self.suit = suit
end
def output_card
puts "#{self.rank} of #{self.suit}"
end
def self.random_card
Card.new(rand(10), :spades)
end
end
class Deck
def initialize
@cards = []
@suits = [:Diamonds, :Hearts, :Spades, :Clubs]
@rank = [:A, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, :Jack, :Queen, :King]
@suits.each do |suit|
@rank.each do |rank|
@cards << Card.new(rank, suit)
end
end
def shuffle
@cards.shuffle!
end
def shift
@cards.shift
end
def output
@cards.each do |card|
card.output_card
end
end
end
end
deck = Deck.new
deck.shuffle
deck.shift
puts "This is the card removed:"
removed = deck.shift
removed.output_card
puts "This is the shuffled deck:"
deck.output |
module CalculationSupport
def retrofit_calculation(field, strict: true, **options)
calculations_set = measure.run_retrofit_calculations(
strict: strict,
**options)
expect(calculations_set.errors_hash[field]).to be_nil
calculations_set.get_calculation_value(field)
end
def should_get_component_field_value(field, inputs, expected_value)
value = value_for_calculation(field, inputs)
expect(value).to be_within(0.1).of(expected_value)
@example.metadata[:description] = "gets #{field}" if @example
end
def should_get_cost_of_measure(value, **options)
should_get_field_value(:cost_of_measure, value, options)
end
def should_get_cost_savings(value, **options)
should_get_field_value(:annual_cost_savings, value, options)
end
def should_get_electric_savings(value, **options)
should_get_field_value(:annual_electric_savings, value, options)
end
def should_get_field_value(field, expected_value, **options)
options.merge!(
before_inputs: before_inputs,
after_inputs: after_inputs,
shared_inputs: shared_inputs)
value = retrofit_calculation(field, options)
if expected_value.nil?
expect(value).to be_nil
else
expect(value).to be_within(0.1).of(expected_value)
end
@example.metadata[:description] = "gets #{field}" if @example
end
def should_get_gas_savings(value, **options)
should_get_field_value(:annual_gas_savings, value, options)
end
def should_get_oil_savings(value, **options)
should_get_field_value(:annual_oil_savings, value, options)
end
def should_get_water_savings(value, **options)
should_get_field_value(:annual_water_savings, value, options)
end
def should_get_years_to_payback(value, **options)
should_get_field_value(:years_to_payback, value, options)
end
def value_for_calculation(field, inputs)
inputs = Kilomeasure::InputsFormatter.new(
inputs: inputs,
measure: measure).inputs
calculations_set = measure.run_calculations(
inputs: inputs)
calculations_set[field]
end
end
|
class Expense < ApplicationRecord
self.inheritance_column = :_type_disabled
belongs_to :user
validates_presence_of :name,:expense_date, :type, message: "field required"
validates :amount, numericality: { only_integer: true }
end
|
# =============================================================================
#
# MODULE : test/test_concurrent_queue.rb
# PROJECT : DispatchQueue
# DESCRIPTION :
#
# Copyright (c) 2016, Marc-Antoine Argenton. All rights reserved.
# =============================================================================
require '_test_env.rb'
module DispatchQueue
describe ConcurrentQueue do
let( :task_count ) { 10 }
let( :log ) { [] }
let( :lock ) { Mutex.new }
let( :logger ) { Proc.new { |e, d| lock.synchronize { log << [e, d] } } }
subject { ConcurrentQueue.new }
it "can initialize a serial queue" do
subject.must_be_instance_of ConcurrentQueue
end
def task( task_id )
logger.call( :begin_task, { task_id:task_id, thread:Thread.current } )
sleep(0.001)
logger.call( :end_task, { task_id:task_id, thread:Thread.current } )
end
describe "dispatch_async" do
it "executes tasks concurrently" do
(1..task_count).each { |i| subject.dispatch_async { task( i ) } }
subject.dispatch_barrier_sync {} # wait for all previous tasks to complete
running_count = 0
parallel_task_count = log.map do |e,d|
running_count += 1 if e == :begin_task
running_count -= 1 if e == :end_task
running_count
end
parallel_task_count.max.must_be :>, 1, parallel_task_count
end
it "preserves ordering arround barrier" do
(1..task_count).each { |i| subject.dispatch_async { task( "a#{i}".to_sym ) } }
subject.dispatch_barrier_async { task( "b0".to_sym ) }
(1..task_count).each { |i| subject.dispatch_async { task( "c#{i}".to_sym ) } }
subject.dispatch_barrier_async { task( "d0".to_sym ) }
subject.dispatch_barrier_sync {} # wait for all previous tasks to complete
task_id_list = log.select { |e,d| e == :begin_task }.map { |e,d| d[:task_id] }
task_chunks = task_id_list.chunk { |e| e.to_s[0] }.map { |c, l| l }
task_chunks.count.must_be :==, 4, task_chunks
end
it "resumes execution after synchronous barrier" do
(1..task_count).each { |i| subject.dispatch_async { task( "a#{i}".to_sym ) } }
subject.dispatch_barrier_sync { task( "b0".to_sym ) }
(1..task_count).each { |i| subject.dispatch_async { task( "c#{i}".to_sym ) } }
subject.dispatch_barrier_sync { task( "d0".to_sym ) }
subject.dispatch_barrier_sync {} # wait for all previous tasks to complete
task_id_list = log.select { |e,d| e == :begin_task }.map { |e,d| d[:task_id] }
task_chunks = task_id_list.chunk { |e| e.to_s[0] }.map { |c, l| l }
task_chunks.count.must_be :==, 4, task_chunks
end
end
describe "with multiple concurrent queues" do
let( :subject2 ) { ConcurrentQueue.new }
it "interleaves barrier tasks from different queues" do
(1..task_count).each { |i| subject.dispatch_barrier_async { task( "a#{i}".to_sym ) } }
(1..task_count).each { |i| subject2.dispatch_barrier_async { task( "b#{i}".to_sym ) } }
subject.dispatch_barrier_sync {} # wait for all previous tasks to complete
subject2.dispatch_barrier_sync {} # wait for all previous tasks to complete
task_id_list = log.select { |e,d| e == :begin_task }.map { |e,d| d[:task_id] }
task_chunks = task_id_list.chunk { |e| e.to_s[0] }.map { |c, l| l }
task_chunks.count.must_be :>, 3, task_chunks
end
end
end
end
|
require 'rails_helper'
describe StructureCombiner do
before do
create(:structure_type, name: 'Lighting', api_name: 'lighting')
end
let!(:json_structures) do
[
{ id: SecureRandom.uuid,
name: 'Hallway lights',
structure_type: { name: 'Lighting', api_name: 'lighting' },
n_structures: 4,
sample_group_id: 'foo',
field_values: {
lamp_type: {
name: 'Lamp type',
value: 'type1',
value_type: 'string' }
}
},
{ id: SecureRandom.uuid,
name: 'Kitchen lights',
structure_type: { name: 'Lighting', api_name: 'lighting' },
n_structures: 2,
sample_group_id: 'foo',
field_values: {
lamp_type: {
name: 'Lamp type',
value: 'type1',
value_type: 'string' }
}
}
]
end
let!(:structures) do
json_structures.map { |json| Wegoaudit::Structure.new(json) }
end
let!(:combiner) { described_class.new(structures) }
describe '#combined_structures' do
it 'returns a structure' do
structure = combiner.combined_structures
expect(structure.class).to eq(Wegoaudit::Structure)
end
it 'sums n_structures across the provided structures' do
structure = combiner.combined_structures
expect(structure.n_structures).to eq 6
end
it 'calls FieldValuesCombiner with field_values for each structure' do
field_values = {
lamp_type: {
name: 'Lamp type',
value: 'type1',
value_type: 'string'
}
}
structure_field_values = [field_values, field_values]
field_values_combiner = instance_double(FieldValuesCombiner)
expect(FieldValuesCombiner).to receive(:new).with(structure_field_values)
.and_return(field_values_combiner)
expect(field_values_combiner).to receive(:combined_field_values)
combiner.combined_structures
end
end
end
|
module Kernel
def document
System::Windows::Browser::HtmlPage.document
end
def window
System::Windows::Browser::HtmlPage.window
end
end
class NilClass
def blank?
true
end
end
class String
def blank?
empty?
end
end
class System::Windows::FrameworkElement
# Monkey-patch FrameworkElement to allow element.ChildName instead of window.FindName("ChildName")
# If FindName doesn't yield an object, it tried the Resources collection (for things like Storyboards)
def method_missing name, *args
obj = find_name(name.to_s.to_clr_string)
obj ||= self.resources[name.to_s.to_clr_string]
obj || super
end
def hide!
self.visibility = System::Windows::Visibility.hidden
end
def collapse!
self.visibility = System::Windows::Visibility.collapsed
end
def show!
self.visibility = System::Windows::Visibility.visible
end
end
module System::Windows::Browser
module HtmlInspector
def inspect
name = "#<#{self.class}"
name << " id=#{self.Id}" unless self.Id.blank?
name << " class=#{self.css_class}" unless self.css_class.blank?
name << ">"
end
end
class HtmlDocument
include HtmlInspector
def method_missing(m, *args)
get_element_by_id(m.to_s)
end
def tags(name)
get_elements_by_tag_name(name.to_s)
end
end
class System::Windows::Browser::ScriptObjectCollection
include Enumerable
def size
count
end
def first
self[0] if size > 0
end
def last
self[size - 1] if size > 0
end
def empty?
size == 0
end
def inspect
"#<#{self.class} size=#{self.size}>"
end
end
class HtmlElement
include HtmlInspector
def [](index)
get_attribute(index.to_s)
end
def []=(index, value)
set_attribute(index.to_s, value)
end
def html
self.innerHTML
end
def html=(value)
self.innerHTML = value
end
def method_missing(m, *args, &block)
super
rescue => e
if block.nil?
if m.to_s[-1..-1] == '='
set_property(m.to_s[0..-2], args.first)
else
id = get_property(m.to_s)
return id unless id.nil?
raise e
end
else
unless attach_event(m.to_s.to_clr_string, System::EventHandler.of(HtmlEventArgs).new(&block))
raise e
end
end
end
def style
HtmlStyle.new(self)
end
end
class System::Windows::Browser::ScriptObject
alias orig_set_property set_property
def set_property(name, value)
# Safari BUG: doesn't recognize MutableString as a String
value = value.to_clr_string if value.kind_of? String
orig_set_property name, value
end
alias SetProperty set_property
end
class HtmlStyle
def initialize(element)
@element = element
end
def [](index)
@element.get_style_attribute(index.to_s)
end
def []=(index, value)
@element.set_style_attribute(index.to_s, value)
end
def method_missing(m, *args)
super
rescue => e
if m.to_s[-1..-1] == "="
self[m.to_s[0..-2]] = args.first
else
style = self[m]
return style unless style.nil?
raise e
end
end
end
end
|
class Jtl::LabeledValue
attr_reader :label
attr_reader :value
def initialize(label, value)
@label = label
@value = value
end
end
|
class CreateHabilitacoes < ActiveRecord::Migration[6.0]
def change
create_table :habilitacoes do |t|
t.references :pessoa, index: true
t.string :numero
t.string :modalidades
t.date :validade
t.timestamps
end
end
end
|
desc "Heroku scheduler add-on used to re-seed db periodically"
task :update_db => :environment do
puts "Updating database. . ."
Rake::Task['db:seed'].invoke
puts "Update complete."
end |
describe StepController do
it 'should return all step templates' do
get '/step/templates'
expect(last_response).to be_ok
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result.length).to eq 2
end
it 'should return step template' do
get '/step/templates/copy_artifacts'
expect(last_response).to be_ok
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result[:id]).to eq 1
end
it 'should check is step template exists via HEAD' do
head '/step/templates/copy_artifacts'
expect(last_response).to be_ok
end
it 'should return 404 when template does exists asked via HEAD' do
head '/step/templates/not%20exists'
expect(last_response.status).to eq 404
end
it 'should return 404 when step template does not exist' do
get '/step/templates/not%20exists'
expect(last_response.status).to eq 404
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result[:msg]).to eq 'Step template with name "not exists" does not exists.'
end
it 'should add new step template' do
step = {
name: 'Run_httpd_service',
description: 'Run httpd service using system tools'
}
post '/step/templates', step.to_json, 'CONTENT_TYPE': 'application/json'
expect(last_response.status).to eq 201
result = Step.templates.all
expect(result.length).to eq 3
new_template = result[2]
expect(new_template[:name]).to eq 'Run_httpd_service'
expect(new_template[:description]).to eq 'Run httpd service using system tools'
end
describe 'step' do
it 'should get file from files table' do
get '/step/1/files'
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result.length).to eq 1
expect(result[0][:name]).to eq 'putit_test.file'
end
end
describe 'ansible specific directories' do
ANSIBLE_TABLES.each do |t|
it "should add file to #{t} table" do
file = Rack::Test::UploadedFile.new('Rakefile', 'text/plain', true)
step = Step.create!(name: 'file_upload', template: true)
name = step.name
post "/step/templates/#{name}/#{t}", file: file
expect(last_response.status).to eq 201
created_file = step.send(t).physical_files.first
expect(created_file.name).to eq 'Rakefile'
expect(created_file.content).to start_with "require './config/environment.rb'\n"
end
it "should get file description from #{t} table" do
file = Rack::Test::UploadedFile.new('Rakefile', 'text/plain', true)
step = Step.create!(name: 'file_upload', template: true)
name = step.name
post "/step/templates/#{name}/#{t}", file: file
expect(last_response.status).to eq 201
get "/step/templates/#{name}/#{t}"
expect(last_response).to be_ok
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result.length).to eq 1
expect(result[0][:name]).to eq 'Rakefile'
end
it "should download file from #{t} table" do
file = Rack::Test::UploadedFile.new('Rakefile', 'text/plain', true)
step = Step.create!(name: 'file_upload', template: true)
name = step.name
post "/step/templates/#{name}/#{t}", file: file
expect(last_response.status).to eq 201
get "/step/templates/#{name}/#{t}/Rakefile"
expect(last_response).to be_ok
expect(last_response.header['Content-Disposition']).to eq 'attachment; filename="Rakefile"'
expect(last_response.body).to start_with "require './config/environment.rb'\n"
end
end
end
it 'should update step template with new files' do
step = {
name: 'httpd',
description: 'Run httpd service using system tools'
}
post '/step/templates', step.to_json, 'CONTENT_TYPE': 'application/json'
expect(last_response.status).to eq 201
rakefile = Rack::Test::UploadedFile.new('Rakefile', 'text/plain', true)
config_ru = Rack::Test::UploadedFile.new('config.ru', 'text/plain', true)
post '/step/templates/httpd/files', file: rakefile
post '/step/templates/httpd/files', file: config_ru
expect(Step.templates.find_by_name('httpd').files.physical_files.length).to eq 2
put '/step/templates/httpd', step.to_json, 'CONTENT_TYPE': 'application/json'
expect(last_response.status).to be 202
expect(Step.templates.find_by_name('httpd').files.physical_files.length).to eq 0
post '/step/templates/httpd/files', file: config_ru
expect(Step.templates.find_by_name('httpd').files.physical_files.length).to eq 1
end
describe 'delete' do
it 'should delete step template' do
s = Step.templates.first
sf_id = s.files.id
st_id = s.templates.id
sh_id = s.handlers.id
st_id = s.tasks.id
sv_id = s.vars.id
sd_id = s.defaults.id
delete "/step/templates/#{s.name}"
expect(last_response.status).to eq 202
result = JSON.parse(last_response.body, symbolize_names: true)
expect(result[:status]).to eq 'ok'
expect(Step.templates.exists?(s.id)).to eq false
expect(AnsibleFiles.exists?(sf_id)).to eq false
expect(AnsibleTemplates.exists?(st_id)).to eq false
expect(AnsibleHandlers.exists?(sh_id)).to eq false
expect(AnsibleTasks.exists?(st_id)).to eq false
expect(AnsibleVars.exists?(sv_id)).to eq false
expect(AnsibleDefaults.exists?(sd_id)).to eq false
end
end
end
|
module BabySqueel
module Nodes
# This proxy class allows us to quack like any arel object. When a
# method missing is hit, we'll instantiate a new proxy object.
class Proxy < ActiveSupport::ProxyObject
# Resolve constants the normal way
def self.const_missing(name)
::Object.const_get(name)
end
attr_reader :_arel
def initialize(arel)
@_arel = Nodes.unwrap(arel)
end
def inspect
"BabySqueel{#{super}}"
end
def respond_to?(meth, include_private = false)
meth.to_s == '_arel' || _arel.respond_to?(meth, include_private)
end
private
def method_missing(meth, *args, &block)
if _arel.respond_to?(meth)
Nodes.wrap _arel.send(meth, *Nodes.unwrap(args), &block)
else
super
end
end
end
end
end
|
class BibleRef < Formula
desc "Look up Bible references and search for verses"
url "https://github.com/padwasabimasala/bible-ref/archive/v1.1.1.tar.gz"
sha256 "1e451ca8d7d9575b8d3187cd8f7b4d7f5eaf755b3566cae9094220c303277ef7"
homepage "https://github.com/padwasabimasala/bible-ref"
head "https://github.com/padwasabimasala/bible-ref.git"
depends_on "perl"
def install
inreplace "bible-ref", /\|\| undef \|\|/, "|| \"#{HOMEBREW_PREFIX}/Cellar/bible-ref/1.1.1/share\" ||"
bin.install "bible-ref"
share.install "KJV"
share.install "KJV.dir"
end
test do
output = pipe_output("#{bin}/bible-ref KJV gen 1:1")
assert_match "Book 01 Genesis 001:001 In the beginning God created the heaven and the earth.", output
end
end
|
def cls
system("cls") || system("clear")
end
def get_letters
slovo = ARGV[0]
slovo = Unicode.downcase(slovo)
if slovo == nil || slovo == ""
abort "Для игры введите загаданное слово в качестве аргумента при " \
"запуске программы"
end
return slovo.encode('UTF-8').split("")
end
def get_user_input
letter = ""
while letter == ""
letter = STDIN.gets.chomp
end
return letter
end
def check_input(user_input, letters, good_letters, bad_letters)
if good_letters.include?(user_input) || bad_letters.include?(user_input)
return 0
end
if letters.include?(user_input) ||
(user_input == "е" && letters.include?("ё")) ||
(user_input == "ё" && letters.include?("е")) ||
(user_input == "и" && letters.include?("й")) ||
(user_input == "й" && letters.include?("и"))
# В любом (поэтому эти условия объединяет оператор ||) из этих случаев мы
# добавляем в массив хороших букв ту, что была введена пользователем и
# её подружку, если есть (считаем «подружками» е + ё» и и + й).
good_letters << user_input
if user_input == "е"
good_letters << "ё"
end
if user_input == "ё"
good_letters << "е"
end
if user_input == "и"
good_letters << "й"
end
if user_input == "й"
good_letters << "и"
end
if (letters - good_letters).empty?
return 1
else
return 0
end
else
bad_letters << user_input
return -1
end
end
def get_word_for_print(letters, good_letters)
result = ""
for item in letters do
if good_letters.include?(item)
result += item + " "
else
result += "__ "
end
end
return result
end
def get_word_for_print(letters, good_letters)
result = ""
for item in letters do
if good_letters.include?(item)
result += item + " "
else
result += "__ "
end
end
return result
end
def print_status(letters, good_letters, bad_letters, errors)
puts "\nСлово: #{get_word_for_print(letters, good_letters)}"
puts "Ошибки (#{errors}): #{bad_letters.join(", ")}"
if errors >= 7
puts "Вы проиграли :("
else
if good_letters.uniq.sort == letters.uniq.sort
puts "Поздравляем, вы выиграли!\n\n"
else
puts "У вас осталось попыток: " + (7 - errors).to_s
end
end
end
|
#
# PaymentsByDates
#
# Displaying payments grouped by dates
#
class PaymentsByDatesController < ApplicationController
def index
params[:date] ||= Payment.last_booked_at
@records = Payment.booked_on(date: params[:date])
.includes(join_tables)
.load
@payments_by_dates = Payment.recent.by_booked_at_date
end
def destroy
@payment = Payment.find params[:id]
cached_message = deleted_message
@payment.destroy
redirect_to payments_by_dates_path, flash: { delete: cached_message }
end
private
# join_tables
# - specifies the relationships to be included in the result set
#
def join_tables
[account: [property: [:entities]]]
end
def identity
"Payment from #{@payment.account.property.occupiers}, " \
"Property #{@payment.account.property.human_ref}, " \
"Amount: £#{@payment.amount}"
end
end
|
require_relative './database_connection'
class Comment
attr_reader :id, :text, :tweet_id
def initialize(id:, text:, tweet_id:)
@id = id
@text = text
@tweet_id = tweet_id
end
def self.create(tweet_id:, text:)
result = DatabaseConnection.query("INSERT INTO comments (tweet_id, text) VALUES ('#{tweet_id}','#{text}') RETURNING id, text, tweet_id;")
Comment.new(
id: result[0]['id'],
text: result[0]['text'],
tweet_id: result[0]['tweet_id']
)
end
def self.where(tweet_id:)
result = DatabaseConnection.query("SELECT * FROM comments WHERE tweet_id = #{tweet_id};")
result.map do |comment|
Comment.new(
id: comment['id'],
text: comment['text'],
tweet_id: comment['tweet_id']
)
end
end
end
|
class AnswersController < ApplicationController
def index
@question = Question.find(params[:question_id])
@answer = @question.answers.order(:created_at)
end
def new
@question = Question.find(params[:question_id])
@answer = Answer.new
end
def create
@question = Question.find(params[:question_id])
@answer = current_user.answers.new(answer_params)
@answer.question = @question
if @answer.save
flash[:notice] = "Answer submitted."
redirect_to "/questions/#{@question.id}/answers"
else
flash[:notice] = "#{@answer.errors[:body].first.capitalize}"
render :new
end
end
private
def answer_params
params.require(:answer).permit(:body)
end
end
|
require 'aepic'
module Aepic
module Concerns
module Serializer
module Adapter
def self.inject!
require 'active_model/serializer/adapter/json_api'
ActiveModel::Serializer::Adapter::JsonApi.send(:include, self)
end
def meta_for(serializer)
STDERR.puts 'Add total_pages'
meta = super(serializer)
meta.merge({ total_pages: serializer.total_pages, total_count: serializer.total_count, size: serializer.size }) if serializer.respond_to?(:total_pages)
meta
end
end
end
end
end
|
module Tact
class Card
attr_reader :contact
def initialize(contact, index="*")
@contact = contact
@index = index
end
def to_s
string = "=" * 40 + "\n"
string += "[#{@index}]".red + " #{@contact.to_s}"
contact.phone_numbers.each_with_index {|number, i| string += "\s\s" + "[#{i + 1}] " + number.to_s + "\n"}
contact.emails.each_with_index {|address, i| string += "\s\s\s\s" + "[#{i + 1}] " + address.to_s + "\n"}
string += "=" * 40 + "\n"
end
end
end
|
Factory.define :metasubservicio do |mss|
mss.sequence(:nombre) { |n| "algun metasubservicio con numero #{n}" }
mss.association :metaservicio
end |
class Table
attr_accessor :table
def initialize
@table = [
["-","-","-"],
["-","-","-"],
["-","-","-"]
]
end
def do_table
@table.each_index do |i|
subtable = @table[i]
subtable.each do |x|
print "| #{x} |"
end
print "\n"
end
end
def reset_table
@table = [["-","-","-"],["-","-","-"],["-","-","-"]]
end
end
class Player
attr_reader :name, :value
attr_accessor :wins
def initialize(name, value)
@name = name
@value = value
@wins = 0
end
def turn(table)
while i = gets.chomp.split(",")
if i[0].to_i > 2 || table.table[i[0].to_i][i[1].to_i] != "-"
puts "Error!"
print "#{name}'s turn for #{value}: "
else
table.table[i[0].to_i][i[1].to_i] = @value
break
end
end
end
end
class Game
def initialize
print "Player 1 Name: "
input = gets.chomp
@player1 = Player.new(input, :X)
print "Player 2 Name: "
input = gets.chomp
@player2 = Player.new(input, :O)
@table = Table.new
@table.do_table
@whos_turn = 0
@win_val = nil
game_loop
end
private
def game_loop
while true
case @whos_turn
when 0
print "#{@player1.name}'s turn for #{@player1.value}, 'x,y': "
@player1.turn(@table)
check_win(@player1)
when 1
print "#{@player2.name}'s turn for #{@player2.value}, 'x,y': "
@player2.turn(@table)
check_win(@player2)
end
@table.do_table
swap_turn
end
end
def swap_turn
if @whos_turn == 1
@whos_turn = 0
else
@whos_turn = 1
end
end
#Need to refactor this soon!
def check_win(player)
if (@table.table[0][0] == player.value && @table.table[0][1] == player.value && @table.table[0][2] == player.value) ||
(@table.table[1][0] == player.value && @table.table[1][1] == player.value && @table.table[1][2] == player.value) ||
(@table.table[2][0] == player.value && @table.table[2][1] == player.value && @table.table[2][2] == player.value) ||
(@table.table[0][0] == player.value && @table.table[1][0] == player.value && @table.table[2][0] == player.value) ||
(@table.table[0][0] == player.value && @table.table[1][0] == player.value && @table.table[2][0] == player.value) ||
(@table.table[0][1] == player.value && @table.table[1][1] == player.value && @table.table[2][1] == player.value) ||
(@table.table[0][2] == player.value && @table.table[1][2] == player.value && @table.table[2][2] == player.value) ||
(@table.table[0][0] == player.value && @table.table[1][1] == player.value && @table.table[2][2] == player.value) ||
(@table.table[2][0] == player.value && @table.table[1][1] == player.value && @table.table[0][2] == player.value)
@win_val = player.value
game_end
end
end
def game_end
if @player1.value == @win_val
puts "#{@player1.name} wins!"
@player1.wins += 1
elsif @player2.value == @win_val
puts "#{@player2.name} wins!"
@player2.wins += 1
elsif "Draw" == @win_val
puts "Game was a draw."
end
puts "#{@player1.name} wins: #{@player1.wins} / #{@player2.name} wins: #{@player2.wins}"
play_again?
end
def play_again?
puts "Type 'new' for new game, or 'rematch' to play again!"
input = gets.chomp.downcase
Game.new if input == "new"
if input == "rematch"
@table.reset_table
game_loop
end
end
end
game = Game.new |
require "error_nande/version"
module ErrorNande
def self.nande(error)
summary = "#{error.inspect} at #{compact_backtrace(error)}"
while error = error.cause
summary << " (cause #{error.inspect} at #{compact_backtrace(error)})"
end
summary
end
class << self
alias_method :summary, :nande
end
def self.compact_backtrace(error)
return "(toplevel)" unless error.backtrace
self.backtrace_cleaner.clean(error.backtrace, :no_silencers).first
end
class NullBacktraceCleaner
def clean(backtrace, *rest)
backtrace
end
end
def self.backtrace_cleaner
if defined?(::Rails) && ::Rails.backtrace_cleaner
::Rails.backtrace_cleaner
else
NullBacktraceCleaner.new
end
end
end
|
require 'fileutils'
require 'tempfile'
require 'util/postgres_admin'
module ManageIQ
module ApplianceConsole
# configure ssl certificates for postgres communication
# and appliance to appliance communications
class CertificateAuthority
CFME_DIR = "/var/www/miq/vmdb/certs"
PSQL_CLIENT_DIR = "/root/.postgresql"
# hostname of current machine
attr_accessor :hostname
attr_accessor :realm
# name of certificate authority
attr_accessor :ca_name
# true if we should configure postgres client
attr_accessor :pgclient
# true if we should configure postgres server
attr_accessor :pgserver
# true if we should configure http endpoint
attr_accessor :http
attr_accessor :verbose
def initialize(options = {})
options.each { |n, v| public_send("#{n}=", v) }
@ca_name ||= "ipa"
end
def ask_questions
if ipa?
self.principal = just_ask("IPA Server Principal", @principal)
self.password = ask_for_password("IPA Server Principal Password", @password)
end
self.pgclient = ask_yn("Configure certificate for postgres client", "Y")
self.pgserver = ask_yn("Configure certificate for postgres server", "Y")
self.http = ask_yn("Configure certificate for http server", "Y")
true
end
def activate
valid_environment?
configure_pgclient if pgclient
configure_pgserver if pgserver
configure_http if http
status_string
end
def valid_environment?
if ipa? && !ExternalHttpdAuthentication.ipa_client_configured?
raise ArgumentError, "ipa client not configured"
end
raise ArgumentError, "hostname needs to be defined" unless hostname
end
def configure_pgclient
unless File.exist?(PSQL_CLIENT_DIR)
FileUtils.mkdir_p(PSQL_CLIENT_DIR, :mode => 0700)
AwesomeSpawn.run!("/sbin/restorecon -R #{PSQL_CLIENT_DIR}")
end
self.pgclient = Certificate.new(
:cert_filename => "#{PSQL_CLIENT_DIR}/postgresql.crt",
:root_filename => "#{PSQL_CLIENT_DIR}/root.crt",
:service => "manageiq",
:extensions => %w(client),
:ca_name => ca_name,
:hostname => hostname,
:realm => realm,
).request.status
end
def configure_pgserver
cert = Certificate.new(
:cert_filename => "#{CFME_DIR}/postgres.crt",
:root_filename => "#{CFME_DIR}/root.crt",
:service => "postgresql",
:extensions => %w(server),
:ca_name => ca_name,
:hostname => hostname,
:realm => realm,
:owner => "postgres.postgres"
).request
if cert.complete?
say "configuring postgres to use certs"
# only telling postgres to rewrite server configuration files
# no need for username/password since not writing database.yml
InternalDatabaseConfiguration.new(:ssl => true).configure_postgres
LinuxAdmin::Service.new(PostgresAdmin.service_name).restart
end
self.pgserver = cert.status
end
def configure_http
cert = Certificate.new(
:key_filename => "#{CFME_DIR}/server.cer.key",
:cert_filename => "#{CFME_DIR}/server.cer",
:root_filename => "#{CFME_DIR}/root.crt",
:service => "HTTP",
:extensions => %w(server),
:ca_name => ca_name,
:hostname => hostname,
:owner => "apache.apache",
).request
if cert.complete?
say "configuring apache to use new certs"
LinuxAdmin::Service.new("httpd").restart
end
self.http = cert.status
end
def status
{"pgclient" => pgclient, "pgserver" => pgserver, "http" => http}.delete_if { |_n, v| !v }
end
def status_string
status.collect { |n, v| "#{n}: #{v}" }.join " "
end
def complete?
!status.values.detect { |v| v != ManageIQ::ApplianceConsole::Certificate::STATUS_COMPLETE }
end
def ipa?
ca_name == "ipa"
end
private
def log
say yield if verbose && block_given?
end
end
end
end
|
class CreateRoomParticipation < ActiveRecord::Migration
def change
create_table :room_participations do |t|
t.references :user, index: true
t.references :room, index: true
end
end
end
|
require 'rails_helper'
describe Leagues::Matches::GenerationService do
describe 'single elimination' do
it 'works' do
division = create(:league_division)
team1 = create(:league_roster, division: division, seeding: 3)
team2 = create(:league_roster, division: division, seeding: 2)
team3 = create(:league_roster, division: division, seeding: 1)
team4 = create(:league_roster, division: division, seeding: 4)
map = create(:map)
match_options = {
round_number: 1, rounds_attributes: [
{ map: map },
]
}
match = described_class.call(division, match_options, :single_elimination, {})
expect(match).to be nil
expect(division.matches.size).to eq(2)
match1 = division.matches.first
expect(match1.home_team).to eq(team3)
expect(match1.away_team).to eq(team4)
expect(match1.has_winner).to be true
expect(match1.round_number).to eq(1)
expect(match1.rounds.size).to eq(1)
expect(match1.rounds.first.map).to eq(map)
match2 = division.matches.second
expect(match2.home_team).to eq(team2)
expect(match2.away_team).to eq(team1)
expect(match2.has_winner).to be true
expect(match2.round_number).to eq(1)
expect(match2.rounds.size).to eq(1)
expect(match2.rounds.first.map).to eq(map)
match1.update!(
status: :confirmed, rounds_attributes: [
{ id: match1.rounds.first.id, home_team_score: 2, away_team_score: 1 },
]
)
expect(match1.winner).to eq(team3)
match2.update!(
status: :confirmed, rounds_attributes: [
{ id: match2.rounds.first.id, home_team_score: 3, away_team_score: 6 },
]
)
expect(match2.winner).to eq(team1)
rosters = division.rosters.ordered.to_a
expect(rosters).to eq([team3, team1, team2, team4])
map = create(:map)
match_options = {
round_number: 2, rounds_attributes: [
{ map: map },
]
}
match = described_class.call(division, match_options, :single_elimination, round: 1)
expect(match).to be nil
expect(division.matches.size).to eq(3)
division.reload
match = division.matches.last
expect(match.home_team).to eq(team3)
expect(match.away_team).to eq(team1)
expect(match.round_number).to eq(2)
expect(match.rounds.size).to eq(1)
expect(match.rounds.first.map).to eq(map)
match.update!(
status: :confirmed, rounds_attributes: [
{ id: match.rounds.first.id, home_team_score: 2, away_team_score: 3 },
]
)
expect(match.winner).to eq(team1)
rosters = division.rosters.ordered.to_a
expect(rosters).to eq([team1, team3, team2, team4])
end
end
end
|
# encoding: UTF-8
##
# Auteur JORIS TOULMONDE
# Version 0.1 : Date : Thu Feb 11 16:27:55 CET 2016
#
load 'ControleurPartie.rb'
load 'Controleur.rb'
load 'Vue.rb'
load 'VueCase.rb'
load 'Grille.rb'
load 'VueChoixGrille.rb'
load 'Aventure.rb'
load 'VueChoixAventureNiveau.rb'
load 'ChoixAventureNiveau.rb'
#Classe permettant de selectionner le niveau de difficulte de l'Aventure
class ChoixAventure < Controleur
@laventure
# Liaison des boutons de la fenetre du choix de difficulte de l'Aventure
#
# * *Args* :
# - +laventure+ -> Aventure du joueur
# - +jeu+ -> Session de jeu actuel du joueur
#
def ChoixAventure.Creer(laventure,jeu)
new(laventure,jeu)
end
#Initialisation du menu pour demander à l'utilisateur quelle taille de grille il souhaite.
def initialize(laventure,jeu)
@choix = VueChoixAventure.Creer()
@laventure = laventure
@choix.facile.signal_connect('clicked'){
@laventure.choixDifficulte(0)
ChoixAventureNiveau.Creer(@laventure,jeu)
@choix.fenetre.hide_all
}
if @laventure.passageLvlUp(0) then
@choix.moyen.signal_connect('clicked'){
@laventure.choixDifficulte(1)
ChoixAventureNiveau.Creer(@laventure,jeu)
@choix.fenetre.hide_all
}
end
if @laventure.passageLvlUp(1) then
@choix.difficile.signal_connect('clicked'){
@laventure.choixDifficulte(2)
ChoixAventureNiveau.Creer(@laventure,jeu)
@choix.fenetre.hide_all
}
end
@choix.retour.signal_connect('clicked'){
jeu.joueur.laventure.aventureEtat = false
EcranAccueil.new(jeu, Gtk::Window::POS_CENTER)
@choix.fenetre.hide_all
}
@choix.quitter.signal_connect('clicked'){
Gtk.main_quit
@choix.fenetre.hide_all
}
end
end
|
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'blade/rails_plugin/version'
Gem::Specification.new do |spec|
spec.name = "blade-rails_plugin"
spec.version = Blade::RailsPlugin::VERSION
spec.authors = ["Celso Fernandes"]
spec.email = ["celso.fernandes@gmail.com"]
spec.summary = %q{Blade plugin to integrate with Rails}
spec.description = %q{Provides an out-of-the-box integration between Blade and Rails}
spec.homepage = "https://github.com/fernandes/blade-rails_plugin"
spec.license = "MIT"
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
# to allow pushing to a single host or delete this section to allow pushing to any host.
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_dependency "blade", "~> 0.5"
spec.add_development_dependency "bundler", "~> 1.12"
spec.add_development_dependency "jquery-rails", "~> 4"
spec.add_development_dependency "rails", "~> 4.2"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "sprockets-rails", "~> 3"
spec.add_development_dependency "minitest", "~> 5.0"
end
|
class HomeController < ApplicationController
include ReposExposer
expose(:articles) { articles_repository.search(params[:query]).page(params[:page]) }
expose(:article)
end
|
require 'spec_helper'
describe 'Apps Requests', type: :request do
describe 'GET /v1/apps/{id}' do
it 'responds with the requested app' do
app = App.create( name: 'example_app', host_group: 'ag-web')
get "/v1/apps/#{app.id}.json", {}, {'Accept' => 'app/vnd.primedia.com; version=1', 'Content-Type' => 'app/json'}
expect(response.status).to eq(200)
end
end
end
|
require_relative 'my_inject'
require 'rubygems'
require 'twilio-ruby'
class Invitraunt
def initialize
@full_order = []
end
attr_reader :full_order
def total_price
corresponding_prices.my_inject { |net_price, item| net_price + item }
end
def corresponding_prices
full_order.map {|dish| dishes[dish] }
end
def dishes
{"vat burger" => 300_000, "rabbit eggs" => 500_000, "raptor nuggets x6" => 2}
end
def order_dishes(quantity, dish)
quantity.times { @full_order << dish }
end
def print_menu
puts "\nWelcome to InVitraunt! We have all your favourite animal templates gestated to taste!\n\n"
dish_num = 0
dishes.each do | dish, price | dish_num += 1
print "#{dish_num}. #{dish.capitalize} #{align_price(price, dish)}\n"
end
puts ""
end
def string_price(price)
'£' + price.to_s + ".00"
end
def align_price(price, former_string)
string_price(price).rjust(50 - former_string.length)
end
def translate(dish)
case dish.to_i
when 1
"vat burger"
when 2
"rabbit eggs"
when 3
"raptor nuggets x6"
end
end
# def take_order
# dish = nil
# until dish == 'end'
# puts "Please enter the menu number of your item, or 'end', if you've finished your order"
# dish = gets.chomp.downcase
# unless dish == 'end'
# dish = translate(dish)
# puts "How many #{dish}s would you like to order?"
# quantity = gets.chomp.to_i
# order_dishes(quantity, dish)
# end
# end
# end
end
# invitraunt = Invitraunt.new
# invitraunt.print_menu
# invitraunt.take_order
"Write a Takeaway program.
Implement the following functionality:
list of dishes with prices
placing the order by giving the list of dishes, their quantities and a number that should be the exact total. If the sum is not correct the method should raise an error, otherwise the customer is sent a text saying that the order was placed successfully and that it will be delivered 1 hour from now, e.g. 'Thank you! Your order was placed and will be delivered before 18:52'.
The text sending functionality should be implemented using Twilio API. You'll need to register for it. It’s free.
Use twilio-ruby gem to access the API
Use a Gemfile to manage your gems
Make sure that your Takeaway is thoroughly tested and that you use mocks and/or stubs, as necessary to not to send texts when your tests are run
However, if your Takeaway class is loaded into IRB and the order is placed, the text should actually be sent
A free account on Twilio will only allow you to send texts to 'verified' numbers. Use your mobile phone number, don't worry about the customer's mobile phone.
" |
class Movie < ApplicationRecord
has_many :reviews , dependent: :destroy
validates_uniqueness_of :api_id
validates_presence_of :api_id
validates_presence_of :title
validates_presence_of :overview
def to_param
self.api_id.to_s
end
def populate_from_api id
Tmdb::Api.key '6d5073fd950729a0d1b024f739c22b4a'
Tmdb::Api.language 'en-US'
result = Tmdb::Movie.detail(id)
self.api_id = id
self.genre = result['genres'].first['name']
direct_params = [:title, :overview, :release_date]
direct_params.each{ |p| self[p] = result[p.to_s] }
self.backdrop_url = "https://image.tmdb.org/t/p/original#{result['backdrop_path']}"
self.poster_url = "https://image.tmdb.org/t/p/w500#{result['poster_path']}"
end
def reviews_histogram_data
data = []
total = self.reviews.length
(1..5).each do |n|
if total == 0
percentage = 0
else
num_reviews = self.reviews.select{|r| r.rating == n}.length
percentage = ((num_reviews.to_f / total.to_f) * 100).to_i
end
data << {num_stars: n, percentage: percentage}
end
data.reverse
end
def update_average_rating!
self.rating = self.reviews.average(:rating)
self.save
end
end
|
# The MIT License (MIT)
#
# Copyright (c) 2015 Oleg Ivanov http://github.com/morhekil
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Symbolizes all of hash's keys and subkeys.
# Also allows for custom pre-processing of keys (e.g. downcasing, etc)
# if the block is given:
#
# somehash.deep_symbolize { |key| key.downcase }
#
# Usage: either include it into global Hash class to make it available to
# to all hashes, or extend only your own hash objects with this
# module.
# E.g.:
# 1) class Hash; include DeepSymbolizable; end
# 2) myhash.extend DeepSymbolizable
module DeepSymbolizable
def deep_symbolize(&block)
method = self.class.to_s.downcase.to_sym
syms = DeepSymbolizable::Symbolizers
syms.respond_to?(method) ? syms.send(method, self, &block) : self
end
module Symbolizers
extend self
# the primary method - symbolizes keys of the given hash,
# preprocessing them with a block if one was given, and recursively
# going into all nested enumerables
def hash(hash, &block)
hash.inject({}) do |result, (key, value)|
# Recursively deep-symbolize subhashes
value = _recurse_(value, &block)
# Pre-process the key with a block if it was given
key = yield key if block_given?
# Symbolize the key string if it responds to to_sym
sym_key = key.to_sym rescue key
# write it back into the result and return the updated hash
result[sym_key] = value
result
end
end
# walking over arrays and symbolizing all nested elements
def array(ary, &block)
ary.map { |v| _recurse_(v, &block) }
end
# handling recursion - any Enumerable elements (except String)
# is being extended with the module, and then symbolized
def _recurse_(value, &block)
if value.is_a?(Enumerable) && !value.is_a?(String)
# support for a use case without extended core Hash
value.extend DeepSymbolizable unless value.class.include?(DeepSymbolizable)
value = value.deep_symbolize(&block)
end
value
end
end
end |
class SetCheckedToEnquiries < ActiveRecord::Migration
def change
change_column_default :user_alerts, :enquiry, true
end
end
|
require 'rails_helper'
describe Park do
it { should validate_presence_of :area}
it { should validate_presence_of :description }
it { should validate_presence_of :state }
it { should validate_presence_of :name }
end
|
class AddPhotosCountToPhotos < ActiveRecord::Migration[5.1]
def change
add_column :photos, :photos_count, :decimal
end
end
|
#!/usr/bin/ruby
require 'bundler/setup'
require 'pi_piper'
PIN_IN1 = 23
PIN_IN2 = 24
SLEEP = 0.01
=begin
MODE = 0 (IN/IN)
IN1 IN2 OUT1 OUT2
0 0 - - 空転 (coast)
0 1 L H 逆進
1 0 H L 前進
1 1 L L 回生ブレーキ (break)
MODE = 1 (PHASE/ENABLE)
IN1 IN2 OUT1 OUT2
0 x L L 回生ブレーキ
1 1 L H 逆進
1 0 H L 前進
=end
class RpiPrarail
attr_reader :pin_in1
attr_reader :pin_in2
attr_reader :pwm
attr_reader :coast
def initialize
@pin_in1 = PiPiper::Pin.new(pin: PIN_IN1, direction: :out)
@pin_in2 = PiPiper::Pin.new(pin: PIN_IN2, direction: :out)
@pwm = nil
@coast = true
@thread = nil
stop
end
def pwm_setting(freq, duty)
@pwm = PWM.new(new_freq: freq, new_duty: duty)
end
def start
if(@pwm)
loop do
_forward
sleep(@pwm.pulse_on)
stop
sleep(@pwm.pulse_off)
end
else
_forward
end
end
def stop
@coast ? _coast : _brake
end
def _coast
@pin_in1.off
@pin_in2.off
#_sleep
end
def _forward
@pin_in1.on
@pin_in2.off
#_sleep
end
def _reverse
@pin_in1.off
@pin_in2.on
#_sleep
end
def _brake
@pin_in1.on
@pin_in2.on
#_sleep
end
private
def _sleep
sleep(SLEEP)
end
# シグナルハンドラを設定する
# @return [void]
def set_signal_handler
# シグナルを捕捉し、ボットを終了させる処理
# trap 内で普通に bot.quit すると ThreadError が出るので
# 新しい Thread で包む
%i(SIGINT SIGTERM).each do |signal|
Signal.trap(signal) do
Thread.new(signal) do |sig|
puts(sig)
stop
end
end
end
end
end
class RpiPrarail::PWM
attr_reader :freq
attr_reader :duty
attr_reader :pulse_on
attr_reader :pulse_off
def initialize(new_freq: 50.0, new_duty: 0.0)
self.freq = new_freq
self.duty = new_duty
end
private
def freq=(new_freq)
@freq = new_freq if(new_freq > 0.0)
end
def duty=(new_duty)
@duty = new_duty if(new_duty >= 0.0 && new_duty <= 100.0)
get_pulse
end
def get_pulse
@pulse_on = 1.0 / freq * duty / 100
@pulse_off = 1.0 / freq - @pulse_on
end
end
puts('program started.')
@prarail = RpiPrarail.new
# 周波数・デューティー比
# 周波数は高めの方が安定する?
# モータ定格は 1.5V のはず、電池はリチウムイオン 3.7V
@prarail.pwm_setting(100, 40)
puts('testing...')
@prarail.start
sleep(5)
@prarail.stop
|
#
# Be sure to run `pod spec lint PYCore.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = "PYGradientCycle"
s.version = "1.1"
s.summary = "Gradient Cycle."
s.description = <<-DESC
Gradient Cycle in iOS
DESC
s.homepage = "https://github.com/littlepush/PYGradientCycle"
s.license = "LGPLv3"
s.license = { :type => "LGPLv3", :file => "LICENSE" }
s.author = { "Push Chen" => "littlepush@gmail.com" }
s.social_media_url = "https://pushchen.com"
s.platform = :ios, "7.0"
s.requires_arc = true
s.source = { :git => "https://github.com/littlepush/PYGradientCycle.git", :tag => "1.1" }
s.source_files = "PYGradientCycle/*.{h,m}"
end
|
require 'psyduck/version'
require 'net/ftp'
module Psyduck
class FTPClient
# attr_readers are needed for tests
attr_reader :ip_address
attr_reader :username
attr_reader :password
attr_reader :command_port
attr_reader :passivity
attr_reader :resumable
def initialize(
ip_address:,
username: 'anonymous',
password: nil,
command_port: 21,
passivity: true,
options: {})
@ip_address = ip_address
@username = username
@password = password
@command_port = command_port
@ftp = Net::FTP.new
@ftp.passive = passivity
@ftp.resume = true
@ftp.debug_mode = options[:debug_mode]
end
def ftp
@ftp
end
def connect
@ftp.connect(@ip_address, @command_port)
end
def login
@ftp.login(@username, @password)
end
def upload_file_to_server(path_to_local_file, path_to_remote_directory)
file = File.open(path_to_local_file)
@ftp.put(file)
end
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.