hexsha
stringlengths 40
40
| size
int64 2
1.01M
| content
stringlengths 2
1.01M
| avg_line_length
float64 1.5
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
1
|
---|---|---|---|---|---|
f8e170c551e9d485905fbd8e76d9fe3d6465a16a | 125 | require 'TestTargetFuncElement.rb'
class GeneralRegister < TestTargetFuncElement
def initialize(name)
super
end
end
| 15.625 | 45 | 0.792 |
037929d386e3767dbea03a6fb12e04fa1186721e | 2,646 | class ListOrdersFilter
class EmptyUser < User
def id
'empty'
end
def full_name
I18n.t('users.empty')
end
def save(*)
raise NotImplementedError
end
end
class << self
def empty_user
@empty_user ||= EmptyUser.new
end
end
module Filters
extend self
def filter_by_date(rel, dates)
{ created_at_from: 'created_at >= ?',
created_at_to: 'created_at <= ?' }.reduce(rel) do |r, (attr, condition)|
if dates[attr].present?
r.where(condition, dates[attr])
else
r
end
end
end
def filter_by_user_id(rel, value)
has_empty = value.find { |v| v == 'empty' }
values = value - %w(empty)
if has_empty && values.present?
rel.where('(user_id in (?) or user_id is null)', values)
elsif has_empty
rel.where(user_id: nil)
else
rel.where(user_id: values)
end
end
def filter_by(rel, column, value)
rel.where(column => value)
end
def filter_with_dispatch(rel, column, value)
if value.nil?
rel
else
if respond_to?('filter_by_%s' % column)
public_send('filter_by_%s' % column, rel, value)
else
filter_by(rel, column, value)
end
end
end
end
EMPTY_USER_ID = 'empty'
delegate :empty_user, to: :'self.class'
attr_reader :current_user, :params
def initialize(current_user, params = {})
@current_user = current_user
@params = params
end
def list_orders(relation = Order.all)
%w(state order_type_id user_id archived).reduce(Filters.filter_by_date(relation, filter_values)) do |rel, column|
Filters.filter_with_dispatch(rel, column, filter_values[column])
end
end
def filter_values
@filter_values ||= params.slice(*%w(state order_type_id archived user_id)).merge(dates)
end
def dates
@dates ||=
begin
now = Time.current
created_at_from = (params[:created_at_from] || (now - 1.day).beginning_of_day).try(:change, {offset: Time.zone.formatted_offset})
created_at_to = (params[:created_at_to] || now.end_of_day).try(:change, {offset: Time.zone.formatted_offset})
{ created_at_from: created_at_from,
created_at_to: created_at_to }.with_indifferent_access
end
end
def users
(params[:user_id] || []).map do |user_id|
if user_id == EMPTY_USER_ID
empty_user
elsif user_id == current_user.id.to_s
current_user
else
User.find(user_id)
end
end
end
private
def filter?
!!params[:filter]
end
end
| 22.615385 | 137 | 0.61678 |
1825971f16edb9d13a5bcfba8e608bb3a3c71fb9 | 54 | $evm.root['method_executed'] = "evm2_missing_method"
| 27 | 53 | 0.759259 |
39eb565264de0e8dbd98e94ce0dcf08843ea7e47 | 1,251 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe LiquidDiagrams::Renderers::GraphvizRenderer, :renderers do
subject(:renderer) { described_class.new('content') }
describe '#render' do
include_examples 'render with stdin and stdout', described_class
end
describe '#executable' do
it { expect(renderer.executable).to eq 'dot -Tsvg' }
end
describe '#arguments' do
context 'with string attributes' do
before do
renderer.instance_variable_set(
:@config, { 'graph_attributes' => 'color=red' }
)
end
it do
expect(renderer.arguments).to match '-Gcolor=red'
end
end
context 'with array attributes' do
before do
renderer.instance_variable_set(
:@config, { 'node_attributes' => %w[color=red size=10] }
)
end
it do
expect(renderer.arguments).to match '-Ncolor=red -Nsize=10'
end
end
context 'with hash attributes' do
before do
renderer.instance_variable_set(
:@config, { 'edge_attributes' => { 'color': 'red', 'size': '10' } }
)
end
it do
expect(renderer.arguments).to match '-Ecolor=red -Esize=10'
end
end
end
end
| 23.166667 | 77 | 0.616307 |
e24595112d5bc8a2e794b093bc0852ed9a50790a | 170 | require 'universaltranslator.rb'
puts 'Write your input path: Example--C:/code/Documents/input.txt'
input = gets
puts UniversalTranslator.new.get_data(input.chomp)
gets
| 24.285714 | 66 | 0.8 |
ac730f9590a2e43cbaf75b4f0d3b02f963016cd6 | 2,603 | module JdbcSpec
module MissingFunctionalityHelper
#Taken from SQLite adapter
def alter_table(table_name, options = {}) #:nodoc:
table_name = table_name.to_s.downcase
altered_table_name = "altered_#{table_name}"
caller = lambda {|definition| yield definition if block_given?}
transaction do
move_table(table_name, altered_table_name, options)
move_table(altered_table_name, table_name, &caller)
end
end
def move_table(from, to, options = {}, &block) #:nodoc:
copy_table(from, to, options, &block)
drop_table(from)
end
def copy_table(from, to, options = {}) #:nodoc:
create_table(to, options) do |@definition|
columns(from).each do |column|
column_name = options[:rename] ?
(options[:rename][column.name] ||
options[:rename][column.name.to_sym] ||
column.name) : column.name
column_name = column_name.to_s
@definition.column(column_name, column.type,
:limit => column.limit, :default => column.default,
:null => column.null)
end
@definition.primary_key(primary_key(from))
yield @definition if block_given?
end
copy_table_indexes(from, to)
copy_table_contents(from, to,
@definition.columns,
options[:rename] || {})
end
def copy_table_indexes(from, to) #:nodoc:
indexes(from).each do |index|
name = index.name.downcase
if to == "altered_#{from}"
name = "temp_#{name}"
elsif from == "altered_#{to}"
name = name[5..-1]
end
# index name can't be the same
opts = { :name => name.gsub(/_(#{from})_/, "_#{to}_") }
opts[:unique] = true if index.unique
add_index(to, index.columns, opts)
end
end
def copy_table_contents(from, to, columns, rename = {}) #:nodoc:
column_mappings = Hash[*columns.map {|col| [col.name, col.name]}.flatten]
rename.inject(column_mappings) {|map, a| map[a.last] = a.first; map}
from_columns = columns(from).collect {|col| col.name}
columns = columns.find_all{|col| from_columns.include?(column_mappings[col.name])}
execute("SELECT * FROM #{from}").each do |row|
sql = "INSERT INTO #{to} ("+columns.map(&:name)*','+") VALUES ("
sql << columns.map {|col| quote(row[column_mappings[col.name]],col)} * ', '
sql << ')'
execute sql
end
end
end
end
| 35.657534 | 88 | 0.574337 |
18161b83e60790a2cae4035b67cb817e54895a04 | 1,328 | Gem::Specification.new do |s|
s.name = 'logstash-output-cloudwatch'
s.version = '3.0.8'
s.licenses = ['Apache License (2.0)']
s.summary = "Aggregates and sends metric data to AWS CloudWatch"
s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program"
s.authors = ["Elastic"]
s.email = '[email protected]'
s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html"
s.require_paths = ["lib"]
# Files
s.files = Dir["lib/**/*","spec/**/*","*.gemspec","*.md","CONTRIBUTORS","Gemfile","LICENSE","NOTICE.TXT", "vendor/jar-dependencies/**/*.jar", "vendor/jar-dependencies/**/*.rb", "VERSION", "docs/**/*"]
# Tests
s.test_files = s.files.grep(%r{^(test|spec|features)/})
# Special flag to let us know this is actually a logstash plugin
s.metadata = { "logstash_plugin" => "true", "logstash_group" => "output" }
# Gem dependencies
s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99"
s.add_runtime_dependency 'logstash-mixin-aws', '>= 1.0.0'
s.add_runtime_dependency 'rufus-scheduler', [ '~> 3.0.9' ]
s.add_development_dependency 'logstash-devutils'
end
| 44.266667 | 205 | 0.649096 |
264e503ce55713955a03cd876b52ad298b311b89 | 3,589 | require 'spec_helper'
module Verify
describe SmsAuthsController do
describe 'GET verify/sms_auth' do
let(:member) { create :verified_member }
before { session[:member_id] = member.id }
before do
get :show
end
it { expect(response).to be_success }
it { expect(response).to render_template(:show) }
context 'already verified' do
let(:member) { create :member, :sms_two_factor_activated }
it { should redirect_to(settings_path) }
end
end
describe 'PUT verify/sms_auth in send code phase' do
let(:member) { create :member }
let(:attrs) {
{
format: :js,
sms_auth: {country: 'CN', phone_number: '123-1234-1234'},
commit: 'send_code'
}
}
subject { assigns(:sms_auth) }
before {
session[:member_id] = member.id
put :update, attrs
}
# it { should_not be_nil }
# its(:otp_secret) { should_not be_blank }
#
# context "with empty number" do
# let(:attrs) {
# {
# format: :js,
# sms_auth: {country: '', phone_number: ''},
# commit: 'send_code'
# }
# }
#
# before { put :update, attrs }
#
# it "should not be ok" do
# expect(response).not_to be_ok
# end
# end
context "with wrong number" do
let(:attrs) {
{
format: :js,
sms_auth: {country: 'CN', phone_number: 'wrong number'},
commit: 'send_code'
}
}
before { put :update, attrs }
it "should not be ok" do
expect(response).not_to be_ok
end
it "should has error message" do
expect(response.body).not_to be_blank
end
end
context "with right number" do
let(:attrs) {
{
format: :js,
sms_auth: {country: 'CN', phone_number: '133.1234.1234'},
commit: 'send_code'
}
}
before do
put :update, attrs
end
it { expect(response).to be_ok }
it { expect(member.reload.phone_number).to eq('8613312341234') }
end
end
describe 'POST verify/sms_auth in verify code phase' do
let(:member) { create :member }
let(:sms_auth) { member.sms_two_factor }
before { session[:member_id] = member.id }
context "with empty code" do
let(:attrs) {
{
format: :js,
sms_auth: {otp: ''}
}
}
before do
put :update, attrs
end
it "not return ok status" do
expect(response).not_to be_ok
end
end
context "with wrong code" do
let(:attrs) {
{
format: :js,
sms_auth: {otp: 'foobar'}
}
}
before do
put :update, attrs
end
it "not return ok status" do
expect(response).not_to be_ok
end
it "has error message" do
expect(response.body).not_to be_blank
end
end
context "with right code" do
let(:attrs) {
{
format: :js,
sms_auth: {otp: sms_auth.otp_secret}
}
}
before do
put :update, attrs
end
it { expect(response).to be_ok }
it { expect(assigns(:sms_auth)).to be_activated }
it { expect(member.sms_two_factor).to be_activated }
end
end
end
end
| 22.291925 | 72 | 0.501532 |
33604a09a9333acf093536357259e5846e027f19 | 236 | module Blockchain
class Transaction
def initialize(from = nil, to, amount)
@from = from
@to = to
@amount = amount
end
def info
{"from" => @from, "to" => @to, "amount" => @amount}
end
end
end
| 16.857143 | 57 | 0.538136 |
03623b6e9044964193c757da864557a41cac25a0 | 2,888 |
require_relative 'Common'
module Confetti
#----------------------------------------------------------------------------------------------
class Database
@@db = nil
@@in_connect = false
@@log = nil
@@migration_log = nil
def self.db_path
Config.db_path
end
def self.cleanup
end
def self.connect
return if @@in_connect
return if @@db
@@in_connect = true
@@log = Logger.new(Config.db_log_path/'activerecord.log')
@@migration_log = File.open(Config.db_log_path/'migration.log', 'a')
ActiveRecord::Base.logger = @@log
ActiveSupport::LogSubscriber.colorize_logging = false
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: Database.db_path)
raise "Cannot connect to database #{Database.db_path}" if !ActiveRecord::Base.connection.active?
internal_create if !ready?
@@db = ActiveRecord::Base.connection
@@in_connect = false
end
def self.connected?
@@db != nil
end
def self.db
@@db
end
def self.ready?
begin
# for a pretty strange bug, we cannot use ActiveRecord::Base.connection.execute here
# rows = ActiveRecord::Base.connection.execute("select * from sqlite_sequence")
rows = Bento.DB(Database.db_path).execute("select * from sqlite_sequence")
true
rescue
false
end
end
def self.create
connect
end
def self.migrate
ActiveRecord::Migrator.migrate(Config.confetti_path/"db/migrate")
end
def self.execute_script(file)
Bento.DB(path: Config.db_path) << File.read(file)
end
def self.dumpSchema
end
def self.dump
end
def self.migration_log
@@migration_log
end
private
def self.internal_create
begin
migrate
data_script = Config.confetti_path/"db/data.sql"
execute_script(data_script) if File.exist?(data_script)
rescue
raise "Creating database #{Database.db_path} failed"
end
end
end # Database
#----------------------------------------------------------------------------------------------
end # module Confetti
#----------------------------------------------------------------------------------------------
module ActiveRecord
#----------------------------------------------------------------------------------------------
module ConnectionHandling
alias_method :old_retrieve_connection, :retrieve_connection
def retrieve_connection
Confetti::Database.connect
old_retrieve_connection
end
end
#----------------------------------------------------------------------------------------------
class Migration
def write(text="")
return if !verbose
log = Confetti::Database.migration_log
if log
log.puts(text)
log.flush
else
puts text
end
end
end
#----------------------------------------------------------------------------------------------
end # module ActiveRecord
#----------------------------------------------------------------------------------------------
| 21.392593 | 98 | 0.550554 |
1849ea79b336350b8c27bd20c4499bae1f856ddf | 7,406 | class Caveats
extend Forwardable
attr_reader :f
def initialize(f)
@f = f
end
def caveats
caveats = []
begin
build = f.build
f.build = Tab.for_formula(f)
s = f.caveats.to_s
caveats << s.chomp + "\n" unless s.empty?
ensure
f.build = build
end
caveats << keg_only_text
caveats << function_completion_caveats(:bash)
caveats << function_completion_caveats(:zsh)
caveats << function_completion_caveats(:fish)
caveats << plist_caveats
caveats << python_caveats
caveats << elisp_caveats
caveats.compact.join("\n")
end
delegate [:empty?, :to_s] => :caveats
private
def keg
@keg ||= [f.prefix, f.opt_prefix, f.linked_keg].map do |d|
begin
Keg.new(d.resolved_path)
rescue
nil
end
end.compact.first
end
def keg_only_text
return unless f.keg_only?
s = <<-EOS.undent
This formula is keg-only, which means it was not symlinked into #{HOMEBREW_PREFIX},
because #{f.keg_only_reason.to_s.chomp}.
EOS
if f.bin.directory? || f.sbin.directory?
s << "\nIf you need to have this software first in your PATH run:\n"
if f.bin.directory?
s << " #{Utils::Shell.prepend_path_in_profile(f.opt_bin.to_s)}\n"
end
if f.sbin.directory?
s << " #{Utils::Shell.prepend_path_in_profile(f.opt_sbin.to_s)}\n"
end
end
if f.lib.directory? || f.include.directory?
s << "\nFor compilers to find this software you may need to set:\n"
s << " LDFLAGS: -L#{f.opt_lib}\n" if f.lib.directory?
s << " CPPFLAGS: -I#{f.opt_include}\n" if f.include.directory?
if which("pkg-config") &&
((f.lib/"pkgconfig").directory? || (f.share/"pkgconfig").directory?)
s << "For pkg-config to find this software you may need to set:\n"
s << " PKG_CONFIG_PATH: #{f.opt_lib}/pkgconfig\n" if (f.lib/"pkgconfig").directory?
s << " PKG_CONFIG_PATH: #{f.opt_share}/pkgconfig\n" if (f.share/"pkgconfig").directory?
end
end
s << "\n"
end
def function_completion_caveats(shell)
return unless keg
return unless which(shell.to_s)
completion_installed = keg.completion_installed?(shell)
functions_installed = keg.functions_installed?(shell)
return unless completion_installed || functions_installed
installed = []
installed << "completions" if completion_installed
installed << "functions" if functions_installed
case shell
when :bash
<<-EOS.undent
Bash completion has been installed to:
#{HOMEBREW_PREFIX}/etc/bash_completion.d
EOS
when :zsh
<<-EOS.undent
zsh #{installed.join(" and ")} have been installed to:
#{HOMEBREW_PREFIX}/share/zsh/site-functions
EOS
when :fish
fish_caveats = "fish #{installed.join(" and ")} have been installed to:"
fish_caveats << "\n #{HOMEBREW_PREFIX}/share/fish/vendor_completions.d" if completion_installed
fish_caveats << "\n #{HOMEBREW_PREFIX}/share/fish/vendor_functions.d" if functions_installed
fish_caveats
end
end
def python_caveats
return unless keg
return unless keg.python_site_packages_installed?
s = nil
homebrew_site_packages = Language::Python.homebrew_site_packages
user_site_packages = Language::Python.user_site_packages "python"
pth_file = user_site_packages/"homebrew.pth"
instructions = <<-EOS.undent.gsub(/^/, " ")
mkdir -p #{user_site_packages}
echo 'import site; site.addsitedir("#{homebrew_site_packages}")' >> #{pth_file}
EOS
if f.keg_only?
keg_site_packages = f.opt_prefix/"lib/python2.7/site-packages"
unless Language::Python.in_sys_path?("python", keg_site_packages)
s = <<-EOS.undent
If you need Python to find bindings for this keg-only formula, run:
echo #{keg_site_packages} >> #{homebrew_site_packages/f.name}.pth
EOS
s += instructions unless Language::Python.reads_brewed_pth_files?("python")
end
return s
end
return if Language::Python.reads_brewed_pth_files?("python")
if !Language::Python.in_sys_path?("python", homebrew_site_packages)
s = <<-EOS.undent
Python modules have been installed and Homebrew's site-packages is not
in your Python sys.path, so you will not be able to import the modules
this formula installed. If you plan to develop with these modules,
please run:
EOS
s += instructions
elsif keg.python_pth_files_installed?
s = <<-EOS.undent
This formula installed .pth files to Homebrew's site-packages and your
Python isn't configured to process them, so you will not be able to
import the modules this formula installed. If you plan to develop
with these modules, please run:
EOS
s += instructions
end
s
end
def elisp_caveats
return if f.keg_only?
return unless keg
return unless keg.elisp_installed?
<<-EOS.undent
Emacs Lisp files have been installed to:
#{HOMEBREW_PREFIX}/share/emacs/site-lisp/#{f.name}
EOS
end
def plist_caveats
s = []
if f.plist || (keg&.plist_installed?)
plist_domain = f.plist_path.basename(".plist")
# we readlink because this path probably doesn't exist since caveats
# occurs before the link step of installation
# Yosemite security measures mildly tighter rules:
# https://github.com/Homebrew/legacy-homebrew/issues/33815
if !plist_path.file? || !plist_path.symlink?
if f.plist_startup
s << "To have launchd start #{f.full_name} now and restart at startup:"
s << " sudo brew services start #{f.full_name}"
else
s << "To have launchd start #{f.full_name} now and restart at login:"
s << " brew services start #{f.full_name}"
end
# For startup plists, we cannot tell whether it's running on launchd,
# as it requires for `sudo launchctl list` to get real result.
elsif f.plist_startup
s << "To restart #{f.full_name} after an upgrade:"
s << " sudo brew services restart #{f.full_name}"
elsif Kernel.system "/bin/launchctl list #{plist_domain} &>/dev/null"
s << "To restart #{f.full_name} after an upgrade:"
s << " brew services restart #{f.full_name}"
else
s << "To start #{f.full_name}:"
s << " brew services start #{f.full_name}"
end
if f.plist_manual
s << "Or, if you don't want/need a background service you can just run:"
s << " #{f.plist_manual}"
end
# pbpaste is the system clipboard tool on macOS and fails with `tmux` by default
# check if this is being run under `tmux` to avoid failing
if ENV["TMUX"] && !quiet_system("/usr/bin/pbpaste")
s << "" << "WARNING: brew services will fail when run under tmux."
end
end
s.join("\n") + "\n" unless s.empty?
end
def plist_path
destination = if f.plist_startup
"/Library/LaunchDaemons"
else
"~/Library/LaunchAgents"
end
plist_filename = if f.plist
f.plist_path.basename
else
File.basename Dir["#{keg}/*.plist"].first
end
destination_path = Pathname.new(File.expand_path(destination))
destination_path/plist_filename
end
end
| 32.915556 | 102 | 0.642992 |
6a4e1d44042a16f992292708c7b765966a2a27c9 | 68 | module Mina
module Secrets
VERSION = '2.1.0'.freeze
end
end
| 11.333333 | 28 | 0.661765 |
e871c7a68addff39742cd90eaea2668b218b0cc7 | 10,879 | module Azure
module Armrest
class Configuration
# Clear all class level caches. Typically used for testing only.
def self.clear_caches
token_cache.clear
end
# Used to store unique token information.
def self.token_cache
@token_cache ||= Hash.new { |h, k| h[k] = [] }
end
# Retrieve the cached token for a configuration.
# Return both the token and its expiration date, or nil if not cached
def self.retrieve_token(configuration)
token_cache[configuration.hash]
end
# Cache the token for a configuration that a token has been fetched from Azure
def self.cache_token(configuration)
raise ArgumentError, "Configuration does not have a token" if configuration.token.nil?
token_cache[configuration.hash] = [configuration.token, configuration.token_expiration]
end
# The api-version string
attr_accessor :api_version
# The client ID used to gather token information.
attr_accessor :client_id
# The client key used to gather token information.
attr_accessor :client_key
# The tenant ID used to gather token information.
attr_accessor :tenant_id
# The subscription ID used for each http request.
attr_reader :subscription_id
# The resource group used for http requests.
attr_accessor :resource_group
# The grant type. The default is client_credentials.
attr_accessor :grant_type
# The content type specified for http requests. The default is 'application/json'
attr_accessor :content_type
# The accept type specified for http request results. The default is 'application/json'
attr_accessor :accept
# Proxy to be used for all http requests.
attr_reader :proxy
# SSL version to be used for all http requests.
attr_accessor :ssl_version
# SSL verify mode for all http requests.
attr_accessor :ssl_verify
# Timeout value for http requests in seconds. The default is 60.
attr_accessor :timeout
# Namespace providers, their resource types, locations and supported api-version strings.
attr_reader :providers
# Maximum number of threads to use within methods that use Parallel for thread pooling.
attr_accessor :max_threads
# The environment object which determines various endpoint URL's. The
# default is Azure::Armrest::Environment::Public.
attr_accessor :environment
# Maximum number of attempts to retry an http request in the case of
# request throttling or server side service issues.
attr_accessor :max_retries
# Yields a new Azure::Armrest::Configuration objects. Note that you must
# specify a client_id, client_key, tenant_id. The subscription_id is optional
# but should be specified in most cases. All other parameters are optional.
#
# Example:
#
# config = Azure::Armrest::Configuration.new(
# :client_id => 'xxxx',
# :client_key => 'yyyy',
# :tenant_id => 'zzzz',
# :subscription_id => 'abcd'
# )
#
# If you specify a :resource_group, that group will be used for resource
# group based service class requests. Otherwise, you will need to specify
# a resource group for most service methods.
#
# Although you can specify an :api_version, it is typically overridden
# by individual service classes.
#
# The constructor will also validate that the subscription ID is valid
# if present.
#
def initialize(args)
# Use defaults, and override with provided arguments
options = {
:api_version => '2015-01-01',
:accept => 'application/json',
:content_type => 'application/json',
:grant_type => 'client_credentials',
:proxy => ENV['http_proxy'],
:ssl_version => 'TLSv1',
:timeout => 60,
:max_threads => 10,
:max_retries => 3,
:environment => Azure::Armrest::Environment::Public
}.merge(args.symbolize_keys)
# Avoid thread safety issues for VCR testing.
options[:max_threads] = 1 if defined?(VCR)
user_token = options.delete(:token)
user_token_expiration = options.delete(:token_expiration)
# We need to ensure these are set before subscription_id=
@tenant_id = options.delete(:tenant_id)
@client_id = options.delete(:client_id)
@client_key = options.delete(:client_key)
unless client_id && client_key && tenant_id
raise ArgumentError, "client_id, client_key, and tenant_id must all be specified"
end
# Then set the remaining options automatically
options.each { |key, value| send("#{key}=", value) }
if user_token && user_token_expiration
set_token(user_token, user_token_expiration)
elsif user_token || user_token_expiration
raise ArgumentError, "token and token_expiration must be both specified"
end
end
def hash
[environment.name, tenant_id, client_id, client_key].join('_').hash
end
# Allow for strings or URI objects when assigning a proxy.
#
def proxy=(value)
@proxy = value ? value.to_s : value
end
# Set the subscription ID, and validate the value. This also sets
# provider information.
#
def subscription_id=(value)
@subscription_id = value
return if value.nil? || value.empty?
validate_subscription
@providers = fetch_providers
set_provider_api_versions
value
end
def eql?(other)
return true if equal?(other)
return false unless self.class == other.class
tenant_id == other.tenant_id && client_id == other.client_id && client_key == other.client_key
end
# Returns the token for the current cache key, or sets it if it does not
# exist or it has expired.
#
def token
ensure_token
@token
end
# Set the token value and expiration time.
#
def set_token(token, token_expiration)
validate_token_time(token_expiration)
@token, @token_expiration = token, token_expiration.utc
self.class.cache_token(self)
end
# Returns the expiration datetime of the current token
#
def token_expiration
ensure_token
@token_expiration
end
# Return the default api version for the given provider and service
def provider_default_api_version(provider, service)
if @provider_api_versions
@provider_api_versions[provider.downcase][service.downcase]
else
nil # Typically only for the fetch_providers method.
end
end
# Returns the logger instance. It might be initially set through a log
# file path, file handler, or already a logger instance.
#
def self.log
RestClient.log
end
# Sets the log to +output+, which can be a file, a file handle, or
# a logger instance
#
def self.log=(output)
output = Logger.new(output) unless output.kind_of?(Logger)
RestClient.log = output
end
# Returns a list of subscriptions for the current configuration object.
#
def subscriptions
Azure::Armrest::SubscriptionService.new(self).list
end
private
# Validate the subscription ID for the given credentials. Returns the
# subscription ID if valid.
#
# If the subscription ID that was provided in the constructor cannot
# be found within the list of valid subscriptions, then an error is
# raised.
#
# If the subscription ID that was provided is found but disabled
# then a warning will be issued, but no error will be raised.
#
def validate_subscription
found = subscriptions.find { |sub| sub.subscription_id == subscription_id }
unless found
raise ArgumentError, "Subscription ID '#{subscription_id}' not found"
end
if found.state.casecmp('enabled') != 0
warn "Subscription '#{found.subscription_id}' found but not enabled."
end
end
def ensure_token
@token, @token_expiration = self.class.retrieve_token(self) if @token.nil?
fetch_token if @token.nil? || Time.now.utc > @token_expiration
end
# Don't allow tokens from the past to be set.
#
def validate_token_time(time)
if time.utc < Time.now.utc
raise ArgumentError, 'token_expiration date invalid'
end
end
# Build a one-time lookup hash that sets the appropriate api-version
# string for a given provider and resource type. If possible, select
# a non-preview version that is not set in the future. Otherwise, just
# just the most recent one.
#
def set_provider_api_versions
# A lookup table for getting api-version strings per provider and service.
@provider_api_versions = Hash.new { |hash, key| hash[key] = {} }
providers.each do |rp|
rp.resource_types.each do |rt|
if rt.api_versions.any? { |v| v !~ /preview/i && Time.parse(v).utc <= Time.now.utc }
api_version = rt.api_versions.reject do |version|
version =~ /preview/i || Time.parse(version).utc > Time.now.utc
end.first
else
api_version = rt.api_versions.first
end
namespace = rp['namespace'].downcase # Avoid name collision
resource_type = rt.resource_type.downcase
@provider_api_versions[namespace][resource_type] = api_version
end
end
end
def fetch_providers
Azure::Armrest::ResourceProviderService.new(self).list
end
def fetch_token
token_url = File.join(environment.active_directory_authority, tenant_id, 'oauth2', 'token')
response = JSON.parse(
ArmrestService.send(
:rest_post,
:url => token_url,
:proxy => proxy,
:ssl_version => ssl_version,
:ssl_verify => ssl_verify,
:timeout => timeout,
:payload => {
:grant_type => grant_type,
:client_id => client_id,
:client_secret => client_key,
:resource => environment.active_directory_resource_id
}
)
)
@token = 'Bearer ' + response['access_token']
@token_expiration = Time.now.utc + response['expires_in'].to_i
self.class.cache_token(self)
end
end
end
end
| 33.996875 | 102 | 0.629562 |
bbd53a489f73fb48622ff3eebabff8aa7de31c17 | 5,527 | module POM
class Project
##
# Mixin adds methods for accessing a project's gemspec and
# other gem releated features.
#
module GemUtils
public
# TODO: Replace everything below here with Indexer code and tie into above.
# Create a Gem::Specification from a POM::Project. Because POM metadata
# is extensive a fairly complete a Gem::Specification can be created from
# it which is sufficient for almost all needs.
#
# TODO: However there are still a few features that need address, such
# as signatures.
def to_gemspec(options={})
require_rubygems
if metadata.resources
homepage = metadata.resources.homepage
else
homepage = nil
end
if homepage && md = /(\w+).rubyforge.org/.match(homepage)
rubyforge_project = md[1]
else
# b/c it has to be something according to Eric Hodel.
rubyforge_project = metadata.name.to_s
end
#TODO: may be able to get this from project method
if news = Dir[root + 'NEWS{,.txt}'].first
install_message = File.read(news)
end
::Gem::Specification.new do |spec|
spec.name = self.name.to_s
spec.version = self.version.to_s
spec.require_paths = self.loadpath.to_a
spec.summary = metadata.summary.to_s
spec.description = metadata.description.to_s
spec.authors = metadata.authors.to_a
spec.email = metadata.email.to_s
spec.licenses = metadata.licenses.to_a
spec.homepage = metadata.homepage.to_s
# -- platform --
# TODO: how to handle multiple platforms?
spec.platform = options[:platform] #|| verfile.platform #'ruby' ???
#if metadata.platform != 'ruby'
# spec.require_paths.concat(spec.require_paths.collect{ |d| File.join(d, platform) })
#end
# -- rubyforge project --
spec.rubyforge_project = rubyforge_project
# -- compiled extensions --
spec.extensions = options[:extensions] || self.extensions
# -- dependencies --
case options[:gemfile]
#when String
# gemfile = root.glob(options[:gemfile]).first # TODO: Alternate gemfile
when nil, true
gemfile = root.glob('Gemfile').first
else
gemfile = nil
end
if gemfile
require 'bundler'
spec.add_bundler_dependencies
else
metadata.requirements.each do |dep|
if dep.development?
spec.add_development_dependency( *[dep.name, dep.constraint].compact )
else
next if dep.optional?
spec.add_runtime_dependency( *[dep.name, dep.constraint].compact )
end
end
end
# TODO: considerations?
#spec.requirements = options[:requirements] || package.consider
# -- executables --
# TODO: bin/ is a POM convention, is there are reason to do otherwise?
spec.bindir = options[:bindir] || "bin"
spec.executables = options[:executables] || self.executables
# -- rdocs (argh!) --
readme = root.glob_relative('README{,.*}', File::FNM_CASEFOLD).first
extra = options[:extra_rdoc_files] || []
rdocfiles = []
rdocfiles << readme.to_s if readme
rdocfiles.concat(extra)
rdocfiles.uniq!
rdoc_options = [] #['--inline-source']
rdoc_options.concat ["--title", "#{metadata.title} API"] #if metadata.title
rdoc_options.concat ["--main", readme.to_s] if readme
spec.extra_rdoc_files = rdocfiles
spec.rdoc_options = rdoc_options
# -- distributed files --
if manifest.exist?
filelist = manifest.select{ |f| File.file?(f) }
spec.files = filelist
else
spec.files = root.glob_relative("**/*").map{ |f| f.to_s } # metadata.distribute ?
end
# DEPRECATED: -- test files --
#spec.test_files = manifest.select do |f|
# File.basename(f) =~ /test\// && File.extname(f) == '.rb'
#end
if install_message
spec.post_install_message = install_message
end
end
end
# Import a Gem::Specification into a POM::Project. This is intended to make it
# farily easy to build a set of POM metadata files from pre-existing gemspec.
def import_gemspec(gemspec=nil)
gemspec = gemspec || self.gemspec
profile.name = gemspec.name
profile.version = gemspec.version.to_s
profile.path = gemspec.require_paths
#metadata.engines = gemspec.platform
profile.title = gemspec.name.capitalize
profile.summary = gemspec.summary
profile.description = gemspec.description
profile.authors = gemspec.authors
profile.contact = gemspec.email
profile.resources.homepage = gemspec.homepage
#metadata.extensions = gemspec.extensions
gemspec.dependencies.each do |d|
next unless d.type == :runtime
requires << "#{d.name} #{d.version_requirements}"
end
end
end #module RubyGems
end #class Project
end #module POM
| 32.321637 | 96 | 0.57391 |
4a47090dc0a3c9bb2cd2763d6aff6a97d86e0e1d | 3,156 | # FriendlyId Global Configuration
#
# Use this to set up shared configuration options for your entire application.
# Any of the configuration options shown here can also be applied to single
# models by passing arguments to the `friendly_id` class method or defining
# methods in your model.
#
# To learn more, check out the guide:
#
# http://norman.github.io/friendly_id/file.Guide.html
FriendlyId.defaults do |config|
# ## Reserved Words
#
# Some words could conflict with Rails's routes when used as slugs, or are
# undesirable to allow as slugs. Edit this list as needed for your app.
config.use :reserved
config.reserved_words = %w(new edit index session login logout users admin
stylesheets assets javascripts images)
# ## Friendly Finders
#
# Uncomment this to use friendly finders in all models. By default, if
# you wish to find a record by its friendly id, you must do:
#
# MyModel.friendly.find('foo')
#
# If you uncomment this, you can do:
#
# MyModel.find('foo')
#
# This is significantly more convenient but may not be appropriate for
# all applications, so you must explicity opt-in to this behavior. You can
# always also configure it on a per-model basis if you prefer.
#
# Something else to consider is that using the :finders addon boosts
# performance because it will avoid Rails-internal code that makes runtime
# calls to `Module.extend`.
#
# config.use :finders
#
# ## Slugs
#
# Most applications will use the :slugged module everywhere. If you wish
# to do so, uncomment the following line.
#
# config.use :slugged
#
# By default, FriendlyId's :slugged addon expects the slug column to be named
# 'slug', but you can change it if you wish.
#
# config.slug_column = 'slug'
#
# When FriendlyId can not generate a unique ID from your base method, it
# appends a UUID, separated by a single dash. You can configure the character
# used as the separator. If you're upgrading from FriendlyId 4, you may wish
# to replace this with two dashes.
#
# config.sequence_separator = '-'
#
# ## Tips and Tricks
#
# ### Controlling when slugs are generated
#
# As of FriendlyId 5.0, new slugs are generated only when the slug field is
# nil, but if you're using a column as your base method can change this
# behavior by overriding the `should_generate_new_friendly_id` method that
# FriendlyId adds to your model. The change below makes FriendlyId 5.0 behave
# more like 4.0.
#
# config.use Module.new {
# def should_generate_new_friendly_id?
# slug.blank? || <your_column_name_here>_changed?
# end
# }
#
# FriendlyId uses Rails's `parameterize` method to generate slugs, but for
# languages that don't use the Roman alphabet, that's not usually suffient.
# Here we use the Babosa library to transliterate Russian Cyrillic slugs to
# ASCII. If you use this, don't forget to add "babosa" to your Gemfile.
#
# config.use Module.new {
# def normalize_friendly_id(text)
# text.to_slug.normalize! :transliterations => [:russian, :latin]
# end
# }
end
| 35.460674 | 79 | 0.704689 |
ede9e271bd4292a52eb0aaf0120c67f9d51ebd2d | 1,749 | #
# Be sure to run `pod lib lint Ents.podspec' to ensure this is a
# valid spec before submitting.
#
# Any lines starting with a # are optional, but their use is encouraged
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
s.name = 'Ents'
s.version = '3.1.8'
s.summary = 'A collection of handy extensions for Swift.'
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
TODO: Add long description of the pod here.
DESC
s.homepage = 'https://github.com/averello/Ents'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'Georges Boumis' => '[email protected]' }
s.source = { :git => 'https://github.com/averello/Ents.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'Ents/Classes/**/*'
s.xcconfig = {
"OTHER_SWIFT_FLAGS[config=Debug]" => '-DDEBUG',
"SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Debug]" => 'DEBUG',
"SWIFT_VERSION" => '5.0'
}
# s.resource_bundles = {
# 'Ents' => ['Ents/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 35.693878 | 97 | 0.632361 |
ac803885244be22463760343ab66e0c10afef3a2 | 263 | # frozen_string_literal: true
FactoryBot.define do
factory :webauthn_registration do
credential_xid { SecureRandom.base64(88) }
public_key { SecureRandom.base64(103) }
name { FFaker::BaconIpsum.characters(10) }
counter { 1 }
user
end
end
| 21.916667 | 46 | 0.714829 |
08f581f320c696163c144dd23f563d5ddc2f760c | 750 | require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe 'Experience' do
describe '::list' do
subject { ExperiencesSpain::Experience.list }
context 'when there is no experiences' do
stub_experiences_api(:experience, :list, :empty)
it { is_expected.to be_empty }
it { is_expected.to be_kind_of(Array) }
end
context 'when there is one or more experiences' do
stub_experiences_api(:experience, :list, :not_empty)
it { is_expected.not_to be_empty }
it { is_expected.to be_kind_of(Array) }
it 'should be a kind of Array of Experience objects' do
subject.each { |element| expect(element).to be_kind_of(ExperiencesSpain::Experience) }
end
end
end
end
| 30 | 94 | 0.686667 |
213effcb283ccb46f659cd855a8603df9c7285f1 | 22,310 | # -*- encoding: utf-8 -*-
#
# Author:: Fletcher Nichol (<[email protected]>)
#
# Copyright (C) 2013, Fletcher Nichol
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require_relative '../../spec_helper'
require 'kitchen/errors'
require 'kitchen/util'
require 'kitchen/loader/yaml'
class Yamled
attr_accessor :foo
end
describe Kitchen::Loader::YAML do
let(:loader) do
Kitchen::Loader::YAML.new(:project_config => "/tmp/.kitchen.yml")
end
before do
FakeFS.activate!
FileUtils.mkdir_p("/tmp")
end
after do
FakeFS.deactivate!
FakeFS::FileSystem.clear
end
describe ".initialize" do
it "sets project_config based on Dir.pwd by default" do
stub_file(File.join(Dir.pwd, '.kitchen.yml'), Hash.new)
loader = Kitchen::Loader::YAML.new
loader.diagnose[:project_config][:filename].
must_equal File.expand_path(File.join(Dir.pwd, '.kitchen.yml'))
end
it "sets project_config from parameter, if given" do
stub_file('/tmp/crazyfunkytown.file', Hash.new)
loader = Kitchen::Loader::YAML.new(
:project_config => '/tmp/crazyfunkytown.file')
loader.diagnose[:project_config][:filename].
must_match %r{/tmp/crazyfunkytown.file$}
end
it "sets local_config based on Dir.pwd by default" do
stub_file(File.join(Dir.pwd, '.kitchen.local.yml'), Hash.new)
loader = Kitchen::Loader::YAML.new
loader.diagnose[:local_config][:filename].
must_equal File.expand_path(File.join(Dir.pwd, '.kitchen.local.yml'))
end
it "sets local_config based on location of project_config by default" do
stub_file('/tmp/.kitchen.local.yml', Hash.new)
loader = Kitchen::Loader::YAML.new(
:project_config => '/tmp/.kitchen.yml')
loader.diagnose[:local_config][:filename].
must_match %r{/tmp/.kitchen.local.yml$}
end
it "sets local_config from parameter, if given" do
stub_file('/tmp/crazyfunkytown.file', Hash.new)
loader = Kitchen::Loader::YAML.new(
:local_config => '/tmp/crazyfunkytown.file')
loader.diagnose[:local_config][:filename].
must_match %r{/tmp/crazyfunkytown.file$}
end
it "sets global_config based on ENV['HOME'] by default" do
stub_file(File.join(ENV['HOME'], '.kitchen/config.yml'), Hash.new)
loader = Kitchen::Loader::YAML.new
loader.diagnose[:global_config][:filename].must_equal File.expand_path(
File.join(ENV['HOME'], '.kitchen/config.yml'))
end
it "sets global_config from parameter, if given" do
stub_file('/tmp/crazyfunkytown.file', Hash.new)
loader = Kitchen::Loader::YAML.new(
:global_config => '/tmp/crazyfunkytown.file')
loader.diagnose[:global_config][:filename].
must_match %r{/tmp/crazyfunkytown.file$}
end
end
describe "#read" do
it "returns a hash of kitchen.yml with symbolized keys" do
stub_yaml!({
'foo' => 'bar'
})
loader.read.must_equal({ :foo => 'bar' })
end
it "deep merges in kitchen.local.yml configuration with kitchen.yml" do
stub_yaml!(".kitchen.yml", {
'common' => { 'xx' => 1 },
'a' => 'b'
})
stub_yaml!(".kitchen.local.yml", {
'common' => { 'yy' => 2 },
'c' => 'd'
})
loader.read.must_equal({
:a => 'b',
:c => 'd',
:common => { :xx => 1, :yy => 2 }
})
end
it "deep merges in a global config file with all other configs" do
stub_yaml!(".kitchen.yml", {
'common' => { 'xx' => 1 },
'a' => 'b'
})
stub_yaml!(".kitchen.local.yml", {
'common' => { 'yy' => 2 },
'c' => 'd'
})
stub_global!({
'common' => { 'zz' => 3 },
'e' => 'f'
})
loader.read.must_equal({
:a => 'b',
:c => 'd',
:e => 'f',
:common => { :xx => 1, :yy => 2, :zz => 3 }
})
end
it "merges kitchen.local.yml over configuration in kitchen.yml" do
stub_yaml!(".kitchen.yml", {
'common' => { 'thekey' => 'nope' }
})
stub_yaml!(".kitchen.local.yml", {
'common' => { 'thekey' => 'yep' }
})
loader.read.must_equal({ :common => { :thekey => 'yep' } })
end
it "merges global config over both kitchen.local.yml and kitchen.yml" do
stub_yaml!(".kitchen.yml", {
'common' => { 'thekey' => 'nope' }
})
stub_yaml!(".kitchen.local.yml", {
'common' => { 'thekey' => 'yep' }
})
stub_global!({
'common' => { 'thekey' => 'kinda' }
})
loader.read.must_equal({ :common => { :thekey => 'kinda' } })
end
NORMALIZED_KEYS = {
"driver" => "name",
"provisioner" => "name",
"busser" => "version"
}
NORMALIZED_KEYS.each do |key, default_key|
describe "normalizing #{key} config hashes" do
it "merges local with #{key} string value over yaml with hash value" do
stub_yaml!(".kitchen.yml", {
key => { 'dakey' => 'ya' }
})
stub_yaml!(".kitchen.local.yml", {
key => 'namey'
})
loader.read.must_equal({
key.to_sym => { default_key.to_sym => "namey", :dakey => 'ya' }
})
end
it "merges local with #{key} hash value over yaml with string value" do
stub_yaml!(".kitchen.yml", {
key => 'namey'
})
stub_yaml!(".kitchen.local.yml", {
key => { 'dakey' => 'ya' }
})
loader.read.must_equal({
key.to_sym => { default_key.to_sym => "namey", :dakey => 'ya' }
})
end
it "merges local with #{key} nil value over yaml with hash value" do
stub_yaml!(".kitchen.yml", {
key => { 'dakey' => 'ya' }
})
stub_yaml!(".kitchen.local.yml", {
key => nil
})
loader.read.must_equal({
key.to_sym => { :dakey => 'ya' }
})
end
it "merges local with #{key} hash value over yaml with nil value" do
stub_yaml!(".kitchen.yml", {
key => 'namey'
})
stub_yaml!(".kitchen.local.yml", {
key => nil
})
loader.read.must_equal({
key.to_sym => { default_key.to_sym => "namey" }
})
end
it "merges global with #{key} string value over yaml with hash value" do
stub_yaml!(".kitchen.yml", {
key => { 'dakey' => 'ya' }
})
stub_global!({
key => 'namey'
})
loader.read.must_equal({
key.to_sym => { default_key.to_sym => "namey", :dakey => 'ya' }
})
end
it "merges global with #{key} hash value over yaml with string value" do
stub_yaml!(".kitchen.yml", {
key => 'namey'
})
stub_global!({
key => { 'dakey' => 'ya' }
})
loader.read.must_equal({
key.to_sym => { default_key.to_sym => "namey", :dakey => 'ya' }
})
end
it "merges global with #{key} nil value over yaml with hash value" do
stub_yaml!(".kitchen.yml", {
key => { 'dakey' => 'ya' }
})
stub_global!({
key => nil
})
loader.read.must_equal({
key.to_sym => { :dakey => 'ya' }
})
end
it "merges global with #{key} hash value over yaml with nil value" do
stub_yaml!(".kitchen.yml", {
key => nil
})
stub_global!({
key => { 'dakey' => 'ya' }
})
loader.read.must_equal({
key.to_sym => { :dakey => 'ya' }
})
end
it "merges global, local, over yaml with mixed hash, string, nil values" do
stub_yaml!(".kitchen.yml", {
key => nil
})
stub_yaml!(".kitchen.local.yml", {
key => "namey"
})
stub_global!({
key => { 'dakey' => 'ya' }
})
loader.read.must_equal({
key.to_sym => { default_key.to_sym => "namey", :dakey => 'ya' }
})
end
end
end
it "handles a kitchen.local.yml with no yaml elements" do
stub_yaml!(".kitchen.yml", {
'a' => 'b'
})
stub_yaml!(".kitchen.local.yml", Hash.new)
loader.read.must_equal({ :a => 'b' })
end
it "handles a kitchen.yml with no yaml elements" do
stub_yaml!(".kitchen.yml", Hash.new)
stub_yaml!(".kitchen.local.yml", {
'a' => 'b'
})
loader.read.must_equal({ :a => 'b' })
end
it "handles a kitchen.yml with yaml elements that parse as nil" do
stub_yaml!(".kitchen.yml", nil)
stub_yaml!(".kitchen.local.yml", {
'a' => 'b'
})
loader.read.must_equal({ :a => 'b' })
end
it "raises an UserError if the config_file does not exist" do
proc { loader.read }.must_raise Kitchen::UserError
end
it "arbitrary objects aren't deserialized in kitchen.yml" do
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.yml", "wb") do |f|
f.write <<-YAML.gsub(/^ {10}/, '')
--- !ruby/object:Yamled
foo: bar
YAML
end
loader.read.class.wont_equal Yamled
loader.read.class.must_equal Hash
loader.read.must_equal({ :foo => 'bar' })
end
it "arbitrary objects aren't deserialized in kitchen.local.yml" do
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.local.yml", "wb") do |f|
f.write <<-YAML.gsub(/^ {10}/, '')
--- !ruby/object:Yamled
wakka: boop
YAML
end
stub_yaml!(".kitchen.yml", Hash.new)
loader.read.class.wont_equal Yamled
loader.read.class.must_equal Hash
loader.read.must_equal({ :wakka => 'boop' })
end
it "raises a UserError if kitchen.yml cannot be parsed" do
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.yml", "wb") { |f| f.write '&*%^*' }
err = proc { loader.read }.must_raise Kitchen::UserError
err.message.must_match Regexp.new(
"Error parsing ([a-zA-Z]:)?\/tmp\/\.kitchen\.yml")
end
it "raises a UserError if kitchen.yml cannot be parsed" do
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.yml", "wb") { |f| f.write 'uhoh' }
err = proc { loader.read }.must_raise Kitchen::UserError
err.message.must_match Regexp.new(
"Error parsing ([a-zA-Z]:)?\/tmp\/\.kitchen\.yml")
end
it "handles a kitchen.yml if it is a commented out YAML document" do
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.yml", "wb") { |f| f.write '#---\n' }
loader.read.must_equal(Hash.new)
end
it "raises a UserError if kitchen.local.yml cannot be parsed" do
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.local.yml", "wb") { |f| f.write '&*%^*' }
stub_yaml!(".kitchen.yml", Hash.new)
proc { loader.read }.must_raise Kitchen::UserError
end
it "evaluates kitchen.yml through erb before loading by default" do
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.yml", "wb") do |f|
f.write <<-'YAML'.gsub(/^ {10}/, '')
---
name: <%= "AHH".downcase + "choo" %>
YAML
end
loader.read.must_equal({ :name => "ahhchoo" })
end
it "raises a UserError if there is an ERB processing error" do
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.yml", "wb") do |f|
f.write <<-'YAML'.gsub(/^ {10}/, '')
---
<%= poop %>: yep
YAML
end
err = proc { loader.read }.must_raise Kitchen::UserError
err.message.must_match Regexp.new(
"Error parsing ERB content in ([a-zA-Z]:)?\/tmp\/\.kitchen\.yml")
end
it "evaluates kitchen.local.yml through erb before loading by default" do
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.local.yml", "wb") do |f|
f.write <<-'YAML'.gsub(/^ {10}/, '')
---
<% %w{noodle mushroom}.each do |kind| %>
<%= kind %>: soup
<% end %>
YAML
end
stub_yaml!(".kitchen.yml", { 'spinach' => 'salad' })
loader.read.must_equal({
:spinach => 'salad',
:noodle => 'soup',
:mushroom => 'soup'
})
end
it "skips evaluating kitchen.yml through erb if disabled" do
loader = Kitchen::Loader::YAML.new(
:project_config => '/tmp/.kitchen.yml', :process_erb => false)
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.yml", "wb") do |f|
f.write <<-'YAML'.gsub(/^ {10}/, '')
---
name: <%= "AHH".downcase %>
YAML
end
loader.read.must_equal({ :name => '<%= "AHH".downcase %>' })
end
it "skips evaluating kitchen.local.yml through erb if disabled" do
loader = Kitchen::Loader::YAML.new(
:project_config => '/tmp/.kitchen.yml', :process_erb => false)
FileUtils.mkdir_p "/tmp"
File.open("/tmp/.kitchen.local.yml", "wb") do |f|
f.write <<-'YAML'.gsub(/^ {10}/, '')
---
name: <%= "AHH".downcase %>
YAML
end
stub_yaml!(".kitchen.yml", Hash.new)
loader.read.must_equal({ :name => '<%= "AHH".downcase %>' })
end
it "skips kitchen.local.yml if disabled" do
loader = Kitchen::Loader::YAML.new(
:project_config => '/tmp/.kitchen.yml', :process_local => false)
stub_yaml!(".kitchen.yml", {
'a' => 'b'
})
stub_yaml!(".kitchen.local.yml", {
'superawesomesauceadditions' => 'enabled, yo'
})
loader.read.must_equal({ :a => 'b' })
end
it "skips the global config if disabled" do
loader = Kitchen::Loader::YAML.new(
:project_config => '/tmp/.kitchen.yml', :process_global => false)
stub_yaml!(".kitchen.yml", {
'a' => 'b'
})
stub_global!({
'superawesomesauceadditions' => 'enabled, yo'
})
loader.read.must_equal({ :a => 'b' })
end
end
describe "#diagnose" do
it "returns a Hash" do
stub_yaml!(Hash.new)
loader.diagnose.must_be_kind_of(Hash)
end
it "contains erb processing information when true" do
stub_yaml!(Hash.new)
loader.diagnose[:process_erb].must_equal true
end
it "contains erb processing information when false" do
stub_yaml!(Hash.new)
loader = Kitchen::Loader::YAML.new(
:project_config => '/tmp/.kitchen.yml', :process_erb => false)
loader.diagnose[:process_erb].must_equal false
end
it "contains local processing information when true" do
stub_yaml!(Hash.new)
loader.diagnose[:process_local].must_equal true
end
it "contains local processing information when false" do
stub_yaml!(Hash.new)
loader = Kitchen::Loader::YAML.new(
:project_config => '/tmp/.kitchen.yml', :process_local => false)
loader.diagnose[:process_local].must_equal false
end
it "contains global processing information when true" do
stub_yaml!(Hash.new)
loader.diagnose[:process_global].must_equal true
end
it "contains global processing information when false" do
stub_yaml!(Hash.new)
loader = Kitchen::Loader::YAML.new(
:project_config => '/tmp/.kitchen.yml', :process_global => false)
loader.diagnose[:process_global].must_equal false
end
describe "for yaml files" do
before do
stub_yaml!(".kitchen.yml", {
"from_project" => "project",
"common" => { "p" => "pretty" }
})
stub_yaml!(".kitchen.local.yml", {
"from_local" => "local",
"common" => { "l" => "looky" }
})
stub_global!({
"from_global" => "global",
"common" => { "g" => "goody" }
})
end
it "global config contains a filename" do
loader.diagnose[:global_config][:filename].
must_equal File.join(ENV["HOME"], ".kitchen/config.yml")
end
it "global config contains raw data" do
loader.diagnose[:global_config][:raw_data].must_equal({
"from_global" => "global",
"common" => { "g" => "goody" }
})
end
it "project config contains a filename" do
loader.diagnose[:project_config][:filename].
must_match %r{/tmp/.kitchen.yml$}
end
it "project config contains raw data" do
loader.diagnose[:project_config][:raw_data].must_equal({
"from_project" => "project",
"common" => { "p" => "pretty" }
})
end
it "local config contains a filename" do
loader.diagnose[:local_config][:filename].
must_match %r{/tmp/.kitchen.local.yml$}
end
it "local config contains raw data" do
loader.diagnose[:local_config][:raw_data].must_equal({
"from_local" => "local",
"common" => { "l" => "looky" }
})
end
it "combined config contains a nil filename" do
loader.diagnose[:combined_config][:filename].
must_equal nil
end
it "combined config contains raw data" do
loader.diagnose[:combined_config][:raw_data].must_equal({
"from_global" => "global",
"from_project" => "project",
"from_local" => "local",
"common" => {
"g" => "goody",
"p" => "pretty",
"l" => "looky"
}
})
end
describe "for global on error" do
before do
FileUtils.mkdir_p(File.join(ENV["HOME"], ".kitchen"))
File.open(File.join(ENV["HOME"], ".kitchen/config.yml"), "wb") do |f|
f.write '&*%^*'
end
end
it "uses an error hash with the raw file contents" do
loader.diagnose[:global_config][:raw_data][:error][:raw_file].
must_equal "&*%^*"
end
it "uses an error hash with the exception" do
loader.diagnose[:global_config][:raw_data][:error][:exception].
must_match %r{Kitchen::UserError}
end
it "uses an error hash with the exception message" do
loader.diagnose[:global_config][:raw_data][:error][:message].
must_match %r{Error parsing}
end
it "uses an error hash with the exception backtrace" do
loader.diagnose[:global_config][:raw_data][:error][:backtrace].
must_be_kind_of Array
end
end
describe "for project on error" do
before do
File.open("/tmp/.kitchen.yml", "wb") do |f|
f.write '&*%^*'
end
end
it "uses an error hash with the raw file contents" do
loader.diagnose[:project_config][:raw_data][:error][:raw_file].
must_equal "&*%^*"
end
it "uses an error hash with the exception" do
loader.diagnose[:project_config][:raw_data][:error][:exception].
must_match %r{Kitchen::UserError}
end
it "uses an error hash with the exception message" do
loader.diagnose[:project_config][:raw_data][:error][:message].
must_match %r{Error parsing}
end
it "uses an error hash with the exception backtrace" do
loader.diagnose[:project_config][:raw_data][:error][:backtrace].
must_be_kind_of Array
end
end
describe "for local on error" do
before do
File.open("/tmp/.kitchen.local.yml", "wb") do |f|
f.write '&*%^*'
end
end
it "uses an error hash with the raw file contents" do
loader.diagnose[:local_config][:raw_data][:error][:raw_file].
must_equal "&*%^*"
end
it "uses an error hash with the exception" do
loader.diagnose[:local_config][:raw_data][:error][:exception].
must_match %r{Kitchen::UserError}
end
it "uses an error hash with the exception message" do
loader.diagnose[:local_config][:raw_data][:error][:message].
must_match %r{Error parsing}
end
it "uses an error hash with the exception backtrace" do
loader.diagnose[:local_config][:raw_data][:error][:backtrace].
must_be_kind_of Array
end
end
describe "for combined on error" do
before do
File.open("/tmp/.kitchen.yml", "wb") do |f|
f.write '&*%^*'
end
end
it "uses an error hash with nil raw file contents" do
loader.diagnose[:combined_config][:raw_data][:error][:raw_file].
must_equal nil
end
it "uses an error hash with the exception" do
loader.diagnose[:combined_config][:raw_data][:error][:exception].
must_match %r{Kitchen::UserError}
end
it "uses an error hash with the exception message" do
loader.diagnose[:combined_config][:raw_data][:error][:message].
must_match %r{Error parsing}
end
it "uses an error hash with the exception backtrace" do
loader.diagnose[:combined_config][:raw_data][:error][:backtrace].
must_be_kind_of Array
end
end
end
end
private
def stub_file(path, hash)
FileUtils.mkdir_p(File.dirname(path))
File.open(path, "wb") { |f| f.write(hash.to_yaml) }
end
def stub_yaml!(name = ".kitchen.yml", hash)
stub_file(File.join("/tmp", name), hash)
end
def stub_global!(hash)
stub_file(File.join(File.expand_path(ENV["HOME"]),
".kitchen", "config.yml"), hash)
end
end
| 29.201571 | 83 | 0.552532 |
1874c985d450e001bc804523698963d6eddb0016 | 3,307 | # frozen_string_literal: true
require "extend/ENV"
require "sandbox"
require "timeout"
require "cli/parser"
module Homebrew
module_function
def test_args
Homebrew::CLI::Parser.new do
usage_banner <<~EOS
`test` [<options>] <formula>
Run the test method provided by an installed formula.
There is no standard output or return code, but generally it should notify the
user if something is wrong with the installed formula.
*Example:* `brew install jruby && brew test jruby`
EOS
switch "--devel",
description: "Test the development version of a formula."
switch "--HEAD",
description: "Test the head version of a formula."
switch "--keep-tmp",
description: "Retain the temporary files created for the test."
switch :verbose
switch :debug
conflicts "--devel", "--HEAD"
min_named :formula
end
end
def test
test_args.parse
require "formula_assertions"
args.resolved_formulae.each do |f|
# Cannot test uninstalled formulae
unless f.latest_version_installed?
ofail "Testing requires the latest version of #{f.full_name}"
next
end
# Cannot test formulae without a test method
unless f.test_defined?
ofail "#{f.full_name} defines no test"
next
end
# Don't test unlinked formulae
if !args.force? && !f.keg_only? && !f.linked?
ofail "#{f.full_name} is not linked"
next
end
# Don't test formulae missing test dependencies
missing_test_deps = f.recursive_dependencies do |_, dependency|
Dependency.prune if dependency.installed?
next if dependency.test?
Dependency.prune if dependency.optional?
Dependency.prune if dependency.build?
end.map(&:to_s)
unless missing_test_deps.empty?
ofail "#{f.full_name} is missing test dependencies: #{missing_test_deps.join(" ")}"
next
end
puts "Testing #{f.full_name}"
env = ENV.to_hash
begin
exec_args = %W[
#{RUBY_PATH}
-W0
-I #{$LOAD_PATH.join(File::PATH_SEPARATOR)}
--
#{HOMEBREW_LIBRARY_PATH}/test.rb
#{f.path}
].concat(args.options_only)
if f.head?
exec_args << "--HEAD"
elsif f.devel?
exec_args << "--devel"
end
Utils.safe_fork do
if Sandbox.test?
sandbox = Sandbox.new
f.logs.mkpath
sandbox.record_log(f.logs/"test.sandbox.log")
sandbox.allow_write_temp_and_cache
sandbox.allow_write_log(f)
sandbox.allow_write_xcode
sandbox.allow_write_path(HOMEBREW_PREFIX/"var/cache")
sandbox.allow_write_path(HOMEBREW_PREFIX/"var/homebrew/locks")
sandbox.allow_write_path(HOMEBREW_PREFIX/"var/log")
sandbox.allow_write_path(HOMEBREW_PREFIX/"var/run")
sandbox.exec(*exec_args)
else
exec(*exec_args)
end
end
rescue Exception => e # rubocop:disable Lint/RescueException
ofail "#{f.full_name}: failed"
puts e, e.backtrace
ensure
ENV.replace(env)
end
end
end
end
| 28.025424 | 91 | 0.60629 |
8723453d8261462f9669d7953190d554d5dc3715 | 997 | #
# Cookbook Name:: ntp
# Recipe:: undo
# Author:: Eric G. Wolfe
#
# Copyright 2012, Eric G. Wolfe
# Copyright 2009, Opscode, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
service node['ntp']['service'] do
supports :status => true, :restart => true
action [ :stop, :disable ]
end
node['ntp']['packages'].each do |ntppkg|
package ntppkg do
action :remove
end
end
ruby_block "remove ntp::undo from run list" do
block do
node.run_list.remove("recipe[ntp::undo]")
end
end
| 26.945946 | 74 | 0.717151 |
b948137f0a017150bd6067db29c9811567e343f2 | 620 | # Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
module OCI
module DataFlow::Models
APPLICATION_LANGUAGE_ENUM = [
APPLICATION_LANGUAGE_SCALA = 'SCALA'.freeze,
APPLICATION_LANGUAGE_JAVA = 'JAVA'.freeze,
APPLICATION_LANGUAGE_PYTHON = 'PYTHON'.freeze,
APPLICATION_LANGUAGE_SQL = 'SQL'.freeze
].freeze
end
end
| 44.285714 | 245 | 0.741935 |
38dc911d7cbf75e9ba6d242db4f3c57b8dbb64c2 | 751 | cask "font-iosevka-ss13" do
version "5.0.5"
sha256 "252f24b4d21a4c1094a298e5a47ce434d58888637aab6997cb7f36167ea7fdcd"
url "https://github.com/be5invis/Iosevka/releases/download/v#{version}/ttc-iosevka-ss13-#{version}.zip"
appcast "https://github.com/be5invis/Iosevka/releases.atom"
name "Iosevka SS13"
desc "Sans-serif, slab-serif, monospace and quasi‑proportional typeface family"
homepage "https://github.com/be5invis/Iosevka/"
font "iosevka-ss13-bold.ttc"
font "iosevka-ss13-extrabold.ttc"
font "iosevka-ss13-extralight.ttc"
font "iosevka-ss13-heavy.ttc"
font "iosevka-ss13-light.ttc"
font "iosevka-ss13-medium.ttc"
font "iosevka-ss13-regular.ttc"
font "iosevka-ss13-semibold.ttc"
font "iosevka-ss13-thin.ttc"
end
| 35.761905 | 105 | 0.757656 |
f74b9d402639f2e344f4ca4fbdccd59a1de9af60 | 1,575 | class PasswordResetsController < ApplicationController
before_action :get_user, only: [:edit, :update]
before_action :valid_user, only: [:edit, :update]
before_action :check_expiration, only:[:edit, :update] # (1)への対応
def new
end
def create
@user = User.find_by(email: params[:password_reset][:email].downcase)
if @user
@user.create_reset_digest
@user.send_password_reset_email
flash[:info] = "Email sent with password reset instructions"
redirect_to root_url
else
flash.now[:danger] = "Email address not found"
render 'new'
end
end
def edit
end
def update
if params[:user][:password].empty? # (3)への対応
@user.errors.add(:password, :blank)
render 'edit'
elsif @user.update(user_params) # (4)への対応
@user.update_attribute(:reset_digest, nil)
log_in @user
flash[:success] = "Password has been reset."
redirect_to @user
else
render 'edit' # (2)への対応
end
end
private
def user_params
params.require(:user).permit(:password, :password_confirmation)
end
def get_user
@user = User.find_by(email: params[:email])
end
# 正しいユーザーかどうか確認する
def valid_user
unless (@user && @user.activated? && @user.authenticated?(:reset, params[:id]))
redirect_to root_url
end
end
def check_expiration
if @user.password_reset_expired?
flash[:danger] = "Password reset has expired."
redirect_to new_password_reset_url
end
end
end
| 23.863636 | 85 | 0.635556 |
87f45ab9be4d44c2fa858dcf1df29692b509fd8d | 454 | # generate tags with ripper-tags -f TAGS -R --force --extra=q .
module Hello
class World
attr_reader :a, :b
attr_writer :c, :d
attr_accessor :e, :f
def a_real_method
p gub
p Hello::World
end
def self.class_method
p 'hi'
end
def gub
p 'hi'
end
def question?
p 'hi'
end
def exclamation!
p 'hi'
end
def with_comment # comment
p 'hi'
end
end
end
| 13.352941 | 63 | 0.544053 |
03dc4471a79d8215c59f675c3be265be9e61ca7c | 543 | class AddTimestampsToProjects < ActiveRecord::Migration
def self.up
add_timestamps :projects
add_column :projects, :status, :string
add_column :projects, :materials_needed, :string
add_column :projects, :funding_needed, :integer
add_column :projects, :overview, :text
end
def self.down
remove_timestamps :projects
remove_column :projects, :status
remove_column :projects, :materials_needed
remove_column :projects, :funding_needed
remove_column :projects, :overview
end
end
| 30.166667 | 55 | 0.721915 |
6ac818012fc482f911a18e2e3d2878a0573caaaf | 3,193 | # frozen_string_literal: true
require "dependabot/file_updaters/base"
module Dependabot
module FileUpdaters
module Ruby
class Bundler < Dependabot::FileUpdaters::Base
require_relative "bundler/gemfile_updater"
require_relative "bundler/gemspec_updater"
require_relative "bundler/lockfile_updater"
def self.updated_files_regex
[/^Gemfile$/, /^Gemfile\.lock$/, %r{^[^/]*\.gemspec$}]
end
def updated_dependency_files
updated_files = []
if gemfile && file_changed?(gemfile)
updated_files <<
updated_file(
file: gemfile,
content: updated_gemfile_content(gemfile)
)
end
if lockfile && dependencies.any?(&:appears_in_lockfile?)
updated_files <<
updated_file(file: lockfile, content: updated_lockfile_content)
end
top_level_gemspecs.each do |file|
next unless file_changed?(file)
updated_files <<
updated_file(file: file, content: updated_gemspec_content(file))
end
evaled_gemfiles.each do |file|
next unless file_changed?(file)
updated_files <<
updated_file(file: file, content: updated_gemfile_content(file))
end
updated_files
end
private
def check_required_files
file_names = dependency_files.map(&:name)
if file_names.include?("Gemfile.lock") &&
!file_names.include?("Gemfile")
raise "A Gemfile must be provided if a lockfile is!"
end
return if file_names.any? { |name| name.match?(%r{^[^/]*\.gemspec$}) }
return if file_names.include?("Gemfile")
raise "A gemspec or Gemfile must be provided!"
end
def gemfile
@gemfile ||= get_original_file("Gemfile")
end
def lockfile
@lockfile ||= get_original_file("Gemfile.lock")
end
def evaled_gemfiles
@evaled_gemfiles ||=
dependency_files.
reject { |f| f.name.end_with?(".gemspec") }.
reject { |f| f.name.end_with?(".lock") }.
reject { |f| f.name.end_with?(".ruby-version") }.
reject { |f| f.name == "Gemfile" }
end
def updated_gemfile_content(file)
GemfileUpdater.new(
dependencies: dependencies,
gemfile: file
).updated_gemfile_content
end
def updated_gemspec_content(gemspec)
GemspecUpdater.new(
dependencies: dependencies,
gemspec: gemspec
).updated_gemspec_content
end
def updated_lockfile_content
@updated_lockfile_content ||=
LockfileUpdater.new(
dependencies: dependencies,
dependency_files: dependency_files,
credentials: credentials
).updated_lockfile_content
end
def top_level_gemspecs
dependency_files.select { |f| f.name.match?(%r{^[^/]*\.gemspec$}) }
end
end
end
end
end
| 28.256637 | 80 | 0.57125 |
1a175c64ff9fdc4e57f728872170e599bb0f0459 | 7,584 | #!/usr/bin/env ruby
# This class encapsulates the config data and environmental setup used
# by the various Flapjack components.
#
# "In Australia and New Zealand, small pancakes (about 75 mm in diameter) known as pikelets
# are also eaten. They are traditionally served with jam and/or whipped cream, or solely
# with butter, at afternoon tea, but can also be served at morning tea."
# from http://en.wikipedia.org/wiki/Pancake
require 'monitor'
require 'webrick'
require 'flapjack'
require 'flapjack/notifier'
require 'flapjack/processor'
require 'flapjack/gateways/aws_sns'
require 'flapjack/gateways/jsonapi'
require 'flapjack/gateways/jabber'
require 'flapjack/gateways/oobetet'
require 'flapjack/gateways/pagerduty'
require 'flapjack/gateways/email'
require 'flapjack/gateways/sms_messagenet'
require 'flapjack/gateways/sms_twilio'
require 'flapjack/gateways/web'
require 'flapjack/logger'
module Flapjack
module Pikelet
class Base
attr_accessor :siblings, :pikelet, :redis
def initialize(pikelet_class, shutdown, opts = {})
@pikelet_class = pikelet_class
@config = opts[:config]
@logger = opts[:logger]
@boot_time = opts[:boot_time]
@shutdown = shutdown
@siblings = []
@lock = Monitor.new
@stop_condition = @lock.new_cond
@pikelet = @pikelet_class.new(:lock => @lock,
:stop_condition => @stop_condition, :config => @config,
:logger => @logger)
@finished_condition = @lock.new_cond
end
def start(&block)
@pikelet.siblings = @siblings.map(&:pikelet) if @pikelet.respond_to?(:siblings=)
@thread = Thread.new do
# TODO rename this, it's only relevant in the error case
max_runs = @config['max_runs'] || 1
runs = 0
keep_running = false
shutdown_all = false
loop do
begin
@logger.debug "pikelet start for #{@pikelet_class.name}"
yield
rescue Flapjack::PikeletStop
@logger.debug "pikelet exception stop for #{@pikelet_class.name}"
rescue Flapjack::GlobalStop
@logger.debug "global exception stop for #{@pikelet_class.name}"
@shutdown_thread = @thread
shutdown_all = true
rescue Exception => e
@logger.warn "#{e.class.name} #{e.message}"
trace = e.backtrace
@logger.warn trace.join("\n") if trace
runs += 1
keep_running = (max_runs > 0) && (runs < max_runs)
shutdown_all = !keep_running
end
break unless keep_running
end
@lock.synchronize do
@finished = true
@finished_condition.signal
end
if shutdown_all
@shutdown.call
end
end
end
def reload(cfg, &block)
@logger.configure(cfg['logger'])
yield
end
def stop(&block)
fin = nil
@lock.synchronize do
fin = @finished
end
return if fin
if block_given?
yield
else
case @pikelet.stop_type
when :exception
@lock.synchronize do
@logger.debug "triggering pikelet exception stop for #{@pikelet_class.name}"
@thread.raise Flapjack::PikeletStop
@finished_condition.wait_until { @finished }
end
when :signal
@lock.synchronize do
@logger.debug "triggering pikelet signal stop for #{@pikelet_class.name}"
@pikelet.instance_variable_set('@should_quit', true)
@stop_condition.signal
@finished_condition.wait_until { @finished }
end
end
end
@thread.join
@thread = nil
end
end
class Generic < Flapjack::Pikelet::Base
TYPES = ['notifier', 'processor', 'jabber', 'pagerduty', 'oobetet',
'email', 'sms', 'aws_sns', 'sms_twilio']
def start
super do
@pikelet.start
end
end
# this should only reload if all changes can be applied -- will
# return false to log warning otherwise
def reload(cfg)
return false unless @pikelet.respond_to?(:reload)
super(cfg) { @pikelet.reload(cfg) }
end
end
class HTTP < Flapjack::Pikelet::Base
TYPES = ['web', 'jsonapi']
def start
@pikelet_class.instance_variable_set('@config', @config)
@pikelet_class.instance_variable_set('@logger', @logger)
if @config
port = @config['port']
port = port.nil? ? nil : port.to_i
timeout = @config['timeout']
timeout = timeout.nil? ? 300 : timeout.to_i
end
port = 3001 if (port.nil? || port <= 0 || port > 65535)
super do
@pikelet_class.start if @pikelet_class.respond_to?(:start)
@server = ::WEBrick::HTTPServer.new(:Port => port, :BindAddress => '127.0.0.1',
:AccessLog => [], :Logger => WEBrick::Log::new("/dev/null", 7))
@server.mount "/", Rack::Handler::WEBrick, @pikelet_class
yield @server if block_given?
@server.start
end
end
# this should only reload if all changes can be applied -- will
# return false to log warning otherwise
def reload(cfg)
# TODO fail if port changes
return false unless @pikelet_class.respond_to?(:reload)
super(cfg) { @pikelet_class.reload(cfg) }
end
def stop
super do |thread|
unless @server.nil?
@logger.info "shutting down server"
@server.shutdown
@logger.info "shut down server"
end
@pikelet_class.stop(thread) if @pikelet_class.respond_to?(:stop)
end
end
end
WRAPPERS = [Flapjack::Pikelet::Generic, Flapjack::Pikelet::HTTP]
TYPES = {'jsonapi' => [Flapjack::Gateways::JSONAPI],
'email' => [Flapjack::Gateways::Email],
'notifier' => [Flapjack::Notifier],
'processor' => [Flapjack::Processor],
'jabber' => [Flapjack::Gateways::Jabber::Bot,
Flapjack::Gateways::Jabber::Notifier,
Flapjack::Gateways::Jabber::Interpreter],
'oobetet' => [Flapjack::Gateways::Oobetet::Bot,
Flapjack::Gateways::Oobetet::Notifier],
'pagerduty' => [Flapjack::Gateways::Pagerduty::Notifier,
Flapjack::Gateways::Pagerduty::AckFinder],
'sms' => [Flapjack::Gateways::SmsMessagenet],
'sms_twilio' => [Flapjack::Gateways::SmsTwilio],
'aws_sns' => [Flapjack::Gateways::AwsSns],
'web' => [Flapjack::Gateways::Web],
}
def self.is_pikelet?(type)
TYPES.has_key?(type)
end
def self.create(type, shutdown, opts = {})
config = opts[:config] || {}
logger = Flapjack::Logger.new("flapjack-#{type}", config['logger'])
types = TYPES[type]
return [] if types.nil?
created = types.collect {|pikelet_class|
wrapper = WRAPPERS.detect {|wrap| wrap::TYPES.include?(type) }
wrapper.new(pikelet_class, shutdown, :config => config,
:logger => logger)
}
created.each {|c| c.siblings = created - [c] }
created
end
end
end
| 30.829268 | 91 | 0.569752 |
87a7913ebbafe0a470aec747a37b0565a5ea16f6 | 11,635 | # This file is auto-generated from the current state of the database. Instead
# of editing this file, please use the migrations feature of Active Record to
# incrementally modify your database, and then regenerate this schema definition.
#
# Note that this schema.rb definition is the authoritative source for your
# database schema. If you need to create the application database on another
# system, you should be using db:schema:load, not running all the migrations
# from scratch. The latter is a flawed and unsustainable approach (the more migrations
# you'll amass, the slower it'll run and the greater likelihood for issues).
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 20190805192704) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "assignment_invitations", id: :serial, force: :cascade do |t|
t.string "key", null: false
t.integer "assignment_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "deleted_at"
t.string "short_key"
t.index ["assignment_id"], name: "index_assignment_invitations_on_assignment_id"
t.index ["deleted_at"], name: "index_assignment_invitations_on_deleted_at"
t.index ["key"], name: "index_assignment_invitations_on_key", unique: true
t.index ["short_key"], name: "index_assignment_invitations_on_short_key"
end
create_table "assignment_repos", id: :serial, force: :cascade do |t|
t.integer "github_repo_id", null: false
t.integer "repo_access_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "assignment_id"
t.integer "user_id"
t.string "submission_sha"
t.string "github_global_relay_id"
t.integer "configuration_state", default: 0
t.index ["assignment_id"], name: "index_assignment_repos_on_assignment_id"
t.index ["github_repo_id"], name: "index_assignment_repos_on_github_repo_id", unique: true
t.index ["repo_access_id"], name: "index_assignment_repos_on_repo_access_id"
t.index ["user_id"], name: "index_assignment_repos_on_user_id"
end
create_table "assignments", id: :serial, force: :cascade do |t|
t.boolean "public_repo", default: true
t.string "title", null: false
t.integer "organization_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "starter_code_repo_id"
t.integer "creator_id"
t.datetime "deleted_at"
t.string "slug", null: false
t.boolean "students_are_repo_admins", default: false, null: false
t.boolean "invitations_enabled", default: true
t.boolean "template_repos_enabled"
t.index ["deleted_at"], name: "index_assignments_on_deleted_at"
t.index ["organization_id"], name: "index_assignments_on_organization_id"
t.index ["slug"], name: "index_assignments_on_slug"
end
create_table "deadlines", id: :serial, force: :cascade do |t|
t.string "assignment_type"
t.integer "assignment_id"
t.datetime "deadline_at", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["assignment_type", "assignment_id"], name: "index_deadlines_on_assignment_type_and_assignment_id"
end
create_table "group_assignment_invitations", id: :serial, force: :cascade do |t|
t.string "key", null: false
t.integer "group_assignment_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "deleted_at"
t.string "short_key"
t.index ["deleted_at"], name: "index_group_assignment_invitations_on_deleted_at"
t.index ["group_assignment_id"], name: "index_group_assignment_invitations_on_group_assignment_id"
t.index ["key"], name: "index_group_assignment_invitations_on_key", unique: true
t.index ["short_key"], name: "index_group_assignment_invitations_on_short_key"
end
create_table "group_assignment_repos", id: :serial, force: :cascade do |t|
t.integer "github_repo_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "group_assignment_id"
t.integer "group_id", null: false
t.string "submission_sha"
t.integer "configuration_state", default: 0
t.string "github_global_relay_id"
t.index ["github_repo_id"], name: "index_group_assignment_repos_on_github_repo_id", unique: true
t.index ["group_assignment_id"], name: "index_group_assignment_repos_on_group_assignment_id"
end
create_table "group_assignments", id: :serial, force: :cascade do |t|
t.boolean "public_repo", default: true
t.string "title", null: false
t.integer "grouping_id"
t.integer "organization_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "starter_code_repo_id"
t.integer "creator_id"
t.datetime "deleted_at"
t.string "slug", null: false
t.integer "max_members"
t.boolean "students_are_repo_admins", default: false, null: false
t.boolean "invitations_enabled", default: true
t.integer "max_teams"
t.boolean "template_repos_enabled"
t.index ["deleted_at"], name: "index_group_assignments_on_deleted_at"
t.index ["organization_id"], name: "index_group_assignments_on_organization_id"
t.index ["slug"], name: "index_group_assignments_on_slug"
end
create_table "group_invite_statuses", force: :cascade do |t|
t.integer "status", default: 0
t.bigint "group_id"
t.bigint "group_assignment_invitation_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["group_assignment_invitation_id"], name: "index_group_invite_statuses_on_group_assignment_invitation_id"
t.index ["group_id"], name: "index_group_invite_statuses_on_group_id"
end
create_table "groupings", id: :serial, force: :cascade do |t|
t.string "title", null: false
t.integer "organization_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "slug", null: false
t.index ["organization_id"], name: "index_groupings_on_organization_id"
end
create_table "groups", id: :serial, force: :cascade do |t|
t.integer "github_team_id", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "grouping_id"
t.string "title", null: false
t.string "slug", null: false
t.index ["github_team_id"], name: "index_groups_on_github_team_id", unique: true
t.index ["grouping_id"], name: "index_groups_on_grouping_id"
end
create_table "groups_repo_accesses", id: false, force: :cascade do |t|
t.integer "group_id"
t.integer "repo_access_id"
t.index ["group_id"], name: "index_groups_repo_accesses_on_group_id"
t.index ["repo_access_id"], name: "index_groups_repo_accesses_on_repo_access_id"
end
create_table "invite_statuses", force: :cascade do |t|
t.integer "status", default: 0
t.bigint "assignment_invitation_id"
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["assignment_invitation_id"], name: "index_invite_statuses_on_assignment_invitation_id"
t.index ["user_id"], name: "index_invite_statuses_on_user_id"
end
create_table "lti_configurations", force: :cascade do |t|
t.text "consumer_key", null: false
t.text "shared_secret", null: false
t.text "lms_link"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.bigint "organization_id"
t.string "context_membership_url"
t.text "lms_type", default: "other", null: false
t.string "cached_launch_message_nonce"
t.index ["consumer_key"], name: "index_lti_configurations_on_consumer_key", unique: true
t.index ["organization_id"], name: "index_lti_configurations_on_organization_id"
end
create_table "organization_webhooks", force: :cascade do |t|
t.integer "github_id"
t.integer "github_organization_id", null: false
t.datetime "last_webhook_recieved"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["github_id"], name: "index_organization_webhooks_on_github_id", unique: true
end
create_table "organizations", id: :serial, force: :cascade do |t|
t.integer "github_id", null: false
t.string "title", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.datetime "deleted_at"
t.string "slug", null: false
t.integer "roster_id"
t.string "github_global_relay_id"
t.bigint "organization_webhook_id"
t.string "google_course_id"
t.datetime "archived_at"
t.index ["deleted_at"], name: "index_organizations_on_deleted_at"
t.index ["github_id"], name: "index_organizations_on_github_id"
t.index ["google_course_id"], name: "index_organizations_on_google_course_id"
t.index ["organization_webhook_id"], name: "index_organizations_on_organization_webhook_id"
t.index ["roster_id"], name: "index_organizations_on_roster_id"
t.index ["slug"], name: "index_organizations_on_slug"
end
create_table "organizations_users", id: false, force: :cascade do |t|
t.integer "user_id"
t.integer "organization_id"
t.index ["organization_id"], name: "index_organizations_users_on_organization_id"
t.index ["user_id"], name: "index_organizations_users_on_user_id"
end
create_table "repo_accesses", id: :serial, force: :cascade do |t|
t.integer "github_team_id"
t.integer "organization_id"
t.integer "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["github_team_id"], name: "index_repo_accesses_on_github_team_id", unique: true
t.index ["organization_id"], name: "index_repo_accesses_on_organization_id"
t.index ["user_id"], name: "index_repo_accesses_on_user_id"
end
create_table "roster_entries", force: :cascade do |t|
t.string "identifier", null: false
t.bigint "roster_id", null: false
t.bigint "user_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "google_user_id"
t.string "lms_user_id"
t.index ["google_user_id"], name: "index_roster_entries_on_google_user_id"
t.index ["lms_user_id"], name: "index_roster_entries_on_lms_user_id"
t.index ["roster_id"], name: "index_roster_entries_on_roster_id"
t.index ["user_id"], name: "index_roster_entries_on_user_id"
end
create_table "rosters", force: :cascade do |t|
t.string "identifier_name", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "users", id: :serial, force: :cascade do |t|
t.integer "uid", null: false
t.string "token", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "site_admin", default: false
t.datetime "last_active_at", null: false
t.string "github_global_relay_id"
t.string "github_login"
t.string "github_name"
t.string "github_avatar_url"
t.string "github_html_url"
t.index ["token"], name: "index_users_on_token", unique: true
t.index ["uid"], name: "index_users_on_uid", unique: true
end
add_foreign_key "group_invite_statuses", "group_assignment_invitations"
add_foreign_key "group_invite_statuses", "groups"
add_foreign_key "invite_statuses", "assignment_invitations"
add_foreign_key "invite_statuses", "users"
add_foreign_key "organizations", "organization_webhooks"
end
| 42.933579 | 117 | 0.7315 |
1a8ee5fcc624e27cbe88c3b648f094b4b35b41b4 | 22,842 | # frozen_string_literal: true
require "cases/helper"
require "models/author"
require "models/company"
require "models/membership"
require "models/person"
require "models/post"
require "models/project"
require "models/subscriber"
require "models/vegetables"
require "models/shop"
require "models/sponsor"
module InheritanceTestHelper
def with_store_full_sti_class(&block)
assign_store_full_sti_class true, &block
end
def without_store_full_sti_class(&block)
assign_store_full_sti_class false, &block
end
def assign_store_full_sti_class(flag)
old_store_full_sti_class = ActiveRecord::Base.store_full_sti_class
ActiveRecord::Base.store_full_sti_class = flag
yield
ensure
ActiveRecord::Base.store_full_sti_class = old_store_full_sti_class
end
end
class InheritanceTest < ActiveRecord::TestCase
include InheritanceTestHelper
fixtures :companies, :projects, :subscribers, :accounts, :vegetables, :memberships
def test_class_with_store_full_sti_class_returns_full_name
with_store_full_sti_class do
assert_equal "Namespaced::Company", Namespaced::Company.sti_name
end
end
def test_class_with_blank_sti_name
company = Company.first
company = company.dup
company.extend(Module.new {
def _read_attribute(name)
return " " if name == "type"
super
end
})
company.save!
company = Company.all.to_a.find { |x| x.id == company.id }
assert_equal " ", company.type
end
def test_class_without_store_full_sti_class_returns_demodulized_name
without_store_full_sti_class do
assert_equal "Company", Namespaced::Company.sti_name
end
end
def test_compute_type_success
assert_equal Author, Company.send(:compute_type, "Author")
end
def test_compute_type_nonexistent_constant
e = assert_raises NameError do
Company.send :compute_type, "NonexistentModel"
end
assert_equal "uninitialized constant Company::NonexistentModel", e.message
assert_equal "Company::NonexistentModel", e.name
end
def test_compute_type_no_method_error
ActiveSupport::Dependencies.stub(:safe_constantize, proc { raise NoMethodError }) do
assert_raises NoMethodError do
Company.send :compute_type, "InvalidModel"
end
end
end
def test_compute_type_on_undefined_method
error = nil
begin
Class.new(Author) do
alias_method :foo, :bar
end
rescue => e
error = e
end
ActiveSupport::Dependencies.stub(:safe_constantize, proc { raise e }) do
exception = assert_raises NameError do
Company.send :compute_type, "InvalidModel"
end
assert_equal error.message, exception.message
end
end
def test_compute_type_argument_error
ActiveSupport::Dependencies.stub(:safe_constantize, proc { raise ArgumentError }) do
assert_raises ArgumentError do
Company.send :compute_type, "InvalidModel"
end
end
end
def test_should_store_demodulized_class_name_with_store_full_sti_class_option_disabled
without_store_full_sti_class do
item = Namespaced::Company.new
assert_equal "Company", item[:type]
end
end
def test_should_store_full_class_name_with_store_full_sti_class_option_enabled
with_store_full_sti_class do
item = Namespaced::Company.new
assert_equal "Namespaced::Company", item[:type]
end
end
def test_different_namespace_subclass_should_load_correctly_with_store_full_sti_class_option
with_store_full_sti_class do
item = Namespaced::Company.create name: "Wolverine 2"
assert_not_nil Company.find(item.id)
assert_not_nil Namespaced::Company.find(item.id)
end
end
def test_descends_from_active_record
assert_not_predicate ActiveRecord::Base, :descends_from_active_record?
# Abstract subclass of AR::Base.
assert_predicate LoosePerson, :descends_from_active_record?
# Concrete subclass of an abstract class.
assert_predicate LooseDescendant, :descends_from_active_record?
# Concrete subclass of AR::Base.
assert_predicate TightPerson, :descends_from_active_record?
# Concrete subclass of a concrete class but has no type column.
assert_predicate TightDescendant, :descends_from_active_record?
# Concrete subclass of AR::Base.
assert_predicate Post, :descends_from_active_record?
# Concrete subclasses of a concrete class which has a type column.
assert_not_predicate StiPost, :descends_from_active_record?
assert_not_predicate SubStiPost, :descends_from_active_record?
# Abstract subclass of a concrete class which has a type column.
# This is pathological, as you'll never have Sub < Abstract < Concrete.
assert_not_predicate AbstractStiPost, :descends_from_active_record?
# Concrete subclass of an abstract class which has a type column.
assert_not_predicate SubAbstractStiPost, :descends_from_active_record?
end
def test_company_descends_from_active_record
assert_not_predicate ActiveRecord::Base, :descends_from_active_record?
assert AbstractCompany.descends_from_active_record?, "AbstractCompany should descend from ActiveRecord::Base"
assert Company.descends_from_active_record?, "Company should descend from ActiveRecord::Base"
assert_not Class.new(Company).descends_from_active_record?, "Company subclass should not descend from ActiveRecord::Base"
end
def test_abstract_class
assert_not_predicate ActiveRecord::Base, :abstract_class?
assert_predicate LoosePerson, :abstract_class?
assert_not_predicate LooseDescendant, :abstract_class?
end
def test_inheritance_base_class
assert_equal Post, Post.base_class
assert_predicate Post, :base_class?
assert_equal Post, SpecialPost.base_class
assert_not_predicate SpecialPost, :base_class?
assert_equal Post, StiPost.base_class
assert_not_predicate StiPost, :base_class?
assert_equal Post, SubStiPost.base_class
assert_not_predicate SubStiPost, :base_class?
assert_equal SubAbstractStiPost, SubAbstractStiPost.base_class
assert_predicate SubAbstractStiPost, :base_class?
end
def test_abstract_inheritance_base_class
assert_equal LoosePerson, LoosePerson.base_class
assert_predicate LoosePerson, :base_class?
assert_equal LooseDescendant, LooseDescendant.base_class
assert_predicate LooseDescendant, :base_class?
assert_equal TightPerson, TightPerson.base_class
assert_predicate TightPerson, :base_class?
assert_equal TightPerson, TightDescendant.base_class
assert_not_predicate TightDescendant, :base_class?
end
def test_base_class_activerecord_error
klass = Class.new { include ActiveRecord::Inheritance }
assert_raise(ActiveRecord::ActiveRecordError) { klass.base_class }
end
def test_a_bad_type_column
Company.connection.insert "INSERT INTO companies (id, #{QUOTED_TYPE}, name) VALUES(100, 'bad_class!', 'Not happening')"
assert_raise(ActiveRecord::SubclassNotFound) { Company.find(100) }
end
def test_inheritance_find
assert_kind_of Firm, Company.find(1), "37signals should be a firm"
assert_kind_of Firm, Firm.find(1), "37signals should be a firm"
assert_kind_of Client, Company.find(2), "Summit should be a client"
assert_kind_of Client, Client.find(2), "Summit should be a client"
end
def test_alt_inheritance_find
assert_kind_of Cucumber, Vegetable.find(1)
assert_kind_of Cucumber, Cucumber.find(1)
assert_kind_of Cabbage, Vegetable.find(2)
assert_kind_of Cabbage, Cabbage.find(2)
end
def test_alt_becomes_works_with_sti
vegetable = Vegetable.find(1)
assert_kind_of Vegetable, vegetable
cabbage = vegetable.becomes(Cabbage)
assert_kind_of Cabbage, cabbage
end
def test_becomes_sets_variables_before_initialization_callbacks
vegetable = Vegetable.create!(name: "yelling carrot")
assert_kind_of Vegetable, vegetable
assert_equal "yelling carrot", vegetable.name
yelling_veggie = vegetable.becomes(YellingVegetable)
assert_equal "YELLING CARROT", yelling_veggie.name, "YellingVegetable name should be YELLING CARROT"
assert_equal "YELLING CARROT", vegetable.name, "Vegetable name should be YELLING CARROT after becoming a YellingVegetable"
end
def test_becomes_and_change_tracking_for_inheritance_columns
cucumber = Vegetable.find(1)
cabbage = cucumber.becomes!(Cabbage)
assert_equal ["Cucumber", "Cabbage"], cabbage.custom_type_change
end
def test_alt_becomes_bang_resets_inheritance_type_column
vegetable = Vegetable.create!(name: "Red Pepper")
assert_nil vegetable.custom_type
cabbage = vegetable.becomes!(Cabbage)
assert_equal "Cabbage", cabbage.custom_type
cabbage.becomes!(Vegetable)
assert_nil cabbage.custom_type
end
def test_inheritance_find_all
companies = Company.all.merge!(order: "id").to_a
assert_kind_of Firm, companies[0], "37signals should be a firm"
assert_kind_of Client, companies[1], "Summit should be a client"
end
def test_alt_inheritance_find_all
companies = Vegetable.all.merge!(order: "id").to_a
assert_kind_of Cucumber, companies[0]
assert_kind_of Cabbage, companies[1]
end
def test_inheritance_save
firm = Firm.new
firm.name = "Next Angle"
firm.save
next_angle = Company.find(firm.id)
assert_kind_of Firm, next_angle, "Next Angle should be a firm"
end
def test_alt_inheritance_save
cabbage = Cabbage.new(name: "Savoy")
cabbage.save!
savoy = Vegetable.find(cabbage.id)
assert_kind_of Cabbage, savoy
end
def test_inheritance_new_with_default_class
company = Company.new
assert_equal Company, company.class
end
def test_inheritance_new_with_base_class
company = Company.new(type: "Company")
assert_equal Company, company.class
end
def test_inheritance_new_with_subclass
firm = Company.new(type: "Firm")
assert_equal Firm, firm.class
end
def test_where_new_with_subclass
firm = Company.where(type: "Firm").new
assert_equal Firm, firm.class
end
def test_where_create_with_subclass
firm = Company.where(type: "Firm").create(name: "Basecamp")
assert_equal Firm, firm.class
end
def test_where_create_bang_with_subclass
firm = Company.where(type: "Firm").create!(name: "Basecamp")
assert_equal Firm, firm.class
end
def test_new_with_abstract_class
e = assert_raises(NotImplementedError) do
AbstractCompany.new
end
assert_equal("AbstractCompany is an abstract class and cannot be instantiated.", e.message)
end
def test_new_with_ar_base
e = assert_raises(NotImplementedError) do
ActiveRecord::Base.new
end
assert_equal("ActiveRecord::Base is an abstract class and cannot be instantiated.", e.message)
end
def test_new_with_invalid_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.new(type: "InvalidType") }
end
def test_new_with_unrelated_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.new(type: "Account") }
end
def test_where_new_with_invalid_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.where(type: "InvalidType").new }
end
def test_where_new_with_unrelated_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.where(type: "Account").new }
end
def test_where_create_with_invalid_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.where(type: "InvalidType").create }
end
def test_where_create_with_unrelated_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.where(type: "Account").create }
end
def test_where_create_bang_with_invalid_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.where(type: "InvalidType").create! }
end
def test_where_create_bang_with_unrelated_type
assert_raise(ActiveRecord::SubclassNotFound) { Company.where(type: "Account").create! }
end
def test_new_with_unrelated_namespaced_type
without_store_full_sti_class do
e = assert_raises ActiveRecord::SubclassNotFound do
Namespaced::Company.new(type: "Firm")
end
assert_equal "Invalid single-table inheritance type: Namespaced::Firm is not a subclass of Namespaced::Company", e.message
end
end
def test_new_with_complex_inheritance
assert_nothing_raised { Client.new(type: "VerySpecialClient") }
end
def test_new_without_storing_full_sti_class
without_store_full_sti_class do
item = Company.new(type: "SpecialCo")
assert_instance_of Company::SpecialCo, item
end
end
def test_new_with_autoload_paths
path = File.expand_path("../models/autoloadable", __dir__)
ActiveSupport::Dependencies.autoload_paths << path
firm = Company.new(type: "ExtraFirm")
assert_equal ExtraFirm, firm.class
ensure
ActiveSupport::Dependencies.autoload_paths.reject! { |p| p == path }
ActiveSupport::Dependencies.clear
end
def test_inheritance_condition
assert_equal 11, Company.count
assert_equal 2, Firm.count
assert_equal 5, Client.count
end
def test_alt_inheritance_condition
assert_equal 4, Vegetable.count
assert_equal 1, Cucumber.count
assert_equal 3, Cabbage.count
end
def test_finding_incorrect_type_data
assert_raise(ActiveRecord::RecordNotFound) { Firm.find(2) }
assert_nothing_raised { Firm.find(1) }
end
def test_alt_finding_incorrect_type_data
assert_raise(ActiveRecord::RecordNotFound) { Cucumber.find(2) }
assert_nothing_raised { Cucumber.find(1) }
end
def test_update_all_within_inheritance
Client.update_all "name = 'I am a client'"
assert_equal "I am a client", Client.first.name
# Order by added as otherwise Oracle tests were failing because of different order of results
assert_equal "37signals", Firm.all.merge!(order: "id").to_a.first.name
end
def test_alt_update_all_within_inheritance
Cabbage.update_all "name = 'the cabbage'"
assert_equal "the cabbage", Cabbage.first.name
assert_equal ["my cucumber"], Cucumber.all.map(&:name).uniq
end
def test_destroy_all_within_inheritance
Client.destroy_all
assert_equal 0, Client.count
assert_equal 2, Firm.count
end
def test_alt_destroy_all_within_inheritance
Cabbage.destroy_all
assert_equal 0, Cabbage.count
assert_equal 1, Cucumber.count
end
def test_find_first_within_inheritance
assert_kind_of Firm, Company.all.merge!(where: "name = '37signals'").first
assert_kind_of Firm, Firm.all.merge!(where: "name = '37signals'").first
assert_nil Client.all.merge!(where: "name = '37signals'").first
end
def test_alt_find_first_within_inheritance
assert_kind_of Cabbage, Vegetable.all.merge!(where: "name = 'his cabbage'").first
assert_kind_of Cabbage, Cabbage.all.merge!(where: "name = 'his cabbage'").first
assert_nil Cucumber.all.merge!(where: "name = 'his cabbage'").first
end
def test_complex_inheritance
very_special_client = VerySpecialClient.create("name" => "veryspecial")
assert_equal very_special_client, VerySpecialClient.where("name = 'veryspecial'").first
assert_equal very_special_client, SpecialClient.all.merge!(where: "name = 'veryspecial'").first
assert_equal very_special_client, Company.all.merge!(where: "name = 'veryspecial'").first
assert_equal very_special_client, Client.all.merge!(where: "name = 'veryspecial'").first
assert_equal 1, Client.all.merge!(where: "name = 'Summit'").to_a.size
assert_equal very_special_client, Client.find(very_special_client.id)
end
def test_alt_complex_inheritance
king_cole = KingCole.create("name" => "uniform heads")
assert_equal king_cole, KingCole.where("name = 'uniform heads'").first
assert_equal king_cole, GreenCabbage.all.merge!(where: "name = 'uniform heads'").first
assert_equal king_cole, Cabbage.all.merge!(where: "name = 'uniform heads'").first
assert_equal king_cole, Vegetable.all.merge!(where: "name = 'uniform heads'").first
assert_equal 1, Cabbage.all.merge!(where: "name = 'his cabbage'").to_a.size
assert_equal king_cole, Cabbage.find(king_cole.id)
end
def test_eager_load_belongs_to_something_inherited
account = Account.all.merge!(includes: :firm).find(1)
assert account.association(:firm).loaded?, "association was not eager loaded"
end
def test_alt_eager_loading
cabbage = RedCabbage.all.merge!(includes: :seller).find(4)
assert cabbage.association(:seller).loaded?, "association was not eager loaded"
end
def test_eager_load_belongs_to_primary_key_quoting
c = Account.connection
bind_param = Arel::Nodes::BindParam.new(nil)
assert_sql(/#{Regexp.escape(c.quote_table_name("companies.id"))} = (?:#{Regexp.escape(bind_param.to_sql)}|1)/i) do
Account.all.merge!(includes: :firm).find(1)
end
end
def test_inherits_custom_primary_key
assert_equal Subscriber.primary_key, SpecialSubscriber.primary_key
end
def test_inheritance_without_mapping
assert_kind_of SpecialSubscriber, SpecialSubscriber.find("webster132")
assert_nothing_raised { s = SpecialSubscriber.new("name" => "And breaaaaathe!"); s.id = "roger"; s.save }
end
def test_scope_inherited_properly
assert_nothing_raised { Company.of_first_firm.to_a }
assert_nothing_raised { Client.of_first_firm.to_a }
end
def test_inheritance_with_default_scope
assert_equal 1, SelectedMembership.count(:all)
end
end
class InheritanceComputeTypeTest < ActiveRecord::TestCase
include InheritanceTestHelper
fixtures :companies
def test_instantiation_doesnt_try_to_require_corresponding_file
without_store_full_sti_class do
foo = Firm.first.clone
foo.type = "FirmOnTheFly"
foo.save!
# Should fail without FirmOnTheFly in the type condition.
assert_raise(ActiveRecord::RecordNotFound) { Firm.find(foo.id) }
assert_raise(ActiveRecord::RecordNotFound) { Firm.find_by!(id: foo.id) }
# Nest FirmOnTheFly in the test case where Dependencies won't see it.
self.class.const_set :FirmOnTheFly, Class.new(Firm)
assert_raise(ActiveRecord::SubclassNotFound) { Firm.find(foo.id) }
assert_raise(ActiveRecord::SubclassNotFound) { Firm.find_by!(id: foo.id) }
# Nest FirmOnTheFly in Firm where Dependencies will see it.
# This is analogous to nesting models in a migration.
Firm.const_set :FirmOnTheFly, Class.new(Firm)
# And instantiate will find the existing constant rather than trying
# to require firm_on_the_fly.
assert_nothing_raised { assert_kind_of Firm::FirmOnTheFly, Firm.find(foo.id) }
assert_nothing_raised { assert_kind_of Firm::FirmOnTheFly, Firm.find_by!(id: foo.id) }
end
ensure
self.class.send(:remove_const, :FirmOnTheFly) rescue nil
Firm.send(:remove_const, :FirmOnTheFly) rescue nil
end
def test_sti_type_from_attributes_disabled_in_non_sti_class
phone = Shop::Product::Type.new(name: "Phone")
product = Shop::Product.new(type: phone)
assert product.save
end
def test_inheritance_new_with_subclass_as_default
original_type = Company.columns_hash["type"].default
ActiveRecord::Base.connection.change_column_default :companies, :type, "Firm"
Company.reset_column_information
firm = Company.new # without arguments
assert_equal "Firm", firm.type
assert_instance_of Firm, firm
firm = Company.new(firm_name: "Shri Hans Plastic") # with arguments
assert_equal "Firm", firm.type
assert_instance_of Firm, firm
client = Client.new
assert_equal "Client", client.type
assert_instance_of Client, client
firm = Company.new(type: "Client") # overwrite the default type
assert_equal "Client", firm.type
assert_instance_of Client, firm
ensure
ActiveRecord::Base.connection.change_column_default :companies, :type, original_type
Company.reset_column_information
end
end
class InheritanceAttributeTest < ActiveRecord::TestCase
class Company < ActiveRecord::Base
self.table_name = "companies"
attribute :type, :string, default: "InheritanceAttributeTest::Startup"
end
class Startup < Company
end
class Empire < Company
end
def test_inheritance_new_with_subclass_as_default
startup = Company.new # without arguments
assert_equal "InheritanceAttributeTest::Startup", startup.type
assert_instance_of Startup, startup
empire = Company.new(type: "InheritanceAttributeTest::Empire") # without arguments
assert_equal "InheritanceAttributeTest::Empire", empire.type
assert_instance_of Empire, empire
end
end
class InheritanceAttributeMappingTest < ActiveRecord::TestCase
setup do
Company.delete_all
Sponsor.delete_all
end
class OmgStiType < ActiveRecord::Type::String
def cast_value(value)
if value =~ /\Aomg_(.+)\z/
$1.classify
else
value
end
end
def serialize(value)
if value
"omg_%s" % value.underscore
end
end
end
ActiveRecord::Type.register :omg_sti, OmgStiType
class Company < ActiveRecord::Base
self.table_name = "companies"
attribute :type, :omg_sti
end
class Startup < Company; end
class Empire < Company; end
class Sponsor < ActiveRecord::Base
self.table_name = "sponsors"
attribute :sponsorable_type, :omg_sti
belongs_to :sponsorable, polymorphic: true
end
def test_sti_with_custom_type
Startup.create! name: "a Startup"
Empire.create! name: "an Empire"
assert_equal [["a Startup", "omg_inheritance_attribute_mapping_test/startup"],
["an Empire", "omg_inheritance_attribute_mapping_test/empire"]], ActiveRecord::Base.connection.select_rows("SELECT name, type FROM companies").sort
assert_equal [["a Startup", "InheritanceAttributeMappingTest::Startup"],
["an Empire", "InheritanceAttributeMappingTest::Empire"]], Company.all.map { |a| [a.name, a.type] }.sort
startup = Startup.first
startup.becomes! Empire
startup.save!
assert_equal [["a Startup", "omg_inheritance_attribute_mapping_test/empire"],
["an Empire", "omg_inheritance_attribute_mapping_test/empire"]], ActiveRecord::Base.connection.select_rows("SELECT name, type FROM companies").sort
assert_equal [["a Startup", "InheritanceAttributeMappingTest::Empire"],
["an Empire", "InheritanceAttributeMappingTest::Empire"]], Company.all.map { |a| [a.name, a.type] }.sort
end
def test_polymorphic_associations_custom_type
startup = Startup.create! name: "a Startup"
sponsor = Sponsor.create! sponsorable: startup
assert_equal ["omg_inheritance_attribute_mapping_test/company"], ActiveRecord::Base.connection.select_values("SELECT sponsorable_type FROM sponsors")
sponsor = Sponsor.find(sponsor.id)
assert_equal startup, sponsor.sponsorable
end
end
| 34.245877 | 165 | 0.753349 |
e9162f920a547dc5914d9fd66f8e32d5530183ff | 713 | #! /usr/bin/ruby
# -*- coding: utf-8 -*-
#
# postgre_read.rb
#
# May/14/2019
#
require 'pg'
require 'dotenv'
#
# --------------------------------------------------------------------
puts "*** 開始 ***"
#
Dotenv.load
user = ENV['user']
password = ENV['password']
data_base = ENV['data_base']
#
connection = PG::connect(:host => "localhost",
:user =>user, :password =>password, :dbname =>data_base)
#
table = connection.exec('select * from cities order by ID')
#
table.each {|row|
print(row["id"] + "\t")
print(row["name"] + "\t")
print(row["population"] + "\t")
print(row["date_mod"] + "\n")
}
#
connection.finish
#
puts "*** 終了 ***"
# --------------------------------------------------------------------
| 20.371429 | 70 | 0.478261 |
bb8e8ccfd6ba3c2933e10553ef379abd3afcb162 | 214 | class Buttercms::BaseController < ActionController::Base
# You can of course change this layout to your main application layout
# to have your blog match the rest of your site.
layout 'buttercms/default'
end
| 35.666667 | 72 | 0.775701 |
abd26dd9afaa957840d184fe44d11af975fa8751 | 243 | module VirtualBox
module COM
module Interface
module Version_4_0_X
class PointingHidType < AbstractEnum
map [:null, :none, :ps2_mouse, :usb_mouse, :usb_tablet, :combo_mouse]
end
end
end
end
end | 22.090909 | 79 | 0.641975 |
6aa3eb06ea8fcc77e5f72aeaad30506d2f279a1a | 463 | module ActionDispatch::Routing
class Mapper
def with_jindouyun options
init_dingding_routes options
end
private
def init_dingding_routes options
notifications_controller = options[:system_notifications] ? options[:system_notifications] : 'jindouyun/dingding/system_notifications'
scope :dingding do
resources :system_notifications, controller: notifications_controller, only: [:create]
end
end
end
end
| 23.15 | 140 | 0.742981 |
f7eb794099f82a64195597a69d75fbe340ad9a38 | 888 | # frozen_string_literal: true
require "delegate"
require "forwardable"
require "redis"
require "active_support/lazy_load_hooks"
require "redi_search/configuration"
require "redi_search/client"
require "redi_search/model"
require "redi_search/index"
require "redi_search/log_subscriber"
require "redi_search/document"
module RediSearch
class << self
attr_writer :configuration
def configuration
@configuration ||= Configuration.new
end
def reset
@configuration = Configuration.new
end
def configure
yield(configuration)
end
def client
@client ||= Client.new(Redis.new(configuration.redis_config.to_h))
end
def env
ENV["RAILS_ENV"] || ENV["RACK_ENV"] || "development"
end
end
end
ActiveSupport.on_load(:active_record) do
include RediSearch::Model
end
RediSearch::LogSubscriber.attach_to :redi_search
| 19.304348 | 72 | 0.733108 |
1a016aacd760f34ad098733c4ead53a5ed16e05c | 5,202 | # encoding: utf-8
# This is a Data Twist file
# Experimental script to twist Open Data into new shapes
# Copyright (c) 2013 Kana Fukuma and Shane Coughlan
# Version 0.5
#
# Data Twist is Free Software. You might also call it Open Source.
# You can redistribute it and/or modify it under either the terms of the
# 2-clause BSDL (see the file BSDL), or the terms listed in README.md
require 'uri'
require 'kconv'
require 'Date'
# input
def input(inputfile)
# initialize
count = 0
array = []
id = 0
name = ""
desc = ""
lat = 0.0
lon = 0.0
type = ""
timestamp = ""
flag = false
# filename input
begin
#print "Please input filename: "
#filename = gets.chop
filename = inputfile
#puts "filename:#{filename}\n"
file = File.read(filename)
rescue
print "\n*** Error : Please one more again! ***\n"
retry
end
print "\n------------\n\n"
begin
# read a line of the file
file.each_line { |line|
# id, lat and lon
if line.match("<node id=")
unless line.match("/>")
if /id="(.*)" v(.*) timestamp="(.*)" uid(.*) lat="(.*)" lon="(.*)"/ =~ line
id = $1
timestamp = $3
lat = $5
lon = $6
flag = true
elsif /id="(.*)" lat="(.*)" lon="(.*)" user(.*) timestamp="(.*)"/ =~ line
id = $1
lat = $2
lon = $3
timestamp = $5
flag = true
end
end
end
if flag
# name
if line.match("k=\"name\"")
if /v="(.*)"/ =~ line
name = $1
end
end
# desc
if line.match("k=\"amenity\"")
if /v="(.*)"/ =~ line
desc = $1
end
end
end
# array
if line.match("</node>")
if name != ""
e_name = name.downcase
e_name.gsub!(" ","-")
e_name = URI.escape(e_name)
timestamp.gsub!("T", " ")
timestamp.gsub!("Z", " ")
array << [type,name,desc,id,lat,lon,e_name,timestamp]
print "."
end
# initialize
id = 0
name = ""
desc = ""
lat = 0.0
lon = 0.0
type = ""
timestamp = ""
flag = false
end
}
rescue
print "error"
end
print "\n------------\n\n"
return array
end
# copy sql_format
def copy_format(new_file)
filename = "sql_format.sql" # format_file
last_str = []
num = 0
# file copy
file = File.read(filename)
File.open(new_file,"w"){ |output|
file.each_line { |input|
if input.include?("=@OLD") # catch the last string
last_str << input
else
output.write input # write the output file
end
}
}
return last_str
end
# output
def output(last_str,outputfile,array)
post_author = 1
count = 0
content = "<br/><br/>[geo_mashup_map zoom=16]<br/><br/>Data from OpenStreetMap. Data from OpenStreetMap. © OpenStreetMap contributors. OpenStreetMap is <i>open data</i>, licensed under the <a href=\"http://opendatacommons.org/licenses/odbl/\">Open Data Commons Open Database License</a> (ODbL)<br/><br/>Last updated:"
File.open(outputfile,"a") { |f|
# write about the "wp_posts" file
f.write "--\n-- Dumping data for table `wp_posts`\n--\n\n"
f.write "INSERT INTO `wp_posts` (`ID`, `post_author`, `post_date`, `post_date_gmt`, `post_content`, `post_title`, `post_excerpt`, `post_status`, `comment_status`, `ping_status`, `post_password`, `post_name`, `to_ping`, `pinged`, `post_modified`, `post_modified_gmt`, `post_content_filtered`, `post_parent`, `guid`, `menu_order`, `post_type`, `post_mime_type`, `comment_count`) VALUES\n"
array.each { |a|
count = count + 1
f.write "(#{a[3]}, #{post_author}, '#{a[7]}', '#{a[7]}', '#{a[2]}#{content}#{a[7]}', '#{a[1]}', '', 'publish', 'open', 'open', '', '#{a[6]}-#{a[3]}', '', '', '#{a[7]}', '#{a[7]}', '', 0, 'http://www.opendawn.com/test/geo1/#{a[7][0..9].gsub!("-","/")}/#{a[6]}-#{a[3]}/', 0, 'post', '', 0)"
f.write ",\n" if array.length != count
}
f.write ";\n\n"
count = 0
# write about the "wp_geo_mashup_locations" file
f.write "--\n-- Dumping data for table `wp_geo_mashup_locations`\n--\n\n"
f.write "INSERT INTO `wp_geo_mashup_locations` (`id`, `lat`, `lng`, `address`, `saved_name`, `geoname`, `postal_code`, `country_code`, `admin_code`, `sub_admin_code`, `locality_name`) VALUES\n"
array.each { |a|
count = count + 1
f.write "(#{a[3]}, #{a[4]}, #{a[5]}, '', '#{a[6]}-#{a[3]}', NULL, '', '', '', NULL, '')"
f.write ",\n" if array.length != count
}
f.write ";\n\n"
count = 0
# write about the "wp_geo_mashup_location_relationships" file
f.write "--\n-- Dumping data for table `wp_geo_mashup_location_relationships`\n--\n\n"
f.write "INSERT INTO `wp_geo_mashup_location_relationships` (`object_name`, `object_id`, `location_id`, `geo_date`) VALUES\n"
array.each { |a|
count = count + 1
f.write "('post', #{a[3]}, #{a[3]}, '#{a[7]}')"
f.write ",\n" if array.length != count
}
f.write ";\n\n"
# write the last string
last_str.each { |str|
f.write str
}
}
end
#inputfile = "test-mapquest-xapi-london-amenity-wildcard-data-big.osm" # -> sql5
#inputfile = "osm-website-central-matsue.osm.xml" # -> sql6
inputfile = "osm-website-central-matsue-min.osm.xml"
outputfile = "o_sql07.sql"
array = input(inputfile)
last_str = copy_format(outputfile)
output(last_str,outputfile,array) | 26.814433 | 388 | 0.592272 |
918c032a556b71e864ac41876a7438eb9968ae6b | 3,224 | ##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##
class MetasploitModule < Msf::Auxiliary
include Msf::Exploit::Remote::Tcp
include Msf::Auxiliary::Report
def initialize(info = {})
super(update_info(info,
'Name' => 'CheckPoint Firewall-1 SecuRemote Topology Service Hostname Disclosure',
'Description' => %q{
This module sends a query to the port 264/TCP on CheckPoint Firewall-1
firewalls to obtain the firewall name and management station
(such as SmartCenter) name via a pre-authentication request. The string
returned is the CheckPoint Internal CA CN for SmartCenter and the firewall
host. Whilst considered "public" information, the majority of installations
use detailed hostnames which may aid an attacker in focusing on compromising
the SmartCenter host, or useful for government, intelligence and military
networks where the hostname reveals the physical location and rack number
of the device, which may be unintentionally published to the world.
},
'Author' => [ 'aushack' ],
'DisclosureDate' => '2011-12-14', # Looks like this module is first real reference
'References' =>
[
# aushack - None? Stumbled across, probably an old bug/feature but unsure.
[ 'URL', 'http://www.osisecurity.com.au/advisories/checkpoint-firewall-securemote-hostname-information-disclosure' ],
[ 'URL', 'https://supportcenter.checkpoint.com/supportcenter/portal?eventSubmit_doGoviewsolutiondetails=&solutionid=sk69360' ]
]
))
register_options(
[
Opt::RPORT(264),
])
end
def autofilter
false
end
def run
print_status("Attempting to contact Checkpoint FW1 SecuRemote Topology service...")
fw_hostname = nil
sc_hostname = nil
connect
sock.put("\x51\x00\x00\x00")
sock.put("\x00\x00\x00\x21")
res = sock.get_once(4)
if (res and res == "Y\x00\x00\x00")
print_good("Appears to be a CheckPoint Firewall...")
sock.put("\x00\x00\x00\x0bsecuremote\x00")
res = sock.get_once
if (res and res =~ /CN=(.+),O=(.+)\./i)
fw_hostname = $1
sc_hostname = $2
print_good("Firewall Host: #{fw_hostname}")
print_good("SmartCenter Host: #{sc_hostname}")
end
else
print_error("Unexpected response: '#{res.inspect}'")
end
report_info(fw_hostname,sc_hostname)
disconnect
end
# Only trust that it's real if we have a hostname. If you get a funny
# response, it might not be what we think it is.
def report_info(fw_hostname,sc_hostname)
return unless fw_hostname
host_info = {
:host => datastore['RHOST'],
:os_name => "Checkpoint Firewall-1",
:purpose => "firewall"
}
host_info[:name] = fw_hostname
host_info[:info] = "SmartCenter Host: #{sc_hostname}" if sc_hostname
report_host(host_info)
svc_info = {
:host => datastore['RHOST'],
:port => datastore['RPORT'],
:proto => "tcp",
:name => "securemote"
}
report_service(svc_info)
end
end
| 34.297872 | 136 | 0.654777 |
e981d50b0395a6fcd80dc4fc203369297f1fa870 | 1,546 | require 'test_helper'
class UserLoginTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
end
test "login with invalid information" do
get login_path
post login_path, params: { session: { email: @user.email, password: 'password' } }
assert_redirected_to @user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(@user)
end
test "login with valid information followed by logout" do
get login_path
post login_path, params: { session: { email: @user.email,
password: 'password' } }
assert is_logged_in?
assert_redirected_to @user
follow_redirect!
assert_template 'users/show'
assert_select "a[href=?]", login_path, count: 0
assert_select "a[href=?]", logout_path
assert_select "a[href=?]", user_path(@user)
delete logout_path
assert_not is_logged_in?
assert_redirected_to root_url
delete logout_path
follow_redirect!
assert_select "a[href=?]", login_path
assert_select "a[href=?]", logout_path, count: 0
assert_select "a[href=?]", user_path(@user), count: 0
end
test "login with remembering" do
log_in_as(@user, remember_me: '1')
assert_equal cookies['remember_token'], assigns(:user).remember_token
end
test "login without remembering" do
log_in_as(@user, remember_me: '1')
delete logout_path
log_in_as(@user, remember_me: '0')
assert_empty cookies['remember_token']
end
end
| 26.655172 | 84 | 0.708926 |
6a8f6ab24ad3b3a100b7346afd5f9e4f4738bb25 | 663 | describe package('vault') do
it { should be_installed }
end
describe group('vault') do
it { should exist }
end
describe user('vault') do
it { should exist }
end
describe file('/etc/vault.d/vault.hcl') do
it { should be_file }
its('owner') { should eq 'vault' }
its('group') { should eq 'vault' }
its('mode') { should cmp '0640' }
its('content') { should match %r{pid_file = \"\./pidfile\"} }
its('content') { should match /use_auto_auth_token = true/ }
end
describe file('/etc/systemd/system/vault-agent.service') do
it { should be_file }
end
describe service('vault-agent') do
it { should be_installed }
it { should be_enabled }
end
| 22.1 | 63 | 0.665158 |
797b8347cbfcc582fc24a1a24fd4c8a239efa414 | 16,821 | # frozen_string_literal: true
require "spec_helper"
require "dependabot/dependency_file"
require "dependabot/npm_and_yarn/file_updater/npmrc_builder"
RSpec.describe Dependabot::NpmAndYarn::FileUpdater::NpmrcBuilder do
let(:npmrc_builder) do
described_class.new(
dependency_files: dependency_files,
credentials: credentials
)
end
let(:dependency_files) { [package_json, yarn_lock] }
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}]
end
let(:package_json) do
Dependabot::DependencyFile.new(
content: fixture("package_files", manifest_fixture_name),
name: "package.json"
)
end
let(:package_lock) do
Dependabot::DependencyFile.new(
name: "package-lock.json",
content: fixture("npm_lockfiles", npm_lock_fixture_name)
)
end
let(:yarn_lock) do
Dependabot::DependencyFile.new(
name: "yarn.lock",
content: fixture("yarn_lockfiles", yarn_lock_fixture_name)
)
end
let(:npmrc) do
Dependabot::DependencyFile.new(
name: ".npmrc",
content: fixture("npmrc", npmrc_fixture_name)
)
end
let(:yarnrc) do
Dependabot::DependencyFile.new(
name: ".yarnrc",
content: fixture("yarnrc", yarnrc_fixture_name)
)
end
let(:manifest_fixture_name) { "package.json" }
let(:npm_lock_fixture_name) { "package-lock.json" }
let(:yarn_lock_fixture_name) { "yarn.lock" }
let(:npmrc_fixture_name) { "auth_token" }
let(:yarnrc_fixture_name) { "global_registry" }
describe "#npmrc_content" do
subject(:npmrc_content) { npmrc_builder.npmrc_content }
context "with a yarn.lock" do
let(:dependency_files) { [package_json, yarn_lock] }
context "with no private sources and no credentials" do
let(:manifest_fixture_name) { "package.json" }
let(:yarn_lock_fixture_name) { "yarn.lock" }
it { is_expected.to eq("") }
context "and an npmrc file" do
let(:dependency_files) { [package_json, yarn_lock, npmrc] }
it "returns the npmrc file unaltered" do
expect(npmrc_content).
to eq(fixture("npmrc", npmrc_fixture_name))
end
context "that needs an authToken sanitizing" do
let(:npmrc_fixture_name) { "env_auth_token" }
it "removes the env variable use" do
expect(npmrc_content).
to eq("@dependabot:registry=https://npm.fury.io/dependabot/\n")
end
end
context "that needs an auth sanitizing" do
let(:npmrc_fixture_name) { "env_auth" }
it "removes the env variable use" do
expect(npmrc_content).
to eq("@dependabot:registry=https://npm.fury.io/dependabot/\n")
end
end
end
context "and a yarnrc file" do
let(:dependency_files) { [package_json, yarn_lock, yarnrc] }
it "uses the yarnrc file registry" do
expect(npmrc_content).to eq(
"registry = https://npm-proxy.fury.io/password/dependabot/\n"
)
end
end
end
context "with no private sources and some credentials" do
let(:manifest_fixture_name) { "package.json" }
let(:yarn_lock_fixture_name) { "yarn.lock" }
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "registry.npmjs.org",
"token" => "my_token"
}]
end
it { is_expected.to eq("//registry.npmjs.org/:_authToken=my_token") }
context "that uses basic auth" do
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "registry.npmjs.org",
"token" => "my:token"
}]
end
it "includes Basic auth details" do
expect(npmrc_content).to eq(
"always-auth = true\n//registry.npmjs.org/:_auth=bXk6dG9rZW4="
)
end
end
context "and an npmrc file" do
let(:dependency_files) { [package_json, yarn_lock, npmrc] }
it "appends to the npmrc file" do
expect(npmrc_content).
to include(fixture("npmrc", npmrc_fixture_name))
expect(npmrc_content).
to end_with("\n\n//registry.npmjs.org/:_authToken=my_token")
end
end
end
context "with a private source used for some dependencies" do
let(:manifest_fixture_name) { "private_source.json" }
let(:yarn_lock_fixture_name) { "private_source.lock" }
it { is_expected.to eq("") }
context "and some credentials" do
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "registry.npmjs.org",
"token" => "my_token"
}]
end
it { is_expected.to eq("//registry.npmjs.org/:_authToken=my_token") }
context "that match a scoped package" do
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "npm.fury.io/dependabot",
"token" => "my_token"
}]
end
it "adds auth details, and scopes them correctly" do
expect(npmrc_content).
to eq("@dependabot:registry=https://npm.fury.io/dependabot/\n"\
"//npm.fury.io/dependabot/:_authToken=my_token")
end
end
end
end
context "with a private source used for all dependencies" do
let(:manifest_fixture_name) { "package.json" }
let(:yarn_lock_fixture_name) { "all_private.lock" }
it { is_expected.to eq("") }
context "and credentials for the private source" do
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "npm.fury.io/dependabot",
"token" => "my_token"
}]
end
it "adds a global registry line, and auth details" do
expect(npmrc_content).
to eq("registry = https://npm.fury.io/dependabot\n"\
"_authToken = my_token\n"\
"always-auth = true\n"\
"//npm.fury.io/dependabot/:_authToken=my_token")
end
context "and an npmrc file" do
let(:dependency_files) { [package_json, yarn_lock, npmrc] }
let(:npmrc_fixture_name) { "env_global_auth" }
it "extends the already existing npmrc" do
expect(npmrc_content).
to eq("always-auth = true\n"\
"strict-ssl = true\n"\
"//npm.fury.io/dependabot/:_authToken=secret_token\n"\
"registry = https://npm.fury.io/dependabot\n"\
"_authToken = my_token\n"\
"always-auth = true\n\n"\
"//npm.fury.io/dependabot/:_authToken=my_token")
end
context "that uses environment variables everywhere" do
let(:npmrc_fixture_name) { "env_registry" }
it "extends the already existing npmrc" do
expect(npmrc_content).
to eq("//dependabot.jfrog.io/dependabot/api/npm/"\
"platform-npm/:always-auth=true\n"\
"always-auth = true\n"\
"registry = https://npm.fury.io/dependabot\n"\
"_authToken = my_token\n"\
"always-auth = true\n\n"\
"//npm.fury.io/dependabot/:_authToken=my_token")
end
end
end
context "and a yarnrc file" do
let(:dependency_files) { [package_json, yarn_lock, yarnrc] }
it "uses the yarnrc file registry" do
expect(npmrc_content).to eq(
"registry = https://npm-proxy.fury.io/password/dependabot/\n\n"\
"//npm.fury.io/dependabot/:_authToken=my_token"
)
end
context "that doesn't contain details of the registry" do
let(:yarnrc_fixture_name) { "offline_mirror" }
it "adds a global registry line based on the lockfile details" do
expect(npmrc_content).
to eq("registry = https://npm.fury.io/dependabot\n"\
"_authToken = my_token\n"\
"always-auth = true\n"\
"//npm.fury.io/dependabot/:_authToken=my_token")
end
end
end
end
end
end
context "with a package-lock.json" do
let(:dependency_files) { [package_json, package_lock] }
context "with no private sources and no credentials" do
let(:manifest_fixture_name) { "package.json" }
let(:npm_lock_fixture_name) { "package-lock.json" }
it { is_expected.to eq("") }
context "and an npmrc file" do
let(:dependency_files) { [package_json, package_lock, npmrc] }
it "returns the npmrc file unaltered" do
expect(npmrc_content).
to eq(fixture("npmrc", npmrc_fixture_name))
end
context "that need sanitizing" do
let(:npmrc_fixture_name) { "env_auth_token" }
it "removes the env variable use" do
expect(npmrc_content).
to eq("@dependabot:registry=https://npm.fury.io/dependabot/\n")
end
end
end
end
context "with no private sources and some credentials" do
let(:manifest_fixture_name) { "package.json" }
let(:npm_lock_fixture_name) { "package-lock.json" }
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "registry.npmjs.org",
"token" => "my_token"
}]
end
it { is_expected.to eq("//registry.npmjs.org/:_authToken=my_token") }
context "and an npmrc file" do
let(:dependency_files) { [package_json, package_lock, npmrc] }
it "appends to the npmrc file" do
expect(npmrc_content).
to include(fixture("npmrc", npmrc_fixture_name))
expect(npmrc_content).
to end_with("\n\n//registry.npmjs.org/:_authToken=my_token")
end
end
end
context "with a private source used for some dependencies" do
let(:manifest_fixture_name) { "private_source.json" }
let(:npm_lock_fixture_name) { "private_source.json" }
it { is_expected.to eq("") }
context "and some credentials" do
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "registry.npmjs.org",
"token" => "my_token"
}]
end
it { is_expected.to eq("//registry.npmjs.org/:_authToken=my_token") }
context "that match a scoped package" do
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "npm.fury.io/dependabot",
"token" => "my_token"
}]
end
it "adds auth details, and scopes them correctly" do
expect(npmrc_content).
to eq("@dependabot:registry=https://npm.fury.io/dependabot/\n"\
"//npm.fury.io/dependabot/:_authToken=my_token")
end
end
end
end
context "with a private source used for all dependencies" do
let(:manifest_fixture_name) { "package.json" }
let(:npm_lock_fixture_name) { "all_private.json" }
it { is_expected.to eq("") }
context "and credentials for the private source" do
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "npm.fury.io/dependabot",
"token" => "my_token"
}]
end
it "adds a global registry line, and token auth details" do
expect(npmrc_content).
to eq("registry = https://npm.fury.io/dependabot\n"\
"_authToken = my_token\n"\
"always-auth = true\n"\
"//npm.fury.io/dependabot/:_authToken=my_token")
end
context "with basic auth credentials" do
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "npm.fury.io/dependabot",
"token" => "secret:token"
}]
end
it "adds a global registry line, and Basic auth details" do
expect(npmrc_content).
to eq("registry = https://npm.fury.io/dependabot\n"\
"_auth = c2VjcmV0OnRva2Vu\n"\
"always-auth = true\n"\
"always-auth = true\n"\
"//npm.fury.io/dependabot/:_auth=c2VjcmV0OnRva2Vu")
end
end
context "and an npmrc file" do
let(:dependency_files) { [package_json, package_lock, npmrc] }
let(:npmrc_fixture_name) { "env_global_auth" }
it "populates the already existing npmrc" do
expect(npmrc_content).
to eq("always-auth = true\n"\
"strict-ssl = true\n"\
"//npm.fury.io/dependabot/:_authToken=secret_token\n"\
"registry = https://npm.fury.io/dependabot\n"\
"_authToken = my_token\n"\
"always-auth = true\n\n"\
"//npm.fury.io/dependabot/:_authToken=my_token")
end
context "with basic auth credentials" do
let(:credentials) do
[{
"type" => "git_source",
"host" => "github.com",
"username" => "x-access-token",
"password" => "token"
}, {
"type" => "npm_registry",
"registry" => "npm.fury.io/dependabot",
"token" => "secret:token"
}]
end
it "populates the already existing npmrc" do
expect(npmrc_content).
to eq("always-auth = true\n"\
"strict-ssl = true\n"\
"//npm.fury.io/dependabot/:_authToken=secret_token\n"\
"registry = https://npm.fury.io/dependabot\n"\
"_auth = c2VjcmV0OnRva2Vu\n"\
"always-auth = true\n\n"\
"always-auth = true\n"\
"//npm.fury.io/dependabot/:_auth=c2VjcmV0OnRva2Vu")
end
end
end
end
end
end
end
end
| 35.04375 | 80 | 0.507342 |
26e9765025920956054a7cdde9519cb4c62f04b9 | 356 | cask 'font-redressed' do
version :latest
sha256 :no_check
# github.com/google/fonts was verified as official when first introduced to the cask
url 'https://github.com/google/fonts/raw/master/apache/redressed/Redressed-Regular.ttf'
name 'Redressed'
homepage 'https://www.google.com/fonts/specimen/Redressed'
font 'Redressed-Regular.ttf'
end
| 29.666667 | 89 | 0.764045 |
4ad799cfc936cb288b38f02ee99bf8cc674bbadf | 968 | require_relative '../../test_init'
context "Included Attributes" do
context "Many" do
hash_source = Controls::Hash.example
object_source = Controls::Object.example
mapping = hash_source.keys
[[hash_source, 'Hash'], [object_source, 'Object']].each do |source_info|
source = source_info[0]
source_type = source_info[1]
context "#{source_type} Source" do
receiver = Controls::Object::New.example
SetAttributes.(receiver, source, include: [
:some_other_attribute,
:yet_another_attribute
])
context "Included" do
test "Are set" do
assert(receiver.some_other_attribute == 'some other value')
assert(receiver.yet_another_attribute == 'yet another value')
end
end
context "Excluded" do
test "Aren't set" do
assert(receiver.some_attribute.nil?)
end
end
end
end
end
end
| 24.820513 | 76 | 0.608471 |
f8ff350f5a581a3078f0c443295719177eca4759 | 621 | module CoolBreeze
module Mixins
module Associations
def self.included(base)
base.class_eval <<-EOS, __FILE__, __LINE__
class_inheritable_accessor(:associations)
self.associations = {}
EOS
base.extend(ClassMethods)
end
end
module ClassMethods
def many(name, options = {})
associations[name] = CoolBreeze::Association.new(self,name,options = {})
class_eval <<-EOS, __FILE__, __LINE__
def #{name}
self.class.associations[:"#{name}"].for(self)
end
EOS
end
end
end
end | 24.84 | 80 | 0.57971 |
87cfec7ff9743d1f37e49c9e89d4447dcfdae165 | 1,349 | class Avra < Formula
desc "Assember for the Atmel AVR microcontroller family"
homepage "http://avra.sourceforge.net/"
url "https://downloads.sourceforge.net/project/avra/1.3.0/avra-1.3.0.tar.bz2"
sha256 "a62cbf8662caf9cc4e75da6c634efce402778639202a65eb2d149002c1049712"
bottle do
cellar :any_skip_relocation
rebuild 1
sha256 "5c80f99bf03f251c6ca038931549259c2e703d16cf331c43a6ef34a7faaf6d52" => :sierra
sha256 "2269beb5581fec707e544f281ae7e5b21250fd0975ee10daed45212aabb31413" => :el_capitan
sha256 "8a382baf62c225aef1730ff1c53dd81257cea6da6c43f227b3405b673968e363" => :yosemite
sha256 "2e208cec5f270c91c9afc0349236a9abb0622e1e8208c67d25c90f017fcecf65" => :mavericks
end
depends_on "autoconf" => :build
depends_on "automake" => :build
def install
# build fails if these don't exist
touch "NEWS"
touch "ChangeLog"
cd "src" do
system "./bootstrap"
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
pkgshare.install Dir["includes/*"]
end
test do
(testpath/"test.asm").write " .device attiny10\n ldi r16,0x42\n"
output = shell_output("#{bin}/avra -l test.lst test.asm")
assert_match "Assembly complete with no errors.", output
assert File.exist?("test.hex")
assert_match "ldi r16,0x42", File.read("test.lst")
end
end
| 34.589744 | 92 | 0.729429 |
0382f7e9ca484a28a8501baf827fd29573131d4a | 133 | class AddSearchNameToProvider < ActiveRecord::Migration[5.2]
def change
add_column :providers, :search_name, :string
end
end
| 22.166667 | 60 | 0.766917 |
0870081b4f6ba1b976c3847c3bc3e55e85790742 | 7,676 | # encoding: UTF-8
require 'test_helper'
class AssociationTest < ActionView::TestCase
def with_association_for(object, *args)
with_concat_form_for(object) do |f|
f.association(*args)
end
end
test 'builder should not allow creating an association input when no object exists' do
assert_raise ArgumentError do
with_association_for :post, :author
end
end
test 'builder association with a block calls simple_fields_for' do
simple_form_for @user do |f|
f.association :posts do |posts_form|
assert posts_form.instance_of?(SimpleForm::FormBuilder)
end
end
end
test 'builder association forwards collection to simple_fields_for' do
calls = 0
simple_form_for @user do |f|
f.association :company, collection: Company.all do |c|
calls += 1
end
end
assert_equal 3, calls
end
test 'builder association marks input as required based on both association and attribute' do
swap SimpleForm, required_by_default: false do
with_association_for @validating_user, :company, collection: []
assert_select 'label.required'
end
end
test 'builder preloads collection association' do
value = @user.tags = MiniTest::Mock.new
value.expect(:to_a, value)
with_association_for @user, :tags
assert_select 'form select.select#user_tag_ids'
assert_select 'form select option[value=1]', 'Tag 1'
assert_select 'form select option[value=2]', 'Tag 2'
assert_select 'form select option[value=3]', 'Tag 3'
value.verify
end
test 'builder does not preload collection association if preload is false' do
value = @user.tags = MiniTest::Mock.new
value.expect(:to_a, nil)
with_association_for @user, :tags, preload: false
assert_select 'form select.select#user_tag_ids'
assert_select 'form select option[value=1]', 'Tag 1'
assert_select 'form select option[value=2]', 'Tag 2'
assert_select 'form select option[value=3]', 'Tag 3'
assert_raises MockExpectationError do
value.verify
end
end
test 'builder does not preload non-collection association' do
value = @user.company = MiniTest::Mock.new
value.expect(:to_a, nil)
with_association_for @user, :company
assert_select 'form select.select#user_company_id'
assert_select 'form select option[value=1]', 'Company 1'
assert_select 'form select option[value=2]', 'Company 2'
assert_select 'form select option[value=3]', 'Company 3'
assert_raises MockExpectationError do
value.verify
end
end
# ASSOCIATIONS - BELONGS TO
test 'builder creates a select for belongs_to associations' do
with_association_for @user, :company
assert_select 'form select.select#user_company_id'
assert_select 'form select option[value=1]', 'Company 1'
assert_select 'form select option[value=2]', 'Company 2'
assert_select 'form select option[value=3]', 'Company 3'
end
test 'builder creates blank select if collection is nil' do
with_association_for @user, :company, collection: nil
assert_select 'form select.select#user_company_id'
assert_no_select 'form select option[value=1]', 'Company 1'
end
test 'builder allows collection radio for belongs_to associations' do
with_association_for @user, :company, as: :radio_buttons
assert_select 'form input.radio_buttons#user_company_id_1'
assert_select 'form input.radio_buttons#user_company_id_2'
assert_select 'form input.radio_buttons#user_company_id_3'
end
test 'builder allows collection to have a proc as a condition' do
with_association_for @user, :extra_special_company
assert_select 'form select.select#user_extra_special_company_id'
assert_select 'form select option[value=1]'
assert_no_select 'form select option[value=2]'
assert_no_select 'form select option[value=3]'
end
test 'builder marks the record which already belongs to the user' do
@user.company_id = 2
with_association_for @user, :company, as: :radio_buttons
assert_no_select 'form input.radio_buttons#user_company_id_1[checked=checked]'
assert_select 'form input.radio_buttons#user_company_id_2[checked=checked]'
assert_no_select 'form input.radio_buttons#user_company_id_3[checked=checked]'
end
# ASSOCIATIONS - FINDERS
test 'builder should use reflection conditions to find collection' do
with_association_for @user, :special_company
assert_select 'form select.select#user_special_company_id'
assert_select 'form select option[value=1]'
assert_no_select 'form select option[value=2]'
assert_no_select 'form select option[value=3]'
end
test 'builder should allow overriding collection to association input' do
with_association_for @user, :company, include_blank: false,
collection: [Company.new(999, 'Teste')]
assert_select 'form select.select#user_company_id'
assert_no_select 'form select option[value=1]'
assert_select 'form select option[value=999]', 'Teste'
assert_select 'form select option', count: 1
end
# ASSOCIATIONS - has_*
test 'builder does not allow has_one associations' do
assert_raise ArgumentError do
with_association_for @user, :first_company, as: :radio_buttons
end
end
test 'builder creates a select with multiple options for collection associations' do
with_association_for @user, :tags
assert_select 'form select.select#user_tag_ids'
assert_select 'form select[multiple=multiple]'
assert_select 'form select option[value=1]', 'Tag 1'
assert_select 'form select option[value=2]', 'Tag 2'
assert_select 'form select option[value=3]', 'Tag 3'
end
test 'builder allows size to be overwritten for collection associations' do
with_association_for @user, :tags, input_html: { size: 10 }
assert_select 'form select[multiple=multiple][size=10]'
end
test 'builder marks all selected records which already belongs to user' do
@user.tag_ids = [1, 2]
with_association_for @user, :tags
assert_select 'form select option[value=1][selected=selected]'
assert_select 'form select option[value=2][selected=selected]'
assert_no_select 'form select option[value=3][selected=selected]'
end
test 'builder allows a collection of check boxes for collection associations' do
@user.tag_ids = [1, 2]
with_association_for @user, :tags, as: :check_boxes
assert_select 'form input#user_tag_ids_1[type=checkbox]'
assert_select 'form input#user_tag_ids_2[type=checkbox]'
assert_select 'form input#user_tag_ids_3[type=checkbox]'
end
test 'builder marks all selected records for collection boxes' do
@user.tag_ids = [1, 2]
with_association_for @user, :tags, as: :check_boxes
assert_select 'form input[type=checkbox][value=1][checked=checked]'
assert_select 'form input[type=checkbox][value=2][checked=checked]'
assert_no_select 'form input[type=checkbox][value=3][checked=checked]'
end
test 'builder with collection support giving collection and item wrapper tags' do
with_association_for @user, :tags, as: :check_boxes,
collection_wrapper_tag: :ul, item_wrapper_tag: :li
assert_select 'form ul', count: 1
assert_select 'form ul li', count: 3
end
test 'builder with collection support should not change the options hash' do
options = { as: :check_boxes, collection_wrapper_tag: :ul, item_wrapper_tag: :li}
with_association_for @user, :tags, options
assert_select 'form ul', count: 1
assert_select 'form ul li', count: 3
assert_equal({ as: :check_boxes, collection_wrapper_tag: :ul, item_wrapper_tag: :li},
options)
end
end
| 37.443902 | 95 | 0.733194 |
39bc84a04f62140a68385fcdec5fecc5f738fc2f | 615 | require_relative '../automated_init'
context "Read Stream Using Alternative Optimized Output Schema" do
stream, batch = Controls::Write.(metadata: true)
read_stream = EventStore::HTTP::ReadStream.build
read_stream.embed_body
read_stream.output_schema = Controls::ReadStream::OutputSchema::Optimized.example
event, * = read_stream.(stream)
test "Event is deserialized into output schema" do
event_id = batch.events[0].id
control_event = Controls::ReadStream::OutputSchema::Optimized::Event.example(
id: event_id,
stream: stream
)
assert event == control_event
end
end
| 26.73913 | 83 | 0.738211 |
e9cd63b2f9ac9d068e9e757a0ff5cef600de48da | 1,717 | require 'spec_helper'
RSpec.describe Spree::Tax::OrderAdjuster do
subject(:adjuster) { described_class.new(order) }
describe 'initialization' do
let(:order) { Spree::Order.new }
it 'sets order to adjustable' do
expect(adjuster.order).to eq(order)
end
end
describe '#adjust!' do
let(:line_items) { build_stubbed_list(:line_item, 2) }
let(:order) { build_stubbed(:order, line_items: line_items) }
let(:rates_for_order_zone) { [] }
let(:rates_for_default_zone) { [] }
let(:item_adjuster) { Spree::Tax::ItemAdjuster.new(line_items.first) }
before do
expect(Spree::TaxRate).to receive(:for_address).with(order.tax_address).and_return(rates_for_order_zone)
end
it 'calls the item adjuster with all line items' do
expect(Spree::Tax::ItemAdjuster).to receive(:new).
with(
line_items.first,
rates_for_order: rates_for_order_zone,
rates_for_default_zone: rates_for_default_zone
).and_return(item_adjuster)
expect(Spree::Tax::ItemAdjuster).to receive(:new).
with(
line_items.second,
rates_for_order: rates_for_order_zone,
rates_for_default_zone: rates_for_default_zone
).and_return(item_adjuster)
expect(item_adjuster).to receive(:adjust!).twice
adjuster.adjust!
end
end
end
| 39.022727 | 110 | 0.536401 |
38e4f6242e2607715b109c4bbfc2c13b9e2d9f10 | 1,003 | module Metadata
module ProcessMapping
def process_mapping(xml, field, mapping)
if mapping.present?
if mapping.is_a?(Array)
mapping.each do |mapping_item|
# recurse and process each item in the array
process_mapping(xml, field, mapping_item)
end
elsif mapping.is_a?(Hash)
if mapping[:field].present?
Array.wrap(self[mapping[:field]]).each do |unparsed_value|
value = self.send(mapping[:'function'], unparsed_value, mapping[:'argument'] || '.')
xml.tag! field, value if value.present?
end
elsif mapping[:function].present?
value = self.send(mapping[:'function'], field, xml)
else
puts "WARNING: mapping #{mapping.inspect} is ignored"
end
elsif mapping.is_a?(String)
Array.wrap(self[mapping]).each do |value|
xml.tag! field, value
end
end
end
end
end
end
| 30.393939 | 98 | 0.571286 |
abd2e87b1e39a66f8f46bd3ffcf3410105b2a323 | 492 | require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module CounterExercise
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
| 30.75 | 82 | 0.76626 |
5d42f33453ec7348199a403c9f5d9605f6e89ad3 | 304 | # encoding: utf-8
# frozen_string_literal: true
require 'essay/abstract_feature'
module Essay
class AttributeFeatures::Base < AbstractFeature
attr_reader :attribute
alias this_attribute attribute
def initialize(env)
super
@attribute = env.fetch(:attribute)
end
end
end
| 17.882353 | 49 | 0.726974 |
bf72ec0bc77b4ae7181aa473c5f1564a5b1cff9a | 1,230 | Pod::Spec.new do |s|
s.name = 'JustTweak'
s.version = '9.0.0'
s.summary = 'A framework for feature flagging, locally and remotely configure and A/B test iOS apps.'
s.description = <<-DESC
JustTweak is a framework for feature flagging, locally and remotely configure and A/B test iOS apps.
DESC
s.homepage = 'https://github.com/justeat/JustTweak'
s.license = { :type => 'Apache 2.0', :file => 'LICENSE' }
s.author = 'Just Eat Takeaway iOS Team'
s.source = { :git => 'https://github.com/justeat/JustTweak.git', :tag => s.version.to_s }
s.ios.deployment_target = '11.0'
s.swift_version = '5.1'
s.source_files = 'JustTweak/Classes/**/*.swift'
s.resource_bundle = { 'JustTweak' => 'JustTweak/Assets/en.lproj/*' }
s.preserve_paths = [
'_TweakAccessorGenerator',
]
# Ensure the generator script are callable via
# ${PODS_ROOT}/<name>
s.prepare_command = <<-PREPARE_COMMAND_END
cp -f ./JustTweak/Assets/TweakAccessorGenerator.bundle/TweakAccessorGenerator ./_TweakAccessorGenerator
PREPARE_COMMAND_END
end
| 39.677419 | 119 | 0.596748 |
615e2cc338795d78c66832920f0c1a47a8d65577 | 1,703 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Compute::Mgmt::V2019_12_01
module Models
#
# Response after calling a manual recovery walk
#
class RecoveryWalkResponse
include MsRestAzure
# @return [Boolean] Whether the recovery walk was performed
attr_accessor :walk_performed
# @return [Integer] The next update domain that needs to be walked. Null
# means walk spanning all update domains has been completed
attr_accessor :next_platform_update_domain
#
# Mapper for RecoveryWalkResponse class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'RecoveryWalkResponse',
type: {
name: 'Composite',
class_name: 'RecoveryWalkResponse',
model_properties: {
walk_performed: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'walkPerformed',
type: {
name: 'Boolean'
}
},
next_platform_update_domain: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'nextPlatformUpdateDomain',
type: {
name: 'Number'
}
}
}
}
}
end
end
end
end
| 28.383333 | 78 | 0.557839 |
7ab05cc09248c0d3d9138c49eeb1c382e901781d | 6,419 | require 'cgi'
module Phrase
class GitHubSyncApi
attr_accessor :api_client
def initialize(api_client = ApiClient.default)
@api_client = api_client
end
# Export from Phrase to GitHub
# Export translations from Phrase to GitHub according to the .phraseapp.yml file within the GitHub repository.
# @param github_sync_export_parameters [GithubSyncExportParameters]
# @param [Hash] opts the optional parameters
# @option opts [String] :x_phrase_app_otp Two-Factor-Authentication token (optional)
# @return [nil]
def github_sync_export(github_sync_export_parameters, opts = {})
data, _status_code, _headers = github_sync_export_with_http_info(github_sync_export_parameters, opts)
data
end
# Export from Phrase to GitHub
# Export translations from Phrase to GitHub according to the .phraseapp.yml file within the GitHub repository.
# @param github_sync_export_parameters [GithubSyncExportParameters]
# @param [Hash] opts the optional parameters
# @option opts [String] :x_phrase_app_otp Two-Factor-Authentication token (optional)
# @return [Array<(Response, Integer, Hash)>] Response<(nil, response status code and response headers
def github_sync_export_with_http_info(github_sync_export_parameters, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: GitHubSyncApi.github_sync_export ...'
end
# verify the required parameter 'github_sync_export_parameters' is set
if @api_client.config.client_side_validation && github_sync_export_parameters.nil?
fail ArgumentError, "Missing the required parameter 'github_sync_export_parameters' when calling GitHubSyncApi.github_sync_export"
end
# resource path
local_var_path = '/github_syncs/export'
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
header_params[:'X-PhraseApp-OTP'] = opts[:'x_phrase_app_otp'] if !opts[:'x_phrase_app_otp'].nil?
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body] || @api_client.object_to_http_body(github_sync_export_parameters)
# return_type
return_type = opts[:return_type]
# auth_names
auth_names = opts[:auth_names] || ['Basic', 'Token']
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: GitHubSyncApi#github_sync_export\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
response = ::Phrase::Response.new(data, headers)
return response, status_code, headers
end
# Import to Phrase from GitHub
# Import files to Phrase from your connected GitHub repository.
# @param github_sync_import_parameters [GithubSyncImportParameters]
# @param [Hash] opts the optional parameters
# @option opts [String] :x_phrase_app_otp Two-Factor-Authentication token (optional)
# @return [nil]
def github_sync_import(github_sync_import_parameters, opts = {})
data, _status_code, _headers = github_sync_import_with_http_info(github_sync_import_parameters, opts)
data
end
# Import to Phrase from GitHub
# Import files to Phrase from your connected GitHub repository.
# @param github_sync_import_parameters [GithubSyncImportParameters]
# @param [Hash] opts the optional parameters
# @option opts [String] :x_phrase_app_otp Two-Factor-Authentication token (optional)
# @return [Array<(Response, Integer, Hash)>] Response<(nil, response status code and response headers
def github_sync_import_with_http_info(github_sync_import_parameters, opts = {})
if @api_client.config.debugging
@api_client.config.logger.debug 'Calling API: GitHubSyncApi.github_sync_import ...'
end
# verify the required parameter 'github_sync_import_parameters' is set
if @api_client.config.client_side_validation && github_sync_import_parameters.nil?
fail ArgumentError, "Missing the required parameter 'github_sync_import_parameters' when calling GitHubSyncApi.github_sync_import"
end
# resource path
local_var_path = '/github_syncs/import'
# query parameters
query_params = opts[:query_params] || {}
# header parameters
header_params = opts[:header_params] || {}
# HTTP header 'Accept' (if needed)
header_params['Accept'] = @api_client.select_header_accept(['application/json'])
# HTTP header 'Content-Type'
header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])
header_params[:'X-PhraseApp-OTP'] = opts[:'x_phrase_app_otp'] if !opts[:'x_phrase_app_otp'].nil?
# form parameters
form_params = opts[:form_params] || {}
# http body (model)
post_body = opts[:body] || @api_client.object_to_http_body(github_sync_import_parameters)
# return_type
return_type = opts[:return_type]
# auth_names
auth_names = opts[:auth_names] || ['Basic', 'Token']
new_options = opts.merge(
:header_params => header_params,
:query_params => query_params,
:form_params => form_params,
:body => post_body,
:auth_names => auth_names,
:return_type => return_type
)
data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)
if @api_client.config.debugging
@api_client.config.logger.debug "API called: GitHubSyncApi#github_sync_import\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}"
end
response = ::Phrase::Response.new(data, headers)
return response, status_code, headers
end
end
end
| 43.666667 | 159 | 0.706808 |
7a23a05ff5efb5273437ecc2b4a2bb56a9ad901f | 467 | ENV["RAILS_ENV"] = 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'webmock/rspec'
ENGINE_RAILS_ROOT=File.join(File.dirname(__FILE__), '../')
# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir[File.join(ENGINE_RAILS_ROOT, "spec/support/**/*.rb")].each {|f| require f }
RSpec.configure do |config|
config.use_transactional_fixtures = true
end
| 29.1875 | 79 | 0.745182 |
6a0c93fe8674ee964318bf6b27362d0e4d2732c6 | 94 | class RemoveUsers < ActiveRecord::Migration[5.0]
def change
drop_table :users
end
end
| 15.666667 | 48 | 0.734043 |
d5d748d22efba8befc88830b8780d52229bc14fa | 12,279 | # Use this hook to configure devise mailer, warden hooks and so forth.
# Many of these configuration options can be set straight in your model.
Devise.setup do |config|
# ==> Mailer Configuration
# Configure the e-mail address which will be shown in Devise::Mailer,
# note that it will be overwritten if you use your own mailer class with default "from" parameter.
config.mailer_sender = "[email protected]"
# Configure the class responsible to send e-mails.
# config.mailer = "Devise::Mailer"
# ==> ORM configuration
# Load and configure the ORM. Supports :active_record (default) and
# :mongoid (bson_ext recommended) by default. Other ORMs may be
# available as additional gems.
require 'devise/orm/active_record'
# ==> Configuration for any authentication mechanism
# Configure which keys are used when authenticating a user. The default is
# just :email. You can configure it to use [:username, :subdomain], so for
# authenticating a user, both parameters are required. Remember that those
# parameters are used only when authenticating and not when retrieving from
# session. If you need permissions, you should implement that in a before filter.
# You can also supply a hash where the value is a boolean determining whether
# or not authentication should be aborted when the value is not present.
config.authentication_keys = [ :email ]
# Configure parameters from the request object used for authentication. Each entry
# given should be a request method and it will automatically be passed to the
# find_for_authentication method and considered in your model lookup. For instance,
# if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
# The same considerations mentioned for authentication_keys also apply to request_keys.
# config.request_keys = []
# Configure which authentication keys should be case-insensitive.
# These keys will be downcased upon creating or modifying a user and when used
# to authenticate or find a user. Default is :email.
config.case_insensitive_keys = [ :email ]
# Configure which authentication keys should have whitespace stripped.
# These keys will have whitespace before and after removed upon creating or
# modifying a user and when used to authenticate or find a user. Default is :email.
config.strip_whitespace_keys = [ :email ]
# Tell if authentication through request.params is enabled. True by default.
# It can be set to an array that will enable params authentication only for the
# given strategies, for example, `config.params_authenticatable = [:database]` will
# enable it only for database (email + password) authentication.
# config.params_authenticatable = true
# Tell if authentication through HTTP Auth is enabled. False by default.
# It can be set to an array that will enable http authentication only for the
# given strategies, for example, `config.http_authenticatable = [:token]` will
# enable it only for token authentication. The supported strategies are:
# :database = Support basic authentication with authentication key + password
# :token = Support basic authentication with token authentication key
# :token_options = Support token authentication with options as defined in
# http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html
# config.http_authenticatable = false
# If http headers should be returned for AJAX requests. True by default.
# config.http_authenticatable_on_xhr = true
# The realm used in Http Basic Authentication. "Application" by default.
# config.http_authentication_realm = "Application"
# It will change confirmation, password recovery and other workflows
# to behave the same regardless if the e-mail provided was right or wrong.
# Does not affect registerable.
# config.paranoid = true
# By default Devise will store the user in session. You can skip storage for
# :http_auth and :token_auth by adding those symbols to the array below.
# Notice that if you are skipping storage for all authentication paths, you
# may want to disable generating routes to Devise's sessions controller by
# passing :skip => :sessions to `devise_for` in your config/routes.rb
config.skip_session_storage = [:http_auth]
# ==> Configuration for :database_authenticatable
# For bcrypt, this is the cost for hashing the password and defaults to 10. If
# using other encryptors, it sets how many times you want the password re-encrypted.
#
# Limiting the stretches to just one in testing will increase the performance of
# your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
# a value less than 10 in other environments.
config.stretches = Rails.env.test? ? 1 : 10
# Setup a pepper to generate the encrypted password.
# config.pepper = "e4daffbe5d347d65015b766fedf4072277a1313f63c86addc607ddde6997e4e28dbb10fbeb89716cd49f4931073895edbecfe13f93d619b8f5b0fec7fc158d3c"
# ==> Configuration for :confirmable
# A period that the user is allowed to access the website even without
# confirming his account. For instance, if set to 2.days, the user will be
# able to access the website for two days without confirming his account,
# access will be blocked just in the third day. Default is 0.days, meaning
# the user cannot access the website without confirming his account.
# config.allow_unconfirmed_access_for = 2.days
# A period that the user is allowed to confirm their account before their
# token becomes invalid. For example, if set to 3.days, the user can confirm
# their account within 3 days after the mail was sent, but on the fourth day
# their account can't be confirmed with the token any more.
# Default is nil, meaning there is no restriction on how long a user can take
# before confirming their account.
# config.confirm_within = 3.days
# If true, requires any email changes to be confirmed (exactly the same way as
# initial account confirmation) to be applied. Requires additional unconfirmed_email
# db field (see migrations). Until confirmed new email is stored in
# unconfirmed email column, and copied to email column on successful confirmation.
config.reconfirmable = true
# Defines which key will be used when confirming an account
# config.confirmation_keys = [ :email ]
# ==> Configuration for :rememberable
# The time the user will be remembered without asking for credentials again.
# config.remember_for = 2.weeks
# If true, extends the user's remember period when remembered via cookie.
# config.extend_remember_period = false
# Options to be passed to the created cookie. For instance, you can set
# :secure => true in order to force SSL only cookies.
# config.rememberable_options = {}
# ==> Configuration for :validatable
# Range for password length. Default is 8..128.
config.password_length = 8..128
# Email regex used to validate email formats. It simply asserts that
# one (and only one) @ exists in the given string. This is mainly
# to give user feedback and not to assert the e-mail validity.
# config.email_regexp = /\A[^@]+@[^@]+\z/
# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
# config.timeout_in = 30.minutes
# If true, expires auth token on session timeout.
# config.expire_auth_token_on_timeout = false
# ==> Configuration for :lockable
# Defines which strategy will be used to lock an account.
# :failed_attempts = Locks an account after a number of failed attempts to sign in.
# :none = No lock strategy. You should handle locking by yourself.
# config.lock_strategy = :failed_attempts
# Defines which key will be used when locking and unlocking an account
# config.unlock_keys = [ :email ]
# Defines which strategy will be used to unlock an account.
# :email = Sends an unlock link to the user email
# :time = Re-enables login after a certain amount of time (see :unlock_in below)
# :both = Enables both strategies
# :none = No unlock strategy. You should handle unlocking by yourself.
# config.unlock_strategy = :both
# Number of authentication tries before locking an account if lock_strategy
# is failed attempts.
# config.maximum_attempts = 20
# Time interval to unlock the account if :time is enabled as unlock_strategy.
# config.unlock_in = 1.hour
# ==> Configuration for :recoverable
#
# Defines which key will be used when recovering the password for an account
# config.reset_password_keys = [ :email ]
# Time interval you can reset your password with a reset password key.
# Don't put a too small interval or your users won't have the time to
# change their passwords.
config.reset_password_within = 6.hours
# ==> Configuration for :encryptable
# Allow you to use another encryption algorithm besides bcrypt (default). You can use
# :sha1, :sha512 or encryptors from others authentication tools as :clearance_sha1,
# :authlogic_sha512 (then you should set stretches above to 20 for default behavior)
# and :restful_authentication_sha1 (then you should set stretches to 10, and copy
# REST_AUTH_SITE_KEY to pepper).
#
# Require the `devise-encryptable` gem when using anything other than bcrypt
# config.encryptor = :sha512
# ==> Configuration for :token_authenticatable
# Defines name of the authentication token params key
# config.token_authentication_key = :auth_token
# ==> Scopes configuration
# Turn scoped views on. Before rendering "sessions/new", it will first check for
# "users/sessions/new". It's turned off by default because it's slower if you
# are using only default views.
# config.scoped_views = false
# Configure the default scope given to Warden. By default it's the first
# devise role declared in your routes (usually :user).
# config.default_scope = :user
# Set this configuration to false if you want /users/sign_out to sign out
# only the current scope. By default, Devise signs out all scopes.
# config.sign_out_all_scopes = true
# ==> Navigation configuration
# Lists the formats that should be treated as navigational. Formats like
# :html, should redirect to the sign in page when the user does not have
# access, but formats like :xml or :json, should return 401.
#
# If you have any extra navigational formats, like :iphone or :mobile, you
# should add them to the navigational formats lists.
#
# The "*/*" below is required to match Internet Explorer requests.
# config.navigational_formats = ["*/*", :html]
# The default HTTP method used to sign out a resource. Default is :delete.
config.sign_out_via = :delete
# ==> OmniAuth
# Add a new OmniAuth provider. Check the wiki for more information on setting
# up on your models and hooks.
config.omniauth :github, 'c78410519314abfeccf8', 'ede095095d51dd1886a5845eac94edce04c1d81b', :scope => 'user,public_repo'
# ==> Warden configuration
# If you want to use other strategies, that are not supported by Devise, or
# change the failure app, you can configure them inside the config.warden block.
#
# config.warden do |manager|
# manager.intercept_401 = false
# manager.default_strategies(:scope => :user).unshift :some_external_strategy
# end
# ==> Mountable engine configurations
# When using Devise inside an engine, let's call it `MyEngine`, and this engine
# is mountable, there are some extra configurations to be taken into account.
# The following options are available, assuming the engine is mounted as:
#
# mount MyEngine, at: "/my_engine"
#
# The router that invoked `devise_for`, in the example above, would be:
# config.router_name = :my_engine
#
# When using omniauth, Devise cannot automatically set Omniauth path,
# so you need to do it manually. For the users scope, it would be:
# config.omniauth_path_prefix = "/my_engine/users/auth"
config.secret_key = 'b17b41185ddda05a971584891937ab583a1682364c82e4bad8eca1c4d0b79a8b865ccd828aee5dc883f875dd2a2c8cdd7d9a7b0bed1e8f552a5e90cfc71fcedf'
end
| 49.313253 | 152 | 0.74941 |
bbf2bf663cc90b2ff25fcf5c9fb3c780e82dbe88 | 1,251 | class User < ApplicationRecord
attr_accessor :remember_token
before_save { email.downcase! }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 }, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }
# Returns the hash digest of the given string.
def User.digest(string)
cost = ActiveModel::SecurePassword.min_cost ? BCrypt::Engine::MIN_COST :
BCrypt::Engine.cost
BCrypt::Password.create(string, cost: cost)
end
# Returns a random token.
def User.new_token
SecureRandom.urlsafe_base64
end
def remember
self.remember_token = User.new_token
update_attribute(:remember_digest, User.digest(remember_token))
end
# Returns true if the given token matches the digest.
def authenticated?(remember_token)
return false if remember_digest.nil?
BCrypt::Password.new(remember_digest).is_password?(remember_token)
end
# Forgets a user.
def forget
update_attribute(:remember_digest, nil)
end
end
| 29.785714 | 136 | 0.686651 |
b99a07b0d4f74ab48fbcfbefac148ad4d1b2de67 | 3,452 | # frozen_string_literal: true
# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
require 'coveralls'
require 'webmock/rspec'
Coveralls.wear!('rails')
RSpec.configure do |config|
config.filter_run_excluding(:live_aws, :live_ibm) unless ENV['CI'] == 'true' # default exclude unless on CI
# rspec-expectations config goes here. You can use an alternate
# assertion/expectation library such as wrong or the stdlib/minitest
# assertions if you prefer.
config.expect_with :rspec do |expectations|
# This option will default to `true` in RSpec 4. It makes the `description`
# and `failure_message` of custom matchers include text for helper methods
# defined using `chain`, e.g.:
# be_bigger_than(2).and_smaller_than(4).description
# # => "be bigger than 2 and smaller than 4"
# ...rather than:
# # => "be bigger than 2"
expectations.include_chain_clauses_in_custom_matcher_descriptions = true
end
config.mock_with :rspec do |mocks|
# Prevents you from mocking or stubbing a method that does not exist on a real object.
# This is generally recommended, and will default to `true` in RSpec 4.
mocks.verify_partial_doubles = true
end
# This option will default to `:apply_to_host_groups` in RSpec 4 (and will
# have no way to turn it off -- the option exists only for backwards
# compatibility in RSpec 3). It causes shared context metadata to be
# inherited by the metadata hash of host groups and examples, rather than
# triggering implicit auto-inclusion in groups with matching metadata.
config.shared_context_metadata_behavior = :apply_to_host_groups
# Many RSpec users commonly either run the entire suite or an individual
# file, and it's useful to allow more verbose output when running an
# individual spec file.
if config.files_to_run.one?
# Use the documentation formatter for detailed output,
# unless a formatter has already been configured
# (e.g. via a command-line flag).
config.default_formatter = "doc"
end
# The settings below are suggested to provide a good initial experience
# with RSpec, but feel free to customize to your heart's content.
=begin
# This allows you to limit a spec run to individual examples or groups
# you care about by tagging them with `:focus` metadata. When nothing
# is tagged with `:focus`, all examples get run. RSpec also provides
# aliases for `it`, `describe`, and `context` that include `:focus`
# metadata: `fit`, `fdescribe` and `fcontext`, respectively.
config.filter_run_when_matching :focus
# Allows RSpec to persist some state between runs in order to support
# the `--only-failures` and `--next-failure` CLI options. We recommend
# you configure your source control system to ignore this file.
config.example_status_persistence_file_path = "spec/examples.txt"
# Limits the available syntax to the non-monkey patched syntax that is
# recommended. For more details, see:
# - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/
# - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
# - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode
config.disable_monkey_patching!
# Print the 10 slowest examples and example groups at the
# end of the spec run, to help surface which specs are running
# particularly slow.
config.profile_examples = 10
=end
end
| 45.421053 | 109 | 0.74044 |
b9630b00038091108929878e724e67ed3726819b | 3,066 | # frozen_string_literal: true
module ExceedQueryLimitHelpers
MARGINALIA_ANNOTATION_REGEX = %r{\s*\/\*.*\*\/}.freeze
def with_threshold(threshold)
@threshold = threshold
self
end
def for_query(query)
@query = query
self
end
def threshold
@threshold.to_i
end
def expected_count
if expected.is_a?(ActiveRecord::QueryRecorder)
expected.count
else
expected
end
end
def actual_count
@actual_count ||= if @query
recorder.log.select { |recorded| recorded =~ @query }.size
else
recorder.count
end
end
def recorder
@recorder ||= ActiveRecord::QueryRecorder.new(skip_cached: skip_cached, &@subject_block)
end
def count_queries(queries)
queries.each_with_object(Hash.new(0)) { |query, counts| counts[query] += 1 }
end
def log_message
if expected.is_a?(ActiveRecord::QueryRecorder)
counts = count_queries(strip_marginalia_annotations(expected.log))
extra_queries = strip_marginalia_annotations(@recorder.log).reject { |query| counts[query] -= 1 unless counts[query].zero? }
extra_queries_display = count_queries(extra_queries).map { |query, count| "[#{count}] #{query}" }
(['Extra queries:'] + extra_queries_display).join("\n\n")
else
@recorder.log_message
end
end
def skip_cached
true
end
def verify_count(&block)
@subject_block = block
actual_count > expected_count + threshold
end
def failure_message
threshold_message = threshold > 0 ? " (+#{@threshold})" : ''
counts = "#{expected_count}#{threshold_message}"
"Expected a maximum of #{counts} queries, got #{actual_count}:\n\n#{log_message}"
end
def strip_marginalia_annotations(logs)
logs.map { |log| log.sub(MARGINALIA_ANNOTATION_REGEX, '') }
end
end
RSpec::Matchers.define :issue_same_number_of_queries_as do
supports_block_expectations
include ExceedQueryLimitHelpers
def control
block_arg
end
def control_recorder
@control_recorder ||= ActiveRecord::QueryRecorder.new(&control)
end
def expected_count
@expected_count ||= control_recorder.count
end
def verify_count(&block)
@subject_block = block
(expected_count - actual_count).abs <= threshold
end
match do |block|
verify_count(&block)
end
failure_message_when_negated do |actual|
failure_message
end
def skip_cached
false
end
end
RSpec::Matchers.define :exceed_all_query_limit do |expected|
supports_block_expectations
include ExceedQueryLimitHelpers
match do |block|
verify_count(&block)
end
failure_message_when_negated do |actual|
failure_message
end
def skip_cached
false
end
end
# Excludes cached methods from the query count
RSpec::Matchers.define :exceed_query_limit do |expected|
supports_block_expectations
include ExceedQueryLimitHelpers
match do |block|
verify_count(&block)
end
failure_message_when_negated do |actual|
failure_message
end
end
| 21.291667 | 130 | 0.695042 |
e9e8905ed5e53d8b09c011f06f6b29c8073c4422 | 5,249 | #
# Be sure to run `pod spec lint RxWebClient.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|
# ――― Spec Metadata ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# These will help people to find your library, and whilst it
# can feel like a chore to fill in it's definitely to your advantage. The
# summary should be tweet-length, and the description more in depth.
#
s.name = "RxWebClient"
s.version = "0.0.1"
s.summary = "Rx & Moya of RxWebClient."
# This description is used to generate tags and improve search results.
# * Think: What does it do? Why did you write it? What is the focus?
# * Try to keep it short, snappy and to the point.
# * Write the description between the DESC delimiters below.
# * Finally, don't worry about the indent, CocoaPods strips it!
s.description = <<-DESC
网络库封装
DESC
s.homepage = "http://EXAMPLE/RxWebClient"
# s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif"
# ――― Spec License ――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Licensing your code is important. See http://choosealicense.com for more info.
# CocoaPods will detect a license file if there is a named LICENSE*
# Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'.
#
s.license = "MIT"
# s.license = { :type => "MIT", :file => "FILE_LICENSE" }
# ――― Author Metadata ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the authors of the library, with email addresses. Email addresses
# of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also
# accepts just a name if you'd rather not provide an email address.
#
# Specify a social_media_url where others can refer to, for example a twitter
# profile URL.
#
s.author = { "2Boss" => "" }
# Or just: s.author = "2Boss"
# s.authors = { "2Boss" => "" }
# s.social_media_url = "http://twitter.com/2Boss"
# ――― Platform Specifics ――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If this Pod runs only on iOS or OS X, then specify the platform and
# the deployment target. You can optionally include the target after the platform.
#
# s.platform = :ios
s.platform = :ios, "8.0"
# When using multiple platforms
# s.ios.deployment_target = "5.0"
# s.osx.deployment_target = "10.7"
# s.watchos.deployment_target = "2.0"
# s.tvos.deployment_target = "9.0"
# ――― Source Location ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Specify the location from where the source should be retrieved.
# Supports git, hg, bzr, svn and HTTP.
# , :tag => "#{s.version}"
s.source = { :git => "https://github.com/jingtao910429/RxWebClient.git"}
# ――― Source Code ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# CocoaPods is smart about how it includes source code. For source files
# giving a folder will include any swift, h, m, mm, c & cpp files.
# For header files it will include any header in the folder.
# Not including the public_header_files will make all headers public.
#
s.source_files = "Source/*.swift"
# s.source_files = "Classes", "Classes/**/*.{h,m}"
# s.exclude_files = "Classes/Exclude"
# s.public_header_files = "Classes/**/*.h"
# ――― Resources ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# A list of resources included with the Pod. These are copied into the
# target bundle with a build phase script. Anything else will be cleaned.
# You can preserve files from being cleaned, please don't preserve
# non-essential files like tests, examples and documentation.
#
# s.resource = "icon.png"
# s.resources = "Resources/*.png"
# s.preserve_paths = "FilesToSave", "MoreFilesToSave"
# ――― Project Linking ―――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# Link your library with frameworks, or libraries. Libraries do not include
# the lib prefix of their name.
#
# s.framework = "SomeFramework"
s.frameworks = 'Foundation'
# s.library = "iconv"
# s.libraries = "iconv", "xml2"
# ――― Project Settings ――――――――――――――――――――――――――――――――――――――――――――――――――――――――― #
#
# If your library depends on compiler flags you can set them in the xcconfig hash
# where they will only apply to your library. If you depend on other Podspecs
# you can include multiple dependencies to ensure it works.
s.requires_arc = true
# s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" }
s.dependency "Alamofire", "~> 4.3"
s.dependency "Moya", "~> 8.0.0"
s.dependency "Moya/RxSwift"
s.dependency "RxSwift", "~> 3.3.0"
s.dependency "RxCocoa", "~> 3.3.0"
s.dependency "SwiftyJSON", "~> 3.1.4"
s.dependency "ObjectMapper", "~> 2.0.0"
end
| 36.2 | 93 | 0.585445 |
218f441f929a089d8956a7e5343955c6796e9da0 | 3,478 | class Glib < Formula
desc "Core application library for C"
homepage "https://developer.gnome.org/glib/"
url "https://download.gnome.org/sources/glib/2.60/glib-2.60.4.tar.xz"
sha256 "2b941ec5dcb92e5ea83fe42f9eb55a827bc8a12c153ad2489d551c31d04733dd"
bottle do
sha256 "037cfa913d974cb0257deeb8575a6e9d7b000634aa1339581b7b12d2369d91c0" => :mojave
sha256 "f236c2ada6727a674e02db25e5dd7a81ffa75975f59cb4ff376c82794591191b" => :high_sierra
sha256 "fe164e352e12e8a39e1382891d64851776932a4e132b0804352088d78044c6dc" => :sierra
sha256 "3b4764f8a097008e5b237cdfa879cd42d9fb00e595fe5785d6f8611884b6e32b" => :x86_64_linux
end
depends_on "meson" => :build
depends_on "ninja" => :build
depends_on "pkg-config" => :build
depends_on "gettext"
depends_on "libffi"
depends_on "pcre"
depends_on "python"
depends_on "util-linux" unless OS.mac? # for libmount.so
# https://bugzilla.gnome.org/show_bug.cgi?id=673135 Resolved as wontfix,
# but needed to fix an assumption about the location of the d-bus machine
# id file.
patch do
url "https://raw.githubusercontent.com/Homebrew/formula-patches/6164294a7/glib/hardcoded-paths.diff"
sha256 "a57fec9e85758896ff5ec1ad483050651b59b7b77e0217459ea650704b7d422b"
end
def install
inreplace %w[gio/gdbusprivate.c gio/xdgmime/xdgmime.c glib/gutils.c],
"@@HOMEBREW_PREFIX@@", HOMEBREW_PREFIX
# Disable dtrace; see https://trac.macports.org/ticket/30413
args = %W[
-Dgio_module_dir=#{HOMEBREW_PREFIX}/lib/gio/modules
-Dbsymbolic_functions=false
-Ddtrace=false
]
args << "-Diconv=native" if OS.mac?
# Prevent meson to use lib64 on centos
args << "--libdir=#{lib}" unless OS.mac?
mkdir "build" do
system "meson", "--prefix=#{prefix}", *args, ".."
system "ninja", "-v"
system "ninja", "install", "-v"
end
# ensure giomoduledir contains prefix, as this pkgconfig variable will be
# used by glib-networking and glib-openssl to determine where to install
# their modules
inreplace lib/"pkgconfig/gio-2.0.pc",
"giomoduledir=#{HOMEBREW_PREFIX}/lib/gio/modules",
"giomoduledir=${libdir}/gio/modules"
# `pkg-config --libs glib-2.0` includes -lintl, and gettext itself does not
# have a pkgconfig file, so we add gettext lib and include paths here.
gettext = Formula["gettext"].opt_prefix
lintl = OS.mac? ? "-lintl ": ""
inreplace lib+"pkgconfig/glib-2.0.pc" do |s|
s.gsub! "Libs: #{lintl}-L${libdir} -lglib-2.0",
"Libs: -L${libdir} -lglib-2.0 -L#{gettext}/lib#{lintl}"
s.gsub! "Cflags: -I${includedir}/glib-2.0 -I${libdir}/glib-2.0/include",
"Cflags: -I${includedir}/glib-2.0 -I${libdir}/glib-2.0/include -I#{gettext}/include"
end
end
def post_install
(HOMEBREW_PREFIX/"lib/gio/modules").mkpath
end
test do
(testpath/"test.c").write <<~EOS
#include <string.h>
#include <glib.h>
int main(void)
{
gchar *result_1, *result_2;
char *str = "string";
result_1 = g_convert(str, strlen(str), "ASCII", "UTF-8", NULL, NULL, NULL);
result_2 = g_convert(result_1, strlen(result_1), "UTF-8", "ASCII", NULL, NULL, NULL);
return (strcmp(str, result_2) == 0) ? 0 : 1;
}
EOS
system ENV.cc, "-o", "test", "test.c", "-I#{include}/glib-2.0",
"-I#{lib}/glib-2.0/include", "-L#{lib}", "-lglib-2.0"
system "./test"
end
end
| 36.229167 | 104 | 0.6659 |
3882813e33faf7bad526743ae760e9d2ff535de0 | 858 | ##
# This file is part of WhatWeb and may be subject to
# redistribution and commercial restrictions. Please see the WhatWeb
# web site for more information on licensing and terms of use.
# http://www.morningstarsecurity.com/research/whatweb
##
Plugin.define "MistCMS" do
author "Brendan Coles <[email protected]>" # 2011-03-03
version "0.1"
description "MistCMS is a free Content Management System written in PHP that allows you to dynamically edit the content on your website without having to reupload everything every time you want to make a change."
# Google results as at 2011-03-03 #
# 1 for MistCMS intitle:MistCMS inurl:admin Username Password
# Matches #
matches [
# Admin Page
{ :text=>'<div class="page">login</div><form method="post" action="mist.php">' },
# HTML Comment
{ :text=>'<!-- Powered by MistCMS @ dvondrake.com -->' },
]
end
| 27.677419 | 212 | 0.736597 |
33c1a2c3c7c0cee648a81ac6e3655c94f8010255 | 541 | require 'ffuse'
require 'ffuse/filesystem'
class HelloWorld2 < FFUSE::Filesystem::AbstractFilesystem
class Hello < FFUSE::Filesystem::File
MESSAGE = "Hello, World.\n"
def read(len, off, fh)
MESSAGE.byteslice off, len
end
def size
MESSAGE.bytesize
end
end
def initialize
@root = FFUSE::Filesystem::Directory.new
@root.set_root
@root.link "hello", Hello.new
end
attr_reader :root
enable :getattr, :read, :readdir, :rename
end
if __FILE__ == $0
FFUSE.main HelloWorld2.new, ARGV
end
| 19.321429 | 57 | 0.678373 |
1cdcc7a2e5dbaea42c0e37a50333e7b57013fdc0 | 113 | class AddBodyToItems < ActiveRecord::Migration[5.2]
def change
add_column :items, :body, :string
end
end
| 18.833333 | 51 | 0.725664 |
bb9e8824b1aafcfa1b809a8e51d2afbaf62a4722 | 3,516 | =begin
#Signing Today Web
#*Signing Today* is the perfect Digital Signature Gateway. Whenever in Your workflow You need to add one or more Digital Signatures to Your document, *Signing Today* is the right choice. You prepare Your documents, *Signing Today* takes care of all the rest: send invitations (`signature tickets`) to signers, collects their signatures, send You back the signed document. Integrating *Signing Today* in Your existing applications is very easy. Just follow these API specifications and get inspired by the many examples presented hereafter.
The version of the OpenAPI document: 2.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 4.2.3
=end
require 'spec_helper'
require 'json'
# Unit tests for SigningTodayAPIClient::Bit4idPathgroupNotificationsApi
# Automatically generated by openapi-generator (https://openapi-generator.tech)
# Please update as you see appropriate
describe 'Bit4idPathgroupNotificationsApi' do
before do
# run before each test
@api_instance = SigningTodayAPIClient::Bit4idPathgroupNotificationsApi.new
end
after do
# run after each test
end
describe 'test an instance of Bit4idPathgroupNotificationsApi' do
it 'should create an instance of Bit4idPathgroupNotificationsApi' do
expect(@api_instance).to be_instance_of(SigningTodayAPIClient::Bit4idPathgroupNotificationsApi)
end
end
# unit tests for notifications_dst_id_delete
# Clear Notifications for a DST
# This API notifies that a user consumed all active notifications for a DST.
# @param id The value of _the unique id_
# @param [Hash] opts the optional parameters
# @return [nil]
describe 'notifications_dst_id_delete test' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for notifications_dsts_get
# Get latest DST Notifications
# This APIs allows to get latest user Notifications for DSTs sorted desc by time.
# @param [Hash] opts the optional parameters
# @option opts [Integer] :top A number of results to return. Applied after **$skip**
# @option opts [Integer] :skip An offset into the collection of results
# @option opts [Boolean] :count If true, the server includes the count of all the items in the response
# @return [NotificationsResponse]
describe 'notifications_dsts_get test' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for notifications_push_token_delete
# Clear a registered push notification token
# This API deregister a deviceId from the push notifications.
# @param device_id The _deviceId_ to deregister
# @param [Hash] opts the optional parameters
# @return [nil]
describe 'notifications_push_token_delete test' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
# unit tests for notifications_push_token_post
# Register a token for push notifications
# This API allows to register a token for push notifications. Only trusted deviceId can be registered.
# @param inline_object6
# @param [Hash] opts the optional parameters
# @return [nil]
describe 'notifications_push_token_post test' do
it 'should work' do
# assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers
end
end
end
| 40.883721 | 540 | 0.761661 |
030242fbc9db71e02464005d2f90f530ecbeae89 | 24,227 | #!/usr/bin/env rspec
require 'spec_helper'
require 'augeasproviders/provider'
describe AugeasProviders::Provider do
context "empty provider" do
class Empty
include AugeasProviders::Provider
attr_accessor :resource
end
subject { Empty }
describe "#lens" do
it "should fail as default lens isn't set" do
subject.expects(:fail).with('Lens is not provided').raises
expect { subject.lens }.to raise_error
end
end
describe "#target" do
it "should fail if no default or resource file" do
subject.expects(:fail).with('No target file given').raises
expect { subject.target }.to raise_error
end
it "should return resource file if set" do
subject.target(:target => '/foo').should == '/foo'
end
it "should strip trailing / from resource file" do
subject.target(:target => '/foo/').should == '/foo'
end
end
describe "#resource_path" do
it "should call #target if no resource path block set" do
resource = { :name => 'foo' }
subject.expects(:target).with(resource)
subject.resource_path(resource).should == '/foo'
end
it "should call #target if a resource path block is set" do
resource = { :name => 'foo' }
subject.expects(:target).with(resource)
subject.resource_path { '/files/test' }
subject.resource_path(resource).should == '/files/test'
end
end
describe "#readquote" do
it "should return :double when value is double-quoted" do
subject.readquote('"foo"').should == :double
end
it "should return :single when value is single-quoted" do
subject.readquote("'foo'").should == :single
end
it "should return nil when value is not quoted" do
subject.readquote("foo").should be_nil
end
it "should return nil when value is not properly quoted" do
subject.readquote("'foo").should be_nil
subject.readquote("'foo\"").should be_nil
subject.readquote("\"foo").should be_nil
subject.readquote("\"foo'").should be_nil
end
end
describe "#quoteit" do
it "should not do anything by default for alphanum values" do
subject.quoteit('foo').should == 'foo'
end
it "should double-quote by default for values containing spaces or special characters" do
subject.quoteit('foo bar').should == '"foo bar"'
subject.quoteit('foo&bar').should == '"foo&bar"'
subject.quoteit('foo;bar').should == '"foo;bar"'
subject.quoteit('foo<bar').should == '"foo<bar"'
subject.quoteit('foo>bar').should == '"foo>bar"'
subject.quoteit('foo(bar').should == '"foo(bar"'
subject.quoteit('foo)bar').should == '"foo)bar"'
subject.quoteit('foo|bar').should == '"foo|bar"'
end
it "should call #readquote and use its value when oldvalue is passed" do
subject.quoteit('foo', nil, "'bar'").should == "'foo'"
subject.quoteit('foo', nil, '"bar"').should == '"foo"'
subject.quoteit('foo', nil, 'bar').should == 'foo'
subject.quoteit('foo bar', nil, "'bar'").should == "'foo bar'"
end
it "should double-quote special values when oldvalue is not quoted" do
subject.quoteit('foo bar', nil, 'bar').should == '"foo bar"'
end
it "should use the :quoted parameter when present" do
resource = { }
resource.stubs(:parameters).returns([:quoted])
resource[:quoted] = :single
subject.quoteit('foo', resource).should == "'foo'"
resource[:quoted] = :double
subject.quoteit('foo', resource).should == '"foo"'
resource[:quoted] = :auto
subject.quoteit('foo', resource).should == 'foo'
subject.quoteit('foo bar', resource).should == '"foo bar"'
end
end
describe "#unquoteit" do
it "should not do anything when value is not quoted" do
subject.unquoteit('foo bar').should == 'foo bar'
end
it "should not do anything when value is badly quoted" do
subject.unquoteit('"foo bar').should == '"foo bar'
subject.unquoteit("'foo bar").should == "'foo bar"
subject.unquoteit("'foo bar\"").should == "'foo bar\""
end
it "should return unquoted value" do
subject.unquoteit('"foo bar"').should == 'foo bar'
subject.unquoteit("'foo bar'").should == 'foo bar'
end
end
describe "#parsed_as?" do
context "when text_store is supported" do
it "should return false when text_store fails" do
Augeas.any_instance.expects(:respond_to?).with(:text_store).returns(true)
Augeas.any_instance.expects(:set).with('/input', 'foo').returns(nil)
Augeas.any_instance.expects(:text_store).with('Baz.lns', '/input', '/parsed').returns(false)
subject.parsed_as?('foo', 'bar', 'Baz.lns').should == false
end
it "should return false when path is not found" do
Augeas.any_instance.expects(:respond_to?).with(:text_store).returns(true)
Augeas.any_instance.expects(:set).with('/input', 'foo').returns(nil)
Augeas.any_instance.expects(:text_store).with('Baz.lns', '/input', '/parsed').returns(true)
Augeas.any_instance.expects(:match).with('/parsed/bar').returns([])
subject.parsed_as?('foo', 'bar', 'Baz.lns').should == false
end
it "should return true when path is found" do
Augeas.any_instance.expects(:respond_to?).with(:text_store).returns(true)
Augeas.any_instance.expects(:set).with('/input', 'foo').returns(nil)
Augeas.any_instance.expects(:text_store).with('Baz.lns', '/input', '/parsed').returns(true)
Augeas.any_instance.expects(:match).with('/parsed/bar').returns(['/parsed/bar'])
subject.parsed_as?('foo', 'bar', 'Baz.lns').should == true
end
end
context "when text_store is not supported" do
it "should return true if path is found in tempfile" do
Augeas.any_instance.expects(:respond_to?).with(:text_store).returns(false)
Augeas.any_instance.expects(:text_store).never
Augeas.any_instance.expects(:match).returns(['/files/tmp/aug_text_store20140410-8734-icc4xn/bar'])
subject.parsed_as?('foo', 'bar', 'Baz.lns').should == true
end
end
end
describe "#attr_aug_reader" do
it "should create a class method" do
subject.attr_aug_reader(:foo, {})
subject.method_defined?('attr_aug_reader_foo').should be_true
end
end
describe "#attr_aug_writer" do
it "should create a class method" do
subject.attr_aug_writer(:foo, {})
subject.method_defined?('attr_aug_writer_foo').should be_true
end
end
describe "#attr_aug_accessor" do
it "should call #attr_aug_reader and #attr_aug_writer" do
name = :foo
opts = { :bar => 'baz' }
subject.expects(:attr_aug_reader).with(name, opts)
subject.expects(:attr_aug_writer).with(name, opts)
subject.attr_aug_accessor(name, opts)
end
end
end
context "working provider" do
class Test
include AugeasProviders::Provider
lens { 'Hosts.lns' }
default_file { '/foo' }
resource_path { |r, p| r[:test] }
attr_accessor :resource
end
subject { Test }
let(:tmptarget) { aug_fixture("full") }
let(:thetarget) { tmptarget.path }
let(:resource) { {:target => thetarget} }
# Class methods
describe "#lens" do
it "should allow retrieval of the set lens" do
subject.lens.should == 'Hosts.lns'
end
end
describe "#target" do
it "should allow retrieval of the set default file" do
subject.target.should == '/foo'
end
end
describe "#resource_path" do
it "should call block to get the resource path" do
subject.resource_path(:test => 'bar').should == 'bar'
end
end
describe "#loadpath" do
it "should return AugeasProviders::Provider.loadpath" do
subject.send(:loadpath).should == AugeasProviders::Provider.loadpath
end
it "should add libdir/augeas/lenses/ to the loadpath if it exists" do
plugindir = File.join(Puppet[:libdir], 'augeas', 'lenses')
File.expects(:exists?).with(plugindir).returns(true)
subject.send(:loadpath).should == "#{AugeasProviders::Provider.loadpath}:#{plugindir}"
end
end
describe "#augopen" do
before do
subject.expects(:augsave!).never
end
context "on Puppet < 3.4.0" do
before :each do
subject.stubs(:supported?).with(:post_resource_eval).returns(false)
end
it "should call Augeas#close when given a block" do
subject.augopen(resource) do |aug|
aug.expects(:close)
end
end
it "should not call Augeas#close when not given a block" do
Augeas.any_instance.expects(:close).never
aug = subject.augopen(resource)
end
end
context "on Puppet >= 3.4.0" do
before :each do
subject.stubs(:supported?).with(:post_resource_eval).returns(true)
end
it "should not call Augeas#close when given a block" do
Augeas.any_instance.expects(:close).never
aug = subject.augopen(resource)
end
it "should not call Augeas#close when not given a block" do
Augeas.any_instance.expects(:close).never
aug = subject.augopen(resource)
end
it "should call Augeas#close when calling post_resource_eval" do
subject.augopen(resource) do |aug|
aug.expects(:close)
subject.post_resource_eval
end
end
end
it "should call #setvars when given a block" do
subject.expects(:setvars)
subject.augopen(resource) { |aug| }
end
it "should not call #setvars when not given a block" do
subject.expects(:setvars).never
aug = subject.augopen(resource)
end
context "with broken file" do
let(:tmptarget) { aug_fixture("broken") }
it "should fail if the file fails to load" do
subject.expects(:fail).with(regexp_matches(/Augeas didn't load #{Regexp.escape(thetarget)} with Hosts.lns from .*: Iterated lens matched less than it should/)).raises
expect { subject.augopen(resource) {} }.to raise_error
end
end
end
describe "#augopen!" do
context "on Puppet < 3.4.0" do
before :each do
subject.stubs(:supported?).with(:post_resource_eval).returns(false)
end
it "should call Augeas#close when given a block" do
subject.augopen!(resource) do |aug|
aug.expects(:close)
end
end
it "should not call Augeas#close when not given a block" do
Augeas.any_instance.expects(:close).never
aug = subject.augopen!(resource)
end
end
context "on Puppet >= 3.4.0" do
before :each do
subject.stubs(:supported?).with(:post_resource_eval).returns(true)
end
it "should not call Augeas#close when given a block" do
Augeas.any_instance.expects(:close).never
aug = subject.augopen!(resource)
end
it "should not call Augeas#close when not given a block" do
Augeas.any_instance.expects(:close).never
aug = subject.augopen!(resource)
end
end
it "should call #setvars when given a block" do
subject.expects(:setvars)
subject.augopen!(resource) { |aug| }
end
it "should not call #setvars when not given a block" do
subject.expects(:setvars).never
aug = subject.augopen!(resource)
end
context "on Puppet < 3.4.0" do
before :each do
subject.stubs(:supported?).with(:post_resource_eval).returns(false)
end
it "should call #augsave when given a block" do
subject.expects(:augsave!)
subject.augopen!(resource) { |aug| }
end
it "should not call #augsave when not given a block" do
subject.expects(:augsave!).never
aug = subject.augopen!(resource)
end
end
context "on Puppet >= 3.4.0" do
before :each do
subject.stubs(:supported?).with(:post_resource_eval).returns(true)
end
it "should not call #augsave when given a block" do
subject.expects(:augsave!).never
subject.augopen!(resource) { |aug| }
end
it "should not call #augsave when not given a block" do
subject.expects(:augsave!).never
aug = subject.augopen!(resource)
end
it "should call Augeas#close when calling post_resource_eval" do
subject.augopen(resource) do |aug|
aug.expects(:close)
subject.post_resource_eval
end
end
end
context "with broken file" do
let(:tmptarget) { aug_fixture("broken") }
it "should fail if the file fails to load" do
subject.expects(:fail).with(regexp_matches(/Augeas didn't load #{Regexp.escape(thetarget)} with Hosts.lns from .*: Iterated lens matched less than it should/)).raises
expect { subject.augopen!(resource) {} }.to raise_error
end
end
context "when raising an exception in the block" do
it "should to raise the right exception" do
expect {
subject.augopen! do |aug|
raise Puppet::Error, "My error"
end
}.to raise_error Puppet::Error, "My error"
end
end
end
describe "#augsave" do
it "should print /augeas//error on save" do
subject.augopen(resource) do |aug|
# Prepare an invalid save
subject.stubs(:debug)
aug.rm("/files#{thetarget}/*/ipaddr").should_not == 0
lambda { subject.augsave!(aug) }.should raise_error Augeas::Error, /Failed to save Augeas tree/
end
end
end
describe "#path_label" do
it "should use Augeas#label when available" do
subject.augopen(resource) do |aug|
aug.expects(:respond_to?).with(:label).returns true
aug.expects(:label).with('/files/foo[2]').returns 'foo'
subject.path_label(aug, '/files/foo[2]').should == 'foo'
end
end
it "should emulate Augeas#label when it is not available" do
subject.augopen(resource) do |aug|
aug.expects(:respond_to?).with(:label).returns false
aug.expects(:label).with('/files/bar[4]').never
subject.path_label(aug, '/files/bar[4]').should == 'bar'
end
end
it "should emulate Augeas#label when no label is found in the tree" do
subject.augopen(resource) do |aug|
aug.expects(:respond_to?).with(:label).returns true
aug.expects(:label).with('/files/baz[15]').returns nil
subject.path_label(aug, '/files/baz[15]').should == 'baz'
end
end
end
describe "#setvars" do
it "should call Augeas#defnode to set $target, Augeas#defvar to set $resource and Augeas#set to set /augeas/context when resource is passed" do
subject.augopen(resource) do |aug|
aug.expects(:set).with('/augeas/context', "/files#{thetarget}")
aug.expects(:defnode).with('target', "/files#{thetarget}", nil)
subject.expects(:resource_path).with(resource).returns('/files/foo')
aug.expects(:defvar).with('resource', '/files/foo')
subject.setvars(aug, resource)
end
end
it "should call Augeas#defnode to set $target but not $resource when no resource is passed" do
subject.augopen(resource) do |aug|
aug.expects(:defnode).with('target', '/files/foo', nil)
aug.expects(:defvar).never
subject.setvars(aug)
end
end
end
describe "#attr_aug_reader" do
it "should create a class method using :string" do
subject.attr_aug_reader(:foo, {})
subject.method_defined?('attr_aug_reader_foo').should be_true
Augeas.any_instance.expects(:get).with('$resource/foo').returns('bar')
subject.augopen(resource) do |aug|
subject.attr_aug_reader_foo(aug).should == 'bar'
end
end
it "should create a class method using :array and no sublabel" do
subject.attr_aug_reader(:foo, { :type => :array })
subject.method_defined?('attr_aug_reader_foo').should be_true
rpath = "/files#{thetarget}/test/foo"
subject.augopen(resource) do |aug|
aug.expects(:match).with('$resource/foo').returns(["#{rpath}[1]", "#{rpath}[2]"])
aug.expects(:get).with("#{rpath}[1]").returns('baz')
aug.expects(:get).with("#{rpath}[2]").returns('bazz')
subject.attr_aug_reader_foo(aug).should == ['baz', 'bazz']
end
end
it "should create a class method using :array and a :seq sublabel" do
subject.attr_aug_reader(:foo, { :type => :array, :sublabel => :seq })
subject.method_defined?('attr_aug_reader_foo').should be_true
rpath = "/files#{thetarget}/test/foo"
subject.augopen(resource) do |aug|
aug.expects(:match).with('$resource/foo').returns(["#{rpath}[1]", "#{rpath}[2]"])
aug.expects(:match).with("#{rpath}[1]/*[label()=~regexp('[0-9]+')]").returns(["#{rpath}[1]/1"])
aug.expects(:get).with("#{rpath}[1]/1").returns('val11')
aug.expects(:match).with("#{rpath}[2]/*[label()=~regexp('[0-9]+')]").returns(["#{rpath}[2]/1", "#{rpath}[2]/2"])
aug.expects(:get).with("#{rpath}[2]/1").returns('val21')
aug.expects(:get).with("#{rpath}[2]/2").returns('val22')
subject.attr_aug_reader_foo(aug).should == ['val11', 'val21', 'val22']
end
end
it "should create a class method using :array and a string sublabel" do
subject.attr_aug_reader(:foo, { :type => :array, :sublabel => 'sl' })
subject.method_defined?('attr_aug_reader_foo').should be_true
rpath = "/files#{thetarget}/test/foo"
subject.augopen(resource) do |aug|
aug.expects(:match).with('$resource/foo').returns(["#{rpath}[1]", "#{rpath}[2]"])
aug.expects(:match).with("#{rpath}[1]/sl").returns(["#{rpath}[1]/sl"])
aug.expects(:get).with("#{rpath}[1]/sl").returns('val11')
aug.expects(:match).with("#{rpath}[2]/sl").returns(["#{rpath}[2]/sl[1]", "#{rpath}[2]/sl[2]"])
aug.expects(:get).with("#{rpath}[2]/sl[1]").returns('val21')
aug.expects(:get).with("#{rpath}[2]/sl[2]").returns('val22')
subject.attr_aug_reader_foo(aug).should == ['val11', 'val21', 'val22']
end
end
it "should create a class method using :hash and no sublabel" do
expect {
subject.attr_aug_reader(:foo, { :type => :hash, :default => 'deflt' })
}.to raise_error(RuntimeError, /You must provide a sublabel/)
end
it "should create a class method using :hash and sublabel" do
subject.attr_aug_reader(:foo, { :type => :hash, :sublabel => 'sl', :default => 'deflt' })
subject.method_defined?('attr_aug_reader_foo').should be_true
rpath = "/files#{thetarget}/test/foo"
subject.augopen(resource) do |aug|
aug.expects(:match).with('$resource/foo').returns(["#{rpath}[1]", "#{rpath}[2]"])
aug.expects(:get).with("#{rpath}[1]").returns('baz')
aug.expects(:get).with("#{rpath}[1]/sl").returns('bazval')
aug.expects(:get).with("#{rpath}[2]").returns('bazz')
aug.expects(:get).with("#{rpath}[2]/sl").returns(nil)
subject.attr_aug_reader_foo(aug).should == { 'baz' => 'bazval', 'bazz' => 'deflt' }
end
end
it "should create a class method using wrong type" do
expect {
subject.attr_aug_reader(:foo, { :type => :foo })
}.to raise_error(RuntimeError, /Invalid type: foo/)
end
end
describe "#attr_aug_writer" do
it "should create a class method using :string" do
subject.attr_aug_writer(:foo, {})
subject.method_defined?('attr_aug_writer_foo').should be_true
subject.augopen(resource) do |aug|
aug.expects(:set).with('$resource/foo', 'bar')
subject.attr_aug_writer_foo(aug, 'bar')
aug.expects(:clear).with('$resource/foo')
subject.attr_aug_writer_foo(aug)
end
end
it "should create a class method using :string with :rm_node" do
subject.attr_aug_writer(:foo, { :rm_node => true })
subject.method_defined?('attr_aug_writer_foo').should be_true
subject.augopen(resource) do |aug|
aug.expects(:set).with('$resource/foo', 'bar')
subject.attr_aug_writer_foo(aug, 'bar')
aug.expects(:rm).with('$resource/foo')
subject.attr_aug_writer_foo(aug)
end
end
it "should create a class method using :array and no sublabel" do
subject.attr_aug_writer(:foo, { :type => :array })
subject.method_defined?('attr_aug_writer_foo').should be_true
subject.augopen(resource) do |aug|
aug.expects(:rm).with('$resource/foo')
aug.expects(:set).with('$resource/foo[1]', 'bar')
subject.attr_aug_writer_foo(aug)
aug.expects(:rm).with('$resource/foo')
aug.expects(:set).with('$resource/foo[2]', 'baz')
subject.attr_aug_writer_foo(aug, ['bar', 'baz'])
end
end
it "should create a class method using :array and a :seq sublabel" do
subject.attr_aug_writer(:foo, { :type => :array, :sublabel => :seq })
subject.method_defined?('attr_aug_writer_foo').should be_true
subject.augopen(resource) do |aug|
aug.expects(:rm).with('$resource/foo')
subject.attr_aug_writer_foo(aug)
aug.expects(:rm).with("$resource/foo/*[label()=~regexp('[0-9]+')]")
aug.expects(:set).with('$resource/foo/1', 'bar')
aug.expects(:set).with('$resource/foo/2', 'baz')
subject.attr_aug_writer_foo(aug, ['bar', 'baz'])
end
end
it "should create a class method using :array and a string sublabel" do
subject.attr_aug_writer(:foo, { :type => :array, :sublabel => 'sl' })
subject.method_defined?('attr_aug_writer_foo').should be_true
subject.augopen(resource) do |aug|
aug.expects(:rm).with('$resource/foo')
subject.attr_aug_writer_foo(aug)
aug.expects(:rm).with('$resource/foo/sl')
aug.expects(:set).with('$resource/foo/sl[1]', 'bar')
aug.expects(:set).with('$resource/foo/sl[2]', 'baz')
subject.attr_aug_writer_foo(aug, ['bar', 'baz'])
end
end
it "should create a class method using :hash and no sublabel" do
expect {
subject.attr_aug_writer(:foo, { :type => :hash, :default => 'deflt' })
}.to raise_error(RuntimeError, /You must provide a sublabel/)
end
it "should create a class method using :hash and sublabel" do
subject.attr_aug_writer(:foo, { :type => :hash, :sublabel => 'sl', :default => 'deflt' })
subject.method_defined?('attr_aug_writer_foo').should be_true
rpath = "/files#{thetarget}/test/foo"
subject.augopen(resource) do |aug|
aug.expects(:rm).with('$resource/foo')
aug.expects(:set).with("$resource/foo[.='baz']", 'baz')
aug.expects(:set).with("$resource/foo[.='baz']/sl", 'bazval')
aug.expects(:set).with("$resource/foo[.='bazz']", 'bazz')
aug.expects(:set).with("$resource/foo[.='bazz']/sl", 'bazzval').never
subject.attr_aug_writer_foo(aug, { 'baz' => 'bazval', 'bazz' => 'deflt' })
end
end
it "should create a class method using wrong type" do
expect {
subject.attr_aug_writer(:foo, { :type => :foo })
}.to raise_error(RuntimeError, /Invalid type: foo/)
end
end
end
end
| 37.678072 | 176 | 0.603748 |
798f7b0ac816ce3f489d44bd9fb1b85c5def08d0 | 1,715 | require "rubygems"
require "rails"
require "rails/test_help"
require "active_support/core_ext"
require "set_builder"
require "shoulda/context"
require "pry"
require "support/fake_connection"
require "timecop"
require "minitest/reporters"
Minitest::Reporters.use! Minitest::Reporters::SpecReporter.new
# Sample class used by tests
SetBuilder::ValueMap.register(:school, [[1, "Concordia"], [2, "McKendree"]])
friends = Arel::Table.new(:friends)
$friend_traits = SetBuilder::Traits.new do
trait('who [are|are not] "awesome"') do |query, scope|
scope << {:conditions => {:awesome => true}}
end
trait('who [have|have not] "died"') do |query, scope|
scope << {:conditions => {:alive => false}}
end
trait('who were "born" <date>') do |query, scope|
scope << {:conditions => query.modifiers[0].build_arel_for(friends[:birthday]).to_sql}
end
trait('whose "age" <number>') do |query, scope|
scope << {:conditions => query.modifiers[0].build_arel_for(friends[:age]).to_sql}
end
trait('who [have|have not] "attended" :school') do |query, scope|
scope << {
:joins => "INNER JOIN schools ON friends.school_id=schools.id",
:conditions => {"schools.id" => query.direct_object}
}
end
trait('whose "name" <string>') do |query, scope|
scope << {:conditions => query.modifiers[0].build_arel_for(friends[:name]).to_sql}
end
end
class Friend
# by stubbing out `all`, we can unit test `Set#perform`
def self.all
[]
end
# Stubs so that Arel can SQL
class << self
attr_accessor :connection_pool
def connection
connection_pool.connection
end
end
@connection_pool = Fake::ConnectionPool.new
end
Arel::Table.engine = Friend
| 23.819444 | 90 | 0.678134 |
1cfa0f7e4f3092e0306b701e5562bcd26b431258 | 303 | module EnglishWords
def hello
return "hello"
end
def world
return "world"
end
end
class Greeting
include EnglishWords
def message
return hello
end
end
class HelloWorld < Greeting
def message
return super + " " + world + "!"
end
end | 13.772727 | 40 | 0.590759 |
ffdd1991dd17dcdc272ea4eb1ea3e5c764e6a8cb | 262 | require_relative '../../automated_init'
context "Data Source" do
context "Hash" do
hash_source = Controls::DataSource::Hash.example
data = hash_source.get_data
test "Converts the data to a Hash" do
assert(data.is_a? Hash)
end
end
end
| 20.153846 | 52 | 0.687023 |
7957c326c5713539b23c75ba271a62e7381b83b6 | 469 | require 'spec_helper'
describe 'roles::logging' do
on_os_under_test.each do |os, facts|
context "on #{os}" do
let(:facts) { facts }
context 'with defaults for all parameters' do
it { is_expected.to contain_class('roles::logging') }
it { is_expected.to contain_class('roles::node') }
it { is_expected.to contain_anchor('logging::begin') }
it { is_expected.to contain_anchor('logging::end') }
end
end
end
end
| 31.266667 | 62 | 0.641791 |
1db033348e76eaefaaa0d6a42b4142dc7833b563 | 3,993 | # ****************************************************************************
#
# Copyright (c) Microsoft Corporation.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of this distribution. If
# you cannot locate the Apache License, Version 2.0, please send an email to
# [email protected]. By using this source code in any fashion, you are agreeing to be bound
# by the terms of the Apache License, Version 2.0.
#
# You must not remove this notice, or any other, from this software.
#
#
# ****************************************************************************
require "stringio"
$: << File.dirname(__FILE__) + "/app"
require "tutorial"
class ConsoleTutorial
attr :tutorial
def initialize(tutorial = nil, inp = $stdin, out = $stdout)
@in = inp
@out = out
@tutorial = tutorial || Tutorial.get_tutorial
@context = Tutorial::ReplContext.new
end
def run_chapter chapter
@out.puts "---------------------"
@out.puts "Starting #{chapter.name}"
@out.print chapter.introduction
prompt = ">>> "
chapter.tasks.each do |task|
@out.puts task.description
next if not task.should_run? @context.bind
task.setup.call(@context.bind) if task.setup
@out.puts "Enter the following code:"
@out.puts task.code_string
begin
@out.print prompt
if @in.eof? then raise "No more input... (Task description: #{task.description}\nTask code: #{task.code_string})" end
input = @in.gets
result = @context.interact input
@out.puts result.output if not result.output.empty?
if result.partial_input?
prompt = "... "
next
elsif result.error
@out.puts result.error.to_s
else
@out.puts "=> #{result.result.inspect}"
end
prompt = ">>> "
end until task.success?(result)
end
@out.puts "Chapter completed successfully!"
@out.puts
end
def run_section section
@out.puts "======================"
@out.puts "Starting #{section.name}"
@out.puts section.introduction
loop do
section.chapters.each_index { |i| @out.puts "#{i + 1}: #{section.chapters[i].name}" }
@out.print "Select a chapter number and press enter (0 to return to previous menu):"
input = @in.gets
break if input == nil or input.chomp == "0" or input.chomp == ""
chapter = section.chapters[input.to_i - 1]
run_chapter chapter
end
@out.puts
end
def run
@out.puts "Welcome to #{@tutorial.name}"
@out.puts @tutorial.introduction
loop do
@tutorial.sections.each_index { |i| @out.puts "#{i + 1}: #{@tutorial.sections[i].name}" }
@out.print "Select a section number and press enter (0 to return to previous menu):"
input = @in.gets
break if input == nil or input.chomp == "0" or input.chomp == ""
section = @tutorial.sections[input.to_i - 1]
run_section section
end
@out.puts "Bye!"
end
end
if $0 == __FILE__
if ARGV.size > 0
tut = Tutorial.get_tutorial(ARGV[0])
ConsoleTutorial.new(tut).run
else
tuts = Tutorial.all.values
_in = $stdin
_out = $stdout
loop do
tuts.each_index { |i| _out.puts "#{i + 1}: #{tuts[i].name}" }
_out.print "Select a tutorial number and press enter (0 to exit): "
input = _in.gets
break if input.nil? or input.chomp == '0' or input.chomp == ''
tut = tuts[input.to_i - 1]
_out.puts
ConsoleTutorial.new(tut).run
end
end
end
| 35.651786 | 133 | 0.541197 |
5d389bd2d5d057bb65e0bfe3a4d56bd3d7c03aae | 1,171 | # WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
require 'aws-sdk-core'
require 'aws-sigv4'
require_relative 'aws-sdk-codestar/types'
require_relative 'aws-sdk-codestar/client_api'
require_relative 'aws-sdk-codestar/client'
require_relative 'aws-sdk-codestar/errors'
require_relative 'aws-sdk-codestar/resource'
require_relative 'aws-sdk-codestar/customizations'
# This module provides support for AWS CodeStar. This module is available in the
# `aws-sdk-codestar` gem.
#
# # Client
#
# The {Client} class provides one method for each API operation. Operation
# methods each accept a hash of request parameters and return a response
# structure.
#
# See {Client} for more information.
#
# # Errors
#
# Errors returned from AWS CodeStar all
# extend {Errors::ServiceError}.
#
# begin
# # do stuff
# rescue Aws::CodeStar::Errors::ServiceError
# # rescues all service API errors
# end
#
# See {Errors} for more information.
#
# @service
module Aws::CodeStar
GEM_VERSION = '1.16.0'
end
| 24.395833 | 80 | 0.743809 |
4ab734474a78c4cb02a55e0e25c5670f4568cb50 | 244 | module Job
module Mail
class CommentOnPost < Base
@queue = :mail
def self.perform(recipient_id, sender_id, comment_id)
Notifier.comment_on_post(recipient_id, sender_id, comment_id).deliver
end
end
end
end
| 20.333333 | 77 | 0.688525 |
1a2bba519d7e7aacb38556a316f631122366a9b9 | 17,308 | # encoding: utf-8
#
# Jekyll categories pages generator
# http://www.ekynoxe.com/
# Version: 0.0.1 (2014-01-25)
#
# Copyright (c) 2014 Mathieu Davy - ekynoxe - http://ekynoxe.com/
# Licensed under the MIT license
# (http://www.opensource.org/licenses/mit-license.php)
#
# Initially based on https://github.com/mwotton/lambdamechanic-jekyll and
# modified to suit a different site and categories architecture
#
#
# This plugin generates pages for each of the categories of your site, as
# defined in their YAML front matter.
# If enabled through configuration, it will also generate the appropriate pagination
#
# To enable category pages generation, add the following in your _config.yml
#
# category_path: "categories/:cat"
#
# If you want to customise the numbered page name, you can use the following:
# Default is "page:num"
#
# category_page_path: "page:num"
#
# Customise those to suit your needs, but you need to keep the placeholders
# as they are: ":cat" ad ":num"
#
# To enable pagination and define the number of posts per page, use:
#
# paginate_categories: 4
#
# This plugin uses the standard Jekyll paginator, so you can also print
# pagination links by simply add the following in your
# category_index.html template:
#
#
# {% if paginator.total_pages > 1 %}
# <nav class="pagination">
# {% if paginator.previous_page_path %}
# <a class="button previous" href="{{ paginator.previous_page_path }}" title="Previous posts">previous </a>
# {% endif %}
# {% if paginator.next_page_path %}
# <a class="button next" href="{{ paginator.next_page_path }}" title="Next posts"> next</a>
# {% endif %}
# </nav>
# {% endif %}
module Jekyll
class CategoryPagesGenerator < Generator
safe true
# Generate category pages, paginated if necessary
#
# site - the Jekyll::Site object
def generate(site)
if enabled?(site)
site.categories.each do |category, posts|
paginate(site, category, posts)
end
end
end
# Paginates each category's posts. Renders the index.html file into paginated
# directories, ie: page2/index.html, page3/index.html, etc and adds more
# site-wide data.
#
# site - the Jekyll::Site object
# category - the String category currently being processed
# posts - an array of that category's posts
#
# {"paginator" => { "page" => <Number>,
# "per_page" => <Number>,
# "posts" => [<Post>],
# "total_posts" => <Number>,
# "total_pages" => <Number>,
# "previous_page" => <Number>,
# "previous_page_path" => <Url>,
# "next_page" => <Number>,
# "next_page_path" => <Url> }}
def paginate(site, category, posts)
all_posts = posts.sort_by { |p| p.date }
all_posts.reverse!
if CategoryPager.pagination_enabled?(site)
pages = CategoryPager.calculate_pages(all_posts, site.config['paginate_categories'].to_i)
else
pages = 1
end
(1..pages).each do |num_page|
pager = CategoryPager.new(site, num_page, all_posts, category, pages)
page = CategoryPage.new(site, site.source, "_layouts", category)
page.dir = CategoryPager.paginate_path(site, num_page, category)
page.pager = pager
site.pages << page
end
end
# Determine if category pages generation is enabled
#
# site - the Jekyll::Site object
#
# Returns true if the category_path config value is set
# and if there are cateories, false otherwise.
def enabled?(site)
!site.config['category_path'].nil? &&
site.categories.size > 0
end
end
class CategoryPage < Page
# Initializes a new CategoryPage.
#
# site - the Jekyll::Site object
# base - the String path to the <source>
# category_dir - the String path between <source> and the category folder
# category - the String category currently being processed
def initialize(site, base, category_dir, category)
@site = site
@base = base
@dir = category_dir
@name = 'index.html'
self.process(@name)
self.read_yaml(File.join(base, '_layouts'), 'category_index.html')
self.data['title'] = "#{category}"
end
end
class CategoryPager
attr_reader :page, :per_page, :posts, :total_posts, :total_pages,
:previous_page, :previous_page_path, :next_page_path, :next_page, :category
# Calculate the number of pages.
#
# all_posts - the Array of all Posts.
# per_page - the Integer of entries per page.
#
# Returns the Integer number of pages.
def self.calculate_pages(all_posts, per_page)
(all_posts.size.to_f / per_page.to_i).ceil
end
def self.removeDiacritics (str)
$defaultDiacriticsRemovalMap.each_with_index do |val, index|
str = str.gsub(val['letters'], val['base'])
end
return str
end
def self.getCategorySlug (headline)
headline = removeDiacritics(headline);
headline = headline.downcase
headline = headline.gsub(/,/, '')
headline = headline.gsub(/'/, '')
headline = headline.gsub(/&/, ' and ')
headline = headline.gsub(/%/, ' percent ')
# invalid chars, make into spaces
headline = headline.gsub(/[^a-z0-9\s-]/, ' ')
# convert multiple spaces/hyphens into one space
headline = headline.gsub(/[\s-]+/, ' ').strip
# hyphens
headline = headline.gsub(/\s/, '-')
return headline;
end
# Determine if category pagination is enabled
#
# site - the Jekyll::Site object
#
# Returns true if pagination is enabled and if there are
# cateories, false otherwise.
def self.pagination_enabled?(site)
!site.config['paginate_categories'].nil? &&
site.categories.size > 0
end
# Static: Return the pagination path of the page
#
# site - the Jekyll::Site object
# num_page - the Integer number of pages in the pagination
# category - the String category currently being processed
#
# Returns the pagination path as a string
def self.paginate_path(site, num_page, category)
return nil if num_page.nil?
format = site.config['category_path'].sub(':cat', getCategorySlug(category))
pagePath = site.config['category_page_path'] ? site.config['category_page_path'] : "page:num"
if num_page > 1
format = File.join(format, pagePath)
format = format.sub(':num', num_page.to_s)
end
ensure_leading_slash(format)
end
# Static: Return a String version of the input which has a leading slash.
# If the input already has a forward slash in position zero, it will be
# returned unchanged.
#
# path - a String path
#
# Returns the path with a leading slash
def self.ensure_leading_slash(path)
path[0..0] == "/" ? path : "/#{path}"
end
# Initialize a new Pager.
#
# site - the Jekyll::Site object
# page - the Integer page number.
# all_posts - the Array of all the site's Posts.
# category - the category currently being processed. As a String
# num_pages - the Integer number of pages or nil if you'd like the number
# of pages calculated.
def initialize(site, page, all_posts, category, num_pages = nil)
@category = category
@page = page
@per_page = site.config['paginate_categories'].to_i
@total_pages = num_pages || Pager.calculate_pages(all_posts, @per_page)
if @page > @total_pages
raise RuntimeError, "page number can't be greater than total pages: #{@page} > #{@total_pages}"
end
init = (@page - 1) * @per_page
offset = (init + @per_page - 1) >= all_posts.size ? all_posts.size : (init + @per_page - 1)
@total_posts = all_posts.size
@posts = all_posts[init..offset]
@previous_page = @page != 1 ? @page - 1 : nil
@previous_page_path = CategoryPager.paginate_path(site, @previous_page, category)
@next_page = @page != @total_pages ? @page + 1 : nil
@next_page_path = CategoryPager.paginate_path(site, @next_page, category)
end
# Convert this Pager's data to a Hash suitable for use by Liquid.
#
# Returns the Hash representation of this Pager.
def to_liquid
{
'page' => page,
'per_page' => per_page,
'posts' => posts,
'total_posts' => total_posts,
'total_pages' => total_pages,
'previous_page' => previous_page,
'previous_page_path' => previous_page_path,
'next_page' => next_page,
'next_page_path' => next_page_path,
'category' => category
}
end
end
end
$defaultDiacriticsRemovalMap = [
{'base' => 'A', 'letters' => /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/},
{'base' => 'AA','letters' => /[\uA732]/},
{'base' => 'AE','letters' => /[\u00C6\u01FC\u01E2]/},
{'base' => 'AO','letters' => /[\uA734]/},
{'base' => 'AU','letters' => /[\uA736]/},
{'base' => 'AV','letters' => /[\uA738\uA73A]/},
{'base' => 'AY','letters' => /[\uA73C]/},
{'base' => 'B', 'letters' => /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/},
{'base' => 'C', 'letters' => /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/},
{'base' => 'D', 'letters' => /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/},
{'base' => 'DZ','letters' => /[\u01F1\u01C4]/},
{'base' => 'Dz','letters' => /[\u01F2\u01C5]/},
{'base' => 'E', 'letters' => /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/},
{'base' => 'F', 'letters' => /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/},
{'base' => 'G', 'letters' => /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/},
{'base' => 'H', 'letters' => /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/},
{'base' => 'I', 'letters' => /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/},
{'base' => 'J', 'letters' => /[\u004A\u24BF\uFF2A\u0134\u0248]/},
{'base' => 'K', 'letters' => /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/},
{'base' => 'L', 'letters' => /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/},
{'base' => 'LJ','letters' => /[\u01C7]/},
{'base' => 'Lj','letters' => /[\u01C8]/},
{'base' => 'M', 'letters' => /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/},
{'base' => 'N', 'letters' => /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/},
{'base' => 'NJ','letters' => /[\u01CA]/},
{'base' => 'Nj','letters' => /[\u01CB]/},
{'base' => 'O', 'letters' => /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/},
{'base' => 'OI','letters' => /[\u01A2]/},
{'base' => 'OO','letters' => /[\uA74E]/},
{'base' => 'OU','letters' => /[\u0222]/},
{'base' => 'P', 'letters' => /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/},
{'base' => 'Q', 'letters' => /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/},
{'base' => 'R', 'letters' => /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/},
{'base' => 'S', 'letters' => /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/},
{'base' => 'T', 'letters' => /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/},
{'base' => 'TZ','letters' => /[\uA728]/},
{'base' => 'U', 'letters' => /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/},
{'base' => 'V', 'letters' => /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/},
{'base' => 'VY','letters' => /[\uA760]/},
{'base' => 'W', 'letters' => /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/},
{'base' => 'X', 'letters' => /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/},
{'base' => 'Y', 'letters' => /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/},
{'base' => 'Z', 'letters' => /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/},
{'base' => 'a', 'letters' => /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/},
{'base' => 'aa','letters' => /[\uA733]/},
{'base' => 'ae','letters' => /[\u00E6\u01FD\u01E3]/},
{'base' => 'ao','letters' => /[\uA735]/},
{'base' => 'au','letters' => /[\uA737]/},
{'base' => 'av','letters' => /[\uA739\uA73B]/},
{'base' => 'ay','letters' => /[\uA73D]/},
{'base' => 'b', 'letters' => /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/},
{'base' => 'c', 'letters' => /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/},
{'base' => 'd', 'letters' => /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/},
{'base' => 'dz','letters' => /[\u01F3\u01C6]/},
{'base' => 'e', 'letters' => /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/},
{'base' => 'f', 'letters' => /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/},
{'base' => 'g', 'letters' => /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/},
{'base' => 'h', 'letters' => /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/},
{'base' => 'hv','letters' => /[\u0195]/},
{'base' => 'i', 'letters' => /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/},
{'base' => 'j', 'letters' => /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/},
{'base' => 'k', 'letters' => /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/},
{'base' => 'l', 'letters' => /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/},
{'base' => 'lj','letters' => /[\u01C9]/},
{'base' => 'm', 'letters' => /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/},
{'base' => 'n', 'letters' => /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/},
{'base' => 'nj','letters' => /[\u01CC]/},
{'base' => 'o', 'letters' => /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/},
{'base' => 'oi','letters' => /[\u01A3]/},
{'base' => 'ou','letters' => /[\u0223]/},
{'base' => 'oo','letters' => /[\uA74F]/},
{'base' => 'p','letters' => /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/},
{'base' => 'q','letters' => /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/},
{'base' => 'r','letters' => /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/},
{'base' => 's','letters' => /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/},
{'base' => 't','letters' => /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/},
{'base' => 'tz','letters' => /[\uA729]/},
{'base' => 'u','letters' => /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/},
{'base' => 'v','letters' => /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/},
{'base' => 'vy','letters' => /[\uA761]/},
{'base' => 'w','letters' => /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/},
{'base' => 'x','letters' => /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/},
{'base' => 'y','letters' => /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/},
{'base' => 'z','letters' => /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/}
] | 48.481793 | 295 | 0.635544 |
1d6d58805440a771050294bae94392b484c36f8f | 2,282 | #
#--
# Copyright (c) 2007-2008, John Mettraux, OpenWFE.org
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# . Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# . Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# . Neither the name of the "OpenWFE" nor the names of its contributors may be
# used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#++
#
#
# Made in Japan
#
# [email protected]
#
class LoginController < ApplicationController
layout "login"
def index
session[:user] = nil
if request.post?
user = User.authenticate params[:name], params[:password]
if user
user.neutralize
# removes password information.
# Maybe it'd be better to just store the user id.
session[:user] = user
redirect_to :controller => "stores", :action => "index"
else
flash.now[:notice] = "Invalid user and/or password"
end
end
end
def logout
session[:user] = nil
flash[:notice] = "Logged out"
redirect_to :action => "index"
end
end
| 30.026316 | 79 | 0.716915 |
d55a2181d22c3634f2ad90ddc5d2439d7cf586fe | 2,426 | # -------------------------------------------------------------------------- #
# Copyright 2019-2020, OpenNebula Systems S.L. #
# #
# Licensed under the OpenNebula Software License #
# (the "License"); you may not use this file except in compliance with #
# the License. You may obtain a copy of the License as part of the software #
# distribution. #
# #
# See https://github.com/OpenNebula/one/blob/master/LICENSE.onsla #
# (or copy bundled with OpenNebula in /usr/share/doc/one/). #
# #
# Unless agreed to in writing, software distributed under the License is #
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #
# KIND, either express or implied. See the License for the specific language #
# governing permissions and limitations under the License. #
# -------------------------------------------------------------------------- #
require "rexml/document"
include REXML
module Migrator
def db_version
"3.0.0"
end
def one_version
"OpenNebula 3.0.0"
end
def up
# The tm_nfs driver has been renamed to tm_shared
# CREATE TABLE host_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, state INTEGER, last_mon_time INTEGER, UNIQUE(name));
@db.run "ALTER TABLE host_pool RENAME TO old_host_pool;"
@db.run "CREATE TABLE host_pool (oid INTEGER PRIMARY KEY, name VARCHAR(256), body TEXT, state INTEGER, last_mon_time INTEGER, UNIQUE(name));"
@db.run "INSERT INTO host_pool SELECT * FROM old_host_pool;"
@db.fetch("SELECT * FROM old_host_pool") do |row|
doc = Document.new(row[:body])
source = nil
doc.root.each_element("TM_MAD") { |e|
if e.text.downcase == "tm_nfs"
e.text = "tm_shared"
@db[:host_pool].filter(:oid => row[:oid]).update(
:body => doc.root.to_s)
end
}
end
@db.run "DROP TABLE old_host_pool;"
return true
end
end
| 42.561404 | 149 | 0.489695 |
333fa074ee752ed8e36f40c3c2a2c9266057c110 | 2,777 | # frozen_string_literal: true
require 'slack-ruby-client'
module PWN
module Plugins
# This plugin is used for interacting w/ Slack over the Web API.
module SlackClient
@@logger = PWN::Plugins::PWNLogger.create
# Supported Method Parameters::
# PWN::Plugins::SlackClient.login(
# api_token: 'required slack api token'
# )
public_class_method def self.login(opts = {})
api_token = opts[:api_token]
if opts[:api_token].nil?
api_token = PWN::Plugins::AuthenticationHelper.mask_password
else
api_token = opts[:api_token].to_s.scrub
end
@@logger.info('Logging into Slack...')
slack_obj = Slack::Web::Client.new
slack_obj.token = api_token
slack_obj.auth_test
slack_obj
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# PWN::Plugins::SlackClient.post_message(
# slack_obj: 'required slack_obj returned from login method',
# channel: 'required #channel to post message',
# message: 'required message to post'
# )
public_class_method def self.post_message(opts = {})
slack_obj = opts[:slack_obj]
channel = opts[:channel].to_s.scrub
message = opts[:message].to_s.scrub
slack_obj.chat_postMessage(
channel: channel,
text: message,
as_user: true
)
slack_obj
rescue StandardError => e
raise e
end
# Supported Method Parameters::
# PWN::Plugins::SlackClient.logout(
# slack_obj: 'required slack_obj returned from login method'
# )
public_class_method def self.logout(opts = {})
slack_obj = opts[:slack_obj]
@@logger.info('Logging out...')
slack_obj.token = nil
slack_obj = nil
@@logger.info('Complete.')
rescue StandardError => e
raise e
end
# Author(s):: 0day Inc. <[email protected]>
public_class_method def self.authors
"AUTHOR(S):
0day Inc. <[email protected]>
"
end
# Display Usage for this Module
public_class_method def self.help
puts "USAGE:
slack_obj = #{self}.login(
api_token: 'optional slack api token (will prompt if blank)'
)
#{self}.post_message(
slack_obj: 'required slack_obj returned from login method',
channel: 'required #channel to post message',
message: 'required message to post'
)
#{self}.logout(
slack_obj: 'required slack_obj returned from login method'
)
#{self}.authors
"
end
end
end
end
| 26.447619 | 72 | 0.589125 |
1d6cfd00c59ba09cddc343973c1eadfcb63a146f | 890 | describe ChargebackRateDetailCurrency do
it "has a valid factory" do
expect(FactoryGirl.create(:chargeback_rate_detail_currency_EUR)).to be_valid
end
it "is invalid without a code" do
expect(FactoryGirl.build(:chargeback_rate_detail_currency_EUR, :code => nil)).not_to be_valid
end
it "is invalid without a name" do
expect(FactoryGirl.build(:chargeback_rate_detail_currency_EUR, :name => nil)).not_to be_valid
end
it "is invalid without a full_name" do
expect(FactoryGirl.build(:chargeback_rate_detail_currency_EUR, :full_name => nil)).not_to be_valid
end
it "is invalid without a symbol" do
expect(FactoryGirl.build(:chargeback_rate_detail_currency_EUR, :symbol => nil)).not_to be_valid
end
it "is invalid without a unicode_hex" do
expect(FactoryGirl.build(:chargeback_rate_detail_currency_EUR, :unicode_hex => nil)).not_to be_valid
end
end
| 42.380952 | 104 | 0.775281 |
5dc09a3ca6ba72f496efb7ec20c875905ab5e223 | 2,815 | module Refinery
class PagesController < ::ApplicationController
include Pages::RenderOptions
before_action :find_page, :set_canonical
before_action :error_404, :unless => :current_user_can_view_page?
# Save whole Page after delivery
after_action :write_cache?
# This action is usually accessed with the root path, normally '/'
def home
render_with_templates?
end
# This action can be accessed normally, or as nested pages.
# Assuming a page named "mission" that is a child of "about",
# you can access the pages with the following URLs:
#
# GET /pages/about
# GET /about
#
# GET /pages/mission
# GET /about/mission
#
def show
if should_skip_to_first_child?
redirect_to refinery.url_for(first_live_child.url) and return
elsif page.link_url.present?
redirect_to page.link_url and return
elsif should_redirect_to_friendly_url?
redirect_to refinery.url_for(page.url), :status => 301 and return
end
render_with_templates?
end
protected
def requested_friendly_id
if ::Refinery::Pages.scope_slug_by_parent
# Pick out last path component, or id if present
"#{params[:path]}/#{params[:id]}".split('/').last
else
# Remove leading and trailing slashes in path, but leave internal
# ones for global slug scoping
params[:path].to_s.gsub(%r{\A/+}, '').presence || params[:id]
end
end
def should_skip_to_first_child?
page.skip_to_first_child && first_live_child
end
def should_redirect_to_friendly_url?
requested_friendly_id != page.friendly_id || (
::Refinery::Pages.scope_slug_by_parent &&
params[:path].present? && params[:path].match(page.root.slug).nil?
)
end
def current_user_can_view_page?
page.live? || authorisation_manager.allow?(:plugin, "refinery_pages")
end
def first_live_child
page.children.order('lft ASC').live.first
end
def find_page(fallback_to_404 = true)
@page ||= case action_name
when "home"
Refinery::Page.find_by(link_url: '/')
when "show"
Refinery::Page.friendly.find_by_path_or_id(params[:path], params[:id])
end
@page || (error_404 if fallback_to_404)
end
alias_method :page, :find_page
def set_canonical
@canonical = refinery.url_for @page.canonical if @page.present?
end
def write_cache?
# Don't cache the page with the site bar showing.
if Refinery::Pages.cache_pages_full && !authorisation_manager.allow?(:read, :site_bar)
cache_page(response.body, File.join('', 'refinery', 'cache', 'pages', request.path).to_s)
end
end
end
end
| 29.946809 | 97 | 0.650799 |
28a5c7855a8bb28cea732df05790bf8217488bfc | 1,018 | require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(*Rails.groups)
require "i18n_o7r"
module Dummy
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Do not swallow errors in after_commit/after_rollback callbacks.
config.active_record.raise_in_transactional_callbacks = true
end
end
| 37.703704 | 99 | 0.730845 |
626af94021818bdb1ea6d774af9b20cfcadff6e1 | 7,677 | =begin
#The Plaid API
#The Plaid REST API. Please see https://plaid.com/docs/api for more details.
The version of the OpenAPI document: 2020-09-14_1.58.1
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.1.0
=end
require 'date'
require 'time'
module Plaid
# An object representing the e-wallet transaction's counterparty
class WalletTransactionCounterparty
# The name of the counterparty
attr_accessor :name
attr_accessor :numbers
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'name' => :'name',
:'numbers' => :'numbers'
}
end
# Returns all the JSON keys this model knows about
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
def self.openapi_types
{
:'name' => :'String',
:'numbers' => :'WalletTransactionCounterpartyNumbers'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Plaid::WalletTransactionCounterparty` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Plaid::WalletTransactionCounterparty`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'name')
self.name = attributes[:'name']
end
if attributes.key?(:'numbers')
self.numbers = attributes[:'numbers']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
if @name.nil?
invalid_properties.push('invalid value for "name", name cannot be nil.')
end
if @name.to_s.length < 1
invalid_properties.push('invalid value for "name", the character length must be great than or equal to 1.')
end
if @numbers.nil?
invalid_properties.push('invalid value for "numbers", numbers cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
return false if @name.nil?
return false if @name.to_s.length < 1
return false if @numbers.nil?
true
end
# Custom attribute writer method with validation
# @param [Object] name Value to be assigned
def name=(name)
if name.nil?
fail ArgumentError, 'name cannot be nil'
end
if name.to_s.length < 1
fail ArgumentError, 'invalid value for "name", the character length must be great than or equal to 1.'
end
@name = name
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
name == o.name &&
numbers == o.numbers
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[name, numbers].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
elsif type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :Time
Time.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
# models (e.g. Pet) or oneOf
klass = Plaid.const_get(type)
klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 29.413793 | 214 | 0.624332 |
87653562997c2fc5dabe1e5813eb270848b13183 | 5,015 | Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Mount Action Cable outside main process or domain.
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment).
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "tails_on_rails_production"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
end
| 44.380531 | 114 | 0.762512 |
5db98f03d2abdea9e07fcf4c7607ce2319f22e64 | 1,946 | describe "Quickeebooks::Windows::Service::SyncActivity" do
before(:all) do
FakeWeb.allow_net_connect = false
qb_key = "key"
qb_secret = "secreet"
@realm_id = "9991111222"
@base_uri = "https://qbo.intuit.com/qbo36"
@oauth_consumer = OAuth::Consumer.new(qb_key, qb_key, {
:site => "https://oauth.intuit.com",
:request_token_path => "/oauth/v1/get_request_token",
:authorize_path => "/oauth/v1/get_access_token",
:access_token_path => "/oauth/v1/get_access_token"
})
@oauth = OAuth::AccessToken.new(@oauth_consumer, "blah", "blah")
end
it "can fetch a list of time_activities" do
xml = windowsFixture("sync_activity_responses.xml")
model = Quickeebooks::Windows::Model::SyncActivityResponse
service = Quickeebooks::Windows::Service::SyncActivity.new
service.access_token = @oauth
service.realm_id = @realm_id
FakeWeb.register_uri(:post, service.url_for_resource(model::REST_RESOURCE), :status => ["200", "OK"], :body => xml)
sync_activity_responses = service.retrieve
sync_activity_responses.entries.count.should == 1
single_response = sync_activity_responses.entries.first
single_response.sync_type.should == "Writeback"
single_response.start_sync_tms.utc.should == Time.parse("2011-07-29T07:09:02.0").utc
single_response.end_sync_tms.utc.should == Time.parse("2011-07-29T07:09:02.0").utc
single_response.entity_name.should == "Customer"
drill_down = single_response.sync_status_drill_down
drill_down.sync_tms.should == Time.parse("2011-07-29T14:09:02.0Z").utc
drill_down.entity_id.should == "2480872"
drill_down.request_id.should == "0729e1124a274fc79d65a1d97233877f"
drill_down.ng_object_type.should == "Customer"
drill_down.operation_type.should == "CustomerAdd"
drill_down.sync_message_code.should == "10"
drill_down.sync_message.should == "success"
end
end
| 45.255814 | 119 | 0.709661 |
914f5733abb529ea61110f4e7e4bfb5ddb747c5b | 5,024 | #! /usr/bin/env ruby
# frozen_string_literal: true
#
# check-azurerm-virtual-network-gateway-failover-connected
#
# DESCRIPTION:
# This plugin checks that at least one of the specified Virtual Network Gateways is connected.
# Firing a Critical alert if both are not in the Connected state.
#
# OUTPUT:
# plain-text
#
# PLATFORMS:
# Linux
#
# DEPENDENCIES:
# gem: azure_mgmt_network
# gem: sensu-plugin
#
# USAGE:
# ./check-azurerm-virtual-network-gateway-failover-connected.rb
# -r "resourcegroup"
# -p "primary_name"
# -s "secondary_name"
#
# ./check-azurerm-virtual-network-gateway-failover-connected.rb
# -t "00000000-0000-0000-0000-000000000000"
# -c "00000000-0000-0000-0000-000000000000"
# -S "00000000-0000-0000-0000-000000000000"
# -s "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234"
# -r "resourcegroup"
# -p "primary_name"
# -s "secondary_name"
#
# ./check-azurerm-virtual-network-gateway-failover-connected.rb
# -tenant "00000000-0000-0000-0000-000000000000"
# -client "00000000-0000-0000-0000-000000000000"
# -client_secret "00000000-0000-0000-0000-000000000000"
# -subscription "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ12345678901234"
# -resourceGroup "resourcegroup"
# -primary_name "gatewayname"
# -secondary_name "gatewayname"
#
# NOTES:
#
# LICENSE:
# Tom Harvey
# Released under the same terms as Sensu (the MIT license); see LICENSE
# for details.
#
require 'azure_mgmt_network'
require 'sensu-plugin/check/cli'
require 'sensu-plugins-azurerm'
class CheckAzureRMVirtualNetworkGatewayConnected < Sensu::Plugin::Check::CLI
include SensuPluginsAzureRM
option :tenant_id,
description: 'ARM Tenant ID. Either set ENV[\'ARM_TENANT_ID\'] or provide it as an option',
short: '-t ID',
long: '--tenant ID',
default: ENV['ARM_TENANT_ID'] # TODO: can we pull these out from the Check too?
option :client_id,
description: 'ARM Client ID. Either set ENV[\'ARM_CLIENT_ID\'] or provide it as an option',
short: '-c ID',
long: '--client ID',
default: ENV['ARM_CLIENT_ID']
option :client_secret,
description: 'ARM Client Secret. Either set ENV[\'ARM_CLIENT_SECRET\'] or provide it as an option',
short: '-s SECRET',
long: '--client_secret SECRET',
default: ENV['ARM_CLIENT_SECRET']
option :subscription_id,
description: 'ARM Subscription ID',
short: '-S ID',
long: '--subscription ID',
default: ENV['ARM_SUBSCRIPTION_ID']
option :resource_group_name,
description: 'Azure Resource Group Name',
short: '-r RESOURCEGROUP',
long: '--resourceGroup RESOURCEGROUP'
option :primary_name,
description: 'Azure Virtual Network Connection Gateway Primary Name',
short: '-p NAME',
long: '--primary_name NAME'
option :secondary_name,
description: 'Azure Virtual Network Connection Gateway Secondary Name',
short: '-s NAME',
long: '--secondary_name NAME'
def run
tenant_id = config[:tenant_id]
client_id = config[:client_id]
client_secret = config[:client_secret]
subscription_id = config[:subscription_id]
resource_group_name = config[:resource_group_name]
primary_name = config[:primary_name]
secondary_name = config[:secondary_name]
network_client = NetworkUsage.new.build_virtual_network_gateways_client(tenant_id, client_id, client_secret, subscription_id)
primary_result = network_client.get(resource_group_name, primary_name)
primary_connection_state = primary_result.connection_status
primary_inbound = primary_result.ingress_bytes_transferred
primary_outbound = primary_result.egress_bytes_transferred
secondary_result = network_client.get(resource_group_name, secondary_name)
secondary_connection_state = secondary_result.connection_status
secondary_inbound = secondary_result.ingress_bytes_transferred
secondary_outbound = secondary_result.egress_bytes_transferred
message = "Primary: State is '#{primary_connection_state}'. Usage is #{primary_inbound} in / #{primary_outbound} out.\n"
message += "Secondary: State is '#{secondary_connection_state}'. Usage is #{secondary_inbound} in / #{secondary_outbound} out."
if primary_result.connection_status.casecmp('connected').zero? ||
secondary_result.connection_status.casecmp('connected').zero?
ok message
else
critical message
end
rescue StandardError => e
puts "Error: exception: #{e}"
critical
end
end
| 37.214815 | 131 | 0.650279 |
d56ef3bea399b75c9b8744a5736806159a2e2d39 | 39,636 | #! /usr/bin/env ruby
require 'spec_helper'
require 'puppet/util/package'
provider_class = Puppet::Type.type(:augeas).provider(:augeas)
describe provider_class do
before(:each) do
@resource = Puppet::Type.type(:augeas).new(
:name => "test",
:root => my_fixture_dir,
:provider => :augeas
)
@provider = provider_class.new(@resource)
end
after(:each) do
@provider.close_augeas
end
describe "command parsing" do
it "should break apart a single line into three tokens and clean up the context" do
@resource[:context] = "/context"
tokens = @provider.parse_commands("set Jar/Jar Binks")
expect(tokens.size).to eq(1)
expect(tokens[0].size).to eq(3)
expect(tokens[0][0]).to eq("set")
expect(tokens[0][1]).to eq("/context/Jar/Jar")
expect(tokens[0][2]).to eq("Binks")
end
it "should break apart a multiple line into six tokens" do
tokens = @provider.parse_commands("set /Jar/Jar Binks\nrm anakin")
expect(tokens.size).to eq(2)
expect(tokens[0].size).to eq(3)
expect(tokens[1].size).to eq(2)
expect(tokens[0][0]).to eq("set")
expect(tokens[0][1]).to eq("/Jar/Jar")
expect(tokens[0][2]).to eq("Binks")
expect(tokens[1][0]).to eq("rm")
expect(tokens[1][1]).to eq("anakin")
end
it "should strip whitespace and ignore blank lines" do
tokens = @provider.parse_commands(" set /Jar/Jar Binks \t\n \n\n rm anakin ")
expect(tokens.size).to eq(2)
expect(tokens[0].size).to eq(3)
expect(tokens[1].size).to eq(2)
expect(tokens[0][0]).to eq("set")
expect(tokens[0][1]).to eq("/Jar/Jar")
expect(tokens[0][2]).to eq("Binks")
expect(tokens[1][0]).to eq("rm")
expect(tokens[1][1]).to eq("anakin")
end
it "should handle arrays" do
@resource[:context] = "/foo/"
commands = ["set /Jar/Jar Binks", "rm anakin"]
tokens = @provider.parse_commands(commands)
expect(tokens.size).to eq(2)
expect(tokens[0].size).to eq(3)
expect(tokens[1].size).to eq(2)
expect(tokens[0][0]).to eq("set")
expect(tokens[0][1]).to eq("/Jar/Jar")
expect(tokens[0][2]).to eq("Binks")
expect(tokens[1][0]).to eq("rm")
expect(tokens[1][1]).to eq("/foo/anakin")
end
# This is not supported in the new parsing class
#it "should concat the last values" do
# provider = provider_class.new
# tokens = provider.parse_commands("set /Jar/Jar Binks is my copilot")
# tokens.size.should == 1
# tokens[0].size.should == 3
# tokens[0][0].should == "set"
# tokens[0][1].should == "/Jar/Jar"
# tokens[0][2].should == "Binks is my copilot"
#end
it "should accept spaces in the value and single ticks" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("set JarJar 'Binks is my copilot'")
expect(tokens.size).to eq(1)
expect(tokens[0].size).to eq(3)
expect(tokens[0][0]).to eq("set")
expect(tokens[0][1]).to eq("/foo/JarJar")
expect(tokens[0][2]).to eq("Binks is my copilot")
end
it "should accept spaces in the value and double ticks" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands('set /JarJar "Binks is my copilot"')
expect(tokens.size).to eq(1)
expect(tokens[0].size).to eq(3)
expect(tokens[0][0]).to eq("set")
expect(tokens[0][1]).to eq('/JarJar')
expect(tokens[0][2]).to eq('Binks is my copilot')
end
it "should accept mixed ticks" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands('set JarJar "Some \'Test\'"')
expect(tokens.size).to eq(1)
expect(tokens[0].size).to eq(3)
expect(tokens[0][0]).to eq("set")
expect(tokens[0][1]).to eq('/foo/JarJar')
expect(tokens[0][2]).to eq("Some \'Test\'")
end
it "should handle predicates with literals" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("rm */*[module='pam_console.so']")
expect(tokens).to eq([["rm", "/foo/*/*[module='pam_console.so']"]])
end
it "should handle whitespace in predicates" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("ins 42 before /files/etc/hosts/*/ipaddr[ . = '127.0.0.1' ]")
expect(tokens).to eq([["ins", "42", "before","/files/etc/hosts/*/ipaddr[ . = '127.0.0.1' ]"]])
end
it "should handle multiple predicates" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("clear pam.d/*/*[module = 'system-auth'][type = 'account']")
expect(tokens).to eq([["clear", "/foo/pam.d/*/*[module = 'system-auth'][type = 'account']"]])
end
it "should handle nested predicates" do
@resource[:context] = "/foo/"
args = ["clear", "/foo/pam.d/*/*[module[ ../type = 'type] = 'system-auth'][type[last()] = 'account']"]
tokens = @provider.parse_commands(args.join(" "))
expect(tokens).to eq([ args ])
end
it "should handle escaped doublequotes in doublequoted string" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("set /foo \"''\\\"''\"")
expect(tokens).to eq([[ "set", "/foo", "''\\\"''" ]])
end
it "should allow escaped spaces and brackets in paths" do
@resource[:context] = "/foo/"
args = [ "set", "/white\\ space/\\[section", "value" ]
tokens = @provider.parse_commands(args.join(" \t "))
expect(tokens).to eq([ args ])
end
it "should allow single quoted escaped spaces in paths" do
@resource[:context] = "/foo/"
args = [ "set", "'/white\\ space/key'", "value" ]
tokens = @provider.parse_commands(args.join(" \t "))
expect(tokens).to eq([[ "set", "/white\\ space/key", "value" ]])
end
it "should allow double quoted escaped spaces in paths" do
@resource[:context] = "/foo/"
args = [ "set", '"/white\\ space/key"', "value" ]
tokens = @provider.parse_commands(args.join(" \t "))
expect(tokens).to eq([[ "set", "/white\\ space/key", "value" ]])
end
it "should remove trailing slashes" do
@resource[:context] = "/foo/"
tokens = @provider.parse_commands("set foo/ bar")
expect(tokens).to eq([[ "set", "/foo/foo", "bar" ]])
end
end
describe "get filters" do
before do
augeas = stub("augeas", :get => "value")
augeas.stubs("close")
@provider.aug = augeas
end
it "should return false for a = nonmatch" do
command = ["get", "fake value", "==", "value"]
expect(@provider.process_get(command)).to eq(true)
end
it "should return true for a != match" do
command = ["get", "fake value", "!=", "value"]
expect(@provider.process_get(command)).to eq(false)
end
it "should return true for a =~ match" do
command = ["get", "fake value", "=~", "val*"]
expect(@provider.process_get(command)).to eq(true)
end
it "should return false for a == nonmatch" do
command = ["get", "fake value", "=~", "num*"]
expect(@provider.process_get(command)).to eq(false)
end
end
describe "values filters" do
before do
augeas = stub("augeas", :match => ["set", "of", "values"])
augeas.stubs(:get).returns('set').then.returns('of').then.returns('values')
augeas.stubs("close")
@provider = provider_class.new(@resource)
@provider.aug = augeas
end
it "should return true for includes match" do
command = ["values", "fake value", "include values"]
expect(@provider.process_values(command)).to eq(true)
end
it "should return false for includes non match" do
command = ["values", "fake value", "include JarJar"]
expect(@provider.process_values(command)).to eq(false)
end
it "should return true for includes match" do
command = ["values", "fake value", "not_include JarJar"]
expect(@provider.process_values(command)).to eq(true)
end
it "should return false for includes non match" do
command = ["values", "fake value", "not_include values"]
expect(@provider.process_values(command)).to eq(false)
end
it "should return true for an array match" do
command = ["values", "fake value", "== ['set', 'of', 'values']"]
expect(@provider.process_values(command)).to eq(true)
end
it "should return false for an array non match" do
command = ["values", "fake value", "== ['this', 'should', 'not', 'match']"]
expect(@provider.process_values(command)).to eq(false)
end
it "should return false for an array match with noteq" do
command = ["values", "fake value", "!= ['set', 'of', 'values']"]
expect(@provider.process_values(command)).to eq(false)
end
it "should return true for an array non match with noteq" do
command = ["values", "fake value", "!= ['this', 'should', 'not', 'match']"]
expect(@provider.process_values(command)).to eq(true)
end
end
describe "match filters" do
before do
augeas = stub("augeas", :match => ["set", "of", "values"])
augeas.stubs("close")
@provider = provider_class.new(@resource)
@provider.aug = augeas
end
it "should return true for size match" do
command = ["match", "fake value", "size == 3"]
expect(@provider.process_match(command)).to eq(true)
end
it "should return false for a size non match" do
command = ["match", "fake value", "size < 3"]
expect(@provider.process_match(command)).to eq(false)
end
it "should return true for includes match" do
command = ["match", "fake value", "include values"]
expect(@provider.process_match(command)).to eq(true)
end
it "should return false for includes non match" do
command = ["match", "fake value", "include JarJar"]
expect(@provider.process_match(command)).to eq(false)
end
it "should return true for includes match" do
command = ["match", "fake value", "not_include JarJar"]
expect(@provider.process_match(command)).to eq(true)
end
it "should return false for includes non match" do
command = ["match", "fake value", "not_include values"]
expect(@provider.process_match(command)).to eq(false)
end
it "should return true for an array match" do
command = ["match", "fake value", "== ['set', 'of', 'values']"]
expect(@provider.process_match(command)).to eq(true)
end
it "should return false for an array non match" do
command = ["match", "fake value", "== ['this', 'should', 'not', 'match']"]
expect(@provider.process_match(command)).to eq(false)
end
it "should return false for an array match with noteq" do
command = ["match", "fake value", "!= ['set', 'of', 'values']"]
expect(@provider.process_match(command)).to eq(false)
end
it "should return true for an array non match with noteq" do
command = ["match", "fake value", "!= ['this', 'should', 'not', 'match']"]
expect(@provider.process_match(command)).to eq(true)
end
end
describe "need to run" do
before(:each) do
@augeas = stub("augeas")
@augeas.stubs("close")
@provider.aug = @augeas
# These tests pretend to be an earlier version so the provider doesn't
# attempt to make the change in the need_to_run? method
@provider.stubs(:get_augeas_version).returns("0.3.5")
end
it "should handle no filters" do
@augeas.stubs("match").returns(["set", "of", "values"])
expect(@provider.need_to_run?).to eq(true)
end
it "should return true when a get filter matches" do
@resource[:onlyif] = "get path == value"
@augeas.stubs("get").returns("value")
expect(@provider.need_to_run?).to eq(true)
end
describe "performing numeric comparisons (#22617)" do
it "should return true when a get string compare is true" do
@resource[:onlyif] = "get bpath > a"
@augeas.stubs("get").returns("b")
expect(@provider.need_to_run?).to eq(true)
end
it "should return false when a get string compare is false" do
@resource[:onlyif] = "get a19path > a2"
@augeas.stubs("get").returns("a19")
expect(@provider.need_to_run?).to eq(false)
end
it "should return true when a get int gt compare is true" do
@resource[:onlyif] = "get path19 > 2"
@augeas.stubs("get").returns("19")
expect(@provider.need_to_run?).to eq(true)
end
it "should return true when a get int ge compare is true" do
@resource[:onlyif] = "get path19 >= 2"
@augeas.stubs("get").returns("19")
expect(@provider.need_to_run?).to eq(true)
end
it "should return true when a get int lt compare is true" do
@resource[:onlyif] = "get path2 < 19"
@augeas.stubs("get").returns("2")
expect(@provider.need_to_run?).to eq(true)
end
it "should return false when a get int le compare is false" do
@resource[:onlyif] = "get path39 <= 4"
@augeas.stubs("get").returns("39")
expect(@provider.need_to_run?).to eq(false)
end
end
describe "performing is_numeric checks (#22617)" do
it "should return false for nil" do
expect(@provider.is_numeric?(nil)).to eq(false)
end
it "should return true for Fixnums" do
expect(@provider.is_numeric?(9)).to eq(true)
end
it "should return true for numbers in Strings" do
expect(@provider.is_numeric?('9')).to eq(true)
end
it "should return false for non-number Strings" do
expect(@provider.is_numeric?('x9')).to eq(false)
end
it "should return false for other types" do
expect(@provider.is_numeric?([true])).to eq(false)
end
end
it "should return false when a get filter does not match" do
@resource[:onlyif] = "get path == another value"
@augeas.stubs("get").returns("value")
expect(@provider.need_to_run?).to eq(false)
end
it "should return true when a match filter matches" do
@resource[:onlyif] = "match path size == 3"
@augeas.stubs("match").returns(["set", "of", "values"])
expect(@provider.need_to_run?).to eq(true)
end
it "should return false when a match filter does not match" do
@resource[:onlyif] = "match path size == 2"
@augeas.stubs("match").returns(["set", "of", "values"])
expect(@provider.need_to_run?).to eq(false)
end
# Now setting force to true
it "setting force should not change the above logic" do
@resource[:force] = true
@resource[:onlyif] = "match path size == 2"
@augeas.stubs("match").returns(["set", "of", "values"])
expect(@provider.need_to_run?).to eq(false)
end
#Ticket 5211 testing
it "should return true when a size != the provided value" do
@resource[:onlyif] = "match path size != 17"
@augeas.stubs("match").returns(["set", "of", "values"])
expect(@provider.need_to_run?).to eq(true)
end
#Ticket 5211 testing
it "should return false when a size does equal the provided value" do
@resource[:onlyif] = "match path size != 3"
@augeas.stubs("match").returns(["set", "of", "values"])
expect(@provider.need_to_run?).to eq(false)
end
[true, false].product([true, false]) do |cfg, param|
describe "and Puppet[:show_diff] is #{cfg} and show_diff => #{param}" do
let(:file) { "/some/random/file" }
before(:each) do
Puppet[:show_diff] = cfg
@resource[:show_diff] = param
@resource[:root] = ""
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
File.stubs(:delete)
@provider.stubs(:get_augeas_version).returns("0.10.0")
@provider.stubs("diff").with("#{file}", "#{file}.augnew").returns("diff")
@augeas.stubs(:set).returns(true)
@augeas.stubs(:save).returns(true)
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved"])
@augeas.stubs(:get).with("/augeas/events/saved").returns("/files#{file}")
@augeas.stubs(:set).with("/augeas/save", "newfile")
end
if cfg && param
it "should display a diff" do
expect(@provider).to be_need_to_run
expect(@logs[0].message).to eq("\ndiff")
end
else
it "should not display a diff" do
expect(@provider).to be_need_to_run
expect(@logs).to be_empty
end
end
end
end
# Ticket 2728 (diff files)
describe "and configured to show diffs" do
before(:each) do
Puppet[:show_diff] = true
@resource[:show_diff] = true
@resource[:root] = ""
@provider.stubs(:get_augeas_version).returns("0.10.0")
@augeas.stubs(:set).returns(true)
@augeas.stubs(:save).returns(true)
end
it "should display a diff when a single file is shown to have been changed" do
file = "/etc/hosts"
File.stubs(:delete)
@resource[:loglevel] = "crit"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved"])
@augeas.stubs(:get).with("/augeas/events/saved").returns("/files#{file}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@provider.expects("diff").with("#{file}", "#{file}.augnew").returns("diff")
expect(@provider).to be_need_to_run
expect(@logs[0].message).to eq("\ndiff")
expect(@logs[0].level).to eq(:crit)
end
it "should display a diff for each file that is changed when changing many files" do
file1 = "/etc/hosts"
file2 = "/etc/resolv.conf"
File.stubs(:delete)
@resource[:context] = "/files"
@resource[:changes] = ["set #{file1}/foo bar", "set #{file2}/baz biz"]
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved[1]", "/augeas/events/saved[2]"])
@augeas.stubs(:get).with("/augeas/events/saved[1]").returns("/files#{file1}")
@augeas.stubs(:get).with("/augeas/events/saved[2]").returns("/files#{file2}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@provider.expects(:diff).with("#{file1}", "#{file1}.augnew").returns("diff #{file1}")
@provider.expects(:diff).with("#{file2}", "#{file2}.augnew").returns("diff #{file2}")
expect(@provider).to be_need_to_run
expect(@logs.collect(&:message)).to include("\ndiff #{file1}", "\ndiff #{file2}")
expect(@logs.collect(&:level)).to eq([:notice, :notice])
end
describe "and resource[:root] is set" do
it "should call diff when a file is shown to have been changed" do
root = "/tmp/foo"
file = "/etc/hosts"
File.stubs(:delete)
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@resource[:root] = root
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved"])
@augeas.stubs(:get).with("/augeas/events/saved").returns("/files#{file}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@provider.expects(:diff).with("#{root}#{file}", "#{root}#{file}.augnew").returns("diff")
expect(@provider).to be_need_to_run
expect(@logs[0].message).to eq("\ndiff")
expect(@logs[0].level).to eq(:notice)
end
end
it "should not call diff if no files change" do
file = "/etc/hosts"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:match).with("/augeas/events/saved").returns([])
@augeas.expects(:set).with("/augeas/save", "newfile")
@augeas.expects(:get).with("/augeas/events/saved").never()
@augeas.expects(:close)
@provider.expects(:diff).never()
expect(@provider).not_to be_need_to_run
end
it "should cleanup the .augnew file" do
file = "/etc/hosts"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved"])
@augeas.stubs(:get).with("/augeas/events/saved").returns("/files#{file}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@augeas.expects(:close)
File.expects(:delete).with(file + ".augnew")
@provider.expects(:diff).with("#{file}", "#{file}.augnew").returns("")
expect(@provider).to be_need_to_run
end
# Workaround for Augeas bug #264 which reports filenames twice
it "should handle duplicate /augeas/events/saved filenames" do
file = "/etc/hosts"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:match).with("/augeas/events/saved").returns(["/augeas/events/saved[1]", "/augeas/events/saved[2]"])
@augeas.stubs(:get).with("/augeas/events/saved[1]").returns("/files#{file}")
@augeas.stubs(:get).with("/augeas/events/saved[2]").returns("/files#{file}")
@augeas.expects(:set).with("/augeas/save", "newfile")
@augeas.expects(:close)
File.expects(:delete).with(file + ".augnew").once()
@provider.expects(:diff).with("#{file}", "#{file}.augnew").returns("").once()
expect(@provider).to be_need_to_run
end
it "should fail with an error if saving fails" do
file = "/etc/hosts"
@resource[:context] = "/files"
@resource[:changes] = ["set #{file}/foo bar"]
@augeas.stubs(:save).returns(false)
@augeas.stubs(:match).with("/augeas/events/saved").returns([])
@augeas.expects(:close)
@provider.expects(:diff).never()
@provider.expects(:print_put_errors)
expect { @provider.need_to_run? }.to raise_error(Puppet::Error)
end
end
end
describe "augeas execution integration" do
before do
@augeas = stub("augeas", :load)
@augeas.stubs("close")
@augeas.stubs(:match).with("/augeas/events/saved").returns([])
@provider.aug = @augeas
@provider.stubs(:get_augeas_version).returns("0.3.5")
end
it "should handle set commands" do
@resource[:changes] = "set JarJar Binks"
@resource[:context] = "/some/path/"
@augeas.expects(:set).with("/some/path/JarJar", "Binks").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle rm commands" do
@resource[:changes] = "rm /Jar/Jar"
@augeas.expects(:rm).with("/Jar/Jar")
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle remove commands" do
@resource[:changes] = "remove /Jar/Jar"
@augeas.expects(:rm).with("/Jar/Jar")
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle clear commands" do
@resource[:changes] = "clear Jar/Jar"
@resource[:context] = "/foo/"
@augeas.expects(:clear).with("/foo/Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
describe "touch command" do
it "should clear missing path" do
@resource[:changes] = "touch Jar/Jar"
@resource[:context] = "/foo/"
@augeas.expects(:match).with("/foo/Jar/Jar").returns([])
@augeas.expects(:clear).with("/foo/Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should not change on existing path" do
@resource[:changes] = "touch Jar/Jar"
@resource[:context] = "/foo/"
@augeas.expects(:match).with("/foo/Jar/Jar").returns(["/foo/Jar/Jar"])
@augeas.expects(:clear).never
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
end
it "should handle ins commands with before" do
@resource[:changes] = "ins Binks before Jar/Jar"
@resource[:context] = "/foo"
@augeas.expects(:insert).with("/foo/Jar/Jar", "Binks", true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle ins commands with after" do
@resource[:changes] = "ins Binks after /Jar/Jar"
@resource[:context] = "/foo"
@augeas.expects(:insert).with("/Jar/Jar", "Binks", false)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle ins with no context" do
@resource[:changes] = "ins Binks after /Jar/Jar"
@augeas.expects(:insert).with("/Jar/Jar", "Binks", false)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle multiple commands" do
@resource[:changes] = ["ins Binks after /Jar/Jar", "clear Jar/Jar"]
@resource[:context] = "/foo/"
@augeas.expects(:insert).with("/Jar/Jar", "Binks", false)
@augeas.expects(:clear).with("/foo/Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle defvar commands" do
@resource[:changes] = "defvar myjar Jar/Jar"
@resource[:context] = "/foo/"
@augeas.expects(:defvar).with("myjar", "/foo/Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should pass through augeas variables without context" do
@resource[:changes] = ["defvar myjar Jar/Jar","set $myjar/Binks 1"]
@resource[:context] = "/foo/"
@augeas.expects(:defvar).with("myjar", "/foo/Jar/Jar").returns(true)
# this is the important bit, shouldn't be /foo/$myjar/Binks
@augeas.expects(:set).with("$myjar/Binks", "1").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle defnode commands" do
@resource[:changes] = "defnode newjar Jar/Jar[last()+1] Binks"
@resource[:context] = "/foo/"
@augeas.expects(:defnode).with("newjar", "/foo/Jar/Jar[last()+1]", "Binks").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle mv commands" do
@resource[:changes] = "mv Jar/Jar Binks"
@resource[:context] = "/foo/"
@augeas.expects(:mv).with("/foo/Jar/Jar", "/foo/Binks").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle rename commands" do
@resource[:changes] = "rename Jar/Jar Binks"
@resource[:context] = "/foo/"
@augeas.expects(:rename).with("/foo/Jar/Jar", "Binks").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should handle setm commands" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","setm test Jar/Jar Binks"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("setm").returns(true)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
@augeas.expects(:setm).with("/foo/test", "Jar/Jar", "Binks").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should throw error if setm command not supported" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","setm test Jar/Jar Binks"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("setm").returns(false)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
expect { @provider.execute_changes }.to raise_error RuntimeError, /command 'setm' not supported/
end
it "should handle clearm commands" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","clearm test Jar/Jar"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("clearm").returns(true)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
@augeas.expects(:clearm).with("/foo/test", "Jar/Jar").returns(true)
@augeas.expects(:save).returns(true)
@augeas.expects(:close)
expect(@provider.execute_changes).to eq(:executed)
end
it "should throw error if clearm command not supported" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","clearm test Jar/Jar"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("clearm").returns(false)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
expect { @provider.execute_changes }.to raise_error(RuntimeError, /command 'clearm' not supported/)
end
it "should throw error if saving failed" do
@resource[:changes] = ["set test[1]/Jar/Jar Foo","set test[2]/Jar/Jar Bar","clearm test Jar/Jar"]
@resource[:context] = "/foo/"
@augeas.expects(:respond_to?).with("clearm").returns(true)
@augeas.expects(:set).with("/foo/test[1]/Jar/Jar", "Foo").returns(true)
@augeas.expects(:set).with("/foo/test[2]/Jar/Jar", "Bar").returns(true)
@augeas.expects(:clearm).with("/foo/test", "Jar/Jar").returns(true)
@augeas.expects(:save).returns(false)
@provider.expects(:print_put_errors)
@augeas.expects(:match).returns([])
expect { @provider.execute_changes }.to raise_error(Puppet::Error)
end
end
describe "when making changes", :if => Puppet.features.augeas? do
include PuppetSpec::Files
it "should not clobber the file if it's a symlink" do
Puppet::Util::Storage.stubs(:store)
link = tmpfile('link')
target = tmpfile('target')
FileUtils.touch(target)
Puppet::FileSystem.symlink(target, link)
resource = Puppet::Type.type(:augeas).new(
:name => 'test',
:incl => link,
:lens => 'Sshd.lns',
:changes => "set PermitRootLogin no"
)
catalog = Puppet::Resource::Catalog.new
catalog.add_resource resource
catalog.apply
expect(File.ftype(link)).to eq('link')
expect(Puppet::FileSystem.readlink(link)).to eq(target)
expect(File.read(target)).to match(/PermitRootLogin no/)
end
end
describe "load/save failure reporting" do
before do
@augeas = stub("augeas")
@augeas.stubs("close")
@provider.aug = @augeas
end
describe "should find load errors" do
before do
@augeas.expects(:match).with("/augeas//error").returns(["/augeas/files/foo/error"])
@augeas.expects(:match).with("/augeas/files/foo/error/*").returns(["/augeas/files/foo/error/path", "/augeas/files/foo/error/message"])
@augeas.expects(:get).with("/augeas/files/foo/error").returns("some_failure")
@augeas.expects(:get).with("/augeas/files/foo/error/path").returns("/foo")
@augeas.expects(:get).with("/augeas/files/foo/error/message").returns("Failed to...")
end
it "and output only to debug when no path supplied" do
@provider.expects(:debug).times(5)
@provider.expects(:warning).never()
@provider.print_load_errors(nil)
end
it "and output a warning and to debug when path supplied" do
@augeas.expects(:match).with("/augeas/files/foo//error").returns(["/augeas/files/foo/error"])
@provider.expects(:warning).once()
@provider.expects(:debug).times(4)
@provider.print_load_errors('/augeas/files/foo//error')
end
it "and output only to debug when path doesn't match" do
@augeas.expects(:match).with("/augeas/files/foo//error").returns([])
@provider.expects(:warning).never()
@provider.expects(:debug).times(5)
@provider.print_load_errors('/augeas/files/foo//error')
end
end
it "should find load errors from lenses" do
@augeas.expects(:match).with("/augeas//error").twice.returns(["/augeas/load/Xfm/error"])
@augeas.expects(:match).with("/augeas/load/Xfm/error/*").returns([])
@augeas.expects(:get).with("/augeas/load/Xfm/error").returns(["Could not find lens php.aug"])
@provider.expects(:warning).once()
@provider.expects(:debug).twice()
@provider.print_load_errors('/augeas//error')
end
it "should find save errors and output to debug" do
@augeas.expects(:match).with("/augeas//error[. = 'put_failed']").returns(["/augeas/files/foo/error"])
@augeas.expects(:match).with("/augeas/files/foo/error/*").returns(["/augeas/files/foo/error/path", "/augeas/files/foo/error/message"])
@augeas.expects(:get).with("/augeas/files/foo/error").returns("some_failure")
@augeas.expects(:get).with("/augeas/files/foo/error/path").returns("/foo")
@augeas.expects(:get).with("/augeas/files/foo/error/message").returns("Failed to...")
@provider.expects(:debug).times(5)
@provider.print_put_errors
end
end
# Run initialisation tests of the real Augeas library to test our open_augeas
# method. This relies on Augeas and ruby-augeas on the host to be
# functioning.
describe "augeas lib initialisation", :if => Puppet.features.augeas? do
# Expect lenses for fstab and hosts
it "should have loaded standard files by default" do
aug = @provider.open_augeas
expect(aug).not_to eq(nil)
expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
expect(aug.match("/files/etc/test")).to eq([])
end
it "should report load errors to debug only" do
@provider.expects(:print_load_errors).with(nil)
aug = @provider.open_augeas
expect(aug).not_to eq(nil)
end
# Only the file specified should be loaded
it "should load one file if incl/lens used" do
@resource[:incl] = "/etc/hosts"
@resource[:lens] = "Hosts.lns"
@provider.expects(:print_load_errors).with('/augeas//error')
aug = @provider.open_augeas
expect(aug).not_to eq(nil)
expect(aug.match("/files/etc/fstab")).to eq([])
expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
expect(aug.match("/files/etc/test")).to eq([])
end
it "should also load lenses from load_path" do
@resource[:load_path] = my_fixture_dir
aug = @provider.open_augeas
expect(aug).not_to eq(nil)
expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
expect(aug.match("/files/etc/test")).to eq(["/files/etc/test"])
end
it "should also load lenses from pluginsync'd path" do
Puppet[:libdir] = my_fixture_dir
aug = @provider.open_augeas
expect(aug).not_to eq(nil)
expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
expect(aug.match("/files/etc/test")).to eq(["/files/etc/test"])
end
# Optimisations added for Augeas 0.8.2 or higher is available, see #7285
describe ">= 0.8.2 optimisations", :if => Puppet.features.augeas? && Facter.value(:augeasversion) && Puppet::Util::Package.versioncmp(Facter.value(:augeasversion), "0.8.2") >= 0 do
it "should only load one file if relevant context given" do
@resource[:context] = "/files/etc/fstab"
@provider.expects(:print_load_errors).with('/augeas/files/etc/fstab//error')
aug = @provider.open_augeas
expect(aug).not_to eq(nil)
expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
expect(aug.match("/files/etc/hosts")).to eq([])
end
it "should only load one lens from load_path if context given" do
@resource[:context] = "/files/etc/test"
@resource[:load_path] = my_fixture_dir
@provider.expects(:print_load_errors).with('/augeas/files/etc/test//error')
aug = @provider.open_augeas
expect(aug).not_to eq(nil)
expect(aug.match("/files/etc/fstab")).to eq([])
expect(aug.match("/files/etc/hosts")).to eq([])
expect(aug.match("/files/etc/test")).to eq(["/files/etc/test"])
end
it "should load standard files if context isn't specific" do
@resource[:context] = "/files/etc"
@provider.expects(:print_load_errors).with(nil)
aug = @provider.open_augeas
expect(aug).not_to eq(nil)
expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
end
it "should not optimise if the context is a complex path" do
@resource[:context] = "/files/*[label()='etc']"
@provider.expects(:print_load_errors).with(nil)
aug = @provider.open_augeas
expect(aug).not_to eq(nil)
expect(aug.match("/files/etc/fstab")).to eq(["/files/etc/fstab"])
expect(aug.match("/files/etc/hosts")).to eq(["/files/etc/hosts"])
end
end
end
describe "get_load_path" do
it "should offer no load_path by default" do
expect(@provider.get_load_path(@resource)).to eq("")
end
it "should offer one path from load_path" do
@resource[:load_path] = "/foo"
expect(@provider.get_load_path(@resource)).to eq("/foo")
end
it "should offer multiple colon-separated paths from load_path" do
@resource[:load_path] = "/foo:/bar:/baz"
expect(@provider.get_load_path(@resource)).to eq("/foo:/bar:/baz")
end
it "should offer multiple paths in array from load_path" do
@resource[:load_path] = ["/foo", "/bar", "/baz"]
expect(@provider.get_load_path(@resource)).to eq("/foo:/bar:/baz")
end
it "should offer pluginsync augeas/lenses subdir" do
Puppet[:libdir] = my_fixture_dir
expect(@provider.get_load_path(@resource)).to eq("#{my_fixture_dir}/augeas/lenses")
end
it "should offer both pluginsync and load_path paths" do
Puppet[:libdir] = my_fixture_dir
@resource[:load_path] = ["/foo", "/bar", "/baz"]
expect(@provider.get_load_path(@resource)).to eq("/foo:/bar:/baz:#{my_fixture_dir}/augeas/lenses")
end
end
end
| 38.631579 | 184 | 0.614896 |
28e0ada602ae3a673cf5fab40e27df6be60ec575 | 301 | class CreateUsersInGames < ActiveRecord::Migration[6.0]
def change
create_table :users_in_games do |t|
t.belongs_to :game, null: false, index: true
t.belongs_to :user, null: false, index: true
t.timestamps
end
add_index :users_in_games, %i[game_id user_id]
end
end
| 23.153846 | 55 | 0.69103 |
38000531e6d7c2acc1edad387981757c12460624 | 1,452 | class Kvazaar < Formula
desc "Ultravideo HEVC encoder"
homepage "https://github.com/ultravideo/kvazaar"
url "https://github.com/ultravideo/kvazaar/releases/download/v1.2.0/kvazaar-1.2.0.tar.xz"
sha256 "9bc9ba4d825b497705bd6d84817933efbee43cbad0ffaac17d4b464e11e73a37"
bottle do
cellar :any
sha256 "cdd936796111dc2b579a313780538417a74e9f2a024deb7f516b255f49c3d377" => :mojave
sha256 "81e3084935b40153b533da73526e453280ffb09fac29745d43d4e305b462aa9a" => :high_sierra
sha256 "0f8150c11184a4a7af203db7e11b9942ceeabd8442e82ff2e34c53145cd85be3" => :sierra
sha256 "918e7ad37489d7bc2c602b47678f85392bcaeca1805e01953e7dabe54c1a153b" => :el_capitan
end
head do
url "https://github.com/ultravideo/kvazaar.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "yasm" => :build
resource "videosample" do
url "https://samples.mplayerhq.hu/V-codecs/lm20.avi"
sha256 "a0ab512c66d276fd3932aacdd6073f9734c7e246c8747c48bf5d9dd34ac8b392"
end
def install
system "./autogen.sh" if build.head?
system "./configure", "--prefix=#{prefix}"
system "make", "install"
end
test do
# download small sample and try to encode it
resource("videosample").stage do
system bin/"kvazaar", "-i", "lm20.avi", "--input-res", "16x16", "-o", "lm20.hevc"
assert_predicate Pathname.pwd/"lm20.hevc", :exist?
end
end
end
| 33 | 93 | 0.734848 |
e9a1844ea94edc4c0f4c47ddecd7424a65b7e6f6 | 2,241 | # This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
# movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
# Character.create(name: 'Luke', movie: movies.first)
# create users
admin = User.create!(username: :admin,
admin: true,
display_name: Faker::Name.unique.name,
email: Faker::Internet.unique.email)
clients = 10.times.map do
client = User.create!(username: Faker::Name.unique.first_name.downcase,
display_name: Faker::Name.unique.name,
email: Faker::Internet.unique.email,
client: true)
end
# create locations
locations = 3.times.map do
Location.create!(name: "BA#{Faker::Address.building_number}",
description: Faker::Movies::HitchhikersGuideToTheGalaxy.unique.location)
end
# create resources and availabilities
past_availabilities = []
future_availabilities = []
10.times.map do
resource = Resource.create!(resource_type: Faker::Appliance.equipment,
name: Faker::NatoPhoneticAlphabet.unique.code_word,
location: locations.sample)
10.times.map do |i|
start_time = i.days.ago.beginning_of_day
avail = Availability.create!(resource: resource, start_time: start_time, end_time: start_time + 1.day - 1.second)
past_availabilities << avail
end
4.times.map do |i|
start_time = (i+1).days.from_now.beginning_of_day
avail = Availability.create!(resource: resource, start_time: start_time, end_time: start_time + 1.day - 1.second)
future_availabilities << avail
end
end
# create availabilities
clients.each do |client|
rand(max=10).times.each do
Booking.create(user: client, creator: client, availability: past_availabilities.delete(past_availabilities.sample))
end
if [true, false].sample
Booking.create!(user: client,
creator: client,
availability: future_availabilities.delete(future_availabilities.sample))
end
end
| 37.35 | 119 | 0.668452 |
e2196ce683865de8d24d9c3a16def1ad5a58c8ad | 41 | class Interview < ActiveRecord::Base
end
| 13.666667 | 36 | 0.804878 |
e82ba7c8ef349e001c177af24ab01534e0299806 | 539 | cask 'trufont' do
version '0.5.0'
sha256 'bdc20b8e11f51b58595a8ed2ff2e6a9684a581c739ed5c1fd500ca8b8cd05fcb'
# github.com/trufont/trufont was verified as official when first introduced to the cask
url "https://github.com/trufont/trufont/releases/download/#{version}/TruFont.app.zip"
appcast 'https://github.com/trufont/trufont/releases.atom',
checkpoint: '94f15046baf1df5da48358493e4ab5895ed918e80abf67623dad4f1490c163a9'
name 'TruFont'
homepage 'https://trufont.github.io/'
license :oss
app 'TruFont.app'
end
| 35.933333 | 89 | 0.77551 |
7a180f8edf9d12a8ff3735328636bb1218896136 | 14,153 | #--
# Author:: Adam Jacob (<[email protected]>)
# Author:: Thom May (<[email protected]>)
# Author:: Nuo Yan (<[email protected]>)
# Author:: Christopher Brown (<[email protected]>)
# Author:: Christopher Walters (<[email protected]>)
# Copyright:: Copyright (c) 2009, 2010 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'net/https'
require 'uri'
require 'chef/json_compat'
require 'tempfile'
require 'chef/rest/auth_credentials'
require 'chef/rest/rest_request'
require 'chef/monkey_patches/string'
class Chef
# == Chef::REST
# Chef's custom REST client with built-in JSON support and RSA signed header
# authentication.
class REST
attr_reader :auth_credentials
attr_accessor :url, :cookies, :sign_on_redirect, :redirect_limit
# Create a REST client object. The supplied +url+ is used as the base for
# all subsequent requests. For example, when initialized with a base url
# http://localhost:4000, a call to +get_rest+ with 'nodes' will make an
# HTTP GET request to http://localhost:4000/nodes
def initialize(url, client_name=Chef::Config[:node_name], signing_key_filename=Chef::Config[:client_key], options={})
@url = url
@cookies = CookieJar.instance
@default_headers = options[:headers] || {}
@auth_credentials = AuthCredentials.new(client_name, signing_key_filename)
@sign_on_redirect, @sign_request = true, true
@redirects_followed = 0
@redirect_limit = 10
end
def signing_key_filename
@auth_credentials.key_file
end
def client_name
@auth_credentials.client_name
end
def signing_key
@auth_credentials.raw_key
end
# Register the client
#--
# Requires you to load chef/api_client beforehand. explicit require is removed since
# most users of this class have no need for chef/api_client. This functionality
# should be moved anyway...
def register(name=Chef::Config[:node_name], destination=Chef::Config[:client_key])
if (File.exists?(destination) && !File.writable?(destination))
raise Chef::Exceptions::CannotWritePrivateKey, "I cannot write your private key to #{destination} - check permissions?"
end
nc = Chef::ApiClient.new
nc.name(name)
catch(:done) do
retries = config[:client_registration_retries] || 5
0.upto(retries) do |n|
begin
response = nc.save(true, true)
Chef::Log.debug("Registration response: #{response.inspect}")
raise Chef::Exceptions::CannotWritePrivateKey, "The response from the server did not include a private key!" unless response.has_key?("private_key")
# Write out the private key
::File.open(destination, "w") {|f|
f.chmod(0600)
f.print(response["private_key"])
}
throw :done
rescue IOError
raise Chef::Exceptions::CannotWritePrivateKey, "I cannot write your private key to #{destination}"
rescue Net::HTTPFatalError => e
Chef::Log.warn("Failed attempt #{n} of #{retries+1} on client creation")
raise unless e.response.code == "500"
end
end
end
true
end
# Send an HTTP GET request to the path
#
# Using this method to +fetch+ a file is considered deprecated.
#
# === Parameters
# path:: The path to GET
# raw:: Whether you want the raw body returned, or JSON inflated. Defaults
# to JSON inflated.
def get_rest(path, raw=false, headers={})
if raw
streaming_request(create_url(path), headers)
else
api_request(:GET, create_url(path), headers)
end
end
# Send an HTTP DELETE request to the path
def delete_rest(path, headers={})
api_request(:DELETE, create_url(path), headers)
end
# Send an HTTP POST request to the path
def post_rest(path, json, headers={})
api_request(:POST, create_url(path), headers, json)
end
# Send an HTTP PUT request to the path
def put_rest(path, json, headers={})
api_request(:PUT, create_url(path), headers, json)
end
# Streams a download to a tempfile, then yields the tempfile to a block.
# After the download, the tempfile will be closed and unlinked.
# If you rename the tempfile, it will not be deleted.
# Beware that if the server streams infinite content, this method will
# stream it until you run out of disk space.
def fetch(path, headers={})
streaming_request(create_url(path), headers) {|tmp_file| yield tmp_file }
end
def create_url(path)
if path =~ /^(http|https):\/\//
URI.parse(path)
else
URI.parse("#{@url}/#{path}")
end
end
def sign_requests?
auth_credentials.sign_requests? && @sign_request
end
# ==== DEPRECATED
# Use +api_request+ instead
#--
# Actually run an HTTP request. First argument is the HTTP method,
# which should be one of :GET, :PUT, :POST or :DELETE. Next is the
# URL, then an object to include in the body (which will be converted with
# .to_json). The limit argument is unused, it is present for backwards
# compatibility. Configure the redirect limit with #redirect_limit=
# instead.
#
# Typically, you won't use this method -- instead, you'll use one of
# the helper methods (get_rest, post_rest, etc.)
#
# Will return the body of the response on success.
def run_request(method, url, headers={}, data=false, limit=nil, raw=false)
json_body = data ? Chef::JSONCompat.to_json(data) : nil
headers = build_headers(method, url, headers, json_body, raw)
tf = nil
retriable_rest_request(method, url, json_body, headers) do |rest_request|
res = rest_request.call do |response|
if raw
tf = stream_to_tempfile(url, response)
else
response.read_body
end
end
if res.kind_of?(Net::HTTPSuccess)
if res['content-type'] =~ /json/
response_body = res.body.chomp
Chef::JSONCompat.from_json(response_body)
else
if method == :HEAD
true
elsif raw
tf
else
res.body
end
end
elsif res.kind_of?(Net::HTTPFound) or res.kind_of?(Net::HTTPMovedPermanently)
follow_redirect {run_request(:GET, create_url(res['location']), {}, false, nil, raw)}
elsif res.kind_of?(Net::HTTPNotModified)
false
else
if res['content-type'] =~ /json/
exception = Chef::JSONCompat.from_json(res.body)
msg = "HTTP Request Returned #{res.code} #{res.message}: "
msg << (exception["error"].respond_to?(:join) ? exception["error"].join(", ") : exception["error"].to_s)
Chef::Log.warn(msg)
end
res.error!
end
end
end
# Runs an HTTP request to a JSON API. File Download not supported.
def api_request(method, url, headers={}, data=false)
json_body = data ? Chef::JSONCompat.to_json(data) : nil
headers = build_headers(method, url, headers, json_body)
retriable_rest_request(method, url, json_body, headers) do |rest_request|
response = rest_request.call {|r| r.read_body}
if response.kind_of?(Net::HTTPSuccess)
if response['content-type'] =~ /json/
Chef::JSONCompat.from_json(response.body.chomp)
else
Chef::Log.warn("Expected JSON response, but got content-type '#{response['content-type']}'")
response.body
end
elsif redirect_location = redirected_to(response)
follow_redirect {api_request(:GET, create_url(redirect_location))}
else
if response['content-type'] =~ /json/
exception = Chef::JSONCompat.from_json(response.body)
msg = "HTTP Request Returned #{response.code} #{response.message}: "
msg << (exception["error"].respond_to?(:join) ? exception["error"].join(", ") : exception["error"].to_s)
Chef::Log.info(msg)
end
response.error!
end
end
end
# Makes a streaming download request. <b>Doesn't speak JSON.</b>
# Streams the response body to a tempfile. If a block is given, it's
# passed to Tempfile.open(), which means that the tempfile will automatically
# be unlinked after the block is executed.
#
# If no block is given, the tempfile is returned, which means it's up to
# you to unlink the tempfile when you're done with it.
def streaming_request(url, headers, &block)
headers = build_headers(:GET, url, headers, nil, true)
retriable_rest_request(:GET, url, nil, headers) do |rest_request|
tempfile = nil
response = rest_request.call do |r|
if block_given? && r.kind_of?(Net::HTTPSuccess)
begin
tempfile = stream_to_tempfile(url, r, &block)
yield tempfile
ensure
tempfile.close!
end
else
tempfile = stream_to_tempfile(url, r)
end
end
if response.kind_of?(Net::HTTPSuccess)
tempfile
elsif redirect_location = redirected_to(response)
# TODO: test tempfile unlinked when following redirects.
tempfile && tempfile.close!
follow_redirect {streaming_request(create_url(redirect_location), {}, &block)}
else
tempfile && tempfile.close!
response.error!
end
end
end
def retriable_rest_request(method, url, req_body, headers)
rest_request = Chef::REST::RESTRequest.new(method, url, req_body, headers)
Chef::Log.debug("Sending HTTP Request via #{method} to #{url.host}:#{url.port}#{rest_request.path}")
http_attempts = 0
begin
http_attempts += 1
res = yield rest_request
rescue SocketError, Errno::ETIMEDOUT => e
e.message.replace "Error connecting to #{url} - #{e.message}"
raise e
rescue Errno::ECONNREFUSED
if http_retry_count - http_attempts + 1 > 0
Chef::Log.error("Connection refused connecting to #{url.host}:#{url.port} for #{rest_request.path}, retry #{http_attempts}/#{http_retry_count}")
sleep(http_retry_delay)
retry
end
raise Errno::ECONNREFUSED, "Connection refused connecting to #{url.host}:#{url.port} for #{rest_request.path}, giving up"
rescue Timeout::Error
if http_retry_count - http_attempts + 1 > 0
Chef::Log.error("Timeout connecting to #{url.host}:#{url.port} for #{rest_request.path}, retry #{http_attempts}/#{http_retry_count}")
sleep(http_retry_delay)
retry
end
raise Timeout::Error, "Timeout connecting to #{url.host}:#{url.port} for #{rest_request.path}, giving up"
rescue Net::HTTPFatalError => e
if http_retry_count - http_attempts + 1 > 0
sleep_time = 1 + (2 ** http_attempts) + rand(2 ** http_attempts)
Chef::Log.error("Server returned error for #{url}, retrying #{http_attempts}/#{http_retry_count} in #{sleep_time}s")
sleep(sleep_time)
retry
end
raise
end
end
def authentication_headers(method, url, json_body=nil)
request_params = {:http_method => method, :path => url.path, :body => json_body, :host => "#{url.host}:#{url.port}"}
request_params[:body] ||= ""
auth_credentials.signature_headers(request_params)
end
def http_retry_delay
config[:http_retry_delay]
end
def http_retry_count
config[:http_retry_count]
end
def config
Chef::Config
end
def follow_redirect
raise Chef::Exceptions::RedirectLimitExceeded if @redirects_followed >= redirect_limit
@redirects_followed += 1
Chef::Log.debug("Following redirect #{@redirects_followed}/#{redirect_limit}")
if @sign_on_redirect
yield
else
@sign_request = false
yield
end
ensure
@redirects_followed = 0
@sign_request = true
end
private
def redirected_to(response)
if response.kind_of?(Net::HTTPFound) || response.kind_of?(Net::HTTPMovedPermanently)
response['location']
else
nil
end
end
def build_headers(method, url, headers={}, json_body=false, raw=false)
headers = @default_headers.merge(headers)
headers['Accept'] = "application/json" unless raw
headers["Content-Type"] = 'application/json' if json_body
headers['Content-Length'] = json_body.bytesize.to_s if json_body
headers.merge!(authentication_headers(method, url, json_body)) if sign_requests?
headers.merge!(Chef::Config[:custom_http_headers]) if Chef::Config[:custom_http_headers]
headers
end
def stream_to_tempfile(url, response)
tf = Tempfile.open("chef-rest")
if RUBY_PLATFORM =~ /mswin|mingw32|windows/
tf.binmode #required for binary files on Windows platforms
end
Chef::Log.debug("Streaming download from #{url.to_s} to tempfile #{tf.path}")
# Stolen from http://www.ruby-forum.com/topic/166423
# Kudos to _why!
size, total = 0, response.header['Content-Length'].to_i
response.read_body do |chunk|
tf.write(chunk)
size += chunk.size
end
tf.close
tf
rescue Exception
tf.close!
raise
end
end
end
| 36.012723 | 160 | 0.636685 |
5d2adaa93f302f6598cb44ec7c6b3a08bafbd80e | 1,249 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::IotHub::Mgmt::V2017_07_01
module Models
#
# The JSON-serialized leaf certificate
#
class CertificateVerificationDescription
include MsRestAzure
# @return [String] base-64 representation of X509 certificate .cer file
# or just .pem file content.
attr_accessor :certificate
#
# Mapper for CertificateVerificationDescription class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'CertificateVerificationDescription',
type: {
name: 'Composite',
class_name: 'CertificateVerificationDescription',
model_properties: {
certificate: {
client_side_validation: true,
required: false,
serialized_name: 'certificate',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 26.574468 | 77 | 0.583667 |
626e0a043f390530c4389c4ab6c9afe2e8426b6c | 779 | Как эффективно использовать сирень в дизайне сада?
Ирина Окунева отвечает на наши вопросы:
Так сирень теряют хороший внешний вид, когда они упали свои цветы, это хорошая идея, чтобы посадить их вместе с другими кустарниками.
Они подходят очень хорошо с многих растений.
Кроме того, можно и нужно сажать сирень рядом обоих растений, которые цветут в разное время, и теми, которые цветут в то же время, как это.
Еще один бонус сирени, что они предлагают так много возможностей, чтобы получить творческий.
Вы можете формировать их в стандартный дерева различных высотах, привлекательный куст, кустарник с широким основанием, или даже в чем-то, напоминающим сад бонсай дерево с причудливой изогнутой складе.
Просто выберите из формы, что лучше всего работает с дизайном вашего сада.
| 86.555556 | 200 | 0.817715 |
abe82b8f2fe94a2e1f8162d686c387b66293e818 | 2,187 | module Dyph
module Support
module SanityCheck
extend self
# rubocop:disable Metrics/AbcSize
def ensure_no_lost_data(left, base, right, final_result)
result_word_map = {}
final_result.each do |result_block|
blocks = case result_block
when Outcome::Resolved then result_block.result
when Outcome::Conflicted then [result_block.left, result_block.right].flatten
else raise "Unknown block type, #{result_block[:type]}"
end
count_blocks(blocks, result_word_map)
end
left_word_map, base_word_map, right_word_map = [left, base, right].map { |str| count_blocks(str) }
# new words are words that are in left or right, but not in base
new_left_words = subtract_words(left_word_map, base_word_map)
new_right_words = subtract_words(right_word_map, base_word_map)
# now make sure all new words are somewhere in the result
missing_new_left_words = subtract_words(new_left_words, result_word_map)
missing_new_right_words = subtract_words(new_right_words, result_word_map)
if missing_new_left_words.any? || missing_new_right_words.any?
raise BadMergeException.new(final_result)
end
end
# rubocop:enable Metrics/AbcSize
private
def count_blocks(blocks, hash={})
blocks.reduce(hash) do |map, block|
map[block] ||= 0
map[block] += 1
map
end
end
def subtract_words(left_map, right_map)
remaining_words = {}
left_map.each do |word, count|
count_in_right = right_map[word] || 0
new_count = count - count_in_right
remaining_words[word] = new_count if new_count > 0
end
remaining_words
end
end
class BadMergeException < StandardError
attr_accessor :merge_result
def initialize(merge_result)
@merge_result = merge_result
end
def inspect
"<#{self.class}: #{merge_result}>"
end
def to_s
inspect
end
end
end
end | 29.958904 | 106 | 0.621399 |
e26f9f9cc366574baa3ec219033fe8ac19a40237 | 3,624 | module Address
class Transfer
include ActiveModel::Model
attr_accessor :cpf, :observation, :unit_id
validates :cpf, cpf: true, presence: true
validates :observation, presence: true
validate :cpf_allow?
def transfer!
#clone cadastre address
#add new cadastre address 'transferido'
address_unit = unit
candidate = address_unit.current_candidate
new_candidate = Candidate::Cadastre.find_by_cpf(self.cpf)
cadastre_address = address_unit.current_cadastre_address
new_cadastre_address = address_unit.cadastre_address.new
cadastre_address.attributes.each do |key, value|
unless %w(id created_at updated_at).include? key
new_cadastre_address[key] = value if new_cadastre_address.attributes.has_key?(key)
end
end
new_cadastre_address.situation_id = 'transferido'
new_cadastre_address.save
# update old candidate
update_candidate(candidate, 77, 8)
# add cadastre address to new candidate
create_candidate_address('distribuído', address_unit, new_candidate)
# update situation and procedural of new candidate
#update_candidate(new_candidate, 4, 7)
# update para contemplação do candidato
@situation = new_candidate.cadastre_situations.new({
situation_status_id: 7
})
@situation.save
# find last assessment unit
@old_procedural = Candidate::CadastreProcedural.where(cadastre_id: candidate).order("created_at desc").first
# update procedural of candidate
@procedural = new_candidate.cadastre_procedurals.new({
procedural_status_id: 4,
convocation_id: @old_procedural.convocation_id,
assessment_id: @old_procedural.assessment_id,
observation: "Transferencia de imóvel via sistema."
})
@procedural.save
end
private
def create_candidate_address(situation, address, candidate)
address.cadastre_address.new({
cadastre_id: candidate.id,
situation_id: situation,
unit_id: address.id,
dominial_chain: address.current_cadastre_address.dominial_chain.to_i + 1,
observation: self.observation,
type_occurrence: 0,
type_receipt: 1
}).save
end
def update_candidate(candidate, procedural, situation)
service = Candidate::SituationService.new(candidate)
service.add_situation(situation)
service.add_procedural(procedural)
end
def unit
Address::Unit.find(self.unit_id) rescue nil
end
def cpf_allow?
candidate = Candidate::Cadastre.find_by_cpf(self.cpf) rescue nil
if unit.nil?
errors.add(:cpf, "Endereço solicĩtado não existe")
else
if unit.current_candidate.present?
if unit.current_candidate.cpf == self.cpf
errors.add(:cpf, "CPF é o último na cadeia dominial, favor informar outro")
end
end
end
if candidate.nil?
errors.add(:cpf, "CPF não existe na base da dados")
else
unless [3,6].include? candidate.program_id
errors.add(:cpf, "CPF não está vínculado ao programa de Regularização")
end
unless [4, 3].include? candidate.current_situation_id
errors.add(:cpf, "CPF não se encontra HABILITADO ou CONVOCADO")
end
unless [14,64,65,66].include? candidate.current_procedural.procedural_status_id
errors.add(:cpf, "CPF não se encontra com situação processual válida para transferência")
end
end
end
end
end
| 29.704918 | 114 | 0.671909 |
ac81beeca50c1df9c52bc7394f2d7e23c4fc788e | 77 | # -*- frozen_string_literal: true -*-
module RSplit
VERSION = "0.1.3"
end
| 12.833333 | 37 | 0.649351 |
08ae88e7085ce004597f8c3d34c202929171bf00 | 700 | require File.expand_path('../../../spec_helper', __FILE__)
describe "Float#round" do
it "returns the nearest Integer" do
5.5.round.should == 6
0.4.round.should == 0
-2.8.round.should == -3
0.0.round.should == 0
0.49999999999999994.round.should == 0 # see http://jira.codehaus.org/browse/JRUBY-5048
end
ruby_version_is "1.9" do
it "rounds self to an optionally given precision" do
5.5.round(0).should == 6
1.2345678.round(2).should be_close(1.23, TOLERANCE)
123456.78.round(-2).should == 123500 # rounded up
12.345678.round(2.9999999999999999999).should be_close(12.346, TOLERANCE)
0.8346268.round(-2.0**30).should == 0
end
end
end
| 30.434783 | 90 | 0.657143 |
edc5e3ca79f93c635239260239f2a540b4a9279a | 498 | require_relative '../embed_objects/embed_field'
module RedmineDiscord
class WrappedJournal
def initialize(journal)
@journal = journal
end
def to_notes_field
notes = @journal.notes
if notes.present?
block_notes = "```#{notes.to_s.gsub(/`/, "\u200b`")}```"
EmbedField.new('Notes', block_notes, false).to_hash
end
end
def to_editor_field
EmbedField.new('Edited by', "`#{@journal.event_author}`", false).to_hash
end
end
end
| 21.652174 | 78 | 0.640562 |
bfb153b09c4dee5eca69610f1a1ae19d041d152c | 1,851 | # frozen_string_literal: true
module RuboCop
module Cop
module Security
# This cop checks for the use of `Kernel#open`.
#
# `Kernel#open` enables not only file access but also process invocation
# by prefixing a pipe symbol (e.g., `open("| ls")`). So, it may lead to
# a serious security risk by using variable input to the argument of
# `Kernel#open`. It would be better to use `File.open`, `IO.popen` or
# `URI#open` explicitly.
#
# @example
# # bad
# open(something)
#
# # good
# File.open(something)
# IO.popen(something)
# URI.parse(something).open
class Open < Base
MSG = 'The use of `Kernel#open` is a serious security risk.'
RESTRICT_ON_SEND = %i[open].freeze
def_node_matcher :open?, <<~PATTERN
(send nil? :open $!str ...)
PATTERN
def on_send(node)
open?(node) do |code|
return if safe?(code)
add_offense(node.loc.selector)
end
end
private
def safe?(node)
if simple_string?(node)
safe_argument?(node.str_content)
elsif composite_string?(node)
safe?(node.children.first)
else
false
end
end
def safe_argument?(argument)
!argument.empty? && !argument.start_with?('|')
end
def simple_string?(node)
node.str_type?
end
def composite_string?(node)
interpolated_string?(node) || concatenated_string?(node)
end
def interpolated_string?(node)
node.dstr_type?
end
def concatenated_string?(node)
node.send_type? && node.method?(:+) && node.receiver.str_type?
end
end
end
end
end
| 25.356164 | 78 | 0.551053 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.