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
|
---|---|---|---|---|---|
1a15e2e79ba2253b44dae8e6f08e1f32fd838f26 | 1,953 | class Rubberband < Formula
desc "Audio time stretcher tool and library"
homepage "https://breakfastquay.com/rubberband/"
url "https://breakfastquay.com/files/releases/rubberband-1.8.2.tar.bz2"
sha256 "86bed06b7115b64441d32ae53634fcc0539a50b9b648ef87443f936782f6c3ca"
revision 1
head "https://bitbucket.org/breakfastquay/rubberband/", :using => :hg
bottle do
cellar :any
sha256 "e100d79a7c55a6ba5642d0ce9e005971bdab26e8b7a0cdec011e21db19ccd767" => :mojave
sha256 "7dd91b6d0baee3f08704fb8dae4ced59725ef23a921dbf00c4db3a39f2119c63" => :high_sierra
sha256 "3fead448ab4b7e72a624cf85e82b0d1965ea8be224b95f43a24f56c248b9ec1e" => :sierra
sha256 "965110230f35d93876ec006522145b35a2e8168bb0202e7666d786f1e8262ce1" => :el_capitan
end
depends_on "pkg-config" => :build
depends_on "libsamplerate"
depends_on "libsndfile"
unless OS.mac?
depends_on "fftw"
depends_on "vamp-plugin-sdk"
end
def install
unless OS.mac?
system "./configure",
"--disable-debug",
"--disable-dependency-tracking",
"--disable-silent-rules",
"--prefix=#{prefix}"
system "make", "install"
return
end
system "make", "-f", "Makefile.osx"
# HACK: Manual install because "make install" is broken
# https://github.com/Homebrew/homebrew-core/issues/28660
bin.install "bin/rubberband"
lib.install "lib/librubberband.dylib" => "librubberband.2.1.1.dylib"
lib.install_symlink lib/"librubberband.2.1.1.dylib" => "librubberband.2.dylib"
lib.install_symlink lib/"librubberband.2.1.1.dylib" => "librubberband.dylib"
include.install "rubberband"
cp "rubberband.pc.in", "rubberband.pc"
inreplace "rubberband.pc", "%PREFIX%", opt_prefix
(lib/"pkgconfig").install "rubberband.pc"
end
test do
output = shell_output("#{bin}/rubberband -t2 #{test_fixtures("test.wav")} out.wav 2>&1")
assert_match "Pass 2: Processing...", output
end
end
| 35.509091 | 93 | 0.715822 |
03ad3ff9385fe54e6df442664ffc387cc3831e7e | 4,048 | require File.expand_path(File.dirname(__FILE__) + '/test_helper')
require 'active_record/schema_dumper'
class SchemaDumperTest < Test::Unit::TestCase
def setup
teardown
end
def teardown
['V_PEOPLE', 'V_PROFILE'].each do |view|
if ActiveRecord::Base.connection.adapter_name == 'OracleEnhanced'
ActiveRecord::Base.connection.execute("
DECLARE
CURSOR C1 is SELECT view_name FROM user_views where view_name = '#{view}';
BEGIN
FOR I IN C1 LOOP
EXECUTE IMMEDIATE 'DROP VIEW '||I.view_name||'';
END LOOP;
END;
");
else
ActiveRecord::Base.connection.execute("drop view if exists #{view}")
end
end
end
def test_view
create_people_view
select_stmt = <<-HERE
select first_name, last_name, ssn from people
UNION
select first_name, last_name, ssn from people2
HERE
ActiveRecord::Base.connection.create_view(:v_profile, select_stmt, :force => true) do |v|
v.column :first_name
v.column :last_name
v.column :ssn
end
stream = StringIO.new
dumper = ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, stream)
stream.rewind
assert_equal File.open(File.dirname(__FILE__) + "/schema.#{$connection}.expected.rb", 'r').readlines, stream.readlines
end
def test_dump_and_load
create_people_view
assert_dump_and_load_succeed
end
def test_union
Person.create(:first_name => 'Joe', :last_name => 'User', :ssn => '123456789')
Person2.create(:first_name => 'Jane', :last_name => 'Doe', :ssn => '222334444')
select_stmt = <<-HERE
select first_name, last_name, ssn from people
UNION
select first_name, last_name, ssn from people2
HERE
ActiveRecord::Base.connection.create_view(:v_profile, select_stmt, :force => true) do |v|
v.column :first_name
v.column :last_name
v.column :ssn
end
assert_dump_and_load_succeed
end
def test_view_creation_order
ActiveRecord::SchemaDumper.view_creation_order << :v_people
create_people_view
assert_dump_and_load_succeed
ActiveRecord::SchemaDumper.view_creation_order.pop
end
def test_symbol_ignore
ActiveRecord::SchemaDumper.ignore_views << :v_people
create_people_view
assert_dump_and_load_succeed
ActiveRecord::SchemaDumper.ignore_views.pop
end
def test_regex_ignore
ActiveRecord::SchemaDumper.ignore_views << Regexp.new(/v_people/)
create_people_view
assert_dump_and_load_succeed
ActiveRecord::SchemaDumper.ignore_views.pop
end
def test_non_allowed_object_raises_error
create_people_view
ActiveRecord::SchemaDumper.ignore_views << 0
begin
schema_file = File.dirname(__FILE__) + "/schema.#{$connection}.out.rb"
File.open(schema_file, "w") do |file|
assert_raise(StandardError) do
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
end
ensure
ActiveRecord::SchemaDumper.ignore_views.pop
end
end
def test_logging_error
ActiveRecord::SchemaDumper.ignore_views << 0
old_logger = ActiveRecord::Base.logger
begin
mock_logger = flexmock('logger', :error => nil)
mock_logger.should_receive(:error)
ActiveRecord::Base.logger = mock_logger
schema_file = File.dirname(__FILE__) + "/schema.#{$connection}.out.rb"
File.open(schema_file, "w") do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
ensure
ActiveRecord::SchemaDumper.ignore_views.pop
ActiveRecord::Base.logger = old_logger
end
end
def assert_dump_and_load_succeed
schema_file = File.dirname(__FILE__) + "/schema.#{$connection}.out.rb"
assert_nothing_raised do
File.open(schema_file, "w") do |file|
ActiveRecord::SchemaDumper.dump(ActiveRecord::Base.connection, file)
end
end
assert_nothing_raised do
load(schema_file)
end
end
end
| 30.900763 | 122 | 0.687006 |
ab251394895350729885d7c1ecca4be5e8cd1bfe | 733 | cask "opera-developer" do
version "72.0.3791.0"
sha256 "0cfbe2683f6397e86a532bc95e294ec9becec3c8b42612707108d316185e504e"
url "https://get.geo.opera.com/pub/opera-developer/#{version}/mac/Opera_Developer_#{version}_Setup.dmg"
name "Opera Developer"
homepage "https://www.opera.com/computer/beta"
auto_updates true
app "Opera Developer.app"
zap trash: [
"~/Library/Application Support/com.operasoftware.OperaDeveloper",
"~/Library/Caches/com.operasoftware.OperaDeveloper",
"~/Library/Cookies/com.operasoftware.OperaDeveloper.binarycookies",
"~/Library/Preferences/com.operasoftware.OperaDeveloper.plist",
"~/Library/Saved Application State/com.operasoftware.OperaDeveloper.savedState",
]
end
| 34.904762 | 105 | 0.768076 |
1db9bfde9444c1d3aa0d2a76b45e24560f972e77 | 1,624 | #
# Be sure to run `pod lib lint iOSViews.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 = 'iOSViews'
s.version = '0.1.0'
s.summary = 'A short description of iOSViews.'
# 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/[email protected]/iOSViews'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { '[email protected]' => '[email protected]' }
s.source = { :git => 'https://github.com/[email protected]/iOSViews.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'iOSViews/Classes/**/*'
# s.resource_bundles = {
# 'iOSViews' => ['iOSViews/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 37.767442 | 115 | 0.639778 |
11343484006fb4247f10413829568c39e9e090d8 | 302 | class CreateUsers < ActiveRecord::Migration[5.1]
def change
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :email
t.string :password_digest
t.string :city
t.string :bio
t.string :img_url
t.timestamps
end
end
end
| 20.133333 | 48 | 0.629139 |
ed0215bda9d0d2354f5868477e1354cfc42842ad | 14,964 | # frozen_string_literal: true
require "fileutils"
require "digest/md5"
require "rails/version" unless defined?(Rails::VERSION)
require "open-uri"
require "uri"
require "rails/generators"
require "active_support/core_ext/array/extract_options"
module Rails
module Generators
class AppBase < Base # :nodoc:
include Database
include AppName
attr_accessor :rails_template
add_shebang_option!
argument :app_path, type: :string
def self.strict_args_position
false
end
def self.add_shared_options_for(name)
class_option :template, type: :string, aliases: "-m",
desc: "Path to some #{name} template (can be a filesystem path or URL)"
class_option :database, type: :string, aliases: "-d", default: "sqlite3",
desc: "Preconfigure for selected database (options: #{DATABASES.join('/')})"
class_option :skip_gemfile, type: :boolean, default: false,
desc: "Don't create a Gemfile"
class_option :skip_git, type: :boolean, aliases: "-G", default: false,
desc: "Skip .gitignore file"
class_option :skip_keeps, type: :boolean, default: false,
desc: "Skip source control .keep files"
class_option :skip_action_mailer, type: :boolean, aliases: "-M",
default: false,
desc: "Skip Action Mailer files"
class_option :skip_action_mailbox, type: :boolean, default: false,
desc: "Skip Action Mailbox gem"
class_option :skip_action_text, type: :boolean, default: false,
desc: "Skip Action Text gem"
class_option :skip_active_record, type: :boolean, aliases: "-O", default: false,
desc: "Skip Active Record files"
class_option :skip_active_storage, type: :boolean, default: false,
desc: "Skip Active Storage files"
class_option :skip_puma, type: :boolean, aliases: "-P", default: false,
desc: "Skip Puma related files"
class_option :skip_action_cable, type: :boolean, aliases: "-C", default: false,
desc: "Skip Action Cable files"
class_option :skip_sprockets, type: :boolean, aliases: "-S", default: false,
desc: "Skip Sprockets files"
class_option :skip_spring, type: :boolean, default: false,
desc: "Don't install Spring application preloader"
class_option :skip_listen, type: :boolean, default: false,
desc: "Don't generate configuration that depends on the listen gem"
class_option :skip_javascript, type: :boolean, aliases: "-J", default: name == "plugin",
desc: "Skip JavaScript files"
class_option :skip_turbolinks, type: :boolean, default: false,
desc: "Skip turbolinks gem"
class_option :skip_test, type: :boolean, aliases: "-T", default: false,
desc: "Skip test files"
class_option :skip_system_test, type: :boolean, default: false,
desc: "Skip system test files"
class_option :skip_bootsnap, type: :boolean, default: false,
desc: "Skip bootsnap gem"
class_option :dev, type: :boolean, default: false,
desc: "Setup the #{name} with Gemfile pointing to your Rails checkout"
class_option :edge, type: :boolean, default: false,
desc: "Setup the #{name} with Gemfile pointing to Rails repository"
class_option :rc, type: :string, default: nil,
desc: "Path to file containing extra configuration options for rails command"
class_option :no_rc, type: :boolean, default: false,
desc: "Skip loading of extra configuration options from .railsrc file"
class_option :help, type: :boolean, aliases: "-h", group: :rails,
desc: "Show this help message and quit"
end
def initialize(*args)
@gem_filter = lambda { |gem| true }
@extra_entries = []
super
end
private
def gemfile_entry(name, *args) # :doc:
options = args.extract_options!
version = args.first
github = options[:github]
path = options[:path]
if github
@extra_entries << GemfileEntry.github(name, github)
elsif path
@extra_entries << GemfileEntry.path(name, path)
else
@extra_entries << GemfileEntry.version(name, version)
end
self
end
def gemfile_entries # :doc:
[rails_gemfile_entry,
database_gemfile_entry,
web_server_gemfile_entry,
assets_gemfile_entry,
webpacker_gemfile_entry,
javascript_gemfile_entry,
jbuilder_gemfile_entry,
psych_gemfile_entry,
cable_gemfile_entry,
@extra_entries].flatten.find_all(&@gem_filter)
end
def add_gem_entry_filter # :doc:
@gem_filter = lambda { |next_filter, entry|
yield(entry) && next_filter.call(entry)
}.curry[@gem_filter]
end
def builder # :doc:
@builder ||= begin
builder_class = get_builder_class
builder_class.include(ActionMethods)
builder_class.new(self)
end
end
def build(meth, *args) # :doc:
builder.send(meth, *args) if builder.respond_to?(meth)
end
def create_root # :doc:
valid_const?
empty_directory "."
FileUtils.cd(destination_root) unless options[:pretend]
end
def apply_rails_template # :doc:
apply rails_template if rails_template
rescue Thor::Error, LoadError, Errno::ENOENT => e
raise Error, "The template [#{rails_template}] could not be loaded. Error: #{e}"
end
def set_default_accessors! # :doc:
self.destination_root = File.expand_path(app_path, destination_root)
self.rails_template = \
case options[:template]
when /^https?:\/\//
options[:template]
when String
File.expand_path(options[:template], Dir.pwd)
else
options[:template]
end
end
def database_gemfile_entry # :doc:
return [] if options[:skip_active_record]
gem_name, gem_version = gem_for_database
GemfileEntry.version gem_name, gem_version,
"Use #{options[:database]} as the database for Active Record"
end
def web_server_gemfile_entry # :doc:
return [] if options[:skip_puma]
comment = "Use Puma as the app server"
GemfileEntry.new("puma", "~> 3.11", comment)
end
def include_all_railties? # :doc:
[
options.values_at(
:skip_active_record,
:skip_action_mailer,
:skip_test,
:skip_sprockets,
:skip_action_cable
),
skip_active_storage?,
skip_action_mailbox?,
skip_action_text?
].flatten.none?
end
def comment_if(value) # :doc:
question = "#{value}?"
comment =
if respond_to?(question, true)
send(question)
else
options[value]
end
comment ? "# " : ""
end
def keeps? # :doc:
!options[:skip_keeps]
end
def sqlite3? # :doc:
!options[:skip_active_record] && options[:database] == "sqlite3"
end
def skip_active_storage? # :doc:
options[:skip_active_storage] || options[:skip_active_record]
end
def skip_action_mailbox? # :doc:
options[:skip_action_mailbox] || skip_active_storage?
end
def skip_action_text? # :doc:
options[:skip_action_text] || skip_active_storage?
end
class GemfileEntry < Struct.new(:name, :version, :comment, :options, :commented_out)
def initialize(name, version, comment, options = {}, commented_out = false)
super
end
def self.github(name, github, branch = nil, comment = nil)
if branch
new(name, nil, comment, github: github, branch: branch)
else
new(name, nil, comment, github: github)
end
end
def self.version(name, version, comment = nil)
new(name, version, comment)
end
def self.path(name, path, comment = nil)
new(name, nil, comment, path: path)
end
def version
version = super
if version.is_a?(Array)
version.join("', '")
else
version
end
end
end
def rails_gemfile_entry
if options.dev?
[
GemfileEntry.path("rails", Rails::Generators::RAILS_DEV_PATH)
]
elsif options.edge?
[
GemfileEntry.github("rails", "rails/rails")
]
else
[GemfileEntry.version("rails",
rails_version_specifier,
"Bundle edge Rails instead: gem 'rails', github: 'rails/rails'")]
end
end
def rails_version_specifier(gem_version = Rails.gem_version)
if gem_version.segments.size == 3 || gem_version.release.segments.size == 3
# ~> 1.2.3
# ~> 1.2.3.pre4
"~> #{gem_version}"
else
# ~> 1.2.3, >= 1.2.3.4
# ~> 1.2.3, >= 1.2.3.4.pre5
patch = gem_version.segments[0, 3].join(".")
["~> #{patch}", ">= #{gem_version}"]
end
end
def assets_gemfile_entry
return [] if options[:skip_sprockets]
GemfileEntry.version("sass-rails", ">= 5", "Use SCSS for stylesheets")
end
def webpacker_gemfile_entry
return [] if options[:skip_javascript]
if options.dev? || options.edge?
GemfileEntry.github "webpacker", "rails/webpacker", nil, "Use development version of Webpacker"
else
GemfileEntry.version "webpacker", "~> 4.0", "Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker"
end
end
def jbuilder_gemfile_entry
comment = "Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder"
GemfileEntry.new "jbuilder", "~> 2.7", comment, {}, options[:api]
end
def javascript_gemfile_entry
if options[:skip_javascript] || options[:skip_turbolinks]
[]
else
[ GemfileEntry.version("turbolinks", "~> 5",
"Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks") ]
end
end
def psych_gemfile_entry
return [] unless defined?(Rubinius)
comment = "Use Psych as the YAML engine, instead of Syck, so serialized " \
"data can be read safely from different rubies (see http://git.io/uuLVag)"
GemfileEntry.new("psych", "~> 2.0", comment, platforms: :rbx)
end
def cable_gemfile_entry
return [] if options[:skip_action_cable]
comment = "Use Redis adapter to run Action Cable in production"
gems = []
gems << GemfileEntry.new("redis", "~> 4.0", comment, {}, true)
gems
end
def bundle_command(command, env = {})
say_status :run, "bundle #{command}"
# We are going to shell out rather than invoking Bundler::CLI.new(command)
# because `rails new` loads the Thor gem and on the other hand bundler uses
# its own vendored Thor, which could be a different version. Running both
# things in the same process is a recipe for a night with paracetamol.
#
# Thanks to James Tucker for the Gem tricks involved in this call.
_bundle_command = Gem.bin_path("bundler", "bundle")
require "bundler"
Bundler.with_original_env do
exec_bundle_command(_bundle_command, command, env)
end
end
def exec_bundle_command(bundle_command, command, env)
full_command = %Q["#{Gem.ruby}" "#{bundle_command}" #{command}]
if options[:quiet]
system(env, full_command, out: File::NULL)
else
system(env, full_command)
end
end
def bundle_install?
!(options[:skip_gemfile] || options[:skip_bundle] || options[:pretend])
end
def spring_install?
!options[:skip_spring] && !options.dev? && Process.respond_to?(:fork) && !RUBY_PLATFORM.include?("cygwin")
end
def webpack_install?
!(options[:skip_javascript] || options[:skip_webpack_install])
end
def depends_on_system_test?
!(options[:skip_system_test] || options[:skip_test] || options[:api])
end
def depend_on_listen?
!options[:skip_listen] && os_supports_listen_out_of_the_box?
end
def depend_on_bootsnap?
!options[:skip_bootsnap] && !options[:dev] && !defined?(JRUBY_VERSION)
end
def os_supports_listen_out_of_the_box?
/darwin|linux/.match?(RbConfig::CONFIG["host_os"])
end
def run_bundle
bundle_command("install", "BUNDLE_IGNORE_MESSAGES" => "1") if bundle_install?
end
def run_webpack
if webpack_install?
rails_command "webpacker:install"
rails_command "webpacker:install:#{options[:webpack]}" if options[:webpack] && options[:webpack] != "webpack"
end
end
def generate_bundler_binstub
if bundle_install?
bundle_command("binstubs bundler")
end
end
def generate_spring_binstubs
if bundle_install? && spring_install?
bundle_command("exec spring binstub --all")
end
end
def empty_directory_with_keep_file(destination, config = {})
empty_directory(destination, config)
keep_file(destination)
end
def keep_file(destination)
create_file("#{destination}/.keep") if keeps?
end
end
end
end
| 34.009091 | 132 | 0.560011 |
5d0117e54247b560dadfc7e12578a4ccf0d8e04b | 1,543 | #
# Be sure to run `pod lib lint NBButton.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 = 'NBButton'
s.version = '0.1.0'
s.summary = '常见的按钮位置改变'
# 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 = 'https://github.com/shiyingfeng/NBButton'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'shiyingfeng' => '[email protected]' }
s.source = { :git => 'https://github.com/shiyingfeng/NBButton.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '8.0'
s.source_files = 'NBButton/Classes/**/*'
# s.resource_bundles = {
# 'NBButton' => ['NBButton/Assets/*.png']
# }
# s.public_header_files = 'Pod/Classes/**/*.h'
# s.frameworks = 'UIKit', 'MapKit'
# s.dependency 'AFNetworking', '~> 2.3'
end
| 35.883721 | 104 | 0.634478 |
874f9eb91ac39a759bb951700115beb5d21e2ce8 | 3,699 | require 'spec_helper'
describe 'Ad Hoc Option Values / Ad Hoc Variant Exclusions ', :js, type: :feature do
describe 'test add links / remove links / add options values / remove options values/ update and cancel buttons' do
extend Spree::TestingSupport::AuthorizationHelpers::Request
include IntegrationHelpers
stub_authorization!
let!(:test_product) { create(:product, name: 'Test Product', price: 12.99) }
let(:color_select) { "ad_hoc_option_type[#{test_product.ad_hoc_option_types.first.id}]" }
let(:size_select) { "ad_hoc_option_type[#{test_product.ad_hoc_option_types.last.id}]" }
it 'ad hoc option types add/removes the associated option value when clicked' do
setup_option_types_plus_ad_hoc_option_type_color(test_product)
go_to_product_page
go_to_edit_ad_hoc_option_type
expect(all('#option_values tr').length).to eq(3)
find('.fa.fa-trash', match: :first).click
accept_alert
expect(page).to have_content(/Ad Hoc Option Value Deleted/i)
expect(all('#option_values tr').length).to eq(2)
go_to_product_page
go_to_edit_ad_hoc_option_type
expect(all('#option_values tr').length).to eq(2)
#add
within('#available_option-values') do
find('.fa.fa-plus', match: :first).click
end
wait_for_ajax
expect(all('#option_values tr').length).to eq(3)
#check the update
check 'ad_hoc_option_type_is_required'
within("#ad_hoc_option_type .option_value", match: :first) do
fill_in 'ad_hoc_option_type_ad_hoc_option_values_attributes_0_price_modifier', with: '1'
check 'ad_hoc_option_type_ad_hoc_option_values_attributes_0_selected'
end
click_on('Update')
expect(page).to have_content(/Ad hoc option type "color" has been successfully updated!/i)
find('#ad_hoc_option_types .fa.fa-edit', match: :first).click
expect find('#ad_hoc_option_type_is_required').should be_checked
within("#ad_hoc_option_type .option_value", match: :first) do
expect(page).to have_selector("input[value='1.0']")
expect find('#ad_hoc_option_type_ad_hoc_option_values_attributes_0_selected').should be_checked
end
click_on('Cancel')
expect(page).to have_content(/Add Option Types/i)
#test deleting a option type
find('.fa.fa-trash').click
accept_alert
expect(page).to have_content(/Ad Hoc Option Type Deleted/i)
wait_for_ajax
expect(all('#ad_hoc_option_types tbody tr').length).to eq(0)
#test adding an option type
click_on('Add Ad Hoc Option Type')
find('.fa.fa-plus', match: :first).click
click_on('Update')
expect(all('#ad_hoc_option_types tr').length).to eq(2)
end
### ad hoc variant exclusions
it 'ad hoc variant exclusions add/removes the associated option value when clicked' do
setup_option_types_plus_ad_hoc_option_type_color(test_product)
go_to_product_page
go_to_ad_hoc_variant_exclusions
expect(page).to have_content(/You only need to configure exclusions when you have more than one ad hoc option type/i)
setup_option_types_plus_ad_hoc_option_type_size(test_product)
go_to_product_page
go_to_ad_hoc_variant_exclusions
expect(page).to have_content(/No Ad hoc variant exclusion found/i)
click_on('Add One')
wait_for_ajax
select "red", from: color_select
select "small", from: size_select
click_on('Create')
expect(all('#listing_ad_hoc_variant_exclusions tr').length).to eq(2)
find('.fa.fa-trash').click
accept_alert
expect(page).to have_content(/Exclusion Removed/i)
end
end
end
| 35.912621 | 123 | 0.707218 |
4a92e1a8a4db8a02c1b2844ff730001d5f73bca9 | 831 | require "pact_broker/webhooks/http_request_with_redacted_headers"
require "pact_broker/webhooks/http_response_with_utf_8_safe_body"
module PactBroker
module Webhooks
class WebhookExecutionResult
attr_reader :request, :response, :logs, :error
def initialize(request, response, logs, error = nil)
@request = PactBroker::Webhooks::HttpRequestWithRedactedHeaders.new(request)
@response = response ? PactBroker::Webhooks::HttpResponseWithUtf8SafeBody.new(response) : nil
@logs = logs
@error = error
end
def success?
if response
# Response HTTP Code must be in success list otherwise it is false
PactBroker.configuration.webhook_http_code_success.include? response.code.to_i
else
false
end
end
end
end
end
| 30.777778 | 101 | 0.700361 |
4a9230f8b3eba6468c63a8753e562d4d659f4644 | 4,184 | require File.expand_path('../../../spec_helper', __FILE__)
require File.expand_path('../fixtures/common', __FILE__)
require File.expand_path('../shared/glob', __FILE__)
describe "Dir.glob" do
it_behaves_like :dir_glob, :glob
end
describe "Dir.glob" do
it_behaves_like :dir_glob_recursive, :glob
end
describe "Dir.glob" do
before :each do
DirSpecs.create_mock_dirs
@cwd = Dir.pwd
Dir.chdir DirSpecs.mock_dir
end
after :each do
Dir.chdir @cwd
DirSpecs.delete_mock_dirs
end
it "can take an array of patterns" do
Dir.glob(["file_o*", "file_t*"]).should ==
%w!file_one.ext file_two.ext!
end
it "calls #to_path to convert multiple patterns" do
pat1 = mock('file_one.ext')
pat1.should_receive(:to_path).and_return('file_one.ext')
pat2 = mock('file_two.ext')
pat2.should_receive(:to_path).and_return('file_two.ext')
Dir.glob([pat1, pat2]).should == %w[file_one.ext file_two.ext]
end
it "matches both dot and non-dotfiles with '*' and option File::FNM_DOTMATCH" do
Dir.glob('*', File::FNM_DOTMATCH).sort.should == DirSpecs.expected_paths
end
it "matches files with any beginning with '*<non-special characters>' and option File::FNM_DOTMATCH" do
Dir.glob('*file', File::FNM_DOTMATCH).sort.should == %w|.dotfile nondotfile|.sort
end
it "matches any files in the current directory with '**' and option File::FNM_DOTMATCH" do
Dir.glob('**', File::FNM_DOTMATCH).sort.should == DirSpecs.expected_paths
end
it "recursively matches any subdirectories except './' or '../' with '**/' from the current directory and option File::FNM_DOTMATCH" do
expected = %w[
.dotsubdir/
brace/
deeply/
deeply/nested/
deeply/nested/directory/
deeply/nested/directory/structure/
dir/
special/
special/test{1}/
subdir_one/
subdir_two/
]
Dir.glob('**/', File::FNM_DOTMATCH).sort.should == expected
end
# This is a separate case to check **/ coming after a constant
# directory as well.
it "recursively matches any subdirectories except './' or '../' with '**/' and option File::FNM_DOTMATCH" do
expected = %w[
./
./.dotsubdir/
./brace/
./deeply/
./deeply/nested/
./deeply/nested/directory/
./deeply/nested/directory/structure/
./dir/
./special/
./special/test{1}/
./subdir_one/
./subdir_two/
]
Dir.glob('./**/', File::FNM_DOTMATCH).sort.should == expected
end
it "matches a list of paths by concatenating their individual results" do
expected = %w[
deeply/
deeply/nested/
deeply/nested/directory/
deeply/nested/directory/structure/
subdir_two/nondotfile
subdir_two/nondotfile.ext
]
Dir.glob('{deeply/**/,subdir_two/*}').sort.should == expected
end
it "accepts a block and yields it with each elements" do
ary = []
ret = Dir.glob(["file_o*", "file_t*"]) { |t| ary << t }
ret.should be_nil
ary.should == %w!file_one.ext file_two.ext!
end
it "ignores non-dirs when traversing recursively" do
touch "spec"
Dir.glob("spec/**/*.rb").should == []
end
it "matches nothing when given an empty list of paths" do
Dir.glob('{}').should == []
end
it "handles infinite directory wildcards" do
Dir.glob('**/**/**').empty?.should == false
end
platform_is_not(:windows) do
it "matches the literal character '\\' with option File::FNM_NOESCAPE" do
Dir.mkdir 'foo?bar'
begin
Dir.glob('foo?bar', File::FNM_NOESCAPE).should == %w|foo?bar|
Dir.glob('foo\?bar', File::FNM_NOESCAPE).should == []
ensure
Dir.rmdir 'foo?bar'
end
Dir.mkdir 'foo\?bar'
begin
Dir.glob('foo\?bar', File::FNM_NOESCAPE).should == %w|foo\\?bar|
ensure
Dir.rmdir 'foo\?bar'
end
end
it "returns nil for directories current user has no permission to read" do
Dir.mkdir('no_permission')
File.chmod(0, 'no_permission')
begin
Dir.glob('no_permission/*').should == []
ensure
Dir.rmdir('no_permission')
end
end
end
end
| 26.649682 | 137 | 0.633843 |
79f9f0e31c9a882c80c0ab2969b7edfa34a79e45 | 1,004 | #
# Be sure to run `pod spec lint SinoroadSDK.podspec' to ensure this is a
# valid spec and to remove all comments including this before submitting the spec.
#
# To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html
# To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/
#
Pod::Spec.new do |s|
s.name = 'SinoroadSDK'
s.version = '4.2.1'
s.summary = 'Sinoroad ios sdk'
s.homepage = 'https://github.com/DKJone/SinoroadSDK'
s.license = { :type => 'Apache', :file => 'License' }
s.author = { 'DKJone' => '[email protected]' }
s.platform = :ios, '8.0'
s.source = { :git => 'https://github.com/DKJone/SinoroadSDK.git', :tag => s.version }
s.source_files = 'SinoroadSDK/Sources/**/*.{swift,m,h}'
# 依赖项
s.dependency 'Alamofire'
s.dependency 'Moya'
s.dependency 'SwiftyJSON'
s.dependency 'PromiseKit'
s.dependency 'SnapKit'
s.dependency 'MBProgressHUD'
end | 35.857143 | 94 | 0.651394 |
7a0e5ca935461a749f9d51b736862981c6067ff8 | 677 | require File.expand_path('../../../spec_helper', __FILE__)
require 'prime'
describe "Prime.new" do
it "returns a new object representing the set of prime numbers" do
Prime.new.should be_kind_of(Prime)
end
it "returns a object with obsolete featrues" do
Prime.new.should be_kind_of(Prime::OldCompatibility)
Prime.new.should respond_to(:succ)
Prime.new.should respond_to(:next)
end
it "complains that the method is obsolete" do
lambda { Prime.new }.should complain(/obsolete.*use.*Prime::instance/)
end
it "raises a ArgumentError when is called with some arguments" do
lambda { Prime.new(1) }.should raise_error(ArgumentError)
end
end
| 29.434783 | 74 | 0.728213 |
ed4dcfe66d07ccb51d6c3e983d9f9867c71f51f4 | 1,375 | module Infoboxer
describe Navigation::Wikipath do
include Saharspec::Util
let(:document) {
Parser.document(multiline(%{
|Test in first ''paragraph''
|
| {{Use dmy dates|date=July 2014}}
|
|=== Section 1 ===
|
|{| some=table
||With
|* cool list
|* ''And'' deep test
|* some more
||}
|
| {{template}}
}))
}
subject { ->(path) { document.wikipath(path) } }
its(['//template']) { is_expected.to be_a(Tree::Nodes).and all be_a(Tree::Template) }
its(['//template']) { is_expected.not_to be_empty }
its(['//table//list//italic']) { is_expected.to have_attributes(text: 'And') }
its(['//template[name=/^Use/]']) {
is_expected
.to include(have_attributes(name: 'Use dmy dates'))
.and not_include(have_attributes(name: 'template'))
}
its(['//table//list/list_item[first]']) {
is_expected
.to include(have_attributes(text_: '* cool list'))
.and not_include(have_attributes(text_: '* some more'))
}
its(['//template/var[name=date]']) { is_expected.to include(be_a(Tree::Var).and(have_attributes(name: 'date'))) }
its(['/section']) { is_expected.not_to be_empty }
its(['/section[heading=Section 1]']) { is_expected.to eq [document.sections.first] }
end
end
| 31.25 | 117 | 0.568 |
91803f2f053e0c19c6bd655b9c44d529eb367a9f | 2,938 | # Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::Network::Mgmt::V2019_06_01
module Models
#
# Response for the ListVirtualNetworkGateways API service call.
#
class VirtualNetworkGatewayListResult
include MsRestAzure
include MsRest::JSONable
# @return [Array<VirtualNetworkGateway>] Gets a list of
# VirtualNetworkGateway resources that exists in a resource group.
attr_accessor :value
# @return [String] The URL to get the next set of results.
attr_accessor :next_link
# return [Proc] with next page method call.
attr_accessor :next_method
#
# Gets the rest of the items for the request, enabling auto-pagination.
#
# @return [Array<VirtualNetworkGateway>] operation results.
#
def get_all_items
items = @value
page = self
while page.next_link != nil && !page.next_link.strip.empty? do
page = page.get_next_page
items.concat(page.value)
end
items
end
#
# Gets the next page of results.
#
# @return [VirtualNetworkGatewayListResult] with next page content.
#
def get_next_page
response = @next_method.call(@next_link).value! unless @next_method.nil?
unless response.nil?
@next_link = response.body.next_link
@value = response.body.value
self
end
end
#
# Mapper for VirtualNetworkGatewayListResult class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'VirtualNetworkGatewayListResult',
type: {
name: 'Composite',
class_name: 'VirtualNetworkGatewayListResult',
model_properties: {
value: {
client_side_validation: true,
required: false,
serialized_name: 'value',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'VirtualNetworkGatewayElementType',
type: {
name: 'Composite',
class_name: 'VirtualNetworkGateway'
}
}
}
},
next_link: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'nextLink',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 29.38 | 80 | 0.542886 |
0123fdcfd678640819db252ca3899af34d35b5e4 | 277 | # frozen_string_literal: true
i = 0
json.array! @article.revisions.each do |revision|
i += 1
json.index i
json.rev_id revision.mw_rev_id
json.wp10 revision.wp10
json.date revision.date
json.username revision.user.username
json.characters revision.characters
end
| 21.307692 | 49 | 0.765343 |
62ce07299367fd45bf09a3b608ebadb0b30ca174 | 849 | class Parse
def initialize(file)
@pages_and_ip = []
@pages = []
File.open(file, "r") do |line|
line.each do |x|
@pages_and_ip << x
@pages << x.split.first
end
end
end
def page_views
ranked_pages = Hash.new
@pages.each{|x| ranked_pages[x] = @pages.count(x)}
puts ranked_pages.sort_by{|page, views| views}.reverse
end
def unique_views
page_array = {}
@pages.each{|pg| page_array[pg] = []}
@pages_and_ip.each do |x|
if page_array.include?(x.split.first)
if !page_array[x.split.first].include?(x.split.last)
page_array[x.split.first] << x.split.last
end
end
end
ranked_pages = {}
page_array.each do |x, y|
ranked_pages[x] = y.length
end
puts ranked_pages.sort_by{|pg, ip| ip }.reverse
end
end
| 18.456522 | 60 | 0.585395 |
6a04f85848249db6c2cffa72e98e483621af3802 | 2,629 | module Shoppe
class Order < ActiveRecord::Base
# The country which this order should be billed to
#
# @return [Shoppe::Country]
belongs_to :billing_country, class_name: 'Shoppe::Country', foreign_key: 'billing_country_id'
# Payments which have been stored for the order
has_many :payments, dependent: :destroy, class_name: 'Shoppe::Payment'
# Validations
with_options if: proc { |o| !o.building? } do |order|
order.validates :first_name, presence: true
order.validates :last_name, presence: true
order.validates :billing_address1, presence: true
order.validates :billing_address3, presence: true
order.validates :billing_address4, presence: true
order.validates :billing_postcode, presence: true
order.validates :billing_country, presence: true
end
# The name for billing purposes
#
# @return [String]
def billing_name
company.blank? ? full_name : "#{full_name} (#{company})"
end
# The total cost of the order
#
# @return [BigDecimal]
def total_cost
delivery_cost_price +
order_items.inject(BigDecimal(0)) { |t, i| t + i.total_cost }
end
# Return the price for the order
#
# @return [BigDecimal]
def profit
total_before_tax - total_cost
end
# The total price of all items in the basket excluding delivery
#
# @return [BigDecimal]
def items_sub_total
order_items.inject(BigDecimal(0)) { |t, i| t + i.sub_total }
end
# The total price of the order before tax
#
# @return [BigDecimal]
def total_before_tax
delivery_price + items_sub_total
end
# The total amount of tax due on this order
#
# @return [BigDecimal]
def tax
delivery_tax_amount +
order_items.inject(BigDecimal(0)) { |t, i| t + i.tax_amount }
end
# The total of the order including tax
#
# @return [BigDecimal]
def total
delivery_price +
delivery_tax_amount +
order_items.inject(BigDecimal(0)) { |t, i| t + i.total }
end
# The total amount due on the order
#
# @return [BigDecimal]
def balance
@balance ||= total - amount_paid
end
# Is there a payment still outstanding on this order?
#
# @return [Boolean]
def payment_outstanding?
balance > BigDecimal(0)
end
# Has this order been paid in full?
#
# @return [Boolean]
def paid_in_full?
!payment_outstanding?
end
# Is the order invoiced?
#
# @return [Boolean]
def invoiced?
!invoice_number.blank?
end
end
end
| 25.278846 | 97 | 0.638646 |
bfd5ed031c386718e5f66a8da36042f54f3ba289 | 144 | # Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_dev_and_jobs_session'
| 36 | 82 | 0.8125 |
6251e05c60f55ee03f96afdbf1ce8e2137578ff1 | 40 | module Certutil
VERSION = "0.2.0"
end
| 10 | 19 | 0.675 |
ff4a693ba02386addd44f6dcbf9f33d41f6490ad | 584 | require './config/environment'
class ApplicationController < Sinatra::Base
configure do
set :public_folder, 'public'
set :views, 'app/views'
enable :sessions
set :session_secret, "glasspassion"
end
get "/" do
erb :welcome
end
helpers do
def current_user
@current_user ||= User.find_by(id: session[:user_id]) if session[:user_id]
end
def logged_in?
!!current_user
end
def redirect_if_not_logged_in
if !logged_in?
redirect "/login?error=Please login to continue"
end
end
end
end
| 16.685714 | 80 | 0.638699 |
1ded521fe1f54511f40bd40d221f6f6cc529730b | 1,901 | module Boards
module Issues
class MoveService < Boards::BaseService
prepend EE::Boards::Issues::MoveService
def execute(issue)
return false unless can?(current_user, :update_issue, issue)
return false if issue_params.empty?
update(issue)
end
private
def board
@board ||= parent.boards.find(params[:board_id])
end
def move_between_lists?
moving_from_list.present? && moving_to_list.present? &&
moving_from_list != moving_to_list
end
def moving_from_list
@moving_from_list ||= board.lists.find_by(id: params[:from_list_id])
end
def moving_to_list
@moving_to_list ||= board.lists.find_by(id: params[:to_list_id])
end
def update(issue)
::Issues::UpdateService.new(issue.project, current_user, issue_params).execute(issue)
end
def issue_params
attrs = {}
if move_between_lists?
attrs.merge!(
add_label_ids: add_label_ids,
remove_label_ids: remove_label_ids,
state_event: issue_state
)
end
attrs[:move_between_ids] = move_between_ids if move_between_ids
attrs
end
def issue_state
return 'reopen' if moving_from_list.closed?
return 'close' if moving_to_list.closed?
end
def add_label_ids
[moving_to_list.label_id].compact
end
def remove_label_ids
label_ids =
if moving_to_list.movable?
moving_from_list.label_id
else
Label.on_project_boards(parent.id).pluck(:label_id)
end
Array(label_ids).compact
end
def move_between_ids
return unless params[:move_after_id] || params[:move_before_id]
[params[:move_after_id], params[:move_before_id]]
end
end
end
end
| 23.7625 | 93 | 0.6202 |
ac517b59af1dc8bdcc68cabf93d20779a7b0b6c4 | 2,358 | # encoding: utf-8
# frozen_string_literal: true
#
# = Message-ID Field
#
# The Message-ID field inherits from StructuredField and handles the
# Message-ID: header field in the email.
#
# Sending message_id to a mail message will instantiate a Mail::Field object that
# has a MessageIdField as its field type. This includes all Mail::CommonMessageId
# module instance metods.
#
# Only one MessageId field can appear in a header, and syntactically it can only have
# one Message ID. The message_ids method call has been left in however as it will only
# return the one message id, ie, an array of length 1.
#
# Note that, the #message_ids method will return an array of message IDs without the
# enclosing angle brackets which per RFC are not syntactically part of the message id.
#
# == Examples:
#
# mail = Mail.new
# mail.message_id = '<[email protected]>'
# mail.message_id #=> '<[email protected]>'
# mail[:message_id] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
# mail['message_id'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
# mail['Message-ID'] #=> '#<Mail::Field:0x180e5e8 @field=#<Mail::MessageIdField:0x180e1c4
#
# mail[:message_id].message_id #=> '[email protected]'
# mail[:message_id].message_ids #=> ['[email protected]']
#
require 'mail/fields/common/common_message_id'
module Mail
class MessageIdField < StructuredField
include Mail::CommonMessageId
FIELD_NAME = 'message-id'
CAPITALIZED_FIELD = 'Message-ID'
def initialize(value = nil, charset = 'utf-8')
self.charset = charset
@uniq = 1
if Utilities.blank?(value)
self.name = CAPITALIZED_FIELD
self.value = generate_message_id
else
super(CAPITALIZED_FIELD, value, charset)
end
self.parse
self
end
def name
'Message-ID'
end
def message_ids
[message_id]
end
def to_s
"<#{message_id}>"
end
def encoded
do_encode(CAPITALIZED_FIELD)
end
def decoded
do_decode
end
private
def generate_message_id
"<#{Mail.random_tag}@#{::Socket.gethostname}.mail>"
end
end
end
| 28.071429 | 90 | 0.675997 |
2641c917cd026df04e78eeac2e7bb9549f2331f2 | 320 | class CreateFeedbookPositionHasEmployees < ActiveRecord::Migration[5.1]
def change
create_table :feedbook_position_has_employees do |t|
t.references :position, foreign_key: true
t.references :employee, foreign_key: true
t.text :notes
t.string :version
t.timestamps
end
end
end
| 24.615385 | 71 | 0.715625 |
e2b8375200f8f3eb5224bbb17391b05da219b25d | 1,194 | require 'test/unit'
require './config/initializers/01_komet_init'
require './lib/isaac_rest/search_apis_rest'
class SearchTest < Test::Unit::TestCase
include KOMETUtilities
include SearchApis
include Fixtures
FAIL_MESSAGE = 'There may be a mismatch between the generated isaac-rest.rb file and rails_komet!: '
# Called before every test method runs. Can be used
# to set up fixture information.
def setup
end
def test_search_descriptions
begin
json = YAML.load_file(FILES[Fixtures::SEARCH_DESCRIPTIONS])
results = SearchApi.new(params: nil, action: ACTION_DESCRIPTIONS, action_constants: ACTION_CONSTANTS).get_rest_class(json).send(:from_json, json)
assert(! results.results.first.nil? , 'The Search result should not be empty!')
assert(results.class.eql?(Gov::Vha::Isaac::Rest::Api1::Data::Search::RestSearchResultPage), 'The search matches should be of type Gov::Vha::Isaac::Rest::Api1::Data::Search::RestSearchResultPage.') unless results.nil?
rescue => ex
fail(FAIL_MESSAGE + ex.to_s)
end
end
# Called after every test method runs. Can be used to tear down fixture information.
def teardown
# Do nothing
end
end
| 36.181818 | 223 | 0.738693 |
39feca23773f39c41940e58961693540162ce28c | 1,020 |
lib = File.expand_path("../lib", __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require "direct_upload/version"
Gem::Specification.new do |spec|
spec.name = "direct_upload"
spec.version = DirectUpload::VERSION
spec.authors = ["Cameron Barker"]
spec.email = ["[email protected]"]
spec.summary = "Upload to AWS S3 from the model"
spec.description = "Upload to AWS S3 from the model"
spec.homepage = "https://github.com/cameronbarker/direct_upload"
spec.license = "MIT"
spec.files = `git ls-files -z`.split("\x0").reject do |f|
f.match(%r{^(test|spec|features)/})
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
spec.add_development_dependency "bundler", "~> 1.16"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "rspec", "~> 3.0"
spec.add_dependency "aws-sdk-s3", "~> 1.16"
end
| 35.172414 | 74 | 0.646078 |
d5a54b4d11729bf7d4e5e1e06e1a24fd316d2ce4 | 69 | module Marty
module Promises
module Delorean
end
end
end
| 9.857143 | 19 | 0.695652 |
6a888dcaa9e2b908d4604977ea7f35556e5cf5fb | 5,054 | #
# Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
#
# 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.
#
include Chef::Mixin::ShellOut
def load_current_resource
@pkg_publisher = new_resource.class.new(new_resource.name)
@pkg_publisher.type(new_resource.type)
@pkg_publisher.uri(new_resource.uri)
@pkg_publisher.root(new_resource.root)
@pkg_publisher.sticky(new_resource.sticky)
@pkg_publisher.non_sticky(new_resource.non_sticky)
@pkg_publisher.search_before(new_resource.search_before)
@pkg_publisher.search_after(new_resource.search_after)
@pkg_publisher.ssl_cert(new_resource.ssl_cert)
@pkg_publisher.ssl_key(new_resource.ssl_key)
@pkg_publisher.enable(new_resource.enable)
@pkg_publisher.disable(new_resource.disable)
@pkg_publisher.publisher(new_resource.name)
@pkg_publisher.proxy(new_resource.proxy)
@pkg_publisher.syspub(new_resource.syspub)
@pkg_publisher.list(list?)
@pkg_publisher.current_props(current_props?)
@pkg_publisher.info(info?)
end
action :create do
unless created?
puts "NO REPO FOUND"
Chef::Log.info("Adding pkg #{@pkg_publisher.publisher} #{@pkg_publisher.uri} ")
pkg_args = ""
if (@pkg_publisher.type == "mirror")
tmp = " -m #{@pkg_publisher.uri} "
pkg_args = pkg_args + tmp
else
tmp = " -g #{@pkg_publisher.uri} "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.sticky == true )
tmp = " --sticky "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.non_sticky == true)
tmp = " --non-sticky "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.search_before)
tmp = " --search-before #{@pkg_publisher.search_before} "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.search_after)
tmp = " --search-after #{@pkg_publisher.search_after} "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.ssl_cert)
tmp = " -c #{@pkg_publisher.ssl_cert} "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.ssl_key)
tmp = " -k #{@pkg_publisher.ssl_key} "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.enable == true)
tmp = " --enable "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.disable == true)
tmp = " --disable "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.proxy)
tmp = " --proxy #{@pkg_publisher.proxy} "
pkg_args = pkg_args + tmp
end
if (@pkg_publisher.root)
puts("pkg -R #{@pkg_publisher.root} set-publisher #{pkg_args} #{@pkg_publisher.publisher}")
shell_out!("pkg -R #{@pkg_publisher.root} set-publisher #{pkg_args} #{@pkg_publisher.publisher}")
else
puts("pkg set-publisher #{pkg_args} #{@pkg_publisher.publisher}")
shell_out!("pkg set-publisher #{pkg_args} #{@pkg_publisher.publisher}")
end
new_resource.updated_by_last_action(true)
@pkg_publisher.current_props(current_props?)
end
end
action :destroy do
if created?
puts "Removing repository"
Chef::Log.info("Destroy publisher #{@pkg_publisher.publisher}")
if @pkg_publisher.uri == ""
puts ("pkg unset-publisher #{@pkg_publisher.publisher}")
shell_out!("pkg unset-publisher #{@pkg_publisher.publisher}")
else
puts("pkg set-publisher -G #{@pkg_publisher.uri} #{@pkg_publisher.publisher}")
shell_out!("pkg set-publisher -G #{@pkg_publisher.uri} #{@pkg_publisher.publisher}")
end
new_resource.updated_by_last_action(true)
end
end
private
def created?
Chef::Log.info("Checking pkg_publisher info")
@pkg_publisher.info.zero?
end
def info?
val = 1
@list = @pkg_publisher.current_props
@list.each { |x|
item = x
puts x
if item[:uri] == @pkg_publisher.uri and item[:publisher] == @pkg_publisher.publisher
if item[:type] == @pkg_publisher.type
#puts "FOUND"
val = 0
end
end
}
val
end
def current_props?
prop_hash = []
item = {}
index = 0
@pkg_publisher.list.stdout.split("\n").each do |line|
l = line.split(/\t/);
item = {:publisher => l[0], :sticky => l[1], :syspub => l[2],
:enabled => l[3], :type => l[4], :status => l[5], :uri => l[6], :mirror => l[7]}
prop_hash[index] = item
index = index + 1
end
prop_hash
end
def list?
Chef::Log.info("Current pkg pulisher")
if (@pkg_publisher.root)
shell_out("pkg -R #{@pkg_publisher.root} publisher -H -F tsv")
else
shell_out("pkg publisher -H -F tsv")
end
end
| 28.234637 | 103 | 0.661456 |
87551c75e507a7504e97d6f9f898fa46f30b07e0 | 6,113 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Slack::BlockKit::Element::MultiStaticSelect do
let(:instance) { described_class.new(**params) }
let(:placeholder_text) { 'some text' }
let(:action_id) { 'my-action' }
let(:params) do
{
placeholder: placeholder_text,
action_id: action_id
}
end
let(:expected_option_groups) do
[
{
label: {
text: '__GROUP__',
type: 'plain_text'
},
options: [
{
text: {
text: '__TEXT_1__',
type: 'plain_text'
},
value: '__VALUE_1__'
},
{
text: {
text: '__TEXT_2__',
type: 'plain_text'
},
value: '__VALUE_2__'
},
{
text: {
text: '__TEXT_3__',
type: 'plain_text'
},
value: '__VALUE_3__'
}
]
}
]
end
let(:expected_initial_options) do
[
{
text: {
text: '__TEXT_2__',
type: 'plain_text'
},
value: '__VALUE_2__'
}
]
end
let(:expected_options) do
[
{
text: {
text: '__TEXT_1__',
type: 'plain_text'
},
value: '__VALUE_1__'
},
{
text: {
text: '__TEXT_2__',
type: 'plain_text'
},
value: '__VALUE_2__'
},
{
text: {
text: '__TEXT_3__',
type: 'plain_text'
},
value: '__VALUE_3__'
}
]
end
describe '#as_json' do
subject(:as_json) { instance.as_json }
let(:expected_json) do
{
type: 'multi_static_select',
placeholder: {
'type': 'plain_text',
'text': placeholder_text
},
action_id: action_id
}
end
context 'with confirmation dialog' do
subject(:as_json) do
instance.confirmation_dialog do |confirm|
confirm.title(text: '__CONFIRM_TITTLE__')
confirm.plain_text(text: '__CONFIRM_TEXT__')
confirm.confirm(text: '__CONFIRMED__')
confirm.deny(text: '__DENIED__')
end
instance.as_json
end
let(:expected_json) do
{
type: 'multi_static_select',
placeholder: {
'type': 'plain_text',
'text': placeholder_text
},
action_id: action_id,
confirm: {
confirm: {
text: '__CONFIRMED__',
type: 'plain_text'
},
deny: {
text: '__DENIED__',
type: 'plain_text'
},
text: {
text: '__CONFIRM_TEXT__',
type: 'plain_text'
},
title: {
text: '__CONFIRM_TITTLE__',
type: 'plain_text'
}
}
}
end
it 'correctly serializes' do
expect(as_json).to eq(expected_json)
end
end
context 'with max_selected_items' do
let(:params) do
{
placeholder: placeholder_text,
action_id: action_id,
max_selected_items: 10
}
end
let(:expected_json) do
{
type: 'multi_static_select',
placeholder: {
'type': 'plain_text',
'text': placeholder_text
},
action_id: action_id,
max_selected_items: 10
}
end
it 'correctly serializes' do
expect(as_json).to eq(expected_json)
end
end
context 'without max_selected_items' do
let(:params) do
{
placeholder: placeholder_text,
action_id: action_id
}
end
it 'correctly serializes' do
expect(as_json).to eq(expected_json)
end
end
context 'with options' do
subject(:as_json) do
instance.option(value: '__VALUE_1__', text: '__TEXT_1__')
instance.option(value: '__VALUE_2__', text: '__TEXT_2__')
instance.option(value: '__VALUE_3__', text: '__TEXT_3__')
instance.as_json
end
it 'correctly serializes' do
expect(as_json).to eq(
expected_json.merge(options: expected_options)
)
end
end
context 'with options and initial option' do
subject(:as_json) do
instance.option(value: '__VALUE_1__', text: '__TEXT_1__')
instance.option(value: '__VALUE_2__', text: '__TEXT_2__', initial: true)
instance.option(value: '__VALUE_3__', text: '__TEXT_3__')
instance.as_json
end
it 'correctly serializes' do
expect(as_json).to eq(
expected_json.merge(
options: expected_options,
initial_options: expected_initial_options
)
)
end
end
context 'with option_groups' do
subject(:as_json) do
instance.option_group(label: '__GROUP__') do |group|
group.option(value: '__VALUE_1__', text: '__TEXT_1__')
group.option(value: '__VALUE_2__', text: '__TEXT_2__')
group.option(value: '__VALUE_3__', text: '__TEXT_3__')
end
instance.as_json
end
it 'correctly serializes' do
expect(as_json).to eq(
expected_json.merge(option_groups: expected_option_groups)
)
end
end
context 'with option_groups and initial option' do
subject(:as_json) do
instance.option_group(label: '__GROUP__') do |group|
group.option(value: '__VALUE_1__', text: '__TEXT_1__')
group.option(value: '__VALUE_2__', text: '__TEXT_2__', initial: true)
group.option(value: '__VALUE_3__', text: '__TEXT_3__')
end
instance.as_json
end
it 'correctly serializes' do
expect(as_json).to eq(
expected_json.merge(
option_groups: expected_option_groups,
initial_options: expected_initial_options
)
)
end
end
end
end
| 23.602317 | 80 | 0.521348 |
bb645d8a7742c06174a8ee152697b411c150f9dd | 48 | json.partial! 'records/record', record: @record
| 24 | 47 | 0.75 |
e9cf9804737d1c84d6f8eec9715b628ea9689735 | 447 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe SolidusShipstation do
describe '.config' do
subject { described_class.config }
specify :aggregate_failures do
is_expected.to respond_to(:username)
is_expected.to respond_to(:password)
is_expected.to respond_to(:weight_units)
is_expected.to respond_to(:ssl_encrypted)
is_expected.to respond_to(:capture_at_notification)
end
end
end
| 24.833333 | 57 | 0.749441 |
1aede880226a14ddae3685a5d35036917bd4b53f | 278 | https://codility.com/programmers/task/prefix_set
https://codility.com/programmers/challenges/alpha2010
def solution(a)
b = a.uniq
n = b.size - 1
max = temp = 0
(0..n).each do |i|
temp = a.index(b[i])
if max < temp
max = temp
end
end
return max
end
| 18.533333 | 53 | 0.629496 |
bb4e677afdebc3204b76761d8c545b58ad9308ef | 15,253 | require "vagrant/action/builder"
module VagrantPlugins
module ProviderVirtualBox
module Action
autoload :Boot, File.expand_path("../action/boot", __FILE__)
autoload :CheckAccessible, File.expand_path("../action/check_accessible", __FILE__)
autoload :CheckCreated, File.expand_path("../action/check_created", __FILE__)
autoload :CheckGuestAdditions, File.expand_path("../action/check_guest_additions", __FILE__)
autoload :CheckRunning, File.expand_path("../action/check_running", __FILE__)
autoload :CheckVirtualbox, File.expand_path("../action/check_virtualbox", __FILE__)
autoload :CleanMachineFolder, File.expand_path("../action/clean_machine_folder", __FILE__)
autoload :ClearForwardedPorts, File.expand_path("../action/clear_forwarded_ports", __FILE__)
autoload :ClearNetworkInterfaces, File.expand_path("../action/clear_network_interfaces", __FILE__)
autoload :Created, File.expand_path("../action/created", __FILE__)
autoload :Customize, File.expand_path("../action/customize", __FILE__)
autoload :Destroy, File.expand_path("../action/destroy", __FILE__)
autoload :DestroyUnusedNetworkInterfaces, File.expand_path("../action/destroy_unused_network_interfaces", __FILE__)
autoload :DiscardState, File.expand_path("../action/discard_state", __FILE__)
autoload :Export, File.expand_path("../action/export", __FILE__)
autoload :ForcedHalt, File.expand_path("../action/forced_halt", __FILE__)
autoload :ForwardPorts, File.expand_path("../action/forward_ports", __FILE__)
autoload :Import, File.expand_path("../action/import", __FILE__)
autoload :ImportMaster, File.expand_path("../action/import_master", __FILE__)
autoload :IsPaused, File.expand_path("../action/is_paused", __FILE__)
autoload :IsRunning, File.expand_path("../action/is_running", __FILE__)
autoload :IsSaved, File.expand_path("../action/is_saved", __FILE__)
autoload :MatchMACAddress, File.expand_path("../action/match_mac_address", __FILE__)
autoload :MessageAlreadyRunning, File.expand_path("../action/message_already_running", __FILE__)
autoload :MessageNotCreated, File.expand_path("../action/message_not_created", __FILE__)
autoload :MessageNotRunning, File.expand_path("../action/message_not_running", __FILE__)
autoload :MessageWillNotDestroy, File.expand_path("../action/message_will_not_destroy", __FILE__)
autoload :Network, File.expand_path("../action/network", __FILE__)
autoload :NetworkFixIPv6, File.expand_path("../action/network_fix_ipv6", __FILE__)
autoload :Package, File.expand_path("../action/package", __FILE__)
autoload :PackageSetupFiles, File.expand_path("../action/package_setup_files", __FILE__)
autoload :PackageSetupFolders, File.expand_path("../action/package_setup_folders", __FILE__)
autoload :PackageVagrantfile, File.expand_path("../action/package_vagrantfile", __FILE__)
autoload :PrepareCloneSnapshot, File.expand_path("../action/prepare_clone_snapshot", __FILE__)
autoload :PrepareNFSSettings, File.expand_path("../action/prepare_nfs_settings", __FILE__)
autoload :PrepareNFSValidIds, File.expand_path("../action/prepare_nfs_valid_ids", __FILE__)
autoload :PrepareForwardedPortCollisionParams, File.expand_path("../action/prepare_forwarded_port_collision_params", __FILE__)
autoload :Resume, File.expand_path("../action/resume", __FILE__)
autoload :SaneDefaults, File.expand_path("../action/sane_defaults", __FILE__)
autoload :SetDefaultNICType, File.expand_path("../action/set_default_nic_type", __FILE__)
autoload :SetName, File.expand_path("../action/set_name", __FILE__)
autoload :SnapshotDelete, File.expand_path("../action/snapshot_delete", __FILE__)
autoload :SnapshotRestore, File.expand_path("../action/snapshot_restore", __FILE__)
autoload :SnapshotSave, File.expand_path("../action/snapshot_save", __FILE__)
autoload :Suspend, File.expand_path("../action/suspend", __FILE__)
# @deprecated use {PackageSetupFiles} instead
autoload :SetupPackageFiles, File.expand_path("../action/setup_package_files", __FILE__)
# Include the built-in modules so that we can use them as top-level
# things.
include Vagrant::Action::Builtin
# This action boots the VM, assuming the VM is in a state that requires
# a bootup (i.e. not saved).
def self.action_boot
Vagrant::Action::Builder.new.tap do |b|
b.use CheckAccessible
b.use CleanMachineFolder
b.use SetName
b.use ClearForwardedPorts
b.use Provision
b.use EnvSet, port_collision_repair: true
b.use PrepareForwardedPortCollisionParams
b.use HandleForwardedPortCollisions
b.use PrepareNFSValidIds
b.use SyncedFolderCleanup
b.use SyncedFolders
b.use PrepareNFSSettings
b.use SetDefaultNICType
b.use ClearNetworkInterfaces
b.use Network
b.use NetworkFixIPv6
b.use ForwardPorts
b.use SetHostname
b.use SaneDefaults
b.use Customize, "pre-boot"
b.use Boot
b.use Customize, "post-boot"
b.use WaitForCommunicator, [:starting, :running]
b.use Customize, "post-comm"
b.use CheckGuestAdditions
end
end
# This is the action that is primarily responsible for completely
# freeing the resources of the underlying virtual machine.
def self.action_destroy
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use Call, Created do |env1, b2|
if !env1[:result]
b2.use MessageNotCreated
next
end
b2.use Call, DestroyConfirm do |env2, b3|
if env2[:result]
b3.use ConfigValidate
b3.use ProvisionerCleanup, :before
b3.use CheckAccessible
b3.use EnvSet, force_halt: true
b3.use action_halt
b3.use Destroy
b3.use CleanMachineFolder
b3.use DestroyUnusedNetworkInterfaces
b3.use PrepareNFSValidIds
b3.use SyncedFolderCleanup
else
b3.use MessageWillNotDestroy
end
end
end
end
end
# This is the action that is primarily responsible for halting
# the virtual machine, gracefully or by force.
def self.action_halt
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use Call, Created do |env, b2|
if env[:result]
b2.use CheckAccessible
b2.use DiscardState
b2.use Call, IsPaused do |env2, b3|
next if !env2[:result]
b3.use Resume
end
b2.use Call, GracefulHalt, :poweroff, :running do |env2, b3|
if !env2[:result]
b3.use ForcedHalt
end
end
else
b2.use MessageNotCreated
end
end
end
end
# This action packages the virtual machine into a single box file.
def self.action_package
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use Call, Created do |env1, b2|
if !env1[:result]
b2.use MessageNotCreated
next
end
b2.use PackageSetupFolders
b2.use PackageSetupFiles
b2.use CheckAccessible
b2.use action_halt
b2.use ClearForwardedPorts
b2.use PrepareNFSValidIds
b2.use SyncedFolderCleanup
b2.use Package
b2.use Export
b2.use PackageVagrantfile
end
end
end
# This action just runs the provisioners on the machine.
def self.action_provision
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use ConfigValidate
b.use Call, Created do |env1, b2|
if !env1[:result]
b2.use MessageNotCreated
next
end
b2.use Call, IsRunning do |env2, b3|
if !env2[:result]
b3.use MessageNotRunning
next
end
b3.use CheckAccessible
b3.use Provision
end
end
end
end
# This action is responsible for reloading the machine, which
# brings it down, sucks in new configuration, and brings the
# machine back up with the new configuration.
def self.action_reload
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use Call, Created do |env1, b2|
if !env1[:result]
b2.use MessageNotCreated
next
end
b2.use ConfigValidate
b2.use action_halt
b2.use action_start
end
end
end
# This is the action that is primarily responsible for resuming
# suspended machines.
def self.action_resume
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use Call, Created do |env, b2|
if env[:result]
b2.use CheckAccessible
b2.use EnvSet, port_collision_repair: false
b2.use PrepareForwardedPortCollisionParams
b2.use HandleForwardedPortCollisions
b2.use Resume
b2.use Provision
b2.use WaitForCommunicator, [:restoring, :running]
else
b2.use MessageNotCreated
end
end
end
end
def self.action_snapshot_delete
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use Call, Created do |env, b2|
if env[:result]
b2.use SnapshotDelete
else
b2.use MessageNotCreated
end
end
end
end
# This is the action that is primarily responsible for restoring a snapshot
def self.action_snapshot_restore
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use Call, Created do |env, b2|
if !env[:result]
raise Vagrant::Errors::VMNotCreatedError
end
b2.use CheckAccessible
b2.use EnvSet, force_halt: true
b2.use action_halt
b2.use SnapshotRestore
b2.use Call, IsEnvSet, :snapshot_delete do |env2, b3|
if env2[:result]
b3.use action_snapshot_delete
end
end
b2.use Call, IsEnvSet, :snapshot_start do |env2, b3|
if env2[:result]
b3.use action_start
end
end
end
end
end
# This is the action that is primarily responsible for saving a snapshot
def self.action_snapshot_save
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use Call, Created do |env, b2|
if env[:result]
b2.use SnapshotSave
else
b2.use MessageNotCreated
end
end
end
end
# This is the action that will exec into an SSH shell.
def self.action_ssh
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use CheckCreated
b.use CheckAccessible
b.use CheckRunning
b.use SSHExec
end
end
# This is the action that will run a single SSH command.
def self.action_ssh_run
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use CheckCreated
b.use CheckAccessible
b.use CheckRunning
b.use SSHRun
end
end
# This action starts a VM, assuming it is already imported and exists.
# A precondition of this action is that the VM exists.
def self.action_start
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use ConfigValidate
b.use BoxCheckOutdated
b.use Call, IsRunning do |env, b2|
# If the VM is running, run the necessary provisioners
if env[:result]
b2.use action_provision
next
end
b2.use Call, IsSaved do |env2, b3|
if env2[:result]
# The VM is saved, so just resume it
b3.use action_resume
next
end
b3.use Call, IsPaused do |env3, b4|
if env3[:result]
b4.use Resume
next
end
# The VM is not saved, so we must have to boot it up
# like normal. Boot!
b4.use action_boot
end
end
end
end
end
# This is the action that is primarily responsible for suspending
# the virtual machine.
def self.action_suspend
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
b.use Call, Created do |env, b2|
if env[:result]
b2.use CheckAccessible
b2.use Suspend
else
b2.use MessageNotCreated
end
end
end
end
# This is the action that is called to sync folders to a running
# machine without a reboot.
def self.action_sync_folders
Vagrant::Action::Builder.new.tap do |b|
b.use PrepareNFSValidIds
b.use SyncedFolders
b.use PrepareNFSSettings
end
end
# This action brings the machine up from nothing, including importing
# the box, configuring metadata, and booting.
def self.action_up
Vagrant::Action::Builder.new.tap do |b|
b.use CheckVirtualbox
# Handle box_url downloading early so that if the Vagrantfile
# references any files in the box or something it all just
# works fine.
b.use Call, Created do |env, b2|
if !env[:result]
b2.use HandleBox
end
end
b.use ConfigValidate
b.use Call, Created do |env, b2|
# If the VM is NOT created yet, then do the setup steps
if !env[:result]
b2.use CheckAccessible
b2.use Customize, "pre-import"
if env[:machine].provider_config.linked_clone
# We are cloning from the box
b2.use ImportMaster
end
b2.use PrepareClone
b2.use PrepareCloneSnapshot
b2.use Import
b2.use DiscardState
b2.use MatchMACAddress
end
end
b.use action_start
end
end
end
end
end
| 36.490431 | 132 | 0.597587 |
216b242a1b5e8d43c079e17b5f3e89db759f57d1 | 533 | module Mongoid #:nodoc
module Errors #:nodoc
# This error is raised when trying to create set nested records above the
# specified :limit
#
# Example:
#
#<tt>TooManyNestedAttributeRecords.new('association', limit)
class TooManyNestedAttributeRecords < MongoidError
def initialize(association, limit)
super(
translate(
"too_many_nested_attribute_records",
{ :association => association, :limit => limit }
)
)
end
end
end
end
| 24.227273 | 77 | 0.621013 |
91907f464fbe471fa9c9902540e5a0bc9fd933be | 833 | # (c) Copyright 2020 Hewlett Packard Enterprise Development LP
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
module OneviewCookbook
module API1800
module C7000
# Hypervisor Cluster Profile API1800 provider
class HypervisorClusterProfileProvider < API1600::C7000::HypervisorClusterProfileProvider
end
end
end
end
| 39.666667 | 95 | 0.773109 |
e93a7077899e197a3b73a2471675bb9a115e8cde | 1,292 | module Api::V1
class UsersController < ApplicationController
before_action :set_user, only: [:show, :update, :destroy]
# GET /users
def index
@users = User.order(:id)
render json: @users
end
# GET /users/1
def show
render json: @user
end
# POST /users
def create
@user = User.new(user_params)
if @user.save
render json: @user, status: :created
else
render json: @user.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /users/1
def update
if @user.update(user_params)
render json: @user
else
render json: @user.errors, status: :unprocessable_entity
end
end
# DELETE /users/1
def destroy
@user.destroy
if @user.destroy
head :no_content, status: :ok
else
render json: @user.errors, status: :unprocessable_entity
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
@user = User.find(params[:id])
end
# Only allow a trusted parameter "white user" through.
def user_params
params.require(:user).permit(:savings_target, :age, :name, :goal_retirement_age, :net_worth)
end
end
end
| 21.898305 | 100 | 0.607585 |
87f7fb39a845e3cc25d7767490c7b1700a578521 | 180 | Rails.application.routes.draw do
resources :quizzes
resources :users
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
| 30 | 102 | 0.783333 |
62dd2eb430696803dcf00e713c9ddcd4d4416a07 | 595 | cask 'focus' do
version '1.10.4'
sha256 '1155078036e9df1d4018eddadcc95d04228354c22ff14b74891249df791dac1a'
url "https://heyfocus.com/uploads/Focus-#{version}.zip"
appcast 'https://macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://heyfocus.com/focus.zip'
name 'Focus'
homepage 'https://heyfocus.com/'
app 'Focus.app'
uninstall quit: 'BradJasper.focus'
zap trash: [
'~/Library/Caches/BradJasper.focus/',
'~/Library/Application Support/Focus/',
'~/Library/Preferences/BradJasper.focus.plist',
]
end
| 29.75 | 111 | 0.67395 |
21e30c2123f4b2aaf84165a1a5e495d02c7add64 | 1,788 | require 'test_helper'
class FollowingTest < ActionDispatch::IntegrationTest
def setup
@user = users(:michael)
@other = users(:archer)
log_in_as(@user)
end
test "following page" do
get following_user_path(@user)
assert_not @user.following.empty?
assert_match @user.following.count.to_s, response.body
@user.following.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
test "followers page" do
get followers_user_path(@user)
assert_not @user.followers.empty?
assert_match @user.followers.count.to_s, response.body
@user.followers.each do |user|
assert_select "a[href=?]", user_path(user)
end
end
test "should follow a user the standard way" do
assert_difference '@user.following.count', 1 do
post relationships_path, params: { followed_id: @other.id }
end
end
test "should follow a user with Ajax" do
assert_difference '@user.following.count', 1 do
post relationships_path, xhr: true, params: { followed_id: @other.id }
end
end
test "should unfollow a user the standard way" do
@user.follow(@other)
relationship = @user.active_relationships.find_by(followed_id: @other.id)
assert_difference '@user.following.count', -1 do
delete relationship_path(relationship)
end
end
test "should unfollow a user with Ajax" do
@user.follow(@other)
relationship = @user.active_relationships.find_by(followed_id: @other.id)
assert_difference '@user.following.count', -1 do
delete relationship_path(relationship), xhr: true
end
end
test "feed on Home page" do
get root_path
@user.feed.paginate(page: 1).each do |micropost|
assert_match CGI.escapeHTML(micropost.content), response.body
end
end
end
| 27.9375 | 77 | 0.700783 |
e94590091e0a5f3f32fb4ff758f1ed77acaf801f | 5,835 | # Licensed to the Software Freedom Conservancy (SFC) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The SFC licenses this file
# to you 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 File.expand_path("../spec_helper", __FILE__)
module Selenium::WebDriver::DriverExtensions
describe HasTouchScreen do
compliant_on :browser => :android do
context "flick" do
before {
reset_driver!
driver.get url_for("longContentPage.html")
driver.rotation = :portrait
}
it "can flick horizontally from element" do
link = driver.find_element(:id => "link1")
link.location.x.should > 1500
to_flick = driver.find_element(:id => "imagestart")
driver.touch.flick(to_flick, -1000, 0, :normal).perform
link.location.x.should < 1500
end
it "can flick horizontally fast from element" do
link = driver.find_element(:id => "link2")
link.location.x.should > 3500
to_flick = driver.find_element(:id => "imagestart")
driver.touch.flick(to_flick, -400, 0, :fast).perform
link.location.x.should < 3500
end
not_compliant_on :browser => :android do
it "can flick horizontally" do
link = driver.find_element(:id => "link1")
link.location.x.should > 1500
driver.touch.flick(1000, 0).perform
link.location.x.should < 1500
end
end
not_compliant_on :browser => :android do
# no compliant driver currently, see TouchFlickTest.java
it "can flick horizontally fast"
end
it "can flick vertically from element" do
link = driver.find_element(:id => "link3")
link.location.y.should > 4200
to_flick = driver.find_element(:id => "imagestart")
driver.touch.flick(to_flick, 0, -600, :normal).perform
link.location.y.should < 4000
end
it "can flick vertically fast from element" do
link = driver.find_element(:id => "link4")
link.location.y.should > 8700
to_flick = driver.find_element(:id => "imagestart")
driver.touch.flick(to_flick, 0, -600, :fast).perform
link.location.y.should < 8700
end
it "can flick vertically" do
link = driver.find_element(:id => "link3")
link.location.y.should > 4200
to_flick = driver.find_element(:id => "imagestart")
driver.touch.flick(0, 750).perform
link.location.y.should < 4200
end
it "can flick vertically fast" do
link = driver.find_element(:id => "link4")
link.location.y.should > 8700
driver.touch.flick(0, 1500).perform
link.location.y.should < 4000
end
end
context "scroll" do
before {
reset_driver!
driver.get url_for("longContentPage.html")
}
compliant_on :browser => nil do
it "can scroll vertically from element" do
link = driver.find_element(:id => "link3")
link.location.y > 4200
to_scroll = driver.find_element(:id => "imagestart")
driver.touch.scroll(to_scroll, 0, -800).perform
link.location.y.should < 3500
end
end
it "can scroll vertically" do
link = driver.find_element(:id => "link3")
link.location.y > 4200
driver.touch.scroll(0, 800).perform
link.location.y.should < 3500
end
it "can scroll horizontally from element" do
link = driver.find_element(:id => "link1")
link.location.x.should > 1500
to_scroll = driver.find_element(:id => "imagestart")
driver.touch.scroll(to_scroll, -1000, 0).perform
link.location.x < 1500
end
it "can scroll horizontally" do
link = driver.find_element(:id => "link1")
link.location.x.should > 1500
driver.touch.scroll(400, 0).perform
link.location.x < 1500
end
end
context "single tap" do
before { driver.get url_for("clicks.html") }
it "can single tap on a link and follow it" do
e = driver.find_element(:id => "normal")
driver.touch.single_tap(e).perform
wait.until { driver.title == "XHTML Test Page" }
end
it "can single tap on an anchor and not reload" do
driver.execute_script "document.latch = true"
e = driver.find_element(:id => "anchor")
driver.touch.single_tap(e).perform
same_page = driver.execute_script "return document.latch"
same_page.should be true
end
end
context "double tap" do
before { driver.get url_for("longContentPage.html") }
it "can double tap an element" do
image = driver.find_element(:id => "imagestart")
image.location.y.should > 100
driver.touch.double_tap(image).perform
image.location.y.should < 50
end
end
context "long press" do
it "can long press on an element"
end
end
end
end
| 30.07732 | 67 | 0.604113 |
4af01806c09b6299bad7fec7359ad0e878616dc8 | 16,878 | require 'spec_helper'
require 'mspec/expectations/expectations'
require 'mspec/helpers/tmp'
require 'mspec/helpers/fs'
require 'mspec/matchers/base'
require 'mspec/runner/mspec'
require 'mspec/runner/example'
RSpec.describe MSpec, ".register_files" do
it "records which spec files to run" do
MSpec.register_files [:one, :two, :three]
expect(MSpec.files_array).to eq([:one, :two, :three])
end
end
RSpec.describe MSpec, ".register_mode" do
before :each do
MSpec.clear_modes
end
it "sets execution mode flags" do
MSpec.register_mode :verify
expect(MSpec.retrieve(:modes)).to eq([:verify])
end
end
RSpec.describe MSpec, ".register_tags_patterns" do
it "records the patterns for generating a tag file from a spec file" do
MSpec.register_tags_patterns [[/spec\/ruby/, "spec/tags"], [/frozen/, "ruby"]]
expect(MSpec.retrieve(:tags_patterns)).to eq([[/spec\/ruby/, "spec/tags"], [/frozen/, "ruby"]])
end
end
RSpec.describe MSpec, ".register_exit" do
before :each do
MSpec.store :exit, 0
end
it "records the exit code" do
expect(MSpec.exit_code).to eq(0)
MSpec.register_exit 1
expect(MSpec.exit_code).to eq(1)
end
end
RSpec.describe MSpec, ".exit_code" do
it "retrieves the code set with .register_exit" do
MSpec.register_exit 99
expect(MSpec.exit_code).to eq(99)
end
end
RSpec.describe MSpec, ".store" do
it "records data for MSpec settings" do
MSpec.store :anything, :value
expect(MSpec.retrieve(:anything)).to eq(:value)
end
end
RSpec.describe MSpec, ".retrieve" do
it "accesses .store'd data" do
MSpec.register :retrieve, :first
expect(MSpec.retrieve(:retrieve)).to eq([:first])
end
end
RSpec.describe MSpec, ".randomize" do
it "sets the flag to randomize spec execution order" do
expect(MSpec.randomize?).to eq(false)
MSpec.randomize = true
expect(MSpec.randomize?).to eq(true)
MSpec.randomize = false
expect(MSpec.randomize?).to eq(false)
end
end
RSpec.describe MSpec, ".register" do
it "is the gateway behind the register(symbol, action) facility" do
MSpec.register :bonus, :first
MSpec.register :bonus, :second
MSpec.register :bonus, :second
expect(MSpec.retrieve(:bonus)).to eq([:first, :second])
end
end
RSpec.describe MSpec, ".unregister" do
it "is the gateway behind the unregister(symbol, actions) facility" do
MSpec.register :unregister, :first
MSpec.register :unregister, :second
MSpec.unregister :unregister, :second
expect(MSpec.retrieve(:unregister)).to eq([:first])
end
end
RSpec.describe MSpec, ".protect" do
before :each do
MSpec.clear_current
@cs = ContextState.new "C#m"
@cs.parent = MSpec.current
@es = ExampleState.new @cs, "runs"
ScratchPad.record Exception.new("Sharp!")
end
it "returns true if no exception is raised" do
expect(MSpec.protect("passed") { 1 }).to be_truthy
end
it "returns false if an exception is raised" do
expect(MSpec.protect("testing") { raise ScratchPad.recorded }).to be_falsey
end
it "rescues any exceptions raised when evaluating the block argument" do
MSpec.protect("") { raise Exception, "Now you see me..." }
end
it "does not rescue SystemExit" do
begin
MSpec.protect("") { exit 1 }
rescue SystemExit
ScratchPad.record :system_exit
end
expect(ScratchPad.recorded).to eq(:system_exit)
end
it "calls all the exception actions" do
exc = ExceptionState.new @es, "testing", ScratchPad.recorded
allow(ExceptionState).to receive(:new).and_return(exc)
action = double("exception")
expect(action).to receive(:exception).with(exc)
MSpec.register :exception, action
MSpec.protect("testing") { raise ScratchPad.recorded }
MSpec.unregister :exception, action
end
it "registers a non-zero exit code when an exception is raised" do
expect(MSpec).to receive(:register_exit).with(1)
MSpec.protect("testing") { raise ScratchPad.recorded }
end
end
RSpec.describe MSpec, ".register_current" do
before :each do
MSpec.clear_current
end
it "sets the value returned by MSpec.current" do
expect(MSpec.current).to be_nil
MSpec.register_current :a
expect(MSpec.current).to eq(:a)
end
end
RSpec.describe MSpec, ".clear_current" do
it "sets the value returned by MSpec.current to nil" do
MSpec.register_current :a
expect(MSpec.current).not_to be_nil
MSpec.clear_current
expect(MSpec.current).to be_nil
end
end
RSpec.describe MSpec, ".current" do
before :each do
MSpec.clear_current
end
it "returns nil if no ContextState has been registered" do
expect(MSpec.current).to be_nil
end
it "returns the most recently registered ContextState" do
first = ContextState.new ""
second = ContextState.new ""
MSpec.register_current first
expect(MSpec.current).to eq(first)
MSpec.register_current second
expect(MSpec.current).to eq(second)
end
end
RSpec.describe MSpec, ".actions" do
before :each do
MSpec.store :start, []
ScratchPad.record []
start_one = double("one")
allow(start_one).to receive(:start) { ScratchPad << :one }
start_two = double("two")
allow(start_two).to receive(:start) { ScratchPad << :two }
MSpec.register :start, start_one
MSpec.register :start, start_two
end
it "does not attempt to run any actions if none have been registered" do
MSpec.store :finish, nil
expect { MSpec.actions :finish }.not_to raise_error
end
it "runs each action registered as a start action" do
MSpec.actions :start
expect(ScratchPad.recorded).to eq([:one, :two])
end
end
RSpec.describe MSpec, ".mode?" do
before :each do
MSpec.clear_modes
end
it "returns true if the mode has been set" do
expect(MSpec.mode?(:verify)).to eq(false)
MSpec.register_mode :verify
expect(MSpec.mode?(:verify)).to eq(true)
end
end
RSpec.describe MSpec, ".clear_modes" do
it "clears all registered modes" do
MSpec.register_mode(:pretend)
MSpec.register_mode(:verify)
expect(MSpec.mode?(:pretend)).to eq(true)
expect(MSpec.mode?(:verify)).to eq(true)
MSpec.clear_modes
expect(MSpec.mode?(:pretend)).to eq(false)
expect(MSpec.mode?(:verify)).to eq(false)
end
end
RSpec.describe MSpec, ".guarded?" do
before :each do
MSpec.instance_variable_set :@guarded, []
end
it "returns false if no guard has run" do
expect(MSpec.guarded?).to eq(false)
end
it "returns true if a single guard has run" do
MSpec.guard
expect(MSpec.guarded?).to eq(true)
end
it "returns true if more than one guard has run" do
MSpec.guard
MSpec.guard
expect(MSpec.guarded?).to eq(true)
end
it "returns true until all guards have finished" do
MSpec.guard
MSpec.guard
expect(MSpec.guarded?).to eq(true)
MSpec.unguard
expect(MSpec.guarded?).to eq(true)
MSpec.unguard
expect(MSpec.guarded?).to eq(false)
end
end
RSpec.describe MSpec, ".describe" do
before :each do
MSpec.clear_current
@cs = ContextState.new ""
allow(ContextState).to receive(:new).and_return(@cs)
allow(MSpec).to receive(:current).and_return(nil)
allow(MSpec).to receive(:register_current)
end
it "creates a new ContextState for the block" do
expect(ContextState).to receive(:new).and_return(@cs)
MSpec.describe(Object) { }
end
it "accepts an optional second argument" do
expect(ContextState).to receive(:new).and_return(@cs)
MSpec.describe(Object, "msg") { }
end
it "registers the newly created ContextState" do
expect(MSpec).to receive(:register_current).with(@cs).twice
MSpec.describe(Object) { }
end
it "invokes the ContextState#describe method" do
expect(@cs).to receive(:describe)
MSpec.describe(Object, "msg") {}
end
end
RSpec.describe MSpec, ".process" do
before :each do
allow(MSpec).to receive(:files)
MSpec.store :start, []
MSpec.store :finish, []
allow(STDOUT).to receive(:puts)
end
it "prints the RUBY_DESCRIPTION" do
expect(STDOUT).to receive(:puts).with(RUBY_DESCRIPTION)
MSpec.process
end
it "calls all start actions" do
start = double("start")
allow(start).to receive(:start) { ScratchPad.record :start }
MSpec.register :start, start
MSpec.process
expect(ScratchPad.recorded).to eq(:start)
end
it "calls all finish actions" do
finish = double("finish")
allow(finish).to receive(:finish) { ScratchPad.record :finish }
MSpec.register :finish, finish
MSpec.process
expect(ScratchPad.recorded).to eq(:finish)
end
it "calls the files method" do
expect(MSpec).to receive(:files)
MSpec.process
end
end
RSpec.describe MSpec, ".files" do
before :each do
MSpec.store :load, []
MSpec.store :unload, []
MSpec.register_files [:one, :two, :three]
allow(Kernel).to receive(:load)
end
it "calls load actions before each file" do
load = double("load")
allow(load).to receive(:load) { ScratchPad.record :load }
MSpec.register :load, load
MSpec.files
expect(ScratchPad.recorded).to eq(:load)
end
it "shuffles the file list if .randomize? is true" do
MSpec.randomize = true
expect(MSpec).to receive(:shuffle)
MSpec.files
MSpec.randomize = false
end
it "registers the current file" do
load = double("load")
files = []
allow(load).to receive(:load) { files << MSpec.file }
MSpec.register :load, load
MSpec.files
expect(files).to eq([:one, :two, :three])
end
end
RSpec.describe MSpec, ".shuffle" do
before :each do
@base = (0..100).to_a
@list = @base.clone
MSpec.shuffle @list
end
it "does not alter the elements in the list" do
@base.each do |elt|
expect(@list).to include(elt)
end
end
it "changes the order of the list" do
# obviously, this spec has a certain probability
# of failing. If it fails, run it again.
expect(@list).not_to eq(@base)
end
end
RSpec.describe MSpec, ".tags_file" do
before :each do
MSpec.store :file, "path/to/spec/something/some_spec.rb"
MSpec.store :tags_patterns, nil
end
it "returns the default tags file for the current spec file" do
expect(MSpec.tags_file).to eq("path/to/spec/tags/something/some_tags.txt")
end
it "returns the tags file for the current spec file with custom tags_patterns" do
MSpec.register_tags_patterns [[/^(.*)\/spec/, '\1/tags'], [/_spec.rb/, "_tags.txt"]]
expect(MSpec.tags_file).to eq("path/to/tags/something/some_tags.txt")
end
it "performs multiple substitutions" do
MSpec.register_tags_patterns [
[%r(/spec/something/), "/spec/other/"],
[%r(/spec/), "/spec/tags/"],
[/_spec.rb/, "_tags.txt"]
]
expect(MSpec.tags_file).to eq("path/to/spec/tags/other/some_tags.txt")
end
it "handles cases where no substitution is performed" do
MSpec.register_tags_patterns [[/nothing/, "something"]]
expect(MSpec.tags_file).to eq("path/to/spec/something/some_spec.rb")
end
end
RSpec.describe MSpec, ".read_tags" do
before :each do
allow(MSpec).to receive(:tags_file).and_return(File.dirname(__FILE__) + '/tags.txt')
end
it "returns a list of tag instances for matching tag names found" do
one = SpecTag.new "fail(broken):Some#method? works"
expect(MSpec.read_tags(["fail", "pass"])).to eq([one])
end
it "returns [] if no tags names match" do
expect(MSpec.read_tags("super")).to eq([])
end
end
RSpec.describe MSpec, ".read_tags" do
before :each do
@tag = SpecTag.new "fails:Some#method"
File.open(tmp("tags.txt", false), "w") do |f|
f.puts ""
f.puts @tag
f.puts ""
end
allow(MSpec).to receive(:tags_file).and_return(tmp("tags.txt", false))
end
it "does not return a tag object for empty lines" do
expect(MSpec.read_tags(["fails"])).to eq([@tag])
end
end
RSpec.describe MSpec, ".write_tags" do
before :each do
FileUtils.cp File.dirname(__FILE__) + "/tags.txt", tmp("tags.txt", false)
allow(MSpec).to receive(:tags_file).and_return(tmp("tags.txt", false))
@tag1 = SpecTag.new "check(broken):Tag#rewrite works"
@tag2 = SpecTag.new "broken:Tag#write_tags fails"
end
after :all do
rm_r tmp("tags.txt", false)
end
it "overwrites the tags in the tag file" do
expect(IO.read(tmp("tags.txt", false))).to eq(%[fail(broken):Some#method? works
incomplete(20%):The#best method ever
benchmark(0.01825):The#fastest method today
extended():\"Multi-line\\ntext\\ntag\"
])
MSpec.write_tags [@tag1, @tag2]
expect(IO.read(tmp("tags.txt", false))).to eq(%[check(broken):Tag#rewrite works
broken:Tag#write_tags fails
])
end
end
RSpec.describe MSpec, ".write_tag" do
before :each do
allow(FileUtils).to receive(:mkdir_p)
allow(MSpec).to receive(:tags_file).and_return(tmp("tags.txt", false))
@tag = SpecTag.new "fail(broken):Some#method works"
end
after :all do
rm_r tmp("tags.txt", false)
end
it "writes a tag to the tags file for the current spec file" do
MSpec.write_tag @tag
expect(IO.read(tmp("tags.txt", false))).to eq("fail(broken):Some#method works\n")
end
it "does not write a duplicate tag" do
File.open(tmp("tags.txt", false), "w") { |f| f.puts @tag }
MSpec.write_tag @tag
expect(IO.read(tmp("tags.txt", false))).to eq("fail(broken):Some#method works\n")
end
end
RSpec.describe MSpec, ".delete_tag" do
before :each do
FileUtils.cp File.dirname(__FILE__) + "/tags.txt", tmp("tags.txt", false)
allow(MSpec).to receive(:tags_file).and_return(tmp("tags.txt", false))
@tag = SpecTag.new "fail(Comments don't matter):Some#method? works"
end
after :each do
rm_r tmp("tags.txt", false)
end
it "deletes the tag if it exists" do
expect(MSpec.delete_tag(@tag)).to eq(true)
expect(IO.read(tmp("tags.txt", false))).to eq(%[incomplete(20%):The#best method ever
benchmark(0.01825):The#fastest method today
extended():\"Multi-line\\ntext\\ntag\"
])
end
it "deletes a tag with escaped newlines" do
expect(MSpec.delete_tag(SpecTag.new('extended:"Multi-line\ntext\ntag"'))).to eq(true)
expect(IO.read(tmp("tags.txt", false))).to eq(%[fail(broken):Some#method? works
incomplete(20%):The#best method ever
benchmark(0.01825):The#fastest method today
])
end
it "does not change the tags file contents if the tag doesn't exist" do
@tag.tag = "failed"
expect(MSpec.delete_tag(@tag)).to eq(false)
expect(IO.read(tmp("tags.txt", false))).to eq(%[fail(broken):Some#method? works
incomplete(20%):The#best method ever
benchmark(0.01825):The#fastest method today
extended():\"Multi-line\\ntext\\ntag\"
])
end
it "deletes the tag file if it is empty" do
expect(MSpec.delete_tag(@tag)).to eq(true)
expect(MSpec.delete_tag(SpecTag.new("incomplete:The#best method ever"))).to eq(true)
expect(MSpec.delete_tag(SpecTag.new("benchmark:The#fastest method today"))).to eq(true)
expect(MSpec.delete_tag(SpecTag.new('extended:"Multi-line\ntext\ntag"'))).to eq(true)
expect(File.exist?(tmp("tags.txt", false))).to eq(false)
end
end
RSpec.describe MSpec, ".delete_tags" do
before :each do
@tags = tmp("tags.txt", false)
FileUtils.cp File.dirname(__FILE__) + "/tags.txt", @tags
allow(MSpec).to receive(:tags_file).and_return(@tags)
end
it "deletes the tag file" do
MSpec.delete_tags
expect(File.exist?(@tags)).to be_falsey
end
end
RSpec.describe MSpec, ".expectation" do
it "sets the flag that an expectation has been reported" do
MSpec.clear_expectations
expect(MSpec.expectation?).to be_falsey
MSpec.expectation
expect(MSpec.expectation?).to be_truthy
end
end
RSpec.describe MSpec, ".expectation?" do
it "returns true if an expectation has been reported" do
MSpec.expectation
expect(MSpec.expectation?).to be_truthy
end
it "returns false if an expectation has not been reported" do
MSpec.clear_expectations
expect(MSpec.expectation?).to be_falsey
end
end
RSpec.describe MSpec, ".clear_expectations" do
it "clears the flag that an expectation has been reported" do
MSpec.expectation
expect(MSpec.expectation?).to be_truthy
MSpec.clear_expectations
expect(MSpec.expectation?).to be_falsey
end
end
RSpec.describe MSpec, ".register_shared" do
it "stores a shared ContextState by description" do
parent = ContextState.new "container"
state = ContextState.new "shared"
state.parent = parent
prc = lambda { }
state.describe(&prc)
MSpec.register_shared(state)
expect(MSpec.retrieve(:shared)["shared"]).to eq(state)
end
end
RSpec.describe MSpec, ".retrieve_shared" do
it "retrieves the shared ContextState matching description" do
state = ContextState.new ""
MSpec.retrieve(:shared)["shared"] = state
expect(MSpec.retrieve_shared(:shared)).to eq(state)
end
end
| 28.22408 | 99 | 0.690129 |
b91392a56d8e61bedb01aad835dea2a7e8f01e2f | 263 | # frozen_string_literal: true
include ActionDispatch::TestProcess
FactoryGirl.define do
factory :image, class: Bootsy::Image do
image_file do
fixture_file_upload(Rails.root.to_s + '/public/test.jpg', 'image/jpeg')
end
image_gallery
end
end
| 21.916667 | 77 | 0.737643 |
2809ca2cdbb77539fefa2c2f0c12a652630d1d64 | 138 | require 'test_helper'
class LiveAssets::Test < ActiveSupport::TestCase
test "truth" do
assert_kind_of Module, LiveAssets
end
end
| 17.25 | 48 | 0.76087 |
edb439fc11127dc0ff010126b2b0a01a51a39a1d | 2,757 | require File.dirname(__FILE__) + '/../../spec_helper'
require 'mspec/runner/formatters/specdoc'
require 'mspec/runner/example'
describe SpecdocFormatter do
before :each do
@formatter = SpecdocFormatter.new
end
it "responds to #register by registering itself with MSpec for appropriate actions" do
MSpec.stub(:register)
MSpec.should_receive(:register).with(:enter, @formatter)
@formatter.register
end
end
describe SpecdocFormatter, "#enter" do
before :each do
$stdout = @out = IOStub.new
@formatter = SpecdocFormatter.new
end
after :each do
$stdout = STDOUT
end
it "prints the #describe string" do
@formatter.enter("describe")
@out.should == "\ndescribe\n"
end
end
describe SpecdocFormatter, "#before" do
before :each do
$stdout = @out = IOStub.new
@formatter = SpecdocFormatter.new
@state = ExampleState.new ContextState.new("describe"), "it"
end
after :each do
$stdout = STDOUT
end
it "prints the #it string" do
@formatter.before @state
@out.should == "- it"
end
it "resets the #exception? flag" do
exc = ExceptionState.new @state, nil, SpecExpectationNotMetError.new("disappointing")
@formatter.exception exc
@formatter.exception?.should be_true
@formatter.before @state
@formatter.exception?.should be_false
end
end
describe SpecdocFormatter, "#exception" do
before :each do
$stdout = @out = IOStub.new
@formatter = SpecdocFormatter.new
context = ContextState.new "describe"
@state = ExampleState.new context, "it"
end
after :each do
$stdout = STDOUT
end
it "prints 'ERROR' if an exception is not an SpecExpectationNotMetError" do
exc = ExceptionState.new @state, nil, MSpecExampleError.new("painful")
@formatter.exception exc
@out.should == " (ERROR - 1)"
end
it "prints 'FAILED' if an exception is an SpecExpectationNotMetError" do
exc = ExceptionState.new @state, nil, SpecExpectationNotMetError.new("disappointing")
@formatter.exception exc
@out.should == " (FAILED - 1)"
end
it "prints the #it string if an exception has already been raised" do
exc = ExceptionState.new @state, nil, SpecExpectationNotMetError.new("disappointing")
@formatter.exception exc
exc = ExceptionState.new @state, nil, MSpecExampleError.new("painful")
@formatter.exception exc
@out.should == " (FAILED - 1)\n- it (ERROR - 2)"
end
end
describe SpecdocFormatter, "#after" do
before :each do
$stdout = @out = IOStub.new
@formatter = SpecdocFormatter.new
@state = ExampleState.new "describe", "it"
end
after :each do
$stdout = STDOUT
end
it "prints a newline character" do
@formatter.after @state
@out.should == "\n"
end
end
| 25.766355 | 89 | 0.691331 |
873366a19024c64f64c0b280b01e040e954302b3 | 24,237 | # frozen_string_literal: true
RSpec.describe "major deprecations" do
let(:warnings) { err }
describe "Bundler" do
before do
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
end
describe ".clean_env" do
before do
source = "Bundler.clean_env"
bundle "exec ruby -e #{source.dump}"
end
it "is deprecated in favor of .unbundled_env", :bundler => "< 3" do
expect(deprecations).to include \
"`Bundler.clean_env` has been deprecated in favor of `Bundler.unbundled_env`. " \
"If you instead want the environment before bundler was originally loaded, use `Bundler.original_env` " \
"(called at -e:1)"
end
pending "is removed and shows a helpful error message about it", :bundler => "3"
end
describe ".with_clean_env" do
before do
source = "Bundler.with_clean_env {}"
bundle "exec ruby -e #{source.dump}"
end
it "is deprecated in favor of .unbundled_env", :bundler => "< 3" do
expect(deprecations).to include(
"`Bundler.with_clean_env` has been deprecated in favor of `Bundler.with_unbundled_env`. " \
"If you instead want the environment before bundler was originally loaded, use `Bundler.with_original_env` " \
"(called at -e:1)"
)
end
pending "is removed and shows a helpful error message about it", :bundler => "3"
end
describe ".clean_system" do
before do
source = "Bundler.clean_system('ls')"
bundle "exec ruby -e #{source.dump}"
end
it "is deprecated in favor of .unbundled_system", :bundler => "< 3" do
expect(deprecations).to include(
"`Bundler.clean_system` has been deprecated in favor of `Bundler.unbundled_system`. " \
"If you instead want to run the command in the environment before bundler was originally loaded, use `Bundler.original_system` " \
"(called at -e:1)"
)
end
pending "is removed and shows a helpful error message about it", :bundler => "3"
end
describe ".clean_exec" do
before do
source = "Bundler.clean_exec('ls')"
bundle "exec ruby -e #{source.dump}"
end
it "is deprecated in favor of .unbundled_exec", :bundler => "< 3" do
expect(deprecations).to include(
"`Bundler.clean_exec` has been deprecated in favor of `Bundler.unbundled_exec`. " \
"If you instead want to exec to a command in the environment before bundler was originally loaded, use `Bundler.original_exec` " \
"(called at -e:1)"
)
end
pending "is removed and shows a helpful error message about it", :bundler => "3"
end
describe ".environment" do
before do
source = "Bundler.environment"
bundle "exec ruby -e #{source.dump}"
end
it "is deprecated in favor of .load", :bundler => "< 3" do
expect(deprecations).to include "Bundler.environment has been removed in favor of Bundler.load (called at -e:1)"
end
pending "is removed and shows a helpful error message about it", :bundler => "3"
end
end
describe "bundle exec --no-keep-file-descriptors" do
before do
bundle "exec --no-keep-file-descriptors -e 1", :raise_on_error => false
end
it "is deprecated", :bundler => "< 3" do
expect(deprecations).to include "The `--no-keep-file-descriptors` has been deprecated. `bundle exec` no longer mess with your file descriptors. Close them in the exec'd script if you need to"
end
pending "is removed and shows a helpful error message about it", :bundler => "3"
end
describe "bundle update --quiet" do
it "does not print any deprecations" do
bundle :update, :quiet => true, :raise_on_error => false
expect(deprecations).to be_empty
end
end
context "bundle check --path" do
before do
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
bundle "check --path vendor/bundle", :raise_on_error => false
end
it "should print a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include(
"The `--path` flag is deprecated because it relies on being " \
"remembered across bundler invocations, which bundler will no " \
"longer do in future versions. Instead please use `bundle config set --local " \
"path 'vendor/bundle'`, and stop using this flag"
)
end
pending "fails with a helpful error", :bundler => "3"
end
context "bundle check --path=" do
before do
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
bundle "check --path=vendor/bundle", :raise_on_error => false
end
it "should print a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include(
"The `--path` flag is deprecated because it relies on being " \
"remembered across bundler invocations, which bundler will no " \
"longer do in future versions. Instead please use `bundle config set --local " \
"path 'vendor/bundle'`, and stop using this flag"
)
end
pending "fails with a helpful error", :bundler => "3"
end
context "bundle cache --all" do
before do
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
bundle "cache --all", :raise_on_error => false
end
it "should print a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include(
"The `--all` flag is deprecated because it relies on being " \
"remembered across bundler invocations, which bundler will no " \
"longer do in future versions. Instead please use `bundle config set " \
"cache_all true`, and stop using this flag"
)
end
pending "fails with a helpful error", :bundler => "3"
end
context "bundle cache --path" do
before do
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
bundle "cache --path foo", :raise_on_error => false
end
it "should print a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include(
"The `--path` flag is deprecated because its semantics are unclear. " \
"Use `bundle config cache_path` to configure the path of your cache of gems, " \
"and `bundle config path` to configure the path where your gems are installed, " \
"and stop using this flag"
)
end
pending "fails with a helpful error", :bundler => "3"
end
describe "bundle config" do
describe "old list interface" do
before do
bundle "config"
end
it "warns", :bundler => "3" do
expect(deprecations).to include("Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle config list` instead.")
end
pending "fails with a helpful error", :bundler => "3"
end
describe "old get interface" do
before do
bundle "config waka"
end
it "warns", :bundler => "3" do
expect(deprecations).to include("Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle config get waka` instead.")
end
pending "fails with a helpful error", :bundler => "3"
end
describe "old set interface" do
before do
bundle "config waka wakapun"
end
it "warns", :bundler => "3" do
expect(deprecations).to include("Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle config set waka wakapun` instead.")
end
pending "fails with a helpful error", :bundler => "3"
end
describe "old set interface with --local" do
before do
bundle "config --local waka wakapun"
end
it "warns", :bundler => "3" do
expect(deprecations).to include("Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle config set --local waka wakapun` instead.")
end
pending "fails with a helpful error", :bundler => "3"
end
describe "old set interface with --global" do
before do
bundle "config --global waka wakapun"
end
it "warns", :bundler => "3" do
expect(deprecations).to include("Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle config set --global waka wakapun` instead.")
end
pending "fails with a helpful error", :bundler => "3"
end
describe "old unset interface" do
before do
bundle "config --delete waka"
end
it "warns", :bundler => "3" do
expect(deprecations).to include("Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle config unset waka` instead.")
end
pending "fails with a helpful error", :bundler => "3"
end
describe "old unset interface with --local" do
before do
bundle "config --delete --local waka"
end
it "warns", :bundler => "3" do
expect(deprecations).to include("Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle config unset --local waka` instead.")
end
pending "fails with a helpful error", :bundler => "3"
end
describe "old unset interface with --global" do
before do
bundle "config --delete --global waka"
end
it "warns", :bundler => "3" do
expect(deprecations).to include("Using the `config` command without a subcommand [list, get, set, unset] is deprecated and will be removed in the future. Use `bundle config unset --global waka` instead.")
end
pending "fails with a helpful error", :bundler => "3"
end
end
describe "bundle update" do
before do
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
end
it "warns when no options are given", :bundler => "3" do
bundle "update"
expect(deprecations).to include("Pass --all to `bundle update` to update everything")
end
pending "fails with a helpful error when no options are given", :bundler => "3"
it "does not warn when --all is passed" do
bundle "update --all"
expect(deprecations).to be_empty
end
end
describe "bundle install --binstubs" do
before do
install_gemfile <<-G, :binstubs => true
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
end
it "should output a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include("The --binstubs option will be removed in favor of `bundle binstubs --all`")
end
pending "fails with a helpful error", :bundler => "3"
end
context "bundle install with both gems.rb and Gemfile present" do
it "should not warn about gems.rb" do
create_file "gems.rb", <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
bundle :install
expect(deprecations).to be_empty
end
it "should print a proper warning, and use gems.rb" do
create_file "gems.rb", "source \"#{file_uri_for(gem_repo1)}\""
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
expect(warnings).to include(
"Multiple gemfiles (gems.rb and Gemfile) detected. Make sure you remove Gemfile and Gemfile.lock since bundler is ignoring them in favor of gems.rb and gems.rb.locked."
)
expect(the_bundle).not_to include_gem "rack 1.0"
end
end
context "bundle install with flags" do
before do
bundle "config set --local path vendor/bundle"
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
end
{
"clean" => ["clean", true],
"deployment" => ["deployment", true],
"frozen" => ["frozen", true],
"no-deployment" => ["deployment", false],
"no-prune" => ["no_prune", true],
"path" => ["path", "vendor/bundle"],
"shebang" => ["shebang", "ruby27"],
"system" => ["system", true],
"without" => ["without", "development"],
"with" => ["with", "development"],
}.each do |name, expectations|
option_name, value = *expectations
flag_name = "--#{name}"
context "with the #{flag_name} flag" do
before do
bundle "install" # to create a lockfile, which deployment or frozen need
bundle "install #{flag_name} #{value}"
end
it "should print a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include(
"The `#{flag_name}` flag is deprecated because it relies on " \
"being remembered across bundler invocations, which bundler " \
"will no longer do in future versions. Instead please use " \
"`bundle config set --local #{option_name} '#{value}'`, and stop using this flag"
)
end
pending "fails with a helpful error", :bundler => "3"
end
end
end
context "bundle install with multiple sources" do
before do
install_gemfile <<-G
source "#{file_uri_for(gem_repo3)}"
source "#{file_uri_for(gem_repo1)}"
G
end
it "shows a deprecation", :bundler => "< 3" do
expect(deprecations).to include(
"Your Gemfile contains multiple primary sources. " \
"Using `source` more than once without a block is a security risk, and " \
"may result in installing unexpected gems. To resolve this warning, use " \
"a block to indicate which gems should come from the secondary source."
)
end
it "doesn't show lockfile deprecations if there's a lockfile", :bundler => "< 3" do
bundle "install"
expect(deprecations).to include(
"Your Gemfile contains multiple primary sources. " \
"Using `source` more than once without a block is a security risk, and " \
"may result in installing unexpected gems. To resolve this warning, use " \
"a block to indicate which gems should come from the secondary source."
)
expect(deprecations).not_to include(
"Your lockfile contains a single rubygems source section with multiple remotes, which is insecure. " \
"Make sure you run `bundle install` in non frozen mode and commit the result to make your lockfile secure."
)
bundle "config set --local frozen true"
bundle "install"
expect(deprecations).to include(
"Your Gemfile contains multiple primary sources. " \
"Using `source` more than once without a block is a security risk, and " \
"may result in installing unexpected gems. To resolve this warning, use " \
"a block to indicate which gems should come from the secondary source."
)
expect(deprecations).not_to include(
"Your lockfile contains a single rubygems source section with multiple remotes, which is insecure. " \
"Make sure you run `bundle install` in non frozen mode and commit the result to make your lockfile secure."
)
end
pending "fails with a helpful error", :bundler => "3"
end
context "bundle install in frozen mode with a lockfile with a single rubygems section with multiple remotes" do
before do
build_repo gem_repo3 do
build_gem "rack", "0.9.1"
end
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
source "#{file_uri_for(gem_repo3)}" do
gem 'rack'
end
G
lockfile <<~L
GEM
remote: #{file_uri_for(gem_repo1)}/
remote: #{file_uri_for(gem_repo3)}/
specs:
rack (0.9.1)
PLATFORMS
ruby
DEPENDENCIES
rack!
BUNDLED WITH
#{Bundler::VERSION}
L
bundle "config set --local frozen true"
end
it "shows a deprecation", :bundler => "< 3" do
bundle "install"
expect(deprecations).to include("Your lockfile contains a single rubygems source section with multiple remotes, which is insecure. Make sure you run `bundle install` in non frozen mode and commit the result to make your lockfile secure.")
end
pending "fails with a helpful error", :bundler => "3"
end
context "when Bundler.setup is run in a ruby script" do
before do
create_file "gems.rb", "source \"#{file_uri_for(gem_repo1)}\""
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack", :group => :test
G
ruby <<-RUBY
require '#{entrypoint}'
Bundler.setup
Bundler.setup
RUBY
end
it "should print a single deprecation warning" do
expect(warnings).to include(
"Multiple gemfiles (gems.rb and Gemfile) detected. Make sure you remove Gemfile and Gemfile.lock since bundler is ignoring them in favor of gems.rb and gems.rb.locked."
)
end
end
context "when `bundler/deployment` is required in a ruby script" do
before do
ruby(<<-RUBY, :env => env_for_missing_prerelease_default_gem_activation)
require 'bundler/deployment'
RUBY
end
it "should print a capistrano deprecation warning", :bundler => "< 3" do
expect(deprecations).to include("Bundler no longer integrates " \
"with Capistrano, but Capistrano provides " \
"its own integration with Bundler via the " \
"capistrano-bundler gem. Use it instead.")
end
pending "fails with a helpful error", :bundler => "3"
end
describe Bundler::Dsl do
before do
@rubygems = double("rubygems")
allow(Bundler::Source::Rubygems).to receive(:new) { @rubygems }
end
context "with github gems" do
it "does not warn about removal", :bundler => "< 3" do
expect(Bundler.ui).not_to receive(:warn)
subject.gem("sparks", :github => "indirect/sparks")
github_uri = "https://github.com/indirect/sparks.git"
expect(subject.dependencies.first.source.uri).to eq(github_uri)
end
it "warns about removal", :bundler => "3" do
msg = <<-EOS
The :github git source is deprecated, and will be removed in the future. Change any "reponame" :github sources to "username/reponame". Add this code to the top of your Gemfile to ensure it continues to work:
git_source(:github) {|repo_name| "https://github.com/\#{repo_name}.git" }
EOS
expect(Bundler.ui).to receive(:warn).with("[DEPRECATED] #{msg}")
subject.gem("sparks", :github => "indirect/sparks")
github_uri = "https://github.com/indirect/sparks.git"
expect(subject.dependencies.first.source.uri).to eq(github_uri)
end
end
context "with bitbucket gems" do
it "does not warn about removal", :bundler => "< 3" do
expect(Bundler.ui).not_to receive(:warn)
subject.gem("not-really-a-gem", :bitbucket => "mcorp/flatlab-rails")
end
it "warns about removal", :bundler => "3" do
msg = <<-EOS
The :bitbucket git source is deprecated, and will be removed in the future. Add this code to the top of your Gemfile to ensure it continues to work:
git_source(:bitbucket) do |repo_name|
user_name, repo_name = repo_name.split("/")
repo_name ||= user_name
"https://\#{user_name}@bitbucket.org/\#{user_name}/\#{repo_name}.git"
end
EOS
expect(Bundler.ui).to receive(:warn).with("[DEPRECATED] #{msg}")
subject.gem("not-really-a-gem", :bitbucket => "mcorp/flatlab-rails")
end
end
context "with gist gems" do
it "does not warn about removal", :bundler => "< 3" do
expect(Bundler.ui).not_to receive(:warn)
subject.gem("not-really-a-gem", :gist => "1234")
end
it "warns about removal", :bundler => "3" do
msg = <<-EOS
The :gist git source is deprecated, and will be removed in the future. Add this code to the top of your Gemfile to ensure it continues to work:
git_source(:gist) {|repo_name| "https://gist.github.com/\#{repo_name}.git" }
EOS
expect(Bundler.ui).to receive(:warn).with("[DEPRECATED] #{msg}")
subject.gem("not-really-a-gem", :gist => "1234")
end
end
end
context "bundle show" do
before do
install_gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
end
context "with --outdated flag" do
before do
bundle "show --outdated"
end
it "prints a deprecation warning informing about its removal", :bundler => "< 3" do
expect(deprecations).to include("the `--outdated` flag to `bundle show` was undocumented and will be removed without replacement")
end
pending "fails with a helpful message", :bundler => "3"
end
end
context "bundle remove" do
before do
gemfile <<-G
source "#{file_uri_for(gem_repo1)}"
gem "rack"
G
end
context "with --install" do
it "shows a deprecation warning", :bundler => "< 3" do
bundle "remove rack --install"
expect(err).to include "[DEPRECATED] The `--install` flag has been deprecated. `bundle install` is triggered by default."
end
pending "fails with a helpful message", :bundler => "3"
end
end
context "bundle console" do
before do
bundle "console", :raise_on_error => false
end
it "prints a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include \
"bundle console will be replaced by `bin/console` generated by `bundle gem <name>`"
end
pending "fails with a helpful message", :bundler => "3"
end
context "bundle viz" do
before do
graphviz_version = RUBY_VERSION >= "2.4" ? "1.2.5" : "1.2.4"
realworld_system_gems "ruby-graphviz --version #{graphviz_version}"
create_file "gems.rb", "source \"#{file_uri_for(gem_repo1)}\""
bundle "viz"
end
it "prints a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include "The `viz` command has been moved to the `bundle-viz` gem, see https://github.com/bundler/bundler-viz"
end
pending "fails with a helpful message", :bundler => "3"
end
describe "deprecating rubocop", :readline do
context "bundle gem --rubocop" do
before do
bundle "gem my_new_gem --rubocop", :raise_on_error => false
end
it "prints a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include \
"--rubocop is deprecated, use --linter=rubocop"
end
end
context "bundle gem --no-rubocop" do
before do
bundle "gem my_new_gem --no-rubocop", :raise_on_error => false
end
it "prints a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include \
"--no-rubocop is deprecated, use --linter"
end
end
context "bundle gem with gem.rubocop set to true" do
before do
bundle "gem my_new_gem", :env => { "BUNDLE_GEM__RUBOCOP" => "true" }, :raise_on_error => false
end
it "prints a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include \
"config gem.rubocop is deprecated; we've updated your config to use gem.linter instead"
end
end
context "bundle gem with gem.rubocop set to false" do
before do
bundle "gem my_new_gem", :env => { "BUNDLE_GEM__RUBOCOP" => "false" }, :raise_on_error => false
end
it "prints a deprecation warning", :bundler => "< 3" do
expect(deprecations).to include \
"config gem.rubocop is deprecated; we've updated your config to use gem.linter instead"
end
end
end
end
| 33.6625 | 244 | 0.62549 |
5db0a70dad8d198ef6d1f09226841016f5a333f9 | 302 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure end
module Azure::ServiceFabric end
module Azure::ServiceFabric::Mgmt end
module Azure::ServiceFabric::Mgmt::V2018_02_01 end
| 30.2 | 70 | 0.791391 |
b94086c7bb063e70d2455d8f9072bb52adeed829 | 24,531 | # frozen_string_literal: true
# Copyright 2020 Google LLC
#
# 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
#
# https://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.
# Auto-generated by gapic-generator-ruby. DO NOT EDIT!
require "google/cloud/errors"
require "google/cloud/recommendationengine/v1beta1/prediction_service_pb"
module Google
module Cloud
module RecommendationEngine
module V1beta1
module PredictionService
##
# Client for the PredictionService service.
#
# Service for making recommendation prediction.
#
class Client
include Paths
# @private
attr_reader :prediction_service_stub
##
# Configure the PredictionService Client class.
#
# See {::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client::Configuration}
# for a description of the configuration fields.
#
# ## Example
#
# To modify the configuration for all PredictionService clients:
#
# ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.configure do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def self.configure
@configure ||= begin
namespace = ["Google", "Cloud", "RecommendationEngine", "V1beta1"]
parent_config = while namespace.any?
parent_name = namespace.join "::"
parent_const = const_get parent_name
break parent_const.configure if parent_const.respond_to? :configure
namespace.pop
end
default_config = Client::Configuration.new parent_config
default_config.rpcs.predict.timeout = 600.0
default_config.rpcs.predict.retry_policy = {
initial_delay: 0.1,
max_delay: 60.0,
multiplier: 1.3,
retry_codes: [14, 4]
}
default_config
end
yield @configure if block_given?
@configure
end
##
# Configure the PredictionService Client instance.
#
# The configuration is set to the derived mode, meaning that values can be changed,
# but structural changes (adding new fields, etc.) are not allowed. Structural changes
# should be made on {Client.configure}.
#
# See {::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client::Configuration}
# for a description of the configuration fields.
#
# @yield [config] Configure the Client client.
# @yieldparam config [Client::Configuration]
#
# @return [Client::Configuration]
#
def configure
yield @config if block_given?
@config
end
##
# Create a new PredictionService client object.
#
# ## Examples
#
# To create a new PredictionService client with the default
# configuration:
#
# client = ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.new
#
# To create a new PredictionService client with a custom
# configuration:
#
# client = ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.new do |config|
# config.timeout = 10.0
# end
#
# @yield [config] Configure the PredictionService client.
# @yieldparam config [Client::Configuration]
#
def initialize
# These require statements are intentionally placed here to initialize
# the gRPC module only when it's required.
# See https://github.com/googleapis/toolkit/issues/446
require "gapic/grpc"
require "google/cloud/recommendationengine/v1beta1/prediction_service_services_pb"
# Create the configuration object
@config = Configuration.new Client.configure
# Yield the configuration if needed
yield @config if block_given?
# Create credentials
credentials = @config.credentials
# Use self-signed JWT if the scope and endpoint are unchanged from default,
# but only if the default endpoint does not have a region prefix.
enable_self_signed_jwt = @config.scope == Client.configure.scope &&
@config.endpoint == Client.configure.endpoint &&
[email protected](".").first.include?("-")
credentials ||= Credentials.default scope: @config.scope,
enable_self_signed_jwt: enable_self_signed_jwt
if credentials.is_a?(String) || credentials.is_a?(Hash)
credentials = Credentials.new credentials, scope: @config.scope
end
@quota_project_id = @config.quota_project
@quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id
@prediction_service_stub = ::Gapic::ServiceStub.new(
::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Stub,
credentials: credentials,
endpoint: @config.endpoint,
channel_args: @config.channel_args,
interceptors: @config.interceptors
)
end
# Service calls
##
# Makes a recommendation prediction. If using API Key based authentication,
# the API Key must be registered using the
# {::Google::Cloud::RecommendationEngine::V1beta1::PredictionApiKeyRegistry::Client PredictionApiKeyRegistry}
# service. [Learn more](/recommendations-ai/docs/setting-up#register-key).
#
# @overload predict(request, options = nil)
# Pass arguments to `predict` via a request object, either of type
# {::Google::Cloud::RecommendationEngine::V1beta1::PredictRequest} or an equivalent Hash.
#
# @param request [::Google::Cloud::RecommendationEngine::V1beta1::PredictRequest, ::Hash]
# A request object representing the call parameters. Required. To specify no
# parameters, or to keep all the default parameter values, pass an empty Hash.
# @param options [::Gapic::CallOptions, ::Hash]
# Overrides the default settings for this call, e.g, timeout, retries, etc. Optional.
#
# @overload predict(name: nil, user_event: nil, page_size: nil, page_token: nil, filter: nil, dry_run: nil, params: nil, labels: nil)
# Pass arguments to `predict` via keyword arguments. Note that at
# least one keyword argument is required. To specify no parameters, or to keep all
# the default parameter values, pass an empty Hash as a request object (see above).
#
# @param name [::String]
# Required. Full resource name of the format:
# `{name=projects/*/locations/global/catalogs/default_catalog/eventStores/default_event_store/placements/*}`
# The id of the recommendation engine placement. This id is used to identify
# the set of models that will be used to make the prediction.
#
# We currently support three placements with the following IDs by default:
#
# * `shopping_cart`: Predicts items frequently bought together with one or
# more catalog items in the same shopping session. Commonly displayed after
# `add-to-cart` events, on product detail pages, or on the shopping cart
# page.
#
# * `home_page`: Predicts the next product that a user will most likely
# engage with or purchase based on the shopping or viewing history of the
# specified `userId` or `visitorId`. For example - Recommendations for you.
#
# * `product_detail`: Predicts the next product that a user will most likely
# engage with or purchase. The prediction is based on the shopping or
# viewing history of the specified `userId` or `visitorId` and its
# relevance to a specified `CatalogItem`. Typically used on product detail
# pages. For example - More items like this.
#
# * `recently_viewed_default`: Returns up to 75 items recently viewed by the
# specified `userId` or `visitorId`, most recent ones first. Returns
# nothing if neither of them has viewed any items yet. For example -
# Recently viewed.
#
# The full list of available placements can be seen at
# https://console.cloud.google.com/recommendation/datafeeds/default_catalog/dashboard
# @param user_event [::Google::Cloud::RecommendationEngine::V1beta1::UserEvent, ::Hash]
# Required. Context about the user, what they are looking at and what action
# they took to trigger the predict request. Note that this user event detail
# won't be ingested to userEvent logs. Thus, a separate userEvent write
# request is required for event logging.
# @param page_size [::Integer]
# Optional. Maximum number of results to return per page. Set this property
# to the number of prediction results required. If zero, the service will
# choose a reasonable default.
# @param page_token [::String]
# Optional. The previous PredictResponse.next_page_token.
# @param filter [::String]
# Optional. Filter for restricting prediction results. Accepts values for
# tags and the `filterOutOfStockItems` flag.
#
# * Tag expressions. Restricts predictions to items that match all of the
# specified tags. Boolean operators `OR` and `NOT` are supported if the
# expression is enclosed in parentheses, and must be separated from the
# tag values by a space. `-"tagA"` is also supported and is equivalent to
# `NOT "tagA"`. Tag values must be double quoted UTF-8 encoded strings
# with a size limit of 1 KiB.
#
# * filterOutOfStockItems. Restricts predictions to items that do not have a
# stockState value of OUT_OF_STOCK.
#
# Examples:
#
# * tag=("Red" OR "Blue") tag="New-Arrival" tag=(NOT "promotional")
# * filterOutOfStockItems tag=(-"promotional")
# * filterOutOfStockItems
# @param dry_run [::Boolean]
# Optional. Use dryRun mode for this prediction query. If set to true, a
# dummy model will be used that returns arbitrary catalog items.
# Note that the dryRun mode should only be used for testing the API, or if
# the model is not ready.
# @param params [::Hash{::String => ::Google::Protobuf::Value, ::Hash}]
# Optional. Additional domain specific parameters for the predictions.
#
# Allowed values:
#
# * `returnCatalogItem`: Boolean. If set to true, the associated catalogItem
# object will be returned in the
# `PredictResponse.PredictionResult.itemMetadata` object in the method
# response.
# * `returnItemScore`: Boolean. If set to true, the prediction 'score'
# corresponding to each returned item will be set in the `metadata`
# field in the prediction response. The given 'score' indicates the
# probability of an item being clicked/purchased given the user's context
# and history.
# @param labels [::Hash{::String => ::String}]
# Optional. The labels for the predict request.
#
# * Label keys can contain lowercase letters, digits and hyphens, must start
# with a letter, and must end with a letter or digit.
# * Non-zero label values can contain lowercase letters, digits and hyphens,
# must start with a letter, and must end with a letter or digit.
# * No more than 64 labels can be associated with a given request.
#
# See https://goo.gl/xmQnxf for more information on and examples of labels.
#
# @yield [response, operation] Access the result along with the RPC operation
# @yieldparam response [::Gapic::PagedEnumerable<::Google::Cloud::RecommendationEngine::V1beta1::PredictResponse::PredictionResult>]
# @yieldparam operation [::GRPC::ActiveCall::Operation]
#
# @return [::Gapic::PagedEnumerable<::Google::Cloud::RecommendationEngine::V1beta1::PredictResponse::PredictionResult>]
#
# @raise [::Google::Cloud::Error] if the RPC is aborted.
#
def predict request, options = nil
raise ::ArgumentError, "request must be provided" if request.nil?
request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::RecommendationEngine::V1beta1::PredictRequest
# Converts hash and nil to an options object
options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h
# Customize the options with defaults
metadata = @config.rpcs.predict.metadata.to_h
# Set x-goog-api-client and x-goog-user-project headers
metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \
lib_name: @config.lib_name, lib_version: @config.lib_version,
gapic_version: ::Google::Cloud::RecommendationEngine::V1beta1::VERSION
metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id
header_params = {
"name" => request.name
}
request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&")
metadata[:"x-goog-request-params"] ||= request_params_header
options.apply_defaults timeout: @config.rpcs.predict.timeout,
metadata: metadata,
retry_policy: @config.rpcs.predict.retry_policy
options.apply_defaults metadata: @config.metadata,
retry_policy: @config.retry_policy
@prediction_service_stub.call_rpc :predict, request, options: options do |response, operation|
response = ::Gapic::PagedEnumerable.new @prediction_service_stub, :predict, request, response, operation, options
yield response, operation if block_given?
return response
end
rescue ::GRPC::BadStatus => e
raise ::Google::Cloud::Error.from_error(e)
end
##
# Configuration class for the PredictionService API.
#
# This class represents the configuration for PredictionService,
# providing control over timeouts, retry behavior, logging, transport
# parameters, and other low-level controls. Certain parameters can also be
# applied individually to specific RPCs. See
# {::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client::Configuration::Rpcs}
# for a list of RPCs that can be configured independently.
#
# Configuration can be applied globally to all clients, or to a single client
# on construction.
#
# # Examples
#
# To modify the global config, setting the timeout for predict
# to 20 seconds, and all remaining timeouts to 10 seconds:
#
# ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.configure do |config|
# config.timeout = 10.0
# config.rpcs.predict.timeout = 20.0
# end
#
# To apply the above configuration only to a new client:
#
# client = ::Google::Cloud::RecommendationEngine::V1beta1::PredictionService::Client.new do |config|
# config.timeout = 10.0
# config.rpcs.predict.timeout = 20.0
# end
#
# @!attribute [rw] endpoint
# The hostname or hostname:port of the service endpoint.
# Defaults to `"recommendationengine.googleapis.com"`.
# @return [::String]
# @!attribute [rw] credentials
# Credentials to send with calls. You may provide any of the following types:
# * (`String`) The path to a service account key file in JSON format
# * (`Hash`) A service account key as a Hash
# * (`Google::Auth::Credentials`) A googleauth credentials object
# (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html))
# * (`Signet::OAuth2::Client`) A signet oauth2 client object
# (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html))
# * (`GRPC::Core::Channel`) a gRPC channel with included credentials
# * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object
# * (`nil`) indicating no credentials
# @return [::Object]
# @!attribute [rw] scope
# The OAuth scopes
# @return [::Array<::String>]
# @!attribute [rw] lib_name
# The library name as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] lib_version
# The library version as recorded in instrumentation and logging
# @return [::String]
# @!attribute [rw] channel_args
# Extra parameters passed to the gRPC channel. Note: this is ignored if a
# `GRPC::Core::Channel` object is provided as the credential.
# @return [::Hash]
# @!attribute [rw] interceptors
# An array of interceptors that are run before calls are executed.
# @return [::Array<::GRPC::ClientInterceptor>]
# @!attribute [rw] timeout
# The call timeout in seconds.
# @return [::Numeric]
# @!attribute [rw] metadata
# Additional gRPC headers to be sent with the call.
# @return [::Hash{::Symbol=>::String}]
# @!attribute [rw] retry_policy
# The retry policy. The value is a hash with the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
# @return [::Hash]
# @!attribute [rw] quota_project
# A separate project against which to charge quota.
# @return [::String]
#
class Configuration
extend ::Gapic::Config
config_attr :endpoint, "recommendationengine.googleapis.com", ::String
config_attr :credentials, nil do |value|
allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil]
allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC
allowed.any? { |klass| klass === value }
end
config_attr :scope, nil, ::String, ::Array, nil
config_attr :lib_name, nil, ::String, nil
config_attr :lib_version, nil, ::String, nil
config_attr(:channel_args, { "grpc.service_config_disable_resolution" => 1 }, ::Hash, nil)
config_attr :interceptors, nil, ::Array, nil
config_attr :timeout, nil, ::Numeric, nil
config_attr :metadata, nil, ::Hash, nil
config_attr :retry_policy, nil, ::Hash, ::Proc, nil
config_attr :quota_project, nil, ::String, nil
# @private
def initialize parent_config = nil
@parent_config = parent_config unless parent_config.nil?
yield self if block_given?
end
##
# Configurations for individual RPCs
# @return [Rpcs]
#
def rpcs
@rpcs ||= begin
parent_rpcs = nil
parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config.respond_to?(:rpcs)
Rpcs.new parent_rpcs
end
end
##
# Configuration RPC class for the PredictionService API.
#
# Includes fields providing the configuration for each RPC in this service.
# Each configuration object is of type `Gapic::Config::Method` and includes
# the following configuration fields:
#
# * `timeout` (*type:* `Numeric`) - The call timeout in seconds
# * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers
# * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields
# include the following keys:
# * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds.
# * `:max_delay` (*type:* `Numeric`) - The max delay in seconds.
# * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier.
# * `:retry_codes` (*type:* `Array<String>`) - The error codes that should
# trigger a retry.
#
class Rpcs
##
# RPC-specific configuration for `predict`
# @return [::Gapic::Config::Method]
#
attr_reader :predict
# @private
def initialize parent_rpcs = nil
predict_config = parent_rpcs.predict if parent_rpcs.respond_to? :predict
@predict = ::Gapic::Config::Method.new predict_config
yield self if block_given?
end
end
end
end
end
end
end
end
end
| 51.644211 | 145 | 0.561861 |
0368ee2041d739bd523e64ade469a932db53423e | 7,300 | # 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.
require 'date'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# Parameters detailing how to provision the initial data of the system.
#
# This class has direct subclasses. If you are using this class as input to a service operations then you should favor using a subclass over the base class
class Mysql::Models::CreateDbSystemSourceDetails
SOURCE_TYPE_ENUM = [
SOURCE_TYPE_NONE = 'NONE'.freeze,
SOURCE_TYPE_BACKUP = 'BACKUP'.freeze,
SOURCE_TYPE_IMPORTURL = 'IMPORTURL'.freeze
].freeze
# **[Required]** The specific source identifier.
#
# @return [String]
attr_reader :source_type
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'source_type': :'sourceType'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'source_type': :'String'
# rubocop:enable Style/SymbolLiteral
}
end
# rubocop:disable Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity, Metrics/AbcSize
# Given the hash representation of a subtype of this class,
# use the info in the hash to return the class of the subtype.
def self.get_subtype(object_hash)
type = object_hash[:'sourceType'] # rubocop:disable Style/SymbolLiteral
return 'OCI::Mysql::Models::CreateDbSystemSourceFromBackupDetails' if type == 'BACKUP'
return 'OCI::Mysql::Models::CreateDbSystemSourceFromNoneDetails' if type == 'NONE'
return 'OCI::Mysql::Models::CreateDbSystemSourceImportFromUrlDetails' if type == 'IMPORTURL'
# TODO: Log a warning when the subtype is not found.
'OCI::Mysql::Models::CreateDbSystemSourceDetails'
end
# rubocop:enable Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity, Metrics/AbcSize
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
# @option attributes [String] :source_type The value to assign to the {#source_type} property
def initialize(attributes = {})
return unless attributes.is_a?(Hash)
# convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v }
self.source_type = attributes[:'sourceType'] if attributes[:'sourceType']
self.source_type = "NONE" if source_type.nil? && !attributes.key?(:'sourceType') # rubocop:disable Style/StringLiterals
raise 'You cannot provide both :sourceType and :source_type' if attributes.key?(:'sourceType') && attributes.key?(:'source_type')
self.source_type = attributes[:'source_type'] if attributes[:'source_type']
self.source_type = "NONE" if source_type.nil? && !attributes.key?(:'sourceType') && !attributes.key?(:'source_type') # rubocop:disable Style/StringLiterals
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity
# rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral
# Custom attribute writer method checking allowed values (enum).
# @param [Object] source_type Object to be assigned
def source_type=(source_type)
raise "Invalid value for 'source_type': this must be one of the values in SOURCE_TYPE_ENUM." if source_type && !SOURCE_TYPE_ENUM.include?(source_type)
@source_type = source_type
end
# rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# Checks equality by comparing each attribute.
# @param [Object] other the other object to be compared
def ==(other)
return true if equal?(other)
self.class == other.class &&
source_type == other.source_type
end
# rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines
# @see the `==` method
# @param [Object] other the other object to be compared
def eql?(other)
self == other
end
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# Calculates hash code according to all attributes.
# @return [Fixnum] Hash code
def hash
[source_type].hash
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# rubocop:disable Metrics/AbcSize, Layout/EmptyLines
# 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.swagger_types.each_pair do |key, type|
if type =~ /^Array<(.*)>/i
# check to ensure the input is an array given that the the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
public_method("#{key}=").call(
attributes[self.class.attribute_map[key]]
.map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) }
)
end
elsif !attributes[self.class.attribute_map[key]].nil?
public_method("#{key}=").call(
OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]])
)
end
# or else data not found in attributes(hash), not an issue as the data can be optional
end
self
end
# rubocop:enable Metrics/AbcSize, Layout/EmptyLines
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
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 = public_method(attr).call
next if value.nil? && !instance_variable_defined?("@#{attr}")
hash[param] = _to_hash(value)
end
hash
end
private
# 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
# rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
| 38.219895 | 245 | 0.68863 |
4aaf9f0ab4ea03677891b460da8a2973ffa72ee5 | 4,708 | require 'sqlite3'
$db = SQLite3::Database.open 'congress_poll_results.db'
def print_arizona_reps
puts 'AZ REPRESENTATIVES'
az_reps = $db.execute("SELECT name FROM congress_members WHERE location = 'AZ'")
az_reps.each { |rep| puts rep }
end
# Print out the number of years served as well as the name of the longest running reps
# output should look like: Rep. C. W. Bill Young - 41 years
#BOUND FOR GAURDING AGAINST SQL INJECTION
def print_longest_serving_reps(minimum_years)
puts 'LONGEST SERVING REPRESENTATIVES (greater than 35 years)'
longest_reps = $db.execute("SELECT name, years_in_congress FROM congress_members WHERE years_in_congress > ?",[minimum_years])
longest_reps.each {|rep, years| puts "#{rep} - #{years} years"}
end
# Need to be able to pass the grade level as an argument, look in schema for "grade_current" column
#BOUND FOR GAURDING AGAINST SQL INJECTION
def print_lowest_grade_level_speakers(maximum_level)
puts 'LOWEST GRADE LEVEL SPEAKERS (less than < 8th grade)'
lowest_grade_level = $db.execute("SELECT name, ROUND(grade_current, 2) FROM congress_members WHERE grade_current < ?",[maximum_level])
lowest_grade_level.each {|rep, level| puts "#{rep} - #{level} grade level"}
end
# Make a method to print the following states representatives as well:
# (New Jersey, New York, Maine, Florida, and Alaska)
# Version 1 pulling all data for target fields into array and filtering target data from there
def print_state_reps(*states)
puts 'REPRESENTATIVES BY STATE'
state_reps = $db.execute('SELECT name, location FROM congress_members')
states.each do |state|
puts "#{state} REPRESENTATIVES"
state_reps.each do |rep, st|
if st == state
puts rep
end
end
puts ''
end
end
# Version 2 with binding parameters to guard against SQL injection
def print_state_reps1(*states)
puts 'REPRESENTATIVES BY STATE'
states.each do |state|
puts "#{state} REPRESENTATIVES"
state_reps = $db.execute("SELECT name FROM congress_members WHERE location = ?",[state])
state_reps.each {|st| puts st}
puts ''
end
end
#BONUSES
# Create a listing of all of the Politicians and the number of votes they received
# output should look like: Sen. John McCain - 7,323 votes
def print_rep_votes
puts 'VOTES BY POLITICIAN'
number_votes = $db.execute("SELECT c.name, COUNT(*)AS number_votes FROM congress_members c,
votes v WHERE c.id = v.politician_id GROUP BY c.name")
number_votes.each {|rep, votes| puts "#{rep} - #{votes} votes"}
end
# Create a listing of each Politician and the voter that voted for them
# output should include the senators name, then a long list of voters separated by a comma
def print_rep_voters
puts 'VOTERS BY POLITICIAN'
rep_concat_voter = $db.execute("SELECT c.name, (r.first_name || ' ' || r.last_name) FROM congress_members c,
votes v, voters r WHERE (c.id = v.politician_id) AND (r.id = v.voter_id) ORDER BY c.name")
rep_voters = Hash[rep_concat_voter.chunk{|x| x[0]}.to_a]
rep_voters.each_pair do |key, value|
print "#{key}: "
puts (value.each {|x| x.delete_at(0)}).join(', ')
end
end
def print_separator
puts
puts "------------------------------------------------------------------------------"
puts
end
print_arizona_reps
print_separator
# Print out the number of years served as well as the name of the longest running reps
# output should look like: Rep. C. W. Bill Young - 41 years
print_longest_serving_reps(35)
print_separator
# Need to be able to pass the grade level as an argument, look in schema for "grade_current" column
print_lowest_grade_level_speakers(8)
print_separator
# Make a method to print the following states representatives as well:
# (New Jersey, New York, Maine, Florida, and Alaska)
# Two versions:
print_state_reps('NJ','NY', 'ME', 'FL', 'AK')
print_state_reps1('NJ','NY', 'ME', 'FL', 'AK')
print_separator
##### BONUS #######
#1. (bonus) - Stop SQL injection attacks! Statmaster learned that interpolation of variables in SQL
# statements leaves some security vulnerabilities. Use the google to figure out how to protect from
# this type of attack.
# BIND PARAMETERS; EXAMPLES:
# db.execute( "INSERT INTO Products ( stockID, Name ) VALUES ( ?, ? )", [id, name])
# db.execute ("SELECT name FROM congress_members WHERE location = ?",[state])
# 2. Create a listing of all of the Politicians and the number of votes they received
# output should look like: Sen. John McCain - 7,323 votes
print_rep_votes
print_separator
# 3. Create a listing of each Politician and the voter that voted for them
# output should include the senators name, then a long list of voters separated by a comma
print_rep_voters | 37.967742 | 136 | 0.722812 |
1d442ac59f74016f688a01bf04239619d9703e7a | 1,314 | # frozen_string_literal: true
require 'rails_helper'
describe Mutations::ApplySquadToMatch, type: :graphql do
subject { described_class }
let(:user) { create :user }
let(:team) { create :team, user: }
let(:match) { create :match, team: }
let(:squad) { create :squad, team: }
it { is_expected.to accept_argument(:match_id).of_type('ID!') }
it { is_expected.to accept_argument(:squad_id).of_type('ID!') }
it { is_expected.to have_a_field(:match).returning('Match!') }
graphql_operation <<-GQL
mutation applySquadToMatch($matchId: ID!, $squadId: ID!) {
applySquadToMatch(matchId: $matchId, squadId: $squadId) {
match { id }
}
}
GQL
graphql_variables do
{
matchId: match.id,
squadId: squad.id
}
end
graphql_context do
{ current_user: user }
end
it 'populates Match caps based on Squad players' do
execute_graphql
expect(match.caps.pluck(:player_id))
.to be == squad.squad_players.pluck(:player_id)
end
it 'populates Match caps based on Squad positions' do
execute_graphql
expect(match.caps.pluck(:pos))
.to be == squad.squad_players.pluck(:pos)
end
it 'returns the affected Squad' do
expect(response_data.dig('applySquadToMatch', 'match', 'id'))
.to be == match.id.to_s
end
end
| 24.792453 | 65 | 0.664384 |
0816e8151e248c9971038adfba0decfa0b1a7f6f | 155 | class DeleteMemberDndFromUsers < ActiveRecord::Migration[4.2]
def change
remove_column :users, :member_dnd
remove_column :users, :role
end
end
| 22.142857 | 61 | 0.754839 |
186cb17f405cc7d6b3d2a3cd2c8af05f0ec33850 | 1,698 | # typed: false
# frozen_string_literal: true
# This file was generated by GoReleaser. DO NOT EDIT.
class Nuke < Formula
desc "☢️ Force quit all applications with one terminal command"
homepage "https://github.com/gleich/nuke"
version "5.2.1"
on_macos do
if Hardware::CPU.intel?
url "https://github.com/gleich/nuke/releases/download/v5.2.1/nuke_5.2.1_darwin_amd64.tar.gz"
sha256 "9bd0e1e8b1940dc95284848f708565376e9954a80fa7d336d470ca64e1f4e474"
def install
bin.install "nuke"
end
end
if Hardware::CPU.arm?
url "https://github.com/gleich/nuke/releases/download/v5.2.1/nuke_5.2.1_darwin_arm64.tar.gz"
sha256 "291833586afe988bb08c076b6afa134709753ec2df3db7ffee293eb185264a72"
def install
bin.install "nuke"
end
end
end
on_linux do
if Hardware::CPU.arm? && !Hardware::CPU.is_64_bit?
url "https://github.com/gleich/nuke/releases/download/v5.2.1/nuke_5.2.1_linux_armv6.tar.gz"
sha256 "3cce2952d88ff66949096b173cab1af8d6920961aa611387cee0a54750b9dd5e"
def install
bin.install "nuke"
end
end
if Hardware::CPU.arm? && Hardware::CPU.is_64_bit?
url "https://github.com/gleich/nuke/releases/download/v5.2.1/nuke_5.2.1_linux_arm64.tar.gz"
sha256 "b94cef57a3944ab7e7056ebad1ccd283162f2d8203061276a99c5063a22ecdd8"
def install
bin.install "nuke"
end
end
if Hardware::CPU.intel?
url "https://github.com/gleich/nuke/releases/download/v5.2.1/nuke_5.2.1_linux_amd64.tar.gz"
sha256 "49900888d0adf563fb81ce5e3fa0c30b07c425e401ab343246c1fed014d9c756"
def install
bin.install "nuke"
end
end
end
end
| 30.321429 | 98 | 0.706125 |
d564cacd2d8f5869964472979f1e3b280e31bc1f | 2,215 | # frozen_string_literal: true
require 'spec_helper'
describe Notes::PostProcessService do
let(:project) { create(:project) }
let(:issue) { create(:issue, project: project) }
let(:user) { create(:user) }
describe '#execute' do
before do
project.add_maintainer(user)
note_opts = {
note: 'Awesome comment',
noteable_type: 'Issue',
noteable_id: issue.id
}
@note = Notes::CreateService.new(project, user, note_opts).execute
end
it do
expect(project).to receive(:execute_hooks)
expect(project).to receive(:execute_services)
described_class.new(@note).execute
end
context 'with a confidential issue' do
let(:issue) { create(:issue, :confidential, project: project) }
it "doesn't call note hooks/services" do
expect(project).not_to receive(:execute_hooks).with(anything, :note_hooks)
expect(project).not_to receive(:execute_services).with(anything, :note_hooks)
described_class.new(@note).execute
end
it "calls confidential-note hooks/services" do
expect(project).to receive(:execute_hooks).with(anything, :confidential_note_hooks)
expect(project).to receive(:execute_services).with(anything, :confidential_note_hooks)
described_class.new(@note).execute
end
end
context 'when the noteable is a design' do
let_it_be(:noteable) { create(:design, :with_file) }
let_it_be(:discussion_note) { create_note }
subject { described_class.new(note).execute }
def create_note(in_reply_to: nil)
create(:diff_note_on_design, noteable: noteable, in_reply_to: in_reply_to)
end
context 'when the note is the start of a new discussion' do
let(:note) { discussion_note }
it 'creates a new system note' do
expect { subject }.to change { Note.system.count }.by(1)
end
end
context 'when the note is a reply within a discussion' do
let_it_be(:note) { create_note(in_reply_to: discussion_note) }
it 'does not create a new system note' do
expect { subject }.not_to change { Note.system.count }
end
end
end
end
end
| 29.533333 | 94 | 0.659594 |
ffe4a79302570ae0350ceb79412923b3cfb9c838 | 694 | require 'test_helper'
class StaticPagesControllerTest < ActionDispatch::IntegrationTest
def setup
@base_title = "Ruby on Rails Tutorial Sample App"
end
test "should get home" do
get root_path
assert_response :success
assert_select "title", @base_title
end
test "should get help" do
get help_url
assert_response :success
assert_select "title", "Help | #{@base_title}"
end
test "should get about" do
get about_url
assert_response :success
assert_select "title", "About | #{@base_title}"
end
test "should get contact" do
get contact_url
assert_response :success
assert_select "title", "Contact | #{@base_title}"
end
end
| 21.6875 | 65 | 0.700288 |
268e37e6ead90be04abbe61f0a4ab9277c80c2b9 | 14,763 | # -*- encoding: utf-8 -*-
require 'spec_helper'
RSpec.describe Brcobranca::Boleto::BancoBrasil do #:nodoc:[all]
before do
@valid_attributes = {
valor: 0.0,
local_pagamento: 'QUALQUER BANCO ATÉ O VENCIMENTO',
cedente: 'Kivanio Barbosa',
documento_cedente: '12345678912',
sacado: 'Claudio Pozzebom',
sacado_documento: '12345678900',
agencia: '4042',
conta_corrente: '61900',
convenio: 12_387_989,
numero_documento: '777700168'
}
end
it 'Criar nova instancia com atributos padrões' do
boleto_novo = described_class.new
expect(boleto_novo.banco).to eql('001')
expect(boleto_novo.especie_documento).to eql('DM')
expect(boleto_novo.especie).to eql('R$')
expect(boleto_novo.moeda).to eql('9')
expect(boleto_novo.data_documento).to eql(Date.today)
expect(boleto_novo.data_vencimento).to eql(Date.today)
expect(boleto_novo.aceite).to eql('S')
expect(boleto_novo.quantidade).to eql(1)
expect(boleto_novo.valor).to eql(0.0)
expect(boleto_novo.valor_documento).to eql(0.0)
expect(boleto_novo.local_pagamento).to eql('QUALQUER BANCO ATÉ O VENCIMENTO')
expect(boleto_novo.carteira).to eql('18')
expect(boleto_novo.codigo_servico).to be_falsey
end
it 'Criar nova instancia com atributos válidos' do
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.banco).to eql('001')
expect(boleto_novo.especie_documento).to eql('DM')
expect(boleto_novo.especie).to eql('R$')
expect(boleto_novo.moeda).to eql('9')
expect(boleto_novo.data_documento).to eql(Date.today)
expect(boleto_novo.data_vencimento).to eql(Date.today)
expect(boleto_novo.aceite).to eql('S')
expect(boleto_novo.quantidade).to eql(1)
expect(boleto_novo.valor).to eql(0.0)
expect(boleto_novo.valor_documento).to eql(0.0)
expect(boleto_novo.local_pagamento).to eql('QUALQUER BANCO ATÉ O VENCIMENTO')
expect(boleto_novo.cedente).to eql('Kivanio Barbosa')
expect(boleto_novo.documento_cedente).to eql('12345678912')
expect(boleto_novo.sacado).to eql('Claudio Pozzebom')
expect(boleto_novo.sacado_documento).to eql('12345678900')
expect(boleto_novo.conta_corrente).to eql('00061900')
expect(boleto_novo.agencia).to eql('4042')
expect(boleto_novo.convenio).to eql(12_387_989)
expect(boleto_novo.numero_documento).to eql('777700168')
expect(boleto_novo.carteira).to eql('18')
expect(boleto_novo.codigo_servico).to be_falsey
end
it 'Montar código de barras para convenio de 8 digitos e nosso número de 9' do
@valid_attributes[:valor] = 135.00
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-01')
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.codigo_barras_segunda_parte).to eql('0000001238798977770016818')
expect(boleto_novo.codigo_barras).to eql('00193376900000135000000001238798977770016818')
expect(boleto_novo.codigo_barras.linha_digitavel).to eql('00190.00009 01238.798977 77700.168188 3 37690000013500')
expect(boleto_novo.conta_corrente_dv).to eql(0)
expect(boleto_novo.nosso_numero_dv).to eql(7)
@valid_attributes[:data_vencimento] = Date.parse('2008-02-02')
@valid_attributes[:numero_documento] = '7700168'
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.codigo_barras_segunda_parte).to eql('0000001238798900770016818')
expect(boleto_novo.codigo_barras).to eql('00193377000000135000000001238798900770016818')
expect(boleto_novo.codigo_barras.linha_digitavel).to eql('00190.00009 01238.798902 07700.168185 3 37700000013500')
expect(boleto_novo.conta_corrente_dv).to eql(0)
expect(boleto_novo.nosso_numero_dv).to eql(7)
end
it 'Montar código de barras para convenio de 7 digitos e nosso numero de 10' do
@valid_attributes[:valor] = 135.00
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-03')
@valid_attributes[:convenio] = 1_238_798
@valid_attributes[:numero_documento] = '7777700168'
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.codigo_barras_segunda_parte).to eql('0000001238798777770016818')
expect(boleto_novo.codigo_barras).to eql('00193377100000135000000001238798777770016818')
expect(boleto_novo.codigo_barras.linha_digitavel).to eql('00190.00009 01238.798779 77700.168188 3 37710000013500')
expect(boleto_novo.conta_corrente_dv).to eql(0)
@valid_attributes[:valor] = 723.56
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-03')
@valid_attributes[:convenio] = 1_238_798
@valid_attributes[:numero_documento] = '7777700168'
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.codigo_barras_segunda_parte).to eql('0000001238798777770016818')
expect(boleto_novo.codigo_barras).to eql('00195377100000723560000001238798777770016818')
expect(boleto_novo.codigo_barras.linha_digitavel).to eql('00190.00009 01238.798779 77700.168188 5 37710000072356')
expect(boleto_novo.conta_corrente_dv).to eql(0)
@valid_attributes[:valor] = 723.56
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-01')
@valid_attributes[:convenio] = 1_238_798
@valid_attributes[:numero_documento] = '7777700168'
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.codigo_barras_segunda_parte).to eql('0000001238798777770016818')
expect(boleto_novo.codigo_barras).to eql('00194376900000723560000001238798777770016818')
expect(boleto_novo.codigo_barras.linha_digitavel).to eql('00190.00009 01238.798779 77700.168188 4 37690000072356')
expect(boleto_novo.conta_corrente_dv).to eql(0)
end
it 'Montar código de barras para convenio de 6 digitos e nosso numero de 5' do
@valid_attributes[:valor] = 135.00
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-01')
@valid_attributes[:convenio] = 123_879
@valid_attributes[:numero_documento] = '1234'
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.conta_corrente_dv).to eql(0)
expect(boleto_novo.codigo_barras_segunda_parte).to eql('1238790123440420006190018')
expect(boleto_novo.codigo_barras).to eql('00192376900000135001238790123440420006190018')
expect(boleto_novo.codigo_barras.linha_digitavel).to eql('00191.23876 90123.440423 00061.900189 2 37690000013500')
end
it 'Montar código de barras para convenio de 6 digitos, nosso numero de 17 e carteira 16' do
@valid_attributes[:valor] = 135.00
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-01')
@valid_attributes[:convenio] = 123_879
@valid_attributes[:numero_documento] = '1234567899'
@valid_attributes[:carteira] = '16'
@valid_attributes[:codigo_servico] = true
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.conta_corrente_dv).to eql(0)
expect(boleto_novo.codigo_barras_segunda_parte).to eql('1238790000000123456789921')
expect(boleto_novo.codigo_barras).to eql('00199376900000135001238790000000123456789921')
expect(boleto_novo.codigo_barras.linha_digitavel).to eql('00191.23876 90000.000126 34567.899215 9 37690000013500')
end
it 'Montar código de barras para convenio de 6 digitos, nosso numero de 17 e carteira 18' do
@valid_attributes[:valor] = 135.00
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-01')
@valid_attributes[:convenio] = 123_879
@valid_attributes[:numero_documento] = '1234567899'
@valid_attributes[:carteira] = '18'
@valid_attributes[:codigo_servico] = true
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.conta_corrente_dv).to eql(0)
expect(boleto_novo.codigo_barras_segunda_parte).to eql('1238790000000123456789921')
expect(boleto_novo.codigo_barras).to eql('00199376900000135001238790000000123456789921')
expect(boleto_novo.codigo_barras.linha_digitavel).to eql('00191.23876 90000.000126 34567.899215 9 37690000013500')
end
it 'Não montar código de barras para convenio de 6 digitos, nosso numero de 17 e carteira 17' do
@valid_attributes[:valor] = 135.00
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-01')
@valid_attributes[:convenio] = 123_879
@valid_attributes[:numero_documento] = '1234567899'
@valid_attributes[:carteira] = '17'
@valid_attributes[:codigo_servico] = true
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.conta_corrente_dv).to eql(0)
expect { boleto_novo.codigo_barras_segunda_parte }.to raise_error(RuntimeError)
expect { boleto_novo.codigo_barras_segunda_parte }.to raise_error('Só é permitido emitir boletos com nosso número de 17 dígitos com carteiras 16 ou 18. Sua carteira atual é 17')
end
it 'Montar código de barras para convenio de 4 digitos e nosso numero de 7' do
@valid_attributes[:valor] = 135.00
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-01')
@valid_attributes[:convenio] = 1238
@valid_attributes[:numero_documento] = '123456'
@valid_attributes[:codigo_servico] = true
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.conta_corrente_dv).to eql(0)
expect(boleto_novo.codigo_barras_segunda_parte).to eql('1238012345640420006190018')
expect(boleto_novo.codigo_barras).to eql('00191376900000135001238012345640420006190018')
expect(boleto_novo.codigo_barras.linha_digitavel).to eql('00191.23801 12345.640424 00061.900189 1 37690000013500')
end
it 'Não permitir gerar boleto com atributos inválido' do
boleto_novo = described_class.new
expect { boleto_novo.codigo_barras }.to raise_error(Brcobranca::NaoImplementado)
expect(boleto_novo.errors.count).to eql(2)
end
it 'Calcular agencia_dv' do
boleto_novo = described_class.new(@valid_attributes)
boleto_novo.agencia = '85068014982'
expect(boleto_novo.agencia_dv).to eql(9)
boleto_novo.agencia = '05009401448'
expect(boleto_novo.agencia_dv).to eql(1)
boleto_novo.agencia = '12387987777700168'
expect(boleto_novo.agencia_dv).to eql(2)
boleto_novo.agencia = '4042'
expect(boleto_novo.agencia_dv).to eql(8)
boleto_novo.agencia = '61900'
expect(boleto_novo.agencia_dv).to eql(0)
boleto_novo.agencia = '0719'
expect(boleto_novo.agencia_dv).to eql(6)
boleto_novo.agencia = 85_068_014_982
expect(boleto_novo.agencia_dv).to eql(9)
boleto_novo.agencia = 5_009_401_448
expect(boleto_novo.agencia_dv).to eql(1)
boleto_novo.agencia = 12_387_987_777_700_168
expect(boleto_novo.agencia_dv).to eql(2)
boleto_novo.agencia = 4042
expect(boleto_novo.agencia_dv).to eql(8)
boleto_novo.agencia = 61_900
expect(boleto_novo.agencia_dv).to eql(0)
boleto_novo.agencia = 719
expect(boleto_novo.agencia_dv).to eql(6)
end
it 'Montar nosso_numero_boleto' do
boleto_novo = described_class.new(@valid_attributes)
boleto_novo.numero_documento = '4042'
expect(boleto_novo.nosso_numero_boleto).to eql('12387989000004042-4')
expect(boleto_novo.nosso_numero_dv).to eql(4)
boleto_novo.numero_documento = '61900'
expect(boleto_novo.nosso_numero_boleto).to eql('12387989000061900-7')
expect(boleto_novo.nosso_numero_dv).to eql(7)
boleto_novo.numero_documento = '0719'
expect(boleto_novo.nosso_numero_boleto).to eql('12387989000000719-2')
expect(boleto_novo.nosso_numero_dv).to eql(2)
boleto_novo.numero_documento = 4042
expect(boleto_novo.nosso_numero_boleto).to eql('12387989000004042-4')
expect(boleto_novo.nosso_numero_dv).to eql(4)
boleto_novo.numero_documento = 61_900
expect(boleto_novo.nosso_numero_boleto).to eql('12387989000061900-7')
expect(boleto_novo.nosso_numero_dv).to eql(7)
boleto_novo.numero_documento = 719
expect(boleto_novo.nosso_numero_boleto).to eql('12387989000000719-2')
expect(boleto_novo.nosso_numero_dv).to eql(2)
end
it 'Montar agencia_conta_boleto' do
boleto_novo = described_class.new(@valid_attributes)
expect(boleto_novo.agencia_conta_boleto).to eql('4042-8 / 00061900-0')
boleto_novo.agencia = '0719'
expect(boleto_novo.agencia_conta_boleto).to eql('0719-6 / 00061900-0')
boleto_novo.agencia = '0548'
boleto_novo.conta_corrente = '1448'
expect(boleto_novo.agencia_conta_boleto).to eql('0548-7 / 00001448-6')
end
it 'Busca logotipo do banco' do
boleto_novo = described_class.new
expect(File.exist?(boleto_novo.logotipo)).to be_truthy
expect(File.stat(boleto_novo.logotipo).zero?).to be_falsey
end
it 'Gerar boleto nos formatos válidos com método to_' do
@valid_attributes[:valor] = 135.00
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-03')
@valid_attributes[:convenio] = 1_238_798
@valid_attributes[:numero_documento] = '7777700168'
boleto_novo = described_class.new(@valid_attributes)
%w(pdf jpg tif png).each do |format|
file_body = boleto_novo.send("to_#{format}".to_sym)
tmp_file = Tempfile.new('foobar.' << format)
tmp_file.puts file_body
tmp_file.close
expect(File.exist?(tmp_file.path)).to be_truthy
expect(File.stat(tmp_file.path).zero?).to be_falsey
expect(File.delete(tmp_file.path)).to eql(1)
expect(File.exist?(tmp_file.path)).to be_falsey
end
end
it 'Gerar boleto nos formatos válidos' do
@valid_attributes[:valor] = 135.00
@valid_attributes[:data_documento] = Date.parse('2008-02-01')
@valid_attributes[:data_vencimento] = Date.parse('2008-02-03')
@valid_attributes[:convenio] = 1_238_798
@valid_attributes[:numero_documento] = '7777700168'
boleto_novo = described_class.new(@valid_attributes)
%w(pdf jpg tif png).each do |format|
file_body = boleto_novo.to(format)
tmp_file = Tempfile.new('foobar.' << format)
tmp_file.puts file_body
tmp_file.close
expect(File.exist?(tmp_file.path)).to be_truthy
expect(File.stat(tmp_file.path).zero?).to be_falsey
expect(File.delete(tmp_file.path)).to eql(1)
expect(File.exist?(tmp_file.path)).to be_falsey
end
end
end
| 47.622581 | 181 | 0.74978 |
4a13345be0402c805ce1a0801cc5b39d89c8956b | 136 | require "sfn"
module Sfn
# Container for monkey patches
module MonkeyPatch
autoload :Stack, "sfn/monkey_patch/stack"
end
end
| 15.111111 | 45 | 0.735294 |
1adfb0a8c0af603d50ece193268648f4c4a8304f | 1,462 | # -*- encoding: utf-8 -*-
# stub: rspec 2.99.0 ruby lib
Gem::Specification.new do |s|
s.name = "rspec"
s.version = "2.99.0"
s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.require_paths = ["lib"]
s.authors = ["Steven Baker", "David Chelimsky"]
s.date = "2014-06-01"
s.description = "BDD for Ruby"
s.email = "[email protected]"
s.extra_rdoc_files = ["README.md"]
s.files = ["README.md"]
s.homepage = "http://github.com/rspec"
s.licenses = ["MIT"]
s.rdoc_options = ["--charset=UTF-8"]
s.rubyforge_project = "rspec"
s.rubygems_version = "2.5.1"
s.summary = "rspec-2.99.0"
s.installed_by_version = "2.5.1" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then
s.add_runtime_dependency(%q<rspec-core>, ["~> 2.99.0"])
s.add_runtime_dependency(%q<rspec-expectations>, ["~> 2.99.0"])
s.add_runtime_dependency(%q<rspec-mocks>, ["~> 2.99.0"])
else
s.add_dependency(%q<rspec-core>, ["~> 2.99.0"])
s.add_dependency(%q<rspec-expectations>, ["~> 2.99.0"])
s.add_dependency(%q<rspec-mocks>, ["~> 2.99.0"])
end
else
s.add_dependency(%q<rspec-core>, ["~> 2.99.0"])
s.add_dependency(%q<rspec-expectations>, ["~> 2.99.0"])
s.add_dependency(%q<rspec-mocks>, ["~> 2.99.0"])
end
end
| 34 | 105 | 0.632695 |
0374b36260205e367f1f868f5ef2f1355eca03bd | 1,072 | # -*- coding: utf-8 -*-
require 'helper'
class TestRegressionChartAxis27 < Test::Unit::TestCase
def setup
setup_dir_var
end
def teardown
@tempfile.close(true)
end
def test_chart_axis27
@xlsx = 'chart_axis27.xlsx'
workbook = WriteXLSX.new(@io)
worksheet = workbook.add_worksheet
chart = workbook.add_chart(:type => 'line', :embedded => 1)
# For testing, copy the randomly generated axis ids in the target xlsx file.
chart.instance_variable_set(:@axis_ids, [73048448, 73049984])
data = [
[ 1, 2, 3, 4, 5 ],
[ 2, 4, 6, 8, 10 ],
[ 3, 6, 9, 12, 15 ]
]
chart.set_x_axis(:num_font => {:rotation => -35})
worksheet.write('A1', data)
chart.add_series(:values => '=Sheet1!$A$1:$A$5')
chart.add_series(:values => '=Sheet1!$B$1:$B$5')
chart.add_series(:values => '=Sheet1!$C$1:$C$5')
worksheet.insert_chart('E9', chart)
workbook.close
compare_for_regression(
nil,
{ 'xl/charts/chart1.xml' => ['<a:defRPr'] }
)
end
end
| 23.822222 | 80 | 0.586754 |
28c43367863ec48b23a4e41ce197ee8e8827ee20 | 1,539 | def update_carrier_type
CarrierType.find_each do |carrier_type|
case carrier_type.name
when "volume"
carrier_type = CarrierType.find_by(name: 'volume')
if carrier_type
unless carrier_type.attachment.attached?
carrier_type.attachment.attach(io: File.open("#{File.dirname(__FILE__)}/../../app/assets/images/enju_biblio/book.png"), filename: 'book.png')
carrier_type.save!
end
end
when "audio_disc"
carrier_type = CarrierType.find_by(name: 'audio_disc')
if carrier_type
unless carrier_type.attachment.attached?
carrier_type.attachment.attach(io: File.open("#{File.dirname(__FILE__)}/../../app/assets/images/enju_biblio/cd.png"), filename: 'cd.png')
carrier_type.save!
end
end
when "videodisc"
carrier_type = CarrierType.find_by(name: 'videodisc')
if carrier_type
unless carrier_type.attachment.attached?
carrier_type.attachment.attach(io: File.open("#{File.dirname(__FILE__)}/../../app/assets/images/enju_biblio/dvd.png"), filename: 'dvd.png')
carrier_type.save!
end
end
when "online_resource"
carrier_type = CarrierType.find_by(name: 'online_resource')
if carrier_type
unless carrier_type.attachment.attached?
carrier_type.attachment.attach(io: File.open("#{File.dirname(__FILE__)}/../../app/assets/images/enju_biblio/monitor.png"), filename: 'monitor.png')
carrier_type.save!
end
end
end
end
end
| 39.461538 | 157 | 0.666017 |
f7aea768557b91abea56b8917eb1254c9ffd8194 | 1,969 | # Redmine - project management software
# Copyright (C) 2006-2017 Jean-Philippe Lang
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
require File.expand_path('../../test_helper', __FILE__)
class DefaultDataTest < ActiveSupport::TestCase
include Redmine::I18n
fixtures :roles
def test_no_data
assert !Redmine::DefaultData::Loader::no_data?
clear_data
assert Redmine::DefaultData::Loader::no_data?
end
def test_load
clear_data
assert Redmine::DefaultData::Loader::load('en')
assert_not_nil DocumentCategory.first
assert_not_nil IssuePriority.first
assert_not_nil TimeEntryActivity.first
assert_not_nil WorkflowTransition.first
end
def test_load_for_all_language
valid_languages.each do |lang|
clear_data
begin
assert Redmine::DefaultData::Loader::load(lang, :workflow => false)
assert_not_nil DocumentCategory.first
assert_not_nil IssuePriority.first
assert_not_nil TimeEntryActivity.first
rescue ActiveRecord::RecordInvalid => e
assert false, ":#{lang} default data is invalid (#{e.message})."
end
end
end
def clear_data
Role.where("builtin = 0").delete_all
Tracker.delete_all
IssueStatus.delete_all
Enumeration.delete_all
WorkflowRule.delete_all
end
end
| 32.278689 | 81 | 0.740985 |
878ec0d6b73fa2454a4b1594f5e6e7219b24b230 | 2,314 | # 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: 2019_08_07_231505) do
create_table "impersonations", force: :cascade do |t|
t.integer "user_id", null: false
t.integer "target_id", null: false
t.boolean "active", default: false, null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["target_id"], name: "index_impersonations_on_target_id"
t.index ["user_id"], name: "index_impersonations_on_user_id"
end
create_table "users", force: :cascade do |t|
t.string "ldap_uid", null: false
t.string "employee_id"
t.integer "affiliate_id"
t.integer "student_id"
t.boolean "superuser_flag", default: false, null: false
t.boolean "inactive_flag", default: false, null: false
t.string "first_name"
t.string "last_name"
t.string "email"
t.string "alternate_first_name"
t.string "alternate_last_name"
t.string "alternate_email"
t.boolean "alternate_flag", default: false, null: false
t.datetime "last_login_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["affiliate_id"], name: "index_users_on_affiliate_id", unique: true
t.index ["email"], name: "index_users_on_email"
t.index ["employee_id"], name: "index_users_on_employee_id", unique: true
t.index ["first_name"], name: "index_users_on_first_name"
t.index ["last_name"], name: "index_users_on_last_name"
t.index ["ldap_uid"], name: "index_users_on_ldap_uid", unique: true
t.index ["student_id"], name: "index_users_on_student_id", unique: true
end
end
| 44.5 | 86 | 0.733362 |
e27624138cc7f4465c73a75486afbabf9a436d8a | 333 | module Dynflow
module Listeners
class Abstract
include Algebrick::TypeCheck
attr_reader :world, :logger
def initialize(world)
@world = Type! world, World
@logger = world.logger
end
def terminate(future = Future.new)
raise NotImplementedError
end
end
end
end
| 18.5 | 40 | 0.624625 |
6196afabed88900c9f3879fbab8e6f3a86688b95 | 42 | module OpenAgenda
VERSION = "0.0.0"
end
| 10.5 | 19 | 0.690476 |
bf286c299dba59fd61d6cd747d803fa888f43c2b | 7,263 | # frozen_string_literal: true
require "delegate"
require "io/console/size"
module ActionDispatch
module Routing
class RouteWrapper < SimpleDelegator
def endpoint
app.dispatcher? ? "#{controller}##{action}" : rack_app.inspect
end
def constraints
requirements.except(:controller, :action)
end
def rack_app
app.rack_app
end
def path
super.spec.to_s
end
def name
super.to_s
end
def reqs
@reqs ||= begin
reqs = endpoint
reqs += " #{constraints}" unless constraints.empty?
reqs
end
end
def controller
parts.include?(:controller) ? ":controller" : requirements[:controller]
end
def action
parts.include?(:action) ? ":action" : requirements[:action]
end
def internal?
internal
end
def engine?
app.engine?
end
end
##
# This class is just used for displaying route information when someone
# executes `rails routes` or looks at the RoutingError page.
# People should not use this class.
class RoutesInspector # :nodoc:
def initialize(routes)
@engines = {}
@routes = routes
end
def format(formatter, filter = {})
routes_to_display = filter_routes(normalize_filter(filter))
routes = collect_routes(routes_to_display)
if routes.none?
formatter.no_routes(collect_routes(@routes), filter)
return formatter.result
end
formatter.header routes
formatter.section routes
@engines.each do |name, engine_routes|
formatter.section_title "Routes for #{name}"
formatter.section engine_routes
end
formatter.result
end
private
def normalize_filter(filter)
if filter[:controller]
{ controller: /#{filter[:controller].underscore.sub(/_?controller\z/, "")}/ }
elsif filter[:grep]
{ controller: /#{filter[:grep]}/, action: /#{filter[:grep]}/,
verb: /#{filter[:grep]}/, name: /#{filter[:grep]}/, path: /#{filter[:grep]}/ }
end
end
def filter_routes(filter)
if filter
@routes.select do |route|
route_wrapper = RouteWrapper.new(route)
filter.any? { |default, value| value.match?(route_wrapper.send(default)) }
end
else
@routes
end
end
def collect_routes(routes)
routes.collect do |route|
RouteWrapper.new(route)
end.reject(&:internal?).collect do |route|
collect_engine_routes(route)
{ name: route.name,
verb: route.verb,
path: route.path,
reqs: route.reqs }
end
end
def collect_engine_routes(route)
name = route.endpoint
return unless route.engine?
return if @engines[name]
routes = route.rack_app.routes
if routes.is_a?(ActionDispatch::Routing::RouteSet)
@engines[name] = collect_routes(routes.routes)
end
end
end
module ConsoleFormatter
class Base
def initialize
@buffer = []
end
def result
@buffer.join("\n")
end
def section_title(title)
end
def section(routes)
end
def header(routes)
end
def no_routes(routes, filter)
@buffer <<
if routes.none?
<<~MESSAGE
You don't have any routes defined!
Please add some routes in config/routes.rb.
MESSAGE
elsif filter.key?(:controller)
"No routes were found for this controller."
elsif filter.key?(:grep)
"No routes were found for this grep pattern."
end
@buffer << "For more information about routes, see the Rails guide: https://guides.rubyonrails.org/routing.html."
end
end
class Sheet < Base
def section_title(title)
@buffer << "\n#{title}:"
end
def section(routes)
@buffer << draw_section(routes)
end
def header(routes)
@buffer << draw_header(routes)
end
private
def draw_section(routes)
header_lengths = ["Prefix", "Verb", "URI Pattern"].map(&:length)
name_width, verb_width, path_width = widths(routes).zip(header_lengths).map(&:max)
routes.map do |r|
"#{r[:name].rjust(name_width)} #{r[:verb].ljust(verb_width)} #{r[:path].ljust(path_width)} #{r[:reqs]}"
end
end
def draw_header(routes)
name_width, verb_width, path_width = widths(routes)
"#{"Prefix".rjust(name_width)} #{"Verb".ljust(verb_width)} #{"URI Pattern".ljust(path_width)} Controller#Action"
end
def widths(routes)
[routes.map { |r| r[:name].length }.max || 0,
routes.map { |r| r[:verb].length }.max || 0,
routes.map { |r| r[:path].length }.max || 0]
end
end
class Expanded < Base
def section_title(title)
@buffer << "\n#{"[ #{title} ]"}"
end
def section(routes)
@buffer << draw_expanded_section(routes)
end
private
def draw_expanded_section(routes)
routes.map.each_with_index do |r, i|
<<~MESSAGE.chomp
#{route_header(index: i + 1)}
Prefix | #{r[:name]}
Verb | #{r[:verb]}
URI | #{r[:path]}
Controller#Action | #{r[:reqs]}
MESSAGE
end
end
def route_header(index:)
console_width = IO.console_size.second
header_prefix = "--[ Route #{index} ]"
dash_remainder = [console_width - header_prefix.size, 0].max
"#{header_prefix}#{'-' * dash_remainder}"
end
end
end
class HtmlTableFormatter
def initialize(view)
@view = view
@buffer = []
end
def section_title(title)
@buffer << %(<tr><th colspan="4">#{title}</th></tr>)
end
def section(routes)
@buffer << @view.render(partial: "routes/route", collection: routes)
end
# The header is part of the HTML page, so we don't construct it here.
def header(routes)
end
def no_routes(*)
@buffer << <<~MESSAGE
<p>You don't have any routes defined!</p>
<ul>
<li>Please add some routes in <tt>config/routes.rb</tt>.</li>
<li>
For more information about routes, please see the Rails guide
<a href="https://guides.rubyonrails.org/routing.html">Rails Routing from the Outside In</a>.
</li>
</ul>
MESSAGE
end
def result
@view.raw @view.render(layout: "routes/table") {
@view.raw @buffer.join("\n")
}
end
end
end
end
| 26.604396 | 124 | 0.532149 |
91ccc19d45874f717cfb8aba45a80fc577450d2c | 700 | class ColorPickerButton < Button
def initialize(source=nil)
init_source source
init_inner_control_vars
end
def current_godot_object
"ColorPickerButton"
end
def init_inner_control_vars
super
@color = Color.new @source.color
end
def color
@color
end
def color=(v)
@color = v
@source.color = v.source
end
def edit_alpha
@source.edit_alpha
end
def edit_alpha=(v)
@source.edit_alpha = v
end
def toggle_mode
@source.toggle_mode
end
def toggle_mode=(v)
@source.toggle_mode = v
end
def get_picker
ColorPicker.new @source.get_picker
end
def get_popup
# TODO: PopupPanel.new @source.get_popup
end
end | 14.583333 | 44 | 0.682857 |
38cc95b637283956d485db9cb47876997e64c3e2 | 1,201 | # 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.
#
# This file is the source Rails uses to define your schema when running `rails
# db:schema:load`. When creating a new database, `rails db:schema:load` tends to
# be faster and is potentially less error prone than running all of your
# migrations from scratch. Old migrations may fail to apply correctly if those
# migrations use external dependencies or application code.
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_10_17_112335) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "answers", force: :cascade do |t|
t.string "question_type", null: false
t.string "text", null: false
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.index ["question_type"], name: "index_answers_on_question_type", unique: true
end
end
| 44.481481 | 86 | 0.766028 |
38402fb64ef1155505d10ec4edc2ed524354c223 | 380 | module TD::Types
# Contains information about the period of inactivity after which the current user's account will automatically be
# deleted.
#
# @attr days [Integer] Number of days of inactivity before the account will be flagged for deletion; should range
# from 30-366 days.
class AccountTtl < Base
attribute :days, TD::Types::Coercible::Integer
end
end
| 34.545455 | 116 | 0.736842 |
ac561b977ab909f9f68121f3f445d418d1ba19e0 | 6,979 | describe "screen properties" do
before do
# Simulate AppDelegate setup of main screen
@screen = HomeScreen.new modal: true, nav_bar: true
@screen.on_load
end
it "should store title" do
HomeScreen.get_title.should == 'Home'
end
it "should set default title on new instances" do
@screen.title.should == "Home"
end
it "should let the instance set its title" do
@screen.title = "instance method"
@screen.title.should == 'instance method'
end
it "should not let the instance reset the default title" do
@screen.title = "instance method"
HomeScreen.get_title.should != 'instance method'
end
it "should set the tab bar item with a system icon" do
@screen.set_tab_bar_item system_icon: :contacts
comparison = UITabBarItem.alloc.initWithTabBarSystemItem(UITabBarSystemItemContacts, tag: 0)
@screen.tabBarItem.systemItem.should == comparison.systemItem
@screen.tabBarItem.tag.should == comparison.tag
@screen.tabBarItem.image.should == comparison.image
end
it "should set the tab bar item with a custom icon and title" do
@screen.set_tab_bar_item title: "My Screen", icon: "list"
icon_image = UIImage.imageNamed("list")
comparison = UITabBarItem.alloc.initWithTitle("My Screen", image: icon_image, tag: 0)
@screen.tabBarItem.systemItem.should == comparison.systemItem
@screen.tabBarItem.tag.should == comparison.tag
@screen.tabBarItem.image.should == comparison.image
end
it "should store debug mode" do
HomeScreen.debug_mode = true
HomeScreen.debug_mode.should == true
end
it "#modal? should be true" do
@screen.modal?.should == true
end
it "should know it is the first screen" do
@screen.first_screen?.should == true
end
it "#should_autorotate should default to 'true'" do
@screen.should_autorotate.should == true
end
# Issue https://github.com/clearsightstudio/ProMotion/issues/109
it "#should_autorotate should fire when shouldAutorotate fires when in a navigation bar" do
parent_screen = BasicScreen.new(nav_bar: true)
parent_screen.open @screen
@screen.mock!(:should_autorotate) { true.should == true }
parent_screen.navigationController.shouldAutorotate
end
# <= iOS 5 only
it "#should_rotate(orientation) should fire when shouldAutorotateToInterfaceOrientation(orientation) fires" do
@screen.mock!(:should_rotate) { |orientation| orientation.should == UIInterfaceOrientationMaskPortrait }
@screen.shouldAutorotateToInterfaceOrientation(UIInterfaceOrientationMaskPortrait)
end
describe "iOS lifecycle methods" do
it "-viewDidLoad" do
@screen.mock!(:view_did_load) { true }
@screen.viewDidLoad.should == true
end
it "-viewWillAppear" do
@screen.mock!(:view_will_appear) { |animated| animated.should == true }
@screen.viewWillAppear(true)
end
it "-viewDidAppear" do
@screen.mock!(:view_did_appear) { |animated| animated.should == true }
@screen.viewDidAppear(true)
end
it "-viewWillDisappear" do
@screen.mock!(:view_will_disappear) { |animated| animated.should == true }
@screen.viewWillDisappear(true)
end
it "-viewDidDisappear" do
@screen.mock!(:view_did_disappear) { |animated| animated.should == true }
@screen.viewDidDisappear(true)
end
it "-shouldAutorotateToInterfaceOrientation" do
@screen.mock!(:should_rotate) { |o| o.should == UIInterfaceOrientationPortrait }
@screen.shouldAutorotateToInterfaceOrientation(UIInterfaceOrientationPortrait)
end
it "-shouldAutorotate" do
@screen.mock!(:should_autorotate) { true }
@screen.shouldAutorotate.should == true
end
it "-willRotateToInterfaceOrientation" do
@screen.mock! :will_rotate do |orientation, duration|
orientation.should == UIInterfaceOrientationPortrait
duration.should == 0.5
end
@screen.willRotateToInterfaceOrientation(UIInterfaceOrientationPortrait, duration: 0.5)
end
it "-didRotateFromInterfaceOrientation" do
@screen.mock!(:on_rotate) { true }
@screen.didRotateFromInterfaceOrientation(UIInterfaceOrientationPortrait).should == true
end
end
describe "navigation controller behavior" do
it "should have a nav bar" do
@screen.nav_bar?.should == true
end
it "#navigation_controller should return a navigation controller" do
@screen.navigation_controller.should.be.instance_of ProMotion::NavigationController
@screen.navigationController.should.be.instance_of ProMotion::NavigationController
end
it "have a right bar button item" do
@screen.navigationItem.rightBarButtonItem.should.not == nil
end
it "should have a left bar button item" do
@screen.navigationItem.leftBarButtonItem.should.not == nil
end
end
describe "bar button behavior" do
describe "system bar buttons" do
before do
@screen.set_nav_bar_right_button nil, action: :add_something, system_icon: UIBarButtonSystemItemAdd
end
it "has a right bar button item of the correct type" do
@screen.navigationItem.rightBarButtonItem.should.be.instance_of UIBarButtonItem
end
it "is an add button" do
@screen.navigationItem.rightBarButtonItem.action.should == :add_something
end
end
describe 'titled bar buttons' do
before do
@screen.set_nav_bar_right_button "Save", action: :save_something, style: UIBarButtonItemStyleDone
end
it "has a right bar button item of the correct type" do
@screen.navigationItem.rightBarButtonItem.should.be.instance_of UIBarButtonItem
end
it "has a right bar button item of the correct style" do
@screen.navigationItem.rightBarButtonItem.style.should == UIBarButtonItemStyleDone
end
it "is titled correctly" do
@screen.navigationItem.rightBarButtonItem.title.should == 'Save'
end
end
describe 'image bar buttons' do
before do
@image = UIImage.alloc.init
@screen.set_nav_bar_right_button @image, action: :save_something, style: UIBarButtonItemStyleDone
end
it "has a right bar button item of the correct type" do
@screen.navigationItem.rightBarButtonItem.should.be.instance_of UIBarButtonItem
end
it "is has the right image" do
@screen.navigationItem.rightBarButtonItem.title.should == nil
end
end
end
end
describe "screen with toolbar" do
it "showing" do
# Simulate AppDelegate setup of main screen
screen = HomeScreen.new modal: true, nav_bar: true, toolbar: true
screen.on_load
screen.navigationController.toolbarHidden?.should == false
end
it "hidden" do
# Simulate AppDelegate setup of main screen
screen = HomeScreen.new modal: true, nav_bar: true, toolbar: false
screen.on_load
screen.navigationController.toolbarHidden?.should == true
end
end
| 31.579186 | 112 | 0.713139 |
610181855e322353c0d7d8a6c54afb3847102fce | 2,000 | # encoding: utf-8
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
module Azure::SQL::Mgmt::V2014_04_01
module Models
#
# ARM resource.
#
class Resource
include MsRestAzure
# @return [String] Resource ID.
attr_accessor :id
# @return [String] Resource name.
attr_accessor :name
# @return [String] Resource type.
attr_accessor :type
# @return [String] the name of the resource group of the resource.
def resource_group
unless self.id.nil?
groups = self.id.match(/.+\/resourceGroups\/([^\/]+)\/.+/)
groups.captures[0].strip if groups
end
end
#
# Mapper for Resource class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'Resource',
type: {
name: 'Composite',
class_name: 'Resource',
model_properties: {
id: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'id',
type: {
name: 'String'
}
},
name: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'name',
type: {
name: 'String'
}
},
type: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'type',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 24.691358 | 72 | 0.476 |
ff5ab3355e4ecd979fdedc2b3b582fdcf53b0f42 | 646 | # encoding: utf-8
# This file is distributed under New Relic's license terms.
# See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details.
# frozen_string_literal: true
require 'grpc'
require 'google/protobuf'
require_relative 'proto/infinite_tracing_pb'
require_relative 'proto/infinite_tracing_services_pb'
# Mapping gRPC namespaced classes into New Relic's
module NewRelic::Agent::InfiniteTracing
Span = Com::Newrelic::Trace::V1::Span
SpanBatch = Com::Newrelic::Trace::V1::SpanBatch
AttributeValue = Com::Newrelic::Trace::V1::AttributeValue
RecordStatus = Com::Newrelic::Trace::V1::RecordStatus
end
| 34 | 93 | 0.786378 |
7a6e57cd474155f6dc2e56f8e30e0bc27c14258e | 234 | class RenameInviteEmailField < ActiveRecord::Migration
def self.up
execute "ALTER TABLE invites RENAME COLUMN invite_email TO email"
end
def self.down
execute "ALTER TABLE invites RENAME COLUMN email TO invite_email"
end
end
| 23.4 | 67 | 0.799145 |
876d3c0b42a7c508d5c2972bf67947f07f63c0af | 12,372 | # frozen_string_literal: true
require 'active_support/deprecation'
require 'uri'
module QA
module Runtime
module Env
extend self
attr_writer :personal_access_token, :admin_personal_access_token
attr_accessor :dry_run
ENV_VARIABLES = Gitlab::QA::Runtime::Env::ENV_VARIABLES
# The environment variables used to indicate if the environment under test
# supports the given feature
SUPPORTED_FEATURES = {
git_protocol_v2: 'QA_CAN_TEST_GIT_PROTOCOL_V2',
admin: 'QA_CAN_TEST_ADMIN_FEATURES',
praefect: 'QA_CAN_TEST_PRAEFECT'
}.freeze
def supported_features
SUPPORTED_FEATURES
end
def additional_repository_storage
ENV['QA_ADDITIONAL_REPOSITORY_STORAGE']
end
def non_cluster_repository_storage
ENV['QA_GITALY_NON_CLUSTER_STORAGE'] || 'gitaly'
end
def praefect_repository_storage
ENV['QA_PRAEFECT_REPOSITORY_STORAGE']
end
def ci_job_url
ENV['CI_JOB_URL']
end
def ci_job_name
ENV['CI_JOB_NAME']
end
def ci_project_name
ENV['CI_PROJECT_NAME']
end
def debug?
enabled?(ENV['QA_DEBUG'], default: false)
end
def generate_allure_report?
enabled?(ENV['QA_GENERATE_ALLURE_REPORT'], default: false)
end
def default_branch
ENV['QA_DEFAULT_BRANCH'] || 'main'
end
def log_destination
ENV['QA_LOG_PATH'] || $stdout
end
def colorized_logs?
enabled?(ENV['COLORIZED_LOGS'], default: false)
end
# set to 'false' to have the browser run visibly instead of headless
def webdriver_headless?
if ENV.key?('CHROME_HEADLESS')
ActiveSupport::Deprecation.warn("CHROME_HEADLESS is deprecated. Use WEBDRIVER_HEADLESS instead.")
end
return enabled?(ENV['WEBDRIVER_HEADLESS']) unless ENV['WEBDRIVER_HEADLESS'].nil?
enabled?(ENV['CHROME_HEADLESS'])
end
# set to 'true' to have Chrome use a fixed profile directory
def reuse_chrome_profile?
enabled?(ENV['CHROME_REUSE_PROFILE'], default: false)
end
# Disable /dev/shm use in CI. See https://gitlab.com/gitlab-org/gitlab/issues/4252
def disable_dev_shm?
running_in_ci? || enabled?(ENV['CHROME_DISABLE_DEV_SHM'], default: false)
end
def accept_insecure_certs?
enabled?(ENV['ACCEPT_INSECURE_CERTS'])
end
def running_on_dot_com?
uri = URI.parse(Runtime::Scenario.gitlab_address)
uri.host.include?('.com')
end
def running_on_dev?
uri = URI.parse(Runtime::Scenario.gitlab_address)
uri.port != 80 && uri.port != 443
end
def running_on_dev_or_dot_com?
running_on_dev? || running_on_dot_com?
end
def running_in_ci?
ENV['CI'] || ENV['CI_SERVER']
end
def qa_cookies
ENV['QA_COOKIES'] && ENV['QA_COOKIES'].split(';')
end
def signup_disabled?
enabled?(ENV['SIGNUP_DISABLED'], default: false)
end
def admin_password
ENV['GITLAB_ADMIN_PASSWORD']
end
def admin_username
ENV['GITLAB_ADMIN_USERNAME']
end
def admin_personal_access_token
@admin_personal_access_token ||= ENV['GITLAB_QA_ADMIN_ACCESS_TOKEN']
end
# specifies token that can be used for the api
def personal_access_token
@personal_access_token ||= ENV['GITLAB_QA_ACCESS_TOKEN']
end
def remote_grid
# if username specified, password/auth token is required
# can be
# - "http://user:[email protected]/wd/hub"
# - "https://user:[email protected]:443/wd/hub"
# - "http://localhost:4444/wd/hub"
return if (ENV['QA_REMOTE_GRID'] || '').empty?
"#{remote_grid_protocol}://#{remote_grid_credentials}#{ENV['QA_REMOTE_GRID']}/wd/hub"
end
def remote_grid_username
ENV['QA_REMOTE_GRID_USERNAME']
end
def remote_grid_access_key
ENV['QA_REMOTE_GRID_ACCESS_KEY']
end
def remote_grid_protocol
ENV['QA_REMOTE_GRID_PROTOCOL'] || 'http'
end
def remote_tunnel_id
ENV['QA_REMOTE_TUNNEL_ID'] || 'gitlab-sl_tunnel_id'
end
def browser
ENV['QA_BROWSER'].nil? ? :chrome : ENV['QA_BROWSER'].to_sym
end
def remote_mobile_device_name
ENV['QA_REMOTE_MOBILE_DEVICE_NAME']
end
def mobile_layout?
return false if ENV['QA_REMOTE_MOBILE_DEVICE_NAME'].blank?
!(ENV['QA_REMOTE_MOBILE_DEVICE_NAME'].downcase.include?('ipad') || ENV['QA_REMOTE_MOBILE_DEVICE_NAME'].downcase.include?('tablet'))
end
def user_username
ENV['GITLAB_USERNAME']
end
def user_password
ENV['GITLAB_PASSWORD']
end
def initial_root_password
ENV['GITLAB_INITIAL_ROOT_PASSWORD']
end
def github_username
ENV['GITHUB_USERNAME']
end
def github_password
ENV['GITHUB_PASSWORD']
end
def forker?
!!(forker_username && forker_password)
end
def forker_username
ENV['GITLAB_FORKER_USERNAME']
end
def forker_password
ENV['GITLAB_FORKER_PASSWORD']
end
def gitlab_qa_username_1
ENV['GITLAB_QA_USERNAME_1'] || 'gitlab-qa-user1'
end
def gitlab_qa_password_1
ENV['GITLAB_QA_PASSWORD_1']
end
def gitlab_qa_username_2
ENV['GITLAB_QA_USERNAME_2'] || 'gitlab-qa-user2'
end
def gitlab_qa_password_2
ENV['GITLAB_QA_PASSWORD_2']
end
def gitlab_qa_username_3
ENV['GITLAB_QA_USERNAME_3'] || 'gitlab-qa-user3'
end
def gitlab_qa_password_3
ENV['GITLAB_QA_PASSWORD_3']
end
def gitlab_qa_username_4
ENV['GITLAB_QA_USERNAME_4'] || 'gitlab-qa-user4'
end
def gitlab_qa_password_4
ENV['GITLAB_QA_PASSWORD_4']
end
def gitlab_qa_username_5
ENV['GITLAB_QA_USERNAME_5'] || 'gitlab-qa-user5'
end
def gitlab_qa_password_5
ENV['GITLAB_QA_PASSWORD_5']
end
def gitlab_qa_username_6
ENV['GITLAB_QA_USERNAME_6'] || 'gitlab-qa-user6'
end
def gitlab_qa_password_6
ENV['GITLAB_QA_PASSWORD_6']
end
def gitlab_qa_2fa_owner_username_1
ENV['GITLAB_QA_2FA_OWNER_USERNAME_1'] || 'gitlab-qa-2fa-owner-user1'
end
def gitlab_qa_2fa_owner_password_1
ENV['GITLAB_QA_2FA_OWNER_PASSWORD_1']
end
def gitlab_qa_1p_email
ENV['GITLAB_QA_1P_EMAIL']
end
def gitlab_qa_1p_password
ENV['GITLAB_QA_1P_PASSWORD']
end
def gitlab_qa_1p_secret
ENV['GITLAB_QA_1P_SECRET']
end
def gitlab_qa_1p_github_uuid
ENV['GITLAB_QA_1P_GITHUB_UUID']
end
def jira_admin_username
ENV['JIRA_ADMIN_USERNAME']
end
def jira_admin_password
ENV['JIRA_ADMIN_PASSWORD']
end
def jira_hostname
ENV['JIRA_HOSTNAME']
end
# this is set by the integrations job
# which will allow bidirectional communication
# between the app and the specs container
# should the specs container spin up a server
def qa_hostname
ENV['QA_HOSTNAME']
end
def cache_namespace_name?
enabled?(ENV['CACHE_NAMESPACE_NAME'], default: true)
end
def knapsack?
ENV['CI_NODE_TOTAL'].to_i > 1 && ENV['NO_KNAPSACK'] != "true"
end
def ldap_username
@ldap_username ||= ENV['GITLAB_LDAP_USERNAME']
end
def ldap_username=(ldap_username)
@ldap_username = ldap_username # rubocop:disable Gitlab/ModuleWithInstanceVariables
ENV['GITLAB_LDAP_USERNAME'] = ldap_username
end
def ldap_password
@ldap_password ||= ENV['GITLAB_LDAP_PASSWORD']
end
def sandbox_name
ENV['GITLAB_SANDBOX_NAME']
end
def namespace_name
ENV['GITLAB_NAMESPACE_NAME']
end
def auto_devops_project_name
ENV['GITLAB_AUTO_DEVOPS_PROJECT_NAME']
end
def gcloud_account_key
ENV.fetch("GCLOUD_ACCOUNT_KEY")
end
def gcloud_account_email
ENV.fetch("GCLOUD_ACCOUNT_EMAIL")
end
def gcloud_region
ENV['GCLOUD_REGION']
end
def gcloud_num_nodes
ENV.fetch('GCLOUD_NUM_NODES', 1)
end
def has_gcloud_credentials?
%w[GCLOUD_ACCOUNT_KEY GCLOUD_ACCOUNT_EMAIL].none? { |var| ENV[var].to_s.empty? }
end
# Specifies the token that can be used for the GitHub API
def github_access_token
ENV['GITHUB_ACCESS_TOKEN'].to_s.strip
end
def require_github_access_token!
return unless github_access_token.empty?
raise ArgumentError, "Please provide GITHUB_ACCESS_TOKEN"
end
def require_admin_access_token!
admin_personal_access_token || (raise ArgumentError, "GITLAB_QA_ADMIN_ACCESS_TOKEN is required!")
end
# Returns true if there is an environment variable that indicates that
# the feature is supported in the environment under test.
# All features are supported by default.
def can_test?(feature)
raise ArgumentError, %(Unknown feature "#{feature}") unless SUPPORTED_FEATURES.include? feature
enabled?(ENV[SUPPORTED_FEATURES[feature]], default: true)
end
def runtime_scenario_attributes
ENV['QA_RUNTIME_SCENARIO_ATTRIBUTES']
end
def disable_rspec_retry?
enabled?(ENV['QA_DISABLE_RSPEC_RETRY'], default: false)
end
def simulate_slow_connection?
enabled?(ENV['QA_SIMULATE_SLOW_CONNECTION'], default: false)
end
def slow_connection_latency
ENV.fetch('QA_SLOW_CONNECTION_LATENCY_MS', 2000).to_i
end
def slow_connection_throughput
ENV.fetch('QA_SLOW_CONNECTION_THROUGHPUT_KBPS', 32).to_i
end
def gitlab_qa_loop_runner_minutes
ENV.fetch('GITLAB_QA_LOOP_RUNNER_MINUTES', 1).to_i
end
def reusable_project_path
ENV.fetch('QA_REUSABLE_PROJECT_PATH', 'reusable_project')
end
def reusable_group_path
ENV.fetch('QA_REUSABLE_GROUP_PATH', 'reusable_group')
end
def mailhog_hostname
ENV['MAILHOG_HOSTNAME']
end
# Get the version of GitLab currently being tested against
# @return String Version
# @example
# > Env.deploy_version
# #=> 13.3.4-ee.0
def deploy_version
ENV['DEPLOY_VERSION']
end
def user_agent
ENV['GITLAB_QA_USER_AGENT']
end
def geo_environment?
QA::Runtime::Scenario.attributes.include?(:geo_secondary_address)
end
def gitlab_agentk_version
ENV.fetch('GITLAB_AGENTK_VERSION', 'v14.5.0')
end
def transient_trials
ENV.fetch('GITLAB_QA_TRANSIENT_TRIALS', 10).to_i
end
def gitlab_tls_certificate
ENV['GITLAB_TLS_CERTIFICATE']
end
def export_metrics?
running_in_ci? && enabled?(ENV['QA_EXPORT_TEST_METRICS'], default: true)
end
def test_resources_created_filepath
file_name = running_in_ci? ? "test-resources-#{SecureRandom.hex(3)}.json" : 'test-resources.json'
ENV.fetch('QA_TEST_RESOURCES_CREATED_FILEPATH', File.join(Path.qa_root, 'tmp', file_name))
end
def ee_activation_code
ENV['QA_EE_ACTIVATION_CODE']
end
def quarantine_disabled?
enabled?(ENV['DISABLE_QUARANTINE'], default: false)
end
def validate_resource_reuse?
enabled?(ENV['QA_VALIDATE_RESOURCE_REUSE'], default: false)
end
private
def remote_grid_credentials
if remote_grid_username
unless remote_grid_access_key
raise ArgumentError, %(Please provide an access key for user "#{remote_grid_username}")
end
return "#{remote_grid_username}:#{remote_grid_access_key}@"
end
''
end
def enabled?(value, default: true)
return default if value.nil?
(value =~ /^(false|no|0)$/i) != 0
end
end
end
end
QA::Runtime::Env.extend_mod_with('Runtime::Env', namespace: QA)
| 25.095335 | 139 | 0.643146 |
bb4771671ca526fe3f7041e7b97e120e3d3f4f9e | 769 | #
# Cookbook Name:: kimchi
# Recipe:: default
#
# Copyright 2015-2016, Chef Software, 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.
#
include_recipe 'runit'
include_recipe 'iptables'
include_recipe 'kimchi::_kvm_install'
include_recipe 'kimchi::_kimchi_install'
| 30.76 | 74 | 0.763329 |
5d55dc31b0c4e0474e151ed6611c77727195d017 | 781 | #frozen_string_literal: false
require 'test_helper'
require 'time'
class JSONStringMatchingTest < Test::Unit::TestCase
include JSON
class TestTime < ::Time
def self.json_create(string)
Time.parse(string)
end
def to_json(*)
%{"#{strftime('%FT%T%z')}"}
end
def ==(other)
to_i == other.to_i
end
end
def test_match_date
t = TestTime.new
t_json = [ t ].to_json
time_regexp = /\A\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[+-]\d{4}\z/
assert_equal [ t ],
parse(
t_json,
:create_additions => true,
:match_string => { time_regexp => TestTime }
)
assert_equal [ t.strftime('%FT%T%z') ],
parse(
t_json,
:match_string => { time_regexp => TestTime }
)
end
end
| 20.025641 | 68 | 0.56338 |
38669454dce99751651707afd42e5c9c6f7e3c77 | 1,189 | require 'test_helper'
class CephalopodsControllerTest < ActionController::TestCase
setup do
@cephalopod = cephalopods(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:cephalopods)
end
test "should get new" do
get :new
assert_response :success
end
test "should create cephalopod" do
assert_difference('Cephalopod.count') do
post :create, cephalopod: { name: @cephalopod.name, tentacles: @cephalopod.tentacles }
end
assert_redirected_to cephalopod_path(assigns(:cephalopod))
end
test "should show cephalopod" do
get :show, id: @cephalopod
assert_response :success
end
test "should get edit" do
get :edit, id: @cephalopod
assert_response :success
end
test "should update cephalopod" do
patch :update, id: @cephalopod, cephalopod: { name: @cephalopod.name, tentacles: @cephalopod.tentacles }
assert_redirected_to cephalopod_path(assigns(:cephalopod))
end
test "should destroy cephalopod" do
assert_difference('Cephalopod.count', -1) do
delete :destroy, id: @cephalopod
end
assert_redirected_to cephalopods_path
end
end
| 23.78 | 108 | 0.719092 |
acc53877c5a594bc7e5b26df3decdc50856f62f8 | 1,795 | class ToursController < ApplicationController
before_action :require_login, except: [:index, :show]
before_action :set_tour, except: [:index, :new, :create, :best]
def index
if params[:agency_id] && current_user.id == params[:agency_id].to_i
@tours = current_user.tours
else
@tours = Tour.all
end
respond_to do |f|
f.html
f.json{render json: @tours}
end
end
def new
@agency = Agency.find_by(id: current_user.id)
@tour = @agency.tours.build
end
def create
@tour = current_user.tours.build(tour_params)
if @tour.save
redirect_to @tour
elsif @tour.errors.any?
render :new
end
end
def show
end
def best
tours_ids = Tour.best
@tours = []
tours_ids.each {|t| @tours << Tour.find_by(id: t[0])}
@tours
end
def edit
@agency = @tour.agency
if @agency == current_user
render :edit
else
flash[:message] = "Sorry, your agency does not have edit privileges."
redirect_to @tour
end
end
def update
if @tour.agency == current_user
@tour.update(tour_params)
if @tour.errors.any?
render :edit
else
redirect_to @tour
end
else
flash[:message] = "Sorry, your agency does not have edit privileges."
redirect_to @tour
end
end
def destroy
if @tour && current_user == @tour.agency
@tour.destroy
redirect_to tours_path
else
flash[:message] = "Sorry, cannot delete a tour that doesn't belong to your agency.'"
redirect_to tours_path
end
end
private
def tour_params
params.require(:tour).permit(:title, :country, :date, :length, :price, :description, :agency_id)
end
def set_tour
@tour = Tour.find_by(id: params[:id])
end
end
| 20.872093 | 100 | 0.627298 |
7adc48d206853f8351b8ba666250df75613d13e1 | 469 | module HealthSeven::V2_6
class Csp < ::HealthSeven::Segment
# Study Phase Identifier
attribute :study_phase_identifier, Cwe, position: "CSP.1", require: true
# Date/time Study Phase Began
attribute :date_time_study_phase_began, Dtm, position: "CSP.2", require: true
# Date/time Study Phase Ended
attribute :date_time_study_phase_ended, Dtm, position: "CSP.3"
# Study Phase Evaluability
attribute :study_phase_evaluability, Cwe, position: "CSP.4"
end
end | 39.083333 | 79 | 0.765458 |
6a4858970be88924bfd404bc9e02cebc1e80bdd0 | 398 | # frozen_string_literal: true
require 'spec_helper'
describe CSI::AWS::CloudWatch do
it 'should display information for authors' do
authors_response = CSI::AWS::CloudWatch
expect(authors_response).to respond_to :authors
end
it 'should display information for existing help method' do
help_response = CSI::AWS::CloudWatch
expect(help_response).to respond_to :help
end
end
| 24.875 | 61 | 0.758794 |
4a76c6d19640f846f8f1a5f7de9a86d39c92e167 | 509 | dir = File.dirname(__FILE__) + '/templatelets'
require dir + '/href'
require dir + '/attribute'
require dir + '/each'
require dir + '/include'
require dir + '/link'
require dir + '/text'
require dir + '/when'
require dir + '/code'
module REXML
class Element
def attribute_value!(name)
value = attribute_value(name)
raise BuildMaster::TemplateError.new(self), "attribute #{name} not found" unless value
return value
end
def attribute_value(name)
return attributes[name]
end
end
end | 21.208333 | 90 | 0.699411 |
bfba3bf2e1760890e494ad7d6b32de97175cb9f6 | 1,487 | # encoding: UTF-8
class ZlibSpecs
def self.compressed_data
File.open(
File.join(File.dirname(__FILE__), 'compressed_file.bin'), 'rb'
) do |f|
block_given? ? yield(f) : f.read
end
end
def self.compressed_data_nocomp
File.open(
File.join(File.dirname(__FILE__), 'compressed_file_nocomp.bin'), 'rb'
) do |f|
block_given? ? yield(f) : f.read
end
end
def self.compressed_data_minwin
File.open(
File.join(File.dirname(__FILE__), 'compressed_file_minwin.bin'), 'rb'
) do |f|
block_given? ? yield(f) : f.read
end
end
def self.compressed_data_minmem
File.open(
File.join(File.dirname(__FILE__), 'compressed_file_minmem.bin'), 'rb'
) do |f|
block_given? ? yield(f) : f.read
end
end
def self.compressed_data_huffman
File.open(
File.join(File.dirname(__FILE__), 'compressed_file_huffman.bin'), 'rb'
) do |f|
block_given? ? yield(f) : f.read
end
end
def self.compressed_data_gzip
File.open(
File.join(File.dirname(__FILE__), 'compressed_file_gzip.bin'), 'rb'
) do |f|
block_given? ? yield(f) : f.read
end
end
def self.compressed_data_raw
File.open(
File.join(File.dirname(__FILE__), 'compressed_file_raw.bin'), 'rb'
) do |f|
block_given? ? yield(f) : f.read
end
end
def self.test_data
File.open(File.join(File.dirname(__FILE__), 'raw_file.txt'), 'rb') do |f|
f.read
end
end
end
| 22.530303 | 77 | 0.631473 |
e2431950826c8c7bb13db45ba13919bc27a9d5e5 | 77 | execute 'zabbix_restart' do
command 'sudo service zabbix-agent restart'
end | 25.666667 | 45 | 0.805195 |
ab086f6acc334a6d108cda1beaba86e4a852fd1f | 383 | class CreateTimeEntries < ActiveRecord::Migration
def change
create_table :time_entries do |t|
t.integer :user_id, null: false
t.date :date, null: false
t.decimal :hours, precision: 4, scale: 2, null: false
t.string :description, null: false
t.text :notes
t.timestamps null: false
end
add_foreign_key :time_entries, :users
end
end
| 27.357143 | 59 | 0.671018 |
f76d130c748b6f39dab593782e54015b0b22ad05 | 7,932 | class ActivityWorker
include Sidekiq::Worker
def perform(band_id, activity, hours, song_id = nil)
@band = Band.find_by_id(band_id)
case activity
when 'practice'
@band.members.each do |member|
increase_skill_amount = (rand(1..6) * hours.to_f/5).ceil
member.increment!(:skill_primary_level, increase_skill_amount)
@band.happenings.create(what: "#{member.name} increased their skill by #{increase_skill_amount} points!")
increase_fatigue_amount = (rand(1..10) * hours.to_f/5).ceil
member.increment!(:trait_fatigue, increase_fatigue_amount)
@band.happenings.create(what: "#{member.name}'s fatigue increased by #{increase_fatigue_amount}")
end
when 'write_song'
@band.members.each do |member|
increase_fatigue_amount = rand(2..5) * hours
member.increment!(:trait_fatigue, increase_fatigue_amount)
@band.happenings.create(what: "#{member.name}'s fatigue increased by #{increase_fatigue_amount}")
end
skill_mp = 50
creativity_mp = 15
time_mp = 30
ego_mp = 5
member_multiplyer = @band.members.count * 100
total_skills = @band.members.pluck(:skill_primary_level).inject(0, :+)
total_creativity = @band.members.pluck(:trait_creativity).inject(0, :+)
total_ego = @band.members.pluck(:trait_ego).inject(0, :+)
possible_points = (member_multiplyer * skill_mp) + (member_multiplyer * creativity_mp) + (24 * time_mp)
quality = 100
points = (total_skills * skill_mp) + (total_creativity * creativity_mp) + (hours * time_mp)
ego_weight = (total_ego * ego_mp).to_f / 10000
total = quality * (points.to_f / possible_points.to_f)
ego_reduction = total * ego_weight
song_quality = (total - ego_reduction).round
@song = Song.find_by_id(song_id)
@song.update_attributes(quality: song_quality)
@band.happenings.create(what: "#{@band.name} wrote a new song called #{@song.name}! It has a quality score of #{song_quality}.")
when 'gig'
@band.members.each do |member|
increase_fatigue_amount = rand(5..15)
member.increment!(:trait_fatigue, increase_fatigue_amount)
@band.happenings.create(what: "#{member.name}'s fatigue increased by #{increase_fatigue_amount}")
end
gig = Gig.find_by_id(song_id)
cap = gig.venue.capacity.to_f
buzz = @band.buzz.to_f
fans = @band.fans.to_f
#new_fans = ((buzz.to_f/cap.to_f) * 10).ceil
#new_fans = new_fans == 0 ? 2 : new_fans
# new_fans = fans**(buzz / 125)
# cap_deduction = (cap - new_fans) / 10
# total_new = new_fans - cap_deduction
#final_new = total_new <= 0 ? 2 : total_new
attendance = ((fans * rand(0.05..0.3)) + ((buzz / 100) * cap)).ceil
attendance = attendance == 0 ? rand(1..3) : attendance
new_fans = new_fans = (((attendance/cap)**rand(1..3.5)) * 100).ceil
new_fans = new_fans == 0 ? rand(1..3) : new_fans
new_buzz = (((attendance/cap)**rand(1..2.5)) * 100).ceil
new_buzz = new_buzz == 0 ? rand(1..3) : new_buzz
ticket_price = 10.0
@band.increment!(:fans, new_fans)
@band.increment!(:buzz, new_buzz)
revenue = attendance * ticket_price
@band.manager.financials.create!(amount: revenue, band_id: @band.id)
gig.update_attributes(fans_gained: new_fans, money_made: revenue)
@band.happenings.create(what: "You made §#{revenue.to_i} from #{attendance.to_i} people at your gig!")
@band.happenings.create(what: "You gained #{new_fans} new fans and #{new_buzz} buzz at your gig!")
when 'record_single'
@band.members.each do |member|
increase_fatigue_amount = rand(10..25)
member.increment!(:trait_fatigue, increase_fatigue_amount)
@band.happenings.create(what: "#{member.name}'s fatigue increased by #{increase_fatigue_amount}")
end
@recording = Recording.find_by_id(song_id)
studio = @recording.studio.weight
song_avg = @recording.songs.average(:quality).to_i
song_mp = 40
studio_mp = 30
skill_mp = 20
creativity_mp = 5
ego_mp = 5
member_multiplyer = @band.members.count * 100
total_skills = @band.members.pluck(:skill_primary_level).inject(0, :+)
total_creativity = @band.members.pluck(:trait_creativity).inject(0, :+)
total_ego = @band.members.pluck(:trait_ego).inject(0, :+)
possible_points = (member_multiplyer * skill_mp) + (member_multiplyer * creativity_mp) + (Studio.order(:weight).last.weight * studio_mp) + (100 * song_mp)
quality = 100
points = (total_skills * skill_mp) + (total_creativity * creativity_mp) + (studio * studio_mp) + (song_avg * song_mp)
ego_weight = (total_ego * ego_mp).to_f / possible_points.to_f
total = quality * (points.to_f / possible_points.to_f)
ego_reduction = total * ego_weight
recording_quality = (total - ego_reduction).round
@recording.update_attributes(quality: recording_quality)
@band.manager.financials.create!(amount: [email protected], band_id: @band.id)
@band.happenings.create(what: "#{@band.name} made a recording of #{@recording.songs.map { |s| s.name }.join ','}! It has a quality score of #{recording_quality} and cost §#{@recording.studio.cost} to record.")
when 'record_album'
@band.members.each do |member|
increase_fatigue_amount = rand(25..75)
member.increment!(:trait_fatigue, increase_fatigue_amount)
@band.happenings.create(what: "#{member.name}'s fatigue increased by #{increase_fatigue_amount}")
end
@recording = Recording.find_by_id(song_id)
studio = @recording.studio.cost
song_avg = @recording.songs.average(:quality).to_i
song_mp = 40
studio_mp = 30
skill_mp = 20
creativity_mp = 5
ego_mp = 5
member_multiplyer = @band.members.count * 100
total_skills = @band.members.pluck(:skill_primary_level).inject(0, :+)
total_creativity = @band.members.pluck(:trait_creativity).inject(0, :+)
total_ego = @band.members.pluck(:trait_ego).inject(0, :+)
possible_points = (member_multiplyer * skill_mp) + (member_multiplyer * creativity_mp) + (studio * studio_mp) + (song_avg * song_mp)
quality = 100
points = (total_skills * skill_mp) + (total_creativity * creativity_mp) + (studio * studio_mp) + (song_avg * song_mp)
ego_weight = (total_ego * ego_mp).to_f / possible_points.to_f
total = quality * (points.to_f / possible_points.to_f)
ego_reduction = total * ego_weight
recording_quality = (total - ego_reduction).round
@recording.update_attributes(quality: recording_quality)
@band.manager.financials.create!(amount: [email protected], band_id: @band.id)
@band.happenings.create(what: "#{@band.name} recorded an album named #{@recording.name}! It has a quality score of #{recording_quality} and cost §#{@recording.studio.cost} to record.")
when 'release'
recording = Recording.find_by_id(song_id)
recording.update_attribute(:release_at, Time.now)
buzz = @band.buzz
fans = @band.fans
quality = recording.quality
streaming_rate = 0.03
streams = (fans + (fans * (buzz/100))) * (quality/100)
earnings = (streaming_rate * streaming_rate).ceil
@band.manager.financials.create!(amount: earnings, band_id: @band.id)
recording.update_attributes(sales: earnings)
@band.happenings.create(what: "You made §#{earnings.to_i} from your release of #{recording.name}!")
when 'rest'
@band.members.each do |member|
decrease_fatigue_amount = (rand(20..50) * hours.to_f/10).ceil
member.decrement!(:trait_fatigue, decrease_fatigue_amount)
@band.happenings.create(what: "#{member.name}'s fatigue decreased by #{decrease_fatigue_amount}")
end
end
end
end
| 40.676923 | 215 | 0.666541 |
7967b0e2f67a2e1ae7560b12f91ede3ff50aa6e1 | 1,023 | module Apo214
module Concerns
module Models
module Asisreconocimiento
extend ActiveSupport::Concern
included do
include Sip::Modelo
belongs_to :lugarpreliminar, class_name: 'Apo214::Lugarpreliminar',
validate: true, foreign_key: 'lugarpreliminar_id'
belongs_to :asistente, class_name: 'Sip::Persona', validate: true,
foreign_key: 'persona_id'
acts_as_list scope: :asistente, column: :posicion
accepts_nested_attributes_for :asistente, reject_if: :all_blank, update_only: true
after_commit :broadcast_me
def broadcast_me
ActionCable.server.broadcast "AsisreconocimientoChannel:#{id}", {
organizacion: organizacion.titleize,
mensaje: AsisreconocimientosController.renderer.render(partial: 'apo214/asisreconocimientos/asisreconocimiento', locals: {asisreconocimiento: self})
}
end
end # included
end
end
end
end
| 34.1 | 164 | 0.656891 |
183b039715c6b2489264bb2403576c3613be9fd0 | 672 | require 'test_helper'
class PasswordTest < ActiveSupport::TestCase
test 'should create password hash' do
assert hashed_password
end
test 'should return NullPassword for invalid hash' do
assert_kind_of(
MinimalistAuthentication::NullPassword,
MinimalistAuthentication::Password.new('').bcrypt_password
)
end
test 'should return false for stale?' do
refute hashed_password.stale?
end
test 'should return true for stale?' do
password = hashed_password
password.expects(:cost).returns(0)
assert password.stale?
end
private
def hashed_password
MinimalistAuthentication::Password.create('testing')
end
end
| 21.677419 | 64 | 0.736607 |
21d58dc6194b84affe6ee10b857d007880c3f74b | 1,138 | class Pari < Formula
desc "Computer algebra system designed for fast computations in number theory"
homepage "https://pari.math.u-bordeaux.fr/"
url "https://pari.math.u-bordeaux.fr/pub/pari/unix/pari-2.9.5.tar.gz"
sha256 "6b451825b41d2f8b29592c08d671999527bf936789c599d77b8dfdc663f1e617"
bottle do
sha256 "c8e1e3c1da64c35a7ecb8696e4cf31113112887fff6f1b16a193900f50ac73e6" => :high_sierra
sha256 "1ae613ef98c71ce691906dc7cf5282374bfa18cc669e8570b77152648bc3d8c7" => :sierra
sha256 "b5426e62d5db7181898d371c444889127e6e7a9336b40020ca65d51cb0f55006" => :el_capitan
end
depends_on "gmp"
depends_on "readline"
depends_on :x11
def install
readline = Formula["readline"].opt_prefix
gmp = Formula["gmp"].opt_prefix
system "./Configure", "--prefix=#{prefix}",
"--with-gmp=#{gmp}",
"--with-readline=#{readline}"
# make needs to be done in two steps
system "make", "all"
system "make", "install"
end
test do
(testpath/"math.tex").write "$k_{n+1} = n^2 + k_n^2 - k_{n-1}$"
system bin/"tex2mail", testpath/"math.tex"
end
end
| 34.484848 | 93 | 0.691564 |
d52d912dee815cc4cf0fa31ec4b550277357d576 | 1,730 | class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy,:following, :followers]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user,only: :destroy
def index
@users = User.search(params[:search]).paginate(page: params[:page])
end
def show
@user = User.find(params[:id])
@microposts = @user.microposts.paginate(page: params[:page])
end
def new
@user = User.new
end
def create
@user = User.new(user_params)
if @user.save
@user.send_activation_email
flash[:info] = "Please check your email to activate your account."
redirect_to root_url
else
render 'new'
end
end
def edit
end
def update
if @user.update_attributes(user_params)
flash[:success] = "Profile updated"
redirect_to @user
else
render 'edit'
end
end
def destroy
User.find(params[:id]).destroy
flash[:success] = "User deleted."
redirect_to users_url
end
def following
@title = "Following"
@user = User.find(params[:id])
@users = @user.following.paginate(page: params[:page])
render 'show_follow'
end
def followers
@title = "Followers"
@user = User.find(params[:id])
@users = @user.followers.paginate(page: params[:page])
render 'show_follow'
end
private
def user_params
params.require(:user).permit(:name, :email, :password, :password_confirmation)
end
# beforeアクション
#正しいユーザかどうか確認
def correct_user
@user = User.find(params[:id])
redirect_to(root_url) unless current_user?(@user)
end
def admin_user
redirect_to root_url unless current_user.admin?
end
end
| 21.358025 | 96 | 0.663584 |
267cefc1cafeb3c25e28045980e11f0889605491 | 4,043 | # RJR Request Representation
#
# Copyright (C) 2012-2014 Mohammed Morsi <[email protected]>
# Licensed under the Apache License, Version 2.0
require 'json'
require 'rjr/result'
require 'rjr/core_ext'
require 'rjr/util/args'
require 'rjr/util/logger'
module RJR
# JSON-RPC request representation.
#
# Registered request handlers will be invoked in the context of
# instances of this class, meaning all member variables will be available
# for use in the handler.
class Request
# Result of the request operation, set by dispatcher
attr_accessor :result
# Method which request is for
attr_accessor :rjr_method
# Arguments be passed to method
attr_accessor :rjr_method_args
# Argument object encapsulating arguments
attr_accessor :rjr_args
# Headers which came w/ request
attr_accessor :rjr_headers
# Client IP which request came in on (only for direct nodes)
attr_accessor :rjr_client_ip
# Port which request came in on (only for direct nodes)
attr_accessor :rjr_client_port
# RJR callback which may be used to push data to client
attr_accessor :rjr_callback
# Node which the request came in on
attr_accessor :rjr_node
# Type of node which request came in on
attr_accessor :rjr_node_type
# ID of node which request came in on
attr_accessor :rjr_node_id
# Environment handler will be run in
attr_accessor :rjr_env
# Actual proc registered to handle request
attr_accessor :rjr_handler
# RJR Request initializer
#
# @param [Hash] args options to set on request,
# see Request accessors for valid keys
def initialize(args = {})
@rjr_method = args[:rjr_method] || args['rjr_method']
@rjr_method_args = args[:rjr_method_args] || args['rjr_method_args'] || []
@rjr_headers = args[:rjr_headers] || args['rjr_headers']
@rjr_client_ip = args[:rjr_client_ip]
@rjr_client_port = args[:rjr_client_port]
@rjr_callback = args[:rjr_callback]
@rjr_node = args[:rjr_node]
@rjr_node_id = args[:rjr_node_id] || args['rjr_node_id']
@rjr_node_type = args[:rjr_node_type] || args['rjr_node_type']
@rjr_handler = args[:rjr_handler]
@rjr_args = Arguments.new :args => @rjr_method_args
@rjr_env = nil
@result = nil
end
# Set the environment by extending Request instance with the specified module
def set_env(env)
@rjr_env = env
self.extend(env)
end
# Invoke the request by calling the registered handler with the registered
# method parameters in the local scope
def handle
node_sig = "#{@rjr_node_id}(#{@rjr_node_type})"
method_sig = "#{@rjr_method}(#{@rjr_method_args.join(',')})"
RJR::Logger.info "#{node_sig}->#{method_sig}"
# TODO option to compare arity of handler to number
# of method_args passed in ?
retval = instance_exec(*@rjr_method_args, &@rjr_handler)
RJR::Logger.info \
"#{node_sig}<-#{method_sig}<-#{retval.nil? ? "nil" : retval}"
return retval
end
def request_json
{:request => { :rjr_method => @rjr_method,
:rjr_method_args => @rjr_method_args,
:rjr_headers => @rjr_headers,
:rjr_node_type => @rjr_node_type,
:rjr_node_id => @rjr_node_id }}
end
def result_json
return {} unless !!@result
{:result => { :result => @result.result,
:error_code => @result.error_code,
:error_msg => @result.error_msg,
:error_class => @result.error_class }}
end
# Convert request to json representation and return it
def to_json(*a)
{'json_class' => self.class.name,
'data' => request_json.merge(result_json)}.to_json(*a)
end
# Create new request from json representation
def self.json_create(o)
result = Result.new(o['data']['result'])
request = Request.new(o['data']['request'])
request.result = result
return request
end
end # class Request
end # module RJR
| 29.086331 | 79 | 0.663616 |
f79552c469d51fbb9ea18536eab41cd5e0ffcc0c | 213 | require 'spec_helper'
require 'object_schema/types/nil'
describe NilClass::Schema do
it "#as_json" do
schema = NilClass::Schema.new
expect(schema.as_json.symbolize_keys).to eq( type: 'null' )
end
end
| 21.3 | 63 | 0.7277 |
39a06f136f1f6654d5e3cf83384d0278ba104bd3 | 1,227 | class ArtistsController < ApplicationController
def index
end
def show
@artist = Artist.find_by(id: params[:id])
@user = User.find_by(id: current_user)
if @user == @artist
@current_artist = @user
elsif Artist.find_by(id: @user)
@other_artist = @user
else
@client = Client.find_by(id: @user)
end
end
def new
if logged_in?
flash[:error] = "You are already signed in."
if Client.find_by(id: current_user)
redirect_to client_path(current_user)
else
redirect_to artist_path(current_user)
end
else
@artist = Artist.new
end
end
def create
@artist = Artist.new(artist_params)
if @artist.save && params[:artist][:secret] == "BTS"
session[:user_id] = @artist.id
redirect_to artist_path(@artist)
else
render :new
end
end
def edit
@artist = Artist.find_by(id: current_user)
end
def update
@artist = Artist.find_by(id: current_user)
if @artist.update(artist_params)
redirect_to artist_path(@artist)
else
render :edit
end
end
private
def artist_params
params.require(:artist).permit(:name, :email, :extra, :password, :secret)
end
end
| 20.79661 | 77 | 0.637327 |
79338dc3691626057da26b565f7220047d8a482e | 843 | require 'spec_helper'
describe 'ceilometer::policy' do
shared_examples_for 'ceilometer policies' do
let :params do
{
:policy_path => '/etc/ceilometer/policy.json',
:policies => {
'context_is_admin' => {
'key' => 'context_is_admin',
'value' => 'foo:bar'
}
}
}
end
it 'set up the policies' do
should contain_openstacklib__policy__base('context_is_admin').with({
:key => 'context_is_admin',
:value => 'foo:bar'
})
end
end
context 'on Debian platforms' do
let :facts do
{ :osfamily => 'Debian' }
end
it_configures 'ceilometer policies'
end
context 'on RedHat platforms' do
let :facts do
{ :osfamily => 'RedHat' }
end
it_configures 'ceilometer policies'
end
end
| 20.071429 | 74 | 0.567023 |
7a1906b3ef96a715b7cf50eaead97e025869f986 | 458 | # frozen_string_literal: true
module Ci
class RetryPipelineWorker # rubocop:disable Scalability/IdempotentWorker
include ::ApplicationWorker
include ::PipelineQueue
urgency :high
worker_resource_boundary :cpu
def perform(pipeline_id, user_id)
::Ci::Pipeline.find_by_id(pipeline_id).try do |pipeline|
::User.find_by_id(user_id).try do |user|
pipeline.retry_failed(user)
end
end
end
end
end
| 22.9 | 74 | 0.700873 |
e8eaf3bed98247f0abc485c9d9d73fc6aa283154 | 441 | require 'rspec'
require_relative "../lib/fighter"
describe Fighter do
subject { Fighter.new("Bob") }
it "should have a strike" do
subject.strike.should be_a(Move)
end
it "should have block" do
subject.block.should be_a(Move)
end
it "should have a name" do
Fighter.new("Mike Tyson").name.should eq("Mike Tyson")
end
it "should return a valid move" do
subject.move = "strike"
subject.last_move.should be_a(Move)
end
end
| 19.173913 | 56 | 0.714286 |
394cfe4d37fae560653857bf8d68921434f87e53 | 483 | # frozen_string_literal: true
class NewsUpdate < ApplicationRecord
belongs_to :creator, class_name: "User"
belongs_to_updater
scope :recent, -> {where("created_at >= ?", 2.weeks.ago).order(created_at: :desc).limit(5)}
def self.visible(user)
if user.is_admin?
all
else
none
end
end
def self.search(params)
q = search_attributes(params, :id, :created_at, :updated_at, :message, :creator, :updater)
q.apply_default_order(params)
end
end
| 23 | 94 | 0.689441 |
e9560a22fa8c9338d5a901f1d398ee2afa9cc257 | 60,518 | # frozen_string_literal: true
# WARNING ABOUT GENERATED CODE
#
# This file is generated. See the contributing guide for more information:
# https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
module Aws::Synthetics
module Types
# A structure that contains the configuration for canary artifacts,
# including the encryption-at-rest settings for artifacts that the
# canary uploads to Amazon S3.
#
# @note When making an API call, you may pass ArtifactConfigInput
# data as a hash:
#
# {
# s3_encryption: {
# encryption_mode: "SSE_S3", # accepts SSE_S3, SSE_KMS
# kms_key_arn: "KmsKeyArn",
# },
# }
#
# @!attribute [rw] s3_encryption
# A structure that contains the configuration of the
# encryption-at-rest settings for artifacts that the canary uploads to
# Amazon S3. Artifact encryption functionality is available only for
# canaries that use Synthetics runtime version
# syn-nodejs-puppeteer-3.3 or later. For more information, see
# [Encrypting canary artifacts][1]
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html
# @return [Types::S3EncryptionConfig]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/ArtifactConfigInput AWS API Documentation
#
class ArtifactConfigInput < Struct.new(
:s3_encryption)
SENSITIVE = []
include Aws::Structure
end
# A structure that contains the configuration for canary artifacts,
# including the encryption-at-rest settings for artifacts that the
# canary uploads to Amazon S3.
#
# @!attribute [rw] s3_encryption
# A structure that contains the configuration of encryption settings
# for canary artifacts that are stored in Amazon S3.
# @return [Types::S3EncryptionConfig]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/ArtifactConfigOutput AWS API Documentation
#
class ArtifactConfigOutput < Struct.new(
:s3_encryption)
SENSITIVE = []
include Aws::Structure
end
# A structure representing a screenshot that is used as a baseline
# during visual monitoring comparisons made by the canary.
#
# @note When making an API call, you may pass BaseScreenshot
# data as a hash:
#
# {
# screenshot_name: "String", # required
# ignore_coordinates: ["BaseScreenshotConfigIgnoreCoordinate"],
# }
#
# @!attribute [rw] screenshot_name
# The name of the screenshot. This is generated the first time the
# canary is run after the `UpdateCanary` operation that specified for
# this canary to perform visual monitoring.
# @return [String]
#
# @!attribute [rw] ignore_coordinates
# Coordinates that define the part of a screen to ignore during
# screenshot comparisons. To obtain the coordinates to use here, use
# the CloudWatch Logs console to draw the boundaries on the screen.
# For more information, see \\\{LINK\\}
# @return [Array<String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/BaseScreenshot AWS API Documentation
#
class BaseScreenshot < Struct.new(
:screenshot_name,
:ignore_coordinates)
SENSITIVE = []
include Aws::Structure
end
# This structure contains all information about one canary in your
# account.
#
# @!attribute [rw] id
# The unique ID of this canary.
# @return [String]
#
# @!attribute [rw] name
# The name of the canary.
# @return [String]
#
# @!attribute [rw] code
# This structure contains information about the canary's Lambda
# handler and where its code is stored by CloudWatch Synthetics.
# @return [Types::CanaryCodeOutput]
#
# @!attribute [rw] execution_role_arn
# The ARN of the IAM role used to run the canary. This role must
# include `lambda.amazonaws.com` as a principal in the trust policy.
# @return [String]
#
# @!attribute [rw] schedule
# A structure that contains information about how often the canary is
# to run, and when these runs are to stop.
# @return [Types::CanaryScheduleOutput]
#
# @!attribute [rw] run_config
# A structure that contains information about a canary run.
# @return [Types::CanaryRunConfigOutput]
#
# @!attribute [rw] success_retention_period_in_days
# The number of days to retain data about successful runs of this
# canary.
# @return [Integer]
#
# @!attribute [rw] failure_retention_period_in_days
# The number of days to retain data about failed runs of this canary.
# @return [Integer]
#
# @!attribute [rw] status
# A structure that contains information about the canary's status.
# @return [Types::CanaryStatus]
#
# @!attribute [rw] timeline
# A structure that contains information about when the canary was
# created, modified, and most recently run.
# @return [Types::CanaryTimeline]
#
# @!attribute [rw] artifact_s3_location
# The location in Amazon S3 where Synthetics stores artifacts from the
# runs of this canary. Artifacts include the log file, screenshots,
# and HAR files.
# @return [String]
#
# @!attribute [rw] engine_arn
# The ARN of the Lambda function that is used as your canary's
# engine. For more information about Lambda ARN format, see [Resources
# and Conditions for Lambda Actions][1].
#
#
#
# [1]: https://docs.aws.amazon.com/lambda/latest/dg/lambda-api-permissions-ref.html
# @return [String]
#
# @!attribute [rw] runtime_version
# Specifies the runtime version to use for the canary. For more
# information about runtime versions, see [ Canary Runtime
# Versions][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html
# @return [String]
#
# @!attribute [rw] vpc_config
# If this canary is to test an endpoint in a VPC, this structure
# contains information about the subnets and security groups of the
# VPC endpoint. For more information, see [ Running a Canary in a
# VPC][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html
# @return [Types::VpcConfigOutput]
#
# @!attribute [rw] visual_reference
# If this canary performs visual monitoring by comparing screenshots,
# this structure contains the ID of the canary run to use as the
# baseline for screenshots, and the coordinates of any parts of the
# screen to ignore during the visual monitoring comparison.
# @return [Types::VisualReferenceOutput]
#
# @!attribute [rw] tags
# The list of key-value pairs that are associated with the canary.
# @return [Hash<String,String>]
#
# @!attribute [rw] artifact_config
# A structure that contains the configuration for canary artifacts,
# including the encryption-at-rest settings for artifacts that the
# canary uploads to Amazon S3.
# @return [Types::ArtifactConfigOutput]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/Canary AWS API Documentation
#
class Canary < Struct.new(
:id,
:name,
:code,
:execution_role_arn,
:schedule,
:run_config,
:success_retention_period_in_days,
:failure_retention_period_in_days,
:status,
:timeline,
:artifact_s3_location,
:engine_arn,
:runtime_version,
:vpc_config,
:visual_reference,
:tags,
:artifact_config)
SENSITIVE = []
include Aws::Structure
end
# Use this structure to input your script code for the canary. This
# structure contains the Lambda handler with the location where the
# canary should start running the script. If the script is stored in an
# S3 bucket, the bucket name, key, and version are also included. If the
# script was passed into the canary directly, the script code is
# contained in the value of `Zipfile`.
#
# @note When making an API call, you may pass CanaryCodeInput
# data as a hash:
#
# {
# s3_bucket: "String",
# s3_key: "String",
# s3_version: "String",
# zip_file: "data",
# handler: "String", # required
# }
#
# @!attribute [rw] s3_bucket
# If your canary script is located in S3, specify the bucket name
# here. Do not include `s3://` as the start of the bucket name.
# @return [String]
#
# @!attribute [rw] s3_key
# The S3 key of your script. For more information, see [Working with
# Amazon S3 Objects][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonS3/latest/dev/UsingObjects.html
# @return [String]
#
# @!attribute [rw] s3_version
# The S3 version ID of your script.
# @return [String]
#
# @!attribute [rw] zip_file
# If you input your canary script directly into the canary instead of
# referring to an S3 location, the value of this parameter is the
# base64-encoded contents of the .zip file that contains the script.
# It must be smaller than 256 Kb.
# @return [String]
#
# @!attribute [rw] handler
# The entry point to use for the source code when running the canary.
# This value must end with the string `.handler`. The string is
# limited to 29 characters or fewer.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryCodeInput AWS API Documentation
#
class CanaryCodeInput < Struct.new(
:s3_bucket,
:s3_key,
:s3_version,
:zip_file,
:handler)
SENSITIVE = []
include Aws::Structure
end
# This structure contains information about the canary's Lambda handler
# and where its code is stored by CloudWatch Synthetics.
#
# @!attribute [rw] source_location_arn
# The ARN of the Lambda layer where Synthetics stores the canary
# script code.
# @return [String]
#
# @!attribute [rw] handler
# The entry point to use for the source code when running the canary.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryCodeOutput AWS API Documentation
#
class CanaryCodeOutput < Struct.new(
:source_location_arn,
:handler)
SENSITIVE = []
include Aws::Structure
end
# This structure contains information about the most recent run of a
# single canary.
#
# @!attribute [rw] canary_name
# The name of the canary.
# @return [String]
#
# @!attribute [rw] last_run
# The results from this canary's most recent run.
# @return [Types::CanaryRun]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryLastRun AWS API Documentation
#
class CanaryLastRun < Struct.new(
:canary_name,
:last_run)
SENSITIVE = []
include Aws::Structure
end
# This structure contains the details about one run of one canary.
#
# @!attribute [rw] id
# A unique ID that identifies this canary run.
# @return [String]
#
# @!attribute [rw] name
# The name of the canary.
# @return [String]
#
# @!attribute [rw] status
# The status of this run.
# @return [Types::CanaryRunStatus]
#
# @!attribute [rw] timeline
# A structure that contains the start and end times of this run.
# @return [Types::CanaryRunTimeline]
#
# @!attribute [rw] artifact_s3_location
# The location where the canary stored artifacts from the run.
# Artifacts include the log file, screenshots, and HAR files.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryRun AWS API Documentation
#
class CanaryRun < Struct.new(
:id,
:name,
:status,
:timeline,
:artifact_s3_location)
SENSITIVE = []
include Aws::Structure
end
# A structure that contains input information for a canary run.
#
# @note When making an API call, you may pass CanaryRunConfigInput
# data as a hash:
#
# {
# timeout_in_seconds: 1,
# memory_in_mb: 1,
# active_tracing: false,
# environment_variables: {
# "EnvironmentVariableName" => "EnvironmentVariableValue",
# },
# }
#
# @!attribute [rw] timeout_in_seconds
# How long the canary is allowed to run before it must stop. You
# can't set this time to be longer than the frequency of the runs of
# this canary.
#
# If you omit this field, the frequency of the canary is used as this
# value, up to a maximum of 14 minutes.
# @return [Integer]
#
# @!attribute [rw] memory_in_mb
# The maximum amount of memory available to the canary while it is
# running, in MB. This value must be a multiple of 64.
# @return [Integer]
#
# @!attribute [rw] active_tracing
# Specifies whether this canary is to use active X-Ray tracing when it
# runs. Active tracing enables this canary run to be displayed in the
# ServiceLens and X-Ray service maps even if the canary does not hit
# an endpoint that has X-Ray tracing enabled. Using X-Ray tracing
# incurs charges. For more information, see [ Canaries and X-Ray
# tracing][1].
#
# You can enable active tracing only for canaries that use version
# `syn-nodejs-2.0` or later for their canary runtime.
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_tracing.html
# @return [Boolean]
#
# @!attribute [rw] environment_variables
# Specifies the keys and values to use for any environment variables
# used in the canary script. Use the following format:
#
# \\\{ "key1" : "value1", "key2" : "value2", ...\\}
#
# Keys must start with a letter and be at least two characters. The
# total size of your environment variables cannot exceed 4 KB. You
# can't specify any Lambda reserved environment variables as the keys
# for your environment variables. For more information about reserved
# keys, see [ Runtime environment variables][1].
#
#
#
# [1]: https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime
# @return [Hash<String,String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryRunConfigInput AWS API Documentation
#
class CanaryRunConfigInput < Struct.new(
:timeout_in_seconds,
:memory_in_mb,
:active_tracing,
:environment_variables)
SENSITIVE = []
include Aws::Structure
end
# A structure that contains information about a canary run.
#
# @!attribute [rw] timeout_in_seconds
# How long the canary is allowed to run before it must stop.
# @return [Integer]
#
# @!attribute [rw] memory_in_mb
# The maximum amount of memory available to the canary while it is
# running, in MB. This value must be a multiple of 64.
# @return [Integer]
#
# @!attribute [rw] active_tracing
# Displays whether this canary run used active X-Ray tracing.
# @return [Boolean]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryRunConfigOutput AWS API Documentation
#
class CanaryRunConfigOutput < Struct.new(
:timeout_in_seconds,
:memory_in_mb,
:active_tracing)
SENSITIVE = []
include Aws::Structure
end
# This structure contains the status information about a canary run.
#
# @!attribute [rw] state
# The current state of the run.
# @return [String]
#
# @!attribute [rw] state_reason
# If run of the canary failed, this field contains the reason for the
# error.
# @return [String]
#
# @!attribute [rw] state_reason_code
# If this value is `CANARY_FAILURE`, an exception occurred in the
# canary code. If this value is `EXECUTION_FAILURE`, an exception
# occurred in CloudWatch Synthetics.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryRunStatus AWS API Documentation
#
class CanaryRunStatus < Struct.new(
:state,
:state_reason,
:state_reason_code)
SENSITIVE = []
include Aws::Structure
end
# This structure contains the start and end times of a single canary
# run.
#
# @!attribute [rw] started
# The start time of the run.
# @return [Time]
#
# @!attribute [rw] completed
# The end time of the run.
# @return [Time]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryRunTimeline AWS API Documentation
#
class CanaryRunTimeline < Struct.new(
:started,
:completed)
SENSITIVE = []
include Aws::Structure
end
# This structure specifies how often a canary is to make runs and the
# date and time when it should stop making runs.
#
# @note When making an API call, you may pass CanaryScheduleInput
# data as a hash:
#
# {
# expression: "String", # required
# duration_in_seconds: 1,
# }
#
# @!attribute [rw] expression
# A `rate` expression or a `cron` expression that defines how often
# the canary is to run.
#
# For a rate expression, The syntax is `rate(number unit)`. *unit* can
# be `minute`, `minutes`, or `hour`.
#
# For example, `rate(1 minute)` runs the canary once a minute,
# `rate(10 minutes)` runs it once every 10 minutes, and `rate(1 hour)`
# runs it once every hour. You can specify a frequency between `rate(1
# minute)` and `rate(1 hour)`.
#
# Specifying `rate(0 minute)` or `rate(0 hour)` is a special value
# that causes the canary to run only once when it is started.
#
# Use `cron(expression)` to specify a cron expression. You can't
# schedule a canary to wait for more than a year before running. For
# information about the syntax for cron expressions, see [ Scheduling
# canary runs using cron][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_cron.html
# @return [String]
#
# @!attribute [rw] duration_in_seconds
# How long, in seconds, for the canary to continue making regular runs
# according to the schedule in the `Expression` value. If you specify
# 0, the canary continues making runs until you stop it. If you omit
# this field, the default of 0 is used.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryScheduleInput AWS API Documentation
#
class CanaryScheduleInput < Struct.new(
:expression,
:duration_in_seconds)
SENSITIVE = []
include Aws::Structure
end
# How long, in seconds, for the canary to continue making regular runs
# according to the schedule in the `Expression` value.
#
# @!attribute [rw] expression
# A `rate` expression or a `cron` expression that defines how often
# the canary is to run.
#
# For a rate expression, The syntax is `rate(number unit)`. *unit* can
# be `minute`, `minutes`, or `hour`.
#
# For example, `rate(1 minute)` runs the canary once a minute,
# `rate(10 minutes)` runs it once every 10 minutes, and `rate(1 hour)`
# runs it once every hour. You can specify a frequency between `rate(1
# minute)` and `rate(1 hour)`.
#
# Specifying `rate(0 minute)` or `rate(0 hour)` is a special value
# that causes the canary to run only once when it is started.
#
# Use `cron(expression)` to specify a cron expression. For information
# about the syntax for cron expressions, see [ Scheduling canary runs
# using cron][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_cron.html
# @return [String]
#
# @!attribute [rw] duration_in_seconds
# How long, in seconds, for the canary to continue making regular runs
# after it was created. The runs are performed according to the
# schedule in the `Expression` value.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryScheduleOutput AWS API Documentation
#
class CanaryScheduleOutput < Struct.new(
:expression,
:duration_in_seconds)
SENSITIVE = []
include Aws::Structure
end
# A structure that contains the current state of the canary.
#
# @!attribute [rw] state
# The current state of the canary.
# @return [String]
#
# @!attribute [rw] state_reason
# If the canary has insufficient permissions to run, this field
# provides more details.
# @return [String]
#
# @!attribute [rw] state_reason_code
# If the canary cannot run or has failed, this field displays the
# reason.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryStatus AWS API Documentation
#
class CanaryStatus < Struct.new(
:state,
:state_reason,
:state_reason_code)
SENSITIVE = []
include Aws::Structure
end
# This structure contains information about when the canary was created
# and modified.
#
# @!attribute [rw] created
# The date and time the canary was created.
# @return [Time]
#
# @!attribute [rw] last_modified
# The date and time the canary was most recently modified.
# @return [Time]
#
# @!attribute [rw] last_started
# The date and time that the canary's most recent run started.
# @return [Time]
#
# @!attribute [rw] last_stopped
# The date and time that the canary's most recent run ended.
# @return [Time]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CanaryTimeline AWS API Documentation
#
class CanaryTimeline < Struct.new(
:created,
:last_modified,
:last_started,
:last_stopped)
SENSITIVE = []
include Aws::Structure
end
# A conflicting operation is already in progress.
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/ConflictException AWS API Documentation
#
class ConflictException < Struct.new(
:message)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass CreateCanaryRequest
# data as a hash:
#
# {
# name: "CanaryName", # required
# code: { # required
# s3_bucket: "String",
# s3_key: "String",
# s3_version: "String",
# zip_file: "data",
# handler: "String", # required
# },
# artifact_s3_location: "String", # required
# execution_role_arn: "RoleArn", # required
# schedule: { # required
# expression: "String", # required
# duration_in_seconds: 1,
# },
# run_config: {
# timeout_in_seconds: 1,
# memory_in_mb: 1,
# active_tracing: false,
# environment_variables: {
# "EnvironmentVariableName" => "EnvironmentVariableValue",
# },
# },
# success_retention_period_in_days: 1,
# failure_retention_period_in_days: 1,
# runtime_version: "String", # required
# vpc_config: {
# subnet_ids: ["SubnetId"],
# security_group_ids: ["SecurityGroupId"],
# },
# tags: {
# "TagKey" => "TagValue",
# },
# artifact_config: {
# s3_encryption: {
# encryption_mode: "SSE_S3", # accepts SSE_S3, SSE_KMS
# kms_key_arn: "KmsKeyArn",
# },
# },
# }
#
# @!attribute [rw] name
# The name for this canary. Be sure to give it a descriptive name that
# distinguishes it from other canaries in your account.
#
# Do not include secrets or proprietary information in your canary
# names. The canary name makes up part of the canary ARN, and the ARN
# is included in outbound calls over the internet. For more
# information, see [Security Considerations for Synthetics
# Canaries][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/servicelens_canaries_security.html
# @return [String]
#
# @!attribute [rw] code
# A structure that includes the entry point from which the canary
# should start running your script. If the script is stored in an S3
# bucket, the bucket name, key, and version are also included.
# @return [Types::CanaryCodeInput]
#
# @!attribute [rw] artifact_s3_location
# The location in Amazon S3 where Synthetics stores artifacts from the
# test runs of this canary. Artifacts include the log file,
# screenshots, and HAR files. The name of the S3 bucket can't include
# a period (.).
# @return [String]
#
# @!attribute [rw] execution_role_arn
# The ARN of the IAM role to be used to run the canary. This role must
# already exist, and must include `lambda.amazonaws.com` as a
# principal in the trust policy. The role must also have the following
# permissions:
#
# * `s3:PutObject`
#
# * `s3:GetBucketLocation`
#
# * `s3:ListAllMyBuckets`
#
# * `cloudwatch:PutMetricData`
#
# * `logs:CreateLogGroup`
#
# * `logs:CreateLogStream`
#
# * `logs:PutLogEvents`
# @return [String]
#
# @!attribute [rw] schedule
# A structure that contains information about how often the canary is
# to run and when these test runs are to stop.
# @return [Types::CanaryScheduleInput]
#
# @!attribute [rw] run_config
# A structure that contains the configuration for individual canary
# runs, such as timeout value.
# @return [Types::CanaryRunConfigInput]
#
# @!attribute [rw] success_retention_period_in_days
# The number of days to retain data about successful runs of this
# canary. If you omit this field, the default of 31 days is used. The
# valid range is 1 to 455 days.
# @return [Integer]
#
# @!attribute [rw] failure_retention_period_in_days
# The number of days to retain data about failed runs of this canary.
# If you omit this field, the default of 31 days is used. The valid
# range is 1 to 455 days.
# @return [Integer]
#
# @!attribute [rw] runtime_version
# Specifies the runtime version to use for the canary. For a list of
# valid runtime versions and more information about runtime versions,
# see [ Canary Runtime Versions][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html
# @return [String]
#
# @!attribute [rw] vpc_config
# If this canary is to test an endpoint in a VPC, this structure
# contains information about the subnet and security groups of the VPC
# endpoint. For more information, see [ Running a Canary in a VPC][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html
# @return [Types::VpcConfigInput]
#
# @!attribute [rw] tags
# A list of key-value pairs to associate with the canary. You can
# associate as many as 50 tags with a canary.
#
# Tags can help you organize and categorize your resources. You can
# also use them to scope user permissions, by granting a user
# permission to access or change only the resources that have certain
# tag values.
# @return [Hash<String,String>]
#
# @!attribute [rw] artifact_config
# A structure that contains the configuration for canary artifacts,
# including the encryption-at-rest settings for artifacts that the
# canary uploads to Amazon S3.
# @return [Types::ArtifactConfigInput]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CreateCanaryRequest AWS API Documentation
#
class CreateCanaryRequest < Struct.new(
:name,
:code,
:artifact_s3_location,
:execution_role_arn,
:schedule,
:run_config,
:success_retention_period_in_days,
:failure_retention_period_in_days,
:runtime_version,
:vpc_config,
:tags,
:artifact_config)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] canary
# The full details about the canary you have created.
# @return [Types::Canary]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/CreateCanaryResponse AWS API Documentation
#
class CreateCanaryResponse < Struct.new(
:canary)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteCanaryRequest
# data as a hash:
#
# {
# name: "CanaryName", # required
# }
#
# @!attribute [rw] name
# The name of the canary that you want to delete. To find the names of
# your canaries, use [DescribeCanaries][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DeleteCanaryRequest AWS API Documentation
#
class DeleteCanaryRequest < Struct.new(
:name)
SENSITIVE = []
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DeleteCanaryResponse AWS API Documentation
#
class DeleteCanaryResponse < Aws::EmptyStructure; end
# @note When making an API call, you may pass DescribeCanariesLastRunRequest
# data as a hash:
#
# {
# next_token: "Token",
# max_results: 1,
# }
#
# @!attribute [rw] next_token
# A token that indicates that there is more data available. You can
# use this token in a subsequent `DescribeCanaries` operation to
# retrieve the next set of results.
# @return [String]
#
# @!attribute [rw] max_results
# Specify this parameter to limit how many runs are returned each time
# you use the `DescribeLastRun` operation. If you omit this parameter,
# the default of 100 is used.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeCanariesLastRunRequest AWS API Documentation
#
class DescribeCanariesLastRunRequest < Struct.new(
:next_token,
:max_results)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] canaries_last_run
# An array that contains the information from the most recent run of
# each canary.
# @return [Array<Types::CanaryLastRun>]
#
# @!attribute [rw] next_token
# A token that indicates that there is more data available. You can
# use this token in a subsequent `DescribeCanariesLastRun` operation
# to retrieve the next set of results.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeCanariesLastRunResponse AWS API Documentation
#
class DescribeCanariesLastRunResponse < Struct.new(
:canaries_last_run,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DescribeCanariesRequest
# data as a hash:
#
# {
# next_token: "Token",
# max_results: 1,
# }
#
# @!attribute [rw] next_token
# A token that indicates that there is more data available. You can
# use this token in a subsequent operation to retrieve the next set of
# results.
# @return [String]
#
# @!attribute [rw] max_results
# Specify this parameter to limit how many canaries are returned each
# time you use the `DescribeCanaries` operation. If you omit this
# parameter, the default of 100 is used.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeCanariesRequest AWS API Documentation
#
class DescribeCanariesRequest < Struct.new(
:next_token,
:max_results)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] canaries
# Returns an array. Each item in the array contains the full
# information about one canary.
# @return [Array<Types::Canary>]
#
# @!attribute [rw] next_token
# A token that indicates that there is more data available. You can
# use this token in a subsequent `DescribeCanaries` operation to
# retrieve the next set of results.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeCanariesResponse AWS API Documentation
#
class DescribeCanariesResponse < Struct.new(
:canaries,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DescribeRuntimeVersionsRequest
# data as a hash:
#
# {
# next_token: "Token",
# max_results: 1,
# }
#
# @!attribute [rw] next_token
# A token that indicates that there is more data available. You can
# use this token in a subsequent `DescribeRuntimeVersions` operation
# to retrieve the next set of results.
# @return [String]
#
# @!attribute [rw] max_results
# Specify this parameter to limit how many runs are returned each time
# you use the `DescribeRuntimeVersions` operation. If you omit this
# parameter, the default of 100 is used.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeRuntimeVersionsRequest AWS API Documentation
#
class DescribeRuntimeVersionsRequest < Struct.new(
:next_token,
:max_results)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] runtime_versions
# An array of objects that display the details about each Synthetics
# canary runtime version.
# @return [Array<Types::RuntimeVersion>]
#
# @!attribute [rw] next_token
# A token that indicates that there is more data available. You can
# use this token in a subsequent `DescribeRuntimeVersions` operation
# to retrieve the next set of results.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/DescribeRuntimeVersionsResponse AWS API Documentation
#
class DescribeRuntimeVersionsResponse < Struct.new(
:runtime_versions,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetCanaryRequest
# data as a hash:
#
# {
# name: "CanaryName", # required
# }
#
# @!attribute [rw] name
# The name of the canary that you want details for.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/GetCanaryRequest AWS API Documentation
#
class GetCanaryRequest < Struct.new(
:name)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] canary
# A strucure that contains the full information about the canary.
# @return [Types::Canary]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/GetCanaryResponse AWS API Documentation
#
class GetCanaryResponse < Struct.new(
:canary)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetCanaryRunsRequest
# data as a hash:
#
# {
# name: "CanaryName", # required
# next_token: "Token",
# max_results: 1,
# }
#
# @!attribute [rw] name
# The name of the canary that you want to see runs for.
# @return [String]
#
# @!attribute [rw] next_token
# A token that indicates that there is more data available. You can
# use this token in a subsequent `GetCanaryRuns` operation to retrieve
# the next set of results.
# @return [String]
#
# @!attribute [rw] max_results
# Specify this parameter to limit how many runs are returned each time
# you use the `GetCanaryRuns` operation. If you omit this parameter,
# the default of 100 is used.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/GetCanaryRunsRequest AWS API Documentation
#
class GetCanaryRunsRequest < Struct.new(
:name,
:next_token,
:max_results)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] canary_runs
# An array of structures. Each structure contains the details of one
# of the retrieved canary runs.
# @return [Array<Types::CanaryRun>]
#
# @!attribute [rw] next_token
# A token that indicates that there is more data available. You can
# use this token in a subsequent `GetCanaryRuns` operation to retrieve
# the next set of results.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/GetCanaryRunsResponse AWS API Documentation
#
class GetCanaryRunsResponse < Struct.new(
:canary_runs,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# An unknown internal error occurred.
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/InternalServerException AWS API Documentation
#
class InternalServerException < Struct.new(
:message)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass ListTagsForResourceRequest
# data as a hash:
#
# {
# resource_arn: "CanaryArn", # required
# }
#
# @!attribute [rw] resource_arn
# The ARN of the canary that you want to view tags for.
#
# The ARN format of a canary is
# `arn:aws:synthetics:Region:account-id:canary:canary-name `.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/ListTagsForResourceRequest AWS API Documentation
#
class ListTagsForResourceRequest < Struct.new(
:resource_arn)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] tags
# The list of tag keys and values associated with the canary that you
# specified.
# @return [Hash<String,String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/ListTagsForResourceResponse AWS API Documentation
#
class ListTagsForResourceResponse < Struct.new(
:tags)
SENSITIVE = []
include Aws::Structure
end
# One of the specified resources was not found.
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/ResourceNotFoundException AWS API Documentation
#
class ResourceNotFoundException < Struct.new(
:message)
SENSITIVE = []
include Aws::Structure
end
# This structure contains information about one canary runtime version.
# For more information about runtime versions, see [ Canary Runtime
# Versions][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html
#
# @!attribute [rw] version_name
# The name of the runtime version. For a list of valid runtime
# versions, see [ Canary Runtime Versions][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html
# @return [String]
#
# @!attribute [rw] description
# A description of the runtime version, created by Amazon.
# @return [String]
#
# @!attribute [rw] release_date
# The date that the runtime version was released.
# @return [Time]
#
# @!attribute [rw] deprecation_date
# If this runtime version is deprecated, this value is the date of
# deprecation.
# @return [Time]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/RuntimeVersion AWS API Documentation
#
class RuntimeVersion < Struct.new(
:version_name,
:description,
:release_date,
:deprecation_date)
SENSITIVE = []
include Aws::Structure
end
# A structure that contains the configuration of encryption-at-rest
# settings for canary artifacts that the canary uploads to Amazon S3.
#
# For more information, see [Encrypting canary artifacts][1]
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_artifact_encryption.html
#
# @note When making an API call, you may pass S3EncryptionConfig
# data as a hash:
#
# {
# encryption_mode: "SSE_S3", # accepts SSE_S3, SSE_KMS
# kms_key_arn: "KmsKeyArn",
# }
#
# @!attribute [rw] encryption_mode
# The encryption method to use for artifacts created by this canary.
# Specify `SSE_S3` to use server-side encryption (SSE) with an Amazon
# S3-managed key. Specify `SSE-KMS` to use server-side encryption with
# a customer-managed KMS key.
#
# If you omit this parameter, an Amazon Web Services-managed KMS key
# is used.
# @return [String]
#
# @!attribute [rw] kms_key_arn
# The ARN of the customer-managed KMS key to use, if you specify
# `SSE-KMS` for `EncryptionMode`
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/S3EncryptionConfig AWS API Documentation
#
class S3EncryptionConfig < Struct.new(
:encryption_mode,
:kms_key_arn)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass StartCanaryRequest
# data as a hash:
#
# {
# name: "CanaryName", # required
# }
#
# @!attribute [rw] name
# The name of the canary that you want to run. To find canary names,
# use [DescribeCanaries][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/StartCanaryRequest AWS API Documentation
#
class StartCanaryRequest < Struct.new(
:name)
SENSITIVE = []
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/StartCanaryResponse AWS API Documentation
#
class StartCanaryResponse < Aws::EmptyStructure; end
# @note When making an API call, you may pass StopCanaryRequest
# data as a hash:
#
# {
# name: "CanaryName", # required
# }
#
# @!attribute [rw] name
# The name of the canary that you want to stop. To find the names of
# your canaries, use [DescribeCanaries][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/StopCanaryRequest AWS API Documentation
#
class StopCanaryRequest < Struct.new(
:name)
SENSITIVE = []
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/StopCanaryResponse AWS API Documentation
#
class StopCanaryResponse < Aws::EmptyStructure; end
# @note When making an API call, you may pass TagResourceRequest
# data as a hash:
#
# {
# resource_arn: "CanaryArn", # required
# tags: { # required
# "TagKey" => "TagValue",
# },
# }
#
# @!attribute [rw] resource_arn
# The ARN of the canary that you're adding tags to.
#
# The ARN format of a canary is
# `arn:aws:synthetics:Region:account-id:canary:canary-name `.
# @return [String]
#
# @!attribute [rw] tags
# The list of key-value pairs to associate with the canary.
# @return [Hash<String,String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/TagResourceRequest AWS API Documentation
#
class TagResourceRequest < Struct.new(
:resource_arn,
:tags)
SENSITIVE = []
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/TagResourceResponse AWS API Documentation
#
class TagResourceResponse < Aws::EmptyStructure; end
# @note When making an API call, you may pass UntagResourceRequest
# data as a hash:
#
# {
# resource_arn: "CanaryArn", # required
# tag_keys: ["TagKey"], # required
# }
#
# @!attribute [rw] resource_arn
# The ARN of the canary that you're removing tags from.
#
# The ARN format of a canary is
# `arn:aws:synthetics:Region:account-id:canary:canary-name `.
# @return [String]
#
# @!attribute [rw] tag_keys
# The list of tag keys to remove from the resource.
# @return [Array<String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/UntagResourceRequest AWS API Documentation
#
class UntagResourceRequest < Struct.new(
:resource_arn,
:tag_keys)
SENSITIVE = []
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/UntagResourceResponse AWS API Documentation
#
class UntagResourceResponse < Aws::EmptyStructure; end
# @note When making an API call, you may pass UpdateCanaryRequest
# data as a hash:
#
# {
# name: "CanaryName", # required
# code: {
# s3_bucket: "String",
# s3_key: "String",
# s3_version: "String",
# zip_file: "data",
# handler: "String", # required
# },
# execution_role_arn: "RoleArn",
# runtime_version: "String",
# schedule: {
# expression: "String", # required
# duration_in_seconds: 1,
# },
# run_config: {
# timeout_in_seconds: 1,
# memory_in_mb: 1,
# active_tracing: false,
# environment_variables: {
# "EnvironmentVariableName" => "EnvironmentVariableValue",
# },
# },
# success_retention_period_in_days: 1,
# failure_retention_period_in_days: 1,
# vpc_config: {
# subnet_ids: ["SubnetId"],
# security_group_ids: ["SecurityGroupId"],
# },
# visual_reference: {
# base_screenshots: [
# {
# screenshot_name: "String", # required
# ignore_coordinates: ["BaseScreenshotConfigIgnoreCoordinate"],
# },
# ],
# base_canary_run_id: "String", # required
# },
# artifact_s3_location: "String",
# artifact_config: {
# s3_encryption: {
# encryption_mode: "SSE_S3", # accepts SSE_S3, SSE_KMS
# kms_key_arn: "KmsKeyArn",
# },
# },
# }
#
# @!attribute [rw] name
# The name of the canary that you want to update. To find the names of
# your canaries, use [DescribeCanaries][1].
#
# You cannot change the name of a canary that has already been
# created.
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_DescribeCanaries.html
# @return [String]
#
# @!attribute [rw] code
# A structure that includes the entry point from which the canary
# should start running your script. If the script is stored in an S3
# bucket, the bucket name, key, and version are also included.
# @return [Types::CanaryCodeInput]
#
# @!attribute [rw] execution_role_arn
# The ARN of the IAM role to be used to run the canary. This role must
# already exist, and must include `lambda.amazonaws.com` as a
# principal in the trust policy. The role must also have the following
# permissions:
#
# * `s3:PutObject`
#
# * `s3:GetBucketLocation`
#
# * `s3:ListAllMyBuckets`
#
# * `cloudwatch:PutMetricData`
#
# * `logs:CreateLogGroup`
#
# * `logs:CreateLogStream`
#
# * `logs:CreateLogStream`
# @return [String]
#
# @!attribute [rw] runtime_version
# Specifies the runtime version to use for the canary. For a list of
# valid runtime versions and for more information about runtime
# versions, see [ Canary Runtime Versions][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Library.html
# @return [String]
#
# @!attribute [rw] schedule
# A structure that contains information about how often the canary is
# to run, and when these runs are to stop.
# @return [Types::CanaryScheduleInput]
#
# @!attribute [rw] run_config
# A structure that contains the timeout value that is used for each
# individual run of the canary.
# @return [Types::CanaryRunConfigInput]
#
# @!attribute [rw] success_retention_period_in_days
# The number of days to retain data about successful runs of this
# canary.
# @return [Integer]
#
# @!attribute [rw] failure_retention_period_in_days
# The number of days to retain data about failed runs of this canary.
# @return [Integer]
#
# @!attribute [rw] vpc_config
# If this canary is to test an endpoint in a VPC, this structure
# contains information about the subnet and security groups of the VPC
# endpoint. For more information, see [ Running a Canary in a VPC][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html
# @return [Types::VpcConfigInput]
#
# @!attribute [rw] visual_reference
# Defines the screenshots to use as the baseline for comparisons
# during visual monitoring comparisons during future runs of this
# canary. If you omit this parameter, no changes are made to any
# baseline screenshots that the canary might be using already.
#
# Visual monitoring is supported only on canaries running the
# **syn-puppeteer-node-3.2** runtime or later. For more information,
# see [ Visual monitoring][1] and [ Visual monitoring blueprint][2]
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Library_SyntheticsLogger_VisualTesting.html
# [2]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Blueprints_VisualTesting.html
# @return [Types::VisualReferenceInput]
#
# @!attribute [rw] artifact_s3_location
# The location in Amazon S3 where Synthetics stores artifacts from the
# test runs of this canary. Artifacts include the log file,
# screenshots, and HAR files. The name of the S3 bucket can't include
# a period (.).
# @return [String]
#
# @!attribute [rw] artifact_config
# A structure that contains the configuration for canary artifacts,
# including the encryption-at-rest settings for artifacts that the
# canary uploads to Amazon S3.
# @return [Types::ArtifactConfigInput]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/UpdateCanaryRequest AWS API Documentation
#
class UpdateCanaryRequest < Struct.new(
:name,
:code,
:execution_role_arn,
:runtime_version,
:schedule,
:run_config,
:success_retention_period_in_days,
:failure_retention_period_in_days,
:vpc_config,
:visual_reference,
:artifact_s3_location,
:artifact_config)
SENSITIVE = []
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/UpdateCanaryResponse AWS API Documentation
#
class UpdateCanaryResponse < Aws::EmptyStructure; end
# A parameter could not be validated.
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/ValidationException AWS API Documentation
#
class ValidationException < Struct.new(
:message)
SENSITIVE = []
include Aws::Structure
end
# An object that specifies what screenshots to use as a baseline for
# visual monitoring by this canary, and optionally the parts of the
# screenshots to ignore during the visual monitoring comparison.
#
# Visual monitoring is supported only on canaries running the
# **syn-puppeteer-node-3.2** runtime or later. For more information, see
# [ Visual monitoring][1] and [ Visual monitoring blueprint][2]
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Library_SyntheticsLogger_VisualTesting.html
# [2]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_Blueprints_VisualTesting.html
#
# @note When making an API call, you may pass VisualReferenceInput
# data as a hash:
#
# {
# base_screenshots: [
# {
# screenshot_name: "String", # required
# ignore_coordinates: ["BaseScreenshotConfigIgnoreCoordinate"],
# },
# ],
# base_canary_run_id: "String", # required
# }
#
# @!attribute [rw] base_screenshots
# An array of screenshots that will be used as the baseline for visual
# monitoring in future runs of this canary. If there is a screenshot
# that you don't want to be used for visual monitoring, remove it
# from this array.
# @return [Array<Types::BaseScreenshot>]
#
# @!attribute [rw] base_canary_run_id
# Specifies which canary run to use the screenshots from as the
# baseline for future visual monitoring with this canary. Valid values
# are `nextrun` to use the screenshots from the next run after this
# update is made, `lastrun` to use the screenshots from the most
# recent run before this update was made, or the value of `Id` in the
# [ CanaryRun][1] from any past run of this canary.
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonSynthetics/latest/APIReference/API_CanaryRun.html
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/VisualReferenceInput AWS API Documentation
#
class VisualReferenceInput < Struct.new(
:base_screenshots,
:base_canary_run_id)
SENSITIVE = []
include Aws::Structure
end
# If this canary performs visual monitoring by comparing screenshots,
# this structure contains the ID of the canary run that is used as the
# baseline for screenshots, and the coordinates of any parts of those
# screenshots that are ignored during visual monitoring comparison.
#
# Visual monitoring is supported only on canaries running the
# **syn-puppeteer-node-3.2** runtime or later.
#
# @!attribute [rw] base_screenshots
# An array of screenshots that are used as the baseline for
# comparisons during visual monitoring.
# @return [Array<Types::BaseScreenshot>]
#
# @!attribute [rw] base_canary_run_id
# The ID of the canary run that produced the screenshots that are used
# as the baseline for visual monitoring comparisons during future runs
# of this canary.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/VisualReferenceOutput AWS API Documentation
#
class VisualReferenceOutput < Struct.new(
:base_screenshots,
:base_canary_run_id)
SENSITIVE = []
include Aws::Structure
end
# If this canary is to test an endpoint in a VPC, this structure
# contains information about the subnets and security groups of the VPC
# endpoint. For more information, see [ Running a Canary in a VPC][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html
#
# @note When making an API call, you may pass VpcConfigInput
# data as a hash:
#
# {
# subnet_ids: ["SubnetId"],
# security_group_ids: ["SecurityGroupId"],
# }
#
# @!attribute [rw] subnet_ids
# The IDs of the subnets where this canary is to run.
# @return [Array<String>]
#
# @!attribute [rw] security_group_ids
# The IDs of the security groups for this canary.
# @return [Array<String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/VpcConfigInput AWS API Documentation
#
class VpcConfigInput < Struct.new(
:subnet_ids,
:security_group_ids)
SENSITIVE = []
include Aws::Structure
end
# If this canary is to test an endpoint in a VPC, this structure
# contains information about the subnets and security groups of the VPC
# endpoint. For more information, see [ Running a Canary in a VPC][1].
#
#
#
# [1]: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Synthetics_Canaries_VPC.html
#
# @!attribute [rw] vpc_id
# The IDs of the VPC where this canary is to run.
# @return [String]
#
# @!attribute [rw] subnet_ids
# The IDs of the subnets where this canary is to run.
# @return [Array<String>]
#
# @!attribute [rw] security_group_ids
# The IDs of the security groups for this canary.
# @return [Array<String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/synthetics-2017-10-11/VpcConfigOutput AWS API Documentation
#
class VpcConfigOutput < Struct.new(
:vpc_id,
:subnet_ids,
:security_group_ids)
SENSITIVE = []
include Aws::Structure
end
end
end
| 35.24636 | 141 | 0.630936 |
7a31ad5f8d101a762a4fa72e66bed6cde74ac830 | 2,361 | module Searchlogic
module NamedScopes
# Adds the ability to create alias scopes that allow you to alias a named
# scope or create a named scope procedure, while at the same time letting
# Searchlogic know that this is a safe method.
module AliasScope
# The searchlogic Search class takes a hash and chains the values together as named scopes.
# For security reasons the only hash keys that are allowed must be mapped to named scopes.
# You can not pass the name of a class method and expect that to be called. In some instances
# you might create a class method that essentially aliases a named scope or represents a
# named scope procedure. Ex:
#
# User.named_scope :teenager, :conditions => ["age >= ? AND age <= ?", 13, 19]
#
# This is obviously a very basic example, but there is logic that is duplicated here. For
# more complicated named scopes this might make more sense, but to make my point you could
# do something like this instead
#
# class User
# def teenager
# age_gte(13).age_lte(19)
# end
# end
#
# As I stated above, you could not use this method with the Searchlogic::Search class because
# there is no way to tell that this is actually a named scope. Instead, Searchlogic lets you
# do something like this:
#
# User.alias_scope :teenager, lambda { age_gte(13).age_lte(19) }
#
# It fits in better, at the same time Searchlogic will know this is an acceptable named scope.
def alias_scope(name, options = nil)
alias_scopes[name.to_sym] = options
(class << self; self end).instance_eval do
define_method name do |*args|
case options
when Symbol
send(options)
else
options.call(*args)
end
end
end
end
def alias_scopes # :nodoc:
@alias_scopes ||= {}
end
def alias_scope?(name) # :nodoc:
return false if name.blank?
alias_scopes.key?(name.to_sym)
end
def condition?(name) # :nodoc:
super || alias_scope?(name)
end
def named_scope_options(name) # :nodoc:
super || alias_scopes[name.to_sym]
end
end
end
end | 36.890625 | 100 | 0.615417 |
33ae567d16ce6bf4dede1bc6b820ec4a38dcd54e | 1,685 | class QpidProton < Formula
desc "High-performance, lightweight AMQP 1.0 messaging library"
homepage "https://qpid.apache.org/proton/"
url "https://www.apache.org/dyn/closer.lua?path=qpid/proton/0.37.0/qpid-proton-0.37.0.tar.gz"
mirror "https://archive.apache.org/dist/qpid/proton/0.37.0/qpid-proton-0.37.0.tar.gz"
sha256 "265a76896bf6ede91aa5e3da3d9c26f5392a2d74f5f047318f3e79cbd348021e"
license "Apache-2.0"
head "https://gitbox.apache.org/repos/asf/qpid-proton.git", branch: "main"
bottle do
root_url "https://github.com/gromgit/homebrew-core-mojave/releases/download/qpid-proton"
sha256 cellar: :any, mojave: "ade8aa4dedeae9a2d0301e7016cc1a67205eeb4fd395c0745cc6609434677627"
end
depends_on "cmake" => :build
depends_on "pkg-config" => :build
depends_on "[email protected]" => :build
depends_on "libuv"
depends_on "[email protected]"
def install
system "cmake", "-S", ".", "-B", "build",
"-DBUILD_BINDINGS=",
"-DLIB_INSTALL_DIR=#{lib}",
"-DCMAKE_INSTALL_RPATH=#{rpath}",
"-Dproactor=libuv",
*std_cmake_args
system "cmake", "--build", "build"
system "cmake", "--install", "build"
end
test do
(testpath/"test.c").write <<~EOS
#include "proton/message.h"
#include "proton/messenger.h"
int main()
{
pn_message_t * message;
pn_messenger_t * messenger;
pn_data_t * body;
message = pn_message();
messenger = pn_messenger(NULL);
return 0;
}
EOS
system ENV.cc, "test.c", "-L#{lib}", "-lqpid-proton", "-o", "test"
system "./test"
end
end
| 33.7 | 99 | 0.622552 |
e815b497e1c34b7723b2592d5a9b8c91b13254c4 | 1,877 | class Variant < ApplicationRecord
include Moderated
include Subscribable
include Flaggable
include Commentable
include WithTimepointCounts
belongs_to :gene
belongs_to :secondary_gene, class_name: 'Gene', optional: true
has_many :evidence_items
has_many :assertions
has_many :variant_group_variants
has_many :variant_groups, through: :variant_group_variants
has_many :source_suggestions
has_and_belongs_to_many :variant_aliases
has_and_belongs_to_many :variant_types
has_and_belongs_to_many :clinvar_entries
has_and_belongs_to_many :hgvs_expressions
has_and_belongs_to_many :sources
has_one :evidence_items_by_status
has_many :comment_mentions, foreign_key: :comment_id, class_name: 'EntityMention'
enum reference_build: [:GRCh38, :GRCh37, :NCBI36]
after_save :update_allele_registry_id
validates :reference_bases, format: {
with: /\A[ACTG]+\z|\A[ACTG]+\/[ACTG]+\z/,
message: "only allows A,C,T,G or /"
}, allow_nil: true
validates :variant_bases, format: {
with: /\A[ACTG]+\z|\A[ACTG]+\/[ACTG]+\z/,
message: "only allows A,C,T,G or /"
}, allow_nil: true
searchkick highlight: [:name, :aliases], callbacks: :async
scope :search_import, -> { includes(:variant_aliases, :gene) }
def search_data
{
name: "#{gene.name} - #{name}",
gene: gene.name,
aliases: variant_aliases.map(&:name),
}
end
def link
Rails.application.routes.url_helpers.url_for("/variants/#{self.id}")
end
def self.timepoint_query
->(x) {
self.joins(:evidence_items)
.group('variants.id')
.select('variants.id')
.where("evidence_items.status != 'rejected'")
.having('MIN(evidence_items.created_at) >= ?', x)
.distinct
.count
}
end
def update_allele_registry_id
SetAlleleRegistryIdSingleVariant.perform_later(self)
end
end
| 27.602941 | 83 | 0.706979 |
5d8f22c320b27db8013eabf7e24101f6afa69173 | 5,058 | class R < Formula
desc "Software environment for statistical computing"
homepage "https://www.r-project.org/"
url "https://cran.r-project.org/src/base/R-4/R-4.1.3.tar.gz"
sha256 "15ff5b333c61094060b2a52e9c1d8ec55cc42dd029e39ca22abdaa909526fed6"
license "GPL-2.0-or-later"
livecheck do
url "https://cran.rstudio.com/banner.shtml"
regex(%r{href=(?:["']?|.*?/)R[._-]v?(\d+(?:\.\d+)+)\.t}i)
end
bottle do
sha256 arm64_monterey: "a34f069127fda71f97b119036520d56703212ab38137b79b7e92cf351f69292e"
sha256 arm64_big_sur: "5f1088340bcd5f8bfc75d2dee84212f8eda0769464e06c24c0819612fb415ee7"
sha256 monterey: "edae2c1cd7044eca95092fdf6f370991db60393baf902acf35844f7fd8203e0c"
sha256 big_sur: "28f9d5c6639eca65d2556b20e8816e04353c5d879ac21ff0186843ced832096e"
sha256 catalina: "bda2b0bd71f0922a8c275b03c8191b4e54acff3a9a8e572df708b096fc17324b"
sha256 x86_64_linux: "39c7d343bb57f8804402e5322bcf97ac49e06933d048d73e2ab0adfa14a8c80a"
end
depends_on "pkg-config" => :build
depends_on "texinfo" => :build
depends_on "cairo"
depends_on "gcc" # for gfortran
depends_on "gettext"
depends_on "jpeg"
depends_on "libffi"
depends_on "libpng"
depends_on "openblas"
depends_on "pcre2"
depends_on "readline"
depends_on "tcl-tk"
depends_on "xz"
uses_from_macos "curl"
uses_from_macos "icu4c"
on_macos do
depends_on "texlive" => :build
end
on_linux do
depends_on "pango"
depends_on "libice"
depends_on "libx11"
depends_on "libxt"
depends_on "libtirpc"
end
# needed to preserve executable permissions on files without shebangs
skip_clean "lib/R/bin", "lib/R/doc"
def install
# BLAS detection fails with Xcode 12 due to missing prototype
# https://bugs.r-project.org/bugzilla/show_bug.cgi?id=18024
ENV.append "CFLAGS", "-Wno-implicit-function-declaration"
args = [
"--prefix=#{prefix}",
"--enable-memory-profiling",
"--with-tcl-config=#{Formula["tcl-tk"].opt_lib}/tclConfig.sh",
"--with-tk-config=#{Formula["tcl-tk"].opt_lib}/tkConfig.sh",
"--with-blas=-L#{Formula["openblas"].opt_lib} -lopenblas",
"--enable-R-shlib",
"--disable-java",
"--with-cairo",
]
if OS.mac?
args << "--without-x"
args << "--with-aqua"
else
args << "--libdir=#{lib}" # avoid using lib64 on CentOS
# Avoid references to homebrew shims
args << "LD=ld"
# If LDFLAGS contains any -L options, configure sets LD_LIBRARY_PATH to
# search those directories. Remove -LHOMEBREW_PREFIX/lib from LDFLAGS.
ENV.remove "LDFLAGS", "-L#{HOMEBREW_PREFIX}/lib"
ENV.append "CPPFLAGS", "-I#{Formula["libtirpc"].opt_include}/tirpc"
ENV.append "LDFLAGS", "-L#{Formula["libtirpc"].opt_lib}"
end
# Help CRAN packages find gettext and readline
["gettext", "readline", "xz"].each do |f|
ENV.append "CPPFLAGS", "-I#{Formula[f].opt_include}"
ENV.append "LDFLAGS", "-L#{Formula[f].opt_lib}"
end
system "./configure", *args
system "make"
ENV.deparallelize do
system "make", "install"
end
cd "src/nmath/standalone" do
system "make"
ENV.deparallelize do
system "make", "install"
end
end
r_home = lib/"R"
# make Homebrew packages discoverable for R CMD INSTALL
inreplace r_home/"etc/Makeconf" do |s|
s.gsub!(/^CPPFLAGS =.*/, "\\0 -I#{HOMEBREW_PREFIX}/include")
s.gsub!(/^LDFLAGS =.*/, "\\0 -L#{HOMEBREW_PREFIX}/lib")
s.gsub!(/.LDFLAGS =.*/, "\\0 $(LDFLAGS)")
end
include.install_symlink Dir[r_home/"include/*"]
lib.install_symlink Dir[r_home/"lib/*"]
# avoid triggering mandatory rebuilds of r when gcc is upgraded
check_replace = OS.mac?
inreplace lib/"R/etc/Makeconf", Formula["gcc"].prefix.realpath,
Formula["gcc"].opt_prefix,
check_replace
end
def post_install
short_version =
`#{bin}/Rscript -e 'cat(as.character(getRversion()[1,1:2]))'`.strip
site_library = HOMEBREW_PREFIX/"lib/R/#{short_version}/site-library"
site_library.mkpath
ln_s site_library, lib/"R/site-library"
end
test do
assert_equal "[1] 2", shell_output("#{bin}/Rscript -e 'print(1+1)'").chomp
assert_equal shared_library(""), shell_output("#{bin}/R CMD config DYLIB_EXT").chomp
system bin/"Rscript", "-e", "if(!capabilities('cairo')) stop('cairo not available')"
system bin/"Rscript", "-e", "install.packages('gss', '.', 'https://cloud.r-project.org')"
assert_predicate testpath/"gss/libs/gss.so", :exist?,
"Failed to install gss package"
winsys = "[1] \"aqua\""
on_linux do
# Fails in Linux CI with: no DISPLAY variable so Tk is not available
return if ENV["HOMEBREW_GITHUB_ACTIONS"]
winsys = "[1] \"x11\""
end
assert_equal winsys,
shell_output("#{bin}/Rscript -e 'library(tcltk)' -e 'tclvalue(.Tcl(\"tk windowingsystem\"))'").chomp
end
end
| 33.058824 | 117 | 0.654211 |
6139cd847b86cfa9261f723243c07b31a49c2b5a | 2,493 | #
# Copyright:: Copyright (c) 2018 Chef Software 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 "chef_apply/action/generate_temp_cookbook"
RSpec.describe ChefApply::Action::GenerateTempCookbook do
let(:options) { {} }
subject { ChefApply::Action::GenerateTempCookbook }
describe ".from_options" do
context "when given options for a recipe" do
let(:options) { { recipe_spec: "some::recipe" } }
it "returns a GenerateCookbookFromRecipe action" do
expect(subject.from_options(options)).to be_a(ChefApply::Action::GenerateCookbookFromRecipe)
end
end
context "when given options for a resource" do
let(:resource_properties) { {} }
let(:options) do
{ resource_name: "user1", resource_type: "user",
resource_properties: resource_properties }
end
it "returns a GenerateCookbookFromResource action" do
expect(subject.from_options(options)).to be_a ChefApply::Action::GenerateCookbookFromResource
end
end
context "when not given sufficient options for either" do
let(:options) { {} }
it "raises MissingOptions" do
expect { subject.from_options(options) }.to raise_error ChefApply::Action::MissingOptions
end
end
end
describe "#perform_action" do
subject { ChefApply::Action::GenerateTempCookbook.new( {} ) }
it "generates a cookbook, notifies caller, and makes the cookbook available" do
expect(subject).to receive(:notify).ordered.with(:generating)
expect(subject).to receive(:generate)
expect(subject).to receive(:notify).ordered.with(:success)
subject.perform_action
expect(subject.generated_cookbook).to_not be nil
end
end
end
RSpec.describe ChefApply::Action::GenerateCookbookFromRecipe do
xit "#generate", "Please implement me"
end
RSpec.describe ChefApply::Action::GenerateCookbookFromResource do
xit "#generate", "Please implement me"
end
| 33.689189 | 101 | 0.720818 |
f88b0ec66b803aa4b6141e8df69826fff6218e5a | 1,700 | class Sonobuoy < Formula
desc "Kubernetes component that generates reports on cluster conformance"
homepage "https://github.com/vmware-tanzu/sonobuoy"
url "https://github.com/vmware-tanzu/sonobuoy/archive/v0.56.6.tar.gz"
sha256 "d2faffe1d68bcc554d201af8d763a2a820c0ed2df8a73732f5996475b94c05a7"
license "Apache-2.0"
bottle do
sha256 cellar: :any_skip_relocation, arm64_monterey: "d05c5aaaf1aab1720dff1cfa9c2898bf70b20c267be998fac50b49545016ac9c"
sha256 cellar: :any_skip_relocation, arm64_big_sur: "1b116b03cffb9b778ef3811a1fcb36e86e95cb93a0b568ac4f86d6105c0fa9f2"
sha256 cellar: :any_skip_relocation, monterey: "ede35cf1fc40860619216efbac2257c27dea9d97c12ae44ecfec81df72043bdd"
sha256 cellar: :any_skip_relocation, big_sur: "dda9134277eac93cd6f9835900257d96bbff8ce5b79d1c93298b2dab51965eb0"
sha256 cellar: :any_skip_relocation, catalina: "f84893fffc0adeaa9c56e510eed70e850fbcc7ab0bb39d8408c4be409d1db010"
sha256 cellar: :any_skip_relocation, x86_64_linux: "d779af929db705821f0a3119d1d38be015526f0d776467277525013fd9e4ea31"
end
# Segfaults on Go 1.18 - try test it again when updating this formula.
depends_on "[email protected]" => :build
def install
system "go", "build", *std_go_args(ldflags: "-s -w -X github.com/vmware-tanzu/sonobuoy/pkg/buildinfo.Version=v#{version}")
end
test do
assert_match "Sonobuoy is a Kubernetes component that generates reports on cluster conformance",
shell_output("#{bin}/sonobuoy 2>&1")
assert_match version.to_s,
shell_output("#{bin}/sonobuoy version 2>&1")
assert_match "name: sonobuoy",
shell_output("#{bin}/sonobuoy gen --kubernetes-version=v1.21 2>&1")
end
end
| 51.515152 | 126 | 0.780588 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.