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
795500559dcb638388d6835ad79cb59f65555cb5
533
# encoding: utf-8 Gem::Specification.new do |s| s.name = "disque" s.version = "0.0.6" s.summary = "Client for Disque" s.description = "Disque client for Ruby" s.authors = ["Michel Martens", "Damian Janowski"] s.email = ["michel@soveran.com", "damian.janowski@gmail.com"] s.homepage = "https://github.com/soveran/disque-rb" s.files = `git ls-files`.split("\n") s.license = "MIT" s.add_dependency "redic", "~> 1.5.0" end
33.3125
75
0.536585
e2eb00a09bd01d0b50859bf2279d43d495443536
1,330
# frozen_string_literal: true describe LayoutHelper, type: :helper do describe '#show_layout_flash?' do subject { show_layout_flash? } context 'without a layout flash' do before { @layout_flash = nil } it { is_expected.to be_truthy } end context 'with a layout flash' do before { @layout_flash = 'layout flash' } it { is_expected.to be_truthy } end end describe '#flash_messages' do context 'without :layout_flash set' do let(:opts) { {} } before { flash_messages(opts) } it 'sets @layout_flash to true' do expect(@layout_flash).to be_truthy end end context 'with :layout_flash set' do let(:opts) { { layout_flash: false } } before { flash_messages(opts) } it 'sets @layout_flash opts(:layout_flash)' do expect(@layout_flash).to eq(opts[:layout_flash]) end end context 'with or without :layout_flash set' do before { flash[:notice] = 'notice_flash' } let(:opts) { { layout_flash: false } } subject(:output) { flash_messages(opts) } it 'will have flash message' do expect(output).to include(flash[:notice]) end it 'will have div with id for each flash' do expect(output).to have_selector('div#flash_notice') end end end end
26.078431
59
0.630075
4a852fde6a6e1c6fafd3a45d868af168ae0277ef
331
module Jekyll module HideCustomBibtex def hideCustomBibtex(input) keywords = @context.registers[:site].config['filtered_bibtex_keywords'] keywords.each do |keyword| input = input.gsub(/^.*#{keyword}.*$\n/, '') end return input end end end Liquid::Template.register_filter(Jekyll::HideCustomBibtex)
20.6875
74
0.703927
21651a7664c0992c831a0801c32497304157341f
807
# (c) Copyright 2018 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. module OneviewCookbook module API600 module Synergy # ServerProfile API600 Synergy provider class ServerProfileProvider < API500::Synergy::ServerProfileProvider end end end end
38.428571
84
0.767038
21853fa9dbc3b4f2ec37faf68eb7dd5eccc770b4
3,196
# frozen_string_literal: true module RuboCop module Cop module Style # Access modifiers should be declared to apply to a group of methods # or inline before each method, depending on configuration. # EnforcedStyle config covers only method definitions. # Applications of visibility methods to symbols can be controlled # using AllowModifiersOnSymbols config. # # @example EnforcedStyle: group (default) # # bad # class Foo # # private def bar; end # private def baz; end # # end # # # good # class Foo # # private # # def bar; end # def baz; end # # end # # @example EnforcedStyle: inline # # bad # class Foo # # private # # def bar; end # def baz; end # # end # # # good # class Foo # # private def bar; end # private def baz; end # # end # # @example AllowModifiersOnSymbols: true # # good # class Foo # # private :bar, :baz # # end # # @example AllowModifiersOnSymbols: false # # bad # class Foo # # private :bar, :baz # # end class AccessModifierDeclarations < Cop include ConfigurableEnforcedStyle GROUP_STYLE_MESSAGE = [ '`%<access_modifier>s` should not be', 'inlined in method definitions.' ].join(' ') INLINE_STYLE_MESSAGE = [ '`%<access_modifier>s` should be', 'inlined in method definitions.' ].join(' ') def_node_matcher :access_modifier_with_symbol?, <<~PATTERN (send nil? {:private :protected :public} (sym _)) PATTERN def on_send(node) return unless node.access_modifier? return if node.parent.pair_type? return if cop_config['AllowModifiersOnSymbols'] && access_modifier_with_symbol?(node) if offense?(node) add_offense(node, location: :selector) do opposite_style_detected end else correct_style_detected end end private def offense?(node) (group_style? && access_modifier_is_inlined?(node)) || (inline_style? && access_modifier_is_not_inlined?(node)) end def group_style? style == :group end def inline_style? style == :inline end def access_modifier_is_inlined?(node) node.arguments.any? end def access_modifier_is_not_inlined?(node) !access_modifier_is_inlined?(node) end def message(node) access_modifier = node.loc.selector.source if group_style? format(GROUP_STYLE_MESSAGE, access_modifier: access_modifier) elsif inline_style? format(INLINE_STYLE_MESSAGE, access_modifier: access_modifier) end end end end end end
24.030075
74
0.532541
87bab129bbcd4cece11db266c7e06fb94dde3e55
330
require 'rails/generators/model_helpers' module Rails module Generators class ModelGenerator < NamedBase # :nodoc: include Rails::Generators::ModelHelpers argument :attributes, type: :array, default: [], banner: "field[:type][:index] field[:type][:index]" hook_for :orm, required: true end end end
25.384615
106
0.693939
261af7bfd693cbc058bfb2a9ad57299846001e93
122
module SS::Addon::EditorSetting extend ActiveSupport::Concern extend SS::Addon include SS::Model::EditorSetting end
20.333333
34
0.778689
e93ed22ff2a820cdf0b955bf52d371d1dc417041
1,185
require "spec_helper" module RubyEventStore RSpec.describe TransformKeys do let(:hash_with_symbols) { { one: 1, two: 2.0, three: true, four: Date.new(2018, 4, 17), five: "five", six: Time.utc(2018, 12, 13, 11 ), seven: true, eight: false, nein: nil, ten: {some: "hash", with: {nested: "values"}}, eleven: [1,{another: "hash", here: 2},3], } } let(:hash_with_strings) { { "one" => 1, "two" => 2.0, "three" => true, "four" => Date.new(2018, 4, 17), "five" => "five", "six" => Time.utc(2018, 12, 13, 11 ), "seven" => true, "eight" => false, "nein" => nil, "ten" => {"some" => "hash", "with" => {"nested" => "values"}}, "eleven" => [1,{"another" => "hash", "here" => 2},3], } } it { expect(TransformKeys.stringify(hash_with_symbols)).to eq(hash_with_strings) } it { expect(TransformKeys.stringify(hash_with_strings)).to eq(hash_with_strings) } it { expect(TransformKeys.symbolize(hash_with_strings)).to eq(hash_with_symbols) } it { expect(TransformKeys.symbolize(hash_with_symbols)).to eq(hash_with_symbols) } end end
30.384615
86
0.562025
bb0d36183e40c49cc667c11cf55e2157ae84e7e7
4,855
# # Copyright (c) 2019-present, Vicarious, Inc. # Copyright (c) 2020-present, Facebook, Inc. # All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default_action [:manage] action :manage do # You can't add users if their primary group doesn't exist. So, first # we find all primary groups, and make sure they exist, or create them if node['fb_users']['user_defaults']['gid'] pgroups = [node['fb_users']['user_defaults']['gid']] end pgroups += node['fb_users']['users'].map { |_, info| info['gid'] } pgroups = pgroups.compact.sort.uniq Chef::Log.debug( 'fb_users: the following groups are GIDs and may need bootstrapping: ' + "#{pgroups.join(', ')}.", ) pgroups.each do |grp| if node['etc']['group'][grp] && node['etc']['group'][grp]['gid'] == ::FB::Users::GID_MAP[grp]['gid'] Chef::Log.debug( "fb_users: Will not bootstrap group #{grp} since it exists, and has " + 'the right GID', ) next end # We may not have this group if it's a remote one, so check we do and # that it's set to create if node['fb_users']['groups'][grp] && node['fb_users']['groups'][grp]['action'] && node['fb_users']['groups'][grp]['action'] != :delete group "bootstrap #{grp}" do # ~FB015 group_name grp gid ::FB::Users::GID_MAP[grp]['gid'] action :create end else Chef::Log.debug( "fb_users: Will not bootstrap group #{grp} since it is marked for " + 'deletion', ) next end end begin data_bag_passwords = data_bag('fb_users_auth') rescue Net::HTTPServerException data_bag_passwords = {} end # Now we can add all the users node['fb_users']['users'].each do |username, info| if info['action'] == :delete user username do # ~FB014 action :remove end next end mapinfo = ::FB::Users::UID_MAP[username] pgroup = info['gid'] || node['fb_users']['user_defaults']['gid'] homedir = info['home'] || "/home/#{username}" # If `manage_homedir` isn't set, we'll use a user-specified default. # If *that* isn't set, then manage_homedir = info['manage_home'] if manage_homedir.nil? if node['fb_users']['user_defaults']['manage_home'] manage_homedir = node['fb_users']['user_defaults']['manage_home'] else manage_homedir = true homebase = ::File.dirname(homedir) if node['filesystem']['by_mountpoint'][homebase] homebase_type = node['filesystem']['by_mountpoint'][homebase]['fs_type'] if homebase_type.start_with?('nfs', 'autofs') manage_homedir = false end end end end pass = mapinfo['password'] if !pass && data_bag_passwords.include?(username) Chef::Log.debug("fb_users[#{username}]: Using password from data_bag") pass = data_bag_item('fb_users_auth', username)['password'] end user username do # ~FB014 uid mapinfo['uid'] # the .to_i here is important - if the usermap accidentally # quotes the gid, then it will try to look up a group named "142" # or whatever. # # We explicityly pass in a GID here instead of a name to ensure that # as GIDs are moving, we get the intended outcome. gid ::FB::Users::GID_MAP[pgroup]['gid'].to_i system mapinfo['system'] if mapinfo['system'] shell info['shell'] || node['fb_users']['user_defaults']['shell'] manage_home manage_homedir home homedir comment mapinfo['comment'] if mapinfo['comment'] password pass if pass action :create end end # and then converge all groups node['fb_users']['groups'].each do |groupname, info| if info['action'] == :delete group groupname do # ~FB015 action :remove end next end # disableing fc009 becasue it triggers on 'comment' below which # is already guarded by a version 'if' group groupname do # ~FC009 ~FB015 gid ::FB::Users::GID_MAP[groupname]['gid'] system info['system'] if info['system'] members info['members'] if info['members'] if FB::Version.new(Chef::VERSION) >= FB::Version.new('14.9') comment info['comment'] if info['comment'] end append false action :create end end end
33.027211
79
0.629042
39b7521d2506f0b4ac380d2219e1e87484b743b4
7,517
require_relative "../errors" require_relative "../extras" require_relative "../file" require "logger" class Train::Plugins::Transport # A Connection instance can be generated and re-generated, given new # connection details such as connection port, hostname, credentials, etc. # This object is responsible for carrying out the actions on the remote # host such as executing commands, transferring files, etc. # # @author Fletcher Nichol <fnichol@nichol.ca> class BaseConnection include Train::Extras # Create a new Connection instance. # # @param options [Hash] connection options # @yield [self] yields itself for block-style invocation def initialize(options = nil) @options = options || {} @logger = @options.delete(:logger) || Logger.new($stdout, level: :fatal) Train::Platforms::Detect::Specifications::OS.load Train::Platforms::Detect::Specifications::Api.load # default caching options @cache_enabled = { file: true, command: false, api_call: false, } @cache = {} @cache_enabled.each_key do |type| clear_cache(type) end end def with_sudo_pty yield end # Returns cached client if caching enabled. Otherwise returns whatever is # given in the block. # # @example # # def demo_client # cached_client(:api_call, :demo_connection) do # DemoClient.new(args) # end # end # # @param [symbol] type one of [:api_call, :file, :command] # @param [symbol] key for your cached connection def cached_client(type, key) return yield unless cache_enabled?(type) @cache[type][key] ||= yield end def cache_enabled?(type) @cache_enabled[type.to_sym] end # Enable caching types for Train. Currently we support # :api_call, :file and :command types def enable_cache(type) raise Train::UnknownCacheType, "#{type} is not a valid cache type" unless @cache_enabled.keys.include?(type.to_sym) @cache_enabled[type.to_sym] = true end def disable_cache(type) raise Train::UnknownCacheType, "#{type} is not a valid cache type" unless @cache_enabled.keys.include?(type.to_sym) @cache_enabled[type.to_sym] = false clear_cache(type.to_sym) end # Closes the session connection, if it is still active. def close # this method may be left unimplemented if that is applicable end def to_json { "files" => Hash[@cache[:file].map { |x, y| [x, y.to_json] }], } end def load_json(j) require_relative "../transports/mock" j["files"].each do |path, jf| @cache[:file][path] = Train::Transports::Mock::Connection::File.from_json(jf) end end def force_platform!(name, platform_details = nil) plat = Train::Platforms.name(name) plat.backend = self plat.platform = platform_details unless platform_details.nil? plat.find_family_hierarchy plat.add_platform_methods plat end def backend_type @options[:backend] || "unknown" end def inspect "%s[%s]" % [self.class, backend_type] end alias direct_platform force_platform! # Get information on the operating system which this transport connects to. # # @return [Platform] system information def platform @platform ||= Train::Platforms::Detect.scan(self) end # we need to keep os as a method for backwards compatibility with inspec alias os platform # This is the main command call for all connections. This will call the private # run_command_via_connection on the connection with optional caching # # This command accepts an optional data handler block. When provided, # inbound data will be published vi `data_handler.call(data)`. This can allow # callers to receive and render updates from remote command execution. # # @param [String] the command to run # @param [Hash] optional hash of options for this command. The derived connection # class's implementation of run_command_via_connection should receive # and apply these options. def run_command(cmd, opts = {}, &data_handler) # Some implementations do not accept an opts argument. # We cannot update all implementations to accept opts due to them being separate plugins. # Therefore here we check the implementation's arity to maintain compatibility. case method(:run_command_via_connection).arity.abs when 1 return run_command_via_connection(cmd, &data_handler) unless cache_enabled?(:command) @cache[:command][cmd] ||= run_command_via_connection(cmd, &data_handler) when 2 return run_command_via_connection(cmd, opts, &data_handler) unless cache_enabled?(:command) @cache[:command][cmd] ||= run_command_via_connection(cmd, opts, &data_handler) else raise NotImplementedError, "#{self.class} does not implement run_command_via_connection with arity #{method(:run_command_via_connection).arity}" end end # This is the main file call for all connections. This will call the private # file_via_connection on the connection with optional caching def file(path, *args) return file_via_connection(path, *args) unless cache_enabled?(:file) @cache[:file][path] ||= file_via_connection(path, *args) end # Builds a LoginCommand which can be used to open an interactive # session on the remote host. # # @return [LoginCommand] array of command line tokens def login_command raise NotImplementedError, "#{self.class} does not implement #login_command()" end # Block and return only when the remote host is prepared and ready to # execute command and upload files. The semantics and details will # vary by implementation, but a round trip through the hosted # service is preferred to simply waiting on a socket to become # available. def wait_until_ready # this method may be left unimplemented if that is applicable log end private # Execute a command using this connection. # # @param command [String] command string to execute # @param &data_handler(data) [Proc] proc that is called when data arrives from # the connection. This block is optional. Individual transports will need # to explicitly invoke the block in their implementation of run_command_via_connection; # if they do not, the block is ignored and will not be used to report data back to the caller. # # @return [CommandResult] contains the result of running the command def run_command_via_connection(_command, &_data_handler) raise NotImplementedError, "#{self.class} does not implement #run_command_via_connection()" end # Interact with files on the target. Read, write, and get metadata # from files via the transport. # # @param [String] path which is being inspected # @return [FileCommon] file object that allows for interaction def file_via_connection(_path, *_args) raise NotImplementedError, "#{self.class} does not implement #file_via_connection(...)" end def clear_cache(type) @cache[type.to_sym] = {} end # @return [Logger] logger for reporting information # @api private attr_reader :logger # @return [Hash] connection options # @api private attr_reader :options end end
34.481651
152
0.683517
386cee61e781b3e510a9d2fa978e2d01e8593202
1,283
require_relative './instructions/array_pop_instruction' require_relative './instructions/array_shift_instruction' require_relative './instructions/const_find_instruction' require_relative './instructions/create_array_instruction' require_relative './instructions/define_block_instruction' require_relative './instructions/define_class_instruction' require_relative './instructions/define_method_instruction' require_relative './instructions/else_instruction' require_relative './instructions/end_instruction' require_relative './instructions/if_instruction' require_relative './instructions/pop_instruction' require_relative './instructions/push_arg_instruction' require_relative './instructions/push_args_instruction' require_relative './instructions/push_argc_instruction' require_relative './instructions/push_int_instruction' require_relative './instructions/push_float_instruction' require_relative './instructions/push_nil_instruction' require_relative './instructions/push_self_instruction' require_relative './instructions/push_string_instruction' require_relative './instructions/push_symbol_instruction' require_relative './instructions/send_instruction' require_relative './instructions/variable_get_instruction' require_relative './instructions/variable_set_instruction'
53.458333
59
0.874513
0170aaf46d2618d2e0db45ae564aafb7ed3e88f6
346
cask "font-carrois-gothic-sc" do version :latest sha256 :no_check url "https://github.com/google/fonts/raw/main/ofl/carroisgothicsc/CarroisGothicSC-Regular.ttf", verified: "github.com/google/fonts/" name "Carrois Gothic SC" homepage "https://fonts.google.com/specimen/Carrois+Gothic+SC" font "CarroisGothicSC-Regular.ttf" end
28.833333
97
0.748555
6a43391496bcf4f1d90de5836d6b450739322289
2,759
# frozen_string_literal: true Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join("tmp", "caching-dev.txt").exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Store uploaded files on the local file system (see config/storage.yml for options) config.active_storage.service = :local # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false # settings for mailcatcher config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: "mailcatcher", port: 1025 } # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = ENV["RAILS_LOG_LEVEL"]&.to_sym || :debug # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = true # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker # Use Resque to manage the ActiveJob queue # config.x.active_job.enabled = true # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = Rails.env # config.active_job.queue_name_delimiter = "." end
35.371795
86
0.76042
6a2267956d32c8737db158e7d5c456c1a1472782
438
desc "Generate the cached bundle/application.js file from app/scripts/*.coffee files" task :bistro_car => :environment do path = "public/javascripts/application.js" puts "Building *.coffee -> #{path}" File.open(path, "w") { |file| file << BistroCar::Bundle.new('default').to_javascript } end file "public/javascripts/application.js" => Dir[File.join(Rails.root, 'app/scripts/*.coffee')] do |t| Rake::Task["bistro_car"].invoke end
43.8
101
0.716895
b9ee556ff632d6d7618b735ad5f1401729df655b
704
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Google module Cloud module Translate module V2 VERSION = "0.2.0".freeze end end end end
28.16
74
0.728693
9196d65ebe42e89a2ed791dbcd076cf627e0e4e5
2,834
module Popolo # A real person, alive or dead. class Person include Mongoid::Document include Mongoid::Timestamps store_in Popolo.storage_options_per_class.fetch(:Person, Popolo.storage_options) # The person's memberships. has_many :memberships, class_name: 'Popolo::Membership', dependent: :destroy # The person's motions. has_many :motions, class_name: 'Popolo::Motion' # The person's votes. has_many :votes, as: :voter, class_name: 'Popolo::Vote' # Alternate or former names. embeds_many :other_names, as: :nameable, class_name: 'Popolo::OtherName' # Issued identifiers. embeds_many :identifiers, as: :identifiable, class_name: 'Popolo::Identifier' # Means of contacting the person. embeds_many :contact_details, as: :contactable, class_name: 'Popolo::ContactDetail' # URLs to documents about the person embeds_many :links, as: :linkable, class_name: 'Popolo::Link' # URLs to documents from which the person is derived. embeds_many :sources, as: :linkable, class_name: 'Popolo::Link' # A person's preferred full name. field :name, type: String # One or more family names. field :family_name, type: String # One or more primary given names. field :given_name, type: String # One or more secondary given names. field :additional_name, type: String # One or more honorifics preceding a person's name. field :honorific_prefix, type: String # One or more honorifics following a person's name. field :honorific_suffix, type: String # One or more patronymic names. field :patronymic_name, type: String # A name to use in an lexicographically ordered list. field :sort_name, type: String # A preferred email address. field :email, type: String # A gender. field :gender, type: String # A date of birth. field :birth_date, type: DateString # A date of death. field :death_date, type: DateString # A URL of a head shot. field :image, type: String # A one-line account of a person's life. field :summary, type: String # An extended account of a person's life. field :biography, type: String # A national identity. field :national_identity, type: String validates_format_of :birth_date, with: DATE_STRING_FORMAT, allow_blank: true validates_format_of :death_date, with: DATE_STRING_FORMAT, allow_blank: true # @note Add email address validation and URL validation to match JSON Schema? def to_s if name.blank? if given_name.present? && family_name.present? "#{given_name} #{family_name}" elsif given_name.present? given_name elsif family_name.present? family_name else name end else name end end end end
35.873418
87
0.684545
d5d6ca2df7d603b4500080d057d76ac60c6ac7e7
59
module ULID module Rails VERSION = "0.5.0" end end
9.833333
21
0.627119
5daa0295b54807a513adc725e27d0163cdf70b33
263
module OpenActive module Models module Schema class TakeAction < ::OpenActive::Models::Schema::TransferAction # @!attribute type # @return [String] def type "schema:TakeAction" end end end end end
18.785714
69
0.585551
f8d7fec7e45874daa033e4e8b1aa06f4977fb20f
4,098
## # $Id$ ## ## # This file is part of the Metasploit Framework and may be subject to # redistribution and commercial restrictions. Please see the Metasploit # Framework web site for more information on licensing and terms of use. # http://metasploit.com/framework/ ## require 'msf/core' class Metasploit3 < Msf::Auxiliary include Msf::Exploit::Remote::HttpClient include Msf::Auxiliary::Scanner def initialize super( 'Name' => 'Adobe XML External Entity Injection', 'Version' => '$Revision$', 'Description' => %q{ Multiple Adobe Products -- XML External Entity Injection. Affected Sofware: BlazeDS 3.2 and earlier versions, LiveCycle 9.0, 8.2.1, and 8.0.1, LiveCycle Data Services 3.0, 2.6.1, and 2.5.1, Flex Data Services 2.0.1, ColdFusion 9.0, 8.0.1, 8.0, and 7.0.2 }, 'References' => [ [ 'CVE', '2009-3960' ], [ 'OSVDB', '62292' ], [ 'BID', '38197' ], [ 'URL', 'http://www.security-assessment.com/files/advisories/2010-02-22_Multiple_Adobe_Products-XML_External_Entity_and_XML_Injection.pdf' ], [ 'URL', 'http://www.adobe.com/support/security/bulletins/apsb10-05.html'], ], 'Author' => [ 'CG' ], 'License' => MSF_LICENSE ) register_options( [ Opt::RPORT(8400), OptString.new('FILE', [ true, "File to read", '/etc/passwd']), ],self.class) end def run_host(ip) path = [ "/flex2gateway/", "/flex2gateway/http", # ColdFusion 9 (disabled by default), works on some CF 8 though :-) "/flex2gateway/httpsecure", # ColdFusion 9 (disabled by default) SSL "/flex2gateway/cfamfpolling", "/flex2gateway/amf", "/flex2gateway/amfpolling", "/messagebroker/http", "/messagebroker/httpsecure", #SSL "/blazeds/messagebroker/http", # Blazeds 3.2 "/blazeds/messagebroker/httpsecure", #SSL "/samples/messagebroker/http", # Blazeds 3.2 "/samples/messagebroker/httpsecure", # Blazeds 3.2 SSL "/lcds/messagebroker/http", # LCDS "/lcds/messagebroker/httpsecure", # LCDS -- SSL "/lcds-samples/messagebroker/http", # LCDS "/lcds-samples/messagebroker/httpsecure", # LCDS -- SSL ] postrequest = "<\?xml version=\"1.0\" encoding=\"utf-8\"\?>" postrequest << "<\!DOCTYPE test [ <\!ENTITY x3 SYSTEM \"#{datastore['FILE']}\"> ]>" postrequest << "<amfx ver=\"3\" xmlns=\"http://www.macromedia.com/2005/amfx\">" postrequest << "<body><object type=\"flex.messaging.messages.CommandMessage\"><traits>" postrequest << "<string>body</string><string>clientId</string><string>correlationId</string><string>destination</string>" postrequest << "<string>headers</string><string>messageId</string><string>operation</string><string>timestamp</string>" postrequest << "<string>timeToLive</string></traits><object><traits /></object><null /><string /><string /><object>" postrequest << "<traits><string>DSId</string><string>DSMessagingVersion</string></traits><string>nil</string>" postrequest << "<int>1</int></object><string>&x3;</string><int>5</int><int>0</int><int>0</int></object></body></amfx>" path.each do | check | res = send_request_cgi({ 'uri' => check, 'method' => 'POST', 'version' => '1.1', 'Content-Type' => 'application/x-amf', 'data' => postrequest }, 25) if (res.nil?) print_error("no response for #{ip}:#{rport} #{check}") elsif (res.code == 200 and res.body =~ /\<\?xml version\="1.0" encoding="utf-8"\?\>/) print_status("#{rhost}:#{rport} #{check} #{res.code}\n #{res.body}") elsif (res and res.code == 302 or res.code == 301) print_status(" Received 302 to #{res.headers['Location']} for #{check}") else print_error("#{res.code} for #{check}") #'' end end rescue ::Rex::ConnectionRefused, ::Rex::HostUnreachable, ::Rex::ConnectionTimeout, Rex::ConnectionError =>e print_error(e.message) rescue Timeout::Error, Errno::EINVAL, Errno::ECONNRESET, EOFError, Errno::ECONNABORTED, Errno::ECONNREFUSED, Errno::EHOSTUNREACH =>e print_error(e.message) end end #set FILE /proc/sys/kernel/osrelease #set FILE /proc/sys/kernel/hostname
38.299065
147
0.65349
4a735cc9505cdbb9a1e742fe470f2af09fff057b
2,803
module Hookit module Resource class Service < Base field :recursive field :service_name field :init field :timeout actions :enable, :disable, :start, :stop, :force_stop, :restart, :reload default_action :enable def initialize(name) service_name(name) unless service_name super # if init scheme is not provided, try to set reasonable defaults if not init case platform.name when 'smartos' init(:smf) when 'ubuntu' init(:upstart) when 'docker' init(:runit) end end end def run(action) case action when :enable enable! when :disable disable! when :start enable! when :stop disable! when :force_stop force_disable! when :restart restart! when :reload reload! end end protected def enable! case init when :smf run_command! "svcadm enable -s #{"-r" if recursive} #{service_name}" when :runit # register and potentially start the service run_command! "sv #{"-w #{timeout}" if timeout} start #{service_name}", false # runit can take up to 5 seconds to register the service before the # service starts to run. We'll keep checking the status for up to # 6 seconds, after which time we'll raise an exception. registered = false 6.times do # check the status `sv status #{service_name}` if $?.exitstatus == 0 registered = true break end sleep 1 end if registered # just in case the service is registered but not started, try # to start the service one more time run_command! "sv #{"-w #{timeout}" if timeout} start #{service_name}" end end end def disable! case init when :smf run_command! "svcadm disable -s #{service_name}" when :runit run_command! "sv #{"-w #{timeout}" if timeout} stop #{service_name}" end end def force_disable! case init when :runit run_command! "sv #{"-w #{timeout}" if timeout} force-stop #{service_name}" end end def restart! case init when :smf run_command! "svcadm restart #{service_name}" when :runit disable!; enable! end end def reload! case init when :smf run_command! "svcadm refresh #{service_name}" end end end end end
23.754237
86
0.522298
1cbf603b071ddb2303dbecc71f79ca3b358bc28a
1,925
class Np2 < Formula desc "Neko Project 2: PC-9801 emulator" homepage "https://www.yui.ne.jp/np2/" url "https://amethyst.yui.ne.jp/svn/pc98/np2/tags/VER_0_86/", :using => :svn, :revision => "2606" head "https://amethyst.yui.ne.jp/svn/pc98/np2/trunk/", :using => :svn bottle do cellar :any sha256 "0d341c9c1da3caccb8c2746e876b578fcdda626cc7d6fe3c071b2a10a2216cb4" => :high_sierra sha256 "18f54de6cd5a7b913c9be1af8494cce362d52f94c751c63da9beffcd4f3fc41c" => :sierra sha256 "969d59ab9401163f14b9c5830f884f0ff9f4d25f81985472f6a41b5b4debcbff" => :el_capitan sha256 "a7340b1deadb9fdb4e117b9d793e695631d7d9a52ae111703e9bc6ea796c290b" => :yosemite end depends_on :xcode => :build if OS.mac? depends_on "sdl2" depends_on "sdl2_ttf" def install sdl2 = Formula["sdl2"] sdl2_ttf = Formula["sdl2_ttf"] cd "sdl2/MacOSX" do # Use brewed library paths inreplace "np2sdl2.xcodeproj/project.pbxproj" do |s| s.gsub! "BAF84E4B195AA35E00183062", "//BAF84E4B195AA35E00183062" s.gsub! "HEADER_SEARCH_PATHS = (", "LIBRARY_SEARCH_PATHS = (\"$(inherited)\", #{sdl2.lib}, #{sdl2_ttf.lib}); " \ "HEADER_SEARCH_PATHS = (#{sdl2.include}/SDL2, #{sdl2.include}, #{sdl2_ttf.include}," s.gsub! "buildSettings = {", 'buildSettings ={ OTHER_LDFLAGS = "-lSDL2 -lSDL2_ttf";' end # Force to use Japanese TTF font inreplace "np2sdl2/compiler.h", "#define RESOURCE_US", "" # Always use current working directory inreplace "np2sdl2/main.m", "[pstrBundlePath UTF8String]", '"./"' xcodebuild "SYMROOT=build" bin.install "build/Release/np2sdl2.app/Contents/MacOS/np2sdl2" => "np2" end end def caveats; <<~EOS A Japanese TTF file named `default.ttf` should be in the working directory. EOS end test do assert_match %r{Usage: #{bin}/np2}, shell_output("#{bin}/np2 -h", 1) end end
37.745098
100
0.68
5dc78ee299cd1bd79715916b4bad43dba7be76d6
2,630
#-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2020 the OpenProject GmbH # # 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 docs/COPYRIGHT.rdoc for more details. #++ class Widget::Table < Widget::Base extend Report::InheritedAttribute include ReportingHelper attr_accessor :debug attr_accessor :fields attr_accessor :mapping def initialize(query) raise ArgumentError, 'Tables only work on Reports!' unless query.is_a? Report super end def resolve_table if @subject.group_bys.size == 0 self.class.detailed_table elsif @subject.group_bys.size == 1 self.class.simple_table else self.class.fancy_table end end def self.detailed_table(klass = nil) @@detail_table = klass if klass defined?(@@detail_table) ? @@detail_table : fancy_table end def self.simple_table(klass = nil) @@simple_table = klass if klass defined?(@@simple_table) ? @@simple_table : fancy_table end def self.fancy_table(klass = nil) @@fancy_table = klass if klass @@fancy_table end fancy_table Widget::Table::ReportTable def render write('<!-- table start -->') if @subject.result.count <= 0 write(content_tag(:div, '', class: 'generic-table--no-results-container') do content_tag(:i, '', class: 'icon-info1') + content_tag(:h2, I18n.t(:no_results_title_text), class: 'generic-table--no-results-title') end) else str = render_widget(resolve_table, @subject, @options.reverse_merge(to: @output)) @cache_output.write(str.html_safe) if @cache_output end end end
32.469136
100
0.720152
035c72a58460036c7226a7a0be7e43ee4ec30bf0
69
require "ruboty-songinfo/version" require "ruboty/handlers/songinfo"
23
34
0.826087
f80fdfe55d7e427baa2ca2ce372e74fbb44f1050
2,059
require 'spec_helper' describe 'SynchronousHttpRequester' do describe '#retrieve_content' do let(:get_request) { double('HTTP::Get') } let(:http_session) { double('Net::HTTP', request: response) } let(:url) { 'http://host/path.html?parameter=value' } let(:response) { double('HTTPResponse', code: '200', body: 'response body', header: {}) } let(:net_http_builder) { double(:net_http_builder, build: http_session) } before do allow(Net::HTTP::Get).to receive(:new).with('/path.html?parameter=value').and_return(get_request) end subject { SynchronousHttpRequester.new(net_http_builder) } context 'when the response status code is in the 200s' do it 'returns the response body' do expect(subject.retrieve_content(url)).to eq('response body') end end context 'when the response status code is in the 300s' do let(:new_location) { 'http://redirect/to/here' } let(:response) { double('HTTPResponse', body: nil, header: {'location' => new_location}, code: (rand 300..399).to_s) } let(:redirected_get_request) { double(:redirected_get_request) } it 'should follow the redirect' do allow(Net::HTTP::Get).to receive(:new).with('/to/here?').and_return(redirected_get_request) expect(net_http_builder).to receive(:build).with(URI.parse(new_location)). and_return(session_that_responds_with("hello, is it me you're looking for?")) expect(subject.retrieve_content(url)).to eq("hello, is it me you're looking for?") end end context 'when the response status code is in the 400s to 500s' do let(:response) { double('HTTPResponse', body: 'response body', code: (rand 400..599).to_s) } it 'returns a helpful error' do expect { subject.retrieve_content(url) }.to raise_error(Net::HTTPError) end end end def session_that_responds_with(response_body) response = double(:response, code: '200', body: response_body, header: {}) double(:net_http_session, request: response) end end
39.596154
124
0.67897
3375a5952aa2cba1bf868863a97dd661090356da
3,022
#-------------------------------------------------------------------- # # Author: Martin Corino # # This program is free software; you can redistribute it and/or # modify it under the terms of the R2CORBA LICENSE which is # included with this program. # # Copyright (c) Remedy IT Expertise BV #-------------------------------------------------------------------- require 'optparse' require 'lib/assert.rb' include TestUtil::Assertions OPTIONS = { :use_implement => false, :orb_debuglevel => 0, :iorfile => 'file://server.ior' } ARGV.options do |opts| script_name = File.basename($0) opts.banner = "Usage: ruby #{script_name} [options]" opts.separator '' opts.on('--k IORFILE', 'Set IOR.', "Default: 'file://server.ior'") { |v| OPTIONS[:iorfile] = v } opts.on('--d LVL', 'Set ORBDebugLevel value.', 'Default: 0') { |v| OPTIONS[:orb_debuglevel] = v } opts.on('--use-implement', 'Load IDL through CORBA.implement() instead of precompiled code.', 'Default: off') { |v| OPTIONS[:use_implement] = v } opts.separator '' opts.on('-h', '--help', 'Show this help message.') { puts opts; exit } opts.parse! end require 'corba' orb = CORBA.ORB_init(['-ORBDebugLevel', OPTIONS[:orb_debuglevel]], 'myORB') begin obj = orb.string_to_object(OPTIONS[:iorfile]) puts '***** Synchronous twoway DII' req = obj._request('echo') req.arguments = [ ['method', CORBA::ARG_IN, CORBA::_tc_string, 'sync twoway'], ['message', CORBA::ARG_IN, CORBA::_tc_string, 'Hello world!'] ] req.set_return_type(CORBA::_tc_string) the_string = req.invoke() puts "string returned <#{the_string}>" puts puts '***** Deferred twoway DII (using get_response())' req = obj._request('echo') req.arguments = [ ['method', CORBA::ARG_IN, CORBA::_tc_string, 'deferred twoway (1)'], ['message', CORBA::ARG_IN, CORBA::_tc_string, 'Hello world!'] ] req.set_return_type(CORBA::_tc_string) req.send_deferred() puts 'getting response...' req.get_response() puts "string returned <#{req.return_value}>" puts ### DOESN'T WORK WITH TAO <= 1.5.9 BECAUSE OF BUG IN TAO if !defined?(TAO) || TAO::MAJOR_VERSION > 1 || (TAO::MAJOR_VERSION == 1 && (TAO::MINOR_VERSION > 5 || (TAO::MINOR_VERSION == 5 && TAO::MICRO_VERSION > 9))) puts '***** Deferred twoway DII (using poll_response())' req = obj._request('echo') req.arguments = [ ['method', CORBA::ARG_IN, CORBA::_tc_string, 'deferred twoway (2)'], ['message', CORBA::ARG_IN, CORBA::_tc_string, 'Hello world!'] ] req.set_return_type(CORBA::_tc_string) req.send_deferred() begin puts 'sleeping...' sleep(0.01) puts 'polling for response...' end while !req.poll_response() puts "string returned <#{req.return_value}>" puts end puts '***** Oneway shutdown' req = obj._request('shutdown') req.send_oneway() ensure orb.destroy() end
26.278261
78
0.59497
21773ec9bc5d9007cbc9de880d0cf817505ea8e7
18,639
# frozen_string_literal: true # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! require "google/cloud/errors" require "google/cloud/binaryauthorization/v1beta1/service_pb" module Google module Cloud module BinaryAuthorization module V1beta1 module SystemPolicy ## # Client for the SystemPolicy service. # # API for working with the system policy. # class Client include Paths # @private attr_reader :system_policy_stub ## # Configure the SystemPolicy Client class. # # See {::Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicy::Client::Configuration} # for a description of the configuration fields. # # @example # # # Modify the configuration for all SystemPolicy clients # ::Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicy::Client.configure do |config| # config.timeout = 10.0 # end # # @yield [config] Configure the Client client. # @yieldparam config [Client::Configuration] # # @return [Client::Configuration] # def self.configure @configure ||= begin namespace = ["Google", "Cloud", "BinaryAuthorization", "V1beta1"] parent_config = while namespace.any? parent_name = namespace.join "::" parent_const = const_get parent_name break parent_const.configure if parent_const.respond_to? :configure namespace.pop end default_config = Client::Configuration.new parent_config default_config end yield @configure if block_given? @configure end ## # Configure the SystemPolicy Client instance. # # The configuration is set to the derived mode, meaning that values can be changed, # but structural changes (adding new fields, etc.) are not allowed. Structural changes # should be made on {Client.configure}. # # See {::Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicy::Client::Configuration} # for a description of the configuration fields. # # @yield [config] Configure the Client client. # @yieldparam config [Client::Configuration] # # @return [Client::Configuration] # def configure yield @config if block_given? @config end ## # Create a new SystemPolicy client object. # # @example # # # Create a client using the default configuration # client = ::Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicy::Client.new # # # Create a client using a custom configuration # client = ::Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicy::Client.new do |config| # config.timeout = 10.0 # end # # @yield [config] Configure the SystemPolicy client. # @yieldparam config [Client::Configuration] # def initialize # These require statements are intentionally placed here to initialize # the gRPC module only when it's required. # See https://github.com/googleapis/toolkit/issues/446 require "gapic/grpc" require "google/cloud/binaryauthorization/v1beta1/service_services_pb" # Create the configuration object @config = Configuration.new Client.configure # Yield the configuration if needed yield @config if block_given? # Create credentials credentials = @config.credentials # Use self-signed JWT if the endpoint is unchanged from default, # but only if the default endpoint does not have a region prefix. enable_self_signed_jwt = @config.endpoint == Client.configure.endpoint && !@config.endpoint.split(".").first.include?("-") credentials ||= Credentials.default scope: @config.scope, enable_self_signed_jwt: enable_self_signed_jwt if credentials.is_a?(::String) || credentials.is_a?(::Hash) credentials = Credentials.new credentials, scope: @config.scope end @quota_project_id = @config.quota_project @quota_project_id ||= credentials.quota_project_id if credentials.respond_to? :quota_project_id @system_policy_stub = ::Gapic::ServiceStub.new( ::Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicyV1Beta1::Stub, credentials: credentials, endpoint: @config.endpoint, channel_args: @config.channel_args, interceptors: @config.interceptors ) end # Service calls ## # Gets the current system policy in the specified location. # # @overload get_system_policy(request, options = nil) # Pass arguments to `get_system_policy` via a request object, either of type # {::Google::Cloud::BinaryAuthorization::V1beta1::GetSystemPolicyRequest} or an equivalent Hash. # # @param request [::Google::Cloud::BinaryAuthorization::V1beta1::GetSystemPolicyRequest, ::Hash] # A request object representing the call parameters. Required. To specify no # parameters, or to keep all the default parameter values, pass an empty Hash. # @param options [::Gapic::CallOptions, ::Hash] # Overrides the default settings for this call, e.g, timeout, retries, etc. Optional. # # @overload get_system_policy(name: nil) # Pass arguments to `get_system_policy` via keyword arguments. Note that at # least one keyword argument is required. To specify no parameters, or to keep all # the default parameter values, pass an empty Hash as a request object (see above). # # @param name [::String] # Required. The resource name, in the format `locations/*/policy`. # Note that the system policy is not associated with a project. # # @yield [response, operation] Access the result along with the RPC operation # @yieldparam response [::Google::Cloud::BinaryAuthorization::V1beta1::Policy] # @yieldparam operation [::GRPC::ActiveCall::Operation] # # @return [::Google::Cloud::BinaryAuthorization::V1beta1::Policy] # # @raise [::Google::Cloud::Error] if the RPC is aborted. # # @example Basic example # require "google/cloud/binary_authorization/v1beta1" # # # Create a client object. The client can be reused for multiple calls. # client = Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicy::Client.new # # # Create a request. To set request fields, pass in keyword arguments. # request = Google::Cloud::BinaryAuthorization::V1beta1::GetSystemPolicyRequest.new # # # Call the get_system_policy method. # result = client.get_system_policy request # # # The returned object is of type Google::Cloud::BinaryAuthorization::V1beta1::Policy. # p result # def get_system_policy request, options = nil raise ::ArgumentError, "request must be provided" if request.nil? request = ::Gapic::Protobuf.coerce request, to: ::Google::Cloud::BinaryAuthorization::V1beta1::GetSystemPolicyRequest # Converts hash and nil to an options object options = ::Gapic::CallOptions.new(**options.to_h) if options.respond_to? :to_h # Customize the options with defaults metadata = @config.rpcs.get_system_policy.metadata.to_h # Set x-goog-api-client and x-goog-user-project headers metadata[:"x-goog-api-client"] ||= ::Gapic::Headers.x_goog_api_client \ lib_name: @config.lib_name, lib_version: @config.lib_version, gapic_version: ::Google::Cloud::BinaryAuthorization::V1beta1::VERSION metadata[:"x-goog-user-project"] = @quota_project_id if @quota_project_id header_params = {} if request.name header_params["name"] = request.name end request_params_header = header_params.map { |k, v| "#{k}=#{v}" }.join("&") metadata[:"x-goog-request-params"] ||= request_params_header options.apply_defaults timeout: @config.rpcs.get_system_policy.timeout, metadata: metadata, retry_policy: @config.rpcs.get_system_policy.retry_policy options.apply_defaults timeout: @config.timeout, metadata: @config.metadata, retry_policy: @config.retry_policy @system_policy_stub.call_rpc :get_system_policy, request, options: options do |response, operation| yield response, operation if block_given? return response end rescue ::GRPC::BadStatus => e raise ::Google::Cloud::Error.from_error(e) end ## # Configuration class for the SystemPolicy API. # # This class represents the configuration for SystemPolicy, # providing control over timeouts, retry behavior, logging, transport # parameters, and other low-level controls. Certain parameters can also be # applied individually to specific RPCs. See # {::Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicy::Client::Configuration::Rpcs} # for a list of RPCs that can be configured independently. # # Configuration can be applied globally to all clients, or to a single client # on construction. # # @example # # # Modify the global config, setting the timeout for # # get_system_policy to 20 seconds, # # and all remaining timeouts to 10 seconds. # ::Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicy::Client.configure do |config| # config.timeout = 10.0 # config.rpcs.get_system_policy.timeout = 20.0 # end # # # Apply the above configuration only to a new client. # client = ::Google::Cloud::BinaryAuthorization::V1beta1::SystemPolicy::Client.new do |config| # config.timeout = 10.0 # config.rpcs.get_system_policy.timeout = 20.0 # end # # @!attribute [rw] endpoint # The hostname or hostname:port of the service endpoint. # Defaults to `"binaryauthorization.googleapis.com"`. # @return [::String] # @!attribute [rw] credentials # Credentials to send with calls. You may provide any of the following types: # * (`String`) The path to a service account key file in JSON format # * (`Hash`) A service account key as a Hash # * (`Google::Auth::Credentials`) A googleauth credentials object # (see the [googleauth docs](https://googleapis.dev/ruby/googleauth/latest/index.html)) # * (`Signet::OAuth2::Client`) A signet oauth2 client object # (see the [signet docs](https://googleapis.dev/ruby/signet/latest/Signet/OAuth2/Client.html)) # * (`GRPC::Core::Channel`) a gRPC channel with included credentials # * (`GRPC::Core::ChannelCredentials`) a gRPC credentails object # * (`nil`) indicating no credentials # @return [::Object] # @!attribute [rw] scope # The OAuth scopes # @return [::Array<::String>] # @!attribute [rw] lib_name # The library name as recorded in instrumentation and logging # @return [::String] # @!attribute [rw] lib_version # The library version as recorded in instrumentation and logging # @return [::String] # @!attribute [rw] channel_args # Extra parameters passed to the gRPC channel. Note: this is ignored if a # `GRPC::Core::Channel` object is provided as the credential. # @return [::Hash] # @!attribute [rw] interceptors # An array of interceptors that are run before calls are executed. # @return [::Array<::GRPC::ClientInterceptor>] # @!attribute [rw] timeout # The call timeout in seconds. # @return [::Numeric] # @!attribute [rw] metadata # Additional gRPC headers to be sent with the call. # @return [::Hash{::Symbol=>::String}] # @!attribute [rw] retry_policy # The retry policy. The value is a hash with the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # @return [::Hash] # @!attribute [rw] quota_project # A separate project against which to charge quota. # @return [::String] # class Configuration extend ::Gapic::Config config_attr :endpoint, "binaryauthorization.googleapis.com", ::String config_attr :credentials, nil do |value| allowed = [::String, ::Hash, ::Proc, ::Symbol, ::Google::Auth::Credentials, ::Signet::OAuth2::Client, nil] allowed += [::GRPC::Core::Channel, ::GRPC::Core::ChannelCredentials] if defined? ::GRPC allowed.any? { |klass| klass === value } end config_attr :scope, nil, ::String, ::Array, nil config_attr :lib_name, nil, ::String, nil config_attr :lib_version, nil, ::String, nil config_attr(:channel_args, { "grpc.service_config_disable_resolution" => 1 }, ::Hash, nil) config_attr :interceptors, nil, ::Array, nil config_attr :timeout, nil, ::Numeric, nil config_attr :metadata, nil, ::Hash, nil config_attr :retry_policy, nil, ::Hash, ::Proc, nil config_attr :quota_project, nil, ::String, nil # @private def initialize parent_config = nil @parent_config = parent_config unless parent_config.nil? yield self if block_given? end ## # Configurations for individual RPCs # @return [Rpcs] # def rpcs @rpcs ||= begin parent_rpcs = nil parent_rpcs = @parent_config.rpcs if defined?(@parent_config) && @parent_config.respond_to?(:rpcs) Rpcs.new parent_rpcs end end ## # Configuration RPC class for the SystemPolicy API. # # Includes fields providing the configuration for each RPC in this service. # Each configuration object is of type `Gapic::Config::Method` and includes # the following configuration fields: # # * `timeout` (*type:* `Numeric`) - The call timeout in seconds # * `metadata` (*type:* `Hash{Symbol=>String}`) - Additional gRPC headers # * `retry_policy (*type:* `Hash`) - The retry policy. The policy fields # include the following keys: # * `:initial_delay` (*type:* `Numeric`) - The initial delay in seconds. # * `:max_delay` (*type:* `Numeric`) - The max delay in seconds. # * `:multiplier` (*type:* `Numeric`) - The incremental backoff multiplier. # * `:retry_codes` (*type:* `Array<String>`) - The error codes that should # trigger a retry. # class Rpcs ## # RPC-specific configuration for `get_system_policy` # @return [::Gapic::Config::Method] # attr_reader :get_system_policy # @private def initialize parent_rpcs = nil get_system_policy_config = parent_rpcs.get_system_policy if parent_rpcs.respond_to? :get_system_policy @get_system_policy = ::Gapic::Config::Method.new get_system_policy_config yield self if block_given? end end end end end end end end end
47.915167
131
0.557272
3916245d7d710476e68f64c4a38933a63e3f3348
494
require 'serverspec' require 'net/ssh' set :backend, :ssh set :disable_sudo, true options = Net::SSH::Config.for(host) options[:user] = 'root' set :host, options[:host_name] || ENV['TARGET_HOST'] set :ssh_options, options describe 'Packages are installed.' do apache = host_inventory['platform'] == 'ubuntu' ? 'apache2' : 'httpd' %W[#{apache} mariadb php].each do |the_package| describe package(the_package) do it { expect(subject).to be_installed } end end end
22.454545
71
0.682186
abc531413ddacacff3f8cfc3b124f8621a019913
1,706
$LOAD_PATH.push( File.join( File.dirname(__FILE__), '..', '..', '..', 'fixtures', 'modules', 'inifile', 'lib') ) $LOAD_PATH.push( File.join( File.dirname(__FILE__), '..', '..', '..', 'fixtures', 'modules', 'openstacklib', 'lib') ) require 'spec_helper' provider_class = Puppet::Type.type(:cinder_api_uwsgi_config).provider(:ini_setting) describe provider_class do it 'should default to the default setting when no other one is specified' do resource = Puppet::Type::Cinder_api_uwsgi_config.new( {:name => 'DEFAULT/foo', :value => 'bar'} ) provider = provider_class.new(resource) expect(provider.section).to eq('DEFAULT') expect(provider.setting).to eq('foo') end it 'should allow setting to be set explicitly' do resource = Puppet::Type::Cinder_api_uwsgi_config.new( {:name => 'dude/foo', :value => 'bar'} ) provider = provider_class.new(resource) expect(provider.section).to eq('dude') expect(provider.setting).to eq('foo') end it 'should ensure absent when <SERVICE DEFAULT> is specified as a value' do resource = Puppet::Type::Cinder_api_uwsgi_config.new( {:name => 'dude/foo', :value => '<SERVICE DEFAULT>'} ) provider = provider_class.new(resource) provider.exists? expect(resource[:ensure]).to eq :absent end it 'should ensure absent when value matches ensure_absent_val' do resource = Puppet::Type::Cinder_api_uwsgi_config.new( {:name => 'dude/foo', :value => 'foo', :ensure_absent_val => 'foo' } ) provider = provider_class.new(resource) provider.exists? expect(resource[:ensure]).to eq :absent end end
25.848485
83
0.644197
0113075152d99af8e0baba56f18b693ebeb58259
154
class NewsController < ApplicationController def show @news = News.find_by(slug: params[:slug]) redirect_to root_path if @news.blank? end end
22
45
0.733766
87eedb5f5aafbb86f9df104b17bdb6added830f6
382
require 'test_helper' class RepositoryTest < ActiveSupport::TestCase [ ['admin', true], ['active', false], ].each do |user, can_edit| test "#{user} can edit attributes #{can_edit}" do use_token user attrs = Repository.new.editable_attributes if can_edit refute_empty attrs else assert_empty attrs end end end end
20.105263
53
0.63089
ff0b6bbedd7a24eb9f6427bbf0b4576cb35875af
363
module Mailclerk class MailclerkError < StandardError end class MailclerkAPIError < MailclerkError attr_accessor :http_status attr_accessor :http_response def initialize(description, http_status=nil, http_response=nil) super(description) self.http_status = http_status self.http_response = http_response end end end
24.2
67
0.746556
03b943b1080f4224035447b4077652b4e687f7a0
466
require_relative 'bible' require 'abbrev' class ActsAsScriptural::AbbreviationLookup def initialize @hash = bible.book_names.abbrev.map{|k,v| [k.gsub(' ','').downcase,v]}.to_h end def fullname(str) @hash[str.gsub(' ','').downcase] end def index_number(str) bible.namehash[fullname(str)].index end def bible @bible || ActsAsScriptural::Bible.new end def abbreviation_to_book(str) bible.namehash[fullname(str)] end end
16.642857
79
0.684549
b9796f160a3763564b535a335ca92b16d0077cde
1,201
# encoding: utf-8 # author: Mesaguy describe file('/opt/prometheus/exporters/wireguard_exporter_mdlayher/active') do it { should be_symlink } its('mode') { should cmp '0755' } its('owner') { should eq 'root' } its('group') { should eq 'prometheus' } end describe file('/opt/prometheus/exporters/wireguard_exporter_mdlayher/active/wireguard_exporter') do it { should be_file } it { should be_executable } its('mode') { should cmp '0755' } its('owner') { should eq 'root' } its('group') { should eq 'prometheus' } end describe service('wireguard_exporter_mdlayher') do it { should be_enabled } it { should be_installed } it { should be_running } end describe processes(Regexp.new("^/opt/prometheus/exporters/wireguard_exporter_mdlayher/(v)?([0-9a-f]{40}__go-[0-9.]+|[0-9.]+|[0-9.]+__go-[0-9.]+)/wireguard_exporter")) do it { should exist } its('entries.length') { should eq 1 } its('users') { should include 'prometheus' } end describe port(9586) do it { should be_listening } end describe http('http://127.0.0.1:9586/metrics') do its('status') { should cmp 200 } its('body') { should match /process_cpu_seconds_total/ } end
30.794872
169
0.673605
e2e5e9db36ab86860eb85ef9a759929d6f43f8cb
5,210
# $Id$ # # Meterpreter script for setting up a route from within a # Meterpreter session, without having to background the # current session. # Default options session = client subnet = nil netmask = "255.255.255.0" print_only = false remove_route = false remove_all_routes = false # Options parsing @@exec_opts = Rex::Parser::Arguments.new( "-h" => [false, "Help and usage"], "-s" => [true, "Subnet (IPv4, for example, 10.10.10.0)"], "-n" => [true, "Netmask (IPv4, for example, 255.255.255.0"], "-p" => [false, "Print active routing table. All other options are ignored"], "-d" => [false, "Delete the named route instead of adding it"], "-D" => [false, "Delete all routes (does not require a subnet)"] ) @@exec_opts.parse(args) { |opt, idx, val| v = val.to_s.strip case opt when "-h" usage raise Rex::Script::Completed when "-s" if v =~ /[0-9\x2e]+\x2f[0-9]{1,2}/ subnet,cidr = v.split("\x2f") netmask = Rex::Socket.addr_ctoa(cidr.to_i) else subnet = v end when "-n" if (0..32) === v.to_i netmask = Rex::Socket.addr_ctoa(v.to_i) else netmask = v end when "-p" print_only = true when "-d" remove_route = true when "-D" remove_all_routes = true end } def delete_all_routes if Rex::Socket::SwitchBoard.routes.size > 0 routes = [] Rex::Socket::SwitchBoard.each do |route| routes << {:subnet => route.subnet, :netmask => route.netmask} end routes.each {|route_opts| delete_route(route_opts)} print_status "Deleted all routes" else print_status "No routes have been added yet" end raise Rex::Script::Completed end # Identical functionality to command_dispatcher/core.rb, and # nearly identical code def print_routes if Rex::Socket::SwitchBoard.routes.size > 0 tbl = Msf::Ui::Console::Table.new( Msf::Ui::Console::Table::Style::Default, 'Header' => "Active Routing Table", 'Prefix' => "\n", 'Postfix' => "\n", 'Columns' => [ 'Subnet', 'Netmask', 'Gateway', ], 'ColProps' => { 'Subnet' => { 'MaxWidth' => 17 }, 'Netmask' => { 'MaxWidth' => 17 }, }) ret = [] Rex::Socket::SwitchBoard.each { |route| if (route.comm.kind_of?(Msf::Session)) gw = "Session #{route.comm.sid}" else gw = route.comm.name.split(/::/)[-1] end tbl << [ route.subnet, route.netmask, gw ] } print tbl.to_s else print_status "No routes have been added yet" end raise Rex::Script::Completed end # Yet another IP validator. I'm sure there's some Rex # function that can just do this. def check_ip(ip=nil) return false if(ip.nil? || ip.strip.empty?) begin rw = Rex::Socket::RangeWalker.new(ip.strip) (rw.valid? && rw.length == 1) ? true : false rescue false end end # Adds a route to the framework instance def add_route(opts={}) subnet = opts[:subnet] netmask = opts[:netmask] || "255.255.255.0" # Default class C Rex::Socket::SwitchBoard.add_route(subnet, netmask, session) end # Removes a route to the framework instance def delete_route(opts={}) subnet = opts[:subnet] netmask = opts[:netmask] || "255.255.255.0" # Default class C Rex::Socket::SwitchBoard.remove_route(subnet, netmask, session) end # Defines usage def usage() print_status "Usage: run autoroute [-r] -s subnet -n netmask" print_status "Examples:" print_status " run autoroute -s 10.1.1.0 -n 255.255.255.0 # Add a route to 10.10.10.1/255.255.255.0" print_status " run autoroute -s 10.10.10.1 # Netmask defaults to 255.255.255.0" print_status " run autoroute -s 10.10.10.1/24 # CIDR notation is also okay" print_status " run autoroute -p # Print active routing table" print_status " run autoroute -d -s 10.10.10.1 # Deletes the 10.10.10.1/255.255.255.0 route" print_status "Use the \"route\" and \"ipconfig\" Meterpreter commands to learn about available routes" end # Validates the command options def validate_cmd(subnet=nil,netmask=nil) if subnet.nil? print_error "Missing -s (subnet) option" return false end unless(check_ip(subnet)) print_error "Subnet invalid (must be IPv4)" usage return false end if(netmask and !(Rex::Socket.addr_atoc(netmask))) print_error "Netmask invalid (must define contiguous IP addressing)" usage return false end if(netmask and !check_ip(netmask)) print_error "Netmask invalid" return usage end true end if print_only print_routes() raise Rex::Script::Completed end if remove_all_routes delete_all_routes() raise Rex::Script::Completed end raise Rex::Script::Completed unless validate_cmd(subnet,netmask) if remove_route print_status("Deleting route to %s/%s..." % [subnet,netmask]) route_result = delete_route(:subnet => subnet, :netmask => netmask) else print_status("Adding a route to %s/%s..." % [subnet,netmask]) route_result = add_route(:subnet => subnet, :netmask => netmask) end if route_result print_good "%s route to %s/%s via %s" % [ (remove_route ? "Deleted" : "Added"), subnet,netmask,client.sock.peerhost ] else print_error "Could not %s route" % [(remove_route ? "delete" : "add")] end if Rex::Socket::SwitchBoard.routes.size > 0 print_status "Use the -p option to list all active routes" end
25.539216
106
0.670825
e9f60b0f3e51defb1e0b32671b2e093526659f2a
5,116
#!/opt/puppetlabs/puppet/bin/ruby require 'json' require 'puppet' require 'openssl' def get_extensions_v1beta1_api_resources(*args) header_params = {} params=args[0][1..-1].split(',') arg_hash={} params.each { |param| mapValues= param.split(':',2) if mapValues[1].include?(';') mapValues[1].gsub! ';',',' end arg_hash[mapValues[0][1..-2]]=mapValues[1][1..-2] } # Remove task name from arguments - should contain all necessary parameters for URI arg_hash.delete('_task') operation_verb = 'Get' query_params, body_params, path_params = format_params(arg_hash) uri_string = "#{arg_hash['kube_api']}/apis/extensions/v1beta1/" % path_params if query_params uri_string = uri_string + '?' + to_query(query_params) end header_params['Content-Type'] = 'application/json' # first of #{parent_consumes} if arg_hash['token'] header_params['Authentication'] = 'Bearer ' + arg_hash['token'] end uri = URI(uri_string) verify_mode= OpenSSL::SSL::VERIFY_NONE if arg_hash['ca_file'] verify_mode=OpenSSL::SSL::VERIFY_PEER end Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', verify_mode: verify_mode, ca_file: arg_hash['ca_file']) do |http| if operation_verb == 'Get' req = Net::HTTP::Get.new(uri) elsif operation_verb == 'Put' req = Net::HTTP::Put.new(uri) elsif operation_verb == 'Delete' req = Net::HTTP::Delete.new(uri) elsif operation_verb == 'Post' req = Net::HTTP::Post.new(uri) end header_params.each { |x, v| req[x] = v } unless header_params.empty? unless body_params.empty? if body_params.key?('file_content') req.body = body_params['file_content'] else req.body = body_params.to_json end end Puppet.debug("URI is (#{operation_verb}) #{uri} headers are #{header_params}") response = http.request req # Net::HTTPResponse object Puppet.debug("response code is #{response.code} and body is #{response.body}") success = response.is_a? Net::HTTPSuccess Puppet.debug("Called (#{operation_verb}) endpoint at #{uri}, success was #{success}") response end end def to_query(hash) if hash return_value = hash.map { |x, v| "#{x}=#{v}" }.reduce { |x, v| "#{x}&#{v}" } if !return_value.nil? return return_value end end return '' end def op_param(name, inquery, paramalias, namesnake) { :name => name, :location => inquery, :paramalias => paramalias, :namesnake => namesnake } end def format_params(key_values) query_params = {} body_params = {} path_params = {} key_values.each { | key, value | if value.include?("=>") Puppet.debug("Running hash from string on #{value}") value.gsub!("=>",":") value.gsub!("'","\"") key_values[key] = JSON.parse(value) Puppet.debug("Obtained hash #{key_values[key].inspect}") end } if key_values.key?('body') if File.file?(key_values['body']) if key_values['body'].include?('json') body_params['file_content'] = File.read(key_values['body']) else body_params['file_content'] =JSON.pretty_generate(YAML.load_file(key_values['body'])) end end end op_params = [ op_param('categories', 'body', 'categories', 'categories'), op_param('group', 'body', 'group', 'group'), op_param('kind', 'body', 'kind', 'kind'), op_param('name', 'body', 'name', 'name'), op_param('namespaced', 'body', 'namespaced', 'namespaced'), op_param('shortnames', 'body', 'shortnames', 'shortnames'), op_param('singularname', 'body', 'singularname', 'singularname'), op_param('storageversionhash', 'body', 'storageversionhash', 'storageversionhash'), op_param('verbs', 'body', 'verbs', 'verbs'), op_param('version', 'body', 'version', 'version'), ] op_params.each do |i| location = i[:location] name = i[:name] paramalias = i[:paramalias] name_snake = i[:namesnake] if location == 'query' query_params[name] = key_values[name_snake] unless key_values[name_snake].nil? query_params[name] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil? elsif location == 'body' body_params[name] = key_values[name_snake] unless key_values[name_snake].nil? body_params[name] = ENV["azure_#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil? else path_params[name_snake.to_sym] = key_values[name_snake] unless key_values[name_snake].nil? path_params[name_snake.to_sym] = ENV["azure__#{name_snake}"] unless ENV["<no value>_#{name_snake}"].nil? end end return query_params,body_params,path_params end def task # Get operation parameters from an input JSON params = STDIN.read result = get_extensions_v1beta1_api_resources(params) if result.is_a? Net::HTTPSuccess puts result.body else raise result.body end rescue StandardError => e result = {} result[:_error] = { msg: e.message, kind: 'puppetlabs-kubernetes/error', details: { class: e.class.to_s }, } puts result exit 1 end task
30.452381
135
0.65129
21c651b14c8385dec429b3a2cda501c090e0b8f3
824
require 'test_helper' class MicropostsControllerTest < ActionDispatch::IntegrationTest def setup @micropost = microposts(:orange) end test "should redirect create when not logged in" do assert_no_difference 'Micropost.count' do post microposts_path , params: { micropost: { content: "Lorem ipsum" } } end assert_redirected_to login_path end test "should redirect destroy when not logged in" do assert_no_difference 'Micropost.count' do delete micropost_path(@micropost) end assert_redirected_to login_path end test "should redirect destroy for wrong micropost" do log_in_as(users(:michael)) micropost = microposts(:ants) assert_no_difference 'Micropost.count' do delete micropost_path(micropost) end assert_redirected_to root_url end end
26.580645
78
0.739078
87ced6527e975ac37d0e56ae60654436e1f5be06
1,846
# == Schema Information # # Table name: countries # # name :string not null, primary key # continent :string # area :integer # population :integer # gdp :integer require_relative './sqlzoo.rb' def example_select execute(<<-SQL) SELECT population FROM countries WHERE name = 'France' SQL end def select_population_of_germany execute(<<-SQL) SELECT population FROM countries WHERE name = 'Germany' SQL end def per_capita_gdp # Show the name and per capita gdp (gdp/population) for each country where # the area is over 5,000,000 km^2 execute(<<-SQL) SELECT name, gdp/population as per_capita_gdp FROM countries WHERE area > 5000000 SQL end def small_and_wealthy # Show the name and continent of countries where the area is less than 2,000 # and the gdp is more than 5,000,000,000. execute(<<-SQL) SELECT name, continent FROM countries WHERE countries.area < 2000 AND countries.gdp > 5000000000 SQL end def scandinavia # Show the name and the population for 'Denmark', 'Finland', 'Norway', and # 'Sweden' execute(<<-SQL) SELECT name, population FROM countries WHERE name = 'Denmark' OR name = 'Norway' OR name = 'Finland' OR name = 'Sweden' SQL end def starts_with_g # Show each country that begins with the letter G execute(<<-SQL) SELECT name FROM countries WHERE name LIKE 'G%'; SQL end def just_the_right_size # Show the country and the area in 1000's of square kilometers for countries # with an area between 200,000 and 250,000. # BETWEEN allows range checking - note that it is inclusive. execute(<<-SQL) SELECT name,area/1000 AS thousands_of_sq_km FROM countries WHERE area BETWEEN 200000 AND 250000 SQL end
20.511111
84
0.670098
91f14a7345106cedfca6d1cf8a37efd2726160d5
160
# Throw exception with unexpected null value. SchemaSerializer.config.raise_on_null = true SchemaSerializer.load_definition(Rails.root.join("doc/schema.yml"))
32
67
0.825
b93ed619de717c651847fc726bab02d534c341ca
1,689
# This file is automatically created by Recurly's OpenAPI generation process # and thus any edits you make by hand will be lost. If you wish to make a # change to this file, please create a Github issue explaining the changes you # need and we will usher them to the appropriate places. module Recurly module Resources class AccountAcquisition < Resource # @!attribute account # @return [AccountMini] Account mini details define_attribute :account, :AccountMini # @!attribute campaign # @return [String] An arbitrary identifier for the marketing campaign that led to the acquisition of this account. define_attribute :campaign, String # @!attribute channel # @return [String] The channel through which the account was acquired. define_attribute :channel, String # @!attribute cost # @return [AccountAcquisitionCost] Account balance define_attribute :cost, :AccountAcquisitionCost # @!attribute created_at # @return [DateTime] When the account acquisition data was created. define_attribute :created_at, DateTime # @!attribute id # @return [String] define_attribute :id, String # @!attribute object # @return [String] Object type define_attribute :object, String # @!attribute subchannel # @return [String] An arbitrary subchannel string representing a distinction/subcategory within a broader channel. define_attribute :subchannel, String # @!attribute updated_at # @return [DateTime] When the account acquisition data was last changed. define_attribute :updated_at, DateTime end end end
35.93617
122
0.703375
3882b558cc7c56e12c3e7ec46c3972897bc56ac9
1,023
# crypt.rb require 'base64' module HipChatSecrets class Crypt def self.encode str Base64::encode64(xor str).strip end def self.decode str xor Base64::decode64(str) end def self.xor input input = input.unpack 'U*' output = [] input.each_with_index do |num,index| output << (num ^ secret[index%secret.length]) end output.pack 'U*' end # You have to figure out the Secret on your own. Good luck! def self.secret return @@key if defined? @@key key_file = File.expand_path('~/.hipchat_secret') send 'secret=', if ENV['HIPCHAT_SECRET'] ENV['HIPCHAT_SECRET'] elsif File.exists? key_file File.open(key_file, 'r') {|f| f.read } else raise "Could not locate HipChat Secret Key in HIPCHAT_SECRET or #{key_file}" end end def self.secret= key @@key = key.strip.unpack 'U*' end def self.secret_str secret.pack 'U*' end end end
19.673077
86
0.588465
e9e40513b55b0517133e3347ec543db0f3c530c8
16
require 'what'
5.333333
14
0.6875
62d1bac7fce28a14e6a1dd4aa3bc18b00b1512db
198
class AddInProgressStepsToJobApplications < ActiveRecord::Migration[6.1] def change add_column :job_applications, :in_progress_steps, :integer, array: true, default: [], null: false end end
33
101
0.772727
acdc68b9bf97dd9126203e6c29102966c91325da
656
# frozen_string_literal: true module Numismatics class CitationDecorator < Valkyrie::ResourceDecorator display :part, :number, :numismatic_reference, :uri delegate :decorated_numismatic_reference, to: :wayfinder def manageable_files? false end def manageable_structure? false end def part Array.wrap(super).first end def number Array.wrap(super).first end def numismatic_reference decorated_numismatic_reference.short_title end def title "#{decorated_numismatic_reference&.short_title} #{part} #{number}" end end end
18.222222
72
0.657012
1c0d138291259842c3742736e9d996d5891406e7
224
class AddExternalBlockedToUsers < ActiveRecord::Migration def change add_column :users, :external, :boolean, default: false, null: false add_column :users, :blocked, :boolean, default: false, null: false end end
32
71
0.745536
f745483973d961083516c52eaafe8f0a517f8ab8
7,465
require "fileutils" begin require "io/console" rescue LoadError end require "net/http" require "pathname" module Datasets class Downloader def initialize(url) if url.is_a?(URI::Generic) url = url.dup else url = URI.parse(url) end @url = url unless @url.is_a?(URI::HTTP) raise ArgumentError, "download URL must be HTTP or HTTPS: <#{@url}>" end end def download(output_path) output_path.parent.mkpath headers = {"User-Agent" => "Red Datasets/#{VERSION}"} start = nil partial_output_path = Pathname.new("#{output_path}.partial") if partial_output_path.exist? start = partial_output_path.size headers["Range"] = "bytes=#{start}-" end Net::HTTP.start(@url.hostname, @url.port, :use_ssl => (@url.scheme == "https")) do |http| path = @url.path path += "?#{@url.query}" if @url.query request = Net::HTTP::Get.new(path, headers) http.request(request) do |response| case response when Net::HTTPPartialContent mode = "ab" when Net::HTTPSuccess start = nil mode = "wb" else break end base_name = @url.path.split("/").last size_current = 0 size_max = response.content_length if start size_current += start size_max += start end progress_reporter = ProgressReporter.new(base_name, size_max) partial_output_path.open(mode) do |output| response.read_body do |chunk| size_current += chunk.bytesize progress_reporter.report(size_current) output.write(chunk) end end end end FileUtils.mv(partial_output_path, output_path) end class ProgressReporter def initialize(base_name, size_max) @base_name = base_name @size_max = size_max @time_previous = Time.now @size_previous = 0 @need_report = ($stderr == STDERR and $stderr.tty?) end def report(size_current) return unless @need_report return if @size_max.nil? return unless foreground? done = (size_current == @size_max) time_current = Time.now if not done and time_current - @time_previous <= 1 return end read_bytes = size_current - @size_previous throughput = read_bytes.to_f / (time_current - @time_previous) @time_previous = time_current @size_previous = size_current message = build_message(size_current, throughput) $stderr.print("\r#{message}") if message $stderr.puts if done end private def build_message(size_current, throughput) percent = (size_current / @size_max.to_f) * 100 formatted_size = "[%s/%s]" % [ format_size(size_current), format_size(@size_max), ] rest_second = (@size_max - size_current) / throughput separator = " - " progress = "%05.1f%% %s %s %s" % [ percent, formatted_size, format_time_interval(rest_second), format_throughput(throughput), ] base_name = @base_name width = guess_terminal_width return "#{base_name}#{separator}#{progress}" if width.nil? return nil if progress.size > width base_name_width = width - progress.size - separator.size if base_name.size > base_name_width ellipsis = "..." shorten_base_name_width = base_name_width - ellipsis.size if shorten_base_name_width < 1 return progress else base_name = base_name[0, shorten_base_name_width] + ellipsis end end "#{base_name}#{separator}#{progress}" end def format_size(size) if size < 1000 "%d" % size elsif size < (1000 ** 2) "%6.2fKB" % (size.to_f / 1000) elsif size < (1000 ** 3) "%6.2fMB" % (size.to_f / (1000 ** 2)) elsif size < (1000 ** 4) "%6.2fGB" % (size.to_f / (1000 ** 3)) else "%.2fTB" % (size.to_f / (1000 ** 4)) end end def format_time_interval(interval) if interval < 60 "00:00:%02d" % interval elsif interval < (60 * 60) minute, second = interval.divmod(60) "00:%02d:%02d" % [minute, second] elsif interval < (60 * 60 * 24) minute, second = interval.divmod(60) hour, minute = minute.divmod(60) "%02d:%02d:%02d" % [hour, minute, second] else minute, second = interval.divmod(60) hour, minute = minute.divmod(60) day, hour = hour.divmod(24) "%dd %02d:%02d:%02d" % [day, hour, minute, second] end end def format_throughput(throughput) throughput_byte = throughput / 8 if throughput_byte <= 1000 "%3dB/s" % throughput_byte elsif throughput_byte <= (1000 ** 2) "%3dKB/s" % (throughput_byte / 1000) elsif throughput_byte <= (1000 ** 3) "%3dMB/s" % (throughput_byte / (1000 ** 2)) else "%3dGB/s" % (throughput_byte / (1000 ** 3)) end end def foreground? proc_stat_path = "/proc/self/stat" ps_path = "/bin/ps" if File.exist?(proc_stat_path) stat = File.read(proc_stat_path).sub(/\A.+\) /, "").split process_group_id = stat[2] terminal_process_group_id = stat[5] process_group_id == terminal_process_group_id elsif File.executable?(ps_path) IO.pipe do |input, output| pid = spawn(ps_path, "-o", "stat", "-p", Process.pid.to_s, {:out => output, :err => output}) output.close _, status = Process.waitpid2(pid) return false unless status.success? input.each_line.to_a.last.include?("+") end else false end end def guess_terminal_width guess_terminal_width_from_io || guess_terminal_width_from_command || guess_terminal_width_from_env || 80 end def guess_terminal_width_from_io if IO.respond_to?(:console) IO.console.winsize[1] elsif $stderr.respond_to?(:winsize) begin $stderr.winsize[1] rescue SystemCallError nil end else nil end end def guess_terminal_width_from_command IO.pipe do |input, output| begin pid = spawn("tput", "cols", {:out => output, :err => output}) rescue SystemCallError return nil end output.close _, status = Process.waitpid2(pid) return nil unless status.success? result = input.read.chomp begin Integer(result, 10) rescue ArgumentError nil end end end def guess_terminal_width_from_env env = ENV["COLUMNS"] || ENV["TERM_WIDTH"] return nil if env.nil? begin Integer(env, 10) rescue ArgumentError nil end end end end end
28.492366
76
0.544675
180bc60b9cdb6c6109a4704c821f3054575eebe5
4,340
# frozen_string_literal: true require 'spec_helper' RSpec.describe Sortable do describe '.order_by' do let(:relation) { Design.all } describe 'ordering by id' do it 'ascending' do allow(relation).to receive(:reorder).with(id: :asc) relation.order_by('id_asc') expect(relation).to have_received(:reorder).with(id: :asc) end it 'descending' do allow(relation).to receive(:reorder).with(id: :desc) relation.order_by('id_desc') expect(relation).to have_received(:reorder).with(id: :desc) end end describe 'ordering by created day' do it 'ascending' do allow(relation).to receive(:reorder).with(created_at: :asc) relation.order_by('created_asc') expect(relation).to have_received(:reorder).with(created_at: :asc) end it 'descending' do allow(relation).to receive(:reorder).with(created_at: :desc) relation.order_by('created_desc') expect(relation).to have_received(:reorder).with(created_at: :desc) end it 'order by "date"' do allow(relation).to receive(:reorder).with(created_at: :desc) relation.order_by('created_date') expect(relation).to have_received(:reorder).with(created_at: :desc) end end describe 'ordering by name' do it 'ascending' do table = Regexp.escape(ActiveRecord::Base.connection.quote_table_name(:designs)) column = Regexp.escape(ActiveRecord::Base.connection.quote_column_name(:name)) sql = relation.order_by('name_asc').to_sql expect(sql).to match(/.+ORDER BY LOWER\(#{table}.#{column}\) ASC\z/) end it 'descending' do table = Regexp.escape(ActiveRecord::Base.connection.quote_table_name(:designs)) column = Regexp.escape(ActiveRecord::Base.connection.quote_column_name(:name)) sql = relation.order_by('name_desc').to_sql expect(sql).to match(/.+ORDER BY LOWER\(#{table}.#{column}\) DESC\z/) end end describe 'ordering by Updated Time' do it 'ascending' do allow(relation).to receive(:reorder).with(updated_at: :asc) relation.order_by('updated_asc') expect(relation).to have_received(:reorder).with(updated_at: :asc) end it 'descending' do allow(relation).to receive(:reorder).with(updated_at: :desc) relation.order_by('updated_desc') expect(relation).to have_received(:reorder).with(updated_at: :desc) end end it 'does not call reorder in case of unrecognized ordering' do allow(relation).to receive(:reorder) relation.order_by('random_ordering') expect(relation).not_to have_received(:reorder) end end describe 'sorting designs' do def ordered_design_names(order) Design.all.order_by(order).map(&:name) end let!(:ref_time) { Time.zone.parse('2020-04-28 00:00:00') } before do create(:design, name: 'aa', id: 1, created_at: ref_time - 15.seconds, updated_at: ref_time) create(:design, name: 'AAA', id: 2, created_at: ref_time - 10.seconds, updated_at: ref_time - 5.seconds) create(:design, name: 'BB', id: 3, created_at: ref_time - 5.seconds, updated_at: ref_time - 10.seconds) create(:design, name: 'bbb', id: 4, created_at: ref_time, updated_at: ref_time - 15.seconds) end it 'sorts designs by id' do expect(ordered_design_names('id_asc')).to eq(%w[aa AAA BB bbb]) expect(ordered_design_names('id_desc')).to eq(%w[bbb BB AAA aa]) end it 'sorts designs by name via case-insensitive comparison' do expect(ordered_design_names('name_asc')).to eq(%w[aa AAA BB bbb]) expect(ordered_design_names('name_desc')).to eq(%w[bbb BB AAA aa]) end it 'sorts designs by created_at' do expect(ordered_design_names('created_asc')).to eq(%w[aa AAA BB bbb]) expect(ordered_design_names('created_desc')).to eq(%w[bbb BB AAA aa]) expect(ordered_design_names('created_date')).to eq(%w[bbb BB AAA aa]) end it 'sorts designs by updated_at' do expect(ordered_design_names('updated_asc')).to eq(%w[bbb BB AAA aa]) expect(ordered_design_names('updated_desc')).to eq(%w[aa AAA BB bbb]) end end end
31.223022
98
0.648157
6200bf118a05ab6b6d25b4038a5dcf8430482108
7,981
require 'net/ssh/test/channel' require 'net/ssh/test/local_packet' require 'net/ssh/test/remote_packet' module Net module SSH module Test # Represents a sequence of scripted events that identify the behavior that # a test expects. Methods named "sends_*" create events for packets being # sent from the local to the remote host, and methods named "gets_*" create # events for packets being received by the local from the remote host. # # A reference to a script. is generally obtained in a unit test via the # Net::SSH::Test#story helper method: # # story do |script| # channel = script.opens_channel # ... # end class Script # The list of scripted events. These will be Net::SSH::Test::LocalPacket # and Net::SSH::Test::RemotePacket instances. attr_reader :events # Create a new, empty script. def initialize @events = [] end # Scripts the opening of a channel by adding a local packet sending the # channel open request, and if +confirm+ is true (the default), also # adding a remote packet confirming the new channel. # # A new Net::SSH::Test::Channel instance is returned, which can be used # to script additional channel operations. def opens_channel(confirm=true) channel = Channel.new(self) channel.remote_id = 5555 events << LocalPacket.new(:channel_open) { |p| channel.local_id = p[:remote_id] } events << RemotePacket.new(:channel_open_confirmation, channel.local_id, channel.remote_id, 0x20000, 0x10000) if confirm channel end # A convenience method for adding an arbitrary local packet to the events # list. def sends(type, *args, &block) events << LocalPacket.new(type, *args, &block) end # A convenience method for adding an arbitrary remote packet to the events # list. def gets(type, *args) events << RemotePacket.new(type, *args) end # Scripts the sending of a new channel request packet to the remote host. # +channel+ should be an instance of Net::SSH::Test::Channel. +request+ # is a string naming the request type to send, +reply+ is a boolean # indicating whether a response to this packet is required , and +data+ # is any additional request-specific data that this packet should send. # +success+ indicates whether the response (if one is required) should be # success or failure. If +data+ is an array it will be treated as multiple # data. # # If a reply is desired, a remote packet will also be queued, :channel_success # if +success+ is true, or :channel_failure if +success+ is false. # # This will typically be called via Net::SSH::Test::Channel#sends_exec or # Net::SSH::Test::Channel#sends_subsystem. def sends_channel_request(channel, request, reply, data, success=true) if data.is_a? Array events << LocalPacket.new(:channel_request, channel.remote_id, request, reply, *data) else events << LocalPacket.new(:channel_request, channel.remote_id, request, reply, data) end if reply if success events << RemotePacket.new(:channel_success, channel.local_id) else events << RemotePacket.new(:channel_failure, channel.local_id) end end end # Scripts the sending of a channel data packet. +channel+ must be a # Net::SSH::Test::Channel object, and +data+ is the (string) data to # expect will be sent. # # This will typically be called via Net::SSH::Test::Channel#sends_data. def sends_channel_data(channel, data) events << LocalPacket.new(:channel_data, channel.remote_id, data) end # Scripts the sending of a channel EOF packet from the given # Net::SSH::Test::Channel +channel+. This will typically be called via # Net::SSH::Test::Channel#sends_eof. def sends_channel_eof(channel) events << LocalPacket.new(:channel_eof, channel.remote_id) end # Scripts the sending of a channel close packet from the given # Net::SSH::Test::Channel +channel+. This will typically be called via # Net::SSH::Test::Channel#sends_close. def sends_channel_close(channel) events << LocalPacket.new(:channel_close, channel.remote_id) end # Scripts the sending of a channel request pty packets from the given # Net::SSH::Test::Channel +channel+. This will typically be called via # Net::SSH::Test::Channel#sends_request_pty. def sends_channel_request_pty(channel) data = ['pty-req', false] data += Net::SSH::Connection::Channel::VALID_PTY_OPTIONS.merge(modes: "\0").values events << LocalPacket.new(:channel_request, channel.remote_id, *data) end # Scripts the reception of a channel data packet from the remote host by # the given Net::SSH::Test::Channel +channel+. This will typically be # called via Net::SSH::Test::Channel#gets_data. def gets_channel_data(channel, data) events << RemotePacket.new(:channel_data, channel.local_id, data) end # Scripts the reception of a channel extended data packet from the remote # host by the given Net::SSH::Test::Channel +channel+. This will typically # be called via Net::SSH::Test::Channel#gets_extended_data. # # Currently the only extended data type is stderr == 1. def gets_channel_extended_data(channel, data) events << RemotePacket.new(:channel_extended_data, channel.local_id, 1, data) end # Scripts the reception of a channel request packet from the remote host by # the given Net::SSH::Test::Channel +channel+. This will typically be # called via Net::SSH::Test::Channel#gets_exit_status. def gets_channel_request(channel, request, reply, data) events << RemotePacket.new(:channel_request, channel.local_id, request, reply, data) end # Scripts the reception of a channel EOF packet from the remote host by # the given Net::SSH::Test::Channel +channel+. This will typically be # called via Net::SSH::Test::Channel#gets_eof. def gets_channel_eof(channel) events << RemotePacket.new(:channel_eof, channel.local_id) end # Scripts the reception of a channel close packet from the remote host by # the given Net::SSH::Test::Channel +channel+. This will typically be # called via Net::SSH::Test::Channel#gets_close. def gets_channel_close(channel) events << RemotePacket.new(:channel_close, channel.local_id) end # By default, removes the next event in the list and returns it. However, # this can also be used to non-destructively peek at the next event in the # list, by passing :first as the argument. # # # remove the next event and return it # event = script.next # # # peek at the next event # event = script.next(:first) def next(mode=:shift) events.send(mode) end # Compare the given packet against the next event in the list. If there is # no next event, an exception will be raised. This is called by # Net::SSH::Test::Extensions::PacketStream#test_enqueue_packet. def process(packet) event = events.shift or raise "end of script reached, but got a packet type #{packet.read_byte}" event.process(packet) end end end end end
43.612022
130
0.630999
185fc3a2c14001ea5e7d430e8c7029564758e154
1,425
# frozen_string_literal: true module Teckel class Config # @!visibility private def initialize @config = {} end # Allow getting or setting a value, with some weird rules: # - The +value+ might not be +nil+ # - Setting via +value+ is allowed only once. Successive calls will raise a {FrozenConfigError} # - Setting via +block+ works almost like {Hash#fetch}: # - returns the existing value if key is present # - sets (and returns) the blocks return value otherwise # - calling without +value+ and +block+ works like {Hash#[]} # # @raise [FrozenConfigError] When overwriting a key # @!visibility private def for(key, value = nil, &block) if value.nil? get_or_set(key, &block) elsif @config.key?(key) raise FrozenConfigError, "Configuration #{key} is already set" else @config[key] = value end end # @!visibility private def replace(key) @config[key] = yield if @config.key?(key) end # @!visibility private def freeze @config.freeze super() end # @!visibility private def dup super().tap do |copy| copy.instance_variable_set(:@config, @config.dup) end end private def get_or_set(key, &block) if block @config[key] ||= @config.fetch(key, &block) else @config[key] end end end end
24.152542
99
0.605614
bbd383dc72484d5480f2b44ccfaf0aedffa1ea74
84
class GameTurn < ApplicationRecord belongs_to :game belongs_to :player_turn end
16.8
34
0.809524
e8ab12483e2240ddb2c1dff21b4ebf5869b2ec22
239
module UseCase module AssessmentSummary class CepcSupplement < UseCase::AssessmentSummary::Supplement def add_data!(hash) registered_by!(hash) related_assessments!(hash) hash end end end end
19.916667
65
0.669456
f8e2e2b38f88390f049f2a3131ed58e1a9cf7619
1,622
# # Be sure to run `pod lib lint TTForm.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| s.name = 'TTForm' s.version = '0.1.0' s.summary = 'A short description of TTForm.' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC TODO: Add long description of the pod here. DESC s.homepage = 'https://github.com/hooliganer/TTForm' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'hooliganer' => '243879136@qq.com' } s.source = { :git => 'https://github.com/hooliganer/TTForm.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' s.source_files = 'TTForm/Classes/**/*' # s.resource_bundles = { # 'TTForm' => ['TTForm/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' s.dependency 'SwiftForms' s.dependency 'SnapKit' end
36.044444
101
0.632552
ac8da9e035ad543ab6fb735b7737c94df9c46500
381
class AccountActivationsController < ApplicationController def edit user = User.find_by(email: params[:email]) if user && !user.activated? && user.authenticated?(:activation, params[:id]) user.activate log_in user flash[:success] = "Account activated!" redirect_to user else flash[:danger] = "Invalid activation link" redirect_to root_url end end end
22.411765
78
0.721785
e8734cc8343b35d1a3dc568e47644aa83cf48e5b
901
# coding: utf-8 Gem::Specification.new do |spec| spec.name = "jekyll-sleek" spec.version = "0.1.8" spec.authors = ["Jan Czizikow"] spec.email = ["jan.czizikow@gmail.com"] spec.summary = %q{Sleek is a modern Jekyll theme focused on speed performance & SEO best practices.} spec.homepage = "https://janczizikow.github.io/sleek/" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").select do |f| f.match(%r!^(assets|_(includes|layouts|sass)/|(LICENSE|README)((\.(txt|md|markdown)|$)))!i) end spec.platform = Gem::Platform::RUBY spec.add_runtime_dependency "jekyll", "~> 3.6" spec.add_runtime_dependency "jekyll-seo-tag", "~> 2.3" spec.add_runtime_dependency "jekyll-sitemap", "~> 1.1" spec.add_development_dependency "bundler", "~> 2.0" spec.add_development_dependency "rake", "~> 12.3.3" end
36.04
108
0.63485
ab2202e680af453f923ed05e9f7d8dfd5cc3bee8
459
class Track < ActiveRecord::Base belongs_to :dj has_attached_file :audio validates_attachment_content_type :audio, :content_type => [ 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio' ] has_attached_file :track_art, :styles => { :medium => "300x300>", :thumb => "100x100>" } validates_attachment_content_type :track_art, :content_type => /\Aimage\/.*\Z/ end
51
201
0.697168
6ad0d460ef093539b74b2fc09cca5e99e7a8a42e
1,324
# Filters added to this controller apply to all controllers in the application. # Likewise, all the methods added will be available for all controllers. class ApplicationController < ActionController::Base helper :all helper_method :current_user_session, :current_user filter_parameter_logging :password, :password_confirmation private def current_user_session return @current_user_session if defined?(@current_user_session) @current_user_session = UserSession.find end def current_user return @current_user if defined?(@current_user) @current_user = current_user_session && current_user_session.record end def require_user unless current_user store_location flash[:notice] = "You must be logged in to access this page" redirect_to new_user_session_url return false end end def require_no_user if current_user store_location flash[:notice] = "You must be logged out to access this page" redirect_to account_url return false end end def store_location session[:return_to] = request.request_uri end def redirect_back_or_default(default) redirect_to(session[:return_to] || default) session[:return_to] = nil end end
28.170213
79
0.702417
21a5afd27adbc0fda5cb54c30ce1261d59418ba2
2,555
require "test_helper" module WillItRuby class StandardLibrary::ArrayOperatorsTest < ProcessorTest def test_union process <<-RUBY [1,2] | [2, 3] RUBY assert_no_issues assert_result :Array # TODO: when implemented ... # assert_equal [1, 2, 2, 3], last_evaluated_result.value.map(&:value) end def test_intersection process <<-RUBY [1,2] & [2, 3] RUBY assert_no_issues assert_result :Array # TODO: when implemented ... # assert_equal [2], last_evaluated_result.value.map(&:value) end def test_addition process <<-RUBY [1,2] + [2, 3] RUBY assert_no_issues assert_result :Array assert_equal [1, 2, 2, 3], last_evaluated_result.value.map(&:value) end def test_subtraction process <<-RUBY [1,2] - [2, 3] RUBY assert_no_issues assert_result :Array # TODO: when implemented ... # assert_equal [1], last_evaluated_result.value.map(&:value) end [[:union, :|], [:intersection, :&], [:addition, :+], [:subtraction, :-]].each do |name, op| define_method("test_#{name}_type_check") do process <<-RUBY [1,2] #{op} 7 RUBY assert_issues "(unknown):1 no implicit conversion of Integer into Array" end define_method("test_#{name}_type_conversion") do process <<-RUBY class Foo def to_ary [2, 3] end end [1,2] #{op} Foo.new RUBY assert_no_issues assert_result :Array end define_method("test_#{name}_broken_type_conversion") do process <<-RUBY class Foo def to_ary 7 end end [1,2] #{op} Foo.new RUBY assert_issues "(unknown):7 can't convert Foo to Array (Foo#to_ary gives Integer)" end end def test_multiply_integer process <<-RUBY [1, 2] * 3 RUBY assert_no_issues assert_result :Array assert_equal [1, 2, 1, 2, 1, 2], last_evaluated_result.value.map(&:value) end def test_multiply_string process <<-RUBY [1, 2] * ',' RUBY assert_no_issues assert_result :String #, '1,2' # TODO: when implemented ... end def test_multiply_type_check process <<-RUBY [1, 2] * Object.new RUBY assert_issues "(unknown):1 no implicit conversion of Object into Integer" end end end
22.217391
95
0.562427
4a8ad8c46e32a79c315604f598fcabf7b641bb0a
168
module VideoLessonsHelper def embed(youtube) youtube_id = youtube.split("=").last content_tag(:iframe, nil, src: "//www.youtube.com/embed/#{youtube_id}") end end
24
73
0.72619
abd5366b854ac8247ed326b55b1b091251a29a39
73
require 'job_state/engine' require 'job_state/base' module JobState end
12.166667
26
0.808219
622e0a6f6e4d5963502c8ca6305741d1df20d52e
75
json.array!(@posts) do |post| json.extract! post, :id, :title, :body end
18.75
40
0.653333
031af4ed6019a201e34c79491b854c5ed5c98c11
1,265
# # Manages a Zone on a given router or switch # Puppet::Type.newtype(:zone) do @doc = "Manages a ZONE on a router or switch." apply_to_device ensurable newparam(:name) do desc "Zone name." validate do |value| if value.strip.length == 0 raise ArgumentError, "The zone name is invalid." end if value =~/^\d/ raise ArgumentError, "The zone name is invalid, Zone name cannot start with a digit" end if value !~ /^\S{1,64}$/ raise ArgumentError, "The zone name is invalid." end end end newproperty(:vsanid) do desc "vsanid" validate do |value| if value.strip.length == 0 raise ArgumentError, "The VSAN Id is invalid." end if value.to_i == 0 raise ArgumentError, "The VSAN Id 0 is invalid." end if value !~ /^\d+/ raise ArgumentError, "The VSAN Id should be numeric." end end end newproperty(:membertype) do desc "member type" newvalues(:'device-alias', :fcalias, :fcid, :fwwn, :pwwn) end newproperty(:member) do desc "member wwpn" end end
23.425926
98
0.53834
ab0aec133a9c4fec7260588faf62bd30fa371250
28
module GakuyuInfoHelper end
9.333333
23
0.892857
d575d78f909256509ceba8abec0e0b672dc2765a
140
class Photo < ActiveRecord::Base belongs_to :user mount_uploader :image, ImageUploader default_scope { order(created_at: :desc) } end
23.333333
44
0.764286
4a2ff87e4f855e59883f63f853da75b85571de2f
1,112
require 'ostruct' class Errapi::ValidationError attr_accessor :reason # TODO: add value to error attr_accessor :check_value attr_accessor :checked_value attr_accessor :validation attr_accessor :constraints attr_accessor :location def initialize options = {} ATTRIBUTES.each do |attr| instance_variable_set "@#{attr}", options[attr] if options.key? attr end end def matches? criteria = {} unknown_criteria = criteria.keys - ATTRIBUTES raise "Unknown error attributes: #{unknown_criteria.join(', ')}." if unknown_criteria.any? ATTRIBUTES.all?{ |attr| criterion_matches? criteria, attr } end private ATTRIBUTES = %i(reason location check_value checked_value validation) def criterion_matches? criteria, attr return true unless criteria.key? attr value = send attr criterion = criteria[attr] if criterion.kind_of? Regexp !!criterion.match(value.to_s) elsif criterion.kind_of? String criterion == value.to_s elsif criterion.respond_to? :=== criterion === value else criterion == value end end end
24.711111
94
0.707734
bb4de26a90b706218b2ef488fbe44a3435ab44b5
548
cask "qownnotes" do version "20.12.3" sha256 "96f96e21a6af502b0c2add8be1e442282f0d22b637c6a1b0d24814a9ec02057d" # github.com/pbek/QOwnNotes/ was verified as official when first introduced to the cask url "https://github.com/pbek/QOwnNotes/releases/download/v#{version}/QOwnNotes.dmg" appcast "https://github.com/pbek/QOwnNotes/releases.atom" name "QOwnNotes" desc "Plain-text file notepad and todo-list manager" homepage "https://www.qownnotes.org/" auto_updates true depends_on macos: ">= :sierra" app "QOwnNotes.app" end
32.235294
89
0.762774
01ffd9aff1874c2e9264dc7fa177d3aa3cfa490c
5,753
###################################################################### # Copyright (c) 2008-2010, Alliance for Sustainable Energy. # All rights reserved. # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ###################################################################### # Each user script is implemented within a class that derives from OpenStudio::Ruleset::UserScript class ExportRPXFile < OpenStudio::Ruleset::ModelUserScript # override name to return the name of your script def name return "Export RPX File" end # returns a vector of arguments, the runner will present these arguments to the user # then pass in the results on run def arguments(model) result = OpenStudio::Ruleset::OSArgumentVector.new #make an argument for thermal_zone thermal_zone_handles = OpenStudio::StringVector.new thermal_zone_display_names = OpenStudio::StringVector.new model.getThermalZones.each do |thermal_zone| thermal_zone_handles << thermal_zone.handle.to_s thermal_zone_display_names << thermal_zone.name.to_s end thermal_zone = OpenStudio::Ruleset::OSArgument::makeChoiceArgument("thermal_zone", thermal_zone_handles, thermal_zone_display_names, true) thermal_zone.setDisplayName("Thermal Zone to Export") result << thermal_zone save_path = OpenStudio::Ruleset::OSArgument::makePathArgument("save_path", false, "rpx", true) save_path.setDisplayName("Output Path") save_path.setDefaultValue("#{OpenStudio::Plugin.model_manager.model_interface.openstudio_name}.rpx") result << save_path return result end # override run to implement the functionality of your script # model is an OpenStudio::Model::Model, runner is a OpenStudio::Ruleset::UserScriptRunner def run(model, runner, user_arguments) super(model, runner, user_arguments) if not runner.validateUserArguments(arguments(model),user_arguments) return false end thermal_zone = runner.getOptionalWorkspaceObjectChoiceValue("thermal_zone",user_arguments,model) #model is passed in because of argument type save_path = runner.getStringArgumentValue("save_path",user_arguments) if thermal_zone.empty? handle = runner.getStringArgumentValue("thermal_zone",user_arguments) if handle.empty? runner.registerError("No thermal zone was chosen.") else runner.registerError("The selected thermal zone with handle '#{handle}' was not found in the model. It may have been removed by another measure.") end return false else if not thermal_zone.get.to_ThermalZone.empty? thermal_zone = thermal_zone.get.to_ThermalZone.get else runner.registerError("Script Error - argument not showing up as thermal zone.") return false end end site = model.getSite report_string = "" report_string << "ROOM, #{thermal_zone.name}, SI\n" report_string << "SITE, #{site.latitude}, #{site.longitude}, #{site.timeZone}, #{model.getSite.elevation}\n" # loop over spaces in thermal zone thermal_zone.spaces.each do |space| # loop over surfaces space.surfaces.each do |surface| # skip surfaces internal to this thermal zone # write surface # TODO: get real emittance value emittance = 0.9 vertices = surface.vertices all_vertices = [] vertices.each do |vertex| all_vertices << vertex.x all_vertices << vertex.y all_vertices << vertex.z end report_string << "S, #{surface.name}, #{emittance}, #{vertices.size}, #{all_vertices.join(', ')}\n" # loop over sub surfaces surface.subSurfaces.each do |sub_surface| # write sub surface # TODO: get real emittance value sub_surface_type = "P" emittance = 0.9 subSurfaceType = sub_surface.subSurfaceType if (subSurfaceType == "FixedWindow" || subSurfaceType == "FixedWindow" || subSurfaceType == "GlassDoor" || subSurfaceType == "Skylight") sub_surface_type = "W" emittance = 0.84 end vertices = sub_surface.vertices all_vertices = [] vertices.each do |vertex| all_vertices << vertex.x all_vertices << vertex.y all_vertices << vertex.z end report_string << "#{sub_surface_type}, #{sub_surface.name}, #{emittance}, #{vertices.size}, #{all_vertices.join(', ')}\n" end end end # TODO: see if there is output data available to get surface temperatures, etc # CASE, <CaseDesc> ; # RC, <RoomAirTemp (C)>,<RoomHumidity (0-1)>,<RoomPressure (Pa)>, <Surf1T>, <SurfT>, etc # write file File.open(save_path, 'w') do |file| file << report_string end return(true) end end # this call registers your script with the OpenStudio SketchUp plug-in ExportRPXFile.new.registerWithApplication
38.099338
154
0.661568
e8f66422101c66b3b651d36ffc0efc91d75d764f
1,112
# # Be sure to run `pod spec lint KKRouter.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| s.name = "KKTableView" s.version = "0.0.8" s.summary = "UITableView" s.description = <<-DESC 对UITableView的封装 1.可以方便快速的使用tableview; 2.tableview模块化开发工具 DESC s.homepage = "https://github.com/cmadc/KKTableView" s.license = "MIT (example)" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "caiming" => "davis_cai@163.com" } s.platform = :ios, "8.0" s.source = { :git => "https://github.com/cmadc/KKTableView.git", :tag => s.version } s.source_files = "Classes", "Pod/*.{h,m}" s.requires_arc = true s.dependency 'KKRouter' s.dependency 'UITableView+FDTemplateLayoutCell' end
32.705882
92
0.608813
ed8424201bfd80b80d07a201d920b4972dcd0079
2,517
require 'faraday' require 'faraday/request/multipart' require 'json' require 'timeout' require 'postcode_anywhere/error' require 'postcode_anywhere/response/raise_error' require 'postcode_anywhere/response/parse_json' module PostcodeAnywhere class Client attr_accessor(*Configuration::VALID_CONFIG_KEYS) def initialize(options = {}) merged_options = PostcodeAnywhere.options.merge(options) Configuration::VALID_CONFIG_KEYS.each do |key| send("#{key}=", merged_options[key]) end end # Perform an HTTP GET request def get(path, body_hash = {}, params = {}) request(:get, path, params, body_hash) end # Perform an HTTP POST request def post(path, body_hash = {}, params = {}) request(:post, path, params, body_hash) end def connection_options @connection_options ||= { builder: middleware, headers: { accept: "application/#{@format}", content_type: "application/#{@format}", user_agent: user_agent }, request: { open_timeout: 10, timeout: 30 } } end def connection @connection ||= Faraday.new(@endpoint, connection_options) end def middleware @middleware ||= Faraday::RackBuilder.new do |faraday| # Checks for files in the payload, otherwise leaves everything untouched faraday.request :multipart # Encodes as "application/x-www-form-urlencoded" if not already encoded faraday.request :url_encoded # Handle error responses faraday.response :postcode_anywhere_raise_error # Parse JSON response bodies faraday.response :postcode_anywhere_parse_json # Set default HTTP adapter faraday.adapter :net_http end end private def request(method, path, params = {}, body_hash = {}) attach_api_key_to params connection.send(method.to_sym, path, params) do |request| request.body = compile_body(body_hash) unless body_hash.empty? end.env rescue Faraday::Error::TimeoutError, Timeout::Error => error raise(PostcodeAnywhere::Error::RequestTimeout.new(error)) rescue Faraday::Error::ClientError, JSON::ParserError => error raise(PostcodeAnywhere::Error.new(error)) end def attach_api_key_to(params) params.merge!('Key' => @api_key) unless params.keys.include? 'Key' end def compile_body(body_hash) body_hash.to_json end end end
28.931034
80
0.659913
08b7e7aaf3dc6ae26d6cbf55964f86f48490a1cb
118,741
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE require 'seahorse/client/plugins/content_length.rb' require 'aws-sdk-core/plugins/credentials_configuration.rb' require 'aws-sdk-core/plugins/logging.rb' require 'aws-sdk-core/plugins/param_converter.rb' require 'aws-sdk-core/plugins/param_validator.rb' require 'aws-sdk-core/plugins/user_agent.rb' require 'aws-sdk-core/plugins/helpful_socket_errors.rb' require 'aws-sdk-core/plugins/retry_errors.rb' require 'aws-sdk-core/plugins/global_configuration.rb' require 'aws-sdk-core/plugins/regional_endpoint.rb' require 'aws-sdk-core/plugins/endpoint_discovery.rb' require 'aws-sdk-core/plugins/endpoint_pattern.rb' require 'aws-sdk-core/plugins/response_paging.rb' require 'aws-sdk-core/plugins/stub_responses.rb' require 'aws-sdk-core/plugins/idempotency_token.rb' require 'aws-sdk-core/plugins/jsonvalue_converter.rb' require 'aws-sdk-core/plugins/client_metrics_plugin.rb' require 'aws-sdk-core/plugins/client_metrics_send_plugin.rb' require 'aws-sdk-core/plugins/transfer_encoding.rb' require 'aws-sdk-core/plugins/http_checksum.rb' require 'aws-sdk-core/plugins/signature_v4.rb' require 'aws-sdk-core/plugins/protocols/query.rb' require 'aws-sdk-sts/plugins/sts_regional_endpoints.rb' Aws::Plugins::GlobalConfiguration.add_identifier(:sts) module Aws::STS # An API client for STS. To construct a client, you need to configure a `:region` and `:credentials`. # # client = Aws::STS::Client.new( # region: region_name, # credentials: credentials, # # ... # ) # # For details on configuring region and credentials see # the [developer guide](/sdk-for-ruby/v3/developer-guide/setup-config.html). # # See {#initialize} for a full list of supported configuration options. class Client < Seahorse::Client::Base include Aws::ClientStubs @identifier = :sts set_api(ClientApi::API) add_plugin(Seahorse::Client::Plugins::ContentLength) add_plugin(Aws::Plugins::CredentialsConfiguration) add_plugin(Aws::Plugins::Logging) add_plugin(Aws::Plugins::ParamConverter) add_plugin(Aws::Plugins::ParamValidator) add_plugin(Aws::Plugins::UserAgent) add_plugin(Aws::Plugins::HelpfulSocketErrors) add_plugin(Aws::Plugins::RetryErrors) add_plugin(Aws::Plugins::GlobalConfiguration) add_plugin(Aws::Plugins::RegionalEndpoint) add_plugin(Aws::Plugins::EndpointDiscovery) add_plugin(Aws::Plugins::EndpointPattern) add_plugin(Aws::Plugins::ResponsePaging) add_plugin(Aws::Plugins::StubResponses) add_plugin(Aws::Plugins::IdempotencyToken) add_plugin(Aws::Plugins::JsonvalueConverter) add_plugin(Aws::Plugins::ClientMetricsPlugin) add_plugin(Aws::Plugins::ClientMetricsSendPlugin) add_plugin(Aws::Plugins::TransferEncoding) add_plugin(Aws::Plugins::HttpChecksum) add_plugin(Aws::Plugins::SignatureV4) add_plugin(Aws::Plugins::Protocols::Query) add_plugin(Aws::STS::Plugins::STSRegionalEndpoints) # @overload initialize(options) # @param [Hash] options # @option options [required, Aws::CredentialProvider] :credentials # Your AWS credentials. This can be an instance of any one of the # following classes: # # * `Aws::Credentials` - Used for configuring static, non-refreshing # credentials. # # * `Aws::SharedCredentials` - Used for loading static credentials from a # shared file, such as `~/.aws/config`. # # * `Aws::AssumeRoleCredentials` - Used when you need to assume a role. # # * `Aws::AssumeRoleWebIdentityCredentials` - Used when you need to # assume a role after providing credentials via the web. # # * `Aws::SSOCredentials` - Used for loading credentials from AWS SSO using an # access token generated from `aws login`. # # * `Aws::ProcessCredentials` - Used for loading credentials from a # process that outputs to stdout. # # * `Aws::InstanceProfileCredentials` - Used for loading credentials # from an EC2 IMDS on an EC2 instance. # # * `Aws::ECSCredentials` - Used for loading credentials from # instances running in ECS. # # * `Aws::CognitoIdentityCredentials` - Used for loading credentials # from the Cognito Identity service. # # When `:credentials` are not configured directly, the following # locations will be searched for credentials: # # * `Aws.config[:credentials]` # * The `:access_key_id`, `:secret_access_key`, and `:session_token` options. # * ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'] # * `~/.aws/credentials` # * `~/.aws/config` # * EC2/ECS IMDS instance profile - When used by default, the timeouts # are very aggressive. Construct and pass an instance of # `Aws::InstanceProfileCredentails` or `Aws::ECSCredentials` to # enable retries and extended timeouts. # # @option options [required, String] :region # The AWS region to connect to. The configured `:region` is # used to determine the service `:endpoint`. When not passed, # a default `:region` is searched for in the following locations: # # * `Aws.config[:region]` # * `ENV['AWS_REGION']` # * `ENV['AMAZON_REGION']` # * `ENV['AWS_DEFAULT_REGION']` # * `~/.aws/credentials` # * `~/.aws/config` # # @option options [String] :access_key_id # # @option options [Boolean] :active_endpoint_cache (false) # When set to `true`, a thread polling for endpoints will be running in # the background every 60 secs (default). Defaults to `false`. # # @option options [Boolean] :adaptive_retry_wait_to_fill (true) # Used only in `adaptive` retry mode. When true, the request will sleep # until there is sufficent client side capacity to retry the request. # When false, the request will raise a `RetryCapacityNotAvailableError` and will # not retry instead of sleeping. # # @option options [Boolean] :client_side_monitoring (false) # When `true`, client-side metrics will be collected for all API requests from # this client. # # @option options [String] :client_side_monitoring_client_id ("") # Allows you to provide an identifier for this client which will be attached to # all generated client side metrics. Defaults to an empty string. # # @option options [String] :client_side_monitoring_host ("127.0.0.1") # Allows you to specify the DNS hostname or IPv4 or IPv6 address that the client # side monitoring agent is running on, where client metrics will be published via UDP. # # @option options [Integer] :client_side_monitoring_port (31000) # Required for publishing client metrics. The port that the client side monitoring # agent is running on, where client metrics will be published via UDP. # # @option options [Aws::ClientSideMonitoring::Publisher] :client_side_monitoring_publisher (Aws::ClientSideMonitoring::Publisher) # Allows you to provide a custom client-side monitoring publisher class. By default, # will use the Client Side Monitoring Agent Publisher. # # @option options [Boolean] :convert_params (true) # When `true`, an attempt is made to coerce request parameters into # the required types. # # @option options [Boolean] :correct_clock_skew (true) # Used only in `standard` and adaptive retry modes. Specifies whether to apply # a clock skew correction and retry requests with skewed client clocks. # # @option options [Boolean] :disable_host_prefix_injection (false) # Set to true to disable SDK automatically adding host prefix # to default service endpoint when available. # # @option options [String] :endpoint # The client endpoint is normally constructed from the `:region` # option. You should only configure an `:endpoint` when connecting # to test or custom endpoints. This should be a valid HTTP(S) URI. # # @option options [Integer] :endpoint_cache_max_entries (1000) # Used for the maximum size limit of the LRU cache storing endpoints data # for endpoint discovery enabled operations. Defaults to 1000. # # @option options [Integer] :endpoint_cache_max_threads (10) # Used for the maximum threads in use for polling endpoints to be cached, defaults to 10. # # @option options [Integer] :endpoint_cache_poll_interval (60) # When :endpoint_discovery and :active_endpoint_cache is enabled, # Use this option to config the time interval in seconds for making # requests fetching endpoints information. Defaults to 60 sec. # # @option options [Boolean] :endpoint_discovery (false) # When set to `true`, endpoint discovery will be enabled for operations when available. # # @option options [Aws::Log::Formatter] :log_formatter (Aws::Log::Formatter.default) # The log formatter. # # @option options [Symbol] :log_level (:info) # The log level to send messages to the `:logger` at. # # @option options [Logger] :logger # The Logger instance to send log messages to. If this option # is not set, logging will be disabled. # # @option options [Integer] :max_attempts (3) # An integer representing the maximum number attempts that will be made for # a single request, including the initial attempt. For example, # setting this value to 5 will result in a request being retried up to # 4 times. Used in `standard` and `adaptive` retry modes. # # @option options [String] :profile ("default") # Used when loading credentials from the shared credentials file # at HOME/.aws/credentials. When not specified, 'default' is used. # # @option options [Proc] :retry_backoff # A proc or lambda used for backoff. Defaults to 2**retries * retry_base_delay. # This option is only used in the `legacy` retry mode. # # @option options [Float] :retry_base_delay (0.3) # The base delay in seconds used by the default backoff function. This option # is only used in the `legacy` retry mode. # # @option options [Symbol] :retry_jitter (:none) # A delay randomiser function used by the default backoff function. # Some predefined functions can be referenced by name - :none, :equal, :full, # otherwise a Proc that takes and returns a number. This option is only used # in the `legacy` retry mode. # # @see https://www.awsarchitectureblog.com/2015/03/backoff.html # # @option options [Integer] :retry_limit (3) # The maximum number of times to retry failed requests. Only # ~ 500 level server errors and certain ~ 400 level client errors # are retried. Generally, these are throttling errors, data # checksum errors, networking errors, timeout errors, auth errors, # endpoint discovery, and errors from expired credentials. # This option is only used in the `legacy` retry mode. # # @option options [Integer] :retry_max_delay (0) # The maximum number of seconds to delay between retries (0 for no limit) # used by the default backoff function. This option is only used in the # `legacy` retry mode. # # @option options [String] :retry_mode ("legacy") # Specifies which retry algorithm to use. Values are: # # * `legacy` - The pre-existing retry behavior. This is default value if # no retry mode is provided. # # * `standard` - A standardized set of retry rules across the AWS SDKs. # This includes support for retry quotas, which limit the number of # unsuccessful retries a client can make. # # * `adaptive` - An experimental retry mode that includes all the # functionality of `standard` mode along with automatic client side # throttling. This is a provisional mode that may change behavior # in the future. # # # @option options [String] :secret_access_key # # @option options [String] :session_token # # @option options [String] :sts_regional_endpoints ("regional") # Passing in 'regional' to enable regional endpoint for STS for all supported # regions (except 'aws-global'). Using 'legacy' mode will force all legacy # regions to resolve to the STS global endpoint. # # @option options [Boolean] :stub_responses (false) # Causes the client to return stubbed responses. By default # fake responses are generated and returned. You can specify # the response data to return or errors to raise by calling # {ClientStubs#stub_responses}. See {ClientStubs} for more information. # # ** Please note ** When response stubbing is enabled, no HTTP # requests are made, and retries are disabled. # # @option options [Boolean] :validate_params (true) # When `true`, request parameters are validated before # sending the request. # # @option options [URI::HTTP,String] :http_proxy A proxy to send # requests through. Formatted like 'http://proxy.com:123'. # # @option options [Float] :http_open_timeout (15) The number of # seconds to wait when opening a HTTP session before raising a # `Timeout::Error`. # # @option options [Integer] :http_read_timeout (60) The default # number of seconds to wait for response data. This value can # safely be set per-request on the session. # # @option options [Float] :http_idle_timeout (5) The number of # seconds a connection is allowed to sit idle before it is # considered stale. Stale connections are closed and removed # from the pool before making a request. # # @option options [Float] :http_continue_timeout (1) The number of # seconds to wait for a 100-continue response before sending the # request body. This option has no effect unless the request has # "Expect" header set to "100-continue". Defaults to `nil` which # disables this behaviour. This value can safely be set per # request on the session. # # @option options [Boolean] :http_wire_trace (false) When `true`, # HTTP debug output will be sent to the `:logger`. # # @option options [Boolean] :ssl_verify_peer (true) When `true`, # SSL peer certificates are verified when establishing a # connection. # # @option options [String] :ssl_ca_bundle Full path to the SSL # certificate authority bundle file that should be used when # verifying peer certificates. If you do not pass # `:ssl_ca_bundle` or `:ssl_ca_directory` the the system default # will be used if available. # # @option options [String] :ssl_ca_directory Full path of the # directory that contains the unbundled SSL certificate # authority files for verifying peer certificates. If you do # not pass `:ssl_ca_bundle` or `:ssl_ca_directory` the the # system default will be used if available. # def initialize(*args) super end # @!group API Operations # Returns a set of temporary security credentials that you can use to # access Amazon Web Services resources that you might not normally have # access to. These temporary credentials consist of an access key ID, a # secret access key, and a security token. Typically, you use # `AssumeRole` within your account or for cross-account access. For a # comparison of `AssumeRole` with other API operations that produce # temporary credentials, see [Requesting Temporary Security # Credentials][1] and [Comparing the STS API operations][2] in the *IAM # User Guide*. # # **Permissions** # # The temporary security credentials created by `AssumeRole` can be used # to make API calls to any Amazon Web Services service with the # following exception: You cannot call the STS `GetFederationToken` or # `GetSessionToken` API operations. # # (Optional) You can pass inline or managed [session policies][3] to # this operation. You can pass a single JSON policy document to use as # an inline session policy. You can also specify up to 10 managed # policies to use as managed session policies. The plaintext that you # use for both inline and managed session policies can't exceed 2,048 # characters. Passing policies to this operation returns new temporary # credentials. The resulting session's permissions are the intersection # of the role's identity-based policy and the session policies. You can # use the role's temporary credentials in subsequent Amazon Web # Services API calls to access resources in the account that owns the # role. You cannot use session policies to grant more permissions than # those allowed by the identity-based policy of the role that is being # assumed. For more information, see [Session Policies][3] in the *IAM # User Guide*. # # To assume a role from a different account, your account must be # trusted by the role. The trust relationship is defined in the role's # trust policy when the role is created. That trust policy states which # accounts are allowed to delegate that access to users in the account. # # A user who wants to access a role in a different account must also # have permissions that are delegated from the user account # administrator. The administrator must attach a policy that allows the # user to call `AssumeRole` for the ARN of the role in the other # account. If the user is in the same account as the role, then you can # do either of the following: # # * Attach a policy to the user (identical to the previous user in a # different account). # # * Add the user as a principal directly in the role's trust policy. # # In this case, the trust policy acts as an IAM resource-based policy. # Users in the same account as the role do not need explicit permission # to assume the role. For more information about trust policies and # resource-based policies, see [IAM Policies][4] in the *IAM User # Guide*. # # **Tags** # # (Optional) You can pass tag key-value pairs to your session. These # tags are called session tags. For more information about session tags, # see [Passing Session Tags in STS][5] in the *IAM User Guide*. # # An administrator must grant you the permissions necessary to pass # session tags. The administrator can also create granular permissions # to allow you to pass only specific session tags. For more information, # see [Tutorial: Using Tags for Attribute-Based Access Control][6] in # the *IAM User Guide*. # # You can set the session tags as transitive. Transitive tags persist # during role chaining. For more information, see [Chaining Roles with # Session Tags][7] in the *IAM User Guide*. # # **Using MFA with AssumeRole** # # (Optional) You can include multi-factor authentication (MFA) # information when you call `AssumeRole`. This is useful for # cross-account scenarios to ensure that the user that assumes the role # has been authenticated with an Amazon Web Services MFA device. In that # scenario, the trust policy of the role being assumed includes a # condition that tests for MFA authentication. If the caller does not # include valid MFA information, the request to assume the role is # denied. The condition in a trust policy that tests for MFA # authentication might look like the following example. # # `"Condition": \{"Bool": \{"aws:MultiFactorAuthPresent": true\}\}` # # For more information, see [Configuring MFA-Protected API Access][8] in # the *IAM User Guide* guide. # # To use MFA with `AssumeRole`, you pass values for the `SerialNumber` # and `TokenCode` parameters. The `SerialNumber` value identifies the # user's hardware or virtual MFA device. The `TokenCode` is the # time-based one-time password (TOTP) that the MFA device produces. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison # [3]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # [4]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html # [5]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html # [6]: https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html # [7]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining # [8]: https://docs.aws.amazon.com/IAM/latest/UserGuide/MFAProtectedAPI.html # # @option params [required, String] :role_arn # The Amazon Resource Name (ARN) of the role to assume. # # @option params [required, String] :role_session_name # An identifier for the assumed role session. # # Use the role session name to uniquely identify a session when the same # role is assumed by different principals or for different reasons. In # cross-account scenarios, the role session name is visible to, and can # be logged by the account that owns the role. The role session name is # also used in the ARN of the assumed role principal. This means that # subsequent cross-account API requests that use the temporary security # credentials will expose the role session name to the external account # in their CloudTrail logs. # # The regex used to validate this parameter is a string of characters # consisting of upper- and lower-case alphanumeric characters with no # spaces. You can also include underscores or any of the following # characters: =,.@- # # @option params [Array<Types::PolicyDescriptorType>] :policy_arns # The Amazon Resource Names (ARNs) of the IAM managed policies that you # want to use as managed session policies. The policies must exist in # the same account as the role. # # This parameter is optional. You can provide up to 10 managed policy # ARNs. However, the plaintext that you use for both inline and managed # session policies can't exceed 2,048 characters. For more information # about ARNs, see [Amazon Resource Names (ARNs) and Amazon Web Services # Service Namespaces][1] in the Amazon Web Services General Reference. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # Passing policies to this operation returns new temporary credentials. # The resulting session's permissions are the intersection of the # role's identity-based policy and the session policies. You can use # the role's temporary credentials in subsequent Amazon Web Services # API calls to access resources in the account that owns the role. You # cannot use session policies to grant more permissions than those # allowed by the identity-based policy of the role that is being # assumed. For more information, see [Session Policies][2] in the *IAM # User Guide*. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # # @option params [String] :policy # An IAM policy in JSON format that you want to use as an inline session # policy. # # This parameter is optional. Passing policies to this operation returns # new temporary credentials. The resulting session's permissions are # the intersection of the role's identity-based policy and the session # policies. You can use the role's temporary credentials in subsequent # Amazon Web Services API calls to access resources in the account that # owns the role. You cannot use session policies to grant more # permissions than those allowed by the identity-based policy of the # role that is being assumed. For more information, see [Session # Policies][1] in the *IAM User Guide*. # # The plaintext that you use for both inline and managed session # policies can't exceed 2,048 characters. The JSON policy characters # can be any ASCII character from the space character to the end of the # valid character list (\\u0020 through \\u00FF). It can also include # the tab (\\u0009), linefeed (\\u000A), and carriage return (\\u000D) # characters. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # # @option params [Integer] :duration_seconds # The duration, in seconds, of the role session. The value specified can # can range from 900 seconds (15 minutes) up to the maximum session # duration that is set for the role. The maximum session duration # setting can have a value from 1 hour to 12 hours. If you specify a # value higher than this setting or the administrator setting (whichever # is lower), the operation fails. For example, if you specify a session # duration of 12 hours, but your administrator set the maximum session # duration to 6 hours, your operation fails. To learn how to view the # maximum value for your role, see [View the Maximum Session Duration # Setting for a Role][1] in the *IAM User Guide*. # # By default, the value is set to `3600` seconds. # # <note markdown="1"> The `DurationSeconds` parameter is separate from the duration of a # console session that you might request using the returned credentials. # The request to the federation endpoint for a console sign-in token # takes a `SessionDuration` parameter that specifies the maximum length # of the console session. For more information, see [Creating a URL that # Enables Federated Users to Access the Management Console][2] in the # *IAM User Guide*. # # </note> # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html # # @option params [Array<Types::Tag>] :tags # A list of session tags that you want to pass. Each session tag # consists of a key name and an associated value. For more information # about session tags, see [Tagging STS Sessions][1] in the *IAM User # Guide*. # # This parameter is optional. You can pass up to 50 session tags. The # plaintext session tag keys can’t exceed 128 characters, and the values # can’t exceed 256 characters. For these and additional limits, see [IAM # and STS Character Limits][2] in the *IAM User Guide*. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # You can pass a session tag with the same key as a tag that is already # attached to the role. When you do, session tags override a role tag # with the same key. # # Tag key–value pairs are not case sensitive, but case is preserved. # This means that you cannot have separate `Department` and `department` # tag keys. Assume that the role has the `Department`=`Marketing` tag # and you pass the `department`=`engineering` session tag. `Department` # and `department` are not saved as separate tags, and the session tag # passed in the request takes precedence over the role tag. # # Additionally, if you used temporary credentials to perform this # operation, the new session inherits any transitive session tags from # the calling session. If you pass a session tag with the same key as an # inherited tag, the operation fails. To view the inherited tags for a # session, see the CloudTrail logs. For more information, see [Viewing # Session Tags in CloudTrail][3] in the *IAM User Guide*. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length # [3]: https://docs.aws.amazon.com/IAM/latest/UserGuide/session-tags.html#id_session-tags_ctlogs # # @option params [Array<String>] :transitive_tag_keys # A list of keys for session tags that you want to set as transitive. If # you set a tag key as transitive, the corresponding key and value # passes to subsequent sessions in a role chain. For more information, # see [Chaining Roles with Session Tags][1] in the *IAM User Guide*. # # This parameter is optional. When you set session tags as transitive, # the session policy and session tags packed binary limit is not # affected. # # If you choose not to specify a transitive tag key, then no tags are # passed from this session to any subsequent sessions. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining # # @option params [String] :external_id # A unique identifier that might be required when you assume a role in # another account. If the administrator of the account to which the role # belongs provided you with an external ID, then provide that value in # the `ExternalId` parameter. This value can be any string, such as a # passphrase or account number. A cross-account role is usually set up # to trust everyone in an account. Therefore, the administrator of the # trusting account might send an external ID to the administrator of the # trusted account. That way, only someone with the ID can assume the # role, rather than everyone in the account. For more information about # the external ID, see [How to Use an External ID When Granting Access # to Your Amazon Web Services Resources to a Third Party][1] in the *IAM # User Guide*. # # The regex used to validate this parameter is a string of characters # consisting of upper- and lower-case alphanumeric characters with no # spaces. You can also include underscores or any of the following # characters: =,.@:/- # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-user_externalid.html # # @option params [String] :serial_number # The identification number of the MFA device that is associated with # the user who is making the `AssumeRole` call. Specify this value if # the trust policy of the role being assumed includes a condition that # requires MFA authentication. The value is either the serial number for # a hardware device (such as `GAHT12345678`) or an Amazon Resource Name # (ARN) for a virtual device (such as # `arn:aws:iam::123456789012:mfa/user`). # # The regex used to validate this parameter is a string of characters # consisting of upper- and lower-case alphanumeric characters with no # spaces. You can also include underscores or any of the following # characters: =,.@- # # @option params [String] :token_code # The value provided by the MFA device, if the trust policy of the role # being assumed requires MFA. (In other words, if the policy includes a # condition that tests for MFA). If the role being assumed requires MFA # and if the `TokenCode` value is missing or expired, the `AssumeRole` # call returns an "access denied" error. # # The format for this parameter, as described by its regex pattern, is a # sequence of six numeric digits. # # @option params [String] :source_identity # The source identity specified by the principal that is calling the # `AssumeRole` operation. # # You can require users to specify a source identity when they assume a # role. You do this by using the `sts:SourceIdentity` condition key in a # role trust policy. You can use source identity information in # CloudTrail logs to determine who took actions with a role. You can use # the `aws:SourceIdentity` condition key to further control access to # Amazon Web Services resources based on the value of source identity. # For more information about using source identity, see [Monitor and # control actions taken with assumed roles][1] in the *IAM User Guide*. # # The regex used to validate this parameter is a string of characters # consisting of upper- and lower-case alphanumeric characters with no # spaces. You can also include underscores or any of the following # characters: =,.@-. You cannot use a value that begins with the text # `aws:`. This prefix is reserved for Amazon Web Services internal use. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_control-access_monitor.html # # @return [Types::AssumeRoleResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::AssumeRoleResponse#credentials #credentials} => Types::Credentials # * {Types::AssumeRoleResponse#assumed_role_user #assumed_role_user} => Types::AssumedRoleUser # * {Types::AssumeRoleResponse#packed_policy_size #packed_policy_size} => Integer # * {Types::AssumeRoleResponse#source_identity #source_identity} => String # # # @example Example: To assume a role # # resp = client.assume_role({ # external_id: "123ABC", # policy: "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:ListAllMyBuckets\",\"Resource\":\"*\"}]}", # role_arn: "arn:aws:iam::123456789012:role/demo", # role_session_name: "testAssumeRoleSession", # tags: [ # { # key: "Project", # value: "Unicorn", # }, # { # key: "Team", # value: "Automation", # }, # { # key: "Cost-Center", # value: "12345", # }, # ], # transitive_tag_keys: [ # "Project", # "Cost-Center", # ], # }) # # resp.to_h outputs the following: # { # assumed_role_user: { # arn: "arn:aws:sts::123456789012:assumed-role/demo/Bob", # assumed_role_id: "ARO123EXAMPLE123:Bob", # }, # credentials: { # access_key_id: "AKIAIOSFODNN7EXAMPLE", # expiration: Time.parse("2011-07-15T23:28:33.359Z"), # secret_access_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY", # session_token: "AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==", # }, # packed_policy_size: 8, # } # # @example Request syntax with placeholder values # # resp = client.assume_role({ # role_arn: "arnType", # required # role_session_name: "roleSessionNameType", # required # policy_arns: [ # { # arn: "arnType", # }, # ], # policy: "sessionPolicyDocumentType", # duration_seconds: 1, # tags: [ # { # key: "tagKeyType", # required # value: "tagValueType", # required # }, # ], # transitive_tag_keys: ["tagKeyType"], # external_id: "externalIdType", # serial_number: "serialNumberType", # token_code: "tokenCodeType", # source_identity: "sourceIdentityType", # }) # # @example Response structure # # resp.credentials.access_key_id #=> String # resp.credentials.secret_access_key #=> String # resp.credentials.session_token #=> String # resp.credentials.expiration #=> Time # resp.assumed_role_user.assumed_role_id #=> String # resp.assumed_role_user.arn #=> String # resp.packed_policy_size #=> Integer # resp.source_identity #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRole AWS API Documentation # # @overload assume_role(params = {}) # @param [Hash] params ({}) def assume_role(params = {}, options = {}) req = build_request(:assume_role, params) req.send_request(options) end # Returns a set of temporary security credentials for users who have # been authenticated via a SAML authentication response. This operation # provides a mechanism for tying an enterprise identity store or # directory to role-based Amazon Web Services access without # user-specific credentials or configuration. For a comparison of # `AssumeRoleWithSAML` with the other API operations that produce # temporary credentials, see [Requesting Temporary Security # Credentials][1] and [Comparing the STS API operations][2] in the *IAM # User Guide*. # # The temporary security credentials returned by this operation consist # of an access key ID, a secret access key, and a security token. # Applications can use these temporary security credentials to sign # calls to Amazon Web Services services. # # **Session Duration** # # By default, the temporary security credentials created by # `AssumeRoleWithSAML` last for one hour. However, you can use the # optional `DurationSeconds` parameter to specify the duration of your # session. Your role session lasts for the duration that you specify, or # until the time specified in the SAML authentication response's # `SessionNotOnOrAfter` value, whichever is shorter. You can provide a # `DurationSeconds` value from 900 seconds (15 minutes) up to the # maximum session duration setting for the role. This setting can have a # value from 1 hour to 12 hours. To learn how to view the maximum value # for your role, see [View the Maximum Session Duration Setting for a # Role][3] in the *IAM User Guide*. The maximum session duration limit # applies when you use the `AssumeRole*` API operations or the # `assume-role*` CLI commands. However the limit does not apply when you # use those operations to create a console URL. For more information, # see [Using IAM Roles][4] in the *IAM User Guide*. # # <note markdown="1"> [Role chaining][5] limits your CLI or Amazon Web Services API role # session to a maximum of one hour. When you use the `AssumeRole` API # operation to assume a role, you can specify the duration of your role # session with the `DurationSeconds` parameter. You can specify a # parameter value of up to 43200 seconds (12 hours), depending on the # maximum session duration setting for your role. However, if you assume # a role using role chaining and provide a `DurationSeconds` parameter # value greater than one hour, the operation fails. # # </note> # # **Permissions** # # The temporary security credentials created by `AssumeRoleWithSAML` can # be used to make API calls to any Amazon Web Services service with the # following exception: you cannot call the STS `GetFederationToken` or # `GetSessionToken` API operations. # # (Optional) You can pass inline or managed [session policies][6] to # this operation. You can pass a single JSON policy document to use as # an inline session policy. You can also specify up to 10 managed # policies to use as managed session policies. The plaintext that you # use for both inline and managed session policies can't exceed 2,048 # characters. Passing policies to this operation returns new temporary # credentials. The resulting session's permissions are the intersection # of the role's identity-based policy and the session policies. You can # use the role's temporary credentials in subsequent Amazon Web # Services API calls to access resources in the account that owns the # role. You cannot use session policies to grant more permissions than # those allowed by the identity-based policy of the role that is being # assumed. For more information, see [Session Policies][6] in the *IAM # User Guide*. # # Calling `AssumeRoleWithSAML` does not require the use of Amazon Web # Services security credentials. The identity of the caller is validated # by using keys in the metadata document that is uploaded for the SAML # provider entity for your identity provider. # # Calling `AssumeRoleWithSAML` can result in an entry in your CloudTrail # logs. The entry includes the value in the `NameID` element of the SAML # assertion. We recommend that you use a `NameIDType` that is not # associated with any personally identifiable information (PII). For # example, you could instead use the persistent identifier # (`urn:oasis:names:tc:SAML:2.0:nameid-format:persistent`). # # **Tags** # # (Optional) You can configure your IdP to pass attributes into your # SAML assertion as session tags. Each session tag consists of a key # name and an associated value. For more information about session tags, # see [Passing Session Tags in STS][7] in the *IAM User Guide*. # # You can pass up to 50 session tags. The plaintext session tag keys # can’t exceed 128 characters and the values can’t exceed 256 # characters. For these and additional limits, see [IAM and STS # Character Limits][8] in the *IAM User Guide*. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # You can pass a session tag with the same key as a tag that is attached # to the role. When you do, session tags override the role's tags with # the same key. # # An administrator must grant you the permissions necessary to pass # session tags. The administrator can also create granular permissions # to allow you to pass only specific session tags. For more information, # see [Tutorial: Using Tags for Attribute-Based Access Control][9] in # the *IAM User Guide*. # # You can set the session tags as transitive. Transitive tags persist # during role chaining. For more information, see [Chaining Roles with # Session Tags][10] in the *IAM User Guide*. # # **SAML Configuration** # # Before your application can call `AssumeRoleWithSAML`, you must # configure your SAML identity provider (IdP) to issue the claims # required by Amazon Web Services. Additionally, you must use Identity # and Access Management (IAM) to create a SAML provider entity in your # Amazon Web Services account that represents your identity provider. # You must also create an IAM role that specifies this SAML provider in # its trust policy. # # For more information, see the following resources: # # * [About SAML 2.0-based Federation][11] in the *IAM User Guide*. # # * [Creating SAML Identity Providers][12] in the *IAM User Guide*. # # * [Configuring a Relying Party and Claims][13] in the *IAM User # Guide*. # # * [Creating a Role for SAML 2.0 Federation][14] in the *IAM User # Guide*. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison # [3]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session # [4]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html # [5]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-role-chaining # [6]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # [7]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html # [8]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length # [9]: https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html # [10]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining # [11]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html # [12]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html # [13]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html # [14]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp_saml.html # # @option params [required, String] :role_arn # The Amazon Resource Name (ARN) of the role that the caller is # assuming. # # @option params [required, String] :principal_arn # The Amazon Resource Name (ARN) of the SAML provider in IAM that # describes the IdP. # # @option params [required, String] :saml_assertion # The base64 encoded SAML authentication response provided by the IdP. # # For more information, see [Configuring a Relying Party and Adding # Claims][1] in the *IAM User Guide*. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/create-role-saml-IdP-tasks.html # # @option params [Array<Types::PolicyDescriptorType>] :policy_arns # The Amazon Resource Names (ARNs) of the IAM managed policies that you # want to use as managed session policies. The policies must exist in # the same account as the role. # # This parameter is optional. You can provide up to 10 managed policy # ARNs. However, the plaintext that you use for both inline and managed # session policies can't exceed 2,048 characters. For more information # about ARNs, see [Amazon Resource Names (ARNs) and Amazon Web Services # Service Namespaces][1] in the Amazon Web Services General Reference. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # Passing policies to this operation returns new temporary credentials. # The resulting session's permissions are the intersection of the # role's identity-based policy and the session policies. You can use # the role's temporary credentials in subsequent Amazon Web Services # API calls to access resources in the account that owns the role. You # cannot use session policies to grant more permissions than those # allowed by the identity-based policy of the role that is being # assumed. For more information, see [Session Policies][2] in the *IAM # User Guide*. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # # @option params [String] :policy # An IAM policy in JSON format that you want to use as an inline session # policy. # # This parameter is optional. Passing policies to this operation returns # new temporary credentials. The resulting session's permissions are # the intersection of the role's identity-based policy and the session # policies. You can use the role's temporary credentials in subsequent # Amazon Web Services API calls to access resources in the account that # owns the role. You cannot use session policies to grant more # permissions than those allowed by the identity-based policy of the # role that is being assumed. For more information, see [Session # Policies][1] in the *IAM User Guide*. # # The plaintext that you use for both inline and managed session # policies can't exceed 2,048 characters. The JSON policy characters # can be any ASCII character from the space character to the end of the # valid character list (\\u0020 through \\u00FF). It can also include # the tab (\\u0009), linefeed (\\u000A), and carriage return (\\u000D) # characters. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # # @option params [Integer] :duration_seconds # The duration, in seconds, of the role session. Your role session lasts # for the duration that you specify for the `DurationSeconds` parameter, # or until the time specified in the SAML authentication response's # `SessionNotOnOrAfter` value, whichever is shorter. You can provide a # `DurationSeconds` value from 900 seconds (15 minutes) up to the # maximum session duration setting for the role. This setting can have a # value from 1 hour to 12 hours. If you specify a value higher than this # setting, the operation fails. For example, if you specify a session # duration of 12 hours, but your administrator set the maximum session # duration to 6 hours, your operation fails. To learn how to view the # maximum value for your role, see [View the Maximum Session Duration # Setting for a Role][1] in the *IAM User Guide*. # # By default, the value is set to `3600` seconds. # # <note markdown="1"> The `DurationSeconds` parameter is separate from the duration of a # console session that you might request using the returned credentials. # The request to the federation endpoint for a console sign-in token # takes a `SessionDuration` parameter that specifies the maximum length # of the console session. For more information, see [Creating a URL that # Enables Federated Users to Access the Management Console][2] in the # *IAM User Guide*. # # </note> # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html # # @return [Types::AssumeRoleWithSAMLResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::AssumeRoleWithSAMLResponse#credentials #credentials} => Types::Credentials # * {Types::AssumeRoleWithSAMLResponse#assumed_role_user #assumed_role_user} => Types::AssumedRoleUser # * {Types::AssumeRoleWithSAMLResponse#packed_policy_size #packed_policy_size} => Integer # * {Types::AssumeRoleWithSAMLResponse#subject #subject} => String # * {Types::AssumeRoleWithSAMLResponse#subject_type #subject_type} => String # * {Types::AssumeRoleWithSAMLResponse#issuer #issuer} => String # * {Types::AssumeRoleWithSAMLResponse#audience #audience} => String # * {Types::AssumeRoleWithSAMLResponse#name_qualifier #name_qualifier} => String # * {Types::AssumeRoleWithSAMLResponse#source_identity #source_identity} => String # # # @example Example: To assume a role using a SAML assertion # # resp = client.assume_role_with_saml({ # duration_seconds: 3600, # principal_arn: "arn:aws:iam::123456789012:saml-provider/SAML-test", # role_arn: "arn:aws:iam::123456789012:role/TestSaml", # saml_assertion: "VERYLONGENCODEDASSERTIONEXAMPLExzYW1sOkF1ZGllbmNlPmJsYW5rPC9zYW1sOkF1ZGllbmNlPjwvc2FtbDpBdWRpZW5jZVJlc3RyaWN0aW9uPjwvc2FtbDpDb25kaXRpb25zPjxzYW1sOlN1YmplY3Q+PHNhbWw6TmFtZUlEIEZvcm1hdD0idXJuOm9hc2lzOm5hbWVzOnRjOlNBTUw6Mi4wOm5hbWVpZC1mb3JtYXQ6dHJhbnNpZW50Ij5TYW1sRXhhbXBsZTwvc2FtbDpOYW1lSUQ+PHNhbWw6U3ViamVjdENvbmZpcm1hdGlvbiBNZXRob2Q9InVybjpvYXNpczpuYW1lczp0YzpTQU1MOjIuMDpjbTpiZWFyZXIiPjxzYW1sOlN1YmplY3RDb25maXJtYXRpb25EYXRhIE5vdE9uT3JBZnRlcj0iMjAxOS0xMS0wMVQyMDoyNTowNS4xNDVaIiBSZWNpcGllbnQ9Imh0dHBzOi8vc2lnbmluLmF3cy5hbWF6b24uY29tL3NhbWwiLz48L3NhbWw6U3ViamVjdENvbmZpcm1hdGlvbj48L3NhbWw6U3ViamVjdD48c2FtbDpBdXRoblN0YXRlbWVudCBBdXRoPD94bWwgdmpSZXNwb25zZT4=", # }) # # resp.to_h outputs the following: # { # assumed_role_user: { # arn: "arn:aws:sts::123456789012:assumed-role/TestSaml", # assumed_role_id: "ARO456EXAMPLE789:TestSaml", # }, # audience: "https://signin.aws.amazon.com/saml", # credentials: { # access_key_id: "ASIAV3ZUEFP6EXAMPLE", # expiration: Time.parse("2019-11-01T20:26:47Z"), # secret_access_key: "8P+SQvWIuLnKhh8d++jpw0nNmQRBZvNEXAMPLEKEY", # session_token: "IQoJb3JpZ2luX2VjEOz////////////////////wEXAMPLEtMSJHMEUCIDoKK3JH9uGQE1z0sINr5M4jk+Na8KHDcCYRVjJCZEvOAiEA3OvJGtw1EcViOleS2vhs8VdCKFJQWPQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==", # }, # issuer: "https://integ.example.com/idp/shibboleth", # name_qualifier: "SbdGOnUkh1i4+EXAMPLExL/jEvs=", # packed_policy_size: 6, # subject: "SamlExample", # subject_type: "transient", # } # # @example Request syntax with placeholder values # # resp = client.assume_role_with_saml({ # role_arn: "arnType", # required # principal_arn: "arnType", # required # saml_assertion: "SAMLAssertionType", # required # policy_arns: [ # { # arn: "arnType", # }, # ], # policy: "sessionPolicyDocumentType", # duration_seconds: 1, # }) # # @example Response structure # # resp.credentials.access_key_id #=> String # resp.credentials.secret_access_key #=> String # resp.credentials.session_token #=> String # resp.credentials.expiration #=> Time # resp.assumed_role_user.assumed_role_id #=> String # resp.assumed_role_user.arn #=> String # resp.packed_policy_size #=> Integer # resp.subject #=> String # resp.subject_type #=> String # resp.issuer #=> String # resp.audience #=> String # resp.name_qualifier #=> String # resp.source_identity #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithSAML AWS API Documentation # # @overload assume_role_with_saml(params = {}) # @param [Hash] params ({}) def assume_role_with_saml(params = {}, options = {}) req = build_request(:assume_role_with_saml, params) req.send_request(options) end # Returns a set of temporary security credentials for users who have # been authenticated in a mobile or web application with a web identity # provider. Example providers include Amazon Cognito, Login with Amazon, # Facebook, Google, or any OpenID Connect-compatible identity provider. # # <note markdown="1"> For mobile applications, we recommend that you use Amazon Cognito. You # can use Amazon Cognito with the [Amazon Web Services SDK for iOS # Developer Guide][1] and the [Amazon Web Services SDK for Android # Developer Guide][2] to uniquely identify a user. You can also supply # the user with a consistent identity throughout the lifetime of an # application. # # To learn more about Amazon Cognito, see [Amazon Cognito Overview][3] # in *Amazon Web Services SDK for Android Developer Guide* and [Amazon # Cognito Overview][4] in the *Amazon Web Services SDK for iOS Developer # Guide*. # # </note> # # Calling `AssumeRoleWithWebIdentity` does not require the use of Amazon # Web Services security credentials. Therefore, you can distribute an # application (for example, on mobile devices) that requests temporary # security credentials without including long-term Amazon Web Services # credentials in the application. You also don't need to deploy # server-based proxy services that use long-term Amazon Web Services # credentials. Instead, the identity of the caller is validated by using # a token from the web identity provider. For a comparison of # `AssumeRoleWithWebIdentity` with the other API operations that produce # temporary credentials, see [Requesting Temporary Security # Credentials][5] and [Comparing the STS API operations][6] in the *IAM # User Guide*. # # The temporary security credentials returned by this API consist of an # access key ID, a secret access key, and a security token. Applications # can use these temporary security credentials to sign calls to Amazon # Web Services service API operations. # # **Session Duration** # # By default, the temporary security credentials created by # `AssumeRoleWithWebIdentity` last for one hour. However, you can use # the optional `DurationSeconds` parameter to specify the duration of # your session. You can provide a value from 900 seconds (15 minutes) up # to the maximum session duration setting for the role. This setting can # have a value from 1 hour to 12 hours. To learn how to view the maximum # value for your role, see [View the Maximum Session Duration Setting # for a Role][7] in the *IAM User Guide*. The maximum session duration # limit applies when you use the `AssumeRole*` API operations or the # `assume-role*` CLI commands. However the limit does not apply when you # use those operations to create a console URL. For more information, # see [Using IAM Roles][8] in the *IAM User Guide*. # # **Permissions** # # The temporary security credentials created by # `AssumeRoleWithWebIdentity` can be used to make API calls to any # Amazon Web Services service with the following exception: you cannot # call the STS `GetFederationToken` or `GetSessionToken` API operations. # # (Optional) You can pass inline or managed [session policies][9] to # this operation. You can pass a single JSON policy document to use as # an inline session policy. You can also specify up to 10 managed # policies to use as managed session policies. The plaintext that you # use for both inline and managed session policies can't exceed 2,048 # characters. Passing policies to this operation returns new temporary # credentials. The resulting session's permissions are the intersection # of the role's identity-based policy and the session policies. You can # use the role's temporary credentials in subsequent Amazon Web # Services API calls to access resources in the account that owns the # role. You cannot use session policies to grant more permissions than # those allowed by the identity-based policy of the role that is being # assumed. For more information, see [Session Policies][9] in the *IAM # User Guide*. # # **Tags** # # (Optional) You can configure your IdP to pass attributes into your web # identity token as session tags. Each session tag consists of a key # name and an associated value. For more information about session tags, # see [Passing Session Tags in STS][10] in the *IAM User Guide*. # # You can pass up to 50 session tags. The plaintext session tag keys # can’t exceed 128 characters and the values can’t exceed 256 # characters. For these and additional limits, see [IAM and STS # Character Limits][11] in the *IAM User Guide*. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # You can pass a session tag with the same key as a tag that is attached # to the role. When you do, the session tag overrides the role tag with # the same key. # # An administrator must grant you the permissions necessary to pass # session tags. The administrator can also create granular permissions # to allow you to pass only specific session tags. For more information, # see [Tutorial: Using Tags for Attribute-Based Access Control][12] in # the *IAM User Guide*. # # You can set the session tags as transitive. Transitive tags persist # during role chaining. For more information, see [Chaining Roles with # Session Tags][13] in the *IAM User Guide*. # # **Identities** # # Before your application can call `AssumeRoleWithWebIdentity`, you must # have an identity token from a supported identity provider and create a # role that the application can assume. The role that your application # assumes must trust the identity provider that is associated with the # identity token. In other words, the identity provider must be # specified in the role's trust policy. # # Calling `AssumeRoleWithWebIdentity` can result in an entry in your # CloudTrail logs. The entry includes the [Subject][14] of the provided # web identity token. We recommend that you avoid using any personally # identifiable information (PII) in this field. For example, you could # instead use a GUID or a pairwise identifier, as [suggested in the OIDC # specification][15]. # # For more information about how to use web identity federation and the # `AssumeRoleWithWebIdentity` API, see the following resources: # # * [Using Web Identity Federation API Operations for Mobile Apps][16] # and [Federation Through a Web-based Identity Provider][17]. # # * [ Web Identity Federation Playground][18]. Walk through the process # of authenticating through Login with Amazon, Facebook, or Google, # getting temporary security credentials, and then using those # credentials to make a request to Amazon Web Services. # # * [Amazon Web Services SDK for iOS Developer Guide][1] and [Amazon Web # Services SDK for Android Developer Guide][2]. These toolkits contain # sample apps that show how to invoke the identity providers. The # toolkits then show how to use the information from these providers # to get and use temporary security credentials. # # * [Web Identity Federation with Mobile Applications][19]. This article # discusses web identity federation and shows an example of how to use # web identity federation to get access to content in Amazon S3. # # # # [1]: http://aws.amazon.com/sdkforios/ # [2]: http://aws.amazon.com/sdkforandroid/ # [3]: https://docs.aws.amazon.com/mobile/sdkforandroid/developerguide/cognito-auth.html#d0e840 # [4]: https://docs.aws.amazon.com/mobile/sdkforios/developerguide/cognito-auth.html#d0e664 # [5]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html # [6]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison # [7]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session # [8]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html # [9]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # [10]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html # [11]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length # [12]: https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html # [13]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html#id_session-tags_role-chaining # [14]: http://openid.net/specs/openid-connect-core-1_0.html#Claims # [15]: http://openid.net/specs/openid-connect-core-1_0.html#SubjectIDTypes # [16]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_oidc_manual.html # [17]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity # [18]: https://aws.amazon.com/blogs/aws/the-aws-web-identity-federation-playground/ # [19]: http://aws.amazon.com/articles/web-identity-federation-with-mobile-applications # # @option params [required, String] :role_arn # The Amazon Resource Name (ARN) of the role that the caller is # assuming. # # @option params [required, String] :role_session_name # An identifier for the assumed role session. Typically, you pass the # name or identifier that is associated with the user who is using your # application. That way, the temporary security credentials that your # application will use are associated with that user. This session name # is included as part of the ARN and assumed role ID in the # `AssumedRoleUser` response element. # # The regex used to validate this parameter is a string of characters # consisting of upper- and lower-case alphanumeric characters with no # spaces. You can also include underscores or any of the following # characters: =,.@- # # @option params [required, String] :web_identity_token # The OAuth 2.0 access token or OpenID Connect ID token that is provided # by the identity provider. Your application must get this token by # authenticating the user who is using your application with a web # identity provider before the application makes an # `AssumeRoleWithWebIdentity` call. # # @option params [String] :provider_id # The fully qualified host component of the domain name of the identity # provider. # # Specify this value only for OAuth 2.0 access tokens. Currently # `www.amazon.com` and `graph.facebook.com` are the only supported # identity providers for OAuth 2.0 access tokens. Do not include URL # schemes and port numbers. # # Do not specify this value for OpenID Connect ID tokens. # # @option params [Array<Types::PolicyDescriptorType>] :policy_arns # The Amazon Resource Names (ARNs) of the IAM managed policies that you # want to use as managed session policies. The policies must exist in # the same account as the role. # # This parameter is optional. You can provide up to 10 managed policy # ARNs. However, the plaintext that you use for both inline and managed # session policies can't exceed 2,048 characters. For more information # about ARNs, see [Amazon Resource Names (ARNs) and Amazon Web Services # Service Namespaces][1] in the Amazon Web Services General Reference. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # Passing policies to this operation returns new temporary credentials. # The resulting session's permissions are the intersection of the # role's identity-based policy and the session policies. You can use # the role's temporary credentials in subsequent Amazon Web Services # API calls to access resources in the account that owns the role. You # cannot use session policies to grant more permissions than those # allowed by the identity-based policy of the role that is being # assumed. For more information, see [Session Policies][2] in the *IAM # User Guide*. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # # @option params [String] :policy # An IAM policy in JSON format that you want to use as an inline session # policy. # # This parameter is optional. Passing policies to this operation returns # new temporary credentials. The resulting session's permissions are # the intersection of the role's identity-based policy and the session # policies. You can use the role's temporary credentials in subsequent # Amazon Web Services API calls to access resources in the account that # owns the role. You cannot use session policies to grant more # permissions than those allowed by the identity-based policy of the # role that is being assumed. For more information, see [Session # Policies][1] in the *IAM User Guide*. # # The plaintext that you use for both inline and managed session # policies can't exceed 2,048 characters. The JSON policy characters # can be any ASCII character from the space character to the end of the # valid character list (\\u0020 through \\u00FF). It can also include # the tab (\\u0009), linefeed (\\u000A), and carriage return (\\u000D) # characters. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # # @option params [Integer] :duration_seconds # The duration, in seconds, of the role session. The value can range # from 900 seconds (15 minutes) up to the maximum session duration # setting for the role. This setting can have a value from 1 hour to 12 # hours. If you specify a value higher than this setting, the operation # fails. For example, if you specify a session duration of 12 hours, but # your administrator set the maximum session duration to 6 hours, your # operation fails. To learn how to view the maximum value for your role, # see [View the Maximum Session Duration Setting for a Role][1] in the # *IAM User Guide*. # # By default, the value is set to `3600` seconds. # # <note markdown="1"> The `DurationSeconds` parameter is separate from the duration of a # console session that you might request using the returned credentials. # The request to the federation endpoint for a console sign-in token # takes a `SessionDuration` parameter that specifies the maximum length # of the console session. For more information, see [Creating a URL that # Enables Federated Users to Access the Management Console][2] in the # *IAM User Guide*. # # </note> # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use.html#id_roles_use_view-role-max-session # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_enable-console-custom-url.html # # @return [Types::AssumeRoleWithWebIdentityResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::AssumeRoleWithWebIdentityResponse#credentials #credentials} => Types::Credentials # * {Types::AssumeRoleWithWebIdentityResponse#subject_from_web_identity_token #subject_from_web_identity_token} => String # * {Types::AssumeRoleWithWebIdentityResponse#assumed_role_user #assumed_role_user} => Types::AssumedRoleUser # * {Types::AssumeRoleWithWebIdentityResponse#packed_policy_size #packed_policy_size} => Integer # * {Types::AssumeRoleWithWebIdentityResponse#provider #provider} => String # * {Types::AssumeRoleWithWebIdentityResponse#audience #audience} => String # * {Types::AssumeRoleWithWebIdentityResponse#source_identity #source_identity} => String # # # @example Example: To assume a role as an OpenID Connect-federated user # # resp = client.assume_role_with_web_identity({ # duration_seconds: 3600, # policy: "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:ListAllMyBuckets\",\"Resource\":\"*\"}]}", # provider_id: "www.amazon.com", # role_arn: "arn:aws:iam::123456789012:role/FederatedWebIdentityRole", # role_session_name: "app1", # web_identity_token: "Atza%7CIQEBLjAsAhRFiXuWpUXuRvQ9PZL3GMFcYevydwIUFAHZwXZXXXXXXXXJnrulxKDHwy87oGKPznh0D6bEQZTSCzyoCtL_8S07pLpr0zMbn6w1lfVZKNTBdDansFBmtGnIsIapjI6xKR02Yc_2bQ8LZbUXSGm6Ry6_BG7PrtLZtj_dfCTj92xNGed-CrKqjG7nPBjNIL016GGvuS5gSvPRUxWES3VYfm1wl7WTI7jn-Pcb6M-buCgHhFOzTQxod27L9CqnOLio7N3gZAGpsp6n1-AJBOCJckcyXe2c6uD0srOJeZlKUm2eTDVMf8IehDVI0r1QOnTV6KzzAI3OY87Vd_cVMQ", # }) # # resp.to_h outputs the following: # { # assumed_role_user: { # arn: "arn:aws:sts::123456789012:assumed-role/FederatedWebIdentityRole/app1", # assumed_role_id: "AROACLKWSDQRAOEXAMPLE:app1", # }, # audience: "client.5498841531868486423.1548@apps.example.com", # credentials: { # access_key_id: "AKIAIOSFODNN7EXAMPLE", # expiration: Time.parse("2014-10-24T23:00:23Z"), # secret_access_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY", # session_token: "AQoDYXdzEE0a8ANXXXXXXXXNO1ewxE5TijQyp+IEXAMPLE", # }, # packed_policy_size: 123, # provider: "www.amazon.com", # subject_from_web_identity_token: "amzn1.account.AF6RHO7KZU5XRVQJGXK6HEXAMPLE", # } # # @example Request syntax with placeholder values # # resp = client.assume_role_with_web_identity({ # role_arn: "arnType", # required # role_session_name: "roleSessionNameType", # required # web_identity_token: "clientTokenType", # required # provider_id: "urlType", # policy_arns: [ # { # arn: "arnType", # }, # ], # policy: "sessionPolicyDocumentType", # duration_seconds: 1, # }) # # @example Response structure # # resp.credentials.access_key_id #=> String # resp.credentials.secret_access_key #=> String # resp.credentials.session_token #=> String # resp.credentials.expiration #=> Time # resp.subject_from_web_identity_token #=> String # resp.assumed_role_user.assumed_role_id #=> String # resp.assumed_role_user.arn #=> String # resp.packed_policy_size #=> Integer # resp.provider #=> String # resp.audience #=> String # resp.source_identity #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/AssumeRoleWithWebIdentity AWS API Documentation # # @overload assume_role_with_web_identity(params = {}) # @param [Hash] params ({}) def assume_role_with_web_identity(params = {}, options = {}) req = build_request(:assume_role_with_web_identity, params) req.send_request(options) end # Decodes additional information about the authorization status of a # request from an encoded message returned in response to an Amazon Web # Services request. # # For example, if a user is not authorized to perform an operation that # he or she has requested, the request returns a # `Client.UnauthorizedOperation` response (an HTTP 403 response). Some # Amazon Web Services operations additionally return an encoded message # that can provide details about this authorization failure. # # <note markdown="1"> Only certain Amazon Web Services operations return an encoded # authorization message. The documentation for an individual operation # indicates whether that operation returns an encoded message in # addition to returning an HTTP code. # # </note> # # The message is encoded because the details of the authorization status # can constitute privileged information that the user who requested the # operation should not see. To decode an authorization status message, a # user must be granted permissions via an IAM policy to request the # `DecodeAuthorizationMessage` (`sts:DecodeAuthorizationMessage`) # action. # # The decoded message includes the following type of information: # # * Whether the request was denied due to an explicit deny or due to the # absence of an explicit allow. For more information, see [Determining # Whether a Request is Allowed or Denied][1] in the *IAM User Guide*. # # * The principal who made the request. # # * The requested action. # # * The requested resource. # # * The values of condition keys in the context of the user's request. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_evaluation-logic.html#policy-eval-denyallow # # @option params [required, String] :encoded_message # The encoded message that was returned with the response. # # @return [Types::DecodeAuthorizationMessageResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::DecodeAuthorizationMessageResponse#decoded_message #decoded_message} => String # # # @example Example: To decode information about an authorization status of a request # # resp = client.decode_authorization_message({ # encoded_message: "<encoded-message>", # }) # # resp.to_h outputs the following: # { # decoded_message: "{\"allowed\": \"false\",\"explicitDeny\": \"false\",\"matchedStatements\": \"\",\"failures\": \"\",\"context\": {\"principal\": {\"id\": \"AIDACKCEVSQ6C2EXAMPLE\",\"name\": \"Bob\",\"arn\": \"arn:aws:iam::123456789012:user/Bob\"},\"action\": \"ec2:StopInstances\",\"resource\": \"arn:aws:ec2:us-east-1:123456789012:instance/i-dd01c9bd\",\"conditions\": [{\"item\": {\"key\": \"ec2:Tenancy\",\"values\": [\"default\"]},{\"item\": {\"key\": \"ec2:ResourceTag/elasticbeanstalk:environment-name\",\"values\": [\"Default-Environment\"]}},(Additional items ...)]}}", # } # # @example Request syntax with placeholder values # # resp = client.decode_authorization_message({ # encoded_message: "encodedMessageType", # required # }) # # @example Response structure # # resp.decoded_message #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/DecodeAuthorizationMessage AWS API Documentation # # @overload decode_authorization_message(params = {}) # @param [Hash] params ({}) def decode_authorization_message(params = {}, options = {}) req = build_request(:decode_authorization_message, params) req.send_request(options) end # Returns the account identifier for the specified access key ID. # # Access keys consist of two parts: an access key ID (for example, # `AKIAIOSFODNN7EXAMPLE`) and a secret access key (for example, # `wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY`). For more information # about access keys, see [Managing Access Keys for IAM Users][1] in the # *IAM User Guide*. # # When you pass an access key ID to this operation, it returns the ID of # the Amazon Web Services account to which the keys belong. Access key # IDs beginning with `AKIA` are long-term credentials for an IAM user or # the Amazon Web Services account root user. Access key IDs beginning # with `ASIA` are temporary credentials that are created using STS # operations. If the account in the response belongs to you, you can # sign in as the root user and review your root user access keys. Then, # you can pull a [credentials report][2] to learn which IAM user owns # the keys. To learn who requested the temporary credentials for an # `ASIA` access key, view the STS events in your [CloudTrail logs][3] in # the *IAM User Guide*. # # This operation does not indicate the state of the access key. The key # might be active, inactive, or deleted. Active keys might not have # permissions to perform an operation. Providing a deleted access key # might return an error that the key doesn't exist. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_access-keys.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_getting-report.html # [3]: https://docs.aws.amazon.com/IAM/latest/UserGuide/cloudtrail-integration.html # # @option params [required, String] :access_key_id # The identifier of an access key. # # This parameter allows (through its regex pattern) a string of # characters that can consist of any upper- or lowercase letter or # digit. # # @return [Types::GetAccessKeyInfoResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::GetAccessKeyInfoResponse#account #account} => String # # @example Request syntax with placeholder values # # resp = client.get_access_key_info({ # access_key_id: "accessKeyIdType", # required # }) # # @example Response structure # # resp.account #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetAccessKeyInfo AWS API Documentation # # @overload get_access_key_info(params = {}) # @param [Hash] params ({}) def get_access_key_info(params = {}, options = {}) req = build_request(:get_access_key_info, params) req.send_request(options) end # Returns details about the IAM user or role whose credentials are used # to call the operation. # # <note markdown="1"> No permissions are required to perform this operation. If an # administrator adds a policy to your IAM user or role that explicitly # denies access to the `sts:GetCallerIdentity` action, you can still # perform this operation. Permissions are not required because the same # information is returned when an IAM user or role is denied access. To # view an example response, see [I Am Not Authorized to Perform: # iam:DeleteVirtualMFADevice][1] in the *IAM User Guide*. # # </note> # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_general.html#troubleshoot_general_access-denied-delete-mfa # # @return [Types::GetCallerIdentityResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::GetCallerIdentityResponse#user_id #user_id} => String # * {Types::GetCallerIdentityResponse#account #account} => String # * {Types::GetCallerIdentityResponse#arn #arn} => String # # # @example Example: To get details about a calling IAM user # # # This example shows a request and response made with the credentials for a user named Alice in the AWS account # # 123456789012. # # resp = client.get_caller_identity({ # }) # # resp.to_h outputs the following: # { # account: "123456789012", # arn: "arn:aws:iam::123456789012:user/Alice", # user_id: "AKIAI44QH8DHBEXAMPLE", # } # # @example Example: To get details about a calling user federated with AssumeRole # # # This example shows a request and response made with temporary credentials created by AssumeRole. The name of the assumed # # role is my-role-name, and the RoleSessionName is set to my-role-session-name. # # resp = client.get_caller_identity({ # }) # # resp.to_h outputs the following: # { # account: "123456789012", # arn: "arn:aws:sts::123456789012:assumed-role/my-role-name/my-role-session-name", # user_id: "AKIAI44QH8DHBEXAMPLE:my-role-session-name", # } # # @example Example: To get details about a calling user federated with GetFederationToken # # # This example shows a request and response made with temporary credentials created by using GetFederationToken. The Name # # parameter is set to my-federated-user-name. # # resp = client.get_caller_identity({ # }) # # resp.to_h outputs the following: # { # account: "123456789012", # arn: "arn:aws:sts::123456789012:federated-user/my-federated-user-name", # user_id: "123456789012:my-federated-user-name", # } # # @example Response structure # # resp.user_id #=> String # resp.account #=> String # resp.arn #=> String # # @see http://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetCallerIdentity AWS API Documentation # # @overload get_caller_identity(params = {}) # @param [Hash] params ({}) def get_caller_identity(params = {}, options = {}) req = build_request(:get_caller_identity, params) req.send_request(options) end # Returns a set of temporary security credentials (consisting of an # access key ID, a secret access key, and a security token) for a # federated user. A typical use is in a proxy application that gets # temporary security credentials on behalf of distributed applications # inside a corporate network. You must call the `GetFederationToken` # operation using the long-term security credentials of an IAM user. As # a result, this call is appropriate in contexts where those credentials # can be safely stored, usually in a server-based application. For a # comparison of `GetFederationToken` with the other API operations that # produce temporary credentials, see [Requesting Temporary Security # Credentials][1] and [Comparing the STS API operations][2] in the *IAM # User Guide*. # # <note markdown="1"> You can create a mobile-based or browser-based app that can # authenticate users using a web identity provider like Login with # Amazon, Facebook, Google, or an OpenID Connect-compatible identity # provider. In this case, we recommend that you use [Amazon Cognito][3] # or `AssumeRoleWithWebIdentity`. For more information, see [Federation # Through a Web-based Identity Provider][4] in the *IAM User Guide*. # # </note> # # You can also call `GetFederationToken` using the security credentials # of an Amazon Web Services account root user, but we do not recommend # it. Instead, we recommend that you create an IAM user for the purpose # of the proxy application. Then attach a policy to the IAM user that # limits federated users to only the actions and resources that they # need to access. For more information, see [IAM Best Practices][5] in # the *IAM User Guide*. # # **Session duration** # # The temporary credentials are valid for the specified duration, from # 900 seconds (15 minutes) up to a maximum of 129,600 seconds (36 # hours). The default session duration is 43,200 seconds (12 hours). # Temporary credentials that are obtained by using Amazon Web Services # account root user credentials have a maximum duration of 3,600 seconds # (1 hour). # # **Permissions** # # You can use the temporary credentials created by `GetFederationToken` # in any Amazon Web Services service except the following: # # * You cannot call any IAM operations using the CLI or the Amazon Web # Services API. # # * You cannot call any STS operations except `GetCallerIdentity`. # # You must pass an inline or managed [session policy][6] to this # operation. You can pass a single JSON policy document to use as an # inline session policy. You can also specify up to 10 managed policies # to use as managed session policies. The plaintext that you use for # both inline and managed session policies can't exceed 2,048 # characters. # # Though the session policy parameters are optional, if you do not pass # a policy, then the resulting federated user session has no # permissions. When you pass session policies, the session permissions # are the intersection of the IAM user policies and the session policies # that you pass. This gives you a way to further restrict the # permissions for a federated user. You cannot use session policies to # grant more permissions than those that are defined in the permissions # policy of the IAM user. For more information, see [Session # Policies][6] in the *IAM User Guide*. For information about using # `GetFederationToken` to create temporary security credentials, see # [GetFederationToken—Federation Through a Custom Identity Broker][7]. # # You can use the credentials to access a resource that has a # resource-based policy. If that policy specifically references the # federated user session in the `Principal` element of the policy, the # session has the permissions allowed by the policy. These permissions # are granted in addition to the permissions granted by the session # policies. # # **Tags** # # (Optional) You can pass tag key-value pairs to your session. These are # called session tags. For more information about session tags, see # [Passing Session Tags in STS][8] in the *IAM User Guide*. # # <note markdown="1"> You can create a mobile-based or browser-based app that can # authenticate users using a web identity provider like Login with # Amazon, Facebook, Google, or an OpenID Connect-compatible identity # provider. In this case, we recommend that you use [Amazon Cognito][3] # or `AssumeRoleWithWebIdentity`. For more information, see [Federation # Through a Web-based Identity Provider][4] in the *IAM User Guide*. # # </note> # # You can also call `GetFederationToken` using the security credentials # of an Amazon Web Services account root user, but we do not recommend # it. Instead, we recommend that you create an IAM user for the purpose # of the proxy application. Then attach a policy to the IAM user that # limits federated users to only the actions and resources that they # need to access. For more information, see [IAM Best Practices][5] in # the *IAM User Guide*. # # **Session duration** # # The temporary credentials are valid for the specified duration, from # 900 seconds (15 minutes) up to a maximum of 129,600 seconds (36 # hours). The default session duration is 43,200 seconds (12 hours). # Temporary credentials that are obtained by using Amazon Web Services # account root user credentials have a maximum duration of 3,600 seconds # (1 hour). # # **Permissions** # # You can use the temporary credentials created by `GetFederationToken` # in any Amazon Web Services service except the following: # # * You cannot call any IAM operations using the CLI or the Amazon Web # Services API. # # * You cannot call any STS operations except `GetCallerIdentity`. # # You must pass an inline or managed [session policy][6] to this # operation. You can pass a single JSON policy document to use as an # inline session policy. You can also specify up to 10 managed policies # to use as managed session policies. The plain text that you use for # both inline and managed session policies can't exceed 2,048 # characters. # # Though the session policy parameters are optional, if you do not pass # a policy, then the resulting federated user session has no # permissions. When you pass session policies, the session permissions # are the intersection of the IAM user policies and the session policies # that you pass. This gives you a way to further restrict the # permissions for a federated user. You cannot use session policies to # grant more permissions than those that are defined in the permissions # policy of the IAM user. For more information, see [Session # Policies][6] in the *IAM User Guide*. For information about using # `GetFederationToken` to create temporary security credentials, see # [GetFederationToken—Federation Through a Custom Identity Broker][7]. # # You can use the credentials to access a resource that has a # resource-based policy. If that policy specifically references the # federated user session in the `Principal` element of the policy, the # session has the permissions allowed by the policy. These permissions # are granted in addition to the permissions granted by the session # policies. # # **Tags** # # (Optional) You can pass tag key-value pairs to your session. These are # called session tags. For more information about session tags, see # [Passing Session Tags in STS][8] in the *IAM User Guide*. # # An administrator must grant you the permissions necessary to pass # session tags. The administrator can also create granular permissions # to allow you to pass only specific session tags. For more information, # see [Tutorial: Using Tags for Attribute-Based Access Control][9] in # the *IAM User Guide*. # # Tag key–value pairs are not case sensitive, but case is preserved. # This means that you cannot have separate `Department` and `department` # tag keys. Assume that the user that you are federating has the # `Department`=`Marketing` tag and you pass the # `department`=`engineering` session tag. `Department` and `department` # are not saved as separate tags, and the session tag passed in the # request takes precedence over the user tag. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison # [3]: http://aws.amazon.com/cognito/ # [4]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_assumerolewithwebidentity # [5]: https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html # [6]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # [7]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getfederationtoken # [8]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html # [9]: https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_attribute-based-access-control.html # # @option params [required, String] :name # The name of the federated user. The name is used as an identifier for # the temporary security credentials (such as `Bob`). For example, you # can reference the federated user name in a resource-based policy, such # as in an Amazon S3 bucket policy. # # The regex used to validate this parameter is a string of characters # consisting of upper- and lower-case alphanumeric characters with no # spaces. You can also include underscores or any of the following # characters: =,.@- # # @option params [String] :policy # An IAM policy in JSON format that you want to use as an inline session # policy. # # You must pass an inline or managed [session policy][1] to this # operation. You can pass a single JSON policy document to use as an # inline session policy. You can also specify up to 10 managed policies # to use as managed session policies. # # This parameter is optional. However, if you do not pass any session # policies, then the resulting federated user session has no # permissions. # # When you pass session policies, the session permissions are the # intersection of the IAM user policies and the session policies that # you pass. This gives you a way to further restrict the permissions for # a federated user. You cannot use session policies to grant more # permissions than those that are defined in the permissions policy of # the IAM user. For more information, see [Session Policies][1] in the # *IAM User Guide*. # # The resulting credentials can be used to access a resource that has a # resource-based policy. If that policy specifically references the # federated user session in the `Principal` element of the policy, the # session has the permissions allowed by the policy. These permissions # are granted in addition to the permissions that are granted by the # session policies. # # The plaintext that you use for both inline and managed session # policies can't exceed 2,048 characters. The JSON policy characters # can be any ASCII character from the space character to the end of the # valid character list (\\u0020 through \\u00FF). It can also include # the tab (\\u0009), linefeed (\\u000A), and carriage return (\\u000D) # characters. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # # @option params [Array<Types::PolicyDescriptorType>] :policy_arns # The Amazon Resource Names (ARNs) of the IAM managed policies that you # want to use as a managed session policy. The policies must exist in # the same account as the IAM user that is requesting federated access. # # You must pass an inline or managed [session policy][1] to this # operation. You can pass a single JSON policy document to use as an # inline session policy. You can also specify up to 10 managed policies # to use as managed session policies. The plaintext that you use for # both inline and managed session policies can't exceed 2,048 # characters. You can provide up to 10 managed policy ARNs. For more # information about ARNs, see [Amazon Resource Names (ARNs) and Amazon # Web Services Service Namespaces][2] in the Amazon Web Services General # Reference. # # This parameter is optional. However, if you do not pass any session # policies, then the resulting federated user session has no # permissions. # # When you pass session policies, the session permissions are the # intersection of the IAM user policies and the session policies that # you pass. This gives you a way to further restrict the permissions for # a federated user. You cannot use session policies to grant more # permissions than those that are defined in the permissions policy of # the IAM user. For more information, see [Session Policies][1] in the # *IAM User Guide*. # # The resulting credentials can be used to access a resource that has a # resource-based policy. If that policy specifically references the # federated user session in the `Principal` element of the policy, the # session has the permissions allowed by the policy. These permissions # are granted in addition to the permissions that are granted by the # session policies. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#policies_session # [2]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # # @option params [Integer] :duration_seconds # The duration, in seconds, that the session should last. Acceptable # durations for federation sessions range from 900 seconds (15 minutes) # to 129,600 seconds (36 hours), with 43,200 seconds (12 hours) as the # default. Sessions obtained using Amazon Web Services account root user # credentials are restricted to a maximum of 3,600 seconds (one hour). # If the specified duration is longer than one hour, the session # obtained by using root user credentials defaults to one hour. # # @option params [Array<Types::Tag>] :tags # A list of session tags. Each session tag consists of a key name and an # associated value. For more information about session tags, see # [Passing Session Tags in STS][1] in the *IAM User Guide*. # # This parameter is optional. You can pass up to 50 session tags. The # plaintext session tag keys can’t exceed 128 characters and the values # can’t exceed 256 characters. For these and additional limits, see [IAM # and STS Character Limits][2] in the *IAM User Guide*. # # <note markdown="1"> An Amazon Web Services conversion compresses the passed session # policies and session tags into a packed binary format that has a # separate limit. Your request can fail for this limit even if your # plaintext meets the other requirements. The `PackedPolicySize` # response element indicates by percentage how close the policies and # tags for your request are to the upper size limit. # # </note> # # You can pass a session tag with the same key as a tag that is already # attached to the user you are federating. When you do, session tags # override a user tag with the same key. # # Tag key–value pairs are not case sensitive, but case is preserved. # This means that you cannot have separate `Department` and `department` # tag keys. Assume that the role has the `Department`=`Marketing` tag # and you pass the `department`=`engineering` session tag. `Department` # and `department` are not saved as separate tags, and the session tag # passed in the request takes precedence over the role tag. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_session-tags.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_iam-limits.html#reference_iam-limits-entity-length # # @return [Types::GetFederationTokenResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::GetFederationTokenResponse#credentials #credentials} => Types::Credentials # * {Types::GetFederationTokenResponse#federated_user #federated_user} => Types::FederatedUser # * {Types::GetFederationTokenResponse#packed_policy_size #packed_policy_size} => Integer # # # @example Example: To get temporary credentials for a role by using GetFederationToken # # resp = client.get_federation_token({ # duration_seconds: 3600, # name: "testFedUserSession", # policy: "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Sid\":\"Stmt1\",\"Effect\":\"Allow\",\"Action\":\"s3:ListAllMyBuckets\",\"Resource\":\"*\"}]}", # tags: [ # { # key: "Project", # value: "Pegasus", # }, # { # key: "Cost-Center", # value: "98765", # }, # ], # }) # # resp.to_h outputs the following: # { # credentials: { # access_key_id: "AKIAIOSFODNN7EXAMPLE", # expiration: Time.parse("2011-07-15T23:28:33.359Z"), # secret_access_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY", # session_token: "AQoDYXdzEPT//////////wEXAMPLEtc764bNrC9SAPBSM22wDOk4x4HIZ8j4FZTwdQWLWsKWHGBuFqwAeMicRXmxfpSPfIeoIYRqTflfKD8YUuwthAx7mSEI/qkPpKPi/kMcGdQrmGdeehM4IC1NtBmUpp2wUE8phUZampKsburEDy0KPkyQDYwT7WZ0wq5VSXDvp75YU9HFvlRd8Tx6q6fE8YQcHNVXAkiY9q6d+xo0rKwT38xVqr7ZD0u0iPPkUL64lIZbqBAz+scqKmlzm8FDrypNC9Yjc8fPOLn9FX9KSYvKTr4rvx3iSIlTJabIQwj2ICCR/oLxBA==", # }, # federated_user: { # arn: "arn:aws:sts::123456789012:federated-user/Bob", # federated_user_id: "123456789012:Bob", # }, # packed_policy_size: 8, # } # # @example Request syntax with placeholder values # # resp = client.get_federation_token({ # name: "userNameType", # required # policy: "sessionPolicyDocumentType", # policy_arns: [ # { # arn: "arnType", # }, # ], # duration_seconds: 1, # tags: [ # { # key: "tagKeyType", # required # value: "tagValueType", # required # }, # ], # }) # # @example Response structure # # resp.credentials.access_key_id #=> String # resp.credentials.secret_access_key #=> String # resp.credentials.session_token #=> String # resp.credentials.expiration #=> Time # resp.federated_user.federated_user_id #=> String # resp.federated_user.arn #=> String # resp.packed_policy_size #=> Integer # # @see http://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetFederationToken AWS API Documentation # # @overload get_federation_token(params = {}) # @param [Hash] params ({}) def get_federation_token(params = {}, options = {}) req = build_request(:get_federation_token, params) req.send_request(options) end # Returns a set of temporary credentials for an Amazon Web Services # account or IAM user. The credentials consist of an access key ID, a # secret access key, and a security token. Typically, you use # `GetSessionToken` if you want to use MFA to protect programmatic calls # to specific Amazon Web Services API operations like Amazon EC2 # `StopInstances`. MFA-enabled IAM users would need to call # `GetSessionToken` and submit an MFA code that is associated with their # MFA device. Using the temporary security credentials that are returned # from the call, IAM users can then make programmatic calls to API # operations that require MFA authentication. If you do not supply a # correct MFA code, then the API returns an access denied error. For a # comparison of `GetSessionToken` with the other API operations that # produce temporary credentials, see [Requesting Temporary Security # Credentials][1] and [Comparing the STS API operations][2] in the *IAM # User Guide*. # # **Session Duration** # # The `GetSessionToken` operation must be called by using the long-term # Amazon Web Services security credentials of the Amazon Web Services # account root user or an IAM user. Credentials that are created by IAM # users are valid for the duration that you specify. This duration can # range from 900 seconds (15 minutes) up to a maximum of 129,600 seconds # (36 hours), with a default of 43,200 seconds (12 hours). Credentials # based on account credentials can range from 900 seconds (15 minutes) # up to 3,600 seconds (1 hour), with a default of 1 hour. # # **Permissions** # # The temporary security credentials created by `GetSessionToken` can be # used to make API calls to any Amazon Web Services service with the # following exceptions: # # * You cannot call any IAM API operations unless MFA authentication # information is included in the request. # # * You cannot call any STS API *except* `AssumeRole` or # `GetCallerIdentity`. # # <note markdown="1"> We recommend that you do not call `GetSessionToken` with Amazon Web # Services account root user credentials. Instead, follow our [best # practices][3] by creating one or more IAM users, giving them the # necessary permissions, and using IAM users for everyday interaction # with Amazon Web Services. # # </note> # # The credentials that are returned by `GetSessionToken` are based on # permissions associated with the user whose credentials were used to # call the operation. If `GetSessionToken` is called using Amazon Web # Services account root user credentials, the temporary credentials have # root user permissions. Similarly, if `GetSessionToken` is called using # the credentials of an IAM user, the temporary credentials have the # same permissions as the IAM user. # # For more information about using `GetSessionToken` to create temporary # credentials, go to [Temporary Credentials for Users in Untrusted # Environments][4] in the *IAM User Guide*. # # # # [1]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html # [2]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#stsapi_comparison # [3]: https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#create-iam-users # [4]: https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html#api_getsessiontoken # # @option params [Integer] :duration_seconds # The duration, in seconds, that the credentials should remain valid. # Acceptable durations for IAM user sessions range from 900 seconds (15 # minutes) to 129,600 seconds (36 hours), with 43,200 seconds (12 hours) # as the default. Sessions for Amazon Web Services account owners are # restricted to a maximum of 3,600 seconds (one hour). If the duration # is longer than one hour, the session for Amazon Web Services account # owners defaults to one hour. # # @option params [String] :serial_number # The identification number of the MFA device that is associated with # the IAM user who is making the `GetSessionToken` call. Specify this # value if the IAM user has a policy that requires MFA authentication. # The value is either the serial number for a hardware device (such as # `GAHT12345678`) or an Amazon Resource Name (ARN) for a virtual device # (such as `arn:aws:iam::123456789012:mfa/user`). You can find the # device for an IAM user by going to the Management Console and viewing # the user's security credentials. # # The regex used to validate this parameter is a string of characters # consisting of upper- and lower-case alphanumeric characters with no # spaces. You can also include underscores or any of the following # characters: =,.@:/- # # @option params [String] :token_code # The value provided by the MFA device, if MFA is required. If any # policy requires the IAM user to submit an MFA code, specify this # value. If MFA authentication is required, the user must provide a code # when requesting a set of temporary security credentials. A user who # fails to provide the code receives an "access denied" response when # requesting resources that require MFA authentication. # # The format for this parameter, as described by its regex pattern, is a # sequence of six numeric digits. # # @return [Types::GetSessionTokenResponse] Returns a {Seahorse::Client::Response response} object which responds to the following methods: # # * {Types::GetSessionTokenResponse#credentials #credentials} => Types::Credentials # # # @example Example: To get temporary credentials for an IAM user or an AWS account # # resp = client.get_session_token({ # duration_seconds: 3600, # serial_number: "YourMFASerialNumber", # token_code: "123456", # }) # # resp.to_h outputs the following: # { # credentials: { # access_key_id: "AKIAIOSFODNN7EXAMPLE", # expiration: Time.parse("2011-07-11T19:55:29.611Z"), # secret_access_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYzEXAMPLEKEY", # session_token: "AQoEXAMPLEH4aoAH0gNCAPyJxz4BlCFFxWNE1OPTgk5TthT+FvwqnKwRcOIfrRh3c/LTo6UDdyJwOOvEVPvLXCrrrUtdnniCEXAMPLE/IvU1dYUg2RVAJBanLiHb4IgRmpRV3zrkuWJOgQs8IZZaIv2BXIa2R4OlgkBN9bkUDNCJiBeb/AXlzBBko7b15fjrBs2+cTQtpZ3CYWFXG8C5zqx37wnOE49mRl/+OtkIKGO7fAE", # }, # } # # @example Request syntax with placeholder values # # resp = client.get_session_token({ # duration_seconds: 1, # serial_number: "serialNumberType", # token_code: "tokenCodeType", # }) # # @example Response structure # # resp.credentials.access_key_id #=> String # resp.credentials.secret_access_key #=> String # resp.credentials.session_token #=> String # resp.credentials.expiration #=> Time # # @see http://docs.aws.amazon.com/goto/WebAPI/sts-2011-06-15/GetSessionToken AWS API Documentation # # @overload get_session_token(params = {}) # @param [Hash] params ({}) def get_session_token(params = {}, options = {}) req = build_request(:get_session_token, params) req.send_request(options) end # @!endgroup # @param params ({}) # @api private def build_request(operation_name, params = {}) handlers = @handlers.for(operation_name) context = Seahorse::Client::RequestContext.new( operation_name: operation_name, operation: config.api.operation(operation_name), client: self, params: params, config: config) context[:gem_name] = 'aws-sdk-core' context[:gem_version] = '3.121.3' Seahorse::Client::Request.new(handlers, context) end # @api private # @deprecated def waiter_names [] end class << self # @api private attr_reader :identifier # @api private def errors_module Errors end end end end
50.983684
687
0.688684
4afb70d1cb7af3237b6f358879b21bf8b9e1c0d7
783
require 'test_helper' class StaticPagesControllerTest < ActionDispatch::IntegrationTest def setup @base_title = "Ruby on Rails Tutorial Sample App" end test "should get root" do get root_path assert_response :success end test "should get home" do get root_path assert_response :success assert_select "title", "#{@base_title}" end test "should get help" do get help_path assert_response :success assert_select "title", "Help | #{@base_title}" end test "should get about" do get about_path assert_response :success assert_select "title", "About | #{@base_title}" end test "should get contact" do get contact_path assert_response :success assert_select "title", "Contact | #{@base_title}" end end
20.076923
65
0.696041
7aa5cf030dd79f92a92a764fb1602d96cd7e3166
464
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'categories/show', type: :view do before(:each) do @category = assign(:category, Category.create!( name: 'Name', display_in_navbar: false )) end it 'renders attributes in <p>' do render expect(rendered).to match(/Name/) expect(rendered).to match(/false/) end end
24.421053
60
0.536638
612e1341d83e6c488d3d2cd0d7961c284a75b8c2
1,266
module SpreeCorreios module Generators class InstallGenerator < Rails::Generators::Base class_option :auto_run_migrations, :type => :boolean, :default => false def add_javascripts append_file 'vendor/assets/javascripts/spree/frontend/all.js', "//= require spree/frontend/spree_correios\n" append_file 'vendor/assets/javascripts/spree/backend/all.js', "//= require spree/backend/spree_correios\n" end def add_stylesheets inject_into_file 'vendor/assets/stylesheets/spree/frontend/all.css', " *= require spree/frontend/spree_correios\n", :before => /\*\//, :verbose => true inject_into_file 'vendor/assets/stylesheets/spree/backend/all.css', " *= require spree/backend/spree_correios\n", :before => /\*\//, :verbose => true end def add_migrations run 'bundle exec rake railties:install:migrations FROM=spree_correios' end def run_migrations run_migrations = options[:auto_run_migrations] || ['', 'y', 'Y'].include?(ask 'Would you like to run the migrations now? [Y/n]') if run_migrations run 'bundle exec rake db:migrate' else puts 'Skipping rake db:migrate, don\'t forget to run it!' end end end end end
39.5625
159
0.669826
7a729894d31409ca789e4874d704638e7bf336cc
43
class ArtistPolicy < ApplicationPolicy end
14.333333
38
0.860465
ac55164d788a1b1a9b0c050b7a0a50b005c657f9
376
require Rails.root.join('lib', 'tasks', 'hbx_import', 'qhp', 'parsers', 'package_list_parser') module Parser class PlanBenefitTemplateParser include HappyMapper tag 'planBenefitTemplateVO' has_one :packages_list, Parser::PackageListParser, :tag => "packagesList" def to_hash { packages_list: packages_list.to_hash } end end end
20.888889
94
0.694149
bfc5e81083408c3628e9aa669891cfffdb20ea91
34,621
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # 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 'date' require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module ManagedidentitiesV1alpha1 class AttachTrustRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Backup class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Binding class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class CancelOperationRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Certificate class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class DailyCycle class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Date class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class DenyMaintenancePeriod class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class DetachTrustRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Domain class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Empty class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Expr class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudManagedidentitiesV1OpMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudManagedidentitiesV1alpha1OpMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudManagedidentitiesV1beta1OpMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudSaasacceleratorManagementProvidersV1Instance class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class LdapsSettings class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListBackupsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListDomainsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListLocationsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListOperationsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListPeeringsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ListSqlIntegrationsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Location class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class MaintenancePolicy class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class MaintenanceWindow class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Operation class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class OperationMetadata class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Peering class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Policy class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ReconfigureTrustRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ResetAdminPasswordRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ResetAdminPasswordResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class RestoreDomainRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class SqlIntegration class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Schedule class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class SetIamPolicyRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class Status class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class TestIamPermissionsRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class TestIamPermissionsResponse class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class TimeOfDay class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class TrustProp class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class UpdatePolicy class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class ValidateTrustRequest class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class WeeklyCycle class Representation < Google::Apis::Core::JsonRepresentation; end include Google::Apis::Core::JsonObjectSupport end class AttachTrustRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :trust_prop, as: 'trust', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation end end class Backup # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' hash :labels, as: 'labels' property :name, as: 'name' property :state, as: 'state' property :status_message, as: 'statusMessage' property :type, as: 'type' property :update_time, as: 'updateTime' end end class Binding # @private class Representation < Google::Apis::Core::JsonRepresentation property :condition, as: 'condition', class: Google::Apis::ManagedidentitiesV1alpha1::Expr, decorator: Google::Apis::ManagedidentitiesV1alpha1::Expr::Representation collection :members, as: 'members' property :role, as: 'role' end end class CancelOperationRequest # @private class Representation < Google::Apis::Core::JsonRepresentation end end class Certificate # @private class Representation < Google::Apis::Core::JsonRepresentation property :expire_time, as: 'expireTime' property :issuing_certificate, as: 'issuingCertificate', class: Google::Apis::ManagedidentitiesV1alpha1::Certificate, decorator: Google::Apis::ManagedidentitiesV1alpha1::Certificate::Representation property :subject, as: 'subject' collection :subject_alternative_name, as: 'subjectAlternativeName' property :thumbprint, as: 'thumbprint' end end class DailyCycle # @private class Representation < Google::Apis::Core::JsonRepresentation property :duration, as: 'duration' property :start_time, as: 'startTime', class: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay, decorator: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay::Representation end end class Date # @private class Representation < Google::Apis::Core::JsonRepresentation property :day, as: 'day' property :month, as: 'month' property :year, as: 'year' end end class DenyMaintenancePeriod # @private class Representation < Google::Apis::Core::JsonRepresentation property :end_date, as: 'endDate', class: Google::Apis::ManagedidentitiesV1alpha1::Date, decorator: Google::Apis::ManagedidentitiesV1alpha1::Date::Representation property :start_date, as: 'startDate', class: Google::Apis::ManagedidentitiesV1alpha1::Date, decorator: Google::Apis::ManagedidentitiesV1alpha1::Date::Representation property :time, as: 'time', class: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay, decorator: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay::Representation end end class DetachTrustRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :trust_prop, as: 'trust', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation end end class Domain # @private class Representation < Google::Apis::Core::JsonRepresentation property :audit_logs_enabled, as: 'auditLogsEnabled' collection :authorized_networks, as: 'authorizedNetworks' property :create_time, as: 'createTime' property :fqdn, as: 'fqdn' hash :labels, as: 'labels' collection :locations, as: 'locations' property :managed_identities_admin_name, as: 'managedIdentitiesAdminName' property :name, as: 'name' property :reserved_ip_range, as: 'reservedIpRange' property :state, as: 'state' property :status_message, as: 'statusMessage' collection :trusts, as: 'trusts', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation property :update_time, as: 'updateTime' end end class Empty # @private class Representation < Google::Apis::Core::JsonRepresentation end end class Expr # @private class Representation < Google::Apis::Core::JsonRepresentation property :description, as: 'description' property :expression, as: 'expression' property :location, as: 'location' property :title, as: 'title' end end class GoogleCloudManagedidentitiesV1OpMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :api_version, as: 'apiVersion' property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :requested_cancellation, as: 'requestedCancellation' property :target, as: 'target' property :verb, as: 'verb' end end class GoogleCloudManagedidentitiesV1alpha1OpMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :api_version, as: 'apiVersion' property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :requested_cancellation, as: 'requestedCancellation' property :target, as: 'target' property :verb, as: 'verb' end end class GoogleCloudManagedidentitiesV1beta1OpMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :api_version, as: 'apiVersion' property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :requested_cancellation, as: 'requestedCancellation' property :target, as: 'target' property :verb, as: 'verb' end end class GoogleCloudSaasacceleratorManagementProvidersV1Instance # @private class Representation < Google::Apis::Core::JsonRepresentation property :consumer_defined_name, as: 'consumerDefinedName' property :create_time, as: 'createTime' property :instance_type, as: 'instanceType' hash :labels, as: 'labels' hash :maintenance_policy_names, as: 'maintenancePolicyNames' hash :maintenance_schedules, as: 'maintenanceSchedules', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule::Representation property :maintenance_settings, as: 'maintenanceSettings', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings::Representation property :name, as: 'name' hash :notification_parameters, as: 'notificationParameters' hash :producer_metadata, as: 'producerMetadata' collection :provisioned_resources, as: 'provisionedResources', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource::Representation property :slm_instance_template, as: 'slmInstanceTemplate' property :slo_metadata, as: 'sloMetadata', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata::Representation hash :software_versions, as: 'softwareVersions' property :state, as: 'state' property :tenant_project_id, as: 'tenantProjectId' property :update_time, as: 'updateTime' end end class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSchedule # @private class Representation < Google::Apis::Core::JsonRepresentation property :can_reschedule, as: 'canReschedule' property :end_time, as: 'endTime' property :rollout_management_policy, as: 'rolloutManagementPolicy' property :schedule_deadline_time, as: 'scheduleDeadlineTime' property :start_time, as: 'startTime' end end class GoogleCloudSaasacceleratorManagementProvidersV1MaintenanceSettings # @private class Representation < Google::Apis::Core::JsonRepresentation property :exclude, as: 'exclude' property :is_rollback, as: 'isRollback' hash :maintenance_policies, as: 'maintenancePolicies', class: Google::Apis::ManagedidentitiesV1alpha1::MaintenancePolicy, decorator: Google::Apis::ManagedidentitiesV1alpha1::MaintenancePolicy::Representation end end class GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :location, as: 'location' property :node_id, as: 'nodeId' property :per_sli_eligibility, as: 'perSliEligibility', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility::Representation end end class GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility # @private class Representation < Google::Apis::Core::JsonRepresentation hash :eligibilities, as: 'eligibilities', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility::Representation end end class GoogleCloudSaasacceleratorManagementProvidersV1ProvisionedResource # @private class Representation < Google::Apis::Core::JsonRepresentation property :resource_type, as: 'resourceType' property :resource_url, as: 'resourceUrl' end end class GoogleCloudSaasacceleratorManagementProvidersV1SloEligibility # @private class Representation < Google::Apis::Core::JsonRepresentation property :eligible, as: 'eligible' property :reason, as: 'reason' end end class GoogleCloudSaasacceleratorManagementProvidersV1SloMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation collection :nodes, as: 'nodes', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1NodeSloMetadata::Representation property :per_sli_eligibility, as: 'perSliEligibility', class: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility, decorator: Google::Apis::ManagedidentitiesV1alpha1::GoogleCloudSaasacceleratorManagementProvidersV1PerSliSloEligibility::Representation property :tier, as: 'tier' end end class LdapsSettings # @private class Representation < Google::Apis::Core::JsonRepresentation property :certificate, as: 'certificate', class: Google::Apis::ManagedidentitiesV1alpha1::Certificate, decorator: Google::Apis::ManagedidentitiesV1alpha1::Certificate::Representation property :certificate_password, as: 'certificatePassword' property :certificate_pfx, :base64 => true, as: 'certificatePfx' property :name, as: 'name' property :state, as: 'state' property :update_time, as: 'updateTime' end end class ListBackupsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :backups, as: 'backups', class: Google::Apis::ManagedidentitiesV1alpha1::Backup, decorator: Google::Apis::ManagedidentitiesV1alpha1::Backup::Representation property :next_page_token, as: 'nextPageToken' collection :unreachable, as: 'unreachable' end end class ListDomainsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :domains, as: 'domains', class: Google::Apis::ManagedidentitiesV1alpha1::Domain, decorator: Google::Apis::ManagedidentitiesV1alpha1::Domain::Representation property :next_page_token, as: 'nextPageToken' collection :unreachable, as: 'unreachable' end end class ListLocationsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :locations, as: 'locations', class: Google::Apis::ManagedidentitiesV1alpha1::Location, decorator: Google::Apis::ManagedidentitiesV1alpha1::Location::Representation property :next_page_token, as: 'nextPageToken' end end class ListOperationsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation property :next_page_token, as: 'nextPageToken' collection :operations, as: 'operations', class: Google::Apis::ManagedidentitiesV1alpha1::Operation, decorator: Google::Apis::ManagedidentitiesV1alpha1::Operation::Representation end end class ListPeeringsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation property :next_page_token, as: 'nextPageToken' collection :peerings, as: 'peerings', class: Google::Apis::ManagedidentitiesV1alpha1::Peering, decorator: Google::Apis::ManagedidentitiesV1alpha1::Peering::Representation collection :unreachable, as: 'unreachable' end end class ListSqlIntegrationsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation property :next_page_token, as: 'nextPageToken' collection :sql_integrations, as: 'sqlIntegrations', class: Google::Apis::ManagedidentitiesV1alpha1::SqlIntegration, decorator: Google::Apis::ManagedidentitiesV1alpha1::SqlIntegration::Representation collection :unreachable, as: 'unreachable' end end class Location # @private class Representation < Google::Apis::Core::JsonRepresentation property :display_name, as: 'displayName' hash :labels, as: 'labels' property :location_id, as: 'locationId' hash :metadata, as: 'metadata' property :name, as: 'name' end end class MaintenancePolicy # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :description, as: 'description' hash :labels, as: 'labels' property :name, as: 'name' property :state, as: 'state' property :update_policy, as: 'updatePolicy', class: Google::Apis::ManagedidentitiesV1alpha1::UpdatePolicy, decorator: Google::Apis::ManagedidentitiesV1alpha1::UpdatePolicy::Representation property :update_time, as: 'updateTime' end end class MaintenanceWindow # @private class Representation < Google::Apis::Core::JsonRepresentation property :daily_cycle, as: 'dailyCycle', class: Google::Apis::ManagedidentitiesV1alpha1::DailyCycle, decorator: Google::Apis::ManagedidentitiesV1alpha1::DailyCycle::Representation property :weekly_cycle, as: 'weeklyCycle', class: Google::Apis::ManagedidentitiesV1alpha1::WeeklyCycle, decorator: Google::Apis::ManagedidentitiesV1alpha1::WeeklyCycle::Representation end end class Operation # @private class Representation < Google::Apis::Core::JsonRepresentation property :done, as: 'done' property :error, as: 'error', class: Google::Apis::ManagedidentitiesV1alpha1::Status, decorator: Google::Apis::ManagedidentitiesV1alpha1::Status::Representation hash :metadata, as: 'metadata' property :name, as: 'name' hash :response, as: 'response' end end class OperationMetadata # @private class Representation < Google::Apis::Core::JsonRepresentation property :api_version, as: 'apiVersion' property :cancel_requested, as: 'cancelRequested' property :create_time, as: 'createTime' property :end_time, as: 'endTime' property :status_detail, as: 'statusDetail' property :target, as: 'target' property :verb, as: 'verb' end end class Peering # @private class Representation < Google::Apis::Core::JsonRepresentation property :authorized_network, as: 'authorizedNetwork' property :create_time, as: 'createTime' property :domain_resource, as: 'domainResource' hash :labels, as: 'labels' property :name, as: 'name' property :state, as: 'state' property :status_message, as: 'statusMessage' property :update_time, as: 'updateTime' end end class Policy # @private class Representation < Google::Apis::Core::JsonRepresentation collection :bindings, as: 'bindings', class: Google::Apis::ManagedidentitiesV1alpha1::Binding, decorator: Google::Apis::ManagedidentitiesV1alpha1::Binding::Representation property :etag, :base64 => true, as: 'etag' property :version, as: 'version' end end class ReconfigureTrustRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :trust_prop, as: 'trust', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation end end class ResetAdminPasswordRequest # @private class Representation < Google::Apis::Core::JsonRepresentation end end class ResetAdminPasswordResponse # @private class Representation < Google::Apis::Core::JsonRepresentation property :password, as: 'password' end end class RestoreDomainRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :backup_id, as: 'backupId' end end class SqlIntegration # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :name, as: 'name' property :sql_instance, as: 'sqlInstance' property :state, as: 'state' property :update_time, as: 'updateTime' end end class Schedule # @private class Representation < Google::Apis::Core::JsonRepresentation property :day, as: 'day' property :duration, as: 'duration' property :start_time, as: 'startTime', class: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay, decorator: Google::Apis::ManagedidentitiesV1alpha1::TimeOfDay::Representation end end class SetIamPolicyRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :policy, as: 'policy', class: Google::Apis::ManagedidentitiesV1alpha1::Policy, decorator: Google::Apis::ManagedidentitiesV1alpha1::Policy::Representation end end class Status # @private class Representation < Google::Apis::Core::JsonRepresentation property :code, as: 'code' collection :details, as: 'details' property :message, as: 'message' end end class TestIamPermissionsRequest # @private class Representation < Google::Apis::Core::JsonRepresentation collection :permissions, as: 'permissions' end end class TestIamPermissionsResponse # @private class Representation < Google::Apis::Core::JsonRepresentation collection :permissions, as: 'permissions' end end class TimeOfDay # @private class Representation < Google::Apis::Core::JsonRepresentation property :hours, as: 'hours' property :minutes, as: 'minutes' property :nanos, as: 'nanos' property :seconds, as: 'seconds' end end class TrustProp # @private class Representation < Google::Apis::Core::JsonRepresentation property :create_time, as: 'createTime' property :last_known_trust_connected_heartbeat_time, as: 'lastKnownTrustConnectedHeartbeatTime' property :selective_authentication, as: 'selectiveAuthentication' property :state, as: 'state' property :state_description, as: 'stateDescription' collection :target_dns_ip_addresses, as: 'targetDnsIpAddresses' property :target_domain_name, as: 'targetDomainName' property :trust_direction, as: 'trustDirection' property :trust_handshake_secret, as: 'trustHandshakeSecret' property :trust_type, as: 'trustType' property :update_time, as: 'updateTime' end end class UpdatePolicy # @private class Representation < Google::Apis::Core::JsonRepresentation property :channel, as: 'channel' collection :deny_maintenance_periods, as: 'denyMaintenancePeriods', class: Google::Apis::ManagedidentitiesV1alpha1::DenyMaintenancePeriod, decorator: Google::Apis::ManagedidentitiesV1alpha1::DenyMaintenancePeriod::Representation property :window, as: 'window', class: Google::Apis::ManagedidentitiesV1alpha1::MaintenanceWindow, decorator: Google::Apis::ManagedidentitiesV1alpha1::MaintenanceWindow::Representation end end class ValidateTrustRequest # @private class Representation < Google::Apis::Core::JsonRepresentation property :trust_prop, as: 'trust', class: Google::Apis::ManagedidentitiesV1alpha1::TrustProp, decorator: Google::Apis::ManagedidentitiesV1alpha1::TrustProp::Representation end end class WeeklyCycle # @private class Representation < Google::Apis::Core::JsonRepresentation collection :schedule, as: 'schedule', class: Google::Apis::ManagedidentitiesV1alpha1::Schedule, decorator: Google::Apis::ManagedidentitiesV1alpha1::Schedule::Representation end end end end end
39.342045
323
0.665463
edc37d4b2d6727837715b27c439565ac4018783a
2,627
# Cloud Foundry Java Buildpack # Copyright 2013-2017 the original author or authors. # # 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 'spec_helper' require 'component_helper' require 'java_buildpack/component/modular_component' describe JavaBuildpack::Component::ModularComponent do include_context 'with component help' let(:component) { StubModularComponent.new context } it 'fails if supports? is unimplemented' do expect { component.supports? }.to raise_error end context do before do allow_any_instance_of(StubModularComponent).to receive(:supports?).and_return(false) end it 'returns nil from detect if not supported' do expect(component.detect).to be_nil end it 'fails if methods are unimplemented' do expect { component.command }.to raise_error expect { component.sub_components(context) }.to raise_error end end context do let(:sub_component) { instance_double('sub_component') } before do allow_any_instance_of(StubModularComponent).to receive(:supports?).and_return(true) allow_any_instance_of(StubModularComponent).to receive(:sub_components).and_return([sub_component, sub_component]) end it 'returns name and version string from detect if supported' do allow(sub_component).to receive(:detect).and_return('sub_component=test-version', 'sub_component=test-version-2') detected = component.detect expect(detected).to include('sub_component=test-version') expect(detected).to include('sub_component=test-version-2') end it 'calls compile on each sub_component' do allow(sub_component).to receive(:compile).twice component.compile end it 'calls release on each sub_component and then command' do allow(sub_component).to receive(:release).twice allow_any_instance_of(StubModularComponent).to receive(:command).and_return('test-command') expect(component.release).to eq('test-command') end end end class StubModularComponent < JavaBuildpack::Component::ModularComponent public :command, :sub_components, :supports? end
31.27381
120
0.746479
e96de7c27ae7eef4c47988e140c638c204509ebb
1,122
# # Author:: Adam Jacob (<adam@opscode.com>) # Author:: AJ Christensen (<aj@junglist.gen.nz>) # Author:: Ho-Sheng Hsiao (<hosh@opscode.com>) # Copyright:: Copyright (c) 2008 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. # module SpecHelpers module Knife def redefine_argv(value) Object.send(:remove_const, :ARGV) Object.send(:const_set, :ARGV, value) end def with_argv(*argv) original_argv = ARGV redefine_argv(argv.flatten) begin yield ensure redefine_argv(original_argv) end end end end
29.526316
74
0.7041
0161964c649eacede85c7336859773da888d2a1c
256
class EmailValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) unless value =~ /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i record.errors[attribute] << (options[:message] || "is not an email") end end end
28.444444
74
0.613281
18396ee91fc49172114665ecf8282130eea1c953
293
require 'rails_helper' RSpec.describe "users/show", type: :view do before(:each) do @user = create(:user) end it "renders attributes in <p>" do render expect(rendered).to match(/First/) expect(rendered).to match(/Last/) expect(rendered).to match(/Email/) end end
19.533333
43
0.658703
e8b1bc1f1584f5ce7579acf6c6cf793635b59179
9,814
# Copyright 2018 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. def job_discovery_batch_create_jobs project_id:, company_name: # [START job_discovery_batch_create_jobs] # project_id = "Id of the project" # company_name = "The resource name of the company listing the job. The format is "projects/{project_id}/companies/{company_id}"" require "google/apis/jobs_v3" jobs = Google::Apis::JobsV3 talent_solution_client = jobs::CloudTalentSolutionService.new # @see https://developers.google.com/identity/protocols/application-default-credentials#callingruby talent_solution_client.authorization = Google::Auth.get_application_default( "https://www.googleapis.com/auth/jobs" ) jobs_created = [] job_generated1 = jobs::Job.new requisition_id: "Job: #{company_name} 1", title: " Lab Technician", company_name: company_name, employment_types: ["FULL_TIME"], language_code: "en-US", application_info: (jobs::ApplicationInfo.new uris: ["http://careers.google.com"]), description: "Design and improve software." job_generated2 = jobs::Job.new requisition_id: "Job: #{company_name} 2", title: "Systems Administrator", company_name: company_name, employment_types: ["FULL_TIME"], language_code: "en-US", application_info: (jobs::ApplicationInfo.new uris: ["http://careers.google.com"]), description: "System Administrator for software." create_job_request1 = jobs::CreateJobRequest.new job: job_generated1 create_job_request2 = jobs::CreateJobRequest.new job: job_generated2 talent_solution_client.batch do |client| client.create_job project_id, create_job_request1 do |job, err| if err.nil? jobs_created.push job else puts "Batch job create error message: #{err.message}" end end client.create_job project_id, create_job_request2 do |job, err| if err.nil? jobs_created.push job else puts "Batch job create error message: #{err.message}" end end end # jobCreated = batchCreate.create_job(project_id, create_job_request1) puts "Batch job created: #{jobs_created.to_json}" jobs_created # [END job_discovery_batch_create_jobs] end def job_discovery_batch_update_jobs job_to_be_updated: # [START job_discovery_batch_update_jobs] # job_to_be_updated = "Updated job objects" require "google/apis/jobs_v3" jobs = Google::Apis::JobsV3 talent_solution_client = jobs::CloudTalentSolutionService.new # @see # https://developers.google.com/identity/protocols/application-default-credentials#callingruby talent_solution_client.authorization = Google::Auth.get_application_default( "https://www.googleapis.com/auth/jobs" ) jobs_updated = [] update_job_requests = [] job_to_be_updated.each do |job| request = jobs::UpdateJobRequest.new job: job update_job_requests.push request end talent_solution_client.batch do |client| update_job_requests.each do |update_job_request| client.patch_project_job update_job_request.job.name, update_job_request do |job, err| if err.nil? jobs_updated.push job else puts "Batch job updated error message: #{err.message}" end end end end # jobCreated = batchCreate.create_job(project_id, create_job_request1) puts "Batch job updated: #{jobs_updated.to_json}" jobs_updated # [END job_discovery_batch_update_jobs] end def job_discovery_batch_update_jobs_with_mask job_to_be_updated: # [START job_discovery_batch_update_jobs_with_mask] # job_to_be_updated = "Updated job objects" require "google/apis/jobs_v3" jobs = Google::Apis::JobsV3 talent_solution_client = jobs::CloudTalentSolutionService.new # @see # https://developers.google.com/identity/protocols/application-default-credentials#callingruby talent_solution_client.authorization = Google::Auth.get_application_default( "https://www.googleapis.com/auth/jobs" ) jobs_updated = [] update_job_with_mask_requests = [] job_to_be_updated.each do |job| request = jobs::UpdateJobRequest.new job: job, update_mask: "title" update_job_with_mask_requests.push request end talent_solution_client.batch do |client| update_job_with_mask_requests.each do |update_job_with_mask_request| client.patch_project_job(update_job_with_mask_request.job.name, update_job_with_mask_request) do |job, err| if err.nil? jobs_updated.push job else puts "Batch job updated error message: #{err.message}" end end end end puts "Batch job updated with Mask: #{jobs_updated.to_json}" jobs_updated # [END job_discovery_batch_update_jobs_with_mask] end def job_discovery_batch_delete_jobs job_to_be_deleted: # [START job_discovery_batch_delete_jobs] # job_to_be_deleted = "Name of the jobs to be deleted" require "google/apis/jobs_v3" jobs = Google::Apis::JobsV3 talent_solution_client = jobs::CloudTalentSolutionService.new # @see # https://developers.google.com/identity/protocols/application-default-credentials#callingruby talent_solution_client.authorization = Google::Auth.get_application_default( "https://www.googleapis.com/auth/jobs" ) jobs_deleted = 0 talent_solution_client.batch do |client| job_to_be_deleted.each do |job_name| client.delete_project_job job_name do |_job, err| if err.nil? jobs_deleted += 1 else puts "Batch job deleted error message: #{err.message}" end end end end puts "Batch job deleted." jobs_deleted # [END job_discovery_batch_delete_jobs] end def job_discovery_list_jobs project_id:, company_name: # [START job_discovery_list_jobs] # project_id = "Id of the project" # company_name = "The company's name which has the job you want to list. The format is "projects/{project_id}/companies/{company_id}"" require "google/apis/jobs_v3" jobs = Google::Apis::JobsV3 talent_solution_client = jobs::CloudTalentSolutionService.new talent_solution_client.authorization = Google::Auth.get_application_default( "https://www.googleapis.com/auth/jobs" ) begin job_got = talent_solution_client.list_project_jobs project_id, filter: "companyName = \"#{company_name}\"" puts "Job got: #{job_got.to_json}" return job_got rescue StandardError => e puts "Exception occurred while getting job: #{e}" end # [END job_discovery_list_jobs] end def run_batch_operation_sample arguments command = arguments.shift default_project_id = "projects/#{ENV['GOOGLE_CLOUD_PROJECT']}" user_input = arguments.shift company_name = "#{default_project_id}/companies/#{user_input}" jobs_created = [] job_names = [] case command when "batch_create_jobs" jobs_created = job_discovery_batch_create_jobs company_name: company_name, project_id: default_project_id when "batch_update_jobs" list_job_response = job_discovery_list_jobs company_name: company_name, project_id: default_project_id jobs_got = list_job_response.jobs jobs_got.each do |job| job.title = job.title + " updated" job.description = job.description + " updated" end job_discovery_batch_update_jobs job_to_be_updated: jobs_got when "batch_update_jobs_with_mask" list_job_response = job_discovery_list_jobs company_name: company_name, project_id: default_project_id jobs_got = list_job_response.jobs jobs_got.each do |job| job.title = job.title + " updated with mask" end job_discovery_batch_update_jobs_with_mask job_to_be_updated: jobs_got when "batch_delete_jobs" list_job_response = job_discovery_list_jobs company_name: company_name, project_id: default_project_id jobs_got = list_job_response.jobs jobs_got.each do |job| job_names.push job.name end job_discovery_batch_delete_jobs job_to_be_deleted: job_names else puts <<~USAGE Usage: bundle exec ruby batch_operation_sample.rb [command] [arguments] Commands: batch_create_jobs <company_id> Batch create jobs under provided company. batch_update_jobs <company_id> Batch update jobs. batch_update_jobs_with_mask <company_id> Batch update jobs with mask. batch_delete_jobs <company_id> Batch delete jobs. Environment variables: GOOGLE_CLOUD_PROJECT must be set to your Google Cloud project ID USAGE end end if $PROGRAM_NAME == __FILE__ run_batch_operation_sample ARGV end
38.03876
137
0.682087
d59bf3f948d43f900be60de12649ec3815e1d4e2
2,873
# == Schema Information # # Table name: assignments # # id :integer not null, primary key # state :enum default("pending") # case_id :integer not null # team_id :integer not null # created_at :datetime not null # updated_at :datetime not null # role :enum # user_id :integer # approved :boolean default(FALSE) # class Assignment < ApplicationRecord validates :case, :role, :state, :team, presence: true validates :reasons_for_rejection, presence: true, if: -> { self.rejected? } validate :approved_only_for_approvals validate :unique_pending_responder enum state: { pending: 'pending', rejected: 'rejected', accepted: 'accepted', bypassed: 'bypassed' } enum role: { managing: 'managing', responding: 'responding', approving: 'approving', } belongs_to :case, foreign_key: :case_id, class_name: 'Case::Base' belongs_to :team belongs_to :user scope :approved, -> { where(approved: true) } scope :unapproved, -> { where(approved: false) } scope :for_user, -> (user) { where(user: user) } scope :with_teams, -> (teams) do where(team: teams, state: ['pending', 'accepted']) end scope :for_team, -> (team) { where(team: team) } scope :pending_accepted, -> { where(state: %w[pending accepted]) } scope :last_responding, -> { responding.where.not(state: 'rejected').order(id: :desc).limit(1) } attr_accessor :reasons_for_rejection before_save :mark_case_as_dirty_for_responding_assignments def reject(rejecting_user, message) self.reasons_for_rejection = message self.case.responder_assignment_rejected(rejecting_user, team, message) rejected! end def accept(accepting_user) self.case.responder_assignment_accepted(accepting_user, team) self.user = accepting_user self.accepted! end def assign_and_validate_state(state) assign_attributes(state: state) valid? end private def mark_case_as_dirty_for_responding_assignments if responding? if new_record? || state_changed_to_rejected_or_bypassed? self.case.mark_as_dirty! SearchIndexUpdaterJob.set(wait: 10.seconds).perform_later end end end def state_changed_to_rejected_or_bypassed? changed.include?('state') && state.in?(%w{ rejected bypassed} ) end def unique_pending_responder if self.case if state == 'pending' && role == 'responding' num_existing = self.case&.assignments.responding.pending.size if num_existing > 1 errors.add(:state, 'responding not unique') end end end end def approved_only_for_approvals if approved? && role != 'approving' errors.add(:approved, 'true') end end end
26.118182
77
0.653672
39b786a9a4faf9f44b0356964f1d6ab9eaab55d1
2,574
def adopt(user_city) adopt_hash = { :Chicago=>"http://www.pawschicago.org/", :NYC=>"http://www.humanesocietyny.org/adoptions/", :Boston=>"http://www.arlboston.org/", :Austin=>"https://www.austinpetsalive.org/", :Miami=>"http://www.miamidade.gov/animals/adopt-a-pet.asp", :LA=>"http://www.laanimalservices.com/volunteer/volunteer-oppurtunies/", :STL=>"https://www.strayrescue.org/", :Oakland=>"http://www.oaklandanimalservices.org/", :Detroit=>"http://www.michiganhumane.org/adoption/locations/adopt_detroit.html?referrer=https://www.google.com/", :Indianapolis=>"http://www.ssasi.org/", :Seattle=>"http://www.seattle.gov/animalshelter/", } return adopt_hash[:"#{user_city}"] end def volunteer(user_city) volunteer_hash = { :Chicago=>"http://www.pawschicago.org/how-to-help/volunteer/volunteer-opportunities/", :NYC=>"https://www.bideawee.org/Volunteer", :Boston=>"http://www.arlboston.org/volunteer/", :Austin=>"https://www.austinpetsalive.org/get-involved/volunteer/", :Miami=>"http://www.miamidade.gov/animals/volunteer-orientation.asp", :LA=>"http://la.bestfriends.org/adopt/adoption-centers", :STL=>"https://www.strayrescue.org/volunteer-at-our-shelter", :Oakland=>"http://www.oaklandanimalservices.org/", :Detroit=>"http://www.michiganhumane.org/adoption/locations/adopt_detroit.html?referrer=https://www.google.com/", :Indianapolis=>"http://www.ssasi.org/", :Seattle=>"http://www.seattle.gov/animalshelter/", } return volunteer_hash[:"#{user_city}"] end def images(user_city) images = { :Chicago=>"https://www.achicagothing.com/wp-content/uploads/2013/10/lpftd.jpg", :NYC=>"http://animalalliancenyc.org/feralcats/wp-content/uploads/PhotoNav-HSNY.jpg", :Boston=>"http://www.arlboston.org/wp-content/uploads/2013/10/BRECKMarathongtFront.jpg", :Austin=>"https://assets.networkforgood.org/1899/Images/Page/35e76a39-ed9a-43ea-bdc7-244b48808162.png", :Miami=>"org/wp-content/uploads/2016/07/Ddd4GdYH.jpeg", :LA=>"http://empowerla.org/wp-content/uploads/2012/11/LA_AnimalServices.jpg", :STL=>"https://www.stlouis-mo.gov/government/departments/mayor/news/images/stray-rescue.jpeg", :Oakland=>"http://www.oaklandanimalservices.org/wp-content/uploads/2016/04/OAS-logo-fbdefault.jpg", :Detroit=>"http://support.michiganhumane.org/images/mihs08/logoMain.jpg", :Indianapolis=>"http://www.ssasi.org/", :Seattle=>"http://www.seattle.gov/animalshelter/" } return images[:"#{user_city}"] end
51.48
119
0.693862
38d9b8421485810496a19e0e0534c98eab2c2e0d
3,415
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::BotService::Mgmt::V2017_12_01_preview module Models # # The parameters to provide for the Facebook channel. # class FacebookChannelProperties include MsRestAzure # @return [String] Verify token. Value only returned through POST to the # action Channel List API, otherwise empty. attr_accessor :verify_token # @return [Array<FacebookPage>] The list of Facebook pages attr_accessor :pages # @return [String] Facebook application id attr_accessor :app_id # @return [String] Facebook application secret. Value only returned # through POST to the action Channel List API, otherwise empty. attr_accessor :app_secret # @return [String] Callback Url attr_accessor :callback_url # @return [Boolean] Whether this channel is enabled for the bot attr_accessor :is_enabled # # Mapper for FacebookChannelProperties class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'FacebookChannelProperties', type: { name: 'Composite', class_name: 'FacebookChannelProperties', model_properties: { verify_token: { client_side_validation: true, required: false, read_only: true, serialized_name: 'verifyToken', type: { name: 'String' } }, pages: { client_side_validation: true, required: false, serialized_name: 'pages', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'FacebookPageElementType', type: { name: 'Composite', class_name: 'FacebookPage' } } } }, app_id: { client_side_validation: true, required: true, serialized_name: 'appId', type: { name: 'String' } }, app_secret: { client_side_validation: true, required: true, serialized_name: 'appSecret', type: { name: 'String' } }, callback_url: { client_side_validation: true, required: false, read_only: true, serialized_name: 'callbackUrl', type: { name: 'String' } }, is_enabled: { client_side_validation: true, required: true, serialized_name: 'isEnabled', type: { name: 'Boolean' } } } } } end end end end
29.95614
78
0.487555
4a56c8be616a9cec39455659653fc8436bd9cbfd
504
Gem::Specification.new do |s| s.name = 'rack-ssl' s.version = '1.3.2' s.date = '2011-03-24' s.homepage = "https://github.com/josh/rack-ssl" s.summary = "Force SSL/TLS in your app." s.description = <<-EOS Rack middleware to force SSL/TLS. EOS s.files = [ 'lib/rack/ssl.rb', 'LICENSE', 'README.md' ] s.add_dependency 'rack' s.authors = ["Joshua Peek"] s.email = "josh@joshpeek.com" s.rubyforge_project = 'rack-ssl' end
21
52
0.563492
267526a4de2e09b3d9aed9b06e2eee61bee68c66
121
require 'test_helper' class RecursoTest < ActiveSupport::TestCase # test "the truth" do # assert true # end end
15.125
43
0.702479
182026b6043c44ab78fe1afa4468342773fce4ee
4,063
require "stringio" describe Fastlane::Actions do describe "#podspechelper" do before do @version_podspec_file = Fastlane::Helper::PodspecHelper.new end it "raises an exception when an incorrect path is given" do expect do Fastlane::Helper::PodspecHelper.new('invalid_podspec') end.to raise_error("Could not find podspec file at path 'invalid_podspec'") end it "raises an exception when there is no version in podspec" do expect do Fastlane::Helper::PodspecHelper.new.parse("") end.to raise_error("Could not find version in podspec content ''") end it "raises an exception when the version is commented-out in podspec" do test_content = '# s.version = "1.3.2"' expect do Fastlane::Helper::PodspecHelper.new.parse(test_content) end.to raise_error("Could not find version in podspec content '#{test_content}'") end context "when semantic version" do it "returns the current version once parsed" do test_content = 'spec.version = "1.3.2"' result = @version_podspec_file.parse(test_content) expect(result).to eq('1.3.2') expect(@version_podspec_file.version_value).to eq('1.3.2') expect(@version_podspec_file.version_match[:major]).to eq('1') expect(@version_podspec_file.version_match[:minor]).to eq('3') expect(@version_podspec_file.version_match[:patch]).to eq('2') end context "with appendix" do it "returns the current version once parsed with appendix" do test_content = 'spec.version = "1.3.2.4"' result = @version_podspec_file.parse(test_content) expect(result).to eq('1.3.2.4') expect(@version_podspec_file.version_value).to eq('1.3.2.4') expect(@version_podspec_file.version_match[:major]).to eq('1') expect(@version_podspec_file.version_match[:minor]).to eq('3') expect(@version_podspec_file.version_match[:patch]).to eq('2') expect(@version_podspec_file.version_match[:appendix]).to eq('.4') end it "returns the current version once parsed with longer appendix" do test_content = 'spec.version = "1.3.2.4.5"' result = @version_podspec_file.parse(test_content) expect(result).to eq('1.3.2.4.5') expect(@version_podspec_file.version_value).to eq('1.3.2.4.5') expect(@version_podspec_file.version_match[:major]).to eq('1') expect(@version_podspec_file.version_match[:minor]).to eq('3') expect(@version_podspec_file.version_match[:patch]).to eq('2') expect(@version_podspec_file.version_match[:appendix]).to eq('.4.5') end end it "returns the current version once parsed with prerelease" do test_content = 'spec.version = "1.3.2-SNAPSHOT"' result = @version_podspec_file.parse(test_content) expect(result).to eq('1.3.2-SNAPSHOT') expect(@version_podspec_file.version_value).to eq('1.3.2-SNAPSHOT') expect(@version_podspec_file.version_match[:major]).to eq('1') expect(@version_podspec_file.version_match[:minor]).to eq('3') expect(@version_podspec_file.version_match[:patch]).to eq('2') expect(@version_podspec_file.version_match[:prerelease]).to eq('SNAPSHOT') end it "returns the current version once parsed with appendix and prerelease" do test_content = 'spec.version = "1.3.2.4-SNAPSHOT"' result = @version_podspec_file.parse(test_content) expect(result).to eq('1.3.2.4-SNAPSHOT') expect(@version_podspec_file.version_value).to eq('1.3.2.4-SNAPSHOT') expect(@version_podspec_file.version_match[:major]).to eq('1') expect(@version_podspec_file.version_match[:minor]).to eq('3') expect(@version_podspec_file.version_match[:patch]).to eq('2') expect(@version_podspec_file.version_match[:appendix]).to eq('.4') expect(@version_podspec_file.version_match[:prerelease]).to eq('SNAPSHOT') end end end end
46.170455
87
0.668225
bba33ca22ce982f0a7e9fea29a05bb44f1732c71
149
class AddUserRefToInstruments < ActiveRecord::Migration def change add_reference :instruments, :user, index: true, foreign_key: true end end
24.833333
69
0.778523
5d94c6bd919b83c6188f8c9c46e6b56e4f40260d
434
module Gerry class Client module Changes # Get changes visible to the caller. # # @param [Array] options the query parameters. # @return [Hash] the changes. def changes(options = []) url = '/changes/' if options.empty? return get(url) end options = map_options(options) get("#{url}?#{options}") end end end end
21.7
52
0.516129
b9d159bcd027347c097ea6546a658c785a0a7d5d
2,686
# frozen_string_literal: true # This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'csv' # Users 3.times do |i| qrcode = i.to_s.rjust(12, '0') u = User.create!(name: "dev#{i}", qrcode: qrcode) u.preferences.create!(note_speed: 10.0, se_volume: 5, platform: :button) u.preferences.create!(note_speed: 10.0, se_volume: 5, platform: :board) end # Musics csv_path = Rails.root.join('musics.csv') CSV.foreach(csv_path) do |row| next unless row[1] =~ /\A\d+\z/ id = row[1].to_i title = row[2] artist = row[3] next if title.blank? Music.create!(id: id, title: title, artist: artist) end # Scores Score.create!( user: User.first, music: Music.first, difficulty: :normal, points: 800_000, max_combo: 50, critical_count: 100, correct_count: 30, nice_count: 10, miss_count: 2, played_times: 1, platform: :button ) Score.create!( user: User.second, music: Music.first, difficulty: :normal, points: 900_000, max_combo: 50, critical_count: 100, correct_count: 30, nice_count: 10, miss_count: 2, played_times: 1, platform: :button, ) Score.create!( user: User.third, music: Music.first, difficulty: :normal, points: 950_000, max_combo: 50, critical_count: 100, correct_count: 30, nice_count: 10, miss_count: 2, played_times: 1, platform: :button, ) Score.create!( user: User.first, music: Music.second, difficulty: :normal, points: 800_000, max_combo: 50, critical_count: 100, correct_count: 30, nice_count: 10, miss_count: 2, played_times: 1, platform: :button, ) Score.create!( user: User.second, music: Music.second, difficulty: :normal, points: 900_000, max_combo: 50, critical_count: 100, correct_count: 30, nice_count: 10, miss_count: 2, played_times: 1, platform: :button, ) Score.create!( user: User.third, music: Music.second, difficulty: :normal, points: 950_000, max_combo: 50, critical_count: 100, correct_count: 30, nice_count: 10, miss_count: 2, played_times: 1, platform: :button, )
23.561404
111
0.600894
03482f80c748f3438223044db58fbb0ffb9a0506
328
class Specinfra::Command::Freebsd::Base::Service < Specinfra::Command::Base::Service class << self def check_is_enabled(service, level=3) "service #{escape(service)} enabled" end def check_is_running_under_init(service) "service #{escape(service)} status | grep -E 'as (pid [0-9]+)'" end end end
29.818182
84
0.67378
39602dcd1c15827923832bd4e41264ca4ad3439d
1,417
control "PHTN-10-000019" do title "The Photon operating system must allow only the ISSM (or individuals or roles appointed by the ISSM) to select which auditable events are to be audited." desc "Without the capability to restrict which roles and individuals can select which events are audited, unauthorized personnel may be able to prevent the auditing of critical events. Misconfigured audits may degrade the system's performance by overwhelming the audit log. Misconfigured audits may also make it more difficult to establish, correlate, and investigate the events relating to an incident or identify those responsible for one." impact 0.5 tag severity: "CAT II" tag gtitle: "SRG-OS-000063-GPOS-00032" tag gid: nil tag rid: "PHTN-10-000019" tag stig_id: "PHTN-10-000019" tag cci: "CCI-000171" tag nist: ["AU-12 b", "Rev_4"] desc 'check', "At the command line, execute the following command: # find /etc/audit/* -type f -exec stat -c \"%n permissions are %a\" {} $1\\; If the permissions of any files are more permissive than 640, then this is a finding." desc 'fix', "At the command line, execute the following command: # chmod 640 <file> Replace <file> with any file with incorrect permissions." command(' find /etc/audit/* -maxdepth 1 -type f').stdout.split.each do | fname | describe file(fname) do it { should_not be_more_permissive_than('0640') } end end end
36.333333
82
0.736768
79fd5816ea9bf9bc48b8d6bc7b1ecae5f39d17f5
213
require 'social_net/facebook/config' require 'social_net/facebook/models' require 'social_net/facebook/errors' module SocialNet module Facebook extend Config include Errors include Models end end
17.75
36
0.779343
abf532b910b7e7eff6981d2487a48570bc2d1a1c
171
http_path = "/" sass_dir = "assets/sass" css_dir = "assets/css" images_dir = "assets/images" javascripts_dir = "assets/js" relative_assets = true output_style = :expanded
21.375
29
0.74269
79f1b49e5d55a3673f61f39d8db52315baf77721
8,686
class Certbot < Formula include Language::Python::Virtualenv desc "Tool to obtain certs from Let's Encrypt and autoenable HTTPS" homepage "https://certbot.eff.org/" url "https://files.pythonhosted.org/packages/e4/9a/affc25d8d52e2977bd58dc79b6825a62a0d4c315048cb4c5144dcd71371a/certbot-1.19.0.tar.gz" sha256 "015cbe210498a01f38b04ca32502c9142ba0e8aeea74bb6ba81a985df14a072c" license "Apache-2.0" head "https://github.com/certbot/certbot.git", branch: "master" bottle do sha256 cellar: :any, arm64_big_sur: "dbd4ffa12c06700e9c8ee0ef306e411452b74bde4f6d37d2128eeb950e18ae78" sha256 cellar: :any, big_sur: "8b714c28c178dd922a234209116bb15ec195d8887c9e0be642090c202d2e0362" sha256 cellar: :any, catalina: "af54d4835a5dbd3aa67bbd8201f82a54a5dd7e3964937dfc3cd0af1aa649338e" sha256 cellar: :any, mojave: "2b242a80867b022e22f1c970c867ee95e36fc0357b773a694e6a394923714230" sha256 cellar: :any_skip_relocation, x86_64_linux: "08cd1eab56ef89cecce74707836ed37df204f5d07baef8b5f73bb2adf3427a1f" end depends_on "rust" => :build # for cryptography depends_on "augeas" depends_on "dialog" depends_on "openssl@1.1" depends_on "python@3.9" uses_from_macos "libffi" on_linux do depends_on "pkg-config" => :build end resource "acme" do url "https://files.pythonhosted.org/packages/e7/eb/2e3099968ca3f1747c04bd0fab26bf21b6d15ffda0a25af51d95aa59800b/acme-1.19.0.tar.gz" sha256 "a7071c5576032092d3f5aa77d4424feb943745ce95714d3194e88df74c3359ce" end resource "certbot-apache" do url "https://files.pythonhosted.org/packages/be/00/173c43a374e5443f257fff25a18bf435da36c2be560ea3f066ac5f2217ec/certbot-apache-1.19.0.tar.gz" sha256 "4f080da078ae77eda1d8ba20383f1a0fbac540a99cab6e93cae8f08f043fbd48" end resource "certbot-nginx" do url "https://files.pythonhosted.org/packages/48/f5/0407c2a9f9d828af66f4580b7b3ab2e49444b61794482a94d6dac2c8889c/certbot-nginx-1.19.0.tar.gz" sha256 "0c2b6b0185304c8d73f7c0ce5fbfe82a03c2322fec09c4dc6c44beee8e18f246" end resource "certifi" do url "https://files.pythonhosted.org/packages/6d/78/f8db8d57f520a54f0b8a438319c342c61c22759d8f9a1cd2e2180b5e5ea9/certifi-2021.5.30.tar.gz" sha256 "2bbf76fd432960138b3ef6dda3dde0544f27cbf8546c458e60baf371917ba9ee" end resource "cffi" do url "https://files.pythonhosted.org/packages/2e/92/87bb61538d7e60da8a7ec247dc048f7671afe17016cd0008b3b710012804/cffi-1.14.6.tar.gz" sha256 "c9a875ce9d7fe32887784274dd533c57909b7b1dcadcc128a2ac21331a9765dd" end resource "charset-normalizer" do url "https://files.pythonhosted.org/packages/e7/4e/2af0238001648ded297fb54ceb425ca26faa15b341b4fac5371d3938666e/charset-normalizer-2.0.4.tar.gz" sha256 "f23667ebe1084be45f6ae0538e4a5a865206544097e4e8bbcacf42cd02a348f3" end resource "ConfigArgParse" do url "https://files.pythonhosted.org/packages/42/1c/3e40ae017361f30b01b391b1ee263ec93e4c2666221c69ebba297ff33be6/ConfigArgParse-1.5.2.tar.gz" sha256 "c39540eb4843883d526beeed912dc80c92481b0c13c9787c91e614a624de3666" end resource "configobj" do url "https://files.pythonhosted.org/packages/64/61/079eb60459c44929e684fa7d9e2fdca403f67d64dd9dbac27296be2e0fab/configobj-5.0.6.tar.gz" sha256 "a2f5650770e1c87fb335af19a9b7eb73fc05ccf22144eb68db7d00cd2bcb0902" end resource "cryptography" do url "https://files.pythonhosted.org/packages/cc/98/8a258ab4787e6f835d350639792527d2eb7946ff9fc0caca9c3f4cf5dcfe/cryptography-3.4.8.tar.gz" sha256 "94cc5ed4ceaefcbe5bf38c8fba6a21fc1d365bb8fb826ea1688e3370b2e24a1c" end resource "distro" do url "https://files.pythonhosted.org/packages/a5/26/256fa167fe1bf8b97130b4609464be20331af8a3af190fb636a8a7efd7a2/distro-1.6.0.tar.gz" sha256 "83f5e5a09f9c5f68f60173de572930effbcc0287bb84fdc4426cb4168c088424" end resource "idna" do url "https://files.pythonhosted.org/packages/cb/38/4c4d00ddfa48abe616d7e572e02a04273603db446975ab46bbcd36552005/idna-3.2.tar.gz" sha256 "467fbad99067910785144ce333826c71fb0e63a425657295239737f7ecd125f3" end resource "josepy" do url "https://files.pythonhosted.org/packages/80/0d/4a2c00b8683b9e6c0fffa9b723dfa07feb3e8bcc6adcdf0890cf7501acd0/josepy-1.8.0.tar.gz" sha256 "a5a182eb499665d99e7ec54bb3fe389f9cbc483d429c9651f20384ba29564269" end resource "parsedatetime" do url "https://files.pythonhosted.org/packages/a8/20/cb587f6672dbe585d101f590c3871d16e7aec5a576a1694997a3777312ac/parsedatetime-2.6.tar.gz" sha256 "4cb368fbb18a0b7231f4d76119165451c8d2e35951455dfee97c62a87b04d455" end resource "pycparser" do url "https://files.pythonhosted.org/packages/0f/86/e19659527668d70be91d0369aeaa055b4eb396b0f387a4f92293a20035bd/pycparser-2.20.tar.gz" sha256 "2d475327684562c3a96cc71adf7dc8c4f0565175cf86b6d7a404ff4c771f15f0" end resource "pyOpenSSL" do url "https://files.pythonhosted.org/packages/98/cd/cbc9c152daba9b5de6094a185c66f1c6eb91c507f378bb7cad83d623ea88/pyOpenSSL-20.0.1.tar.gz" sha256 "4c231c759543ba02560fcd2480c48dcec4dae34c9da7d3747c508227e0624b51" end resource "pyparsing" do url "https://files.pythonhosted.org/packages/c1/47/dfc9c342c9842bbe0036c7f763d2d6686bcf5eb1808ba3e170afdb282210/pyparsing-2.4.7.tar.gz" sha256 "c203ec8783bf771a155b207279b9bccb8dea02d8f0c9e5f8ead507bc3246ecc1" end resource "pyRFC3339" do url "https://files.pythonhosted.org/packages/00/52/75ea0ae249ba885c9429e421b4f94bc154df68484847f1ac164287d978d7/pyRFC3339-1.1.tar.gz" sha256 "81b8cbe1519cdb79bed04910dd6fa4e181faf8c88dff1e1b987b5f7ab23a5b1a" end resource "python-augeas" do url "https://files.pythonhosted.org/packages/af/cc/5064a3c25721cd863e6982b87f10fdd91d8bcc62b6f7f36f5231f20d6376/python-augeas-1.1.0.tar.gz" sha256 "5194a49e86b40ffc57055f73d833f87e39dce6fce934683e7d0d5bbb8eff3b8c" end resource "pytz" do url "https://files.pythonhosted.org/packages/b0/61/eddc6eb2c682ea6fd97a7e1018a6294be80dba08fa28e7a3570148b4612d/pytz-2021.1.tar.gz" sha256 "83a4a90894bf38e243cf052c8b58f381bfe9a7a483f6a9cab140bc7f702ac4da" end resource "requests" do url "https://files.pythonhosted.org/packages/e7/01/3569e0b535fb2e4a6c384bdbed00c55b9d78b5084e0fb7f4d0bf523d7670/requests-2.26.0.tar.gz" sha256 "b8aa58f8cf793ffd8782d3d8cb19e66ef36f7aba4353eec859e74678b01b07a7" end resource "requests-toolbelt" do url "https://files.pythonhosted.org/packages/28/30/7bf7e5071081f761766d46820e52f4b16c8a08fef02d2eb4682ca7534310/requests-toolbelt-0.9.1.tar.gz" sha256 "968089d4584ad4ad7c171454f0a5c6dac23971e9472521ea3b6d49d610aa6fc0" end resource "six" do url "https://files.pythonhosted.org/packages/71/39/171f1c67cd00715f190ba0b100d606d440a28c93c7714febeca8b79af85e/six-1.16.0.tar.gz" sha256 "1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926" end resource "urllib3" do url "https://files.pythonhosted.org/packages/4f/5a/597ef5911cb8919efe4d86206aa8b2658616d676a7088f0825ca08bd7cb8/urllib3-1.26.6.tar.gz" sha256 "f57b4c16c62fa2760b7e3d97c35b255512fb6b59a259730f36ba32ce9f8e342f" end resource "zope.component" do url "https://files.pythonhosted.org/packages/c5/c0/64931e1e8f2bfde9d8bc01670de2d2a395efcf8f49d3a9daa21cf3ffee2b/zope.component-5.0.1.tar.gz" sha256 "32cbe426ba8fa7b62ce5b211f80f0718a0c749cc7ff09e3f4b43a57f7ccdf5e5" end resource "zope.event" do url "https://files.pythonhosted.org/packages/30/00/94ed30bfec18edbabfcbd503fcf7482c5031b0fbbc9bc361f046cb79781c/zope.event-4.5.0.tar.gz" sha256 "5e76517f5b9b119acf37ca8819781db6c16ea433f7e2062c4afc2b6fbedb1330" end resource "zope.hookable" do url "https://files.pythonhosted.org/packages/10/6d/47d817b01741477ce485f842649b02043639d1f9c2f50600052766c99821/zope.hookable-5.1.0.tar.gz" sha256 "8fc3e6cd0486c6af48e3317c299def719b57538332a194e0b3bc6a772f4faa0e" end resource "zope.interface" do url "https://files.pythonhosted.org/packages/ae/58/e0877f58daa69126a5fb325d6df92b20b77431cd281e189c5ec42b722f58/zope.interface-5.4.0.tar.gz" sha256 "5dba5f530fec3f0988d83b78cc591b58c0b6eb8431a85edd1569a0539a8a5a0e" end def install virtualenv_install_with_resources bin.install_symlink libexec/"bin/certbot" pkgshare.install buildpath/"examples" end test do assert_match version.to_s, pipe_output("#{bin}/certbot --version 2>&1") # This throws a bad exit code but we can check it actually is failing # for the right reasons by asserting. --version never fails even if # resources are missing or outdated/too new/etc. assert_match "Either run as root", shell_output("#{bin}/certbot 2>&1", 1) end end
48.255556
148
0.812457
1ca87acf12c60124a40eed7a7aea10e423f77b0c
491
Rails::Generator::Commands::Create.class_eval do def rake_db_migrate logger.rake "db:migrate" unless system("rake db:migrate") logger.rake "db:migrate failed. Rolling back" command(:destroy).invoke! end end end Rails::Generator::Commands::Destroy.class_eval do def rake_db_migrate logger.rake "db:rollback" system "rake db:rollback" end end Rails::Generator::Commands::List.class_eval do def rake_db_migrate logger.rake "db:migrate" end end
21.347826
51
0.718941
395eab6fe36a338922329e6a4faafdb7769f0697
48
module RackspaceCloudDns VERSION = "0.2.0" end
16
24
0.75
03fca3eb974e7aa831c0abbf2d052b627a3d5c15
1,862
require 'open3' require 'slop' require 'nokogiri' require 'monitor' require 'httpclient' require 'hashie' require 'json' require 'active_support/all' require 'rexml/document' require 'rexml/formatters/pretty' require_relative 'property_tagger/version' require_relative 'property_tagger/cli' require_relative 'property_tagger/remote_aspects_cache' require_relative 'property_tagger/file_aspects_cache' require_relative 'property_tagger/processor' module Opener ## # Ruby wrapper around the Python based polarity tagger. # # @!attribute [r] options # @return [Hash] # # @!attribute [r] args # @return [Array] # class PropertyTagger attr_reader :options, :args ## # @param [Hash] options # # @option options [Array] :args Collection of arbitrary arguments to pass # to the underlying kernel. # # @option options [TrueClass] :no_time Disables adding of timestamps. # def initialize(options = {}) @args = options.delete(:args) || [] @options = options end ## # Get the resource path for the lexicon files, defaults to an ENV variable # # @return [String] # def path return @path if @path @path = options[:resource_path] || ENV['RESOURCE_PATH'] || ENV['PROPERTY_TAGGER_LEXICONS_PATH'] return unless @path @path = File.expand_path @path end def remote_url @remote_url ||= ENV['PROPERTY_TAGGER_LEXICONS_URL'] end ## # Processes the input KAF document. # # @param [String] input # @return [String] # def run input, params = {} timestamp = !options[:no_time] Processor.new(input, params: params, url: remote_url, path: path, timestamp: timestamp, pretty: options[:pretty], ).process end end end
21.905882
78
0.643931
7aa1b270c53d1ab2ce8a9bd677644c78d50b9664
492
require 'spec_helper' describe Icalendar::Todo do describe '#dtstart' do it 'is not normally required' do subject.dtstart = nil expect(subject).to be_valid end context 'with duration set' do before(:each) { subject.duration = 'PT15M' } it 'is invalid if not set' do expect(subject).to_not be_valid end it 'is valid when set' do subject.dtstart = Date.today expect(subject).to be_valid end end end end
19.68
50
0.623984
08da8ae8faa4a26bc7de881b79b1d46975293040
1,292
Gem::Specification.new do |s| s.name = 'logstash-codec-rubydebug' s.version = '3.0.3' s.licenses = ['Apache License (2.0)'] s.summary = "The rubydebug codec will output your Logstash event data using the Ruby Awesome Print library." s.description = "This gem is a Logstash plugin required to be installed on top of the Logstash core pipeline using $LS_HOME/bin/logstash-plugin install gemname. This gem is not a stand-alone program" s.authors = ["Elastic"] s.email = 'info@elastic.co' s.homepage = "http://www.elastic.co/guide/en/logstash/current/index.html" s.require_paths = ["lib"] # Files s.files = Dir["lib/**/*","spec/**/*","*.gemspec","*.md","CONTRIBUTORS","Gemfile","LICENSE","NOTICE.TXT", "vendor/jar-dependencies/**/*.jar", "vendor/jar-dependencies/**/*.rb", "VERSION", "docs/**/*"] # Tests s.test_files = s.files.grep(%r{^(test|spec|features)/}) # Special flag to let us know this is actually a logstash plugin s.metadata = { "logstash_plugin" => "true", "logstash_group" => "codec" } # Gem dependencies s.add_runtime_dependency "logstash-core-plugin-api", ">= 1.60", "<= 2.99" s.add_runtime_dependency 'awesome_print' s.add_development_dependency 'logstash-devutils' end
43.066667
205
0.657121
d59c512a2bbafe135acdea7b7e394a781ca95e19
152
# encoding: utf-8 module Backup module Configuration module Encryptor class Base < Backup::Configuration::Base end end end end
13.818182
46
0.671053
1af93845f1639e5f1ddf8a6ff144f3f2cb0f1f37
815
# encoding: utf-8 Gem::Specification.new do |spec| spec.add_dependency 'delayed_job', ['>= 3.0', '< 5'] spec.add_dependency 'mongoid', ['>= 3.0', '< 7'] spec.add_dependency 'mongoid-compatibility', '>= 0.4.0' spec.authors = ['Chris Gaffney', 'Brandon Keepers', 'Erik Michaels-Ober'] spec.email = ['chris@collectiveidea.com', 'brandon@opensoul.com', 'sferik@gmail.com'] spec.files = %w(CHANGELOG.md CONTRIBUTING.md LICENSE.md README.md delayed_job_mongoid.gemspec) + Dir['lib/**/*.rb'] spec.homepage = 'http://github.com/collectiveidea/delayed_job_mongoid' spec.licenses = ['MIT'] spec.name = 'delayed_job_mongoid' spec.require_paths = ['lib'] spec.summary = 'Mongoid backend for delayed_job' spec.version = '2.3.1' end
47.941176
127
0.633129