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
1d74a901f9be23360286296d0d3037a986e3096a
936
require File.expand_path '../../test_helper', __dir__ # Test class for List Deployment Request class TestListDeployment < Minitest::Test def setup @service = Fog::Resources::AzureRM.new(credentials) @client = @service.instance_variable_get(:@rmc) @deployments = @client.deployments @resource_group = 'fog-test-rg' end def test_list_deployment_success mocked_response = ApiStub::Requests::Resources::Deployment.list_deployment_response(@client) @deployments.stub :list_as_lazy, mocked_response do assert_equal @service.list_deployments(@resource_group), mocked_response.value end end def test_list_deployment_failure response = proc { raise MsRestAzure::AzureOperationError.new(nil, nil, 'error' => { 'message' => 'mocked exception' }) } @deployments.stub :list_as_lazy, response do assert_raises(RuntimeError) { @service.list_deployments(@resource_group) } end end end
36
124
0.745726
1aebff9717060c338a651fdc3c74bfaa55e2e205
1,120
# frozen_string_literal: true require 'rainbow' module Root module Display # Handle logic for showing the victory points # Either stack, or all one square? # Some way to handle it so it's not shifting constantly. class Hand attr_reader :hand def initialize(hand) @hand = hand end def display ::Terminal::Table.new( rows: rows ) end def rows [ hand.map { |card| handle_name(card) }, hand.map { |card| handle_phase(card) }, hand.map { |card| handle_body(card) } ] end def handle_name(card) craft_text = card .craft .map { |suit| Rainbow(suit.capitalize).fg(Colors::SUIT_COLOR[suit]) } .join(', ') format_craft_text = craft_text.empty? ? '' : " (#{craft_text})" title = Rainbow(card.name).fg(Colors::SUIT_COLOR[card.suit]) "#{title}#{format_craft_text}" end def handle_phase(card) card.phase end def handle_body(card) card.body end end end end
21.132075
79
0.551786
79e50dd53fe9021266fbadaecaa972a194c1d6b2
812
Gem::Specification.new do |s| s.name = 'jekyll-rushed-analytics' s.version = '0.1.15.pre' s.date = '2021-11-16' s.summary = "Jekyll plugin that handle analytic like google analytic, adsense, mpuls, piwik etc" s.description = "Plugin to easily add web analytics to your jekyll site without modifying your templates. Supported are: Google Analytics, Piwik, Matomo, MPulse" s.authors = ["Adi Prasetyo", "Hendrik Schneider"] s.email = '[email protected]' s.files = ["lib/jekyll-rushed-analytics.rb"] s.files += Dir["lib/analytics/*.rb"] s.homepage = 'https://github.com/ap-automator/jekyll-rushed-analytics' s.license = 'MIT' s.metadata = { "source_code_uri" => "https://github.com/ap-automator/jekyll-rushed-analytics" } end
54.133333
163
0.667488
8723427b5afa4e890cbbc124a6016169a0ed1b8e
473
require 'skeptick/sugar/compose' require 'skeptick/sugar/write' require 'skeptick/sugar/draw' require 'skeptick/sugar/canvas' require 'skeptick/sugar/font' require 'skeptick/sugar/text' require 'skeptick/sugar/geometry' require 'skeptick/sugar/clone' require 'skeptick/sugar/delete' require 'skeptick/sugar/swap' require 'skeptick/sugar/format' require 'skeptick/sugar/resized_image' require 'skeptick/sugar/rounded_corners_image' require 'skeptick/sugar/torn_paper_image'
31.533333
46
0.82241
9154887ab2865d6aae9b3990cfe6d371bd818fd7
8,556
require 'rbconfig' # ruby 1.8.7 doesn't define RUBY_ENGINE ruby_engine = defined?(RUBY_ENGINE) ? RUBY_ENGINE : 'ruby' ruby_version = RbConfig::CONFIG["ruby_version"] path = File.expand_path('..', __FILE__) $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/concurrent-ruby-1.1.9/lib/concurrent-ruby" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/i18n-1.8.10/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/minitest-5.14.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/tzinfo-2.0.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/zeitwerk-2.5.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/activesupport-6.1.4.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/public_suffix-4.0.6/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/addressable-2.8.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ast-2.4.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/bindata-2.4.10/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/x86_64-darwin-14/2.6.0-static/msgpack-1.4.2" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/msgpack-1.4.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/x86_64-darwin-14/2.6.0-static/bootsnap-1.9.1" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/bootsnap-1.9.1/lib" $:.unshift "#{path}/" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/x86_64-darwin-14/2.6.0-static/byebug-11.1.3" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/byebug-11.1.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/coderay-1.1.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/highline-2.0.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/commander-4.6.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/connection_pool-2.2.5/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/did_you_mean-1.5.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/diff-lcs-1.4.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/docile-1.4.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/x86_64-darwin-14/2.6.0-static/unf_ext-0.0.8" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/unf_ext-0.0.8/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/unf-0.1.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/domain_name-0.5.20190701/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/regexp_parser-2.1.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ecma-re-validator-0.3.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/elftools-1.1.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/hana-1.3.7/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/x86_64-darwin-14/2.6.0-static/hpricot-0.8.6" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/hpricot-0.8.6/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/http-cookie-1.0.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/uri_template-0.7.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/json_schemer-0.2.18/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mime-types-data-3.2021.0901/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mime-types-3.3.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/net-http-digest_auth-1.4.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/net-http-persistent-4.0.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mini_portile2-2.6.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/x86_64-darwin-14/2.6.0-static/racc-1.6.0" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/racc-1.6.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/nokogiri-1.12.5-x86_64-darwin/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubyntlm-0.6.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/webrick-1.7.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/webrobots-0.1.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mechanize-2.8.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/method_source-1.0.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/mustache-1.1.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/parallel-1.21.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/parallel_tests-3.7.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/parser-3.0.2.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rainbow-3.0.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/sorbet-runtime-0.5.9287/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/parlour-6.0.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/patchelf-1.3.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/plist-3.6.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/pry-0.14.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rack-2.2.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/unparser-0.6.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rbi-0.0.6/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/extensions/x86_64-darwin-14/2.6.0-static/rdiscount-2.2.0.2" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rdiscount-2.2.0.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rexml-3.2.5/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ronn-0.7.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-support-3.10.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-core-3.10.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-expectations-3.10.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-mocks-3.10.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-3.10.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-github-2.3.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-its-1.3.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-retry-0.6.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/sorbet-static-0.5.9287-universal-darwin-14/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/sorbet-0.5.9287/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-sorbet-1.8.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec-wait-0.0.9/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rspec_junit_formatter-0.4.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-ast-1.12.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ruby-progressbar-1.11.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/unicode-display_width-2.1.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-1.22.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-performance-1.11.5/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-rails-2.12.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-rspec-2.5.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/rubocop-sorbet-0.6.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/ruby-macho-2.5.1/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/simplecov-html-0.12.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/simplecov_json_formatter-0.1.3/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/simplecov-0.21.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/simplecov-cobertura-1.4.2/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/sorbet-runtime-stub-0.2.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/thor-1.1.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/spoom-1.1.5/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/yard-0.9.26/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/yard-sorbet-0.6.0/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/tapioca-0.5.4/lib" $:.unshift "#{path}/../#{ruby_engine}/#{ruby_version}/gems/warning-1.2.1/lib"
80.716981
113
0.669822
6a4463f2989ef575313125b5f9fe8ab43b3c459c
5,355
Pod::Spec.new do |s| s.name = 'FirebaseRemoteConfig' s.version = '8.1.0' s.summary = 'Firebase Remote Config' s.description = <<-DESC Firebase Remote Config is a cloud service that lets you change the appearance and behavior of your app without requiring users to download an app update. DESC s.homepage = 'https://firebase.google.com' s.license = { :type => 'Apache', :file => 'LICENSE' } s.authors = 'Google, Inc.' s.source = { :git => 'https://github.com/firebase/firebase-ios-sdk.git', :tag => 'CocoaPods-' + s.version.to_s } s.social_media_url = 'https://twitter.com/Firebase' ios_deployment_target = '10.0' osx_deployment_target = '10.12' tvos_deployment_target = '10.0' watchos_deployment_target = '6.0' s.ios.deployment_target = ios_deployment_target s.osx.deployment_target = osx_deployment_target s.tvos.deployment_target = tvos_deployment_target s.watchos.deployment_target = watchos_deployment_target s.cocoapods_version = '>= 1.4.0' s.prefix_header_file = false base_dir = "FirebaseRemoteConfig/Sources/" s.source_files = [ base_dir + '**/*.[mh]', 'Interop/Analytics/Public/*.h', 'FirebaseABTesting/Sources/Private/*.h', 'FirebaseCore/Sources/Private/*.h', 'FirebaseInstallations/Source/Library/Private/*.h', ] s.public_header_files = base_dir + 'Public/FirebaseRemoteConfig/*.h' s.pod_target_xcconfig = { 'GCC_C_LANGUAGE_STANDARD' => 'c99', 'HEADER_SEARCH_PATHS' => '"${PODS_TARGET_SRCROOT}"' } s.dependency 'FirebaseABTesting', '~> 8.0' s.dependency 'FirebaseCore', '~> 8.0' s.dependency 'FirebaseInstallations', '~> 8.0' s.dependency 'GoogleUtilities/Environment', '~> 7.4' s.dependency 'GoogleUtilities/NSData+zlib', '~> 7.4' s.test_spec 'unit' do |unit_tests| unit_tests.scheme = { :code_coverage => true } # TODO(dmandar) - Update or delete the commented files. unit_tests.source_files = 'FirebaseRemoteConfig/Tests/Unit/FIRRemoteConfigComponentTest.m', 'FirebaseRemoteConfig/Tests/Unit/RCNConfigContentTest.m', 'FirebaseRemoteConfig/Tests/Unit/RCNConfigDBManagerTest.m', # 'FirebaseRemoteConfig/Tests/Unit/RCNConfigSettingsTest.m', # 'FirebaseRemoteConfig/Tests/Unit/RCNConfigTest.m', 'FirebaseRemoteConfig/Tests/Unit/RCNConfigExperimentTest.m', 'FirebaseRemoteConfig/Tests/Unit/RCNConfigValueTest.m', 'FirebaseRemoteConfig/Tests/Unit/RCNPersonalizationTest.m', # 'FirebaseRemoteConfig/Tests/Unit/RCNRemoteConfig+FIRAppTest.m', 'FirebaseRemoteConfig/Tests/Unit/RCNRemoteConfigTest.m', # 'FirebaseRemoteConfig/Tests/Unit/RCNThrottlingTests.m', 'FirebaseRemoteConfig/Tests/Unit/RCNTestUtilities.m', 'FirebaseRemoteConfig/Tests/Unit/RCNUserDefaultsManagerTests.m', 'FirebaseRemoteConfig/Tests/Unit/RCNTestUtilities.h', 'FirebaseRemoteConfig/Tests/Unit/RCNInstanceIDTest.m' # Supply plist custom plist testing. unit_tests.resources = 'FirebaseRemoteConfig/Tests/Unit/Defaults-testInfo.plist', 'FirebaseRemoteConfig/Tests/Unit/SecondApp-GoogleService-Info.plist', 'FirebaseRemoteConfig/Tests/Unit/TestABTPayload.txt' unit_tests.requires_app_host = true unit_tests.dependency 'OCMock' unit_tests.requires_arc = true end # Run Swift API tests on a real backend. s.test_spec 'swift-api-tests' do |swift_api| swift_api.scheme = { :code_coverage => true } swift_api.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } swift_api.source_files = 'FirebaseRemoteConfig/Tests/SwiftAPI/*.swift', 'FirebaseRemoteConfig/Tests/FakeUtils/*.[hm]', 'FirebaseRemoteConfig/Tests/FakeUtils/*.swift' swift_api.requires_app_host = true swift_api.pod_target_xcconfig = { 'SWIFT_OBJC_BRIDGING_HEADER' => '$(PODS_TARGET_SRCROOT)/FirebaseRemoteConfig/Tests/FakeUtils/Bridging-Header.h' } swift_api.resources = 'FirebaseRemoteConfig/Tests/SwiftAPI/GoogleService-Info.plist', 'FirebaseRemoteConfig/Tests/SwiftAPI/AccessToken.json' swift_api.dependency 'OCMock' end # Run Swift API tests and tests requiring console changes on a Fake Console. s.test_spec 'fake-console-tests' do |fake_console| fake_console.scheme = { :code_coverage => true } fake_console.platforms = { :ios => ios_deployment_target, :osx => osx_deployment_target, :tvos => tvos_deployment_target } fake_console.source_files = 'FirebaseRemoteConfig/Tests/SwiftAPI/*.swift', 'FirebaseRemoteConfig/Tests/FakeUtils/*.[hm]', 'FirebaseRemoteConfig/Tests/FakeUtils/*.swift', 'FirebaseRemoteConfig/Tests/FakeConsole/*.swift' fake_console.requires_app_host = true fake_console.pod_target_xcconfig = { 'SWIFT_OBJC_BRIDGING_HEADER' => '$(PODS_TARGET_SRCROOT)/FirebaseRemoteConfig/Tests/FakeUtils/Bridging-Header.h' } fake_console.resources = 'FirebaseRemoteConfig/Tests/FakeUtils/GoogleService-Info.plist' fake_console.dependency 'OCMock' end end
43.893443
117
0.689823
795d1fbc560fcc0039185bde72192cecd1bc18b2
19,843
# frozen_string_literal: true module ActiveRecord module ConnectionAdapters # :nodoc: module DatabaseStatements def initialize super reset_transaction end # Converts an arel AST to SQL def to_sql(arel_or_sql_string, binds = []) sql, _ = to_sql_and_binds(arel_or_sql_string, binds) sql end def to_sql_and_binds(arel_or_sql_string, binds = [], preparable = nil) # :nodoc: if arel_or_sql_string.respond_to?(:ast) unless binds.empty? raise "Passing bind parameters with an arel AST is forbidden. " \ "The values must be stored on the AST directly" end collector = collector() if prepared_statements collector.preparable = true sql, binds = visitor.compile(arel_or_sql_string.ast, collector) if binds.length > bind_params_length unprepared_statement do return to_sql_and_binds(arel_or_sql_string) end end preparable = collector.preparable else sql = visitor.compile(arel_or_sql_string.ast, collector) end [sql.freeze, binds, preparable] else arel_or_sql_string = arel_or_sql_string.dup.freeze unless arel_or_sql_string.frozen? [arel_or_sql_string, binds, preparable] end end private :to_sql_and_binds # This is used in the StatementCache object. It returns an object that # can be used to query the database repeatedly. def cacheable_query(klass, arel) # :nodoc: if prepared_statements sql, binds = visitor.compile(arel.ast, collector) query = klass.query(sql) else collector = klass.partial_query_collector parts, binds = visitor.compile(arel.ast, collector) query = klass.partial_query(parts) end [query, binds] end # Returns an ActiveRecord::Result instance. def select_all(arel, name = nil, binds = [], preparable: nil) arel = arel_from_relation(arel) sql, binds, preparable = to_sql_and_binds(arel, binds, preparable) if prepared_statements && preparable select_prepared(sql, name, binds) else select(sql, name, binds) end end # Returns a record hash with the column names as keys and column values # as values. def select_one(arel, name = nil, binds = []) select_all(arel, name, binds).first end # Returns a single value from a record def select_value(arel, name = nil, binds = []) single_value_from_rows(select_rows(arel, name, binds)) end # Returns an array of the values of the first column in a select: # select_values("SELECT id FROM companies LIMIT 3") => [1,2,3] def select_values(arel, name = nil, binds = []) select_rows(arel, name, binds).map(&:first) end # Returns an array of arrays containing the field values. # Order is the same as that returned by +columns+. def select_rows(arel, name = nil, binds = []) select_all(arel, name, binds).rows end def query_value(sql, name = nil) # :nodoc: single_value_from_rows(query(sql, name)) end def query_values(sql, name = nil) # :nodoc: query(sql, name).map(&:first) end def query(sql, name = nil) # :nodoc: exec_query(sql, name).rows end # Determines whether the SQL statement is a write query. def write_query?(sql) raise NotImplementedError end # Executes the SQL statement in the context of this connection and returns # the raw result from the connection adapter. # Note: depending on your database connector, the result returned by this # method may be manually memory managed. Consider using the exec_query # wrapper instead. def execute(sql, name = nil) raise NotImplementedError end # Executes +sql+ statement in the context of this connection using # +binds+ as the bind substitutes. +name+ is logged along with # the executed +sql+ statement. def exec_query(sql, name = "SQL", binds = [], prepare: false) raise NotImplementedError end # Executes insert +sql+ statement in the context of this connection using # +binds+ as the bind substitutes. +name+ is logged along with # the executed +sql+ statement. def exec_insert(sql, name = nil, binds = [], pk = nil, sequence_name = nil) sql, binds = sql_for_insert(sql, pk, binds) exec_query(sql, name, binds) end # Executes delete +sql+ statement in the context of this connection using # +binds+ as the bind substitutes. +name+ is logged along with # the executed +sql+ statement. def exec_delete(sql, name = nil, binds = []) exec_query(sql, name, binds) end # Executes update +sql+ statement in the context of this connection using # +binds+ as the bind substitutes. +name+ is logged along with # the executed +sql+ statement. def exec_update(sql, name = nil, binds = []) exec_query(sql, name, binds) end def exec_insert_all(sql, name) # :nodoc: exec_query(sql, name) end # Executes an INSERT query and returns the new record's ID # # +id_value+ will be returned unless the value is +nil+, in # which case the database will attempt to calculate the last inserted # id and return that value. # # If the next id was calculated in advance (as in Oracle), it should be # passed in as +id_value+. def insert(arel, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) sql, binds = to_sql_and_binds(arel, binds) value = exec_insert(sql, name, binds, pk, sequence_name) id_value || last_inserted_id(value) end alias create insert # Executes the update statement and returns the number of rows affected. def update(arel, name = nil, binds = []) sql, binds = to_sql_and_binds(arel, binds) exec_update(sql, name, binds) end # Executes the delete statement and returns the number of rows affected. def delete(arel, name = nil, binds = []) sql, binds = to_sql_and_binds(arel, binds) exec_delete(sql, name, binds) end # Executes the truncate statement. def truncate(table_name, name = nil) execute(build_truncate_statement(table_name), name) end def truncate_tables(*table_names) # :nodoc: table_names -= [schema_migration.table_name, InternalMetadata.table_name] return if table_names.empty? with_multi_statements do disable_referential_integrity do statements = build_truncate_statements(table_names) execute_batch(statements, "Truncate Tables") end end end # Runs the given block in a database transaction, and returns the result # of the block. # # == Nested transactions support # # #transaction calls can be nested. By default, this makes all database # statements in the nested transaction block become part of the parent # transaction. For example, the following behavior may be surprising: # # ActiveRecord::Base.transaction do # Post.create(title: 'first') # ActiveRecord::Base.transaction do # Post.create(title: 'second') # raise ActiveRecord::Rollback # end # end # # This creates both "first" and "second" posts. Reason is the # ActiveRecord::Rollback exception in the nested block does not issue a # ROLLBACK. Since these exceptions are captured in transaction blocks, # the parent block does not see it and the real transaction is committed. # # Most databases don't support true nested transactions. At the time of # writing, the only database that supports true nested transactions that # we're aware of, is MS-SQL. # # In order to get around this problem, #transaction will emulate the effect # of nested transactions, by using savepoints: # https://dev.mysql.com/doc/refman/en/savepoint.html. # # It is safe to call this method if a database transaction is already open, # i.e. if #transaction is called within another #transaction block. In case # of a nested call, #transaction will behave as follows: # # - The block will be run without doing anything. All database statements # that happen within the block are effectively appended to the already # open database transaction. # - However, if +:requires_new+ is set, the block will be wrapped in a # database savepoint acting as a sub-transaction. # # In order to get a ROLLBACK for the nested transaction you may ask for a # real sub-transaction by passing <tt>requires_new: true</tt>. # If anything goes wrong, the database rolls back to the beginning of # the sub-transaction without rolling back the parent transaction. # If we add it to the previous example: # # ActiveRecord::Base.transaction do # Post.create(title: 'first') # ActiveRecord::Base.transaction(requires_new: true) do # Post.create(title: 'second') # raise ActiveRecord::Rollback # end # end # # only post with title "first" is created. # # See ActiveRecord::Transactions to learn more. # # === Caveats # # MySQL doesn't support DDL transactions. If you perform a DDL operation, # then any created savepoints will be automatically released. For example, # if you've created a savepoint, then you execute a CREATE TABLE statement, # then the savepoint that was created will be automatically released. # # This means that, on MySQL, you shouldn't execute DDL operations inside # a #transaction call that you know might create a savepoint. Otherwise, # #transaction will raise exceptions when it tries to release the # already-automatically-released savepoints: # # Model.connection.transaction do # BEGIN # Model.connection.transaction(requires_new: true) do # CREATE SAVEPOINT active_record_1 # Model.connection.create_table(...) # # active_record_1 now automatically released # end # RELEASE SAVEPOINT active_record_1 <--- BOOM! database error! # end # # == Transaction isolation # # If your database supports setting the isolation level for a transaction, you can set # it like so: # # Post.transaction(isolation: :serializable) do # # ... # end # # Valid isolation levels are: # # * <tt>:read_uncommitted</tt> # * <tt>:read_committed</tt> # * <tt>:repeatable_read</tt> # * <tt>:serializable</tt> # # You should consult the documentation for your database to understand the # semantics of these different levels: # # * https://www.postgresql.org/docs/current/static/transaction-iso.html # * https://dev.mysql.com/doc/refman/en/set-transaction.html # # An ActiveRecord::TransactionIsolationError will be raised if: # # * The adapter does not support setting the isolation level # * You are joining an existing open transaction # * You are creating a nested (savepoint) transaction # # The mysql2 and postgresql adapters support setting the transaction # isolation level. def transaction(requires_new: nil, isolation: nil, joinable: true) if !requires_new && current_transaction.joinable? if isolation raise ActiveRecord::TransactionIsolationError, "cannot set isolation when joining a transaction" end yield else transaction_manager.within_new_transaction(isolation: isolation, joinable: joinable) { yield } end rescue ActiveRecord::Rollback # rollbacks are silently swallowed end attr_reader :transaction_manager #:nodoc: delegate :within_new_transaction, :open_transactions, :current_transaction, :begin_transaction, :commit_transaction, :rollback_transaction, :materialize_transactions, :disable_lazy_transactions!, :enable_lazy_transactions!, to: :transaction_manager def transaction_open? current_transaction.open? end def reset_transaction #:nodoc: @transaction_manager = ConnectionAdapters::TransactionManager.new(self) end # Register a record with the current transaction so that its after_commit and after_rollback callbacks # can be called. def add_transaction_record(record, ensure_finalize = true) current_transaction.add_record(record, ensure_finalize) end # Begins the transaction (and turns off auto-committing). def begin_db_transaction() end def transaction_isolation_levels { read_uncommitted: "READ UNCOMMITTED", read_committed: "READ COMMITTED", repeatable_read: "REPEATABLE READ", serializable: "SERIALIZABLE" } end # Begins the transaction with the isolation level set. Raises an error by # default; adapters that support setting the isolation level should implement # this method. def begin_isolated_db_transaction(isolation) raise ActiveRecord::TransactionIsolationError, "adapter does not support setting transaction isolation" end # Commits the transaction (and turns on auto-committing). def commit_db_transaction() end # Rolls back the transaction (and turns on auto-committing). Must be # done if the transaction block raises an exception or returns false. def rollback_db_transaction exec_rollback_db_transaction end def exec_rollback_db_transaction() end #:nodoc: def rollback_to_savepoint(name = nil) exec_rollback_to_savepoint(name) end def default_sequence_name(table, column) nil end # Set the sequence to the max value of the table's column. def reset_sequence!(table, column, sequence = nil) # Do nothing by default. Implement for PostgreSQL, Oracle, ... end # Inserts the given fixture into the table. Overridden in adapters that require # something beyond a simple insert (e.g. Oracle). # Most of adapters should implement `insert_fixtures_set` that leverages bulk SQL insert. # We keep this method to provide fallback # for databases like sqlite that do not support bulk inserts. def insert_fixture(fixture, table_name) execute(build_fixture_sql(Array.wrap(fixture), table_name), "Fixture Insert") end def insert_fixtures_set(fixture_set, tables_to_delete = []) fixture_inserts = build_fixture_statements(fixture_set) table_deletes = tables_to_delete.map { |table| "DELETE FROM #{quote_table_name(table)}" } statements = table_deletes + fixture_inserts with_multi_statements do disable_referential_integrity do transaction(requires_new: true) do execute_batch(statements, "Fixtures Load") end end end end def empty_insert_statement_value(primary_key = nil) "DEFAULT VALUES" end # Sanitizes the given LIMIT parameter in order to prevent SQL injection. # # The +limit+ may be anything that can evaluate to a string via #to_s. It # should look like an integer, or an Arel SQL literal. # # Returns Integer and Arel::Nodes::SqlLiteral limits as is. def sanitize_limit(limit) if limit.is_a?(Integer) || limit.is_a?(Arel::Nodes::SqlLiteral) limit else Integer(limit) end end # Fixture value is quoted by Arel, however scalar values # are not quotable. In this case we want to convert # the column value to YAML. def with_yaml_fallback(value) # :nodoc: if value.is_a?(Hash) || value.is_a?(Array) YAML.dump(value) else value end end private def execute_batch(statements, name = nil) statements.each do |statement| execute(statement, name) end end DEFAULT_INSERT_VALUE = Arel.sql("DEFAULT").freeze private_constant :DEFAULT_INSERT_VALUE def default_insert_value(column) DEFAULT_INSERT_VALUE end def build_fixture_sql(fixtures, table_name) columns = schema_cache.columns_hash(table_name) values_list = fixtures.map do |fixture| fixture = fixture.stringify_keys unknown_columns = fixture.keys - columns.keys if unknown_columns.any? raise Fixture::FixtureError, %(table "#{table_name}" has no columns named #{unknown_columns.map(&:inspect).join(', ')}.) end columns.map do |name, column| if fixture.key?(name) type = lookup_cast_type_from_column(column) with_yaml_fallback(type.serialize(fixture[name])) else default_insert_value(column) end end end table = Arel::Table.new(table_name) manager = Arel::InsertManager.new manager.into(table) if values_list.size == 1 values = values_list.shift new_values = [] columns.each_key.with_index { |column, i| unless values[i].equal?(DEFAULT_INSERT_VALUE) new_values << values[i] manager.columns << table[column] end } values_list << new_values else columns.each_key { |column| manager.columns << table[column] } end manager.values = manager.create_values_list(values_list) visitor.compile(manager.ast) end def build_fixture_statements(fixture_set) fixture_set.map do |table_name, fixtures| next if fixtures.empty? build_fixture_sql(fixtures, table_name) end.compact end def build_truncate_statement(table_name) "TRUNCATE TABLE #{quote_table_name(table_name)}" end def build_truncate_statements(table_names) table_names.map do |table_name| build_truncate_statement(table_name) end end def with_multi_statements yield end def combine_multi_statements(total_sql) total_sql.join(";\n") end # Returns an ActiveRecord::Result instance. def select(sql, name = nil, binds = []) exec_query(sql, name, binds, prepare: false) end def select_prepared(sql, name = nil, binds = []) exec_query(sql, name, binds, prepare: true) end def sql_for_insert(sql, pk, binds) [sql, binds] end def last_inserted_id(result) single_value_from_rows(result.rows) end def single_value_from_rows(rows) row = rows.first row && row.first end def arel_from_relation(relation) if relation.is_a?(Relation) relation.arel else relation end end end end end
36.143898
134
0.632918
874483511e567a1fafac8a84540956bff465b232
5,983
#%Header { ############################################################################## # # File adanaxis-data/spaces/level21/space.rb # # Copyright: Andy Southgate 2002-2007, 2020 # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the "Software"), # to deal in the Software without restriction, including without limitation # the rights to use, copy, modify, merge, publish, distribute, sublicense, # and/or sell copies of the Software, and to permit persons to whom the # Software is furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER # DEALINGS IN THE SOFTWARE. # ############################################################################## #%Header } fJedHhrWwO8dJI+QqNu/Lw # $Id: space.rb,v 1.4 2007/06/27 13:18:57 southa Exp $ # $Log: space.rb,v $ # Revision 1.4 2007/06/27 13:18:57 southa # Debian packaging # # Revision 1.3 2007/06/27 12:58:16 southa # Debian packaging # # Revision 1.2 2007/06/05 12:15:14 southa # Level 21 # # Revision 1.1 2007/06/02 15:56:57 southa # Shader fix and prerelease work # require 'Mushware.rb' require 'Adanaxis.rb' class Adanaxis_level21 < AdanaxisSpace def initialize(inParams = {}) super mIsBattleSet(true) mJammingSet(true) end def mLoad(game) mLoadStandard(game) mMusicAdd('game1', 'mushware-sanity-fault.ogg') MushGame.cSoundDefine("voice-intro", "mush://waves/voice-L21.ogg|null:") end def mPrecacheListBuild super mPrecacheListAdd(mPieceLibrary.mAttendantTex('blue')) mPrecacheListAdd(mPieceLibrary.mCisternTex('red', 'blue')) mPrecacheListAdd(mPieceLibrary.mFreshenerTex('blue')) mPrecacheListAdd(mPieceLibrary.mHarpikTex('red', 'blue')) mPrecacheListAdd(mPieceLibrary.mRailTex('red')) mPrecacheListAdd(mPieceLibrary.mVendorTex('red')) end def mInitialPiecesCreate super MushTools.cRandomSeedSet(21) diff = AdanaxisRuby.cGameDifficulty angVel = MushTools.cRotationInXYPlane(Math::PI / 1200); MushTools.cRotationInZWPlane(Math::PI / 1314).mRotate(angVel); MushTools.cRotationInYZPlane(Math::PI / 1575).mRotate(angVel); vel = MushVector.new(-0.05*(1+diff),0,0,0) angPos = MushTools.cRotationInXZPlane(Math::PI/2) (3+3*diff).times do |param| mPieceLibrary.mVendorCreate( :colour => 'red', :post => MushPost.new( :position => MushVector.new(0, 0, 0, -300) + MushTools.cRandomUnitVector * (50 + rand((diff+0.5)*100)), :angular_position => MushTools.cRandomOrientation ) ) end 4.times do |param| mPieceLibrary.mFreshenerCreate( :colour => 'blue', :post => MushPost.new( :position => MushVector.new(200, -200, -100, -300-100*param), :angular_velocity => angVel ), :is_jammer => true ) end 4.times do |param| ['blue', 'red', 'red'].each do |colour| mPieceLibrary.mHarpikCreate( :colour => colour, :post => MushPost.new( :position => MushVector.new(500, 0, 0, -500+((colour == 'red')?-200:200)) + MushTools.cRandomUnitVector * (20 + rand(100)), :angular_position => MushTools.cRandomOrientation ) ) end end 2.times do |param| mPieceLibrary.mRailCreate( :colour => 'red', :post => MushPost.new( :position => MushVector.new(-400, -200, -50, -500-100*param), :angular_position => MushTools.cRandomOrientation ), :ai_state => :dormant, :ai_state_msec => 15000 ) end mPieceLibrary.mCisternCreate( :colour => 'red', :post => MushPost.new( :position => MushVector.new(-500, -200, -50, -500), :velocity => vel, :angular_position => angPos ), :patrol_points => [ MushVector.new(-500, -200, -200, -1000), MushVector.new(-200, 0, 200, -1000), MushVector.new(-200, 0, 200, -500), MushVector.new(-500, -200, -200, -500) ], :ammo_count => 5+10*diff, :ai_state => :patrol, :ai_state_msec => 10000, :weapon => :vendor_spawner ) mPieceLibrary.mCisternCreate( :colour => 'blue', :post => MushPost.new( :position => MushVector.new(1000, -20, 0, -1000), :velocity => vel, :angular_position => angPos ), :patrol_points => [ MushVector.new(-200, 200, 0, -1000), MushVector.new(200, 200, 0, -1000) ], :ammo_count => 15, :ai_state => :patrol, :ai_state_msec => 10000 ) $currentLogic.mRemnant.mCreate( :item_type => (AdanaxisRuby.cGameDifficulty < 2) ? :player_light_missile : :player_heavy_cannon, :post => MushPost.new( :position => MushVector.new(-10, 0 , 0, -20) ) ) if diff < 1 $currentLogic.mRemnant.mCreate( :item_type => :player_heavy_cannon, :post => MushPost.new( :position => MushVector.new(0, 0, 0, -40) ) ) end $currentLogic.mRemnant.mCreate( :item_type => :player_heavy_missile, :post => MushPost.new( :position => MushVector.new(10, 0, 0, -80) ) ) mStandardCosmos(21) end def mJammersEliminated mJammingSet(false) MushGame.cNamedDialoguesAdd('^unjammed') end end
30.682051
102
0.615912
87c02d4ba9ad7967d9366d388def973d3f78035c
1,323
# frozen_string_literal: true lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'at_coder_friends/version' Gem::Specification.new do |spec| spec.name = 'at_coder_friends' spec.version = AtCoderFriends::VERSION spec.authors = ['nejiko96'] spec.email = ['[email protected]'] spec.summary = 'AtCoder support tool' spec.description = <<-DESCRIPTION AtCoder support tool - generate source template - generate test data from sample input/output - run tests - submit code DESCRIPTION spec.homepage = 'https://github.com/nejiko96/at_coder_friends' spec.license = 'MIT' spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.3.0' spec.add_dependency 'mechanize', '~> 2.0' spec.add_development_dependency 'bundler', '~> 1.16' spec.add_development_dependency 'rake', '~> 10.0' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'simplecov', '~> 0.10' spec.add_development_dependency 'webmock', '~> 3.0' end
32.268293
74
0.662132
f7eef5252d63572266f41cdc314ac18536ac6039
2,197
class PlosFulltext < Agent def get_query_url(options = {}) query_string = get_query_string(options) return {} unless query_string.present? url % { query_string: query_string } end def get_provenance_url(options = {}) query_string = get_query_string(options) return {} unless query_string.present? provenance_url % { query_string: query_string } end def get_query_string(options={}) # don't query if work is PLOS article work = Work.where(id: options.fetch(:work_id, nil)).first return nil if work.nil? || work.prefix == "10.1371" || !registration_agencies.include?(work.registration_agency) [work.doi, work.canonical_url].compact.map { |i| "everything:%22#{i}%22" }.join("+OR+") end def get_relations_with_related_works(result, work) provenance_url = get_provenance_url(work_id: work.id) result.fetch("response", {}).fetch("docs", []).map do |item| doi = item.fetch("id", nil) pid = doi_as_url(doi) { prefix: work.prefix, relation: { "subj_id" => pid, "obj_id" => work.pid, "relation_type_id" => "cites", "provenance_url" => provenance_url, "source_id" => source_id }, subj: { "pid" => pid, "author" => get_authors(item.fetch("author_display", [])), "title" => item.fetch("title", ""), "container-title" => item.fetch("cross_published_journal_name", []).first, "issued" => get_iso8601_from_time(item.fetch("publication_date", nil)), "DOI" => doi, "type" => "article-journal", "tracked" => tracked, "registration_agency" => "crossref" }} end end def config_fields [:url, :provenance_url] end def url "http://api.plos.org/search?q=%{query_string}&fq=doc_type:full&fl=id,publication_date,title,cross_published_journal_name,author_display&wt=json&rows=1000" end def provenance_url "http://www.plosone.org/search/advanced?unformattedQuery=%{query_string}" end def registration_agencies ["datacite", "dataone", "cdl", "github", "bitbucket"] end end
33.8
158
0.617205
380fa763e24b0f15e23e7ecff18f3ed8db14a847
18,607
# encoding: UTF-8 module GoodData module Model class ProjectBlueprint attr_accessor :data # Instantiates a project blueprint either from a file or from a string containing # json. Also eats Hash for convenience. # # @param spec [String | Hash] value of an label you are looking for # @return [GoodData::Model::ProjectBlueprint] class << self def from_json(spec) if spec.is_a?(String) if File.file?(spec) ProjectBlueprint.new(MultiJson.load(File.read(spec), :symbolize_keys => true)) else ProjectBlueprint.new(MultiJson.load(spec, :symbolize_keys => true)) end else ProjectBlueprint.new(spec) end end def build(title, &block) pb = ProjectBuilder.create(title, &block) pb.to_blueprint end end # Removes dataset from blueprint. Dataset can be given as either a name # or a DatasetBlueprint or a Hash representation. # # @param project [Hash] Project blueprint # @param dataset_name [GoodData::Model::DatasetBlueprint | String | Hash] Dataset to be removed # @return [Hash] project with removed dataset def self.remove_dataset(project, dataset_name) dataset = dataset_name.is_a?(String) ? find_dataset(project, dataset_name) : dataset_name index = project[:datasets].index(dataset) dupped_project = project.deep_dup dupped_project[:datasets].delete_at(index) dupped_project end # Removes dataset from blueprint. Dataset can be given as either a name # or a DatasetBlueprint or a Hash representation. This version mutates # the dataset in place # # @param project [Hash] Project blueprint # @param dataset_name [GoodData::Model::DatasetBlueprint | String | Hash] Dataset to be removed # @return [Hash] project with removed dataset def self.remove_dataset!(project, dataset_name) dataset = dataset_name.is_a?(String) ? find_dataset(project, dataset_name) : dataset_name index = project[:datasets].index(dataset) project[:datasets].delete_at(index) project end # Returns datasets of blueprint. Those can be optionally including # date dimensions # # @param project [GoodData::Model::ProjectBlueprint | Hash] Project blueprint # @param options [Hash] options # @return [Array<Hash>] def self.datasets(project, options = {}) include_date_dimensions = options[:include_date_dimensions] || options[:dd] ds = (project.to_hash[:datasets] || []) if include_date_dimensions ds + date_dimensions(project) else ds end end # Returns true if a dataset contains a particular dataset false otherwise # # @param project [GoodData::Model::ProjectBlueprint | Hash] Project blueprint # @param name [GoodData::Model::DatasetBlueprint | String | Hash] Dataset # @return [Boolean] def self.dataset?(project, name) find_dataset(project, name) true rescue false end # Returns dataset specified. It can check even for a date dimension # # @param project [GoodData::Model::ProjectBlueprint | Hash] Project blueprint # @param obj [GoodData::Model::DatasetBlueprint | String | Hash] Dataset # @param options [Hash] options # @return [GoodData::Model::DatasetBlueprint] def self.find_dataset(project, obj, options = {}) include_date_dimensions = options[:include_date_dimensions] || options[:dd] return obj.to_hash if DatasetBlueprint.dataset_blueprint?(obj) all_datasets = if include_date_dimensions datasets(project) + date_dimensions(project) else datasets(project) end name = obj.respond_to?(:key?) ? obj[:name] : obj ds = all_datasets.find { |d| d[:name] == name } fail "Dataset #{name} could not be found" if ds.nil? ds end # Returns list of date dimensions # # @param project [GoodData::Model::ProjectBlueprint | Hash] Project blueprint # @return [Array<Hash>] def self.date_dimensions(project) project.to_hash[:date_dimensions] || [] end # Returns true if a date dimension of a given name exists in a bleuprint # # @param project [GoodData::Model::ProjectBlueprint | Hash] Project blueprint # @param name [string] Date dimension # @return [Boolean] def self.date_dimension?(project, name) find_date_dimension(project, name) true rescue false end # Finds a date dimension of a given name in a bleuprint. If a dataset is # not found it throws an exeception # # @param project [GoodData::Model::ProjectBlueprint | Hash] Project blueprint # @param name [string] Date dimension # @return [Hash] def self.find_date_dimension(project, name) ds = date_dimensions(project).find { |d| d[:name] == name } fail "Date dimension #{name} could not be found" if ds.nil? ds end # Returns fields from all datasets # # @param project [GoodData::Model::ProjectBlueprint | Hash] Project blueprint # @return [Array<Hash>] def self.fields(project) datasets(project).mapcat { |d| DatasetBlueprint.fields(d) } end def change(&block) builder = ProjectBuilder.create_from_data(self) block.call(builder) @data = builder.to_hash self end # Returns datasets of blueprint. Those can be optionally including # date dimensions # # @param options [Hash] options # @return [Array<GoodData::Model::DatasetBlueprint>] def datasets(options = {}) ProjectBlueprint.datasets(to_hash, options).map { |d| DatasetBlueprint.new(d) } end def add_dataset(a_dataset, index = nil) if index.nil? || index > datasets.length data[:datasets] << a_dataset.to_hash else data[:datasets].insert(index, a_dataset.to_hash) end end # Removes dataset from blueprint. Dataset can be given as either a name # or a DatasetBlueprint or a Hash representation. # # @param dataset_name [GoodData::Model::DatasetBlueprint | String | Hash] Dataset to be removed # @return [Hash] project with removed dataset def remove_dataset(dataset_name) ProjectBlueprint.remove_dataset(to_hash, dataset_name) end # Removes dataset from blueprint. Dataset can be given as either a name # or a DatasetBlueprint or a Hash representation. # # @param dataset_name [GoodData::Model::DatasetBlueprint | String | Hash] Dataset to be removed # @return [Hash] project with removed dataset def remove_dataset!(dataset_name) ProjectBlueprint.remove_dataset!(to_hash, dataset_name) end # Is this a project blueprint? # # @return [Boolean] if it is def project_blueprint? true end # Returns list of date dimensions # # @return [Array<Hash>] def date_dimensions ProjectBlueprint.date_dimensions(to_hash) end # Returns true if a dataset contains a particular dataset false otherwise # # @param name [GoodData::Model::DatasetBlueprint | String | Hash] Dataset # @return [Boolean] def dataset?(name) ProjectBlueprint.dataset?(to_hash, name) end # Returns dataset specified. It can check even for a date dimension # # @param name [GoodData::Model::DatasetBlueprint | String | Hash] Dataset # @param options [Hash] options # @return [GoodData::Model::DatasetBlueprint] def find_dataset(name, options = {}) DatasetBlueprint.new(ProjectBlueprint.find_dataset(to_hash, name, options)) end # Returns a dataset of a given name. If a dataset is not found it throws an exeception # # @param project [String] Dataset title # @return [Array<Hash>] def find_dataset_by_title(title) ds = ProjectBlueprint.find_dataset_by_title(to_hash, title) DatasetBlueprint.new(ds) end # Constructor # # @param init_data [ProjectBlueprint | Hash] Blueprint or a blueprint definition. If passed a hash it is used as data for new instance. If there is a ProjectBlueprint passed it is duplicated and a new instance is created. # @return [ProjectBlueprint] A new project blueprint instance def initialize(init_data) some_data = if init_data.respond_to?(:project_blueprint?) && init_data.project_blueprint? init_data.to_hash elsif init_data.respond_to?(:to_blueprint) init_data.to_blueprint.to_hash else init_data end @data = some_data.deep_dup end # Validate the blueprint in particular if all references reference existing datasets and valid fields inside them. # # @return [Array] array of errors def validate_references if datasets.count == 1 [] else x = datasets.reduce([]) { |a, e| e.anchor? ? a << [e.name] : a } + date_dimensions.map { |y| [y[:name]] } refs = datasets.reduce([]) do |a, e| a.concat(e.references) end refs.reduce([]) do |a, e| x.include?([e[:dataset]]) ? a : a.concat([e]) end end end # Validate the blueprint and all its datasets return array of errors that are found. # # @return [Array] array of errors def validate refs_errors = validate_references labels_errors = datasets.reduce([]) { |a, e| a.concat(e.validate) } refs_errors.concat(labels_errors) end # Validate the blueprint and all its datasets and return true if model is valid. False otherwise. # # @return [Boolean] is model valid? def valid? validate.empty? end # Returns list of datasets which are referenced by given dataset. This can be # optionally switched to return even date dimensions # # @param project [GoodData::Model::DatasetBlueprint | Hash | String] Dataset blueprint # @return [Array<Hash>] def referenced_by(dataset) find_dataset(dataset, include_date_dimensions: true).references.map do |ref| find_dataset(ref[:dataset], include_date_dimensions: true) end end # Returns list of attributes from all the datasets in a blueprint # # @return [Array<Hash>] def attributes datasets.reduce([]) { |a, e| a.concat(e.attributes) } end # Returns list of attributes and anchors from all the datasets in a blueprint # # @return [Array<Hash>] def attributes_and_anchors datasets.mapcat(&:attributes_and_anchors) end # Returns list of labels from all the datasets in a blueprint # # @return [Array<Hash>] def labels datasets.mapcat(&:labels) end # Returns list of facts from all the datasets in a blueprint # # @return [Array<Hash>] def facts datasets.mapcat(&:facts) end # Returns list of fields from all the datasets in a blueprint # # @return [Array<Hash>] def fields ProjectBlueprint.fields(to_hash) end # Returns list of attributes that can break facts in a given dataset. # This basically means that it is giving you all attributes from the # datasets that are references by given dataset. Currently does not # work transitively # # @param project [GoodData::Model::DatasetBlueprint | Hash | String] Dataset blueprint # @return [Array<Hash>] def can_break(dataset) dataset = find_dataset(dataset) if dataset.is_a?(String) (referenced_by(dataset) + [dataset]).mapcat do |ds| ds.attributes_and_anchors.map do |attr| [ds, attr] end end end # Experimental but a basis for automatic check of health of a project # # @param project [GoodData::Model::DatasetBlueprint | Hash | String] Dataset blueprint # @return [Array<Hash>] def lint(full = false) errors = [] find_star_centers.each do |dataset| next unless dataset.anchor? errors << { type: :anchor_on_fact_dataset, dataset_name: dataset.name, anchor_name: dataset.anchor[:name] } end date_facts = datasets.mapcat(&:date_facts) date_facts.each do |date_fact| errors << { type: :date_fact, date_fact: date_fact[:name] } end unique_titles = fields.map { |f| Model.title(f) }.uniq (fields.map { |f| Model.title(f) } - unique_titles).each do |duplicate_title| errors << { type: :duplicate_title, title: duplicate_title } end datasets.select(&:wide?).each do |wide_dataset| errors << { type: :wide_dataset, dataset: wide_dataset.name } end if full # GoodData::Attributes.all(:full => true).select { |attr| attr.used_by} end errors end # Return list of datasets that are centers of the stars in datamart. # This means these datasets are not referenced by anybody else # In a good blueprint design these should be fact tables # # @return [Array<Hash>] def find_star_centers referenced = datasets.mapcat { |d| referenced_by(d) } referenced.flatten! res = datasets.map(&:to_hash) - referenced.map(&:to_hash) res.map { |d| DatasetBlueprint.new(d) } end # Returns some reports that might get you started. They are just simple # reports. Currently it is implemented by getting facts from star centers # and randomly picking attributes form referenced datasets. # # @return [Array<Hash>] def suggest_reports(options = {}) strategy = options[:strategy] || :stupid case strategy when :stupid reports = suggest_metrics.reduce([]) do |a, e| star, metrics = e metrics.each(&:save) reports_stubs = metrics.map do |m| breaks = can_break(star).map { |ds, aM| ds.identifier_for(aM) } # [breaks.sample((breaks.length/10.0).ceil), m] [breaks, m] end a.concat(reports_stubs) end reports.reduce([]) do |a, e| attrs, metric = e attrs.each do |attr| a << GoodData::Report.create(:title => 'Fantastic report', :top => [attr], :left => metric) end a end end end # Returns some metrics that might get you started. They are just simple # reports. Currently it is implemented by getting facts from star centers # and randomly picking attributes form referenced datasets. # # @return [Array<Hash>] def suggest_metrics stars = find_star_centers metrics = stars.map(&:suggest_metrics) stars.zip(metrics) end # Merging two blueprints. The self blueprint is changed in place # # @param a_blueprint [GoodData::Model::DatasetBlueprint] Dataset blueprint to be merged # @return [GoodData::Model::ProjectBlueprint] def merge!(a_blueprint) temp_blueprint = merge(a_blueprint) @data = temp_blueprint.data self end # Merging two blueprints. A new blueprint is created. The self one # is nto mutated # # @param a_blueprint [GoodData::Model::DatasetBlueprint] Dataset blueprint to be merged # @return [GoodData::Model::ProjectBlueprint] def merge(a_blueprint) temp_blueprint = dup return temp_blueprint unless a_blueprint a_blueprint.datasets.each do |dataset| if temp_blueprint.dataset?(dataset.name) local_dataset = temp_blueprint.find_dataset(dataset.name) index = temp_blueprint.datasets.index(local_dataset) local_dataset.merge!(dataset) temp_blueprint.remove_dataset(local_dataset.name) temp_blueprint.add_dataset(local_dataset, index) else temp_blueprint.add_dataset(dataset.dup) end end temp_blueprint end # Duplicated blueprint # # @param a_blueprint [GoodData::Model::DatasetBlueprint] Dataset blueprint to be merged # @return [GoodData::Model::DatasetBlueprint] def dup ProjectBlueprint.new(data.deep_dup) end # Returns title of a dataset. If not present it is generated from the name # # @return [String] a title def title Model.title(to_hash) end # Returns Wire representation. This is used by our API to generate and # change projects # # @return [Hash] a title def to_wire ToWire.to_wire(data) end # Returns SLI manifest representation. This is used by our API to allow # loading data # # @return [Array<Hash>] a title def to_manifest ToManifest.to_manifest(to_hash) end # Returns SLI manifest for one dataset. This is used by our API to allow # loading data. The method is on project blueprint because you need # acces to whole project to be able to generate references # # @param dataset [GoodData::Model::DatasetBlueprint | Hash | String] Dataset # @param mode [String] Method of loading. FULL or INCREMENTAL # @return [Array<Hash>] a title def dataset_to_manifest(dataset, mode = 'FULL') ToManifest.dataset_to_manifest(self, dataset, mode) end # Returns hash representation of blueprint # # @return [Hash] a title def to_hash @data end def ==(other) to_hash == other.to_hash end def eql?(other) to_hash == other.to_hash end end end end
35.173913
227
0.614876
6a9698328fd748a006ce9710fc3283a2017ef8da
1,216
module CatarsePagarme class Configuration attr_accessor :api_key, :slip_tax, :credit_card_tax, :interest_rate, :host, :subdomain, :protocol, :max_installments, :minimum_value_for_installment, :credit_card_cents_fee, :pagarme_tax, :stone_tax, :stone_installment_tax, :cielo_tax, :cielo_installment_diners_tax, :cielo_installment_not_diners_tax, :cielo_installment_amex_tax, :cielo_installment_not_amex_tax, :ecr_key, :slip_week_day_interval, :antifraud_tax def initialize self.api_key = '' self.ecr_key = '' self.slip_tax = 0 self.credit_card_tax = 0 self.antifraud_tax = 0 self.interest_rate = 0 self.max_installments = 12 self.minimum_value_for_installment = 10 self.credit_card_cents_fee = 0 self.host = 'catarse.me' self.subdomain = 'www' self.protocol = 'http' self.pagarme_tax = 0 self.stone_tax = 0 self.stone_installment_tax = 0 self.cielo_tax = 0 self.cielo_installment_diners_tax = 0 self.cielo_installment_not_diners_tax = 0 self.cielo_installment_amex_tax = 0 self.cielo_installment_not_amex_tax = 0 self.slip_week_day_interval = 2 end end end
36.848485
117
0.712993
e935285cafa62e3c55d7d0950acdf4a2b4ef01db
4,595
require_relative "../test_helper" class ManageApiUsersTest < ActionDispatch::IntegrationTest context "as Superadmin" do setup do @application = create(:application, with_supported_permissions: %w[write]) @superadmin = create(:superadmin_user) visit new_user_session_path signin_with(@superadmin) @api_user = create(:api_user, with_permissions: { @application => %w[write] }) create(:access_token, resource_owner_id: @api_user.id, application_id: @application.id) click_link "APIs" end should "be able to view a list of API users alongwith their authorised applications" do assert page.has_selector?("td.email", text: @api_user.name) assert page.has_selector?("td.email", text: @api_user.email) assert page.has_selector?("td.role", text: "Normal") assert page.has_selector?("abbr", text: @application.name) assert page.has_selector?("td:last-child", text: "No") # suspended? end should "be able to create an API user" do click_link "Create API user" fill_in "Name", with: "Content Store Application" fill_in "Email", with: "[email protected]" click_button "Create API user" assert page.has_text?("Successfully created API user") end should "be able to authorise application access and manage permissions for an API user which should get recorded in event log" do create(:application, name: "Whitehall", with_supported_permissions: ["Managing Editor", "signin"]) click_link @api_user.name click_link "Add application token" select "Whitehall", from: "Application" click_button "Create access token" token = @api_user.authorisations.last.token assert page.has_selector?("div.alert-danger", text: "Make sure to copy the access token for Whitehall now. You won't be able to see it again!") assert page.has_selector?("div.alert-info", text: "Access token for Whitehall: #{token}") # shows truncated token assert page.has_selector?("code", text: (token[0..7]).to_s) assert_not page.has_selector?("code", text: (token[9..-9]).to_s) assert page.has_selector?("code", text: (token[-8..]).to_s) select "Managing Editor", from: "Permissions for Whitehall" click_button "Update API user" assert page.has_selector?("abbr[title='Permissions: Managing Editor and signin']", text: "Whitehall") click_link @api_user.name unselect "Managing Editor", from: "Permissions for Whitehall" click_button "Update API user" assert page.has_selector?("abbr[title='Permissions: signin']", text: "Whitehall") click_link @api_user.name click_link "Account access log" assert page.has_text?("Access token generated for Whitehall by #{@superadmin.name}") end should "be able to revoke application access for an API user which should get recorded in event log" do click_link @api_user.name assert page.has_selector?("td:first-child", text: @application.name) click_button "Revoke" assert page.has_text?("Access for #{@application.name} was revoked") assert_not page.has_selector?("td:first-child", text: @application.name) click_link "Account access log" assert page.has_text?("Access token revoked for #{@application.name} by #{@superadmin.name}") end should "be able to regenerate application access token for an API user which should get recorded in event log" do click_link @api_user.name assert page.has_selector?("td:first-child", text: @application.name) click_button "Re-generate" assert page.has_selector?("div.alert-danger", text: "Make sure to copy the access token for #{@application.name} now. You won't be able to see it again!") assert page.has_selector?("div.alert-info", text: "Access token for #{@application.name}: #{@api_user.authorisations.last.token}") click_link "Account access log" assert page.has_text?("Access token re-generated for #{@application.name} by #{@superadmin.name}") end should "be able to suspend and unsuspend API user" do click_link @api_user.name click_link "Suspend user" check "Suspended?" fill_in "Reason for suspension", with: "Stole data" click_button "Save" assert page.has_selector?("p.alert-warning", text: "User suspended: Stole data") click_link "Unsuspend user" uncheck "Suspended?" click_button "Save" assert page.has_selector?(".alert-success", text: "#{@api_user.email} is now active.") end end end
39.612069
160
0.692492
bfa2aeeb05f099c1a34c6287cc39924704e3f9b0
358
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__) require "jruby-jolt" def spec_path "#{File.expand_path("../../", __FILE__)}/spec" end def fixtures_path "#{spec_path}/fixtures" end def fixture_path(file) fixtures_path + '/' + file end def fixture(file) File.read(fixture_path(file)) end def parse_json(json) MultiJson.load(json) end
15.565217
58
0.706704
e8d4c7bb6d28d9fa8dc202bb2ab337d6ab49561d
49
module ActsAsRequestable VERSION = "0.0.1" end
12.25
24
0.734694
d56f8b0015deb2fd0682f8a7112da568db17a12a
784
describe 'locomotive/translations/edit', type: :view do helper(Locomotive::BaseHelper, Locomotive::SitesHelper, Locomotive::Engine.routes.url_helpers) helper(Locomotive::TestViewHelpers) let(:site) { build('test site', locales: [:en, :fr]) } let(:translation) { create(:translation) } let(:nav) { { filter_by: 'untranslated', q: 'hell' } } before do allow(view).to receive(:current_site).and_return(site) allow(view).to receive(:translation_nav_params).and_return(nav) assign(:translation, translation) end subject { render } it 'renders something without an exception' do expect { expect(subject).to include(%(<a href="/locomotive/test/translations?filter_by=untranslated&amp;q=hell">)) }.to_not raise_error end end
31.36
111
0.697704
870870f2fa43066b28318ee6bdb73526dc2e757f
564
require_relative '../../../spec_helper' require 'stringio' require 'zlib' describe "Zlib::GzipFile#close" do it "finishes the stream and closes the io" do io = StringIO.new "".b Zlib::GzipWriter.wrap io do |gzio| gzio.close gzio.closed?.should == true -> { gzio.orig_name }.should \ raise_error(Zlib::GzipFile::Error, 'closed gzip stream') -> { gzio.comment }.should \ raise_error(Zlib::GzipFile::Error, 'closed gzip stream') end io.string[10..-1].should == ([3] + Array.new(9,0)).pack('C*') end end
25.636364
65
0.620567
793d050b973d4bc8c5b0653d5b62a16385f23b55
822
# -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{domino} s.version = "0.1.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Chris Kalafarski"] s.date = %q{2009-02-06} s.description = %q{TODO} s.email = %q{[email protected]} s.files = ["VERSION.yml", "lib/domino.rb", "test/domino_test.rb", "test/test_helper.rb"] s.homepage = %q{http://github.com/farski/domino} s.require_paths = ["lib"] s.rubygems_version = %q{1.3.1} s.summary = %q{TODO} if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 2 if Gem::Version.new(Gem::RubyGemsVersion) >= Gem::Version.new('1.2.0') then else end else end end
29.357143
105
0.671533
7a57255763104e35abeffd65cf97a2061bfb92e5
1,023
# Generated with JReleaser 1.0.0-M2 at 2022-06-02T01:04:44.629395287Z class KfkClusterState < Formula desc "Kafka: CLI: Topic List: Expand Kafka topic listing with Offsets and more." homepage "https://github.com/jeqo/kafka-cli" version "0.3.0" license "Apache-2.0" if OS.linux? && Hardware::CPU.intel? url "https://github.com/jeqo/kafka-cli/releases/download/cli-cluster-state-v0.3.0/kfk-cluster-state-0.3.0-linux-x86_64.zip" sha256 "921a2174d95d0483630f864cd6daf15cb869fc16f551cf364c409f934ff62bca" end if OS.mac? && Hardware::CPU.intel? url "https://github.com/jeqo/kafka-cli/releases/download/cli-cluster-state-v0.3.0/kfk-cluster-state-0.3.0-osx-x86_64.zip" sha256 "d6ab50dd278102ae8023458fd3f38a02eb0f17c071b7f04e7e458a18fc6e8d47" end def install libexec.install Dir["*"] bin.install_symlink "#{libexec}/bin/kfk-cluster-state" => "kfk-cluster-state" end test do output = shell_output("#{bin}/kfk-cluster-state --version") assert_match "0.3.0", output end end
36.535714
127
0.733138
01a93556d2a398df9bc75c593b5ee26d53ecd955
1,934
#!/usr/bin/env ruby require 'bundler/setup' require 'html/pipeline' require_relative 'HHVM/UserDocumentation/SyntaxHighlightFilter.rb' require_relative 'HHVM/UserDocumentation/IncludeExamplesFilter.rb' require_relative 'HHVM/UserDocumentation/IncludeGuidesGeneratedMarkdownFilter.rb' require_relative 'HHVM/UserDocumentation/InternalLinksFilter.rb' require_relative 'HHVM/UserDocumentation/HeadingAnchorsFilter.rb' require_relative 'HHVM/UserDocumentation/ResponsiveTablesFilter.rb' require_relative 'HHVM/UserDocumentation/VersionedImagesFilter.rb' require_relative 'HHVM/UserDocumentation/IgnoreNewlinesFilter.rb' require_relative 'HHVM/UserDocumentation/AutoLinkifyAPIFilter.rb' generatedMarkdownProcessor = HHVM::UserDocumentation::IncludeGuidesGeneratedMarkdownFilter.new markdownPipeline = HTML::Pipeline.new( [ HTML::Pipeline::MarkdownFilter, HHVM::UserDocumentation::IncludeExamplesFilter, HHVM::UserDocumentation::SyntaxHighlightFilter, HHVM::UserDocumentation::InternalLinksFilter, HHVM::UserDocumentation::HeadingAnchorsFilter, HHVM::UserDocumentation::ResponsiveTablesFilter, HHVM::UserDocumentation::VersionedImagesFilter, HHVM::UserDocumentation::IgnoreNewlinesFilter, HHVM::UserDocumentation::AutoLinkifyAPIFilter, ], ) STDOUT.sync = true STDIN.each_line do |line| in_file, out_file = line.strip.split ' -> ' in_text = File.read(in_file) out_text = generatedMarkdownProcessor.call( in_text, in_file ) # If nothing happened in the preMarkdownFilter (etc. no generated markdown), # then what we write to out_file will be the same content as in_file. # out_file here is serving as an intermediary to the final out_file below File.open(out_file, 'w+') { |f| f.write out_text } out_text = markdownPipeline.call( File.read(out_file), { file: in_file }, )[:output].to_s File.open(out_file, 'w+') { |f| f.write out_text } puts 'OK] '+line end
36.490566
94
0.791624
2181846b6a0fee74545fe68db864d5cc91126fab
356
# # It is auto-generated content. # Do not do required for this file in your application. # module Application def self.quit end def self.minimize end def self.restore end def self.getVersion end def self.applicationEvent=(argument) end def self.versionEvent=(argument) end def self.setEmml(argument) end end
14.833333
55
0.688202
f875d695a4d02b554ecdcc14e27c38b5796e0a40
203
require File.dirname(__FILE__) + '/../../test_helper' class Admin::InterviewControllerTest < ActionController::TestCase # Replace this with your real tests. def test_truth assert true end end
22.555556
65
0.743842
7990dfdea200336033e9ab201e6da8c858c6dc97
812
# frozen_string_literal: true require 'shaf/yard/base_method_handler' module Shaf module Yard # Handles call to Shaf::Serializer::link class LinkMethodHandler < BaseMethodHandler handles method_call(:link) def object LinkObject.new(serializer_namespace, name).tap do |link| link.dynamic = true link.rel = name link.curie = curie end end def name super.sub(/[^:]+:/, '') end def curie m = name.match(/([^:]+):/) return m[1] if m statement.parameters(false).each do |param| next unless param&.respond_to? :source str = String(param.source) m = str.match(/curie:\s:?(\w+)/) return m[1] if m end nil end end end end
20.3
64
0.554187
e926ec937603085bded1c432841f575a5b838439
1,134
# == Schema Information # # Table name: illustration_categories # # id :integer not null, primary key # name :string(32) not null # created_at :datetime # updated_at :datetime # # Indexes # # index_illustration_categories_on_name (name) # class IllustrationCategory < ActiveRecord::Base validates :name, presence: true, uniqueness: { case_sensitive: false }, length: { maximum: 32 } default_scope {order("name ASC") } has_and_belongs_to_many :illustrations after_create :add_uuid_and_origin_url after_commit :reindex_illustrations translates :name, :translated_name def add_uuid_and_origin_url if self.uuid == nil && self.origin_url == nil self.uuid = "#{Settings.org_info.prefix}-#{self.id}" self.origin_url = Settings.org_info.url self.save! elsif self.uuid == nil self.uuid = "#{Settings.org_info.prefix}-#{self.id}" self.save! elsif self.origin_url == nil self.origin_url = Settings.org_info.url self.save! end end def reindex_illustrations illustrations.each{|illustration| illustration.reindex} end end
25.2
97
0.693122
e9740eb3ffa14f700e4a1f8f03763071063b3f94
2,025
require "open-uri" require "nokogiri" require "mechanize" require "pry" require "byebug" require "io/console" require_relative "./profile" require_relative "./challenge" GH_OAUTH_SIGNIN_URL = "https://www.codewars.com/users/preauth/github/signin" def get_gh_authenticated_connection mech = Mechanize.new @username = get_username @password = get_password gh_signed_in_page = get_gh_signed_in_page(mech, @username, @password) @limit = get_limit mech.click(gh_signed_in_page.link_with(text: "click here")) mech end def get_username print "\nEnter your Github username: " gets.chomp end def get_password print "Enter your Github password: " password = STDIN.noecho(&:gets).chomp puts "OK" password end def get_gh_signed_in_page(mech, username, password) mech.get(GH_OAUTH_SIGNIN_URL).form_with(name: nil) do |form| form.login, form.password = [username, password] end.submit if mech.page.links.any?{ |link| link.text =~ /two-factor recovery/ } gh_signed_in_page = mech.page.form_with(name: nil) do |form| print "Enter your 2FA code: " otp = gets.chomp form.otp = otp end.submit else gh_signed_in_page = mech.page end gh_signed_in_page end def get_limit print "Max number of katas to fetch: " gets.chomp.to_i end # authenticate mech = get_gh_authenticated_connection print "\nAuthenticating..." print "." profile = Profile.new(@username, mech, 1, @limit) print "." katas = profile.katas print ".\n" # fetch challenges print "Fetching challenges and solutions..." begin challenges = katas.reduce([]) do |acc, kata| print "." sleep(0.5) acc << Challenge.new(mech, kata) end print "\n" rescue StandardError => e puts "Couldn't fetch all solutions" puts e.backtrace end # parse solutions solns = challenges.map(&:lang_parsed_solution_lists) begin challenges.map(&:generate_output_files) puts "Generated #{katas.count} kata files in output/ directory" rescue StandardError => e puts "Failed to generate output fules" end
23.275862
76
0.728889
ab5b5f71ec046406e0a5a03b99a4e474eadcffa0
1,038
class OccasionsController < ApplicationController def new @occasion = Occasion.new if session[:user_id] @user = User.find_by_id(session[:user_id]) if @user.admin render "new" end end end def create @occasion = Occasion.create(attr_params) redirect_to "/occasions/#{@occasion.id}" end def index if !!session[:user_id] @occasions = Occasion.all else redirect_to '/' end end def show @occasion = Occasion.find_by_id(params[:id]) @user = User.find_by_id(session[:user_id]) end def edit @occasion = Occasion.find_by_id(params[:id]) end def update @occasion = Occasion.find_by_id(params[:id]) @occasion.update(attr_params) @occasion.save redirect_to "/occasions/#{@occasion.id}" end private def attr_params params.require(:occasion).permit(:name) end end end
22.085106
54
0.55973
f869c517a20ac13420207da044b8469e35a5c1ec
969
require "yaml" require "securerandom" require "storageMemory/DeviceManagerMemory" module Hub class DeviceManagerYaml < DeviceManagerMemory def initialize(filename = nil) super() if filename == nil then @filename = SecureRandom.hex + ".yaml" else @filename = filename end loadDevices() end def loadDevices() if File.file?(@filename) then @devices = YAML::load_file(@filename) end end def addDevice(device) super save() end def save() File.open(@filename, "w") do |file| file.truncate(0) file.puts YAML::dump(@devices) end end def clear() super if File.file?(@filename) then File.delete(@filename) end end end end
22.534884
54
0.480908
393baf8cf5f3974be772add748a04f3b23efebeb
180
class RegistrationsController < Devise::RegistrationsController protected def after_sign_up_path_for(resource) '/pets/new' # Or :prefix_to_your_route end end
25.714286
63
0.744444
1d23c72cc0f83f447b94c0fbd4955d4055f996aa
971
# frozen_string_literal: true module Api module V1 class UsersController < ::ApplicationController skip_before_action :authenticate_user!, :authorize_action, :set_conference before_action :doorkeeper_authorize! def show json_user = current_user.as_json(only: %i[ id email username first_name last_name twitter_username organization phone country state city default_locale ], methods: %i[reviewer? organizer?]) render json: json_user end def make_voter current_user.add_role :voter current_user.save render json: { success: true, vote_url: sessions_url } end private def current_user @current_user ||= User.find(doorkeeper_token.resource_owner_id) if doorkeeper_token end end end end
29.424242
98
0.584964
bf7ce4e27fa9e57279c5a98c75fc63954480d52b
1,113
# frozen_string_literal: true class HearingsForAppeal def initialize(appeal_id) @appeal_id = appeal_id end # This method is optimized to avoid calling VACOLS for legacy appeals. def held_hearings if Appeal::UUID_REGEX.match?(appeal_id) Appeal.find_by_uuid!(appeal_id).hearings.where(disposition: Constants.HEARING_DISPOSITION_TYPES.held) else # Assumes that an appeal exists in VACOLS if there are hearings # for it. legacy_hearings = HearingRepository.hearings_for_appeal(appeal_id) # If there are no hearings for the VACOLS id, maybe the case doesn't # actually exist? This is SLOW! Only load VACOLS data if the Legacy Appeal # doesn't exist in Caseflow. `LegacyAppeal.find_or_create_by_vacols_id` will # ALWAYS load data from VACOLS. LegacyAppeal.find_or_create_by_vacols_id(appeal_id) if legacy_hearings.empty? && !LegacyAppeal.exists?(appeal_id) legacy_hearings.select do |hearing| hearing.disposition.to_s == Constants.HEARING_DISPOSITION_TYPES.held end end end private attr_reader :appeal_id end
33.727273
119
0.743935
e91f546dfa5561183f435a8f3b97455ae696d360
1,056
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module FAODatabase class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 5.2 config.i18n.default_locale = :ru puts "---> FAO Database is started! <--- " # Settings in config/environments/* take precedence over those specified here. # Application configuration can go into files in config/initializers # -- all .rb files in that directory are automatically loaded after loading # the framework and any gems in your application. config.action_view.field_error_proc = Proc.new { |html_tag, instance| class_attr_index = html_tag.index 'class="' if class_attr_index html_tag.insert class_attr_index + 7, 'is-invalid ' else html_tag.insert html_tag.index('>'), ' class="is-invalid"' end } end end
33
82
0.713068
ed8b8559b5a6e1db9f87fbcdea1eba1466044956
1,735
cask 'parallels-desktop11' do version '11.2.2-32651' sha256 'f0af6eafb8fd468f84a7ce6dd21d7465589901d2215766f2989add5d5a61ca12' url "https://download.parallels.com/desktop/v#{version.major}/#{version}/ParallelsDesktop-#{version}.dmg" name 'Parallels Desktop' homepage 'https://www.parallels.com/products/desktop/' app 'Parallels Desktop.app' postflight do # Unhide the application system_command '/usr/bin/chflags', args: ['nohidden', "#{appdir}/Parallels Desktop.app"], sudo: true # Run the initialization script system_command "#{appdir}/Parallels Desktop.app/Contents/MacOS/inittool", args: ['init', '-b', "#{appdir}/Parallels Desktop.app"], sudo: true end uninstall_preflight do set_ownership "#{appdir}/Parallels Desktop.app" end uninstall delete: [ '/usr/bin/prl_convert', '/usr/bin/prl_disk_tool', '/usr/bin/prl_perf_ctl', '/usr/bin/prlctl', '/usr/bin/prlsrvctl', ] zap delete: [ '~/.parallels_settings', '~/Library/Caches/com.parallels.desktop.console', '~/Library/Preferences/com.parallels.desktop.console.LSSharedFileList.plist', '~/Library/Preferences/com.parallels.desktop.console.plist', '~/Library/Preferences/com.parallels.Parallels Desktop Statistics.plist', '~/Library/Preferences/com.parallels.Parallels Desktop.plist', '~/Library/Preferences/com.parallels.Parallels.plist', ] end
38.555556
107
0.58098
1c98dd53a6aa8063c1f507975f8eb688a35714fd
1,326
require_relative 'lib/denso/calendar/version' Gem::Specification.new do |spec| spec.name = 'denso-calendar' spec.version = Denso::Calendar::VERSION spec.authors = ['Tatsuya Sato'] spec.email = ['[email protected]'] spec.summary = 'A parser DENSO calendar' spec.description = 'A parser DENSO calendar' spec.homepage = 'https://github.com/satoryu/denso-calendar' spec.license = 'MIT' spec.required_ruby_version = Gem::Requirement.new('>= 2.6.0') spec.metadata['homepage_uri'] = spec.homepage spec.metadata['source_code_uri'] = spec.homepage # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_dependency 'icalendar', '~> 2.6' spec.add_dependency 'nokogiri', '~> 1.10' spec.add_development_dependency 'rake', '~> 12.0' spec.add_development_dependency 'rspec', '~> 3.0' spec.add_development_dependency 'webmock', '~> 3.8' end
40.181818
87
0.659879
ab63ea248bedb5411e8b2156861f00d8f4b91371
1,496
class Enscript < Formula desc "Convert text to Postscript, HTML, or RTF, with syntax highlighting" homepage "https://www.gnu.org/software/enscript/" url "https://ftp.gnu.org/gnu/enscript/enscript-1.6.6.tar.gz" mirror "https://ftpmirror.gnu.org/enscript/enscript-1.6.6.tar.gz" sha256 "6d56bada6934d055b34b6c90399aa85975e66457ac5bf513427ae7fc77f5c0bb" license "GPL-3.0-or-later" revision 1 head "https://git.savannah.gnu.org/git/enscript.git" bottle do sha256 arm64_big_sur: "18c0e8fd04b918f671236e5feffe8406c8368369eb08fe301f817e59233659c0" sha256 big_sur: "97b523c5513e54b82d963a7b34a4cfbcbe0af74399bc48839b5285cfce29a9a1" sha256 catalina: "3611a6a01c76502ae6d4b1ff13d802acc5b2a2a3f2cf647e6b9323b7e40bde7e" sha256 mojave: "a8bbba8f7d64eed40dd59a9db980b049ec786e148d31a0aeb92556959b4ad0b0" sha256 high_sierra: "00045dff3bdf7ac98a19236838d7af7101cc1fc002e55550312042bb2e4d7426" sha256 sierra: "c14fad6cfd67fa782beb7a425eb03c3ed0b8090ed751c37f5f5ec426808df25c" sha256 x86_64_linux: "d968c97391029600c54ace8362e7293202ca6227421d626dced22f21b2ccfa26" end depends_on "gettext" conflicts_with "cspice", because: "both install `states` binaries" def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do assert_match "GNU Enscript #{version}", shell_output("#{bin}/enscript -V") end end
42.742857
92
0.762701
793541742b010a9565414a363214a18402c32150
91
class BatchEditsController < ApplicationController include Hydra::BatchEditBehavior end
18.2
50
0.857143
26ac6794ecdbdb5c860366018bf6669a5e933292
5,267
# frozen_string_literal: true module Kanrisuru module Core module IP def ip_route(action, opts) case action when 'show', 'list' version = ip_version.to_i command = ip_route_show(opts, version) when 'flush' command = ip_route_flush(opts) when 'add', 'change', 'append', 'del', 'delete', 'replace' command = ip_route_modify(action, opts) when 'get' command = ip_route_get(opts) end execute_shell(command) Kanrisuru::Result.new(command) do |cmd| Parser::Route.parse(cmd, action, version) end end def ip_route_show(opts, version) command = Kanrisuru::Command.new('ip') command.append_flag('-json') if version >= IPROUTE2_JSON_VERSION command.append_arg('-family', opts[:family]) command << 'route show' ip_route_common_opts(command, opts) command end def ip_route_modify(action, opts) command = Kanrisuru::Command.new('ip route') command << action command.append_arg('to', opts[:to]) command.append_arg('tos', opts[:tos]) command.append_arg('dsfield', opts[:dsfield]) command.append_arg('metric', opts[:metric]) command.append_arg('preference', opts[:preference]) command.append_arg('table', opts[:table]) command.append_arg('vrf', opts[:vrf]) command.append_arg('dev', opts[:dev]) command.append_arg('via', opts[:via]) command.append_arg('src', opts[:src]) command.append_arg('realm', opts[:realm]) if Kanrisuru::Util.present?(opts[:mtu]) if Kanrisuru::Util.present?(opts[:mtu_lock]) command.append_arg('mtu lock', opts[:mtu]) else command.append_arg('mtu', opts[:mtu]) end end command.append_arg('window', opts[:window]) command.append_arg('rtt', opts[:rtt]) command.append_arg('rttvar', opts[:rttvar]) command.append_arg('rto_min', opts[:rto_min]) command.append_arg('ssthresh', opts[:ssthresh]) command.append_arg('cwnd', opts[:cwnd]) command.append_arg('initcwnd', opts[:initcwnd]) command.append_arg('initrwnd', opts[:initrwnd]) command.append_arg('features', opts[:features]) command.append_arg('quickack', opts[:quickack]) command.append_arg('fastopen_no_cookie', opts[:fastopen_no_cookie]) if Kanrisuru::Util.present?(opts[:congctl]) if Kanrisuru::Util.present?(opts[:congctl_lock]) command.append_arg('congctl lock', opts[:congctl]) else command.append_arg('congctl', opts[:congctl]) end end command.append_arg('advmss', opts[:advmss]) command.append_arg('reordering', opts[:reordering]) if Kanrisuru::Util.present?(opts[:next_hop]) next_hop = opts[:next_hop] command << 'next_hop' command.append_arg('via', next_hop[:via]) command.append_arg('dev', next_hop[:dev]) command.append_arg('weight', next_hop[:weight]) end command.append_arg('scope', opts[:scope]) command.append_arg('protocol', opts[:protocol]) command.append_flag('onlink', opts[:onlink]) command.append_arg('pref', opts[:pref]) command.append_arg('nhid', opts[:nhid]) command end def ip_route_flush(opts) command = Kanrisuru::Command.new('ip') command.append_arg('-family', opts[:family]) command << 'route flush' ip_route_common_opts(command, opts) command end def ip_route_get(opts) command = Kanrisuru::Command.new('ip route get') command.append_flag('fibmatch', opts[:fibmatch]) command.append_arg('to', opts[:to]) command.append_arg('from', opts[:from]) command.append_arg('tos', opts[:tos]) command.append_arg('dsfield', opts[:dsfield]) command.append_arg('iif', opts[:iif]) command.append_arg('oif', opts[:oif]) command.append_arg('mark', opts[:mark]) command.append_arg('vrf', opts[:vrf]) command.append_arg('ipproto', opts[:ipproto]) command.append_arg('sport', opts[:sport]) command.append_arg('dport', opts[:dport]) command.append_flag('connected', opts[:connected]) command end def ip_route_common_opts(command, opts) command.append_arg('to', opts[:to]) command.append_arg('dev', opts[:dev]) command.append_arg('protocol', opts[:protocol]) command.append_arg('type', opts[:type]) command.append_arg('table', opts[:table]) command.append_arg('tos', opts[:tos]) command.append_arg('dsfield', opts[:dsfield]) command.append_arg('via', opts[:via]) command.append_arg('vrf', opts[:vrf]) command.append_arg('src', opts[:src]) command.append_arg('realm', opts[:realm]) command.append_arg('realms', opts[:realms]) command.append_arg('scope', opts[:scope]) command.append_flag('cloned', opts[:cloned]) command.append_flag('cached', opts[:cached]) end end end end
34.424837
75
0.604519
b972c482b3002ebb80c88981d2fd8d6884a0c24e
594
class User < ActiveRecord::Base has_secure_password validates :email, presence: true, uniqueness: true, format: /@/ before_create { generate_token(:auth_token) } def self.authenticate(email, password) user = find_by email: email user if user && user.authenticate(password) end def generate_token(column) begin self[column] = SecureRandom.urlsafe_base64 end while User.exists?(column => self[column]) end def prepare_password_reset generate_token(:password_reset_token) self.password_reset_sent_at = Time.zone.now save! end end
23.76
65
0.713805
abb0fb2ffc5acb16c897c0c796be54049d1a3ced
528
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE module Aws::ElasticsearchService class Resource # @param options ({}) # @option options [Client] :client def initialize(options = {}) @client = options[:client] || Client.new(options) end # @return [Client] def client @client end end end
19.555556
74
0.683712
bbd48fa6f7e9f437664ff741383f9128f1194772
137
class MuiPassword::Javascripts < MuiPassword::Application only_provides :js def password render :layout => false end end
15.222222
57
0.715328
6a44aa17e8d2b2bdc44fab6e7a9ca663046d58f5
2,168
# frozen_string_literal: true require 'spec_helper' RSpec.describe Slack::Surfaces::Home do let(:image_url) { 'https://s3-media3.fl.yelpcdn.com/bphoto/c7ed05m9lC2EmA3Aruue7A/o.jpg' } describe '#as_json' do context 'with blocks argument' do subject(:instance) { described_class.new(blocks: blocks) } let(:blocks) do Slack::BlockKit.blocks do |block| block.image(url: image_url, alt_text: '__ALT_TEXT__') end end let(:expected_json) do { type: 'home', blocks: [ { alt_text: '__ALT_TEXT__', image_url: image_url, type: 'image' } ] } end it 'correctly serializes' do expect(instance.as_json).to eq(expected_json) end end context 'without blocks argument' do subject(:instance) { described_class.new } let(:expected_json) do { type: 'home', blocks: [ { alt_text: '__ALT_TEXT__', image_url: image_url, type: 'image' } ] } end it 'correctly serializes' do instance.blocks.image(url: image_url, alt_text: '__ALT_TEXT__') expect(instance.as_json).to eq(expected_json) end end context 'with other arguments' do subject(:instance) do described_class.new(private_metadata: '__METADATA__', callback_id: '__CALLBACK_ID__', external_id: '__EXTERNAL_ID__') end let(:expected_json) do { type: 'home', blocks: [ { alt_text: '__ALT_TEXT__', image_url: image_url, type: 'image' } ], private_metadata: '__METADATA__', callback_id: '__CALLBACK_ID__', external_id: '__EXTERNAL_ID__' } end it 'correctly serializes' do instance.blocks.image(url: image_url, alt_text: '__ALT_TEXT__') expect(instance.as_json).to eq(expected_json) end end end end
24.359551
92
0.535517
38b21b7a926ce5b4beda882dbdeb584b82588a30
197
class RemoveUnusedStuffs < ActiveRecord::Migration[5.0] def change remove_column :links, :logo remove_column :links, :order remove_column :restaurants, :plain_opening_hours end end
24.625
55
0.756345
bb97e20bee4e5373693a7cfaa0900e5bdf14fbdf
340
require 'formula' class Vramsteg < Formula homepage 'http://tasktools.org/projects/vramsteg.html' url 'http://taskwarrior.org/download/vramsteg-1.0.1.tar.gz' sha1 'bbc9f54e6e10b3e82dbbac6275e2e611d752e85d' depends_on 'cmake' => :build def install system "cmake", ".", *std_cmake_args system "make", "install" end end
22.666667
61
0.720588
bf520b07c13164b324e1ae2ea338dea0f3111d4a
222
Rails.application.config.assets.version = '1.0' Rails.application.config.assets.precompile = ['*.js', '*.css', '*.png', '*.eot', '*.woff', '*.ttf'] Rails.application.config.assets.paths << Rails.root.join('vendor/assets')
55.5
99
0.68018
bf3c34836a1de50deb682d8b8c3ef1f644ff5602
498
require 'active_support/concern' module GrapeV0_14_0 module DSL module API extend ActiveSupport::Concern include GrapeV0_14_0::Middleware::Auth::DSL include GrapeV0_14_0::DSL::Validations include GrapeV0_14_0::DSL::Callbacks include GrapeV0_14_0::DSL::Configuration include GrapeV0_14_0::DSL::Helpers include GrapeV0_14_0::DSL::Middleware include GrapeV0_14_0::DSL::RequestResponse include GrapeV0_14_0::DSL::Routing end end end
24.9
49
0.7249
abc4ed95675480ce50a021df9264375d43142c15
162
class MeetupSerializer < ActiveModel::Serializer attributes :id, :name, :location, :day, :time belongs_to :group has_many :tags, through: :meetup_tags end
23.142857
48
0.746914
6a7d5ff42a40ea2fc50f12b03700cbe04b663297
4,675
# encoding: utf-8 module PhoneNumberMiner require 'mechanize' class AngkorThom require 'google/transliterate' require 'phony' # Gets data from the following catalogue pages # http://akt-media.com/friendship.php?f=2 # http://akt-media.com/friendship.php?f=3 BASE_URL = "http://akt-media.com/friendship.php?f=" COUNTRY_ID = "855" CATALOGUES = { :angkor_thom => 2, :dara => 3 } KHMER_NUMERALS = ["០", "១", "២", "៣", "៤", "៥", "៦", "៧", "៨", "៩"] PROVINCE_ABBREVIATIONS = { "ប.ជ" => "Banteay Meanchey", "ប.ប" => "Battambang", "ក.ច" => "Kampong Cham", "ក.ឆ" => "Kampong Chhnang", "ក.ស្ព" => "Kampong Speu", "ក.ធ" => "Kampong Thom", "ក.ព" => "Kampot", "ក.ណ" => "Kandal", "ខ.ក" => "Kep", "ក.ក" => "Koh Kong", "ក្រ.ច" => "Kratie", "ម.រ" => "Mondulkiri", "ឧ.ជ" => "Oddar Meanchey", "ប.ល" => "Pailin", "ភ.ព" => "Phnom Penh", "ព្រ.ហ" => "Preah Vihear", "ព.វ" => "Prey Veng", "ព.ស" => "Pursat", "រ.រ" => "Ratanakiri", "ស.រ" => "Siem Reap", "ស.នុ" => "Kampong Som", "ស្ទ.ត" => "Stung Treng", "ស្វ.រ" => "Svaay Rieng", "ត.ក" => "Takeo" } def mine!(angkor_thom_page = nil, dara_page = nil) phone_numbers = {} phone_number_catalogues = catalogues(angkor_thom_page, dara_page) @latest_catalogue_pages = {} phone_number_catalogues.each do |catalogue_id, start_page| catalogue = visit_catalogue(catalogue_id) page_range(start_page).each do |potential_page| if page_link = link_to_page(catalogue, potential_page) @latest_catalogue_pages[catalogue_id] = potential_page page_link.click page_data(agent.page).each do |child| child_text = child.text if child_text =~ /(\d+\-\d+)/ formatted_number = $~[1].gsub("-", "") formatted_number.slice!(0) full_number = COUNTRY_ID + formatted_number if Phony.plausible?(full_number) metadata = child_text.split phone_numbers[full_number] = { "gender" => gender(metadata), "name" => name(metadata), "age" => age(metadata), "location" => location(metadata) } end end end end end end phone_numbers end def latest_angkor_thom_page latest_catalogue_page(:angkor_thom) end def latest_dara_page latest_catalogue_page(:dara) end private def latest_catalogue_page(catalogue) latest_page = latest_catalogue_pages[CATALOGUES[catalogue]] latest_page.to_i if latest_page end def page_data(page) data_page = page.search("#left_layout table li p").first data_page ? data_page.children : [] end def latest_catalogue_pages @latest_catalogue_pages ||= {} end def location(metadata) khmer_location = metadata[3].to_s.strip PROVINCE_ABBREVIATIONS.each do |khmer_abbreviation, english_name| return english_name if khmer_location =~ /#{khmer_abbreviation}/ end nil end def age(metadata) khmer_age = metadata[2].to_s.strip.dup KHMER_NUMERALS.each_with_index do |khmer_numeral, index| khmer_age.gsub!(/#{khmer_numeral}/, index.to_s) end khmer_age.gsub(/\D/, "") end def name(metadata) Google::Transliterate::Transliterator.new.transliterate!( "kh", metadata[1].strip ).gsub(/\s+/, "").encode( 'ASCII', :invalid => :replace, :undef => :replace, :replace => '' ) if metadata[1] end def gender(metadata) khmer_gender = metadata[0].to_s.strip if khmer_gender =~ /ខ្ញុំបាទ/ "m" elsif khmer_gender =~ /នាងខ្ញុំ/ "f" end end def agent @agent ||= Mechanize.new end def catalogues(angkor_thom_page, dara_page) { CATALOGUES[:angkor_thom] => angkor_thom_page.to_i + 1, CATALOGUES[:dara] => dara_page.to_i + 1 } end def page_range(start) link_ids = [] agent.page.links.find_all do |link| link_ids << $~[1].to_i if link.text =~ /\-(\d+)/ end start = nil unless start > 1 (start || link_ids.min)..link_ids.max end def visit_catalogue(catalogue_id) agent.get(BASE_URL + catalogue_id.to_s) end def link_to_page(catalogue, id) catalogue.links.find { |link| link.text =~ /\-#{id}/ } end end end
27.339181
73
0.558075
912bd3bed52efdc2d54a0f6c08a616d9a4ea9736
1,928
# # Copyright:: Copyright 2013-2016, 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 "support/shared/integration/integration_helper" require "support/shared/context/config" require "chef/knife/cookbook_bulk_delete" describe "knife cookbook bulk delete", :workstation do include IntegrationSupport include KnifeSupport include_context "default config options" when_the_chef_server "has a cookbook" do before do cookbook "foo", "1.0.0" cookbook "foo", "0.6.5" cookbook "fox", "0.6.0" cookbook "fox", "0.6.5" cookbook "fax", "0.6.0" cookbook "zfa", "0.6.5" end # rubocop:disable Layout/TrailingWhitespace it "knife cookbook bulk delete deletes all matching cookbooks" do stdout = <<EOM All versions of the following cookbooks will be deleted: foo fox Do you really want to delete these cookbooks? (Y/N) EOM stderr = <<EOM Deleted cookbook foo [1.0.0] Deleted cookbook foo [0.6.5] Deleted cookbook fox [0.6.5] Deleted cookbook fox [0.6.0] EOM knife("cookbook bulk delete ^fo.*", input: "Y").should_succeed(stderr: stderr, stdout: stdout) knife("cookbook list -a").should_succeed <<EOM fax 0.6.0 zfa 0.6.5 EOM end # rubocop:enable Layout/TrailingWhitespace end end
29.661538
100
0.681017
7937c88438c6bde68f40421a515f14290a64f411
42
module NewScience VERSION = "0.1.0" end
10.5
19
0.690476
4a2cea927ffcce8855d5963ef398934c524581f7
23,884
require 'date' require 'time' require 'bigdecimal' module DataMapper # :include:QUICKLINKS # # = Properties # Properties for a model are not derived from a database structure, but # instead explicitly declared inside your model class definitions. These # properties then map (or, if using automigrate, generate) fields in your # repository/database. # # If you are coming to DataMapper from another ORM framework, such as # ActiveRecord, this is a fundamental difference in thinking. However, there # are several advantages to defining your properties in your models: # # * information about your model is centralized in one place: rather than # having to dig out migrations, xml or other configuration files. # * having information centralized in your models, encourages you and the # developers on your team to take a model-centric view of development. # * it provides the ability to use Ruby's access control functions. # * and, because DataMapper only cares about properties explicitly defined in # your models, DataMapper plays well with legacy databases, and shares # databases easily with other applications. # # == Declaring Properties # Inside your class, you call the property method for each property you want # to add. The only two required arguments are the name and type, everything # else is optional. # # class Post # include DataMapper::Resource # property :title, String, :nullable => false # # Cannot be null # property :publish, TrueClass, :default => false # # Default value for new records is false # end # # By default, DataMapper supports the following primitive types: # # * TrueClass, Boolean # * String # * Text (limit of 65k characters by default) # * Float # * Integer # * BigDecimal # * DateTime # * Date # * Time # * Object (marshalled out during serialization) # * Class (datastore primitive is the same as String. Used for Inheritance) # # For more information about available Types, see DataMapper::Type # # == Limiting Access # Property access control is uses the same terminology Ruby does. Properties # are public by default, but can also be declared private or protected as # needed (via the :accessor option). # # class Post # include DataMapper::Resource # property :title, String, :accessor => :private # # Both reader and writer are private # property :body, Text, :accessor => :protected # # Both reader and writer are protected # end # # Access control is also analogous to Ruby accessors and mutators, and can # be declared using :reader and :writer, in addition to :accessor. # # class Post # include DataMapper::Resource # # property :title, String, :writer => :private # # Only writer is private # # property :tags, String, :reader => :protected # # Only reader is protected # end # # == Overriding Accessors # The accessor for any property can be overridden in the same manner that Ruby # class accessors can be. After the property is defined, just add your custom # accessor: # # class Post # include DataMapper::Resource # property :title, String # # def title=(new_title) # raise ArgumentError if new_title != 'Luke is Awesome' # @title = new_title # end # end # # == Lazy Loading # By default, some properties are not loaded when an object is fetched in # DataMapper. These lazily loaded properties are fetched on demand when their # accessor is called for the first time (as it is often unnecessary to # instantiate -every- property -every- time an object is loaded). For # instance, DataMapper::Types::Text fields are lazy loading by default, # although you can over-ride this behavior if you wish: # # Example: # # class Post # include DataMapper::Resource # property :title, String # Loads normally # property :body, DataMapper::Types::Text # Is lazily loaded by default # end # # If you want to over-ride the lazy loading on any field you can set it to a # context or false to disable it with the :lazy option. Contexts allow # multipule lazy properties to be loaded at one time. If you set :lazy to # true, it is placed in the :default context # # class Post # include DataMapper::Resource # # property :title, String # # Loads normally # # property :body, DataMapper::Types::Text, :lazy => false # # The default is now over-ridden # # property :comment, String, lazy => [:detailed] # # Loads in the :detailed context # # property :author, String, lazy => [:summary,:detailed] # # Loads in :summary & :detailed context # end # # Delaying the request for lazy-loaded attributes even applies to objects # accessed through associations. In a sense, DataMapper anticipates that # you will likely be iterating over objects in associations and rolls all # of the load commands for lazy-loaded properties into one request from # the database. # # Example: # # Widget[1].components # # loads when the post object is pulled from database, by default # # Widget[1].components.first.body # # loads the values for the body property on all objects in the # # association, rather than just this one. # # Widget[1].components.first.comment # # loads both comment and author for all objects in the association # # since they are both in the :detailed context # # == Keys # Properties can be declared as primary or natural keys on a table. # You should a property as the primary key of the table: # # Examples: # # property :id, Serial # auto-incrementing key # property :legacy_pk, String, :key => true # 'natural' key # # This is roughly equivalent to ActiveRecord's <tt>set_primary_key</tt>, # though non-integer data types may be used, thus DataMapper supports natural # keys. When a property is declared as a natural key, accessing the object # using the indexer syntax <tt>Class[key]</tt> remains valid. # # User[1] # # when :id is the primary key on the users table # User['bill'] # # when :name is the primary (natural) key on the users table # # == Indeces # You can add indeces for your properties by using the <tt>:index</tt> # option. If you use <tt>true</tt> as the option value, the index will be # automatically named. If you want to name the index yourself, use a symbol # as the value. # # property :last_name, String, :index => true # property :first_name, String, :index => :name # # You can create multi-column composite indeces by using the same symbol in # all the columns belonging to the index. The columns will appear in the # index in the order they are declared. # # property :last_name, String, :index => :name # property :first_name, String, :index => :name # # => index on (last_name, first_name) # # If you want to make the indeces unique, use <tt>:unique_index</tt> instead # of <tt>:index</tt> # # == Inferred Validations # If you require the dm-validations plugin, auto-validations will # automatically be mixed-in in to your model classes: # validation rules that are inferred when properties are declared with # specific column restrictions. # # class Post # include DataMapper::Resource # # property :title, String, :length => 250 # # => infers 'validates_length :title, # :minimum => 0, :maximum => 250' # # property :title, String, :nullable => false # # => infers 'validates_present :title # # property :email, String, :format => :email_address # # => infers 'validates_format :email, :with => :email_address # # property :title, String, :length => 255, :nullable => false # # => infers both 'validates_length' as well as # # 'validates_present' # # better: property :title, String, :length => 1..255 # # end # # This functionality is available with the dm-validations gem, part of the # dm-more bundle. For more information about validations, check the # documentation for dm-validations. # # == Default Values # To set a default for a property, use the <tt>:default</tt> key. The # property will be set to the value associated with that key the first time # it is accessed, or when the resource is saved if it hasn't been set with # another value already. This value can be a static value, such as 'hello' # but it can also be a proc that will be evaluated when the property is read # before its value has been set. The property is set to the return of the # proc. The proc is passed two values, the resource the property is being set # for and the property itself. # # property :display_name, String, :default => { |r, p| r.login } # # Word of warning. Don't try to read the value of the property you're setting # the default for in the proc. An infinite loop will ensue. # # == Embedded Values # As an alternative to extraneous has_one relationships, consider using an # EmbeddedValue. # # == Misc. Notes # * Properties declared as strings will default to a length of 50, rather than # 255 (typical max varchar column size). To overload the default, pass # <tt>:length => 255</tt> or <tt>:length => 0..255</tt>. Since DataMapper # does not introspect for properties, this means that legacy database tables # may need their <tt>String</tt> columns defined with a <tt>:length</tt> so # that DM does not apply an un-needed length validation, or allow overflow. # * You may declare a Property with the data-type of <tt>Class</tt>. # see SingleTableInheritance for more on how to use <tt>Class</tt> columns. class Property include Assertions # NOTE: check is only for psql, so maybe the postgres adapter should # define its own property options. currently it will produce a warning tho # since PROPERTY_OPTIONS is a constant # # NOTE: PLEASE update PROPERTY_OPTIONS in DataMapper::Type when updating # them here PROPERTY_OPTIONS = [ :accessor, :reader, :writer, :lazy, :default, :nullable, :key, :serial, :field, :size, :length, :format, :index, :unique_index, :check, :ordinal, :auto_validation, :validates, :unique, :track, :precision, :scale ] # FIXME: can we pull the keys from # DataMapper::Adapters::DataObjectsAdapter::TYPES # for this? TYPES = [ TrueClass, String, DataMapper::Types::Text, Float, Integer, BigDecimal, DateTime, Date, Time, Object, Class, DataMapper::Types::Discriminator, DataMapper::Types::Serial ] IMMUTABLE_TYPES = [ TrueClass, Float, Integer, BigDecimal] VISIBILITY_OPTIONS = [ :public, :protected, :private ] DEFAULT_LENGTH = 50 DEFAULT_PRECISION = 10 DEFAULT_SCALE_BIGDECIMAL = 0 DEFAULT_SCALE_FLOAT = nil attr_reader :primitive, :model, :name, :instance_variable_name, :type, :reader_visibility, :writer_visibility, :getter, :options, :default, :precision, :scale, :track, :extra_options # Supplies the field in the data-store which the property corresponds to # # @return <String> name of field in data-store # - # @api semi-public def field(repository_name = nil) @field || @fields[repository_name] ||= self.model.field_naming_convention(repository_name).call(self) end def unique @unique ||= @options.fetch(:unique, @serial || @key || false) end def hash if @custom && !@bound @type.bind(self) @bound = true end return @model.hash + @name.hash end def eql?(o) if o.is_a?(Property) return o.model == @model && o.name == @name else return false end end def length @length.is_a?(Range) ? @length.max : @length end alias size length def index @index end def unique_index @unique_index end # Returns whether or not the property is to be lazy-loaded # # @return <TrueClass, FalseClass> whether or not the property is to be # lazy-loaded # - # @api public def lazy? @lazy end # Returns whether or not the property is a key or a part of a key # # @return <TrueClass, FalseClass> whether the property is a key or a part of # a key #- # @api public def key? @key end # Returns whether or not the property is "serial" (auto-incrementing) # # @return <TrueClass, FalseClass> whether or not the property is "serial" #- # @api public def serial? @serial end # Returns whether or not the property can accept 'nil' as it's value # # @return <TrueClass, FalseClass> whether or not the property can accept 'nil' #- # @api public def nullable? @nullable end def custom? @custom end # Provides a standardized getter method for the property # # @raise <ArgumentError> "+resource+ should be a DataMapper::Resource, but was ...." #- # @api private def get(resource) lazy_load(resource) value = get!(resource) set_original_value(resource, value) # [YK] Why did we previously care whether options[:default] is nil. # The default value of nil will be applied either way if value.nil? && resource.new_record? && !resource.attribute_loaded?(name) value = default_for(resource) set(resource, value) end value end def get!(resource) resource.instance_variable_get(instance_variable_name) end def set_original_value(resource, val) unless resource.original_values.key?(name) val = val.try_dup val = val.hash if track == :hash resource.original_values[name] = val end end # Provides a standardized setter method for the property # # @raise <ArgumentError> "+resource+ should be a DataMapper::Resource, but was ...." #- # @api private def set(resource, value) # [YK] We previously checked for new_record? here, but lazy loading # is blocked anyway if we're in a new record by by # Resource#reload_attributes. This may eventually be useful for # optimizing, but let's (a) benchmark it first, and (b) do # whatever refactoring is necessary, which will benefit from the # centralize checking lazy_load(resource) new_value = typecast(value) old_value = get!(resource) set_original_value(resource, old_value) set!(resource, new_value) end def set!(resource, value) resource.instance_variable_set(instance_variable_name, value) end # Loads lazy columns when get or set is called. #- # @api private def lazy_load(resource) # It is faster to bail out at at a new_record? rather than to process # which properties would be loaded and then not load them. return if resource.new_record? || resource.attribute_loaded?(name) # If we're trying to load a lazy property, load it. Otherwise, lazy-load # any properties that should be eager-loaded but were not included # in the original :fields list contexts = lazy? ? name : model.eager_properties(resource.repository.name) resource.send(:lazy_load, contexts) end # typecasts values into a primitive # # @return <TrueClass, String, Float, Integer, BigDecimal, DateTime, Date, Time # Class> the primitive data-type, defaults to TrueClass #- # @api private def typecast(value) return type.typecast(value, self) if type.respond_to?(:typecast) return value if value.kind_of?(primitive) || value.nil? begin if primitive == TrueClass then %w[ true 1 t ].include?(value.to_s.downcase) elsif primitive == String then value.to_s elsif primitive == Float then value.to_f elsif primitive == Integer # The simplest possible implementation, i.e. value.to_i, is not # desirable because "junk".to_i gives "0". We want nil instead, # because this makes it clear that the typecast failed. # # After benchmarking, we preferred the current implementation over # these two alternatives: # * Integer(value) rescue nil # * Integer(value_to_s =~ /(\d+)/ ? $1 : value_to_s) rescue nil # # [YK] The previous implementation used a rescue. Why use a rescue # when the list of cases where a valid string other than "0" could # produce 0 is known? value_to_i = value.to_i if value_to_i == 0 value.to_s =~ /^(0x|0b)?0+/ ? 0 : nil else value_to_i end elsif primitive == BigDecimal then BigDecimal(value.to_s) elsif primitive == DateTime then typecast_to_datetime(value) elsif primitive == Date then typecast_to_date(value) elsif primitive == Time then typecast_to_time(value) elsif primitive == Class then self.class.find_const(value) else value end rescue value end end def default_for(resource) @default.respond_to?(:call) ? @default.call(resource, self) : @default end def value(val) custom? ? self.type.dump(val, self) : val end def inspect "#<Property:#{@model}:#{@name}>" end # TODO: add docs # @api private def _dump(*) Marshal.dump([ repository, model, name ]) end # TODO: add docs # @api private def self._load(marshalled) repository, model, name = Marshal.load(marshalled) model.properties(repository.name)[name] end private def initialize(model, name, type, options = {}) assert_kind_of 'model', model, Model assert_kind_of 'name', name, Symbol assert_kind_of 'type', type, Class if Fixnum == type # It was decided that Integer is a more expressively names class to # use instead of Fixnum. Fixnum only represents smaller numbers, # so there was some confusion over whether or not it would also # work with Bignum too (it will). Any Integer, which includes # Fixnum and Bignum, can be stored in this property. warn "#{type} properties are deprecated. Please use Integer instead" type = Integer end unless TYPES.include?(type) || (DataMapper::Type > type && TYPES.include?(type.primitive)) raise ArgumentError, "+type+ was #{type.inspect}, which is not a supported type: #{TYPES * ', '}", caller end @extra_options = {} (options.keys - PROPERTY_OPTIONS).each do |key| @extra_options[key] = options.delete(key) end @model = model @name = name.to_s.sub(/\?$/, '').to_sym @type = type @custom = DataMapper::Type > @type @options = @custom ? @type.options.merge(options) : options @instance_variable_name = "@#{@name}" # TODO: This default should move to a DataMapper::Types::Text # Custom-Type and out of Property. @primitive = @options.fetch(:primitive, @type.respond_to?(:primitive) ? @type.primitive : @type) @getter = TrueClass == @primitive ? "#{@name}?".to_sym : @name @field = @options.fetch(:field, nil) @serial = @options.fetch(:serial, false) @key = @options.fetch(:key, @serial || false) @default = @options.fetch(:default, nil) @nullable = @options.fetch(:nullable, @key == false) @index = @options.fetch(:index, false) @unique_index = @options.fetch(:unique_index, false) @lazy = @options.fetch(:lazy, @type.respond_to?(:lazy) ? @type.lazy : false) && !@key @fields = {} @track = @options.fetch(:track) do if @custom && @type.respond_to?(:track) && @type.track @type.track else IMMUTABLE_TYPES.include?(@primitive) ? :set : :get end end # assign attributes per-type if String == @primitive || Class == @primitive @length = @options.fetch(:length, @options.fetch(:size, DEFAULT_LENGTH)) elsif BigDecimal == @primitive || Float == @primitive @precision = @options.fetch(:precision, DEFAULT_PRECISION) default_scale = (Float == @primitive) ? DEFAULT_SCALE_FLOAT : DEFAULT_SCALE_BIGDECIMAL @scale = @options.fetch(:scale, default_scale) # @scale = @options.fetch(:scale, DEFAULT_SCALE_BIGDECIMAL) unless @precision > 0 raise ArgumentError, "precision must be greater than 0, but was #{@precision.inspect}" end if (BigDecimal == @primitive) || (Float == @primitive && [email protected]?) unless @scale >= 0 raise ArgumentError, "scale must be equal to or greater than 0, but was #{@scale.inspect}" end unless @precision >= @scale raise ArgumentError, "precision must be equal to or greater than scale, but was #{@precision.inspect} and scale was #{@scale.inspect}" end end end determine_visibility @model.auto_generate_validations(self) if @model.respond_to?(:auto_generate_validations) @model.property_serialization_setup(self) if @model.respond_to?(:property_serialization_setup) end def determine_visibility # :nodoc: @reader_visibility = @options[:reader] || @options[:accessor] || :public @writer_visibility = @options[:writer] || @options[:accessor] || :public unless VISIBILITY_OPTIONS.include?(@reader_visibility) && VISIBILITY_OPTIONS.include?(@writer_visibility) raise ArgumentError, 'property visibility must be :public, :protected, or :private', caller(2) end end # Typecasts an arbitrary value to a DateTime def typecast_to_datetime(value) case value when Hash then typecast_hash_to_datetime(value) else DateTime.parse(value.to_s) end end # Typecasts an arbitrary value to a Date def typecast_to_date(value) case value when Hash then typecast_hash_to_date(value) else Date.parse(value.to_s) end end # Typecasts an arbitrary value to a Time def typecast_to_time(value) case value when Hash then typecast_hash_to_time(value) else Time.parse(value.to_s) end end def typecast_hash_to_datetime(hash) args = extract_time_args_from_hash(hash, :year, :month, :day, :hour, :min, :sec) DateTime.new(*args) rescue ArgumentError => e t = typecast_hash_to_time(hash) DateTime.new(t.year, t.month, t.day, t.hour, t.min, t.sec) end def typecast_hash_to_date(hash) args = extract_time_args_from_hash(hash, :year, :month, :day) Date.new(*args) rescue ArgumentError t = typecast_hash_to_time(hash) Date.new(t.year, t.month, t.day) end def typecast_hash_to_time(hash) args = extract_time_args_from_hash(hash, :year, :month, :day, :hour, :min, :sec) Time.local(*args) end # Extracts the given args from the hash. If a value does not exist, it # uses the value of Time.now def extract_time_args_from_hash(hash, *args) now = Time.now args.map { |arg| hash[arg] || hash[arg.to_s] || now.send(arg) } end end # class Property end # module DataMapper
35.279173
146
0.643401
bb326d0d392a74408792b03057a6cb58bddf7b93
2,478
require 'digest' module PragmaticTokenizer module PreProcessor def pre_process(language: Languages::Common) @urls = {} url_to_md5! remove_non_breaking_space! shift_various_characters! replace_colon_in_url! shift_remaining_colons! shift_hashtag! convert_double_quotes! convert_single_quotes!(language) convert_acute_accent_s! shift_hyphens! md5_to_urls! squeeze(' '.freeze) end private def url_to_md5! URI.extract(self, %w(http https ftp)).each do |url| md5 = Digest::MD5.hexdigest(url) @urls[md5] = url gsub!(url, md5) end end def md5_to_urls! @urls.each do |k, v| gsub!(k, v) end end def remove_non_breaking_space! gsub!(Regex::NO_BREAK_SPACE, ''.freeze) end def shift_various_characters! gsub!(Regex::PRE_PROCESS, ' \1 \2 \3 \4 \5 \6 \7 \8 \9 ') end def replace_colon_in_url! gsub!(Regex::COLON_IN_URL, replacement_for_key(':'.freeze)) end def shift_remaining_colons! gsub!(':'.freeze, ' :'.freeze) if self !~ Regex::TIME_WITH_COLON end def shift_hashtag! gsub!('#'.freeze, ' #'.freeze) end def convert_double_quotes! gsub!(Regex::QUOTE, replacements_for_quotes) end def replacements_for_quotes @replacements_for_quotes ||= { "''" => ' ' << replacement_for_key('"'.freeze) << ' ', '"' => ' ' << replacement_for_key('"'.freeze) << ' ', '“' => ' ' << replacement_for_key('“'.freeze) << ' ' }.freeze end def convert_single_quotes!(language) replace(class_for_single_quotes(language).new.handle_single_quotes(self)) end def class_for_single_quotes(language) defined?(language::SingleQuotes) ? language::SingleQuotes : PragmaticTokenizer::Languages::Common::SingleQuotes end def convert_acute_accent_s! gsub!(Regex::ACUTE_ACCENT_S, replacement_for_key('`'.freeze)) end # can these two regular expressions be merged somehow? def shift_hyphens! gsub!(Regex::HYPHEN_AFTER_NON_WORD, ' - '.freeze) gsub!(Regex::HYPHEN_BEFORE_NON_WORD, ' - '.freeze) end def replacement_for_key(replacement_key) PragmaticTokenizer::Languages::Common::PUNCTUATION_MAP[replacement_key] end end end
26.645161
119
0.608959
ab0b8ac0257ea701246e7aaf1b81d6eeb29e38f2
57
module Exist class Attributes < Hashie::Mash end end
11.4
33
0.736842
796df7b5724637b77f8d96aaed1b0fad93693da4
1,285
# frozen_string_literal: true # WARNING ABOUT GENERATED CODE # # This file is generated. See the contributing guide for more information: # https://github.com/aws/aws-sdk-ruby/blob/version-3/CONTRIBUTING.md # # WARNING ABOUT GENERATED CODE Gem::Specification.new do |spec| spec.name = 'aws-sdk-personalize' spec.version = File.read(File.expand_path('../VERSION', __FILE__)).strip spec.summary = 'AWS SDK for Ruby - Amazon Personalize' spec.description = 'Official AWS Ruby gem for Amazon Personalize. This gem is part of the AWS SDK for Ruby.' spec.author = 'Amazon Web Services' spec.homepage = 'https://github.com/aws/aws-sdk-ruby' spec.license = 'Apache-2.0' spec.email = ['[email protected]'] spec.require_paths = ['lib'] spec.files = Dir['LICENSE.txt', 'CHANGELOG.md', 'VERSION', 'lib/**/*.rb'] spec.metadata = { 'source_code_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sdk-personalize', 'changelog_uri' => 'https://github.com/aws/aws-sdk-ruby/tree/version-3/gems/aws-sdk-personalize/CHANGELOG.md' } spec.add_dependency('aws-sdk-core', '~> 3', '>= 3.121.2') spec.add_dependency('aws-sigv4', '~> 1.1') spec.required_ruby_version = '>= 2.3' end
38.939394
115
0.670039
ab1fc569ae38ac225b0a304a93172eb1f119bf33
5,961
require 'spec_helper' describe 'tuskar::logging' do let :params do { } end let :log_params do { :logging_context_format_string => '%(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s [%(request_id)s %(user_identity)s] %(instance)s%(message)s', :logging_default_format_string => '%(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s [-] %(instance)s%(message)s', :logging_debug_format_suffix => '%(funcName)s %(pathname)s:%(lineno)d', :logging_exception_prefix => '%(asctime)s.%(msecs)03d %(process)d TRACE %(name)s %(instance)s', :log_config_append => '/etc/tuskar/logging.conf', :publish_errors => true, :default_log_levels => { 'amqp' => 'WARN', 'amqplib' => 'WARN', 'boto' => 'WARN', 'qpid' => 'WARN', 'sqlalchemy' => 'WARN', 'suds' => 'INFO', 'iso8601' => 'WARN', 'requests.packages.urllib3.connectionpool' => 'WARN' }, :fatal_deprecations => true, :instance_format => '[instance: %(uuid)s] ', :instance_uuid_format => '[instance: %(uuid)s] ', :log_date_format => '%Y-%m-%d %H:%M:%S', :use_syslog => true, :use_stderr => false, :log_facility => 'LOG_FOO', :log_dir => '/var/log', :log_file => '/var/log/foo/bar.log', :verbose => true, :debug => true, } end shared_examples_for 'tuskar-logging' do context 'with basic logging options and default settings' do it_configures 'basic default logging settings' end context 'with basic logging options and non-default settings' do before { params.merge!( log_params ) } it_configures 'basic non-default logging settings' end context 'with extended logging options' do before { params.merge!( log_params ) } it_configures 'logging params set' end context 'without extended logging options' do it_configures 'logging params unset' end end shared_examples 'basic default logging settings' do it 'configures tuskar logging settins with default values' do is_expected.to contain_tuskar_config('DEFAULT/use_syslog').with(:value => '<SERVICE DEFAULT>') is_expected.to contain_tuskar_config('DEFAULT/use_stderr').with(:value => '<SERVICE DEFAULT>') is_expected.to contain_tuskar_config('DEFAULT/log_dir').with(:value => '/var/log/tuskar') is_expected.to contain_tuskar_config('DEFAULT/log_file').with(:value => '/var/log/tuskar/tuskar-api.log') is_expected.to contain_tuskar_config('DEFAULT/verbose').with(:value => '<SERVICE DEFAULT>') is_expected.to contain_tuskar_config('DEFAULT/debug').with(:value => '<SERVICE DEFAULT>') end end shared_examples 'basic non-default logging settings' do it 'configures tuskar logging settins with non-default values' do is_expected.to contain_tuskar_config('DEFAULT/use_syslog').with(:value => 'true') is_expected.to contain_tuskar_config('DEFAULT/use_stderr').with(:value => 'false') is_expected.to contain_tuskar_config('DEFAULT/syslog_log_facility').with(:value => 'LOG_FOO') is_expected.to contain_tuskar_config('DEFAULT/log_dir').with(:value => '/var/log') is_expected.to contain_tuskar_config('DEFAULT/log_file').with(:value => '/var/log/foo/bar.log') is_expected.to contain_tuskar_config('DEFAULT/verbose').with(:value => 'true') is_expected.to contain_tuskar_config('DEFAULT/debug').with(:value => 'true') end end shared_examples_for 'logging params set' do it 'enables logging params' do is_expected.to contain_tuskar_config('DEFAULT/logging_context_format_string').with_value( '%(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s [%(request_id)s %(user_identity)s] %(instance)s%(message)s') is_expected.to contain_tuskar_config('DEFAULT/logging_default_format_string').with_value( '%(asctime)s.%(msecs)03d %(process)d %(levelname)s %(name)s [-] %(instance)s%(message)s') is_expected.to contain_tuskar_config('DEFAULT/logging_debug_format_suffix').with_value( '%(funcName)s %(pathname)s:%(lineno)d') is_expected.to contain_tuskar_config('DEFAULT/logging_exception_prefix').with_value( '%(asctime)s.%(msecs)03d %(process)d TRACE %(name)s %(instance)s') is_expected.to contain_tuskar_config('DEFAULT/log_config_append').with_value( '/etc/tuskar/logging.conf') is_expected.to contain_tuskar_config('DEFAULT/publish_errors').with_value( true) is_expected.to contain_tuskar_config('DEFAULT/default_log_levels').with_value( 'amqp=WARN,amqplib=WARN,boto=WARN,iso8601=WARN,qpid=WARN,requests.packages.urllib3.connectionpool=WARN,sqlalchemy=WARN,suds=INFO') is_expected.to contain_tuskar_config('DEFAULT/fatal_deprecations').with_value( true) is_expected.to contain_tuskar_config('DEFAULT/instance_format').with_value( '[instance: %(uuid)s] ') is_expected.to contain_tuskar_config('DEFAULT/instance_uuid_format').with_value( '[instance: %(uuid)s] ') is_expected.to contain_tuskar_config('DEFAULT/log_date_format').with_value( '%Y-%m-%d %H:%M:%S') end end shared_examples_for 'logging params unset' do [ :logging_context_format_string, :logging_default_format_string, :logging_debug_format_suffix, :logging_exception_prefix, :log_config_append, :publish_errors, :default_log_levels, :fatal_deprecations, :instance_format, :instance_uuid_format, :log_date_format, ].each { |param| it { is_expected.to contain_tuskar_config("DEFAULT/#{param}").with_value('<SERVICE DEFAULT>') } } end context 'on Debian platforms' do let :facts do @default_facts.merge({ :osfamily => 'Debian' }) end it_configures 'tuskar-logging' end context 'on RedHat platforms' do let :facts do @default_facts.merge({ :osfamily => 'RedHat' }) end it_configures 'tuskar-logging' end end
40.55102
160
0.685623
7a361411ec7e259178b26ecca67c44be41b26e0e
2,336
# frozen_string_literal: true %w[htmlbeautifier tty-markdown].each do |optional_dep| require optional_dep rescue LoadError warn "The #{optional_dep} gem is unavailable. Install it as a dependency in your project, if you'd like to use it." end module Html2rss module Configs ## # A collection of methods helping with printing. module PrintHelper ## # Prints nicely formatted markdown to `output`. # # @param markdown [String] # @return [nil] def self.markdown(markdown, output: $stdout) if Object.const_defined?('TTY::Markdown') output.puts TTY::Markdown.parse markdown else output.puts markdown end end ## # Prints nicely formatted code to `output` by wrapping it in a # markdown code block and `.print_markdown`. # # If lang is :html, it beautifies the code # # @param lang [Symbol] e.g. :html, :yaml, :ruby, ... # @param code [String] # @return [nil] def self.code(lang, code, output: $stdout) return code if code&.to_s == '' code = HtmlBeautifier.beautify(code) if Object.const_defined?('HtmlBeautifier') && lang == :html markdown ["```#{lang}", code, '```'].join("\n"), output: output end ## # Pretty prints a Nokogiri::Element and highlights the selector # # @param selector [String] # @param tag [Nokogiri::Node] # @param warn_on_multiple [true, false] # @param warn_on_single [true, false] # @return [nil] def self.tag(selector, tag, warn_on_multiple: true, warn_on_single: false) tag_count = tag.count if warn_on_multiple && tag_count > 1 markdown <<~MARKDOWN *** `#{selector}` selects multiple elements! Please write a selector as precise as possible to select just one element. *** MARKDOWN elsif warn_on_single && tag_count == 1 markdown <<~MARKDOWN *** `#{selector}` selects just one element! Please broaden the selector to select multiple elements. *** MARKDOWN end markdown "**The selector `#{selector}` selects:**" code :html, tag&.to_xhtml nil end end end end
29.948718
117
0.589041
62fb126e505164274a78b458ae02200b27d541d4
3,094
require "jumunge/version" module Jumunge module Utils def remaining_trails @remaining_trails ||= @trails.join('.') end end class JuValue def initialize(object, trail, trails) @object = object @trail = trail @trails = trails end def perform @object[key_name] = empty_value unless @object.key? key_name @object end private def key_name @key_name ||= @trail[0..-2] end def empty_value nil end end class JuArray def initialize(object, trail, trails) @object = object @trail = trail @trails = trails end def perform @object[key_name] = empty_value unless @object.key? key_name @object[key_name] = deep_applied_value if @trails.size.positive? @object end private def key_name @key_name ||= @trail[0..-3] end def empty_value [] end def deep_applied_value @object[key_name].map do |value| Jumunge.new(value, remaining_trails).perform end end include Utils end class JuOther def initialize(object, trail, trails) @object = object @trail = trail @trails = trails end def perform @object[key_name] = empty_value unless @object.key? key_name @object[key_name] = deep_applied_value if @trails.size.positive? @object end private def key_name @trail end def empty_value {} end def deep_applied_value Jumunge.new(@object[key_name], remaining_trails).perform end include Utils end class JuThru def initialize(object, *) @object = object end def perform @object end end class JuOpt def initialize(object, trail, trails) @object = object @trail = trail @trails = trails end def perform if @object.key? key_name @object[key_name] = deep_applied_value if @trails.size.positive? @object else @object end end private def key_name @key_name ||= @trail[0..-2] end def deep_applied_value Jumunge.new(@object[key_name], remaining_trails).perform end include Utils end class Jumunge def initialize(object, path) @object = object @trail, *@trails = path.split '.' @is_array = @trail[-2..-1] == '[]' @is_value = @trail[-1] == '!' @is_opt = @trail[-1] == '?' @performer = performer_class.new @object, @trail, @trails end def perform @performer.perform end private def performer_class if @object if @is_array JuArray elsif @is_value JuValue elsif @is_opt JuOpt else JuOther end else JuThru end end end private_constant :Jumunge, :JuArray, :JuValue, :JuOther, :JuThru, :JuOpt def jumunge(object, *paths) paths.inject(object) do |result, path| Jumunge.new(result, path).perform end end module_function :jumunge end
17.68
74
0.587589
9129dda53b1f8d050f43db63af3bc94f37e58d35
1,055
Lit::Engine.routes.draw do if Lit.api_enabled namespace :api do namespace :v1 do get '/last_change' => 'localizations#last_change' resources :locales, :only=>[:index] resources :localization_keys, :only=>[:index] resources :localizations, :only=>[:index] do get 'last_change', :on=>:collection end end end end resources :locales, :only=>[:index, :destroy] do put :hide, :on=>:member end resources :localization_keys, :only=>[:index, :destroy] do member do get :star end collection do get :starred end resources :localizations, :only=>[:edit, :update] do member do get :previous_versions end end end resources :sources do member do get :synchronize end resources :incomming_localizations, :only=>[:index, :destroy] do member do get :accept end collection do get :accept_all post :reject_all end end end root :to=>"dashboard#index" end
21.530612
68
0.598104
bf3eebcd78c6aa4a130bc4cc79f3fe3239ceeff1
1,176
class ConsoleBridge < Formula desc "Robot Operating System-independent package for logging" homepage "https://wiki.ros.org/console_bridge/" url "https://github.com/ros/console_bridge/archive/0.4.2.tar.gz" sha256 "f44641bed7268d72354476c8c5ff936f0e600e4170e1ff7f61a4b6e1f3fc20ff" bottle do cellar :any sha256 "6cfc06d8ae110d740f208b162127d4e0a2cabf479ece89b8e80cdeb4246596f5" => :mojave sha256 "db387172475ff9b2316e108c3948949a5772d15bd031f4cfdc2cbc78720ea737" => :high_sierra sha256 "1685e012b79d53b1797db76c370a1fb8e1e88eefc589d79cc09a67e834552aaf" => :sierra sha256 "eafbea4c45d5c8ba57a171fff20a776f2c6f4d2b017cd8007201e1b29e4858a1" => :x86_64_linux end depends_on "cmake" => :build needs :cxx11 def install ENV.cxx11 system "cmake", ".", *std_cmake_args system "make", "install" end test do (testpath/"test.cpp").write <<~EOS #include <console_bridge/console.h> int main() { CONSOLE_BRIDGE_logDebug("Testing Log"); return 0; } EOS system ENV.cxx, "test.cpp", "-L#{lib}", "-lconsole_bridge", "-std=c++11", "-o", "test" system "./test" end end
30.947368
94
0.709184
4a1d6f0aa01b721bafc3370bfcdae5bd931faf58
1,488
require 'spec_helper' describe "redact" do let(:node) { 'test.example.com' } let(:facts) { { :fqdn => 'test.example.com', } } let(:params) { { :param => 'a param', :redacted => 'to be redacted', :replaced => 'to be replaced', } } it { is_expected.to contain_class('redact').with({ :param => 'a param', :redacted => '<<redacted>>', :replaced => 'a replacement string', }) } it { is_expected.to contain_redact__thing('one').with({ :param => 'a param', :redacted => '<<redacted>>', :replaced => 'a replacement string', }) } it { is_expected.to contain_redact__thing('two').with({ :param => 'a param', :redacted => '<<redacted>>', :replaced => 'a replacement string', }) } it { is_expected.to contain_redact__thing('three').with({ :param => 'a param', :redacted => '<<redacted>>', :replaced => 'a replacement string', }) } it { is_expected.to contain_redact__thing('four').with({ :param => 'a param', :redacted => '<<redacted>>', :replaced => 'a replacement string', }) } describe 'parameters being redacted are still available to use in manifests' do ['one','two','three','four'].each do |title| it { is_expected.to contain_notify("#{title} The value of redacted is to be redacted") } it { is_expected.to contain_notify("#{title} The value of replaced is to be replaced") } end end end
28.615385
94
0.572581
285b0d7c80c3a9fa49437d3d674b94f8f6899277
1,146
# frozen_string_literal: true class HearingAdminActionForeignVeteranCaseTask < HearingAdminActionTask def self.label "Foreign Veteran case" end def available_actions(user) hearing_admin_actions = available_hearing_user_actions(user) if (assigned_to &.== user) || HearingsManagement.singleton.user_has_access?(user) return [ Constants.TASK_ACTIONS.TOGGLE_TIMED_HOLD.to_h, Constants.TASK_ACTIONS.CANCEL_FOREIGN_VETERANS_CASE_TASK.to_h, Constants.TASK_ACTIONS.SEND_TO_SCHEDULE_VETERAN_LIST.to_h ] | hearing_admin_actions end hearing_admin_actions end def update_from_params(params, current_user) payload_values = params.delete(:business_payloads)&.dig(:values) super(params.except(:instructions), current_user) # verifies access params[:instructions] = flattened_instructions(params) parent.update!(instructions: params[:instructions]) case params[:status] when Constants.TASK_STATUSES.completed appeal.va_dot_gov_address_validator.assign_ro_and_update_ahls( payload_values[:regional_office_value] ) end [self] end end
27.95122
85
0.756545
2665431967cb0fcc602be376592f7bdb80fad80f
101
class BoardSerializer < ActiveModel::Serializer attributes :id, :name, :date has_many :props end
20.2
47
0.762376
b93be96891728caf3dd7aca1979d14c2bd3c5bea
1,114
module HotPotato # Workers manipulate data from other workers or faucets. Examples include: Calculate Scores, Merge # Data, and Filter Data. Each worker is a ruby file in the app directory that extends HotPotato::Worker # and implements the perform(message) method. For each message the worker wants to send to the next AppTask, # the send_message method should be called. # # class Influencer < HotPotato::Worker # # def perform(message) # message["influence"] = rand(100) # send_message message # end # # end class Worker include HotPotato::AppTask def start(queue_in) @queue_out = underscore(self.class.name.to_sym) if !self.respond_to?('perform') log.error "The Worker #{self.class.name} does not implement a perform method." exit 1 end start_heartbeat_service queue_subscribe(queue_in) do |m| count_message_in perform m end end def send_message(m) queue_inject @queue_out, m count_message_out end end end
27.85
111
0.641831
3345266d2fe126981446b0e91208fdaad239d273
2,330
# Custom tags for JSDuck 5.x # See also: # - https://github.com/senchalabs/jsduck/wiki/Custom-tags # - https://github.com/senchalabs/jsduck/wiki/Custom-tags/7f5c32e568eab9edc8e3365e935bcb836cb11f1d require 'jsduck/tag/tag' class CommonTag < JsDuck::Tag::Tag def initialize @html_position = POS_DOC + 0.1 @repeatable = true end def parse_doc(scanner, _position) if @multiline return { tagname: @tagname, doc: :multiline } else text = scanner.match(/.*$/) return { tagname: @tagname, doc: text } end end def process_doc(context, tags, _position) context[@tagname] = tags end def format(context, formatter) context[@tagname].each do |tag| tag[:doc] = formatter.format(tag[:doc]) end end end class SeeTag < CommonTag def initialize @tagname = :see @pattern = 'see' super end def format(context, formatter) position = context[:files][0] context[@tagname].each do |tag| tag[:doc] = '<li>' + render_long_see(tag[:doc], formatter, position) + '</li>' end end def to_html(context) <<-EOHTML <h3 class="pa">Related</h3> <ul> #{context[@tagname].map { |tag| tag[:doc] }.join("\n")} </ul> EOHTML end def render_long_see(tag, formatter, position) match = /\A([^\s]+)( .*)?\Z/m.match(tag) if match name = match[1] doc = match[2] ? ': ' + match[2] : '' return formatter.format("{@link #{name}} #{doc}") else JsDuck::Logger.warn(nil, 'Unexpected @see argument: "' + tag + '"', position) return tag end end end class ContextTag < CommonTag def initialize @tagname = :this @pattern = 'this' super end def format(context, formatter) position = context[:files][0] context[@tagname].each do |tag| tag[:doc] = render_long_this(tag[:doc], formatter, position) end end def to_html(context) <<-EOHTML <h3 class="pa">Context</h3> #{context[@tagname].last[:doc]} EOHTML end def render_long_this(tag, formatter, position) match = /\A([^\s]+)/m.match(tag) if match name = match[1] return formatter.format("`context` : {@link #{name}}") else JsDuck::Logger.warn(nil, 'Unexpected @this argument: "' + tag + '"', position) return tag end end end
22.621359
98
0.608155
ffdda4d88db567f4dc7819bcfaa2fd91d51c6508
762
module Mandate module CallInjector def self.extended(base) # Defining call allows us to do use the syntax: # Foobar.(some, args) # which internally calls: # Foobar.new(some, args).call() class << base def call(*args) # If the last argument is a hash and the last param is a keyword params (signified by # its type being :key, the we should pass the hash in in using the **kwords syntax. # This fixes a deprecation issue in Ruby 2.7. if args.last.is_a?(Hash) && instance_method(:initialize).parameters.last&.first == :key new(*args[0..-2], **args[-1]).() else new(*args).() end end end end end end
31.75
95
0.564304
5d2b78b44e064ad9f0e03104af50af1e982be36d
2,832
# myExperiment: db/migrate/018_savage_beast_tables.rb # # Copyright (c) 2007 University of Manchester and the University of Southampton. # See license.txt for details. class SavageBeastTables < ActiveRecord::Migration def self.up # create_table "forums", :force => true do |t| # t.column "name", :string # t.column "contributor_id", :integer # t.column "contributor_type", :string # t.column "description", :string # t.column "topics_count", :integer, :default => 0 # t.column "posts_count", :integer, :default => 0 # t.column "position", :integer # t.column "description_html", :text # end # create_table "moderatorships", :force => true do |t| # t.column "forum_id", :integer # t.column "user_id", :integer # end # add_index "moderatorships", ["forum_id"], :name => "index_moderatorships_on_forum_id" # create_table "monitorships", :force => true do |t| # t.column "topic_id", :integer # t.column "user_id", :integer # t.column "active", :boolean, :default => true # end # create_table "posts", :force => true do |t| # t.column "user_id", :integer # t.column "topic_id", :integer # t.column "body", :text # t.column "created_at", :datetime # t.column "updated_at", :datetime # t.column "forum_id", :integer # t.column "body_html", :text # end # add_index "posts", ["forum_id", "created_at"], :name => "index_posts_on_forum_id" # add_index "posts", ["user_id", "created_at"], :name => "index_posts_on_user_id" # # create_table "topics", :force => true do |t| # t.column "forum_id", :integer # t.column "user_id", :integer # t.column "title", :string # t.column "created_at", :datetime # t.column "updated_at", :datetime # t.column "hits", :integer, :default => 0 # t.column "sticky", :integer, :default => 0 # t.column "posts_count", :integer, :default => 0 # t.column "replied_at", :datetime # t.column "locked", :boolean, :default => false # t.column "replied_by", :integer # t.column "last_post_id", :integer # end # add_index "topics", ["forum_id"], :name => "index_topics_on_forum_id" # add_index "topics", ["forum_id", "sticky", "replied_at"], :name => "index_topics_on_sticky_and_replied_at" # add_index "topics", ["forum_id", "replied_at"], :name => "index_topics_on_forum_id_and_replied_at" # add_column :users, :posts_count, :integer, :default => 0 add_column :users, :last_seen_at, :datetime end def self.down # drop_table :forums # drop_table :moderatorships # drop_table :monitorships # drop_table :posts # drop_table :topics # # remove_column :users, :posts_count remove_column :users, :last_seen_at end end
35.4
110
0.631356
6206e5f49dab92c68c8fd57f405aa8d7e60ce308
957
Pod::Spec.new do |s| s.name = "KCProtocolKit" s.version = "0.1.101" s.summary = "A short description of KCProtocolKit." s.license = 'MIT' s.author = { "Emil Wojtaszek" => "[email protected]" } s.source = { :git => "[email protected]:newmedia/chat-protocol-ios.git", :tag => s.version.to_s } s.platform = :ios, '8.0' s.requires_arc = true s.source_files = 'KCProtocolKit/*.{h,m}' s.homepage = 'https://www.appunite.com' # protobuf s.dependency 'chat-protocol-objc' # networking s.dependency 'AFNetworking', '< 3.0' s.dependency 'AFgzipRequestSerializer' s.dependency 'SocketRocket' # storage s.dependency 'ObjectiveLevelDBappunite' s.dependency 'Mantle', '~> 2.0' s.dependency 'FastCoding', '~> 3.2' #kingschat s.dependency 'KCFilesKit' s.dependency 'KCImageKit' # others s.dependency 'FormatterKit', '~> 1.8' end
29.90625
112
0.607106
5d0b002b9f218adf525b4f2c8813eef354a0e834
10,462
#-- encoding: UTF-8 #-- copyright # OpenProject is a project management system. # Copyright (C) 2012-2018 the OpenProject Foundation (OPF) # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See docs/COPYRIGHT.rdoc for more details. #++ class UsersController < ApplicationController layout 'admin' before_action :disable_api before_action :require_admin, except: [:show, :deletion_info, :destroy] before_action :find_user, only: [:show, :edit, :update, :change_status_info, :change_status, :destroy, :deletion_info, :resend_invitation] # should also contain destroy but post data can not be redirected before_action :require_login, only: [:deletion_info] before_action :authorize_for_user, only: [:destroy] before_action :check_if_deletion_allowed, only: [:deletion_info, :destroy] # Password confirmation helpers and actions include Concerns::PasswordConfirmation before_action :check_password_confirmation, only: [:destroy] accept_key_auth :index, :show, :create, :update, :destroy include SortHelper include CustomFieldsHelper include PaginationHelper def index @groups = Group.all.sort @status = Users::UserFilterCell.status_param params @users = Users::UserFilterCell.filter params respond_to do |format| format.html do render layout: !request.xhr? end end end def show # show projects based on current user visibility @memberships = @user.memberships .visible(current_user) events = Redmine::Activity::Fetcher.new(User.current, author: @user).events(nil, nil, limit: 10) @events_by_day = events.group_by { |e| e.event_datetime.to_date } unless User.current.admin? if !(@user.active? || @user.registered?) || (@user != User.current && @memberships.empty? && events.empty?) render_404 return end end respond_to do |format| format.html do render layout: 'base' end end end def new @user = User.new(language: Setting.default_language, mail_notification: Setting.default_notification_option) @auth_sources = AuthSource.all end verify method: :post, only: :create, render: { nothing: true, status: :method_not_allowed } def create @user = User.new(language: Setting.default_language, mail_notification: Setting.default_notification_option) @user.attributes = permitted_params.user_create_as_admin(false, @user.change_password_allowed?) @user.admin = params[:user][:admin] || false @user.login = params[:user][:login] || @user.mail if UserInvitation.invite_user! @user respond_to do |format| format.html do flash[:notice] = l(:notice_successful_create) redirect_to(params[:continue] ? new_user_path : edit_user_path(@user)) end end else @auth_sources = AuthSource.all respond_to do |format| format.html do render action: 'new' end end end end def edit @auth_sources = AuthSource.all @membership ||= Member.new end verify method: :put, only: :update, render: { nothing: true, status: :method_not_allowed } def update @user.attributes = permitted_params.user_update_as_admin(@user.uses_external_authentication?, @user.change_password_allowed?) if @user.change_password_allowed? if params[:user][:assign_random_password] @user.random_password! elsif set_password? params @user.password = params[:user][:password] @user.password_confirmation = params[:user][:password_confirmation] end end pref_params = if params[:pref].present? permitted_params.pref else {} end if @user.save update_email_service = UpdateUserEmailSettingsService.new(@user) update_email_service.call(mail_notification: pref_params.delete(:mail_notification), self_notified: params[:self_notified] == '1', notified_project_ids: params[:notified_project_ids]) @user.pref.attributes = pref_params @user.pref.save if [email protected]? && @user.change_password_allowed? send_information = params[:send_information] if @user.invited? # setting a password for an invited user activates them implicitly @user.activate! send_information = true end if @user.active? && send_information UserMailer.account_information(@user, @user.password).deliver_now end end respond_to do |format| format.html do flash[:notice] = l(:notice_successful_update) redirect_back(fallback_location: edit_user_path(@user)) end end else @auth_sources = AuthSource.all @membership ||= Member.new # Clear password input @user.password = @user.password_confirmation = nil respond_to do |format| format.html do render action: :edit end end end rescue ::ActionController::RedirectBackError redirect_to controller: '/users', action: 'edit', id: @user end def change_status_info @status_change = params[:change_action].to_sym return render_400 unless %i(activate lock unlock).include? @status_change end def change_status if @user.id == current_user.id # user is not allowed to change own status redirect_back_or_default(action: 'edit', id: @user) return end if params[:unlock] @user.failed_login_count = 0 @user.activate elsif params[:lock] @user.lock elsif params[:activate] @user.activate end # Was the account activated? (do it before User#save clears the change) was_activated = (@user.status_change == [User::STATUSES[:registered], User::STATUSES[:active]]) if params[:activate] && @user.missing_authentication_method? flash[:error] = I18n.t(:error_status_change_failed, errors: I18n.t(:notice_user_missing_authentication_method), scope: :user) elsif @user.save flash[:notice] = I18n.t(:notice_successful_update) if was_activated UserMailer.account_activated(@user).deliver_now end else flash[:error] = I18n.t(:error_status_change_failed, errors: @user.errors.full_messages.join(', '), scope: :user) end redirect_back_or_default(action: 'edit', id: @user) end def resend_invitation status = Principal::STATUSES[:invited] @user.update status: status if @user.status != status token = UserInvitation.reinvite_user @user.id if token.persisted? flash[:notice] = I18n.t(:notice_user_invitation_resent, email: @user.mail) else logger.error "could not re-invite #{@user.mail}: #{token.errors.full_messages.join(' ')}" flash[:error] = I18n.t(:notice_internal_server_error, app_title: Setting.app_title) end redirect_to edit_user_path(@user) end def destroy # true if the user deletes him/herself self_delete = (@user == User.current) DeleteUserService.new(@user, User.current).call flash[:notice] = l('account.deleted') respond_to do |format| format.html do redirect_to self_delete ? signin_path : users_path end end end def deletion_info render action: 'deletion_info', layout: my_or_admin_layout end private def find_user if params[:id] == 'current' || params['id'].nil? require_login || return @user = User.current else @user = User.find(params[:id]) end rescue ActiveRecord::RecordNotFound render_404 end def authorize_for_user if (User.current != @user || User.current == User.anonymous) && !User.current.admin? respond_to do |format| format.html do render_403 end format.xml do head :unauthorized, 'WWW-Authenticate' => 'Basic realm="OpenProject API"' end format.js do head :unauthorized, 'WWW-Authenticate' => 'Basic realm="OpenProject API"' end format.json do head :unauthorized, 'WWW-Authenticate' => 'Basic realm="OpenProject API"' end end false end end def check_if_deletion_allowed render_404 unless DeleteUserService.deletion_allowed? @user, User.current end def my_or_admin_layout # TODO: how can this be done better: # check if the route used to call the action is in the 'my' namespace if url_for(:delete_my_account_info) == request.url 'my' else 'admin' end end def set_password?(params) params[:user][:password].present? && !OpenProject::Configuration.disable_password_choice? end protected def default_breadcrumb if action_name == 'index' t('label_user_plural') else ActionController::Base.helpers.link_to(t('label_user_plural'), users_path) end end def show_local_breadcrumb true end end
31.70303
100
0.646721
61dae1b32fe6472ecbe2fc979abb274a4afad131
51
def self.foo(a, *) end def bar puts "hello" end
7.285714
18
0.627451
bf27ae085ec25a3a0eababb698024a09441fd289
1,070
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20151126210113) do create_table "todos", force: :cascade do |t| t.text "title" t.date "due" t.string "state" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "project" t.string "to" t.integer "at" end end
38.214286
86
0.737383
618acd1f4ab2e36e8bf9e68a7f9e2b660bc8faa6
305
class DashboardController < ApplicationController breadcrumb "Dashboard", :dashboard_path def show @user = UserPresenter.new(current_user) journeys = Journey.not_remove.includes(:category).where(user_id: current_user.id) @journeys = journeys.map { |j| JourneyPresenter.new(j) } end end
30.5
85
0.754098
62c3c9355e9887d52e9c9e01693589a1833c603d
1,003
module Ammitto class Document attr_reader :type, :number, :country, :note, :doc_name def initialize(doc) @type = doc["type"] if doc["type"].is_a?(String) @number = doc["number"] if doc["number"].is_a?(String) @country = doc["country"] if doc["country"].is_a?(String) @note = doc["note"] if doc["note"].is_a?(String) end def to_hash res = {} doc_name = self.class.to_s.sub('Ammitto::','').downcase res[doc_name] = {} res[doc_name]["type"] = type.to_s if type res[doc_name]["number"] = number.to_s if number res[doc_name]["country"] = country.to_s if country res[doc_name]["note"] = note.to_s if note res end def to_xml(builder) doc_name = self.class.to_s.sub('Ammitto::','').downcase builder.send(doc_name) do builder.type type if type builder.number number if number builder.country country if country builder.note note if note end end end end
27.861111
63
0.605184
ac366159a3456570c619753e71900a1053456a37
797
cask 'brave-browser-beta' do version '0.70.112' sha256 'b80765721888bd0873032dc801b5875839f3e0bb73a6dadeab6d1282fe74d319' # github.com/brave/brave-browser was verified as official when first introduced to the cask url "https://github.com/brave/brave-browser/releases/download/v#{version}/Brave-Browser-Beta.dmg" appcast 'https://updates.bravesoftware.com/sparkle/Brave-Browser/beta/appcast.xml' name 'Brave Beta' homepage 'https://brave.com/download-beta/' auto_updates true depends_on macos: '>= :mavericks' app 'Brave Browser Beta.app' zap trash: [ '~/Library/Application Support/brave', '~/Library/Preferences/com.electron.brave.plist', '~/Library/Saved Application State/com.electron.brave.savedState', ] end
36.227273
99
0.711418
bfa34a19e69b6156befaf5d714df889bf1c0878d
30,202
module Typelib # In Typelib, a registry contains a consistent set of types, i.e. the types # are that are related to each other. # # As mentionned in the Typelib module documentation, it is better to # manipulate value objects from types from the same registry. That is more # efficient, as it removes the need to compare the type definitions whenever # the values are manipulated together. # # I.e., it is better to use a global registry to represent all the types # used in your application. In case you need to load different registries, # that can be achieved by +merging+ them together (which will work only if # the type definitions match between the registries). class Registry TYPE_BY_EXT = { ".c" => "c", ".cc" => "c", ".cxx" => "c", ".cpp" => "c", ".h" => "c", ".hh" => "c", ".hxx" => "c", ".hpp" => "c", ".tlb" => "tlb" } TYPE_HANDLERS = Hash.new def dup copy = self.class.new copy.merge(self) copy end # Generates the smallest new registry that allows to define a set of types # # @overload minimal(type_name, with_aliases = true) # @param [String] type_name the name of a type # @param [Boolean] with_aliases if true, aliases defined in self that # point to types ending up in the minimal registry will be copied # @return [Typelib::Registry] the registry that allows to define the # named type # # @overload minimal(auto_types, with_aliases = true) # @param [Typelib::Registry] auto_types a registry containing the # types that are not necessary in the result # @param [Boolean] with_aliases if true, aliases defined in self that # point to types ending up in the minimal registry will be copied # @return [Typelib::Registry] the registry that allows to define all # types of self that are not in auto_types. Note that it may contain # types that are in the auto_types registry, if they are needed to # define some other type def minimal(type, with_aliases = true) do_minimal(type, with_aliases) end # Creates a new registry by loading a typelib XML file # # @see Registry#merge_xml def self.from_xml(xml) reg = Typelib::Registry.new reg.merge_xml(xml) reg end # Enumerate the types contained in this registry # # @overload each(prefix, :with_aliases => false) # Enumerates the types and not the aliases # # @param [nil,String] prefix if non-nil, only types whose name is this prefix # will be enumerated # @yieldparam [Model<Typelib::Type>] type a type # # @overload each(prefix, :with_aliases => true) # Enumerates the types and the aliases # # @param [nil,String] prefix if non-nil, only types whose name is this prefix # will be enumerated # @yieldparam [String] name the type name, it is different from type.name for # aliases # @yieldparam [Model<Typelib::Type>] type a type def each(filter = nil, options = Hash.new, &block) if filter.kind_of?(Hash) filter, options = nil, filter end options = Kernel.validate_options options, :with_aliases => false if !block_given? enum_for(:each, filter, options) else each_type(filter, options[:with_aliases], &block) end end include Enumerable # Tests for the presence of a type by its name # # @param [String] name the type name # @return [Boolean] true if this registry contains a type named like # this def include?(name) includes?(name) end attr_reader :exported_type_to_real_type attr_reader :real_type_to_exported_type def setup_type_export_module(mod) if !mod.respond_to?('find_exported_template') mod.extend(TypeExportNamespace) mod.registry = self end end def export_solve_namespace(base_module, typename) @export_namespaces ||= Hash.new @export_namespaces[base_module] ||= Hash.new if result = export_namespaces[base_module][typename] return result end namespace = Typelib.split_typename(typename) basename = namespace.pop setup_type_export_module(base_module) mod = namespace.inject(base_module) do |mod, ns| template_basename, template_args = GCCXMLLoader.parse_template(ns) ns = template_basename.gsub(/\s+/, '_').camelcase(:upper) if template_args.empty? mod = if mod.const_defined_here?(ns) mod.const_get(ns) else result = Module.new mod.const_set(ns, result) result end setup_type_export_module(mod) mod else # Must already be defined as it is an actual type object, # not a namespace template_args.map! do |s| if s =~ /^\d+$/ then Integer(s) else s end end if !mod.respond_to?(:find_exported_template) return end template = mod.find_exported_template(ns, [], template_args) return if !template template end end export_namespaces[base_module][typename] = [basename, mod] end attr_reader :export_typemap attr_reader :export_namespaces class InconsistentTypeExport < RuntimeError attr_reader :path attr_reader :existing_type attr_reader :new_type def initialize(path, existing_type, new_type, message = nil) super(message) @path = path @existing_type = existing_type @new_type = new_type end def exception(message = nil) if message.respond_to?(:to_str) self.class.new(path, existing_type, new_type, message) else self end end def pretty_print(pp) pp.text "there is a type registered at #{path} that differs from the one we are trying to register" pp.breakable pp.text "registered type is" pp.nest(2) do pp.breakable existing_type.pretty_print(pp) end pp.breakable pp.text "new type is" pp.nest(2) do pp.breakable new_type.pretty_print(pp) end end end # Export this registry in the Ruby namespace. The base namespace under # which it should be done is given in +base_module+ def export_to_ruby(base_module = Kernel, options = Hash.new) options = Kernel.validate_options options, :override => false, :excludes => nil override = options[:override] exclude_rx = /^$/ if options[:excludes].respond_to?(:each) rx_elements = [] options[:excludes].each do |s| if s.respond_to?(:to_str) rx_elements << "^#{Regexp.quote(s)}$" elsif s.kind_of?(Regexp) rx_elements << s.to_s end end exclude_rx = Regexp.new(rx_elements.join("|")) elsif options[:excludes] exclude_rx = Regexp.new("^#{Regexp.quote(options[:excludes])}$") end new_export_typemap = Hash.new each(:with_aliases => true) do |name, type| next if name =~ exclude_rx basename, mod = export_solve_namespace(base_module, name) if !mod.respond_to?(:find_exported_template) next end next if !mod exported_type = if type.convertion_to_ruby type.convertion_to_ruby[0] || type else type end if block_given? exported_type = yield(name, type, mod, basename, exported_type) next if !exported_type if !exported_type.kind_of?(Class) raise ArgumentError, "the block given to export_to_ruby must return a Ruby class or nil (got #{exported_type})" end if exported_type.respond_to?(:convertion_to_ruby) && exported_type.convertion_to_ruby exported_type = exported_type.convertion_to_ruby[0] || exported_type end end new_export_typemap[exported_type] ||= Set.new new_export_typemap[exported_type] << [type, mod, basename] if (existing_exports = @export_typemap[exported_type]) && existing_exports.include?([type, mod, basename]) next end if type <= Typelib::PointerType || type <= Typelib::ArrayType # We ignore arrays for now # export_array_to_ruby(mod, $1, Integer($2), exported_type) next end template_basename, template_args = GCCXMLLoader.parse_template(basename) if template_args.empty? basename = basename.gsub(/\s+/, '_').camelcase(:upper) if mod.const_defined_here?(basename) existing_type = mod.const_get(basename) if override mod.const_set(basename, exported_type) elsif !(existing_type <= exported_type) if existing_type.class == Module # The current value is a namespace, the new a # type. We probably loaded a nested definition # first and then the parent type. Migrate one to # the other mod.const_set(basename, exported_type) setup_type_export_module(exported_type) existing_type.exported_types.each do |name, type| exported_type.const_set(name, type) end else raise InconsistentTypeExport.new("#{mod.name}::#{basename}", existing_type, exported_type), "there is a type registered at #{mod.name}::#{basename} which differs from the one in the registry, and override is false" end end else mod.exported_types[basename] = type mod.const_set(basename, exported_type) end else export_template_to_ruby(mod, template_basename, template_args, type, exported_type) end end ensure @export_typemap = new_export_typemap end # Remove all types exported by #export_to_ruby under +mod+, and # de-registers them from the export_typemap def clear_exports(export_target_mod) if !export_target_mod.respond_to?(:exported_types) return end found_type_exports = ValueSet.new export_target_mod.constants.each do |c| c = export_target_mod.const_get(c) if c.respond_to?(:exported_types) clear_exports(c) end end export_target_mod.exported_types.each do |const_name, type| found_type_exports.insert(export_target_mod.const_get(const_name)) export_target_mod.send(:remove_const, const_name) end export_target_mod.exported_types.clear found_type_exports.each do |exported_type| set = export_typemap[exported_type] set.delete_if do |_, mod, _| export_target_mod == mod end if set.empty? export_typemap.delete(exported_type) end end end module TypeExportNamespace attr_writer :registry def registry if @registry then @registry elsif superclass.respond_to?(:registry) superclass.registry end end attribute(:exported_types) { Hash.new } attribute(:exported_templates) { Hash.new } def find_exported_template(template_basename, args, remaining) if remaining.empty? return exported_templates[[template_basename, args]] end head, *tail = remaining # Accept Ruby types in place of the corresponding Typelib type, # and accept type objects in place of type names if head.kind_of?(Class) if real_types = registry.export_typemap[head] head = real_types.map do |t, _| t.name end else raise ArgumentError, "#{arg} is not a type exported from a Typelib registry" end end if head.respond_to?(:each) args << nil for a in head args[-1] = a if result = find_exported_template(template_basename, args, tail) return result end end return nil else args << head return find_exported_template(template_basename, args, tail) end end end def export_template_to_ruby(mod, template_basename, template_args, actual_type, exported_type) template_basename = template_basename.gsub(/\s+/, '_').camelcase(:upper) if !mod.respond_to?(template_basename) mod.singleton_class.class_eval do define_method(template_basename) do |*args| if !(result = find_exported_template(template_basename, [], args)) raise ArgumentError, "there is no template instanciation #{template_basename}<#{args.join(",")}> available" end result end end end template_args = template_args.map do |arg| if arg =~ /^\d+$/ Integer(arg) else arg end end exports = mod.exported_templates exports[[template_basename, template_args]] = exported_type end # Returns the file type as expected by Typelib from # the extension of +file+ (see TYPE_BY_EXT) # # Raises RuntimeError if the file extension is unknown def self.guess_type(file) ext = File.extname(file) if type = TYPE_BY_EXT[ext] type else raise "Cannot guess file type for #{file}: unknown extension '#{ext}'" end end # Format +option_hash+ to the form expected by do_import # (Yes, I'm lazy and don't want to handles hashes in C) def self.format_options(option_hash) # :nodoc: option_hash.to_a.collect do |opt| if opt[1].kind_of?(Array) if opt[1].first.kind_of?(Hash) [ opt[0].to_s, opt[1].map { |child| format_options(child) } ] else [ opt[0].to_s, opt[1].map { |child| child.to_s } ] end elsif opt[1].kind_of?(Hash) [ opt[0].to_s, format_options(opt[1]) ] else [ opt[0].to_s, opt[1].to_s ] end end end # Shortcut for # registry = Registry.new # registry.import(args) # # See Registry#import def self.import(*args) registry = Registry.new registry.import(*args) registry end def initialize(load_plugins = nil) if load_plugins || (load_plugins.nil? && Typelib.load_type_plugins?) Typelib.load_typelib_plugins end @export_typemap = Hash.new super() end # Returns the handler that will be used to import that file. It can # either be a string, in which case we use a Typelib internal importer, # or a Ruby object responding to 'call' in which case Registry#import # will use that object to do the importing. def self.handler_for(file, kind = 'auto') file = File.expand_path(file) if !kind || kind == 'auto' kind = Registry.guess_type(file) end if handler = TYPE_HANDLERS[kind] return handler end return kind end # Imports the +file+ into this registry. +kind+ is the file format or # nil, in which case the file format is guessed by extension (see # TYPE_BY_EXT) # # +options+ is an option hash. The Ruby bindings define the following # specific options: # merge:: # merges +file+ into this repository. If this is false, an exception # is raised if +file+ contains types already defined in +self+, even # if the definitions are the same. # # registry.import(my_path, 'auto', :merge => true) # # The Tlb importer has no options # # The C importer defines the following options: preprocessor: # # define:: # a list of VAR=VALUE or VAR options for cpp # registry.import(my_path, :define => ['PATH=/usr', 'NDEBUG']) # include:: # a list of path to add to cpp's search path # registry.import(my_path, :include => ['/usr', '/home/blabla/prefix/include']) # rawflags:: # flags to be passed as-is to cpp. For instance, the two previous # examples can be written # # registry.import(my_path, 'auto', # :rawflags => ['-I/usr', '-I/home/blabla/prefix/include', # -DPATH=/usr', -DNDEBUG]) # debug:: # if true, debugging information is outputted on stdout, and the # preprocessed output is kept. # # merge:: # load the file into its own registry, and merge the result back into # this one. If it is not set, types defined in +file+ that are already # defined in +self+ will generate an error, even if the two # definitions are the same. # def import(file, kind = 'auto', options = {}) file = File.expand_path(file) handler = Registry.handler_for(file, kind) if handler.respond_to?(:call) return handler.call(self, file, kind, options) else kind = handler end do_merge = if options.has_key?('merge') then options.delete('merge') elsif options.has_key?(:merge) then options.delete(:merge) else true end options = Registry.format_options(options) do_import(file, kind, do_merge, options) end # Resizes the given type to the given size, while updating the rest of # the registry to keep it consistent # # In practice, it means it modifies the compound field offsets and # sizes, and modifies the array sizes so that it matches the new sizes. # # +type+ must either be a type class or a type name, and to_size the new # size for it. # # See #resize to resize multiple types in one call. def resize_type(type, to_size) resize(type => to_size) end # Resize a set of types, while updating the rest of the registry to keep # it consistent # # In practice, it means it modifies the compound field offsets and # sizes, and modifies the array sizes so that it matches the new sizes. # # The given type map must be a mapping from a type name or type class to # the new size for that type. # # See #resize to resize multiple types in one call. def resize(typemap) new_sizes = typemap.map do |type, size| if type.respond_to?(:name) [type.name, size] else [type.to_str, size] end end do_resize(new_sizes) nil end # Exports the registry in the provided format, into a Ruby string. The # following formats are allowed as +format+: # # +tlb+:: Typelib's own XML format # +idl+:: CORBA IDL # # +options+ is an option hash, which is export-format specific. See the C++ # documentation of each exporter for more information. def export(kind, options = {}) options = Registry.format_options(options) do_export(kind, options) end # Export the registry into Typelib's own XML format def to_xml export('tlb') end # Helper class for Registry#create_compound class CompoundBuilder # The compound type name attr_reader :name # The registry on which we are creating the new compound attr_reader :registry # The compound fields, registered at each called of #method_missing # and #add. The new type is registered when #build is called. attr_reader :fields # The compound size, as specified on object creation. If zero, it is # automatically computed attr_reader :size def initialize(name, registry, size = 0) @name, @registry, @size = name, registry, size @fields = [] end # Create the type on the underlying registry def build if @fields.empty? raise ArgumentError, "trying to create an empty compound" end # Create the offsets, if they are not provided current_offset = 0 fields.each do |field_def| field_def[2] ||= current_offset current_offset = field_def[2] + field_def[1].size end registry.do_create_compound(name, fields, size) end # Adds a new field # # @param [String] name the field name # @param [Type,String] type the field's typelib type # @param [Integer,nil] offset the field offset. If nil, it is # automatically computed in #build so as to follow the previous # field. def add(name, type, offset = nil) if type.respond_to?(:to_str) || type.respond_to?(:to_sym) type = registry.build(type.to_s) end @fields << [name.to_s, type, offset] end # See {Registry#add} for the alternative to #add def method_missing(name, *args, &block) if name.to_s =~ /^(.*)=$/ type = args.first name = $1 add($1, type) else super end end end # Creates a new compound type with the given name on this registry # # @yield [CompoundBuilder] the compound building helper, see below for # examples. Only the #add method allows to set offsets. When no # offsets are given, they are computed from the previous field. # @return [Type] the type representation # # @example create a compound using #add # registry.create_compound "/new/Compound" do |c| # c.add "field0", "/int", 15 # c.add "field1", "/another/Compound", 20 # end # # @example create a compound using the c.field = type syntax # registry.create_compound "/new/Compound" do |c| # c.field0 = "/int" # c.field1 = "/another/Compound" # end # def create_compound(name, size = 0) recorder = CompoundBuilder.new(name, self, size) yield(recorder) recorder.build end # Creates a new container type on this registry # # @param [String] container_type the name of the container type # @param [String,Type] element_type the type of the container elements, # either as a type or as a type name # # @example create a new std::vector type # registry.create_container "/std/vector", "/my/Container" def create_container(container_type, element_type, size = 0) if element_type.respond_to?(:to_str) element_type = build(element_type) end return define_container(container_type.to_str, element_type, size) end # Creates a new array type on this registry # # @param [String,Type] base_type the type of the array elements, # either as a type or as a type name # @param [Integer] size the array size # # @example create a new array of 10 elements # registry.create_array "/my/Container", 10 def create_array(base_type, element_count, size = 0) if base_type.respond_to?(:name) base_type = base_type.name end return build("#{base_type}[#{element_count}]", size) end # Helper class to build new enumeration types class EnumBuilder # [String] The enum type name attr_reader :name # [Registry] The registry on which the enum should be defined attr_reader :registry # [Array<Array(String,Integer)>] the enumeration name-to-integer # mapping. Values are added with #add attr_reader :symbols # Size, in bytes. If zero, it is automatically computed attr_reader :size def initialize(name, registry, size) @name, @registry, @size = name, registry, size @symbols = [] end # Creates the new enum type on the registry def build if @symbols.empty? raise ArgumentError, "trying to create an empty enum" end # Create the values, if they are not provided current_value = 0 symbols.each do |sym_def| sym_def[1] ||= current_value current_value = sym_def[1] + 1 end registry.do_create_enum(name, symbols, size) end # Add a new symbol to this enum def add(name, value = nil) symbols << [name.to_s, (Integer(value) if value)] end # Alternative method to add new symbols. See {Registry#create_enum} # for examples. def method_missing(name, *args, &block) if name.to_s =~ /^(.*)=$/ value = args.first add($1, value) elsif args.empty? add(name.to_s) else super end end end # Creates a new enum type with the given name on this registry # # @yield [EnumBuilder] the enum building helper. In both methods, if a # symbol's value is not provided, it is computed as last_value + 1 # @return [Type] the type representation # # @example create an enum using #add # registry.create_enum "/new/Enum" do |c| # c.add "sym0", 15 # c.add "sym1", 2 # # sym2 will be 3 # c.add "sym2" # end # # @example create an enum using the c.sym = value syntax # registry.create_enum "/new/Enum" do |c| # c.sym0 = 15 # c.sym1 = 2 # # sym2 will be 3 # c.sym2 # end # def create_enum(name, size = 0) recorder = EnumBuilder.new(name, self, size) yield(recorder) recorder.build end # Add a type from a different registry to this one # # @param [Class<Typelib::Type>] the type to be added # @return [void] def add(type) merge(type.registry.minimal(type.name)) nil end end end
38.133838
246
0.524402
7a6d8abe33829eeb5a8480bcfbce2e96d67b9148
1,133
# frozen_string_literal: true require 'get_process_mem' module RssObserver # Class containing the Rails Middleware that class Middleware UnsupportedHandlerError = Class.new(RssObserver::Error) # @param app [Object] Rails middleware instance # @param handler [Object] Handler that accepts memory change updates def initialize(app, handler) @app = app unless handler.respond_to?(:initial_memory) raise UnsupportedHandlerError, 'Handler must respond to the #initial_memory(kilobytes) method' end unless handler.respond_to?(:final_memory) raise UnsupportedHandlerError, 'Handler must respond to the #final_memory(kilobytes) method' end @handler = handler end # @param env [Hash] Full application environment hash # @return [Array] Status code, hash of headers, response body def call(env) handler.initial_memory(current_memory) app.call(env).tap do handler.final_memory(current_memory) end end private attr_reader :app, :handler def current_memory RssObserver.current_memory end end end
26.97619
102
0.708738
5d8bcada2970f22e0fb0b5375debb02d4c45ef1f
2,371
# Copyright 2011-2019, The Trustees of Indiana University and Northwestern # University. 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. # --- END LICENSE_HEADER BLOCK --- require 'rails_helper' describe Permalink do describe '#permalink' do let(:master_file){ FactoryBot.build(:master_file) } context 'permalink does not exist' do it 'returns nil' do expect(master_file.permalink).to be_nil end it 'returns nil with query variables' do expect(master_file.permalink({a:'b'})).to be_nil end end context 'permalink exists' do let(:permalink_url){ "http://permalink.com/object/#{master_file.id}" } before do master_file.permalink = permalink_url end it 'returns a string' do expect(master_file.permalink).to be_kind_of(String) end it 'appends query variables to the url' do query_var_hash = { urlappend: '/embed' } expect(master_file.permalink_with_query(query_var_hash)).to eq("#{permalink_url}?#{query_var_hash.to_query}") end end context 'creating permalink' do let(:media_object) do mo = FactoryBot.build(:media_object) mo.save mo.reload end let(:master_file) { FactoryBot.create(:master_file, media_object: media_object) } it 'should get the absolute path to the object' do expect(Permalink.url_for(media_object)).to eq("http://test.host/media_objects/#{CGI::escape(media_object.id)}") expect(Permalink.url_for(master_file)).to eq("http://test.host/media_objects/#{CGI::escape(media_object.id)}/section/#{CGI::escape(master_file.id)}") end it 'permalink_for raises ArgumentError if not passed media_object or master_file' do expect{Permalink.permalink_for(Object.new)}.to raise_error(ArgumentError) end end end end
33.394366
157
0.694222
21ed70e9df5210c164596df90e4e32402ac5bd6d
2,156
$LOAD_PATH.unshift File.expand_path("../lib", __FILE__) require "vcr/version" Gem::Specification.new do |s| s.name = "vcr" s.homepage = "http://github.com/myronmarston/vcr" s.authors = ["Myron Marston"] s.summary = "Record your test suite's HTTP interactions and replay them during future test runs for fast, deterministic, accurate tests." s.description = "VCR provides a simple API to record and replay your test suite's HTTP interactions. It works with a variety of HTTP client libraries, HTTP stubbing libraries and testing frameworks." s.email = "[email protected]" s.require_path = "lib" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {spec,features}/*`.split("\n") s.version = VCR.version s.platform = Gem::Platform::RUBY s.required_ruby_version = '>= 1.8.7' s.required_rubygems_version = '>= 1.3.5' s.add_development_dependency 'bundler', '>= 1.0.7' s.add_development_dependency 'rake', '~> 0.9.2' s.add_development_dependency 'cucumber', '~> 1.1.4' s.add_development_dependency 'aruba', '~> 0.4.11' s.add_development_dependency 'rspec', '~> 2.11' s.add_development_dependency 'shoulda', '~> 2.9.2' s.add_development_dependency 'fakeweb', '~> 1.3.0' s.add_development_dependency 'webmock', '~> 1.9' s.add_development_dependency 'faraday', '~> 0.8' s.add_development_dependency 'httpclient', '~> 2.2' s.add_development_dependency 'excon', '>= 0.11.0', '< 1.0' s.add_development_dependency 'timecop', '~> 0.3.5' s.add_development_dependency 'rack', '~> 1.3.6' s.add_development_dependency 'sinatra', '~> 1.3.2' s.add_development_dependency 'multi_json', '~> 1.0.3' s.add_development_dependency 'json', '~> 1.6.5' s.add_development_dependency 'simplecov', '~> 0.5.3' s.add_development_dependency 'redis', '~> 2.2.2' unless RUBY_PLATFORM == 'java' s.add_development_dependency 'patron', '~> 0.4.15' s.add_development_dependency 'em-http-request', '~> 1.0.2' s.add_development_dependency 'curb', '~> 0.8.0' s.add_development_dependency 'typhoeus', '~> 0.5.3' s.add_development_dependency 'yajl-ruby', '~> 1.1.0' end end
41.461538
202
0.69295
e8114a4e519725c9b2046b3437a5c0a2f6309f7d
2,184
require 'test_helper' class BuildProxyTest < Test::Unit::TestCase context "with a class to build" do setup do @class = Class.new @instance = mock('built-instance') @association = mock('associated-instance') @class. stubs(:new). returns(@instance) @instance.stubs(:attribute).returns('value') Factory. stubs(:create). returns(@association) @instance.stubs(:attribute=) @instance.stubs(:owner=) end context "the build proxy" do setup do @proxy = Factory::Proxy::Build.new(@class) end before_should "instantiate the class" do @class.expects(:new).with().returns(@instance) end context "when asked to associate with another factory" do setup do @proxy.associate(:owner, :user, {}) end before_should "create the associated instance" do Factory.expects(:create).with(:user, {}).returns(@association) end before_should "set the associated instance" do @instance.expects(:owner=).with(@association) end end should "call Factory.create when building an association" do association = 'association' attribs = { :first_name => 'Billy' } Factory.expects(:create).with(:user, attribs).returns(association) assert_equal association, @proxy.association(:user, attribs) end should "return the built instance when asked for the result" do assert_equal @instance, @proxy.result end context "when setting an attribute" do setup do @proxy.set(:attribute, 'value') end before_should "set that value" do @instance.expects(:attribute=).with('value') end end context "when getting an attribute" do setup do @result = @proxy.get(:attribute) end before_should "ask the built class for the value" do @instance.expects(:attribute).with().returns('value') end should "return the value for that attribute" do assert_equal 'value', @result end end end end end
27.3
74
0.604853
33e0f1a966cd6a60f8da67aec3a8f817efb42a82
1,533
require 'spec_helper' RSpec.describe GeneSystem::Generators do describe '::TEMPLATE_MANIFEST' do let(:name) { 'my_dev_setup' } before do @manifest = Hashie::Mash.new( described_class::TEMPLATE_MANIFEST.call(name) ) end it 'has expected name' do expect(@manifest.name).to eq name end it 'has expected version' do expect(@manifest.version).to eq '0.0.1' end it 'has gene system metadata' do expect(@manifest.metadata.gene_system).not_to be nil end it 'renders app version into gene system metadata' do expect(@manifest.metadata.gene_system.version) .to eq GeneSystem::VERSION end it 'has default step' do expect(@manifest.steps.first).to eq described_class::DEFAULT_STEP end end describe '.render_empty_manifest' do let(:name) { 'new_dev_setup' } let(:path) { 'path/to/manifests' } let(:manifest_path) { File.join(path, name) } let(:manifest_file) { double } let(:manifest) { 'manifest' } before do allow(File).to receive(:open) .with(manifest_path, 'w') .and_yield(manifest_file) allow(manifest_file).to receive(:write) allow(described_class::TEMPLATE_MANIFEST) .to receive(:call).and_return(manifest) described_class.render_empty_manifest( name, path ) end it 'renders blank manifest' do expect(manifest_file) .to have_received(:write) .with("\"#{manifest}\"") end end end
23.227273
71
0.637312
21c5a45ca7cf09f37feeacd5227d716c4e3e893c
2,601
# Copyright © 2011-2020 MUSC Foundation for Research Development~ # All rights reserved.~ # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:~ # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.~ # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following~ # disclaimer in the documentation and/or other materials provided with the distribution.~ # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products~ # derived from this software without specific prior written permission.~ # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,~ # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT~ # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL~ # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS~ # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR~ # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.~ require 'rails_helper' RSpec.describe Dashboard::BaseController, type: :controller do let!(:logged_in_user) { create(:identity) } let!(:protocol) { create(:protocol_without_validations) } before :each do log_in_dashboard_identity(obj: logged_in_user) controller.instance_variable_set(:@protocol, protocol) end describe '#find_admin_for_protocol' do context 'user has empty protocol access' do before :each do create(:super_user, :access_empty_protocols, identity: logged_in_user) allow(protocol).to receive(:sub_service_requests).and_return(SubServiceRequest.none) end it 'should permit' do controller.send(:find_admin_for_protocol) expect(assigns(:admin)).to eq(true) end end context 'user does not have empty protocol access' do it 'should check admin rights' do expect(Protocol).to receive(:for_admin).with(logged_in_user.id).and_return([@protocol]) controller.send(:find_admin_for_protocol) end end end end
46.446429
146
0.761246
281bee581b4dc255b13865a4c854e53bfb9a0843
4,189
# require 'puppet' # require 'rspec' require 'rspec-puppet' require 'spec_helper' require 'puppetlabs_spec_helper/puppetlabs_spec/puppet_internals' # Ubintu, static describe 'l23network::examples::bond_lnx_old_style', :type => :class do let(:module_path) { '../' } #let(:title) { 'bond0' } let(:params) { { :bond => 'bond0', :ipaddr => '1.1.1.1/27', :interfaces => ['eth4','eth5'], :bond_mode => 2, :bond_miimon => 200, :bond_lacp_rate => 2, } } let(:facts) { { :osfamily => 'Debian', :operatingsystem => 'Ubuntu', :kernel => 'Linux' } } let(:interface_file_start) { '/etc/network/interfaces.d/ifcfg-' } it "Should contains interface_file" do should contain_file('/etc/network/interfaces').with_content(/\*/) end it 'Should contains interface_file with IP-addr' do rv = contain_file("#{interface_file_start}#{params[:bond]}") should rv.with_content(/auto\s+#{params[:bond]}/) should rv.with_content(/iface\s+#{params[:bond]}/) should rv.with_content(/address\s+1.1.1.1/) should rv.with_content(/netmask\s+255.255.255.224/) end it 'Should contains bond-specific parameters' do rv = contain_file("#{interface_file_start}#{params[:bond]}") should rv.with_content(/slaves\s+none/) should rv.with_content(/bond-mode\s+#{params[:bond_mode]}/) should rv.with_content(/bond-miimon\s+#{params[:bond_miimon]}/) should rv.with_content(/bond-lacp-rate\s+#{params[:bond_lacp_rate]}/) end it 'Should contains interface files for bond-slave interfaces' do params[:interfaces].each do |iface| rv = contain_file("#{interface_file_start}#{iface}") should rv.with_content(/auto\s+#{iface}/) should rv.with_content(/iface\s+#{iface}/) should rv.with_content(/bond-master\s+#{params[:bond]}/) end end end # Centos, static describe 'l23network::examples::bond_lnx_old_style', :type => :class do let(:module_path) { '../' } #let(:title) { 'bond0' } let(:params) { { :bond => 'bond0', :ipaddr => '1.1.1.1/27', :interfaces => ['eth4','eth5'], :bond_mode => 2, :bond_miimon => 200, :bond_lacp_rate => 0, } } let(:facts) { { :osfamily => 'RedHat', :operatingsystem => 'Centos', :kernel => 'Linux' } } let(:interface_file_start) { '/etc/sysconfig/network-scripts/ifcfg-' } let(:interface_up_file_start) { '/etc/sysconfig/network-scripts/interface-up-script-' } let(:bond_modes) { [ 'balance-rr', 'active-backup', 'balance-xor', 'broadcast', '802.3ad', 'balance-tlb', 'balance-alb' ] } it 'Should contains interface_file with IP-addr' do rv = contain_file("#{interface_file_start}#{params[:bond]}") should rv.with_content(/DEVICE=#{params[:bond]}/) should rv.with_content(/BOOTPROTO=none/) should rv.with_content(/ONBOOT=yes/) should rv.with_content(/IPADDR=1.1.1.1/) should rv.with_content(/NETMASK=255.255.255.224/) end it 'Should contains interface files for bond-slave interfaces' do params[:interfaces].each do |iface| rv = contain_file("#{interface_file_start}#{iface}") should rv.with_content(/DEVICE=#{iface}/) should rv.with_content(/BOOTPROTO=none/) should rv.with_content(/ONBOOT=yes/) should rv.with_content(/MASTER=#{params[:bond]}/) should rv.with_content(/SLAVE=yes/) end end it 'Should contains Bonding-opts line' do rv = contain_file("#{interface_file_start}#{params[:bond]}") should rv.with_content(/DEVICE=#{params[:bond]}/) should rv.with_content(/BONDING_OPTS="mode=/) end it 'Should contains Bond mode' do rv = contain_file("#{interface_file_start}#{params[:bond]}") should rv.with_content(/BONDING_OPTS.*mode=#{bond_modes[params[:bond_mode]]}/) end it 'Should contains miimon' do rv = contain_file("#{interface_file_start}#{params[:bond]}") should rv.with_content(/BONDING_OPTS.*miimon=#{params[:miimon]}/) end it 'Should contains lacp_rate' do rv = contain_file("#{interface_file_start}#{params[:bond]}") should rv.with_content(/BONDING_OPTS.*lacp_rate=#{params[:lacp_rate]}/) end end
32.984252
89
0.652184
39edf3caac5e10498ae2a0514b1dfd7c3861394a
1,368
# Copyright (c) 2015, Hothza # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module Fbox VERSION = "0.1.2" end
48.857143
80
0.782164
0141731529b496c355e803454ff7e0c57fffe11d
1,315
# frozen_string_literal: true require 'spec_helper' RSpec.describe WorkItems::Widgets::Hierarchy do let_it_be(:work_item) { create(:work_item) } describe '.type' do subject { described_class.type } it { is_expected.to eq(:hierarchy) } end describe '#type' do subject { described_class.new(work_item).type } it { is_expected.to eq(:hierarchy) } end describe '#parent' do let_it_be(:parent_link) { create(:parent_link) } subject { described_class.new(parent_link.work_item).parent } it { is_expected.to eq parent_link.work_item_parent } context 'when work_items_hierarchy flag is disabled' do before do stub_feature_flags(work_items_hierarchy: false) end it { is_expected.to be_nil } end end describe '#children' do let_it_be(:parent_link1) { create(:parent_link, work_item_parent: work_item) } let_it_be(:parent_link2) { create(:parent_link, work_item_parent: work_item) } subject { described_class.new(work_item).children } it { is_expected.to match_array([parent_link1.work_item, parent_link2.work_item]) } context 'when work_items_hierarchy flag is disabled' do before do stub_feature_flags(work_items_hierarchy: false) end it { is_expected.to be_empty } end end end
24.811321
87
0.706464
5d0dc82bdf654fb2991ca3765d5b2a0353b998b4
10,949
require 'active_support/core_ext/string/access' module ActiveMerchant module Billing class DataCashGateway < Gateway self.default_currency = 'GBP' self.supported_countries = ['GB'] self.supported_cardtypes = %i[visa master american_express discover diners_club jcb maestro] self.homepage_url = 'http://www.datacash.com/' self.display_name = 'DataCash' self.test_url = 'https://testserver.datacash.com/Transaction' self.live_url = 'https://mars.transaction.datacash.com/Transaction' AUTH_TYPE = 'auth' CANCEL_TYPE = 'cancel' FULFILL_TYPE = 'fulfill' PRE_TYPE = 'pre' REFUND_TYPE = 'refund' TRANSACTION_REFUND_TYPE = 'txn_refund' POLICY_ACCEPT = 'accept' POLICY_REJECT = 'reject' def initialize(options = {}) requires!(options, :login, :password) super end def purchase(money, authorization_or_credit_card, options = {}) requires!(options, :order_id) if authorization_or_credit_card.is_a?(String) request = build_purchase_or_authorization_request_with_continuous_authority_reference_request(AUTH_TYPE, money, authorization_or_credit_card, options) else request = build_purchase_or_authorization_request_with_credit_card_request(AUTH_TYPE, money, authorization_or_credit_card, options) end commit(request) end def authorize(money, authorization_or_credit_card, options = {}) requires!(options, :order_id) if authorization_or_credit_card.is_a?(String) request = build_purchase_or_authorization_request_with_continuous_authority_reference_request(AUTH_TYPE, money, authorization_or_credit_card, options) else request = build_purchase_or_authorization_request_with_credit_card_request(PRE_TYPE, money, authorization_or_credit_card, options) end commit(request) end def capture(money, authorization, options = {}) commit(build_void_or_capture_request(FULFILL_TYPE, money, authorization, options)) end def void(authorization, options = {}) request = build_void_or_capture_request(CANCEL_TYPE, nil, authorization, options) commit(request) end def credit(money, reference_or_credit_card, options = {}) if reference_or_credit_card.is_a?(String) ActiveMerchant.deprecated CREDIT_DEPRECATION_MESSAGE refund(money, reference_or_credit_card) else request = build_credit_request(money, reference_or_credit_card, options) commit(request) end end def refund(money, reference, options = {}) commit(build_transaction_refund_request(money, reference)) end def supports_scrubbing? true end def scrub(transcript) transcript. gsub(/(<pan>)\d+(<\/pan>)/i, '\1[FILTERED]\2'). gsub(/(<cv2>)\d+(<\/cv2>)/i, '\1[FILTERED]\2'). gsub(/(<password>).+(<\/password>)/i, '\1[FILTERED]\2') end private def build_void_or_capture_request(type, money, authorization, options) parsed_authorization = parse_authorization_string(authorization) xml = Builder::XmlMarkup.new indent: 2 xml.instruct! xml.tag! :Request, version: '2' do add_authentication(xml) xml.tag! :Transaction do xml.tag! :HistoricTxn do xml.tag! :reference, parsed_authorization[:reference] xml.tag! :authcode, parsed_authorization[:auth_code] xml.tag! :method, type end if money xml.tag! :TxnDetails do xml.tag! :merchantreference, format_reference_number(options[:order_id]) xml.tag! :amount, amount(money), currency: options[:currency] || currency(money) xml.tag! :capturemethod, 'ecomm' end end end end xml.target! end def build_purchase_or_authorization_request_with_credit_card_request(type, money, credit_card, options) xml = Builder::XmlMarkup.new indent: 2 xml.instruct! xml.tag! :Request, version: '2' do add_authentication(xml) xml.tag! :Transaction do xml.tag! :ContAuthTxn, type: 'setup' if options[:set_up_continuous_authority] xml.tag! :CardTxn do xml.tag! :method, type add_credit_card(xml, credit_card, options[:billing_address]) end xml.tag! :TxnDetails do xml.tag! :merchantreference, format_reference_number(options[:order_id]) xml.tag! :amount, amount(money), currency: options[:currency] || currency(money) xml.tag! :capturemethod, 'ecomm' end end end xml.target! end def build_purchase_or_authorization_request_with_continuous_authority_reference_request(type, money, authorization, options) parsed_authorization = parse_authorization_string(authorization) raise ArgumentError, 'The continuous authority reference is required for continuous authority transactions' if parsed_authorization[:ca_reference].blank? xml = Builder::XmlMarkup.new indent: 2 xml.instruct! xml.tag! :Request, version: '2' do add_authentication(xml) xml.tag! :Transaction do xml.tag! :ContAuthTxn, type: 'historic' xml.tag! :HistoricTxn do xml.tag! :reference, parsed_authorization[:ca_reference] xml.tag! :method, type end xml.tag! :TxnDetails do xml.tag! :merchantreference, format_reference_number(options[:order_id]) xml.tag! :amount, amount(money), currency: options[:currency] || currency(money) xml.tag! :capturemethod, 'cont_auth' end end end xml.target! end def build_transaction_refund_request(money, authorization) parsed_authorization = parse_authorization_string(authorization) xml = Builder::XmlMarkup.new indent: 2 xml.instruct! xml.tag! :Request, version: '2' do add_authentication(xml) xml.tag! :Transaction do xml.tag! :HistoricTxn do xml.tag! :reference, parsed_authorization[:reference] xml.tag! :method, TRANSACTION_REFUND_TYPE end unless money.nil? xml.tag! :TxnDetails do xml.tag! :amount, amount(money) xml.tag! :capturemethod, 'ecomm' end end end end xml.target! end def build_credit_request(money, credit_card, options) xml = Builder::XmlMarkup.new indent: 2 xml.instruct! xml.tag! :Request, version: '2' do add_authentication(xml) xml.tag! :Transaction do xml.tag! :CardTxn do xml.tag! :method, REFUND_TYPE add_credit_card(xml, credit_card, options[:billing_address]) end xml.tag! :TxnDetails do xml.tag! :merchantreference, format_reference_number(options[:order_id]) xml.tag! :amount, amount(money) xml.tag! :capturemethod, 'ecomm' end end end xml.target! end def add_authentication(xml) xml.tag! :Authentication do xml.tag! :client, @options[:login] xml.tag! :password, @options[:password] end end def add_credit_card(xml, credit_card, address) xml.tag! :Card do # DataCash calls the CC number 'pan' xml.tag! :pan, credit_card.number xml.tag! :expirydate, format_date(credit_card.month, credit_card.year) xml.tag! :Cv2Avs do xml.tag! :cv2, credit_card.verification_value if credit_card.verification_value? if address xml.tag! :street_address1, address[:address1] unless address[:address1].blank? xml.tag! :street_address2, address[:address2] unless address[:address2].blank? xml.tag! :street_address3, address[:address3] unless address[:address3].blank? xml.tag! :street_address4, address[:address4] unless address[:address4].blank? xml.tag! :postcode, address[:zip] unless address[:zip].blank? end # The ExtendedPolicy defines what to do when the passed data # matches, or not... # # All of the following elements MUST be present for the # xml to be valid (or can drop the ExtendedPolicy and use # a predefined one xml.tag! :ExtendedPolicy do xml.tag! :cv2_policy, notprovided: POLICY_REJECT, notchecked: POLICY_REJECT, matched: POLICY_ACCEPT, notmatched: POLICY_REJECT, partialmatch: POLICY_REJECT xml.tag! :postcode_policy, notprovided: POLICY_ACCEPT, notchecked: POLICY_ACCEPT, matched: POLICY_ACCEPT, notmatched: POLICY_REJECT, partialmatch: POLICY_ACCEPT xml.tag! :address_policy, notprovided: POLICY_ACCEPT, notchecked: POLICY_ACCEPT, matched: POLICY_ACCEPT, notmatched: POLICY_REJECT, partialmatch: POLICY_ACCEPT end end end end def commit(request) response = parse(ssl_post(test? ? self.test_url : self.live_url, request)) Response.new(response[:status] == '1', response[:reason], response, test: test?, authorization: "#{response[:datacash_reference]};#{response[:authcode]};#{response[:ca_reference]}" ) end def format_date(month, year) "#{format(month, :two_digits)}/#{format(year, :two_digits)}" end def parse(body) response = {} xml = REXML::Document.new(body) root = REXML::XPath.first(xml, '//Response') root.elements.to_a.each do |node| parse_element(response, node) end response end def parse_element(response, node) if node.has_elements? node.elements.each { |e| parse_element(response, e) } else response[node.name.underscore.to_sym] = node.text end end def format_reference_number(number) number.to_s.gsub(/[^A-Za-z0-9]/, '').rjust(6, '0').first(30) end def parse_authorization_string(authorization) reference, auth_code, ca_reference = authorization.to_s.split(';') {reference: reference, auth_code: auth_code, ca_reference: ca_reference} end end end end
36.016447
161
0.612476
e29f9667b7bc10b7e724134211812293d2404288
138
json.extract! material, :id, :nome, :valor, :tipo, :cor, :origem, :created_at, :updated_at json.url material_url(material, format: :json)
46
90
0.724638
21bf32fc1de6becbf3f71dd29d4e1c1ffede7722
160
require 'serverspec' set :backend, :exec %w{ zip unzip wget git openssl }.each do | pkg | describe package(pkg) do it { should be_installed } end end
16
48
0.68125
1c87c125ff0e66e6045a39205ea36eb36b23acf6
436
# coding: US-ASCII # frozen_string_literal: true Capybara::SpecHelper.spec '#save_screenshot' do let(:image_path) { File.join(Dir.tmpdir, 'capybara-screenshot.png') } before do @session.visit '/' end it 'should generate PNG file', requires: [:screenshot] do path = @session.save_screenshot image_path magic = File.read(image_path, 4) expect(magic).to eq "\x89PNG" expect(path).to eq image_path end end
22.947368
71
0.699541
1853f64bd02d73421eac967a7a20f414956e17ce
10,547
module Fog module Compute class VcloudDirector class Real # List operating systems available for use on virtual machines owned by # this organization. # # @return [Excon::Response] # * body<~Hash>: # # @see http://pubs.vmware.com/vcd-51/topic/com.vmware.vcloud.api.reference.doc_51/doc/operations/GET-SupportedSystemsInfo.html # @since vCloud API version 5.1 def get_supported_systems_info request( :expects => 200, :idempotent => true, :method => 'GET', :parser => Fog::ToHashDocument.new, :path => 'supportedSystemsInfo' ) end end class Mock def get_supported_systems_info body = # this is a subset of the full list {:xmlns=>xmlns, :xmlns_xsi=>xmlns_xsi, :type=>"application/vnd.vmware.vcloud.supportedSystemsInfo+xml", :href=>make_href('supportedSystemsInfo/'), :xsi_schemaLocation=>xsi_schema_location, :OperatingSystemFamilyInfo=> [{:Name=>"Microsoft Windows", :OperatingSystemFamilyId=>"1", :OperatingSystem=> [{:OperatingSystemId=>"85", :DefaultHardDiskAdapterType=>"4", :MinimumHardDiskSizeGigabytes=>"40", :MinimumMemoryMegabytes=>"512", :Name=>"Microsoft Windows Server 2012 (64-bit)", :InternalName=>"windows8Server64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"8", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"true", :SupportsMemHotAdd=>"true", :cimOsId=>"74", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"3", :DefaultHardDiskAdapterType=>"4", :MinimumHardDiskSizeGigabytes=>"40", :MinimumMemoryMegabytes=>"512", :Name=>"Microsoft Windows Server 2008 R2 (64-bit)", :InternalName=>"windows7Server64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"true", :SupportsMemHotAdd=>"true", :cimOsId=>"102", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"4", :DefaultHardDiskAdapterType=>"4", :MinimumHardDiskSizeGigabytes=>"40", :MinimumMemoryMegabytes=>"512", :Name=>"Microsoft Windows Server 2008 (32-bit)", :InternalName=>"winLonghornGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"true", :SupportsMemHotAdd=>"true", :cimOsId=>"73", :CimVersion=>"0", :SupportedForCreate=>"true"}]}, {:Name=>"Linux", :OperatingSystemFamilyId=>"2", :OperatingSystem=> [{:OperatingSystemId=>"48", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"64", :Name=>"Ubuntu Linux (64-bit)", :InternalName=>"ubuntu64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"94", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"47", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"64", :Name=>"Ubuntu Linux (32-bit)", :InternalName=>"ubuntuGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"93", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"50", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other 2.6.x Linux (64-bit)", :InternalName=>"other26xLinux64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"7", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"100", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"49", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other 2.6.x Linux (32-bit)", :InternalName=>"other26xLinuxGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"7", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"99", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"54", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other Linux (64-bit)", :InternalName=>"otherLinux64Guest", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"false", :cimOsId=>"101", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"53", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other Linux (32-bit)", :InternalName=>"otherLinuxGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"true", :PersonalizationAuto=>"true", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"false", :cimOsId=>"36", :CimVersion=>"0", :SupportedForCreate=>"true"}]}, {:Name=>"Other", :OperatingSystemFamilyId=>"3", :OperatingSystem=> [{:OperatingSystemId=>"68", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other (64-bit)", :InternalName=>"otherGuest64", :Supported=>"true", :x64=>"true", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"false", :PersonalizationAuto=>"false", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"102", :CimVersion=>"0", :SupportedForCreate=>"true"}, {:OperatingSystemId=>"67", :DefaultHardDiskAdapterType=>"3", :MinimumHardDiskSizeGigabytes=>"8", :MinimumMemoryMegabytes=>"32", :Name=>"Other (32-bit)", :InternalName=>"otherGuest", :Supported=>"true", :x64=>"false", :MaximumCpuCount=>"64", :MinimumHardwareVersion=>"4", :PersonalizationEnabled=>"false", :PersonalizationAuto=>"false", :SysprepPackagingSupported=>"false", :SupportsMemHotAdd=>"true", :cimOsId=>"1", :CimVersion=>"0", :SupportedForCreate=>"true"}]}]} Excon::Response.new( :status => 200, :headers => {'Content-Type' => "#{body[:type]};version=#{api_version}"}, :body => body ) end end end end end
43.945833
134
0.453494
38933a98b8288a19b692295a0d59c639fc4f8c8e
2,030
require 'fileutils' module BuildPack class Installer class << self def install(build_dir, cache_dir) init_paths(build_dir, cache_dir) make_dirs Downloader.download_latest_lib_to(@lib_mysql_pkg) unless cached? Downloader.download_latest_client_to(@mysql_pkg) unless cached? if client_exists? install_client and cleanup else fail_install end end private def init_paths(build_dir, cache_dir) @bin_path = "#{build_dir}/bin" @tmp_path = "#{build_dir}/tmp" @mysql_path = "#{@tmp_path}/mysql" @mysql_binaries = "#{@mysql_path}/usr/bin" @mysql_pkg = "#{cache_dir}/mysql.deb" @lib_mysql_pkg = "#{cache_dir}/lib_mysql.deb" end def make_dirs FileUtils.mkdir_p(@bin_path) FileUtils.mkdir_p(@tmp_path) end def cached? if exists = client_exists? Logger.log_header("Using MySQL Client package from cache") end exists end def client_exists? File.exist?(@mysql_pkg) end def install_client run_command_with_message(command: "dpkg -x #{@lib_mysql_pkg} #{@mysql_path}", message: "Installing MySQL Lib") run_command_with_message(command: "dpkg -x #{@mysql_pkg} #{@mysql_path}", message: "Installing MySQL Client") fix_perms_and_mv_binaries end def run_command_with_message(command:, message:) Logger.log_header("#{message}") Logger.log("#{command}") output = `#{command}` puts output end def fix_perms_and_mv_binaries binaries = Dir.glob("#{@mysql_binaries}/*") FileUtils.mv(binaries, @bin_path) end def cleanup Logger.log_header("Cleaning up") FileUtils.remove_dir(@mysql_path) end def fail_install Logger.log_header("Failing mysql client installation as no suitable clients were found") exit 1 end end end end
25.696203
118
0.618719
f74aab72991a336c40be55f538e465698c2c864d
93,760
# Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'date' require 'google/apis/core/base_service' require 'google/apis/core/json_representation' require 'google/apis/core/hashable' require 'google/apis/errors' module Google module Apis module GameservicesV1 # Specifies the audit configuration for a service. The configuration determines # which permission types are logged, and what identities, if any, are exempted # from logging. An AuditConfig must have one or more AuditLogConfigs. If there # are AuditConfigs for both `allServices` and a specific service, the union of # the two AuditConfigs is used for that service: the log_types specified in each # AuditConfig are enabled, and the exempted_members in each AuditLogConfig are # exempted. Example Policy with multiple AuditConfigs: ` "audit_configs": [ ` " # service": "allServices", "audit_log_configs": [ ` "log_type": "DATA_READ", " # exempted_members": [ "user:[email protected]" ] `, ` "log_type": "DATA_WRITE" `, # ` "log_type": "ADMIN_READ" ` ] `, ` "service": "sampleservice.googleapis.com", # "audit_log_configs": [ ` "log_type": "DATA_READ" `, ` "log_type": "DATA_WRITE" # , "exempted_members": [ "user:[email protected]" ] ` ] ` ] ` For sampleservice, # this policy enables DATA_READ, DATA_WRITE and ADMIN_READ logging. It also # exempts [email protected] from DATA_READ logging, and [email protected] from # DATA_WRITE logging. class AuditConfig include Google::Apis::Core::Hashable # The configuration for logging of each type of permission. # Corresponds to the JSON property `auditLogConfigs` # @return [Array<Google::Apis::GameservicesV1::AuditLogConfig>] attr_accessor :audit_log_configs # # Corresponds to the JSON property `exemptedMembers` # @return [Array<String>] attr_accessor :exempted_members # Specifies a service that will be enabled for audit logging. For example, ` # storage.googleapis.com`, `cloudsql.googleapis.com`. `allServices` is a special # value that covers all services. # Corresponds to the JSON property `service` # @return [String] attr_accessor :service def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @audit_log_configs = args[:audit_log_configs] if args.key?(:audit_log_configs) @exempted_members = args[:exempted_members] if args.key?(:exempted_members) @service = args[:service] if args.key?(:service) end end # Provides the configuration for logging a type of permissions. Example: ` " # audit_log_configs": [ ` "log_type": "DATA_READ", "exempted_members": [ "user: # [email protected]" ] `, ` "log_type": "DATA_WRITE" ` ] ` This enables ' # DATA_READ' and 'DATA_WRITE' logging, while exempting [email protected] from # DATA_READ logging. class AuditLogConfig include Google::Apis::Core::Hashable # Specifies the identities that do not cause logging for this type of permission. # Follows the same format of Binding.members. # Corresponds to the JSON property `exemptedMembers` # @return [Array<String>] attr_accessor :exempted_members # # Corresponds to the JSON property `ignoreChildExemptions` # @return [Boolean] attr_accessor :ignore_child_exemptions alias_method :ignore_child_exemptions?, :ignore_child_exemptions # The log type that this config enables. # Corresponds to the JSON property `logType` # @return [String] attr_accessor :log_type def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @exempted_members = args[:exempted_members] if args.key?(:exempted_members) @ignore_child_exemptions = args[:ignore_child_exemptions] if args.key?(:ignore_child_exemptions) @log_type = args[:log_type] if args.key?(:log_type) end end # Authorization-related information used by Cloud Audit Logging. class AuthorizationLoggingOptions include Google::Apis::Core::Hashable # The type of the permission that was checked. # Corresponds to the JSON property `permissionType` # @return [String] attr_accessor :permission_type def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @permission_type = args[:permission_type] if args.key?(:permission_type) end end # Associates `members` with a `role`. class Binding include Google::Apis::Core::Hashable # # Corresponds to the JSON property `bindingId` # @return [String] attr_accessor :binding_id # Represents a textual expression in the Common Expression Language (CEL) syntax. # CEL is a C-like expression language. The syntax and semantics of CEL are # documented at https://github.com/google/cel-spec. Example (Comparison): title: # "Summary size limit" description: "Determines if a summary is less than 100 # chars" expression: "document.summary.size() < 100" Example (Equality): title: " # Requestor is owner" description: "Determines if requestor is the document # owner" expression: "document.owner == request.auth.claims.email" Example ( # Logic): title: "Public documents" description: "Determine whether the document # should be publicly visible" expression: "document.type != 'private' && # document.type != 'internal'" Example (Data Manipulation): title: "Notification # string" description: "Create a notification string with a timestamp." # expression: "'New message received at ' + string(document.create_time)" The # exact variables and functions that may be referenced within an expression are # determined by the service that evaluates it. See the service documentation for # additional information. # Corresponds to the JSON property `condition` # @return [Google::Apis::GameservicesV1::Expr] 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, `my-other-app@appspot. # gserviceaccount.com`. * `group:`emailid``: An email address that represents a # Google group. For example, `[email protected]`. * `deleted:user:`emailid`?uid= # `uniqueid``: An email address (plus unique identifier) representing a user # that has been recently deleted. For example, `[email protected]?uid= # 123456789012345678901`. If the user is recovered, this value reverts to `user:` # emailid`` and the recovered user retains the role in the binding. * `deleted: # serviceAccount:`emailid`?uid=`uniqueid``: An email address (plus unique # identifier) representing a service account that has been recently deleted. For # example, `[email protected]?uid=123456789012345678901`. # If the service account is undeleted, this value reverts to `serviceAccount:` # emailid`` and the undeleted service account retains the role in the binding. * # `deleted:group:`emailid`?uid=`uniqueid``: An email address (plus unique # identifier) representing a Google group that has been recently deleted. For # example, `[email protected]?uid=123456789012345678901`. If the group is # recovered, this value reverts to `group:`emailid`` and the recovered group # retains the role in the binding. * `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) @binding_id = args[:binding_id] if args.key?(:binding_id) @condition = args[:condition] if args.key?(:condition) @members = args[:members] if args.key?(:members) @role = args[:role] if args.key?(:role) end end # The request message for Operations.CancelOperation. class CancelOperationRequest include Google::Apis::Core::Hashable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) end end # Write a Cloud Audit log class CloudAuditOptions include Google::Apis::Core::Hashable # Authorization-related information used by Cloud Audit Logging. # Corresponds to the JSON property `authorizationLoggingOptions` # @return [Google::Apis::GameservicesV1::AuthorizationLoggingOptions] attr_accessor :authorization_logging_options # The log_name to populate in the Cloud Audit Record. # Corresponds to the JSON property `logName` # @return [String] attr_accessor :log_name def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @authorization_logging_options = args[:authorization_logging_options] if args.key?(:authorization_logging_options) @log_name = args[:log_name] if args.key?(:log_name) end end # A condition to be met. class Condition include Google::Apis::Core::Hashable # Trusted attributes supplied by the IAM system. # Corresponds to the JSON property `iam` # @return [String] attr_accessor :iam # An operator to apply the subject with. # Corresponds to the JSON property `op` # @return [String] attr_accessor :op # Trusted attributes discharged by the service. # Corresponds to the JSON property `svc` # @return [String] attr_accessor :svc # Trusted attributes supplied by any service that owns resources and uses the # IAM system for access control. # Corresponds to the JSON property `sys` # @return [String] attr_accessor :sys # The objects of the condition. # Corresponds to the JSON property `values` # @return [Array<String>] attr_accessor :values def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @iam = args[:iam] if args.key?(:iam) @op = args[:op] if args.key?(:op) @svc = args[:svc] if args.key?(:svc) @sys = args[:sys] if args.key?(:sys) @values = args[:values] if args.key?(:values) end end # Increment a streamz counter with the specified metric and field names. Metric # names should start with a '/', generally be lowercase-only, and end in "_count" # . Field names should not contain an initial slash. The actual exported metric # names will have "/iam/policy" prepended. Field names correspond to IAM request # parameters and field values are their respective values. Supported field names: # - "authority", which is "[token]" if IAMContext.token is present, otherwise # the value of IAMContext.authority_selector if present, and otherwise a # representation of IAMContext.principal; or - "iam_principal", a representation # of IAMContext.principal even if a token or authority selector is present; or - # "" (empty string), resulting in a counter with no fields. Examples: counter ` # metric: "/debug_access_count" field: "iam_principal" ` ==> increment counter / # iam/policy/debug_access_count `iam_principal=[value of IAMContext.principal]` class CounterOptions include Google::Apis::Core::Hashable # Custom fields. # Corresponds to the JSON property `customFields` # @return [Array<Google::Apis::GameservicesV1::CustomField>] attr_accessor :custom_fields # The field value to attribute. # Corresponds to the JSON property `field` # @return [String] attr_accessor :field # The metric to update. # Corresponds to the JSON property `metric` # @return [String] attr_accessor :metric def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @custom_fields = args[:custom_fields] if args.key?(:custom_fields) @field = args[:field] if args.key?(:field) @metric = args[:metric] if args.key?(:metric) end end # Custom fields. These can be used to create a counter with arbitrary field/ # value pairs. See: go/rpcsp-custom-fields. class CustomField include Google::Apis::Core::Hashable # Name is the field name. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # Value is the field value. It is important that in contrast to the # CounterOptions.field, the value here is a constant that is not derived from # the IAMContext. # Corresponds to the JSON property `value` # @return [String] attr_accessor :value def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @name = args[:name] if args.key?(:name) @value = args[:value] if args.key?(:value) end end # Write a Data Access (Gin) log class DataAccessOptions include Google::Apis::Core::Hashable # # Corresponds to the JSON property `logMode` # @return [String] attr_accessor :log_mode def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @log_mode = args[:log_mode] if args.key?(:log_mode) end end # The game server cluster changes made by the game server deployment. class DeployedClusterState include Google::Apis::Core::Hashable # The name of the cluster. # Corresponds to the JSON property `cluster` # @return [String] attr_accessor :cluster # The details about the Agones fleets and autoscalers created in the game server # cluster. # Corresponds to the JSON property `fleetDetails` # @return [Array<Google::Apis::GameservicesV1::DeployedFleetDetails>] attr_accessor :fleet_details def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @cluster = args[:cluster] if args.key?(:cluster) @fleet_details = args[:fleet_details] if args.key?(:fleet_details) end end # Agones fleet specification and details. class DeployedFleet include Google::Apis::Core::Hashable # The name of the Agones fleet. # Corresponds to the JSON property `fleet` # @return [String] attr_accessor :fleet # The fleet spec retrieved from the Agones fleet. # Corresponds to the JSON property `fleetSpec` # @return [String] attr_accessor :fleet_spec # Encapsulates Agones fleet spec and Agones autoscaler spec sources. # Corresponds to the JSON property `specSource` # @return [Google::Apis::GameservicesV1::SpecSource] attr_accessor :spec_source # DeployedFleetStatus has details about the Agones fleets such as how many are # running, how many allocated, and so on. # Corresponds to the JSON property `status` # @return [Google::Apis::GameservicesV1::DeployedFleetStatus] attr_accessor :status def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @fleet = args[:fleet] if args.key?(:fleet) @fleet_spec = args[:fleet_spec] if args.key?(:fleet_spec) @spec_source = args[:spec_source] if args.key?(:spec_source) @status = args[:status] if args.key?(:status) end end # Details about the Agones autoscaler. class DeployedFleetAutoscaler include Google::Apis::Core::Hashable # The name of the Agones autoscaler. # Corresponds to the JSON property `autoscaler` # @return [String] attr_accessor :autoscaler # The autoscaler spec retrieved from Agones. # Corresponds to the JSON property `fleetAutoscalerSpec` # @return [String] attr_accessor :fleet_autoscaler_spec # Encapsulates Agones fleet spec and Agones autoscaler spec sources. # Corresponds to the JSON property `specSource` # @return [Google::Apis::GameservicesV1::SpecSource] attr_accessor :spec_source def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @autoscaler = args[:autoscaler] if args.key?(:autoscaler) @fleet_autoscaler_spec = args[:fleet_autoscaler_spec] if args.key?(:fleet_autoscaler_spec) @spec_source = args[:spec_source] if args.key?(:spec_source) end end # Details of the deployed Agones fleet. class DeployedFleetDetails include Google::Apis::Core::Hashable # Details about the Agones autoscaler. # Corresponds to the JSON property `deployedAutoscaler` # @return [Google::Apis::GameservicesV1::DeployedFleetAutoscaler] attr_accessor :deployed_autoscaler # Agones fleet specification and details. # Corresponds to the JSON property `deployedFleet` # @return [Google::Apis::GameservicesV1::DeployedFleet] attr_accessor :deployed_fleet def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @deployed_autoscaler = args[:deployed_autoscaler] if args.key?(:deployed_autoscaler) @deployed_fleet = args[:deployed_fleet] if args.key?(:deployed_fleet) end end # DeployedFleetStatus has details about the Agones fleets such as how many are # running, how many allocated, and so on. class DeployedFleetStatus include Google::Apis::Core::Hashable # The number of GameServer replicas in the ALLOCATED state in this fleet. # Corresponds to the JSON property `allocatedReplicas` # @return [Fixnum] attr_accessor :allocated_replicas # The number of GameServer replicas in the READY state in this fleet. # Corresponds to the JSON property `readyReplicas` # @return [Fixnum] attr_accessor :ready_replicas # The total number of current GameServer replicas in this fleet. # Corresponds to the JSON property `replicas` # @return [Fixnum] attr_accessor :replicas # The number of GameServer replicas in the RESERVED state in this fleet. # Reserved instances won't be deleted on scale down, but won't cause an # autoscaler to scale up. # Corresponds to the JSON property `reservedReplicas` # @return [Fixnum] attr_accessor :reserved_replicas def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @allocated_replicas = args[:allocated_replicas] if args.key?(:allocated_replicas) @ready_replicas = args[:ready_replicas] if args.key?(:ready_replicas) @replicas = args[:replicas] if args.key?(:replicas) @reserved_replicas = args[:reserved_replicas] if args.key?(:reserved_replicas) end end # A generic empty message that you can re-use to avoid defining duplicated empty # messages in your APIs. A typical example is to use it as the request or the # response type of an API method. For instance: service Foo ` rpc Bar(google. # protobuf.Empty) returns (google.protobuf.Empty); ` The JSON representation for # `Empty` is empty JSON object ````. class Empty include Google::Apis::Core::Hashable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) end end # Represents a textual expression in the Common Expression Language (CEL) syntax. # CEL is a C-like expression language. The syntax and semantics of CEL are # documented at https://github.com/google/cel-spec. Example (Comparison): title: # "Summary size limit" description: "Determines if a summary is less than 100 # chars" expression: "document.summary.size() < 100" Example (Equality): title: " # Requestor is owner" description: "Determines if requestor is the document # owner" expression: "document.owner == request.auth.claims.email" Example ( # Logic): title: "Public documents" description: "Determine whether the document # should be publicly visible" expression: "document.type != 'private' && # document.type != 'internal'" Example (Data Manipulation): title: "Notification # string" description: "Create a notification string with a timestamp." # expression: "'New message received at ' + string(document.create_time)" The # exact variables and functions that may be referenced within an expression are # determined by the service that evaluates it. See the service documentation for # additional information. class Expr include Google::Apis::Core::Hashable # 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. # Corresponds to the JSON property `expression` # @return [String] attr_accessor :expression # 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 # 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 # Request message for GameServerDeploymentsService.FetchDeploymentState. class FetchDeploymentStateRequest include Google::Apis::Core::Hashable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) end end # Response message for GameServerDeploymentsService.FetchDeploymentState. class FetchDeploymentStateResponse include Google::Apis::Core::Hashable # The state of the game server deployment in each game server cluster. # Corresponds to the JSON property `clusterState` # @return [Array<Google::Apis::GameservicesV1::DeployedClusterState>] attr_accessor :cluster_state # List of locations that could not be reached. # Corresponds to the JSON property `unavailable` # @return [Array<String>] attr_accessor :unavailable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @cluster_state = args[:cluster_state] if args.key?(:cluster_state) @unavailable = args[:unavailable] if args.key?(:unavailable) end end # Fleet configs for Agones. class FleetConfig include Google::Apis::Core::Hashable # Agones fleet spec. Example spec: `https://agones.dev/site/docs/reference/fleet/ # `. # Corresponds to the JSON property `fleetSpec` # @return [String] attr_accessor :fleet_spec # The name of the FleetConfig. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @fleet_spec = args[:fleet_spec] if args.key?(:fleet_spec) @name = args[:name] if args.key?(:name) end end # A game server cluster resource. class GameServerCluster include Google::Apis::Core::Hashable # The state of the Kubernetes cluster. # Corresponds to the JSON property `clusterState` # @return [Google::Apis::GameservicesV1::KubernetesClusterState] attr_accessor :cluster_state # The game server cluster connection information. # Corresponds to the JSON property `connectionInfo` # @return [Google::Apis::GameservicesV1::GameServerClusterConnectionInfo] attr_accessor :connection_info # Output only. The creation time. # Corresponds to the JSON property `createTime` # @return [String] attr_accessor :create_time # Human readable description of the cluster. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # ETag of the resource. # Corresponds to the JSON property `etag` # @return [String] attr_accessor :etag # The labels associated with this game server cluster. Each label is a key-value # pair. # Corresponds to the JSON property `labels` # @return [Hash<String,String>] attr_accessor :labels # Required. The resource name of the game server cluster, in the following form: # `projects/`project`/locations/`location`/realms/`realm`/gameServerClusters/` # cluster``. For example, `projects/my-project/locations/`location`/realms/ # zanzibar/gameServerClusters/my-onprem-cluster`. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # Output only. The last-modified time. # Corresponds to the JSON property `updateTime` # @return [String] attr_accessor :update_time def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @cluster_state = args[:cluster_state] if args.key?(:cluster_state) @connection_info = args[:connection_info] if args.key?(:connection_info) @create_time = args[:create_time] if args.key?(:create_time) @description = args[:description] if args.key?(:description) @etag = args[:etag] if args.key?(:etag) @labels = args[:labels] if args.key?(:labels) @name = args[:name] if args.key?(:name) @update_time = args[:update_time] if args.key?(:update_time) end end # The game server cluster connection information. class GameServerClusterConnectionInfo include Google::Apis::Core::Hashable # A reference to a GKE cluster. # Corresponds to the JSON property `gkeClusterReference` # @return [Google::Apis::GameservicesV1::GkeClusterReference] attr_accessor :gke_cluster_reference # Namespace designated on the game server cluster where the Agones game server # instances will be created. Existence of the namespace will be validated during # creation. # Corresponds to the JSON property `namespace` # @return [String] attr_accessor :namespace def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @gke_cluster_reference = args[:gke_cluster_reference] if args.key?(:gke_cluster_reference) @namespace = args[:namespace] if args.key?(:namespace) end end # A game server config resource. class GameServerConfig include Google::Apis::Core::Hashable # Output only. The creation time. # Corresponds to the JSON property `createTime` # @return [String] attr_accessor :create_time # The description of the game server config. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # FleetConfig contains a list of Agones fleet specs. Only one FleetConfig is # allowed. # Corresponds to the JSON property `fleetConfigs` # @return [Array<Google::Apis::GameservicesV1::FleetConfig>] attr_accessor :fleet_configs # The labels associated with this game server config. Each label is a key-value # pair. # Corresponds to the JSON property `labels` # @return [Hash<String,String>] attr_accessor :labels # The resource name of the game server config, in the following form: `projects/` # project`/locations/`location`/gameServerDeployments/`deployment`/configs/` # config``. For example, `projects/my-project/locations/global/ # gameServerDeployments/my-game/configs/my-config`. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # The autoscaling settings. # Corresponds to the JSON property `scalingConfigs` # @return [Array<Google::Apis::GameservicesV1::ScalingConfig>] attr_accessor :scaling_configs # Output only. The last-modified time. # Corresponds to the JSON property `updateTime` # @return [String] attr_accessor :update_time def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @create_time = args[:create_time] if args.key?(:create_time) @description = args[:description] if args.key?(:description) @fleet_configs = args[:fleet_configs] if args.key?(:fleet_configs) @labels = args[:labels] if args.key?(:labels) @name = args[:name] if args.key?(:name) @scaling_configs = args[:scaling_configs] if args.key?(:scaling_configs) @update_time = args[:update_time] if args.key?(:update_time) end end # A game server config override. class GameServerConfigOverride include Google::Apis::Core::Hashable # The game server config for this override. # Corresponds to the JSON property `configVersion` # @return [String] attr_accessor :config_version # The realm selector, used to match realm resources. # Corresponds to the JSON property `realmsSelector` # @return [Google::Apis::GameservicesV1::RealmSelector] attr_accessor :realms_selector def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @config_version = args[:config_version] if args.key?(:config_version) @realms_selector = args[:realms_selector] if args.key?(:realms_selector) end end # A game server deployment resource. class GameServerDeployment include Google::Apis::Core::Hashable # Output only. The creation time. # Corresponds to the JSON property `createTime` # @return [String] attr_accessor :create_time # Human readable description of the game server delpoyment. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # ETag of the resource. # Corresponds to the JSON property `etag` # @return [String] attr_accessor :etag # The labels associated with this game server deployment. Each label is a key- # value pair. # Corresponds to the JSON property `labels` # @return [Hash<String,String>] attr_accessor :labels # The resource name of the game server deployment, in the following form: ` # projects/`project`/locations/`location`/gameServerDeployments/`deployment``. # For example, `projects/my-project/locations/global/gameServerDeployments/my- # deployment`. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # Output only. The last-modified time. # Corresponds to the JSON property `updateTime` # @return [String] attr_accessor :update_time def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @create_time = args[:create_time] if args.key?(:create_time) @description = args[:description] if args.key?(:description) @etag = args[:etag] if args.key?(:etag) @labels = args[:labels] if args.key?(:labels) @name = args[:name] if args.key?(:name) @update_time = args[:update_time] if args.key?(:update_time) end end # The game server deployment rollout which represents the desired rollout state. class GameServerDeploymentRollout include Google::Apis::Core::Hashable # Output only. The creation time. # Corresponds to the JSON property `createTime` # @return [String] attr_accessor :create_time # The default game server config is applied to all realms unless overridden in # the rollout. For example, `projects/my-project/locations/global/ # gameServerDeployments/my-game/configs/my-config`. # Corresponds to the JSON property `defaultGameServerConfig` # @return [String] attr_accessor :default_game_server_config # ETag of the resource. # Corresponds to the JSON property `etag` # @return [String] attr_accessor :etag # Contains the game server config rollout overrides. Overrides are processed in # the order they are listed. Once a match is found for a realm, the rest of the # list is not processed. # Corresponds to the JSON property `gameServerConfigOverrides` # @return [Array<Google::Apis::GameservicesV1::GameServerConfigOverride>] attr_accessor :game_server_config_overrides # The resource name of the game server deployment rollout, in the following form: # `projects/`project`/locations/`location`/gameServerDeployments/`deployment`/ # rollout`. For example, `projects/my-project/locations/global/ # gameServerDeployments/my-deployment/rollout`. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # Output only. The last-modified time. # Corresponds to the JSON property `updateTime` # @return [String] attr_accessor :update_time def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @create_time = args[:create_time] if args.key?(:create_time) @default_game_server_config = args[:default_game_server_config] if args.key?(:default_game_server_config) @etag = args[:etag] if args.key?(:etag) @game_server_config_overrides = args[:game_server_config_overrides] if args.key?(:game_server_config_overrides) @name = args[:name] if args.key?(:name) @update_time = args[:update_time] if args.key?(:update_time) end end # A reference to a GKE cluster. class GkeClusterReference include Google::Apis::Core::Hashable # The full or partial name of a GKE cluster, using one of the following forms: * # `projects/`project`/locations/`location`/clusters/`cluster`` * `locations/` # location`/clusters/`cluster`` * ``cluster`` If project and location are not # specified, the project and location of the GameServerCluster resource are used # to generate the full name of the GKE cluster. # Corresponds to the JSON property `cluster` # @return [String] attr_accessor :cluster def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @cluster = args[:cluster] if args.key?(:cluster) end end # The state of the Kubernetes cluster. class KubernetesClusterState include Google::Apis::Core::Hashable # Output only. The version of Agones currently installed in the registered # Kubernetes cluster. # Corresponds to the JSON property `agonesVersionInstalled` # @return [String] attr_accessor :agones_version_installed # Output only. The version of Agones that is targeted to be installed in the # cluster. # Corresponds to the JSON property `agonesVersionTargeted` # @return [String] attr_accessor :agones_version_targeted # Output only. The state for the installed versions of Agones/Kubernetes. # Corresponds to the JSON property `installationState` # @return [String] attr_accessor :installation_state # Output only. The version of Kubernetes that is currently used in the # registered Kubernetes cluster (as detected by the Cloud Game Servers service). # Corresponds to the JSON property `kubernetesVersionInstalled` # @return [String] attr_accessor :kubernetes_version_installed # Output only. The cloud provider type reported by the first node's providerID # in the list of nodes on the Kubernetes endpoint. On Kubernetes platforms that # support zero-node clusters (like GKE-on-GCP), the provider type will be empty. # Corresponds to the JSON property `provider` # @return [String] attr_accessor :provider # Output only. The detailed error message for the installed versions of Agones/ # Kubernetes. # Corresponds to the JSON property `versionInstalledErrorMessage` # @return [String] attr_accessor :version_installed_error_message def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @agones_version_installed = args[:agones_version_installed] if args.key?(:agones_version_installed) @agones_version_targeted = args[:agones_version_targeted] if args.key?(:agones_version_targeted) @installation_state = args[:installation_state] if args.key?(:installation_state) @kubernetes_version_installed = args[:kubernetes_version_installed] if args.key?(:kubernetes_version_installed) @provider = args[:provider] if args.key?(:provider) @version_installed_error_message = args[:version_installed_error_message] if args.key?(:version_installed_error_message) end end # The label selector, used to group labels on the resources. class LabelSelector include Google::Apis::Core::Hashable # Resource labels for this selector. # Corresponds to the JSON property `labels` # @return [Hash<String,String>] attr_accessor :labels def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @labels = args[:labels] if args.key?(:labels) end end # Response message for GameServerClustersService.ListGameServerClusters. class ListGameServerClustersResponse include Google::Apis::Core::Hashable # The list of game server clusters. # Corresponds to the JSON property `gameServerClusters` # @return [Array<Google::Apis::GameservicesV1::GameServerCluster>] attr_accessor :game_server_clusters # Token to retrieve the next page of results, or empty if there are no more # results in the list. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token # List of locations that could not be reached. # Corresponds to the JSON property `unreachable` # @return [Array<String>] attr_accessor :unreachable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @game_server_clusters = args[:game_server_clusters] if args.key?(:game_server_clusters) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) @unreachable = args[:unreachable] if args.key?(:unreachable) end end # Response message for GameServerConfigsService.ListGameServerConfigs. class ListGameServerConfigsResponse include Google::Apis::Core::Hashable # The list of game server configs. # Corresponds to the JSON property `gameServerConfigs` # @return [Array<Google::Apis::GameservicesV1::GameServerConfig>] attr_accessor :game_server_configs # Token to retrieve the next page of results, or empty if there are no more # results in the list. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token # List of locations that could not be reached. # Corresponds to the JSON property `unreachable` # @return [Array<String>] attr_accessor :unreachable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @game_server_configs = args[:game_server_configs] if args.key?(:game_server_configs) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) @unreachable = args[:unreachable] if args.key?(:unreachable) end end # Response message for GameServerDeploymentsService.ListGameServerDeployments. class ListGameServerDeploymentsResponse include Google::Apis::Core::Hashable # The list of game server deployments. # Corresponds to the JSON property `gameServerDeployments` # @return [Array<Google::Apis::GameservicesV1::GameServerDeployment>] attr_accessor :game_server_deployments # Token to retrieve the next page of results, or empty if there are no more # results in the list. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token # List of locations that could not be reached. # Corresponds to the JSON property `unreachable` # @return [Array<String>] attr_accessor :unreachable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @game_server_deployments = args[:game_server_deployments] if args.key?(:game_server_deployments) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) @unreachable = args[:unreachable] if args.key?(:unreachable) end end # The response message for Locations.ListLocations. class ListLocationsResponse include Google::Apis::Core::Hashable # A list of locations that matches the specified filter in the request. # Corresponds to the JSON property `locations` # @return [Array<Google::Apis::GameservicesV1::Location>] attr_accessor :locations # The standard List next-page token. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @locations = args[:locations] if args.key?(:locations) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) end end # The response message for Operations.ListOperations. class ListOperationsResponse include Google::Apis::Core::Hashable # The standard List next-page token. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token # A list of operations that matches the specified filter in the request. # Corresponds to the JSON property `operations` # @return [Array<Google::Apis::GameservicesV1::Operation>] attr_accessor :operations def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) @operations = args[:operations] if args.key?(:operations) end end # Response message for RealmsService.ListRealms. class ListRealmsResponse include Google::Apis::Core::Hashable # Token to retrieve the next page of results, or empty if there are no more # results in the list. # Corresponds to the JSON property `nextPageToken` # @return [String] attr_accessor :next_page_token # The list of realms. # Corresponds to the JSON property `realms` # @return [Array<Google::Apis::GameservicesV1::Realm>] attr_accessor :realms # List of locations that could not be reached. # Corresponds to the JSON property `unreachable` # @return [Array<String>] attr_accessor :unreachable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @next_page_token = args[:next_page_token] if args.key?(:next_page_token) @realms = args[:realms] if args.key?(:realms) @unreachable = args[:unreachable] if args.key?(:unreachable) end end # A resource that represents Google Cloud Platform location. class Location include Google::Apis::Core::Hashable # The friendly name for this location, typically a nearby city name. For example, # "Tokyo". # Corresponds to the JSON property `displayName` # @return [String] attr_accessor :display_name # Cross-service attributes for the location. For example `"cloud.googleapis.com/ # region": "us-east1"` # Corresponds to the JSON property `labels` # @return [Hash<String,String>] attr_accessor :labels # The canonical id for this location. For example: `"us-east1"`. # Corresponds to the JSON property `locationId` # @return [String] attr_accessor :location_id # Service-specific metadata. For example the available capacity at the given # location. # Corresponds to the JSON property `metadata` # @return [Hash<String,Object>] attr_accessor :metadata # Resource name for the location, which may vary between implementations. For # example: `"projects/example-project/locations/us-east1"` # Corresponds to the JSON property `name` # @return [String] attr_accessor :name def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @display_name = args[:display_name] if args.key?(:display_name) @labels = args[:labels] if args.key?(:labels) @location_id = args[:location_id] if args.key?(:location_id) @metadata = args[:metadata] if args.key?(:metadata) @name = args[:name] if args.key?(:name) end end # Specifies what kind of log the caller must write class LogConfig include Google::Apis::Core::Hashable # Write a Cloud Audit log # Corresponds to the JSON property `cloudAudit` # @return [Google::Apis::GameservicesV1::CloudAuditOptions] attr_accessor :cloud_audit # Increment a streamz counter with the specified metric and field names. Metric # names should start with a '/', generally be lowercase-only, and end in "_count" # . Field names should not contain an initial slash. The actual exported metric # names will have "/iam/policy" prepended. Field names correspond to IAM request # parameters and field values are their respective values. Supported field names: # - "authority", which is "[token]" if IAMContext.token is present, otherwise # the value of IAMContext.authority_selector if present, and otherwise a # representation of IAMContext.principal; or - "iam_principal", a representation # of IAMContext.principal even if a token or authority selector is present; or - # "" (empty string), resulting in a counter with no fields. Examples: counter ` # metric: "/debug_access_count" field: "iam_principal" ` ==> increment counter / # iam/policy/debug_access_count `iam_principal=[value of IAMContext.principal]` # Corresponds to the JSON property `counter` # @return [Google::Apis::GameservicesV1::CounterOptions] attr_accessor :counter # Write a Data Access (Gin) log # Corresponds to the JSON property `dataAccess` # @return [Google::Apis::GameservicesV1::DataAccessOptions] attr_accessor :data_access def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @cloud_audit = args[:cloud_audit] if args.key?(:cloud_audit) @counter = args[:counter] if args.key?(:counter) @data_access = args[:data_access] if args.key?(:data_access) end end # This resource represents a long-running operation that is the result of a # network API call. class Operation include Google::Apis::Core::Hashable # If the value is `false`, it means the operation is still in progress. If `true` # , the operation is completed, and either `error` or `response` is available. # Corresponds to the JSON property `done` # @return [Boolean] attr_accessor :done alias_method :done?, :done # The `Status` type defines a logical error model that is suitable for different # programming environments, including REST APIs and RPC APIs. It is used by [ # gRPC](https://github.com/grpc). Each `Status` message contains three pieces of # data: error code, error message, and error details. You can find out more # about this error model and how to work with it in the [API Design Guide](https: # //cloud.google.com/apis/design/errors). # Corresponds to the JSON property `error` # @return [Google::Apis::GameservicesV1::Status] attr_accessor :error # Service-specific metadata associated with the operation. It typically contains # progress information and common metadata such as create time. Some services # might not provide such metadata. Any method that returns a long-running # operation should document the metadata type, if any. # Corresponds to the JSON property `metadata` # @return [Hash<String,Object>] attr_accessor :metadata # The server-assigned name, which is only unique within the same service that # originally returns it. If you use the default HTTP mapping, the `name` should # be a resource name ending with `operations/`unique_id``. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # The normal response of the operation in case of success. If the original # method returns no data on success, such as `Delete`, the response is `google. # protobuf.Empty`. If the original method is standard `Get`/`Create`/`Update`, # the response should be the resource. For other methods, the response should # have the type `XxxResponse`, where `Xxx` is the original method name. For # example, if the original method name is `TakeSnapshot()`, the inferred # response type is `TakeSnapshotResponse`. # Corresponds to the JSON property `response` # @return [Hash<String,Object>] attr_accessor :response def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @done = args[:done] if args.key?(:done) @error = args[:error] if args.key?(:error) @metadata = args[:metadata] if args.key?(:metadata) @name = args[:name] if args.key?(:name) @response = args[:response] if args.key?(:response) end end # Represents the metadata of the long-running operation. class OperationMetadata include Google::Apis::Core::Hashable # Output only. API version used to start the operation. # Corresponds to the JSON property `apiVersion` # @return [String] attr_accessor :api_version # Output only. The time the operation was created. # Corresponds to the JSON property `createTime` # @return [String] attr_accessor :create_time # Output only. The time the operation finished running. # Corresponds to the JSON property `endTime` # @return [String] attr_accessor :end_time # Output only. Operation status for Game Services API operations. Operation # status is in the form of key-value pairs where keys are resource IDs and the # values show the status of the operation. In case of failures, the value # includes an error code and error message. # Corresponds to the JSON property `operationStatus` # @return [Hash<String,Google::Apis::GameservicesV1::OperationStatus>] attr_accessor :operation_status # Output only. Identifies whether the user has requested cancellation of the # operation. Operations that have successfully been cancelled have Operation. # error value with a google.rpc.Status.code of 1, corresponding to `Code. # CANCELLED`. # Corresponds to the JSON property `requestedCancellation` # @return [Boolean] attr_accessor :requested_cancellation alias_method :requested_cancellation?, :requested_cancellation # Output only. Human-readable status of the operation, if any. # Corresponds to the JSON property `statusMessage` # @return [String] attr_accessor :status_message # Output only. Server-defined resource path for the target of the operation. # Corresponds to the JSON property `target` # @return [String] attr_accessor :target # Output only. List of Locations that could not be reached. # Corresponds to the JSON property `unreachable` # @return [Array<String>] attr_accessor :unreachable # Output only. Name of the verb executed by the operation. # Corresponds to the JSON property `verb` # @return [String] attr_accessor :verb def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @api_version = args[:api_version] if args.key?(:api_version) @create_time = args[:create_time] if args.key?(:create_time) @end_time = args[:end_time] if args.key?(:end_time) @operation_status = args[:operation_status] if args.key?(:operation_status) @requested_cancellation = args[:requested_cancellation] if args.key?(:requested_cancellation) @status_message = args[:status_message] if args.key?(:status_message) @target = args[:target] if args.key?(:target) @unreachable = args[:unreachable] if args.key?(:unreachable) @verb = args[:verb] if args.key?(:verb) end end # class OperationStatus include Google::Apis::Core::Hashable # Output only. Whether the operation is done or still in progress. # Corresponds to the JSON property `done` # @return [Boolean] attr_accessor :done alias_method :done?, :done # The error code in case of failures. # Corresponds to the JSON property `errorCode` # @return [String] attr_accessor :error_code # The human-readable error message. # Corresponds to the JSON property `errorMessage` # @return [String] attr_accessor :error_message def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @done = args[:done] if args.key?(:done) @error_code = args[:error_code] if args.key?(:error_code) @error_message = args[:error_message] if args.key?(:error_message) end end # An Identity and Access Management (IAM) policy, which specifies access # controls for Google Cloud resources. A `Policy` is a collection of `bindings`. # A `binding` binds one or more `members` to a single `role`. Members can be # user accounts, service accounts, Google groups, and domains (such as G Suite). # A `role` is a named list of permissions; each `role` can be an IAM predefined # role or a user-created custom role. For some types of Google Cloud resources, # a `binding` can also specify a `condition`, which is a logical expression that # allows access to a resource only if the expression evaluates to `true`. A # condition can add constraints based on attributes of the request, the resource, # or both. To learn which resources support conditions in their IAM policies, # see the [IAM documentation](https://cloud.google.com/iam/help/conditions/ # resource-policies). **JSON example:** ` "bindings": [ ` "role": "roles/ # resourcemanager.organizationAdmin", "members": [ "user:[email protected]", " # group:[email protected]", "domain:google.com", "serviceAccount:my-project-id@ # appspot.gserviceaccount.com" ] `, ` "role": "roles/resourcemanager. # organizationViewer", "members": [ "user:[email protected]" ], "condition": ` " # title": "expirable access", "description": "Does not grant access after Sep # 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", ` # ` ], "etag": "BwWWja0YfJA=", "version": 3 ` **YAML example:** bindings: - # members: - user:[email protected] - group:[email protected] - domain:google. # com - serviceAccount:[email protected] role: roles/ # resourcemanager.organizationAdmin - members: - user:[email protected] role: # roles/resourcemanager.organizationViewer condition: title: expirable access # description: Does not grant access after Sep 2020 expression: request.time < # timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 For a # description of IAM and its features, see the [IAM documentation](https://cloud. # google.com/iam/docs/). class Policy include Google::Apis::Core::Hashable # Specifies cloud audit logging configuration for this policy. # Corresponds to the JSON property `auditConfigs` # @return [Array<Google::Apis::GameservicesV1::AuditConfig>] attr_accessor :audit_configs # Associates a list of `members` to a `role`. Optionally, may specify a ` # condition` that determines how and when the `bindings` are applied. Each of # the `bindings` must contain at least one member. # Corresponds to the JSON property `bindings` # @return [Array<Google::Apis::GameservicesV1::Binding>] 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. **Important:** If you use IAM # Conditions, you must include the `etag` field whenever you call `setIamPolicy`. # If you omit this field, then IAM allows you to overwrite a version `3` policy # with a version `1` policy, and all of the conditions in the version `3` policy # are lost. # Corresponds to the JSON property `etag` # NOTE: Values are automatically base64 encoded/decoded in the client library. # @return [String] attr_accessor :etag # # Corresponds to the JSON property `iamOwned` # @return [Boolean] attr_accessor :iam_owned alias_method :iam_owned?, :iam_owned # If more than one rule is specified, the rules are applied in the following # manner: - All matching LOG rules are always applied. - If any DENY/ # DENY_WITH_LOG rule matches, permission is denied. Logging will be applied if # one or more matching rule requires logging. - Otherwise, if any ALLOW/ # ALLOW_WITH_LOG rule matches, permission is granted. Logging will be applied if # one or more matching rule requires logging. - Otherwise, if no rule applies, # permission is denied. # Corresponds to the JSON property `rules` # @return [Array<Google::Apis::GameservicesV1::Rule>] attr_accessor :rules # Specifies the format of the policy. Valid values are `0`, `1`, and `3`. # Requests that specify an invalid value are rejected. Any operation that # affects conditional role bindings must specify version `3`. This requirement # applies to the following operations: * Getting a policy that includes a # conditional role binding * Adding a conditional role binding to a policy * # Changing a conditional role binding in a policy * Removing any role binding, # with or without a condition, from a policy that includes conditions ** # Important:** If you use IAM Conditions, you must include the `etag` field # whenever you call `setIamPolicy`. If you omit this field, then IAM allows you # to overwrite a version `3` policy with a version `1` policy, and all of the # conditions in the version `3` policy are lost. If a policy does not include # any conditions, operations on that policy may specify any valid version or # leave the field unset. To learn which resources support conditions in their # IAM policies, see the [IAM documentation](https://cloud.google.com/iam/help/ # conditions/resource-policies). # 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) @audit_configs = args[:audit_configs] if args.key?(:audit_configs) @bindings = args[:bindings] if args.key?(:bindings) @etag = args[:etag] if args.key?(:etag) @iam_owned = args[:iam_owned] if args.key?(:iam_owned) @rules = args[:rules] if args.key?(:rules) @version = args[:version] if args.key?(:version) end end # Response message for GameServerClustersService.PreviewCreateGameServerCluster. class PreviewCreateGameServerClusterResponse include Google::Apis::Core::Hashable # The state of the Kubernetes cluster. # Corresponds to the JSON property `clusterState` # @return [Google::Apis::GameservicesV1::KubernetesClusterState] attr_accessor :cluster_state # The ETag of the game server cluster. # Corresponds to the JSON property `etag` # @return [String] attr_accessor :etag # Encapsulates the Target state. # Corresponds to the JSON property `targetState` # @return [Google::Apis::GameservicesV1::TargetState] attr_accessor :target_state def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @cluster_state = args[:cluster_state] if args.key?(:cluster_state) @etag = args[:etag] if args.key?(:etag) @target_state = args[:target_state] if args.key?(:target_state) end end # Response message for GameServerClustersService.PreviewDeleteGameServerCluster. class PreviewDeleteGameServerClusterResponse include Google::Apis::Core::Hashable # The ETag of the game server cluster. # Corresponds to the JSON property `etag` # @return [String] attr_accessor :etag # Encapsulates the Target state. # Corresponds to the JSON property `targetState` # @return [Google::Apis::GameservicesV1::TargetState] attr_accessor :target_state def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @etag = args[:etag] if args.key?(:etag) @target_state = args[:target_state] if args.key?(:target_state) end end # Response message for PreviewGameServerDeploymentRollout. This has details # about the Agones fleet and autoscaler to be actuated. class PreviewGameServerDeploymentRolloutResponse include Google::Apis::Core::Hashable # ETag of the game server deployment. # Corresponds to the JSON property `etag` # @return [String] attr_accessor :etag # Encapsulates the Target state. # Corresponds to the JSON property `targetState` # @return [Google::Apis::GameservicesV1::TargetState] attr_accessor :target_state # Locations that could not be reached on this request. # Corresponds to the JSON property `unavailable` # @return [Array<String>] attr_accessor :unavailable def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @etag = args[:etag] if args.key?(:etag) @target_state = args[:target_state] if args.key?(:target_state) @unavailable = args[:unavailable] if args.key?(:unavailable) end end # Response message for RealmsService.PreviewRealmUpdate. class PreviewRealmUpdateResponse include Google::Apis::Core::Hashable # ETag of the realm. # Corresponds to the JSON property `etag` # @return [String] attr_accessor :etag # Encapsulates the Target state. # Corresponds to the JSON property `targetState` # @return [Google::Apis::GameservicesV1::TargetState] attr_accessor :target_state def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @etag = args[:etag] if args.key?(:etag) @target_state = args[:target_state] if args.key?(:target_state) end end # Response message for GameServerClustersService.PreviewUpdateGameServerCluster class PreviewUpdateGameServerClusterResponse include Google::Apis::Core::Hashable # The ETag of the game server cluster. # Corresponds to the JSON property `etag` # @return [String] attr_accessor :etag # Encapsulates the Target state. # Corresponds to the JSON property `targetState` # @return [Google::Apis::GameservicesV1::TargetState] attr_accessor :target_state def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @etag = args[:etag] if args.key?(:etag) @target_state = args[:target_state] if args.key?(:target_state) end end # A realm resource. class Realm include Google::Apis::Core::Hashable # Output only. The creation time. # Corresponds to the JSON property `createTime` # @return [String] attr_accessor :create_time # Human readable description of the realm. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # ETag of the resource. # Corresponds to the JSON property `etag` # @return [String] attr_accessor :etag # The labels associated with this realm. Each label is a key-value pair. # Corresponds to the JSON property `labels` # @return [Hash<String,String>] attr_accessor :labels # The resource name of the realm, in the following form: `projects/`project`/ # locations/`location`/realms/`realm``. For example, `projects/my-project/ # locations/`location`/realms/my-realm`. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # Required. Time zone where all policies targeting this realm are evaluated. The # value of this field must be from the IANA time zone database: https://www.iana. # org/time-zones. # Corresponds to the JSON property `timeZone` # @return [String] attr_accessor :time_zone # Output only. The last-modified time. # Corresponds to the JSON property `updateTime` # @return [String] attr_accessor :update_time def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @create_time = args[:create_time] if args.key?(:create_time) @description = args[:description] if args.key?(:description) @etag = args[:etag] if args.key?(:etag) @labels = args[:labels] if args.key?(:labels) @name = args[:name] if args.key?(:name) @time_zone = args[:time_zone] if args.key?(:time_zone) @update_time = args[:update_time] if args.key?(:update_time) end end # The realm selector, used to match realm resources. class RealmSelector include Google::Apis::Core::Hashable # List of realms to match. # Corresponds to the JSON property `realms` # @return [Array<String>] attr_accessor :realms def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @realms = args[:realms] if args.key?(:realms) end end # A rule to be applied in a Policy. class Rule include Google::Apis::Core::Hashable # Required # Corresponds to the JSON property `action` # @return [String] attr_accessor :action # Additional restrictions that must be met. All conditions must pass for the # rule to match. # Corresponds to the JSON property `conditions` # @return [Array<Google::Apis::GameservicesV1::Condition>] attr_accessor :conditions # Human-readable description of the rule. # Corresponds to the JSON property `description` # @return [String] attr_accessor :description # If one or more 'in' clauses are specified, the rule matches if the PRINCIPAL/ # AUTHORITY_SELECTOR is in at least one of these entries. # Corresponds to the JSON property `in` # @return [Array<String>] attr_accessor :in # The config returned to callers of tech.iam.IAM.CheckPolicy for any entries # that match the LOG action. # Corresponds to the JSON property `logConfig` # @return [Array<Google::Apis::GameservicesV1::LogConfig>] attr_accessor :log_config # If one or more 'not_in' clauses are specified, the rule matches if the # PRINCIPAL/AUTHORITY_SELECTOR is in none of the entries. The format for in and # not_in entries can be found at in the Local IAM documentation (see go/local- # iam#features). # Corresponds to the JSON property `notIn` # @return [Array<String>] attr_accessor :not_in # A permission is a string of form '..' (e.g., 'storage.buckets.list'). A value # of '*' matches all permissions, and a verb part of '*' (e.g., 'storage.buckets. # *') matches all verbs. # 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) @action = args[:action] if args.key?(:action) @conditions = args[:conditions] if args.key?(:conditions) @description = args[:description] if args.key?(:description) @in = args[:in] if args.key?(:in) @log_config = args[:log_config] if args.key?(:log_config) @not_in = args[:not_in] if args.key?(:not_in) @permissions = args[:permissions] if args.key?(:permissions) end end # Autoscaling config for an Agones fleet. class ScalingConfig include Google::Apis::Core::Hashable # Required. Agones fleet autoscaler spec. Example spec: https://agones.dev/site/ # docs/reference/fleetautoscaler/ # Corresponds to the JSON property `fleetAutoscalerSpec` # @return [String] attr_accessor :fleet_autoscaler_spec # Required. The name of the Scaling Config # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # The schedules to which this Scaling Config applies. # Corresponds to the JSON property `schedules` # @return [Array<Google::Apis::GameservicesV1::Schedule>] attr_accessor :schedules # Labels used to identify the game server clusters to which this Agones scaling # config applies. A game server cluster is subject to this Agones scaling config # if its labels match any of the selector entries. # Corresponds to the JSON property `selectors` # @return [Array<Google::Apis::GameservicesV1::LabelSelector>] attr_accessor :selectors def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @fleet_autoscaler_spec = args[:fleet_autoscaler_spec] if args.key?(:fleet_autoscaler_spec) @name = args[:name] if args.key?(:name) @schedules = args[:schedules] if args.key?(:schedules) @selectors = args[:selectors] if args.key?(:selectors) end end # The schedule of a recurring or one time event. The event's time span is # specified by start_time and end_time. If the scheduled event's timespan is # larger than the cron_spec + cron_job_duration, the event will be recurring. If # only cron_spec + cron_job_duration are specified, the event is effective # starting at the local time specified by cron_spec, and is recurring. # start_time|-------[cron job]-------[cron job]-------[cron job]---|end_time # cron job: cron spec start time + duration class Schedule include Google::Apis::Core::Hashable # The duration for the cron job event. The duration of the event is effective # after the cron job's start time. # Corresponds to the JSON property `cronJobDuration` # @return [String] attr_accessor :cron_job_duration # The cron definition of the scheduled event. See https://en.wikipedia.org/wiki/ # Cron. Cron spec specifies the local time as defined by the realm. # Corresponds to the JSON property `cronSpec` # @return [String] attr_accessor :cron_spec # The end time of the event. # Corresponds to the JSON property `endTime` # @return [String] attr_accessor :end_time # The start time of the event. # Corresponds to the JSON property `startTime` # @return [String] attr_accessor :start_time def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @cron_job_duration = args[:cron_job_duration] if args.key?(:cron_job_duration) @cron_spec = args[:cron_spec] if args.key?(:cron_spec) @end_time = args[:end_time] if args.key?(:end_time) @start_time = args[:start_time] if args.key?(:start_time) end end # Request message for `SetIamPolicy` method. class SetIamPolicyRequest include Google::Apis::Core::Hashable # An Identity and Access Management (IAM) policy, which specifies access # controls for Google Cloud resources. A `Policy` is a collection of `bindings`. # A `binding` binds one or more `members` to a single `role`. Members can be # user accounts, service accounts, Google groups, and domains (such as G Suite). # A `role` is a named list of permissions; each `role` can be an IAM predefined # role or a user-created custom role. For some types of Google Cloud resources, # a `binding` can also specify a `condition`, which is a logical expression that # allows access to a resource only if the expression evaluates to `true`. A # condition can add constraints based on attributes of the request, the resource, # or both. To learn which resources support conditions in their IAM policies, # see the [IAM documentation](https://cloud.google.com/iam/help/conditions/ # resource-policies). **JSON example:** ` "bindings": [ ` "role": "roles/ # resourcemanager.organizationAdmin", "members": [ "user:[email protected]", " # group:[email protected]", "domain:google.com", "serviceAccount:my-project-id@ # appspot.gserviceaccount.com" ] `, ` "role": "roles/resourcemanager. # organizationViewer", "members": [ "user:[email protected]" ], "condition": ` " # title": "expirable access", "description": "Does not grant access after Sep # 2020", "expression": "request.time < timestamp('2020-10-01T00:00:00.000Z')", ` # ` ], "etag": "BwWWja0YfJA=", "version": 3 ` **YAML example:** bindings: - # members: - user:[email protected] - group:[email protected] - domain:google. # com - serviceAccount:[email protected] role: roles/ # resourcemanager.organizationAdmin - members: - user:[email protected] role: # roles/resourcemanager.organizationViewer condition: title: expirable access # description: Does not grant access after Sep 2020 expression: request.time < # timestamp('2020-10-01T00:00:00.000Z') - etag: BwWWja0YfJA= - version: 3 For a # description of IAM and its features, see the [IAM documentation](https://cloud. # google.com/iam/docs/). # Corresponds to the JSON property `policy` # @return [Google::Apis::GameservicesV1::Policy] attr_accessor :policy # OPTIONAL: A FieldMask specifying which fields of the policy to modify. Only # the fields in the mask will be modified. If no mask is provided, the following # default mask is used: `paths: "bindings, etag"` # Corresponds to the JSON property `updateMask` # @return [String] attr_accessor :update_mask def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @policy = args[:policy] if args.key?(:policy) @update_mask = args[:update_mask] if args.key?(:update_mask) end end # Encapsulates Agones fleet spec and Agones autoscaler spec sources. class SpecSource include Google::Apis::Core::Hashable # The game server config resource. Uses the form: `projects/`project`/locations/` # location`/gameServerDeployments/`deployment_id`/configs/`config_id``. # Corresponds to the JSON property `gameServerConfigName` # @return [String] attr_accessor :game_server_config_name # The name of the Agones leet config or Agones scaling config used to derive the # Agones fleet or Agones autoscaler spec. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @game_server_config_name = args[:game_server_config_name] if args.key?(:game_server_config_name) @name = args[:name] if args.key?(:name) end end # The `Status` type defines a logical error model that is suitable for different # programming environments, including REST APIs and RPC APIs. It is used by [ # gRPC](https://github.com/grpc). Each `Status` message contains three pieces of # data: error code, error message, and error details. You can find out more # about this error model and how to work with it in the [API Design Guide](https: # //cloud.google.com/apis/design/errors). class Status include Google::Apis::Core::Hashable # The status code, which should be an enum value of google.rpc.Code. # Corresponds to the JSON property `code` # @return [Fixnum] attr_accessor :code # A list of messages that carry the error details. There is a common set of # message types for APIs to use. # Corresponds to the JSON property `details` # @return [Array<Hash<String,Object>>] attr_accessor :details # A developer-facing error message, which should be in English. Any user-facing # error message should be localized and sent in the google.rpc.Status.details # field, or localized by the client. # Corresponds to the JSON property `message` # @return [String] attr_accessor :message def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @code = args[:code] if args.key?(:code) @details = args[:details] if args.key?(:details) @message = args[:message] if args.key?(:message) end end # Details about the Agones resources. class TargetDetails include Google::Apis::Core::Hashable # Agones fleet details for game server clusters and game server deployments. # Corresponds to the JSON property `fleetDetails` # @return [Array<Google::Apis::GameservicesV1::TargetFleetDetails>] attr_accessor :fleet_details # The game server cluster name. Uses the form: `projects/`project`/locations/` # location`/realms/`realm`/gameServerClusters/`cluster``. # Corresponds to the JSON property `gameServerClusterName` # @return [String] attr_accessor :game_server_cluster_name # The game server deployment name. Uses the form: `projects/`project`/locations/` # location`/gameServerDeployments/`deployment_id``. # Corresponds to the JSON property `gameServerDeploymentName` # @return [String] attr_accessor :game_server_deployment_name def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @fleet_details = args[:fleet_details] if args.key?(:fleet_details) @game_server_cluster_name = args[:game_server_cluster_name] if args.key?(:game_server_cluster_name) @game_server_deployment_name = args[:game_server_deployment_name] if args.key?(:game_server_deployment_name) end end # Target Agones fleet specification. class TargetFleet include Google::Apis::Core::Hashable # The name of the Agones fleet. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # Encapsulates Agones fleet spec and Agones autoscaler spec sources. # Corresponds to the JSON property `specSource` # @return [Google::Apis::GameservicesV1::SpecSource] attr_accessor :spec_source def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @name = args[:name] if args.key?(:name) @spec_source = args[:spec_source] if args.key?(:spec_source) end end # Target Agones autoscaler policy reference. class TargetFleetAutoscaler include Google::Apis::Core::Hashable # The name of the Agones autoscaler. # Corresponds to the JSON property `name` # @return [String] attr_accessor :name # Encapsulates Agones fleet spec and Agones autoscaler spec sources. # Corresponds to the JSON property `specSource` # @return [Google::Apis::GameservicesV1::SpecSource] attr_accessor :spec_source def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @name = args[:name] if args.key?(:name) @spec_source = args[:spec_source] if args.key?(:spec_source) end end # Details of the target Agones fleet. class TargetFleetDetails include Google::Apis::Core::Hashable # Target Agones autoscaler policy reference. # Corresponds to the JSON property `autoscaler` # @return [Google::Apis::GameservicesV1::TargetFleetAutoscaler] attr_accessor :autoscaler # Target Agones fleet specification. # Corresponds to the JSON property `fleet` # @return [Google::Apis::GameservicesV1::TargetFleet] attr_accessor :fleet def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @autoscaler = args[:autoscaler] if args.key?(:autoscaler) @fleet = args[:fleet] if args.key?(:fleet) end end # Encapsulates the Target state. class TargetState include Google::Apis::Core::Hashable # Details about Agones fleets. # Corresponds to the JSON property `details` # @return [Array<Google::Apis::GameservicesV1::TargetDetails>] attr_accessor :details def initialize(**args) update!(**args) end # Update properties of this object def update!(**args) @details = args[:details] if args.key?(:details) end end # Request message for `TestIamPermissions` method. class TestIamPermissionsRequest 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 TestIamPermissionsResponse 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 end end end
41.671111
130
0.627005
61e59820cd08829fb422d9307090d55ffcc52d9e
807
module Api class SizeController < BaseController caches_action :average_sizes def average_sizes() @data = {} ReportInteger.where(ReportInteger.arel_table[:integer].gt(0)).scoping do @data = { t('.size') => ReportInteger.where({:key => 'Reports::Size'}).average(:integer).floor(), t('.html_size') => ReportInteger.where({:key => 'Reports::HtmlSize'}).average(:integer).floor(), t('.html_downloaded_size') => ReportInteger.where({:key => 'Reports::HtmlDownloadedSize'}).average(:integer).floor(), t('.text_size') => ReportInteger.where({:key => 'Reports::TextSize'}).average(:integer).floor() } end respond_to do |format| format.json do render :json => @data end end end end end
33.625
127
0.60223
b9fa9844e69cf462ccb7d88a10e9e68c44377f3b
2,456
class Array # call-seq: # array.shuffle!(random: Random) -> array # # Shuffles the elements of +self+ in place. # a = [1, 2, 3] #=> [1, 2, 3] # a.shuffle! #=> [2, 3, 1] # a #=> [2, 3, 1] # # The optional +random+ argument will be used as the random number generator: # a.shuffle!(random: Random.new(1)) #=> [1, 3, 2] def shuffle!(random: Random) Primitive.rb_ary_shuffle_bang(random) end # call-seq: # array.shuffle(random: Random) -> new_ary # # Returns a new array with elements of +self+ shuffled. # a = [1, 2, 3] #=> [1, 2, 3] # a.shuffle #=> [2, 3, 1] # a #=> [1, 2, 3] # # The optional +random+ argument will be used as the random number generator: # a.shuffle(random: Random.new(1)) #=> [1, 3, 2] def shuffle(random: Random) Primitive.rb_ary_shuffle(random) end # call-seq: # array.sample(random: Random) -> object # array.sample(n, random: Random) -> new_ary # # Returns random elements from +self+. # # When no arguments are given, returns a random element from +self+: # a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # a.sample # => 3 # a.sample # => 8 # If +self+ is empty, returns +nil+. # # When argument +n+ is given, returns a new \Array containing +n+ random # elements from +self+: # a.sample(3) # => [8, 9, 2] # a.sample(6) # => [9, 6, 10, 3, 1, 4] # Returns no more than <tt>a.size</tt> elements # (because no new duplicates are introduced): # a.sample(a.size * 2) # => [6, 4, 1, 8, 5, 9, 10, 2, 3, 7] # But +self+ may contain duplicates: # a = [1, 1, 1, 2, 2, 3] # a.sample(a.size * 2) # => [1, 1, 3, 2, 1, 2] # The argument +n+ must be a non-negative numeric value. # The order of the result array is unrelated to the order of +self+. # Returns a new empty \Array if +self+ is empty. # # The optional +random+ argument will be used as the random number generator: # a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # a.sample(random: Random.new(1)) #=> 6 # a.sample(4, random: Random.new(1)) #=> [6, 10, 9, 2] def sample(n = (ary = false), random: Random) if Primitive.mandatory_only? # Primitive.cexpr! %{ rb_ary_sample(self, rb_cRandom, Qfalse, Qfalse) } Primitive.ary_sample0 else # Primitive.cexpr! %{ rb_ary_sample(self, random, n, ary) } Primitive.ary_sample(random, n, ary) end end end
35.085714
79
0.567997
26edd8ac28180c55f28c5638d3a63d3ae697ff29
538
# frozen_string_literal: true require 'spec_helper' RSpec.describe Ializer::DateDeSer do describe '#serialize' do it 'serializes values to string' do expect(described_class.serialize(Date.new(2018, 4, 4))).to eq '2018-04-04' end end describe '#parse' do it 'parses values to date' do expect(described_class.parse('2018-04-04')).to eq Date.new(2018, 4, 4) # parse failures expect(described_class.parse('asdf')).to eq 'asdf' expect(described_class.parse(nil)).to eq nil end end end
24.454545
80
0.680297
f8ab5411ba6233de7a302945b1029c170607087a
4,797
require 'log4r' require 'vagrant' require 'git' require 'fileutils' require "log4r" require_relative 'errors' module VagrantPlugins module Saltdeps class Provisioner < Vagrant.plugin('2', :provisioner) def initialize(machine, config) super @logger = Log4r::Logger.new("vagrant::provisioner::saltdeps") @checkout_path = config.checkout_path @grains_path = config.grains_path @pillars_path = config.pillars_path @merge_pillars = config.merge_pillars @merge_grains = config.merge_grains @merged_path = config.merged_path @deps = YAML.load_file(config.deps_path)['deps'] || {} @current_formula = YAML.load_file(config.deps_path)['name'] @formula_folders = [] end def configure(root_config) checkout_deps link_deps(root_config) merge_grains merge_pillars end def checkout_deps @deps.each do |name,props| uri = props.fetch('git', 'foobar') name = "#{name}-formula" branch = props.fetch('branch','master') if File.directory? @checkout_path + "/#{name}" g = Git.open @checkout_path + "/#{name}" else g = Git.clone(uri, name, path: @checkout_path) end begin g.checkout(branch) g.pull rescue Git::GitExecuteError => e raise GitCheckoutError.new :branch => branch, :message => e.message end end end def link_deps(root_config) @deps.each do |name, props| base_path = @checkout_path + "/#{name}-formula/" if File.directory? base_path + "#{name}" @formula_folders << {host_path: base_path + "#{name}", guest_path: '/srv/salt'} else @machine.ui.warn("Not creating shared folder for dependency #{name} because no folder was found at #{base_path + name}") end end end def provision communicator = @machine.communicate @formula_folders.each do |folder| communicator.upload(folder[:host_path],folder[:guest_path]) end current_path = File.expand_path(@current_formula, @machine.env.root_path) communicator.upload(current_path,'/srv/salt') end def cleanup if File.directory? @checkout_path FileUtils.rm_rf(@checkout_path) end if File.directory? @merged_path FileUtils.rm(@merged_path + '/compiled_grains') if File.exists? @merged_path + '/compiled_grains' FileUtils.rm(@merged_path + '/compiled_pillars') if File.exists? @merged_path + '/compiled_pillars' end cleanup_check_path = self.clean_up_path cleanup_folders = @deps.keys cleanup_folders << @current_formula cleanup_folders.each do |dep| FileUtils.rm_rf(cleanup_check_path + '/' + dep) if File.directory?(cleanup_check_path + '/' + dep) end end def merge_grains output_path = File.expand_path(@merged_path+'/compiled_grains', @machine.env.root_path) if @merge_grains merge(@grains_path, output_path) @machine.config.vm.provisioners.each do |provisioner| next unless provisioner.type == :salt provisioner.config.grains_config= output_path end end end def merge_pillars output_path = File.expand_path(@merged_path+'/compiled_pillars', @machine.env.root_path) if @merge_pillars merge(@pillars_path, output_path) @machine.config.vm.provisioners.each do |provisioner| next unless provisioner.type == :salt provisioner.config.pillar(YAML.load_file(output_path) || {}) end end end def merge(path, output) local_path = File.expand_path(path, @machine.env.root_path) merge_object = {} @formula_folders.each do |folder| split_host_path = folder[:host_path].split('/') base_dep_path = split_host_path[0..(split_host_path.length-2)].join('/') dep_path = File.expand_path(base_dep_path + '/' + path, @machine.env.root_path) merge_object.deep_merge!(YAML.load_file(dep_path) || {}) if File.exists?(dep_path) end merge_object.deep_merge!(File.exists?(local_path) ? YAML.load_file(local_path) || {} : {}) File.open(output, 'w') {|f| f.write merge_object.to_yaml } end def clean_up_path checkout_path = @checkout_path.split('/') base_checkout_path = checkout_path[0..(checkout_path.length-2)].join('/') File.expand_path(base_checkout_path, @machine.env.root_path) end end end end
35.272059
132
0.612258
bf13573b754af075f36c2d135e74774ced39c50e
4,045
require 'typhoeus' require_relative "../interface_topology_provider.rb" require_relative "../../network_entities/topology.rb" require_relative '../../network_entities/abstracts/path.rb' class OpendaylightTopologyProvider < ITopologyProvider attr_accessor :uri_resource def initialize(new_uri_resource) raise ArgumentError, 'No uri recieved as parameter' unless new_uri_resource @uri_resource = new_uri_resource @topology = Topology.new end =begin This is who it looks like the xml received by the opendaylight api <topology> <topology-id>flow:1</topology-id> <node> <node-id>openflow:1</node-id> <inventory-node-ref>/a:nodes/a:node[a:id='openflow:1']</inventory-node-ref> <termination-point> <tp-id>openflow:1:2</tp-id> <inventory-node-connector-ref>/a:nodes/a:node[a:id='openflow:1']/a:node-connector[a:id='openflow:1:2']</inventory-node-connector-ref> </termination-point> <termination-point> <tp-id>openflow:1:1</tp-id> <inventory-node-connector-ref>/a:nodes/a:node[a:id='openflow:1']/a:node-connector[a:id='openflow:1:1']</inventory-node-connector-ref> </termination-point> <termination-point> <tp-id>openflow:1:LOCAL</tp-id> <inventory-node-connector-ref>/a:nodes/a:node[a:id='openflow:1']/a:node-connector[a:id='openflow:1:LOCAL']</inventory-node-connector-ref> </termination-point> </node> <node> <node-id>host:52:57:c6:e4:b3:33</node-id> <id>52:57:c6:e4:b3:33</id> <addresses> <id>1</id> <mac>52:57:c6:e4:b3:33</mac> <ip>10.0.0.2</ip> <first-seen>1480973744947</first-seen> <last-seen>1480973744947</last-seen> </addresses> <attachment-points> <tp-id>openflow:2:2</tp-id> <active>true</active> <corresponding-tp>host:52:57:c6:e4:b3:33</corresponding-tp> </attachment-points> <termination-point> <tp-id>host:52:57:c6:e4:b3:33</tp-id> </termination-point> </node> <link> <link-id>openflow:1:2</link-id> <source> <source-node>openflow:1</source-node> <source-tp>openflow:1:2</source-tp> </source> <destination> <dest-node>openflow:2</dest-node> <dest-tp>openflow:2:1</dest-tp> </destination> </link> <link> <link-id>host:5e:66:e6:c2:d0:02/openflow:3:1</link-id> <source> <source-node>host:5e:66:e6:c2:d0:02</source-node> <source-tp>host:5e:66:e6:c2:d0:02</source-tp> </source> <destination> <dest-node>openflow:3</dest-node> <dest-tp>openflow:3:1</dest-tp> </destination> </link> </topology> =end def get_topology response = Typhoeus.get "#{@uri_resource}/restconf/operational/network-topology:network-topology/topology/flow:1/", userpwd:"admin:admin" topology_json_response = (JSON.parse response.body)['topology'].first nodes_info = topology_json_response['node'] links_info = topology_json_response['link'] nodes_info.each do |node| if node['node-id'].include? 'openflow' @topology.add_router node['node-id'] else node_info = node["host-tracker-service:addresses"].first @topology.add_host node['node-id'], [node_info['ip']], node_info['mac'] end end links_info.each do |link| source = @topology.get_element_by_id link['source']['source-node'] destiny = @topology.get_element_by_id link['destination']['dest-node'] #TODO: WHICH IS THE FORM OF FINDING THE PORT OF THE HOST? source_port = (source.is_a? Host) ? 1 : (link['source']['source-tp'].gsub "#{source.id}:", '').to_i destiny_port = (destiny.is_a? Host) ? 1 : (link['destination']['dest-tp'].gsub "#{destiny.id}:", '').to_i @topology.add_link link['link-id'], source, source_port, destiny, destiny_port end @topology.topology_elements end def get_path_between(source, destination) raise NotImplementedError, "OpenDayLight provider: This method is not implemented!" end end
35.79646
143
0.651422
2893b8433eee8f6a2ebaf4af807d2ad46ab6fa20
17,397
# frozen_string_literal: false DEBUG = false # Rank Position Total Global Points # Bronze 981 1,127 13.51 # Bronze 994 1,158 13.90 # Bronze 592 1,167 26.85 # Bronze 611 1,209 27.30 # Bronze 591 1,212 27.85 # Bronze 455 1,212 30.90 # Bronze 142 931 29.26 # Bronze 73 932 31.22 # Bronze 102 929 30.45 # Bronze 45 927 32.00 # Silver 528 560 12.00 # Silver 402 555 15.53 # Silver 406 557 15.36 # Silver 284 556 17.43 # Silver 258 558 17.81 # Silver 165 558 19.88 # Silver 174 555 19.81 # Silver 169 566 20.25 # Silver 99 577 22.07 # Silver 129 586 21.68 # Silver 150 588 21.27 # Silver 126 590 21.85 # Silver 44 590 24.29 # Gold 342 426 18.35 # Gold 376 429 17.08 # Gold 330 453 18.70 # Gold 223 455 260 21.58 # Gold 162 456 199 23.33 STDOUT.sync = true # DO NOT REMOVE # Deliver more ore to hq (left side of the map) than your opponent. Use radars to find ore but beware of traps! alias org_gets gets def gets org_gets # .tap { |v| warn v } end INT_TO_ITEM = { -1 => :none, 2 => :radar, 3 => :trap, 4 => :ore }.freeze class Integer def sqr self * self end def to_item INT_TO_ITEM[self] end end WIDTH, HEIGHT = gets.split(' ').collect(&:to_i) # 30 x 15 SECTOR_SIZE = 5 HORZ_SECTORS = WIDTH / SECTOR_SIZE VERT_SECTORS = HEIGHT / SECTOR_SIZE class Position attr_reader :row, :col def initialize(row, col) @row = row.clamp(0, HEIGHT - 1) @col = col.clamp(0, WIDTH - 1) end def distance_to(pos) Math.sqrt((row - pos.row).sqr + (col - pos.col).sqr) end def manhattan_to(pos) (row - pos.row).abs + (col - pos.col).abs end def self.random Position.new(rand(HEIGHT), rand(WIDTH)) end def ==(other) other.is_a?(Position) && row == other.row && col == other.col end def to_s "#{@col} #{@row}" end end class Task def initialize(state, bot) @gs = state @bot = bot @done = false end def move_to(target) yield if block_given? @gs.move_to target, msg: self.class end def move_to_hq move_to @bot.hq end def dig_at(target) yield if block_given? @gs.dig_at target, msg: self.class end def request(item) yield if block_given? @gs.request item, msg: self.class end def wait @gs.wait msg: self.class end def finish_by @done = true yield end def finished? @done || @bot.disabled? end end class NoTask < Task def initialize(state, bot) super state, bot end def next_command wait end end class ScanSectorTask < Task def initialize(state, bot) super state, bot @rand_target = around_next_radar end def around_next_radar return unless (target = @gs.available_radar_pos) drow = rand(-4..4) dcol = rand((-4 + drow.abs)..(4 - drow.abs)) Position.new(target.row + drow, target.col + dcol) end def next_command target = @gs.nearest_ore(@bot)&.pos || @rand_target return finish_by { wait } if target.nil? if @bot.can_dig? target finish_by { dig_at target } else move_to target end end end class PlaceRadarTask < Task def initialize(state, bot) super state, bot end def next_command unless @bot.carrying?(:radar) return move_to_hq unless @bot.at_hq? return wait unless @gs.can_place_radar? return request :RADAR end target = @gs.available_radar_pos return finish_by { wait } if target.nil? if @bot.can_dig? target finish_by { dig_at target } else move_to target end end end class MineOreTask < Task def initialize(state, bot) super state, bot end def next_command unless (target = @gs.nearest_ore(@bot)&.pos) return finish_by { wait } end if @bot.can_dig? target finish_by { dig_at target } else move_to target end end end class DeliverOreTask < Task def initialize(state, bot) super state, bot end def next_command # warn "bot: #{@bot}, target: #{@target}" move_to_hq end def finished? super || @bot.at_hq? end end class PlaceTrapTask < Task attr_reader :target def initialize(state, bot) super state, bot @target = (state.nearest_ore(bot, min_size: 2, max_size: 2) || state.nearest_ore(bot, min_size: 2))&.pos end def next_command return request :TRAP unless @bot.carrying? :trap @target = (@gs.nearest_ore(@bot, min_size: 2, max_size: 2) || @gs.nearest_ore(@bot, min_size: 2))&.pos return wait if @target.nil? if @bot.can_dig? @target finish_by { dig_at @target } else move_to @target end end end class SuicideTask < Task def initialize(state, bot, target) super state, bot @target = target end def next_command finish_by { dig_at @target } end end class Cell attr_accessor :dangerous attr_reader :ore, :hole, :pos, :entities, :just_digged def initialize(pos) @pos = pos @ore = nil @hole = :none @just_digged = false end def entity=(entity) @entities = @entities.nil? ? [entity] : @entities << entity end def set_state(ore, hole) @just_digged = false if ore != '?' ore = ore.to_i @just_digged = true if @ore && @ore > ore @ore = ore end if !hole? && hole == '1' @hole = :opponent @just_digged = true end @entities = nil end def claim_hole @hole = :player end def hole? @hole != :none end def my_hole? @hole == :player end def contains_ore? @ore&.positive? end def trap? @entities&.any?(&:trap?) end def robots? return @entities&.any?(&:robot?) unless block_given? @entities&.each do |ent| yield ent if ent.robot? end end def contains_item_type?(type) @entities&.any? { |itm| itm.is_a? type } end def decrement_ore(clear: false) @ore -= (clear ? @ore : 1) if contains_ore? end def distance_to(pos) @pos.distance_to(pos) end def to_s ent = if @entities.nil? @dangerous ? '!' : ' ' elsif @entities.size > 1 @entities.size else @entities.first.to_s end ore = case @hole when :player @ore ? %w[O A B C D E F][@ore] : 'H' when :opponent @ore ? %w[° a b c d e f][@ore] : 'h' else @ore&.zero? ? '_' : @ore || '.' end "#{ore}#{ent}" end end class Board def initialize @cells = Array.new(HEIGHT) { |row| Array.new(WIDTH) { |col| Cell.new(Position.new(row, col)) } } @ores = [] end def [](pos = nil, row: pos.row, col: pos.col) @cells[row]&.[](col) end def ore(pos) self[pos].ore end def hole(pos) self[pos].hole end def each_neighbour(pos, range: 1, &block) self[pos].tap(&block) (1..range).each do |delta| self[row: pos.row + delta, col: pos.col]&.tap(&block) self[row: pos.row - delta, col: pos.col]&.tap(&block) self[row: pos.row, col: pos.col + delta]&.tap(&block) self[row: pos.row, col: pos.col - delta]&.tap(&block) end end def nearest_ore_list(min_size: 1, max_size: 99) @ores.select { |cell| cell.ore.between?(min_size, max_size) && !cell.trap? && !cell.dangerous } # @ores.select { |cell| cell.ore.between?(min_size, max_size) && !cell.trap? } if list.empty? end def nearest_ore(pos, min_size: 1, max_size: 99) nearest_ore_list(min_size: min_size, max_size: max_size).min_by { |cell| pos.distance_to cell.pos } end def decrement_ore(pos, clear: false) cell = self[pos] cell.decrement_ore clear: clear @ores.delete(cell) unless cell.contains_ore? end def ore_count nearest_ore_list.map(&:ore).sum end def all_dangerous danger = [] (0...HEIGHT).each do |row| (0...WIDTH).each do |col| cell = self[row: row, col: col] danger << cell if cell.dangerous end end danger end def read_state @ores = [] HEIGHT.times do |row| # ore: amount of ore or "?" if unknown # hole: 1 if cell has a hole cells = @cells[row].each gets.split(' ').each_slice(2) do |ore, hole| cell = cells.next cell.set_state(ore, hole) @ores << cell if cell.contains_ore? end end end def to_s @cells .map { |row| row.join('') } .join("\n") # + "\n" + @ores.map(&:pos).join(',') end end class Entity attr_reader :id, :pos def initialize(id, col, row) @id = id @pos = Position.new(row, col) end def trap? false end def robot? false end end class Robot < Entity attr_reader :pos, :item, :owner attr_accessor :task def initialize(id, col, row, item_id, owner) super id, col, row @item = item_id.to_item @owner = %i[player opponent][owner] @last_pos = @pos @last_cmd = nil @carry = false @dropped = false end def update(col, row, item_id) @last_pos = @pos if row.negative? @pos = nil @item = :none else @pos = Position.new(row, col) @item = item_id.to_item @dropped = false if @pos == @last_pos @dropped = @carry && !at_hq? @carry = at_hq? end end self end def robot? true end def distance_to(pos) @pos.distance_to pos end def nearest(pos1, pos2) distance_to(pos) < distance_to(pos2) ? pos1 : pos2 end def mine? if block_given? yield if @owner == :player else @owner == :player end end def disabled? @pos.nil? end def enabled? !disabled? end def carrying?(item = nil) item.nil? ? @item != :none : @item == item end def carrying_ore? @item == :ore end def can_dig?(pos) @pos == pos || @pos.col == pos.col && (@pos.row - pos.row).abs <= 1 || @pos.row == pos.row && (@pos.col - pos.col).abs <= 1 end def mark_dangerous(board) return if disabled? || !@dropped marked = 0 board.each_neighbour(@pos) do |cell| if cell.just_digged && cell.hole == :opponent cell.dangerous = true marked += 1 end end return if marked.positive? board.each_neighbour(@pos) do |cell| cell.dangerous |= cell.hole? end end def at_hq? @pos.col.zero? end def hq Position.new(pos.row, 0) end def finished_task? @task.nil? || @task.finished? end def next_command @last_cmd = @task&.next_command end def inspect "Robot \##{@id} @ [#{@pos}]" + mine? { enabled? ? " (#{@item})" : ' (X)' }.to_s end def to_s case @owner when :player carrying? ? 'R' : 'r' else @carry ? 'S' : 's' end end end class Radar < Entity def to_s 'Y' end end class Trap < Entity def to_s '=' end def trap? true end end RADAR_LOCATIONS = [ Position.new(7, 8), Position.new(2, 12), Position.new(12, 12), Position.new(2, 4), Position.new(12, 4), Position.new(7, 15), Position.new(2, 19), Position.new(12, 19), Position.new(7, 23), Position.new(2, 27), Position.new(12, 27), Position.new(7, 27) ].freeze class GameState class Command def initialize(action = :WAIT, pos: nil, item: nil, msg: nil) @act = action @pos = pos @itm = item @msg = msg end def action act end def to_s @msg = '' unless DEBUG case @act when :MOVE, :DIG "#{@act} #{@pos} #{@msg}" when :REQUEST "#{@act} #{@itm} #{@msg}" else "#{@act} #{@msg}" end end end def initialize @board = Board.new @score = 0 @enemy_score = 0 @entity_count = 0 @radar_cooldown = 0 @trap_cooldown = 0 @robots = {} @my_bots = [] @items = {} end def move_to(target, msg: nil) Command.new(:MOVE, pos: target, msg: msg) end def dig_at(target, msg: nil) @board[target].claim_hole @board.decrement_ore(target) Command.new(:DIG, pos: target, msg: msg) end def request(item, msg: nil) case item when :RADAR @radar_cooldown = 5 when :TRAP @trap_cooldown = 5 end Command.new(:REQUEST, item: item, msg: msg) end def wait(msg: nil) Command.new(:WAIT, msg: msg) end def read_state # my_score: Amount of ore delivered @score, @enemy_score = gets.split(' ').collect(&:to_i) @board.read_state @items = {} # entity_count: number of entities visible to you # radar_cooldown: turns left until a new radar can be requested # trap_cooldown: turns left until a new trap can be requested @entity_count, @radar_cooldown, @trap_cooldown = gets.split(' ').collect(&:to_i) @entity_count.times do # id: unique id of the entity # type: 0 for your robot, 1 for other robot, 2 for radar, 3 for trap # y: position of the entity # item: if this entity is a robot, the item it is carrying (-1 for NONE, 2 for RADAR, 3 for TRAP, 4 for ORE) id, type, col, row, item_id = gets.split(' ').collect(&:to_i) case type when 0, 1 (@robots[id] = @robots[id]&.update(col, row, item_id) || Robot.new(id, col, row, item_id, type)) .tap { |bot| bot.mark_dangerous(@board) unless bot.mine? } when 2 @items[id] = Radar.new(id, col, row) when 3 @items[id] = Trap.new(id, col, row) end.tap { |entity| @board[entity.pos].entity = entity if entity.pos } end @my_bots = @robots.map(&:last).select(&:mine?) end def [](pos) @board[pos] end def radar_available? @radar_cooldown.zero? end def available_radar_pos RADAR_LOCATIONS.find do |pos| cell = @board[pos] !(cell.dangerous || cell.contains_item_type?(Radar)) end # .tap { |loc| warn "Radar location: #{loc}" } end def can_place_radar? radar_available? && available_radar_pos end def trap_available? @trap_cooldown.zero? end def nearest_ore(bot, min_size: 1, max_size: 99) @board.nearest_ore(bot.pos, min_size: min_size, max_size: max_size) end def placing_radar_count @my_bots.count { |bot| bot.enabled? && bot.task.is_a?(PlaceRadarTask) } end def radar_bot @my_bots.find { |bot| bot.task.is_a? PlaceRadarTask } end def all_traps @items.values.select { |item| item.is_a? Trap }.map(&:pos) + @board.all_dangerous.map(&:pos) end def trap_kills(pos, kills = { player: [], opponent: [] }, visited = {}) @board.each_neighbour(pos) do |cell| next if visited[cell.pos] visited[cell.pos] = true cell.robots? { |bot| kills[bot.owner] << bot if bot.enabled? } kills = trap_kills(cell.pos, kills, visited) if cell.trap? end kills end def kamikazes bots = {} all_traps.each do |pos| kills = trap_kills(pos) plys = kills[:player] opos = kills[:opponent] bots[plys.first.id] = pos if plys.size == 1 && opos.size >= 1 && plys.none?(&:carrying_ore?) end bots end def assign_tasks radar_avail = can_place_radar? && !radar_bot trap_avail = trap_available? kamis = kamikazes @my_bots.each do |bot| if kamis[bot.id] bot.task = SuicideTask.new(self, bot, kamis[bot.id]) next end next unless bot.finished_task? if bot.enabled? ore_cell = nearest_ore(bot) ore_dist = ore_cell&.distance_to(bot.pos) || 999 end # warn "bot: #{bot} => ore: #{ore_cell} @ #{ore_cell&.pos}" bot.task = if bot.disabled? NoTask.new self, bot elsif bot.carrying? :ore DeliverOreTask.new(self, bot) elsif radar_avail && ore_dist > 4 PlaceRadarTask.new(self, bot).tap { radar_avail = false } elsif bot.at_hq? && trap_avail && rand(10) < 0 && nearest_ore(bot, min_size: 2) && ore_dist > 4 PlaceTrapTask.new(self, bot).tap { |tsk| @board.decrement_ore(tsk.target, clear: true); trap_avail = false } elsif ore_cell MineOreTask.new(self, bot) else ScanSectorTask.new(self, bot) end end end def clear_tasks @my_bots.each { |bot| bot.task = nil if bot.finished_task? } end # WAIT|MOVE x y|DIG x y|REQUEST item def moves # warn "Explorer: #{explorer.last}" # warn @robots.map(&:last) # warn @items.map(&:last) clear_tasks assign_tasks @my_bots.map(&:next_command) end def to_s # @board.to_s s = '' @items.each do |_, item| if item.is_a? Trap kills = trap_kills(item.pos) s << "#{item.pos} => #{kills}" if kills[:player].size == 1 && kills[:opponent].size.positive? end end s end end # game loop gs = GameState.new loop do gs.read_state warn gs if DEBUG puts gs.moves end
21.061743
127
0.575387
28e78af074749d132eba3fc20c865a7467d47b7a
1,184
class Wellington < Formula desc "Project-focused tool to manage Sass and spriting" homepage "https://getwt.io/" url "https://github.com/wellington/wellington/archive/v1.0.5.tar.gz" sha256 "e2379722849cdd8e5f094849290aacba4b789d4d65c733dec859565c728e7205" license "Apache-2.0" head "https://github.com/wellington/wellington.git" bottle do cellar :any_skip_relocation sha256 "9aaeb3a098cbee88efc4e60d1edbfec242d6b2271f821b4d096fe6acb3d16987" => :catalina sha256 "a49538429713f2f7b979ab533d4231de84140d9e4e63b5658941552c1c99117a" => :mojave sha256 "53a61eeebc1e787fa7870437ce089276c5f1daad26430078e988d1b6aa50c7b8" => :high_sierra sha256 "4475484cb2378a741c1cfdcdabc95b5ea175202c1b78ce2481d23aff35fb3da4" => :x86_64_linux end depends_on "go" => :build def install system "go", "build", "-ldflags", "-X github.com/wellington/wellington/version.Version=#{version}", "-o", bin/"wt", "wt/main.go" end test do s = "div { p { color: red; } }" expected = <<~EOS /* line 1, stdin */ div p { color: red; } EOS assert_equal expected, pipe_output("#{bin}/wt --comment", s, 0) end end
33.828571
94
0.709459
08f4c97f8ceb5907c4ea20954e0993466295e0ca
1,110
# # SonarQube, open source software quality management tool. # Copyright (C) 2008-2014 SonarSource # mailto:contact AT sonarsource DOT com # # SonarQube is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 3 of the License, or (at your option) any later version. # # SonarQube is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # # Sonar 2.12 # class AddIndexOnDependenciesProjectSnapshot < ActiveRecord::Migration def self.up begin add_index('dependencies', 'project_snapshot_id', :name => 'deps_prj_sid') rescue # already exists end end end
31.714286
79
0.752252
ed073df28a1fca7551589b7a29cbc935c14eb849
83
json.extract! @grade, :id, :studentID, :courseID, :value, :created_at, :updated_at
41.5
82
0.722892
910205a9e61b7ba5257a92d6491b5caca98b3a70
826
# coding: utf-8 class PDF::Reader module WidthCalculator # Type0 (or Composite) fonts are a "root font" that rely on a "descendant font" # to do the heavy lifting. The "descendant font" is a CID-Keyed font. # see Section 9.7.1, PDF 32000-1:2008, pp 267 # so if we are calculating a Type0 font width, we just pass off to # the descendant font class TypeZero def initialize(font) @font = font @descendant_font = @font.descendantfonts.first end def glyph_width(code_point) return 0 if code_point.nil? || code_point < 0 @descendant_font.glyph_width(code_point).to_f end def glyph_height(code_point) return 0 if code_point.nil? || code_point < 0 @descendant_font.glyph_height(code_point).to_f end end end end
26.645161
83
0.657385
ab55f0e34d83ee0f1d2eb432610f05255bc0f0cf
1,346
class Tmate < Formula desc "Instant terminal sharing" homepage "https://tmate.io/" url "https://github.com/tmate-io/tmate/archive/2.4.0.tar.gz" sha256 "62b61eb12ab394012c861f6b48ba0bc04ac8765abca13bdde5a4d9105cb16138" license "ISC" head "https://github.com/tmate-io/tmate.git" bottle do cellar :any sha256 "215c8724caffc137265dc5fa565bed563b5bd8d046b0e54addcf1628d60a9268" => :big_sur sha256 "d92025cef2400ab0fcb0f8efa5866e180fff73486db2e73f4e77b5d1afba5d97" => :arm64_big_sur sha256 "a278bcb401068bed2434ec48bfb059a86d793a6daa4877574ac0ed7168cb1ebc" => :catalina sha256 "7e5158460b898422b4c6e84390d0e8446e2ad52789a30f9942288c5c32acc8a1" => :mojave sha256 "0f4f06d0ab7715adc7f6d33cf7d3c08fd057e7f038a666b360ac4ad6a3449ad9" => :high_sierra end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build depends_on "pkg-config" => :build depends_on "libevent" depends_on "libssh" depends_on "msgpack" uses_from_macos "ncurses" def install system "sh", "autogen.sh" ENV.append "LDFLAGS", "-lresolv" system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}", "--sysconfdir=#{etc}" system "make", "install" end test do system "#{bin}/tmate", "-V" end end
32.047619
95
0.71471
6a3eb324a17143d14019554ed2d9c4b358a83861
400
module Notifiers class Slack def self.notify(text:, username: 'Informative Parrot', emoji: ':gentleman_parrot:', channel: '#taxonomy') message_payload = { username: username, icon_emoji: emoji, text: text, mrkdwn: true, channel: channel, } HTTP.post(ENV["BADGER_SLACK_WEBHOOK_URL"], body: JSON.dump(message_payload)) end end end
25
109
0.63