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
f7ef0ba02ca50e7707186adad4fb3e10180d3686
170
require 'jquery/modal/filters/ajax_request_filters' module Jquery module Filters end end ActiveSupport.on_load(:action_controller) do include Jquery::Filters end
15.454545
51
0.811765
4a1037a53fc87dea4778df710215deb38cc78c9f
241
# frozen_string_literal: true title 'Chruby should be installable and available' describe file('/usr/local/share/chruby/chruby.sh') do it { should exist } end describe file('/usr/local/share/chruby/auto.sh') do it { should exist } end
21.909091
53
0.742739
91a148e471b342b9c590de86eafce61148bd3bf5
713
require 'trb1-representable/binding' module Trb1 module Representable module Hash class Binding < Representable::Binding def self.build_for(definition) return Collection.new(definition) if definition.array? new(definition) end def read(hash, as) hash.has_key?(as) ? hash[as] : FragmentNotFound end def write(hash, fragment, as) hash[as] = fragment end def serialize_method :to_hash end def deserialize_method :from_hash end class Collection < self include Trb1::Representable::Binding::Collection end end end end end
20.371429
64
0.584853
ac606c9d8f81303ec3b46855b772f24f1311cc0f
33,179
# frozen_string_literal: true require "abstract_unit" require "active_support/log_subscriber/test_helper" require "active_support/messages/rotation_configuration" # common controller actions module RequestForgeryProtectionActions def index render inline: "<%= form_tag('/') {} %>" end def show_button render inline: "<%= button_to('New', '/') %>" end def unsafe render plain: "pwn" end def meta render inline: "<%= csrf_meta_tags %>" end def form_for_remote render inline: "<%= form_for(:some_resource, :remote => true ) {} %>" end def form_for_remote_with_token render inline: "<%= form_for(:some_resource, :remote => true, :authenticity_token => true ) {} %>" end def form_for_with_token render inline: "<%= form_for(:some_resource, :authenticity_token => true ) {} %>" end def form_for_remote_with_external_token render inline: "<%= form_for(:some_resource, :remote => true, :authenticity_token => 'external_token') {} %>" end def form_with_remote render inline: "<%= form_with(scope: :some_resource) {} %>" end def form_with_remote_with_token render inline: "<%= form_with(scope: :some_resource, authenticity_token: true) {} %>" end def form_with_local_with_token render inline: "<%= form_with(scope: :some_resource, local: true, authenticity_token: true) {} %>" end def form_with_remote_with_external_token render inline: "<%= form_with(scope: :some_resource, authenticity_token: 'external_token') {} %>" end def same_origin_js render js: "foo();" end def negotiate_same_origin respond_to do |format| format.js { same_origin_js } end end def cross_origin_js same_origin_js end def negotiate_cross_origin negotiate_same_origin end end # sample controllers class RequestForgeryProtectionControllerUsingResetSession < ActionController::Base include RequestForgeryProtectionActions protect_from_forgery only: %w(index meta same_origin_js negotiate_same_origin), with: :reset_session end class RequestForgeryProtectionControllerUsingException < ActionController::Base include RequestForgeryProtectionActions protect_from_forgery only: %w(index meta same_origin_js negotiate_same_origin), with: :exception end class RequestForgeryProtectionControllerUsingNullSession < ActionController::Base protect_from_forgery with: :null_session def signed cookies.signed[:foo] = "bar" head :ok end def encrypted cookies.encrypted[:foo] = "bar" head :ok end def try_to_reset_session reset_session head :ok end end class PrependProtectForgeryBaseController < ActionController::Base before_action :custom_action attr_accessor :called_callbacks def index render inline: "OK" end private def add_called_callback(name) @called_callbacks ||= [] @called_callbacks << name end def custom_action add_called_callback("custom_action") end def verify_authenticity_token add_called_callback("verify_authenticity_token") end end class FreeCookieController < RequestForgeryProtectionControllerUsingResetSession self.allow_forgery_protection = false def index render inline: "<%= form_tag('/') {} %>" end def show_button render inline: "<%= button_to('New', '/') %>" end end class CustomAuthenticityParamController < RequestForgeryProtectionControllerUsingResetSession def form_authenticity_param "foobar" end end class PerFormTokensController < ActionController::Base protect_from_forgery with: :exception self.per_form_csrf_tokens = true def index render inline: "<%= form_tag (params[:form_path] || '/per_form_tokens/post_one'), method: params[:form_method] %>" end def button_to render inline: "<%= button_to 'Button', (params[:form_path] || '/per_form_tokens/post_one'), method: params[:form_method] %>" end def post_one render plain: "" end def post_two render plain: "" end end class SkipProtectionController < ActionController::Base include RequestForgeryProtectionActions protect_from_forgery with: :exception skip_forgery_protection if: :skip_requested attr_accessor :skip_requested end # common test methods module RequestForgeryProtectionTests def setup @token = Base64.strict_encode64("railstestrailstestrailstestrails") @old_request_forgery_protection_token = ActionController::Base.request_forgery_protection_token ActionController::Base.request_forgery_protection_token = :custom_authenticity_token end def teardown ActionController::Base.request_forgery_protection_token = @old_request_forgery_protection_token end def test_should_render_form_with_token_tag @controller.stub :form_authenticity_token, @token do assert_not_blocked do get :index end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", @token end end def test_should_render_button_to_with_token_tag @controller.stub :form_authenticity_token, @token do assert_not_blocked do get :show_button end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", @token end end def test_should_render_form_without_token_tag_if_remote assert_not_blocked do get :form_for_remote end assert_no_match(/authenticity_token/, response.body) end def test_should_render_form_with_token_tag_if_remote_and_embedding_token_is_on original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms begin ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true assert_not_blocked do get :form_for_remote end assert_match(/authenticity_token/, response.body) ensure ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original end end def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested_and_embedding_is_on original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms begin ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true assert_not_blocked do get :form_for_remote_with_external_token end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", "external_token" ensure ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original end end def test_should_render_form_with_token_tag_if_remote_and_external_authenticity_token_requested assert_not_blocked do get :form_for_remote_with_external_token end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", "external_token" end def test_should_render_form_with_token_tag_if_remote_and_authenticity_token_requested @controller.stub :form_authenticity_token, @token do assert_not_blocked do get :form_for_remote_with_token end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", @token end end def test_should_render_form_with_token_tag_with_authenticity_token_requested @controller.stub :form_authenticity_token, @token do assert_not_blocked do get :form_for_with_token end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", @token end end def test_should_render_form_with_with_token_tag_if_remote assert_not_blocked do get :form_with_remote end assert_match(/authenticity_token/, response.body) end def test_should_render_form_with_without_token_tag_if_remote_and_embedding_token_is_off original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms begin ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = false assert_not_blocked do get :form_with_remote end assert_no_match(/authenticity_token/, response.body) ensure ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original end end def test_should_render_form_with_with_token_tag_if_remote_and_external_authenticity_token_requested_and_embedding_is_on original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms begin ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true assert_not_blocked do get :form_with_remote_with_external_token end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", "external_token" ensure ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original end end def test_should_render_form_with_with_token_tag_if_remote_and_external_authenticity_token_requested assert_not_blocked do get :form_with_remote_with_external_token end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", "external_token" end def test_should_render_form_with_with_token_tag_if_remote_and_authenticity_token_requested @controller.stub :form_authenticity_token, @token do assert_not_blocked do get :form_with_remote_with_token end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", @token end end def test_should_render_form_with_with_token_tag_with_authenticity_token_requested @controller.stub :form_authenticity_token, @token do assert_not_blocked do get :form_with_local_with_token end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", @token end end def test_should_render_form_with_with_token_tag_if_remote_and_embedding_token_is_on original = ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms begin ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = true @controller.stub :form_authenticity_token, @token do assert_not_blocked do get :form_with_remote end end assert_select "form>input[name=?][value=?]", "custom_authenticity_token", @token ensure ActionView::Helpers::FormTagHelper.embed_authenticity_token_in_remote_forms = original end end def test_should_allow_get assert_not_blocked { get :index } end def test_should_allow_head assert_not_blocked { head :index } end def test_should_allow_post_without_token_on_unsafe_action assert_not_blocked { post :unsafe } end def test_should_not_allow_post_without_token assert_blocked { post :index } end def test_should_not_allow_post_without_token_irrespective_of_format assert_blocked { post :index, format: "xml" } end def test_should_not_allow_patch_without_token assert_blocked { patch :index } end def test_should_not_allow_put_without_token assert_blocked { put :index } end def test_should_not_allow_delete_without_token assert_blocked { delete :index } end def test_should_not_allow_xhr_post_without_token assert_blocked { post :index, xhr: true } end def test_should_allow_post_with_token session[:_csrf_token] = @token @controller.stub :form_authenticity_token, @token do assert_not_blocked { post :index, params: { custom_authenticity_token: @token } } end end def test_should_allow_patch_with_token session[:_csrf_token] = @token @controller.stub :form_authenticity_token, @token do assert_not_blocked { patch :index, params: { custom_authenticity_token: @token } } end end def test_should_allow_put_with_token session[:_csrf_token] = @token @controller.stub :form_authenticity_token, @token do assert_not_blocked { put :index, params: { custom_authenticity_token: @token } } end end def test_should_allow_delete_with_token session[:_csrf_token] = @token @controller.stub :form_authenticity_token, @token do assert_not_blocked { delete :index, params: { custom_authenticity_token: @token } } end end def test_should_allow_post_with_token_in_header session[:_csrf_token] = @token @request.env["HTTP_X_CSRF_TOKEN"] = @token assert_not_blocked { post :index } end def test_should_allow_delete_with_token_in_header session[:_csrf_token] = @token @request.env["HTTP_X_CSRF_TOKEN"] = @token assert_not_blocked { delete :index } end def test_should_allow_patch_with_token_in_header session[:_csrf_token] = @token @request.env["HTTP_X_CSRF_TOKEN"] = @token assert_not_blocked { patch :index } end def test_should_allow_put_with_token_in_header session[:_csrf_token] = @token @request.env["HTTP_X_CSRF_TOKEN"] = @token assert_not_blocked { put :index } end def test_should_allow_post_with_origin_checking_and_correct_origin forgery_protection_origin_check do session[:_csrf_token] = @token @controller.stub :form_authenticity_token, @token do assert_not_blocked do @request.set_header "HTTP_ORIGIN", "http://test.host" post :index, params: { custom_authenticity_token: @token } end end end end def test_should_allow_post_with_origin_checking_and_no_origin forgery_protection_origin_check do session[:_csrf_token] = @token @controller.stub :form_authenticity_token, @token do assert_not_blocked do post :index, params: { custom_authenticity_token: @token } end end end end def test_should_raise_for_post_with_null_origin forgery_protection_origin_check do session[:_csrf_token] = @token @controller.stub :form_authenticity_token, @token do exception = assert_raises(ActionController::InvalidAuthenticityToken) do @request.set_header "HTTP_ORIGIN", "null" post :index, params: { custom_authenticity_token: @token } end assert_match "The browser returned a 'null' origin for a request", exception.message end end end def test_should_block_post_with_origin_checking_and_wrong_origin old_logger = ActionController::Base.logger logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new ActionController::Base.logger = logger forgery_protection_origin_check do session[:_csrf_token] = @token @controller.stub :form_authenticity_token, @token do assert_blocked do @request.set_header "HTTP_ORIGIN", "http://bad.host" post :index, params: { custom_authenticity_token: @token } end end end assert_match( "HTTP Origin header (http://bad.host) didn't match request.base_url (http://test.host)", logger.logged(:warn).last ) ensure ActionController::Base.logger = old_logger end def test_should_warn_on_missing_csrf_token old_logger = ActionController::Base.logger logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new ActionController::Base.logger = logger begin assert_blocked { post :index } assert_equal 1, logger.logged(:warn).size assert_match(/CSRF token authenticity/, logger.logged(:warn).last) ensure ActionController::Base.logger = old_logger end end def test_should_not_warn_if_csrf_logging_disabled old_logger = ActionController::Base.logger logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new ActionController::Base.logger = logger ActionController::Base.log_warning_on_csrf_failure = false begin assert_blocked { post :index } assert_equal 0, logger.logged(:warn).size ensure ActionController::Base.logger = old_logger ActionController::Base.log_warning_on_csrf_failure = true end end def test_should_only_allow_same_origin_js_get_with_xhr_header assert_cross_origin_blocked { get :same_origin_js } assert_cross_origin_blocked { get :same_origin_js, format: "js" } assert_cross_origin_blocked do @request.accept = "text/javascript" get :negotiate_same_origin end assert_cross_origin_not_blocked { get :same_origin_js, xhr: true } assert_cross_origin_not_blocked { get :same_origin_js, xhr: true, format: "js" } assert_cross_origin_not_blocked do @request.accept = "text/javascript" get :negotiate_same_origin, xhr: true end end def test_should_warn_on_not_same_origin_js old_logger = ActionController::Base.logger logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new ActionController::Base.logger = logger begin assert_cross_origin_blocked { get :same_origin_js } assert_equal 1, logger.logged(:warn).size assert_match(/<script> tag on another site requested protected JavaScript/, logger.logged(:warn).last) ensure ActionController::Base.logger = old_logger end end def test_should_not_warn_if_csrf_logging_disabled_and_not_same_origin_js old_logger = ActionController::Base.logger logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new ActionController::Base.logger = logger ActionController::Base.log_warning_on_csrf_failure = false begin assert_cross_origin_blocked { get :same_origin_js } assert_equal 0, logger.logged(:warn).size ensure ActionController::Base.logger = old_logger ActionController::Base.log_warning_on_csrf_failure = true end end # Allow non-GET requests since GET is all a remote <script> tag can muster. def test_should_allow_non_get_js_without_xhr_header session[:_csrf_token] = @token assert_cross_origin_not_blocked { post :same_origin_js, params: { custom_authenticity_token: @token } } assert_cross_origin_not_blocked { post :same_origin_js, params: { format: "js", custom_authenticity_token: @token } } assert_cross_origin_not_blocked do @request.accept = "text/javascript" post :negotiate_same_origin, params: { custom_authenticity_token: @token } end end def test_should_only_allow_cross_origin_js_get_without_xhr_header_if_protection_disabled assert_cross_origin_not_blocked { get :cross_origin_js } assert_cross_origin_not_blocked { get :cross_origin_js, format: "js" } assert_cross_origin_not_blocked do @request.accept = "text/javascript" get :negotiate_cross_origin end assert_cross_origin_not_blocked { get :cross_origin_js, xhr: true } assert_cross_origin_not_blocked { get :cross_origin_js, xhr: true, format: "js" } assert_cross_origin_not_blocked do @request.accept = "text/javascript" get :negotiate_cross_origin, xhr: true end end def test_should_not_raise_error_if_token_is_not_a_string assert_blocked do patch :index, params: { custom_authenticity_token: { foo: "bar" } } end end def assert_blocked session[:something_like_user_id] = 1 yield assert_nil session[:something_like_user_id], "session values are still present" assert_response :success end def assert_not_blocked assert_nothing_raised { yield } assert_response :success end def assert_cross_origin_blocked assert_raises(ActionController::InvalidCrossOriginRequest) do yield end end def assert_cross_origin_not_blocked assert_not_blocked { yield } end def forgery_protection_origin_check old_setting = ActionController::Base.forgery_protection_origin_check ActionController::Base.forgery_protection_origin_check = true begin yield ensure ActionController::Base.forgery_protection_origin_check = old_setting end end end # OK let's get our test on class RequestForgeryProtectionControllerUsingResetSessionTest < ActionController::TestCase include RequestForgeryProtectionTests test "should emit a csrf-param meta tag and a csrf-token meta tag" do @controller.stub :form_authenticity_token, @token + "<=?" do get :meta assert_select "meta[name=?][content=?]", "csrf-param", "custom_authenticity_token" assert_select "meta[name=?]", "csrf-token" regexp = "#{@token}&lt;=\?" assert_match(/#{regexp}/, @response.body) end end end class RequestForgeryProtectionControllerUsingNullSessionTest < ActionController::TestCase class NullSessionDummyKeyGenerator def generate_key(secret, length = nil) "03312270731a2ed0d11ed091c2338a06" end end def setup @request.env[ActionDispatch::Cookies::GENERATOR_KEY] = NullSessionDummyKeyGenerator.new @request.env[ActionDispatch::Cookies::COOKIES_ROTATIONS] = ActiveSupport::Messages::RotationConfiguration.new end test "should allow to set signed cookies" do post :signed assert_response :ok end test "should allow to set encrypted cookies" do post :encrypted assert_response :ok end test "should allow reset_session" do post :try_to_reset_session assert_response :ok end end class RequestForgeryProtectionControllerUsingExceptionTest < ActionController::TestCase include RequestForgeryProtectionTests def assert_blocked assert_raises(ActionController::InvalidAuthenticityToken) do yield end end end class PrependProtectForgeryBaseControllerTest < ActionController::TestCase PrependTrueController = Class.new(PrependProtectForgeryBaseController) do protect_from_forgery prepend: true end PrependFalseController = Class.new(PrependProtectForgeryBaseController) do protect_from_forgery prepend: false end PrependDefaultController = Class.new(PrependProtectForgeryBaseController) do protect_from_forgery end def test_verify_authenticity_token_is_prepended @controller = PrependTrueController.new get :index expected_callback_order = ["verify_authenticity_token", "custom_action"] assert_equal(expected_callback_order, @controller.called_callbacks) end def test_verify_authenticity_token_is_not_prepended @controller = PrependFalseController.new get :index expected_callback_order = ["custom_action", "verify_authenticity_token"] assert_equal(expected_callback_order, @controller.called_callbacks) end def test_verify_authenticity_token_is_not_prepended_by_default @controller = PrependDefaultController.new get :index expected_callback_order = ["custom_action", "verify_authenticity_token"] assert_equal(expected_callback_order, @controller.called_callbacks) end end class FreeCookieControllerTest < ActionController::TestCase def setup @controller = FreeCookieController.new @token = "cf50faa3fe97702ca1ae" super end def test_should_not_render_form_with_token_tag SecureRandom.stub :base64, @token do get :index assert_select "form>div>input[name=?][value=?]", "authenticity_token", @token, false end end def test_should_not_render_button_to_with_token_tag SecureRandom.stub :base64, @token do get :show_button assert_select "form>div>input[name=?][value=?]", "authenticity_token", @token, false end end def test_should_allow_all_methods_without_token SecureRandom.stub :base64, @token do [:post, :patch, :put, :delete].each do |method| assert_nothing_raised { send(method, :index) } end end end test "should not emit a csrf-token meta tag" do SecureRandom.stub :base64, @token do get :meta assert_predicate @response.body, :blank? end end end class CustomAuthenticityParamControllerTest < ActionController::TestCase def setup super @old_logger = ActionController::Base.logger @logger = ActiveSupport::LogSubscriber::TestHelper::MockLogger.new @token = Base64.strict_encode64(SecureRandom.random_bytes(32)) @old_request_forgery_protection_token = ActionController::Base.request_forgery_protection_token ActionController::Base.request_forgery_protection_token = @token end def teardown ActionController::Base.request_forgery_protection_token = @old_request_forgery_protection_token super end def test_should_not_warn_if_form_authenticity_param_matches_form_authenticity_token ActionController::Base.logger = @logger begin @controller.stub :valid_authenticity_token?, :true do post :index, params: { custom_token_name: "foobar" } assert_equal 0, @logger.logged(:warn).size end ensure ActionController::Base.logger = @old_logger end end def test_should_warn_if_form_authenticity_param_does_not_match_form_authenticity_token ActionController::Base.logger = @logger begin post :index, params: { custom_token_name: "bazqux" } assert_equal 1, @logger.logged(:warn).size ensure ActionController::Base.logger = @old_logger end end end class PerFormTokensControllerTest < ActionController::TestCase def setup @old_request_forgery_protection_token = ActionController::Base.request_forgery_protection_token ActionController::Base.request_forgery_protection_token = :custom_authenticity_token end def teardown ActionController::Base.request_forgery_protection_token = @old_request_forgery_protection_token end def test_per_form_token_is_same_size_as_global_token get :index expected = ActionController::RequestForgeryProtection::AUTHENTICITY_TOKEN_LENGTH actual = @controller.send(:per_form_csrf_token, session, "/path", "post").size assert_equal expected, actual end def test_accepts_token_for_correct_path_and_method get :index form_token = assert_presence_and_fetch_form_csrf_token assert_matches_session_token_on_server form_token # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one" assert_nothing_raised do post :post_one, params: { custom_authenticity_token: form_token } end assert_response :success end def test_rejects_token_for_incorrect_path get :index form_token = assert_presence_and_fetch_form_csrf_token assert_matches_session_token_on_server form_token # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_two" assert_raises(ActionController::InvalidAuthenticityToken) do post :post_two, params: { custom_authenticity_token: form_token } end end def test_rejects_token_for_incorrect_method get :index form_token = assert_presence_and_fetch_form_csrf_token assert_matches_session_token_on_server form_token # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one" assert_raises(ActionController::InvalidAuthenticityToken) do patch :post_one, params: { custom_authenticity_token: form_token } end end def test_rejects_token_for_incorrect_method_button_to get :button_to, params: { form_method: "delete" } form_token = assert_presence_and_fetch_form_csrf_token assert_matches_session_token_on_server form_token, "delete" # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one" assert_raises(ActionController::InvalidAuthenticityToken) do patch :post_one, params: { custom_authenticity_token: form_token } end end test "Accepts proper token for implicit post method on button_to tag" do get :button_to form_token = assert_presence_and_fetch_form_csrf_token assert_matches_session_token_on_server form_token, "post" # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one" assert_nothing_raised do post :post_one, params: { custom_authenticity_token: form_token } end end %w{delete post patch}.each do |verb| test "Accepts proper token for #{verb} method on button_to tag" do get :button_to, params: { form_method: verb } form_token = assert_presence_and_fetch_form_csrf_token assert_matches_session_token_on_server form_token, verb # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one" assert_nothing_raised do send verb, :post_one, params: { custom_authenticity_token: form_token } end end end def test_accepts_global_csrf_token get :index token = @controller.send(:form_authenticity_token) # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one" assert_nothing_raised do post :post_one, params: { custom_authenticity_token: token } end assert_response :success end def test_does_not_return_old_csrf_token get :index token = @controller.send(:form_authenticity_token) unmasked_token = @controller.send(:unmask_token, Base64.urlsafe_decode64(token)) assert_not_equal @controller.send(:real_csrf_token, session), unmasked_token end def test_returns_hmacd_token get :index token = @controller.send(:form_authenticity_token) unmasked_token = @controller.send(:unmask_token, Base64.urlsafe_decode64(token)) assert_equal @controller.send(:global_csrf_token, session), unmasked_token end def test_accepts_old_csrf_token get :index non_hmac_token = @controller.send(:mask_token, @controller.send(:real_csrf_token, session)) # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one" assert_nothing_raised do post :post_one, params: { custom_authenticity_token: non_hmac_token } end assert_response :success end def test_ignores_params get :index, params: { form_path: "/per_form_tokens/post_one?foo=bar" } form_token = assert_presence_and_fetch_form_csrf_token assert_matches_session_token_on_server form_token # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one?foo=baz" assert_nothing_raised do post :post_one, params: { custom_authenticity_token: form_token, baz: "foo" } end assert_response :success end def test_ignores_trailing_slash_during_generation get :index, params: { form_path: "/per_form_tokens/post_one/" } form_token = assert_presence_and_fetch_form_csrf_token # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one" assert_nothing_raised do post :post_one, params: { custom_authenticity_token: form_token } end assert_response :success end def test_ignores_origin_during_generation get :index, params: { form_path: "https://example.com/per_form_tokens/post_one/" } form_token = assert_presence_and_fetch_form_csrf_token # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one" assert_nothing_raised do post :post_one, params: { custom_authenticity_token: form_token } end assert_response :success end def test_ignores_trailing_slash_during_validation get :index form_token = assert_presence_and_fetch_form_csrf_token # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one/" assert_nothing_raised do post :post_one, params: { custom_authenticity_token: form_token } end assert_response :success end def test_method_is_case_insensitive get :index, params: { form_method: "POST" } form_token = assert_presence_and_fetch_form_csrf_token # This is required because PATH_INFO isn't reset between requests. @request.env["PATH_INFO"] = "/per_form_tokens/post_one/" assert_nothing_raised do post :post_one, params: { custom_authenticity_token: form_token } end assert_response :success end private def assert_presence_and_fetch_form_csrf_token assert_select 'input[name="custom_authenticity_token"]' do |input| form_csrf_token = input.first["value"] assert_not_nil form_csrf_token return form_csrf_token end end def assert_matches_session_token_on_server(form_token, method = "post") actual = @controller.send(:unmask_token, Base64.strict_decode64(form_token)) expected = @controller.send(:per_form_csrf_token, session, "/per_form_tokens/post_one", method) assert_equal expected, actual end end class SkipProtectionControllerTest < ActionController::TestCase def test_should_not_allow_post_without_token_when_not_skipping @controller.skip_requested = false assert_blocked { post :index } end def test_should_allow_post_without_token_when_skipping @controller.skip_requested = true assert_not_blocked { post :index } end def assert_blocked assert_raises(ActionController::InvalidAuthenticityToken) do yield end end def assert_not_blocked assert_nothing_raised { yield } assert_response :success end end
31.689589
129
0.756322
bb0971993c2ddf455e4b17da51e1e408e2c70fc7
305
# frozen_string_literal: true class BranchDecorator < Draper::Decorator delegate_all def as_json(*) { id: id, name: name, order_id: order_id, path: path, created_at: created_at.iso8601, updated_at: updated_at.iso8601, count: srpms.count } end end
16.944444
41
0.632787
e80b219b8a481071e8c2ee679e31a73c03fa2195
364
class CreateCatalogues < ActiveRecord::Migration def change create_table :catalogues do |t| t.string :name t.integer :parent_id t.integer :lft, default: 0 t.integer :rgt, default: 0 t.integer :depth, default: 0 t.timestamps end add_index :catalogues, :parent_id add_index :catalogues, [:lft, :rgt] end end
21.411765
48
0.648352
627cff0925663471da941c16542a79e83e38400e
2,342
require "rails_helper" class OrdersController < ApplicationController end describe OrdersController, type: :controller do shared_examples "a payload setter" do |payload_type| describe "#set_#{payload_type}_payload" do it "sets the #{payload_type}_payload to an array of the passed arguments" do controller.send("set_#{payload_type}_payload", "foo") expect(assigns("#{payload_type}_payload")).to eq(', "foo"') controller.send("set_#{payload_type}_payload", "foo", "bar", "baz") expect(assigns("#{payload_type}_payload")).to eq(', "foo", "bar", "baz"') controller.send("set_#{payload_type}_payload", ["foo", "bar", "baz"]) expect(assigns("#{payload_type}_payload")).to eq(', ["foo","bar","baz"]') end end end it_behaves_like "a payload setter", :action it_behaves_like "a payload setter", :controller it_behaves_like "a payload setter", :app describe "#jskit" do let(:view_context) { controller.view_context } before do controller.action_name = "action" end it "returns a script tag with the global event and the controller event" do app_event = "App.Dispatcher.trigger(\"controller:application:all\", \"baz\");" controller_event = "App.Dispatcher.trigger(\"controller:orders:all\", \"bar\");" action_event = "App.Dispatcher.trigger(\"controller:orders:action\", \"foo\");" expected_js = view_context.javascript_tag([app_event, controller_event, action_event].join("\n")) controller.set_action_payload("foo") controller.set_controller_payload("bar") controller.set_app_payload("baz") expect(controller.jskit).to eq(expected_js) end it "is exposed as a helper method" do expect(controller.view_context.jskit).to eq(controller.jskit) end it "namespaces events based on the config" do app_event = "App.Dispatcher.trigger(\"some_namespace:controller:application:all\");" controller_event = "App.Dispatcher.trigger(\"some_namespace:controller:orders:all\");" action_event = "App.Dispatcher.trigger(\"some_namespace:controller:orders:action\");" expected_js = view_context.javascript_tag([app_event, controller_event, action_event].join("\n")) expect(controller.jskit(namespace: "some_namespace")).to eq(expected_js) end end end
39.033333
103
0.694278
1d1ed3f329e7c9c21bd0eb6cbddc2ec35fbc6304
2,051
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2021_05_02_223438) do create_table "companies", force: :cascade do |t| t.string "name" t.string "ticker_symbol" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "risk_factor" end create_table "cryptocurrencies", force: :cascade do |t| t.string "name" t.string "ticker_symbol" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "cryptocurrency_prices", force: :cascade do |t| t.decimal "price" t.datetime "captured_at" t.integer "cryptocurrency_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["cryptocurrency_id"], name: "index_cryptocurrency_prices_on_cryptocurrency_id" end create_table "stock_prices", force: :cascade do |t| t.decimal "price" t.datetime "captured_at" t.integer "company_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["company_id"], name: "index_stock_prices_on_company_id" end add_foreign_key "cryptocurrency_prices", "cryptocurrencies" add_foreign_key "stock_prices", "companies" end
40.215686
91
0.740614
91aa14fab33c1af0dadc96ff9e4cfc99fe977227
1,369
class Mkcert < Formula desc "Simple tool to make locally trusted development certificates" homepage "https://github.com/FiloSottile/mkcert" url "https://github.com/FiloSottile/mkcert/archive/v1.4.1.tar.gz" sha256 "b539e11ac0a06ff4831b76134b8d391610287cf8e56b002365b3786b96e0acbe" bottle do cellar :any_skip_relocation sha256 "b7cc76858dc35c6d3aabb07242ab6f5f079c4cb85deea4a9f66114528980914b" => :catalina sha256 "9100c7f044d91e6ca0c483ed572217de28daa34c04fa6e2a130116175ba162e9" => :mojave sha256 "f7d3255bc7f40e66bc75fd6ebfacc6b02c91514f412de9cf4b85b0d332bc4931" => :high_sierra end depends_on "go" => :build def install ENV["GOPATH"] = HOMEBREW_CACHE/"go_cache" (buildpath/"src/github.com/FiloSottile/mkcert").install buildpath.children cd "src/github.com/FiloSottile/mkcert" do system "go", "build", "-o", bin/"mkcert", "-ldflags", "-X main.Version=v#{version}" prefix.install_metafiles end end test do ENV["CAROOT"] = testpath system bin/"mkcert", "brew.test" assert_predicate testpath/"brew.test.pem", :exist? assert_predicate testpath/"brew.test-key.pem", :exist? output = (testpath/"brew.test.pem").read assert_match "-----BEGIN CERTIFICATE-----", output output = (testpath/"brew.test-key.pem").read assert_match "-----BEGIN PRIVATE KEY-----", output end end
37
93
0.73046
5d7957d1e8a63b8654f6e149143d93575de79940
573
# frozen_string_literal: true require 'simplecov' unless ENV['CI'] require 'capybara' require 'capybara/dsl' $LOAD_PATH << './lib' $LOAD_PATH << './features/support' require 'site_prism' require_relative 'fixtures/all' Capybara.default_max_wait_time = 0 RSpec.configure do |rspec| rspec.default_formatter = :documentation rspec.after(:each) do SitePrism.configure do |config| config.enable_logging = false end end end class MyTestApp def call(_env) [200, { 'Content-Length' => '9' }, ['MyTestApp']] end end Capybara.app = MyTestApp.new
17.363636
53
0.710297
798986e865b2d840556c96e9243c49d5c2c5b776
107
# frozen_string_literal: true FactoryBot.define do factory :field_type do name { 'text' } end end
13.375
29
0.71028
6a0b4a8af20edc465bed3d7ef6d6654bfa3d07b6
2,017
# -*- encoding: utf-8 -*- # stub: ffi 1.15.5 ruby lib # stub: ext/ffi_c/extconf.rb Gem::Specification.new do |s| s.name = "ffi".freeze s.version = "1.15.5" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.metadata = { "bug_tracker_uri" => "https://github.com/ffi/ffi/issues", "changelog_uri" => "https://github.com/ffi/ffi/blob/master/CHANGELOG.md", "documentation_uri" => "https://github.com/ffi/ffi/wiki", "mailing_list_uri" => "http://groups.google.com/group/ruby-ffi", "source_code_uri" => "https://github.com/ffi/ffi/", "wiki_uri" => "https://github.com/ffi/ffi/wiki" } if s.respond_to? :metadata= s.require_paths = ["lib".freeze] s.authors = ["Wayne Meissner".freeze] s.date = "2022-01-10" s.description = "Ruby FFI library".freeze s.email = "[email protected]".freeze s.extensions = ["ext/ffi_c/extconf.rb".freeze] s.files = ["ext/ffi_c/extconf.rb".freeze] s.homepage = "https://github.com/ffi/ffi/wiki".freeze s.licenses = ["BSD-3-Clause".freeze] s.rdoc_options = ["--exclude=ext/ffi_c/.*\\.o$".freeze, "--exclude=ffi_c\\.(bundle|so)$".freeze] s.required_ruby_version = Gem::Requirement.new(">= 2.3".freeze) s.rubygems_version = "3.3.11".freeze s.summary = "Ruby FFI".freeze s.installed_by_version = "3.3.11" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 4 end if s.respond_to? :add_runtime_dependency then s.add_development_dependency(%q<rake>.freeze, ["~> 13.0"]) s.add_development_dependency(%q<rake-compiler>.freeze, ["~> 1.0"]) s.add_development_dependency(%q<rake-compiler-dock>.freeze, ["~> 1.0"]) s.add_development_dependency(%q<rspec>.freeze, ["~> 2.14.1"]) else s.add_dependency(%q<rake>.freeze, ["~> 13.0"]) s.add_dependency(%q<rake-compiler>.freeze, ["~> 1.0"]) s.add_dependency(%q<rake-compiler-dock>.freeze, ["~> 1.0"]) s.add_dependency(%q<rspec>.freeze, ["~> 2.14.1"]) end end
46.906977
401
0.676748
e2e1cf0ea69e007eaf260a8a85f3245fa93b6b79
11,213
#!/usr/bin/env ruby # # Mapping demo: Outbound, from inhouse to EANCOM # # Inhouse format: GS1 Germany's WebEDI ASCII interface for ORDERS # Output format: EANCOM'02 ORDERS, according to GS1 Germany' # recommendations for application # (EDI-Anwendungsempfehlungen V 2.0 (ORDERS) in EANCOM 2002 S3) # and the general EANCOM 2002 (ORDERS) documentation # Comments: # # Inhouse and output format were selected, because they represent typical # data structures and tasks for users, and because documentation of # these formats is freely available. # # $Id: webedi2eancom.rb,v 1.1 2006/05/28 16:08:48 werntges Exp $ # # Author: Heinz W. Werntges ([email protected]) # # License: This code is put under the Ruby license # # Copyright (c) 2006 Heinz W. Werntges, FH Wiesbaden # # Include statement during test setup: $:.unshift File.join(File.dirname(__FILE__), '..', 'lib') require 'edi4r' require 'edi4r/edifact' # Regular include statements: #require "rubygems" #require_gem "edi4r" #require "edi4r/edifact" class WebEDI_to_EANCOM02_Map_ORDERS include EDI # Mengeneinheit_cvt = {'STK' => 'PCE', 'KG' => 'KGM'} # UNBsender_cvt = {'10' => '4333099000009', # Kaufhof ILN # '1034' => '(C+C ILN)', # '1037' => '(extra ILN)', # '1063' => '(real,- ILN)', # # etc. # } attr_accessor :with_rff_va # # Variable names for header record, derived from original documentation # Adaptations: # lower-case names, no umlaut chars, uniqueness of name (see "ust-id") # def processHeader( line ) bestellung, satzartkennung, iln_lieferanschrift, iln_kaeufer, bestellnummer, releasenummer, iln_lieferant, lieferantennummer, ust_id_lieferant, abteilung_beim_kaeufer, ust_id_kaeufer, iln_rechnungsempfaenger, abteilung_beim_rechnungsempfaenger, ust_id_re, abteilung_der_lieferanschrift, iln_endempfaenger, abteilung_beim_endempfaenger, datum_der_bestellung, lieferdatum_gefordert, pick_up_datum, waehrung, nr_der_werbeaktion, von_um, bis, _others = line.split(';') raise "Header line mismatch: Too many fields" unless _others.nil? # Store for consistency checks at line item level: @unique_document_id=[iln_lieferanschrift, iln_kaeufer, bestellnummer] unb = @ic.header unb.cS002.d0004 = iln_kaeufer unb.cS002.d0007 = 14 unb.cS003.d0010 = iln_lieferant unb.cS003.d0007 = 14 # unb.d0035 = '1' if whatever ... bgm = @msg.new_segment("BGM") bgm.cC002.d1001 = bestellung # expected: '220' bgm.cC106.d1004 = bestellnummer bgm.d1225 = 9 @msg.add(bgm) raise "Mandatory element missing: datum_der_bestellung" if datum_der_bestellung.empty? dtm = @msg.new_segment("DTM") dtm.cC507.d2005 = 137 dtm.cC507.d2380 = datum_der_bestellung dtm.cC507.d2379 = 102 @msg.add(dtm) unless lieferdatum_gefordert.empty? dtm = @msg.new_segment("DTM") dtm.cC507.d2005 = 2 lieferdatum_gefordert =~ /(\d\d\d\d)(\d\d)(\d\d)/ date = $1+$2+$3 # showing off a bit here... if von_um.empty? and bis.empty? dtm.cC507.d2380 = date dtm.cC507.d2379 = 102 elsif bis.empty? raise "Format error in 'von_um'" unless von_um =~ /\d*(\d\d\d\d)$/ dtm.cC507.d2380 = date+$1 dtm.cC507.d2379 = 203 else raise "Format error in 'von_um'" unless von_um =~ /\d*(\d\d\d\d)$/ von = $1 raise "Format error in 'bis'" unless bis =~ /\d*(\d\d\d\d)$/ bis = $1 dtm.cC507.d2380 = date+von+date+bis dtm.cC507.d2379 = 719 end @msg.add(dtm) end unless pick_up_datum.empty? dtm = @msg.new_segment("DTM") dtm.cC507.d2005 = '200' dtm.cC507.d2380 = pick_up_datum dtm.cC507.d2379 = '102' @msg.add(dtm) end unless nr_der_werbeaktion.empty? rff = @msg.new_segment("RFF") cde = rff.cC506 cde.d1153 = 'PD' cde.d1154 = nr_der_werbeaktion @msg.add(rff) end # Use a loop for the NAD group [ [iln_lieferant, 'SU', nil, nil, lieferantennummer, ust_id_lieferant], [iln_kaeufer, 'BY', abteilung_beim_kaeufer, 'PD', nil, ust_id_kaeufer], [iln_rechnungsempfaenger, 'IV', abteilung_beim_rechnungsempfaenger, 'OC', nil, ust_id_re], [iln_lieferanschrift, 'DP', abteilung_der_lieferanschrift, 'DL', nil, nil], [iln_endempfaenger, 'UC', abteilung_beim_endempfaenger, 'GR', nil, nil] ].each do |nad_params| iln, qu, dept, qu_dept, no, ust_id = nad_params raise "Mandatory ILN missing for #{qu}" if iln.nil? or iln.empty? nad = @msg.new_segment("NAD") nad.d3035 = qu cde = nad.cC082 cde.d3039 = iln cde.d3055 = '9' @msg.add(nad) # Special treatment - depending segments - in some cases: if qu=='SU' and no and !no.empty? rff = @msg.new_segment("RFF") cde = rff.cC506 cde.d1153 = 'YC1' cde.d1154 = no @msg.add(rff) end if with_rff_va # ust_id: reserved for INVOIC ?! unless ust_id.nil? rff = @msg.new_segment("RFF") cde = rff.cC506 cde.d1153 = 'VA' cde.d1154 = ust_id @msg.add(rff) end end if dept and !dept.empty? cta = @msg.new_segment("CTA") cta.d3139 = qu_dept cta.cC056.d3413 = dept @msg.add(cta) end end unless waehrung.empty? seg = @msg.new_segment("CUX") cde = seg.aC504.first # [0] cde.d6347 = '2' cde.d6345 = waehrung cde.d6343 = '9' @msg.add(seg) end end def processItem( line ) bestellung, satzartkennung, iln_lieferanschrift, iln_kaeufer, bestellnummer, positionsnummer, ean, artikelbezeichnung, farbe, groesse, lieferantenartikelnummer, kaeuferartikelnummer, bestellmenge, einheit, preisbezugseinheit, ek, vk = line.split(';') # Consistency check if @unique_document_id != [iln_lieferanschrift, iln_kaeufer, bestellnummer] puts @unique_document_id puts [iln_lieferanschrift, iln_kaeufer, bestellnummer] raise "Item does not match header!" end # LIN lin = @msg.new_segment("LIN") lin.d1082 = positionsnummer lin.cC212.d7140 = ean lin.cC212.d7143 = "SRV" unless ean.empty? @msg.add(lin) #PIA if ean.empty? raise "Mandatory article id missing" if lieferantenartikelnummer.empty? pia = @msg.new_segment("PIA") pia.d4347 = '5' cde = pia.cC212[0] cde.d7140 = lieferantenartikelnummer cde.d7143 = 'SA' cde.d3055 = '91' end unless kaeuferartikelnummer.empty? and lieferantenartikelnummer.empty? pia = @msg.new_segment("PIA") pia.d4347 = '1' cde = pia.aC212[0] if !lieferantenartikelnummer.empty? cde.d7140 = lieferantenartikelnummer cde.d7143 = 'SA' cde.d3055 = '91' if !kaeuferartikelnummer.empty? cde = pia.aC212[1] cde.d7140 = kaeuferartikelnummer cde.d7143 = 'IN' cde.d3055 = '92' end else cde.d7140 = lieferantenartikelnummer cde.d7143 = 'BP' cde.d3055 = '92' end @msg.add(pia) end # IMD unless artikelbezeichnung.empty? imd = @msg.new_segment("IMD") imd.d7077 = 'A' imd.cC273.a7008[0].value = artikelbezeichnung @msg.add(imd) end unless farbe.empty? imd = @msg.new_segment("IMD") imd.d7077 = 'F' imd.cC272.d7081 = '35' imd.cC273.a7008[0].value = farbe @msg.add(imd) end unless groesse.empty? imd = @msg.new_segment("IMD") imd.d7077 = 'F' imd.cC272.d7081 = '98' imd.cC273.a7008[0].value = groesse @msg.add(imd) end # QTY qty = @msg.new_segment("QTY") cde = qty.cC186 cde.d6063 = '21' cde.d6060 = bestellmenge.to_i cde.d6411 = einheit unless einheit == 'PCE' # Mengeneinheit_cvt[masseinh_menge] cde.root = @ic @msg.add(qty) # PRI [[ek,'AAA'], [vk, 'AAE']].each do |params| preis, qu = params unless preis.empty? pri = @msg.new_segment("PRI") cde = pri.cC509 cde.d5125 = qu cde.d5118 = preis.sub(/,/,'.').to_f # decimal sign adjustment if qu == 'AAA' cde.d5387 = 'LIU' else cde.d5387 = 'SRP' cde.d5284 = preisbezugseinheit # cde.d6411 = 'PCE' ?? end @msg.add(pri) end end end def wrapup_msg # Fine as long as we don't create a summary section return if @msg.nil? uns = @msg.new_segment("UNS") uns.d0081 = 'S' @msg.add(uns) @ic.add(@msg) @msg = nil end # Dispatcher # # Call specialized mapping methods, depending on record type # def processLine( line ) case line when /^#.*/ # Skip comment lines when /^220;100;.*/ # Header: Triggers a new message wrapup_msg params = { :msg_type => 'ORDERS', :version => 'D', :release => '01B', :resp_agency => 'UN', :assigned_code => 'EAN010' } @msg = @ic.new_message( params ) processHeader( line.chomp ) when /^220;200;.*/ # Item: Requires a message to add to raise "Illegal state: Item before header?" if @msg == nil processItem(line.chomp) when /^\W*$/ # EOF: Add message to interchange wrapup_msg else print "Illegal line: #{line}\n" wrapup_msg end end def initialize(interchange) @msg = nil @with_rf_va = false @ic = interchange end def validate @ic.validate end def write(hnd) @ic.write(hnd) end end # class WebEDI_to_EANCOM02_Mapper # # MAIN # # We assume that all input is subject to the same mapping code, # and that all resulting messages go into the same interchange. # # Sender and recipient code of this interchange's UNB segment # are determined by buyer and supplier of one of the messages. # # In "real live", you may have to sort input documents according # to message type, sender/recipient, and required mapping code. ic = EDI::E::Interchange.new({:show_una => true, :charset => 'UNOC', :version => 3, :interchange_control_reference => Time.now.to_f.to_s[0...14] , # :application_reference => 'EANCOM' , # :output_mode => :verbatim, # :acknowledgment_request => true, :interchange_agreement_id => 'EANCOM'+'' , # your ref here! :test_indicator => 1, }) with_rff_va = false while ARGV[0] =~ /^-(\w)/ opt = ARGV.shift case $1 when 'v' # verbose mode - here: use formatted output ic.output_mode = :indented when 'a' with_rff_va = true else raise "Option not supported: #{opt}" end end map = WebEDI_to_EANCOM02_Map_ORDERS.new( ic ) map.with_rff_va = with_rff_va while (line=gets) map.processLine( line ) end map.wrapup_msg ic.validate $stdout.write ic # ic.inspect
27.415648
96
0.607331
5de591a76d9d386dcd376d6c6691f5a2be43609d
433
require "bundler/setup" require "peatio/ganjacoin" require "pry-byebug" require "webmock/rspec" require "mocha" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
24.055556
66
0.757506
396ce85ef105835305d577e7c6c3010f055d62da
1,962
# frozen_string_literal: true require "active_support/core_ext/object/inclusion" # A set of transformations that can be applied to a blob to create a variant. This class is exposed via # the `ActiveStorage::Blob#variant` method and should rarely be used directly. # # In case you do need to use this directly, it's instantiated using a hash of transformations where # the key is the command and the value is the arguments. Example: # # ActiveStorage::Variation.new(resize: "100x100", monochrome: true, trim: true, rotate: "-90") # # A list of all possible transformations is available at https://www.imagemagick.org/script/mogrify.php. class ActiveStorage::Variation attr_reader :transformations class << self # Returns a variation instance with the transformations that were encoded by +#encode+. def decode(key) new ActiveStorage.verifier.verify(key, purpose: :variation) end # Returns a signed key for the +transformations+, which can be used to refer to a specific # variation in a URL or combined key (like `ActiveStorage::Variant#key`). def encode(transformations) ActiveStorage.verifier.generate(transformations, purpose: :variation) end end def initialize(transformations) @transformations = transformations end # Accepts an open MiniMagick image instance, like what's return by `MiniMagick::Image.read(io)`, # and performs the +transformations+ against it. The transformed image instance is then returned. def transform(image) transformations.each do |(method, argument)| if eligible_argument?(argument) image.public_send(method, argument) else image.public_send(method) end end end # Returns a signed key for all the +transformations+ that this variation was instantiated with. def key self.class.encode(transformations) end private def eligible_argument?(argument) argument.present? && argument != true end end
35.035714
104
0.737003
bfc614ef066b29dcbf58d9c730b4c62b800013b3
133
module Types class ApiUserType < BaseObject field :id, ID, null: false field :display_name, String, null: false end end
19
44
0.699248
ffc8c35fbcc3c3cf6d9302680e03981df9e14c43
1,801
# frozen_string_literal: true module Packages class GroupPackagesFinder attr_reader :current_user, :group, :params InvalidPackageTypeError = Class.new(StandardError) def initialize(current_user, group, params = { exclude_subgroups: false, order_by: 'created_at', sort: 'asc' }) @current_user = current_user @group = group @params = params end def execute return ::Packages::Package.none unless group packages_for_group_projects end private def packages_for_group_projects packages = ::Packages::Package .for_projects(group_projects_visible_to_current_user) .processed .has_version .sort_by_attribute("#{params[:order_by]}_#{params[:sort]}") packages = filter_by_package_type(packages) packages = filter_by_package_name(packages) packages end def group_projects_visible_to_current_user ::Project .in_namespace(groups) .public_or_visible_to_user(current_user, Gitlab::Access::REPORTER) .with_project_feature .select { |project| Ability.allowed?(current_user, :read_package, project) } end def package_type params[:package_type].presence end def groups return [group] if exclude_subgroups? group.self_and_descendants end def exclude_subgroups? params[:exclude_subgroups] end def filter_by_package_type(packages) return packages unless package_type raise InvalidPackageTypeError unless Package.package_types.key?(package_type) packages.with_package_type(package_type) end def filter_by_package_name(packages) return packages unless params[:package_name].present? packages.search_by_name(params[:package_name]) end end end
25.366197
115
0.705164
bb65ee8b65548d47c9c727288399dd39260cefca
2,167
# 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 to check this file into your version control system. ActiveRecord::Schema.define(:version => 20120622215258) do create_table "marked_problems", :force => true do |t| t.string "status" t.integer "user_id" t.integer "problem_id" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false end add_index "marked_problems", ["problem_id"], :name => "index_marked_problems_on_problem_id" add_index "marked_problems", ["user_id", "problem_id"], :name => "index_marked_problems_on_user_id_and_problem_id" add_index "marked_problems", ["user_id"], :name => "index_marked_problems_on_user_id" create_table "problems", :force => true do |t| t.string "code" t.string "name" t.text "description" t.text "input_format" t.text "output_format" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.string "input_file_name" t.string "input_content_type" t.integer "input_file_size" t.datetime "input_updated_at" t.string "solution_file_name" t.string "solution_content_type" t.integer "solution_file_size" t.datetime "solution_updated_at" end create_table "users", :force => true do |t| t.string "username" t.string "email" t.string "password_digest" t.datetime "created_at", :null => false t.datetime "updated_at", :null => false t.boolean "admin" end end
38.696429
116
0.702353
9143cda3847f45069a2678a98e4d59f17aa80526
7,233
module Capachrome module Remote # # Specification of the desired and/or actual capabilities of the browser that the # server is being asked to create. # class Capabilities DEFAULTS = { :browser_name => "", :version => "", :platform => :any, :javascript_enabled => false, :css_selectors_enabled => false, :takes_screenshot => false, :native_events => false, :rotatable => false, :firefox_profile => nil, :proxy => nil } DEFAULTS.each_key do |key| define_method key do @capabilities.fetch(key) end define_method "#{key}=" do |value| @capabilities[key] = value end end alias_method :css_selectors_enabled?, :css_selectors_enabled alias_method :javascript_enabled? , :javascript_enabled alias_method :native_events? , :native_events alias_method :takes_screenshot? , :takes_screenshot alias_method :rotatable? , :rotatable # # Convenience methods for the common choices. # class << self def android(opts = {}) new({ :browser_name => "android", :platform => :android, :javascript_enabled => true, :rotatable => true, :takes_screenshot => true }.merge(opts)) end def chrome(opts = {}) new({ :browser_name => "chrome", :javascript_enabled => true, :css_selectors_enabled => true }.merge(opts)) end def firefox(opts = {}) new({ :browser_name => "firefox", :javascript_enabled => true, :takes_screenshot => true, :css_selectors_enabled => true }.merge(opts)) end def htmlunit(opts = {}) new({ :browser_name => "htmlunit" }.merge(opts)) end def htmlunitwithjs(opts = {}) new({ :browser_name => "htmlunit", :javascript_enabled => true }.merge(opts)) end def internet_explorer(opts = {}) new({ :browser_name => "internet explorer", :platform => :windows, :takes_screenshot => true, :css_selectors_enabled => true, :native_events => true }.merge(opts)) end alias_method :ie, :internet_explorer def iphone(opts = {}) new({ :browser_name => "iPhone", :platform => :mac, :javascript_enabled => true }.merge(opts)) end def ipad(opts = {}) new({ :browser_name => "iPad", :platform => :mac, :javascript_enabled => true }.merge(opts)) end def phantomjs(opts = {}) new({ :browser_name => "phantomjs", :javascript_enabled => true, :takes_screenshot => true, :css_selectors_enabled => true }.merge(opts)) end def safari(opts = {}) new({ :browser_name => "safari", :javascript_enabled => true, :takes_screenshot => true, :css_selectors_enabled => true }.merge(opts)) end # # @api private # def json_create(data) data = data.dup caps = new caps.browser_name = data.delete("browserName") caps.version = data.delete("version") caps.platform = data.delete("platform").downcase.to_sym if data.has_key?('platform') caps.javascript_enabled = data.delete("javascriptEnabled") caps.css_selectors_enabled = data.delete("cssSelectorsEnabled") caps.takes_screenshot = data.delete("takesScreenshot") caps.native_events = data.delete("nativeEvents") caps.rotatable = data.delete("rotatable") caps.proxy = Proxy.json_create(data['proxy']) if data.has_key?('proxy') # any remaining pairs will be added as is, with no conversion caps.merge!(data) caps end end # @option :browser_name [String] required browser name # @option :version [String] required browser version number # @option :platform [Symbol] one of :any, :win, :mac, or :x # @option :javascript_enabled [Boolean] does the driver have javascript enabled? # @option :css_selectors_enabled [Boolean] does the driver support CSS selectors? # @option :takes_screenshot [Boolean] can this driver take screenshots? # @option :native_events [Boolean] does this driver use native events? # @option :proxy [Selenium::WebDriver::Proxy, Hash] proxy configuration # # Firefox-specific options: # # @option :firefox_profile [Selenium::WebDriver::Firefox::Profile] the firefox profile to use # # @api public # def initialize(opts = {}) @capabilities = DEFAULTS.merge(opts) end # # Allows setting arbitrary capabilities. # def []=(key, value) @capabilities[key] = value end def [](key) @capabilities[key] end def merge!(other) if other.respond_to?(:capabilities, true) && other.capabilities.kind_of?(Hash) @capabilities.merge! other.capabilities elsif other.kind_of? Hash @capabilities.merge! other else raise ArgumentError, "argument should be a Hash or implement #capabilities" end end # @api private # def as_json(opts = nil) hash = {} @capabilities.each do |key, value| case key when :platform hash['platform'] = value.to_s.upcase when :firefox_profile hash['firefox_profile'] = value.as_json['zip'] if value when :proxy hash['proxy'] = value.as_json if value when String, :firefox_binary hash[key.to_s] = value when Symbol hash[camel_case(key.to_s)] = value else raise TypeError, "expected String or Symbol, got #{key.inspect}:#{key.class} / #{value.inspect}" end end hash end def to_json(*args) WebDriver.json_dump as_json end def ==(other) return false unless other.kind_of? self.class as_json == other.as_json end alias_method :eql?, :== protected def capabilities @capabilities end private def camel_case(str) str.gsub(/_([a-z])/) { $1.upcase } end end # Capabilities end # Remote end # Selenium
29.402439
108
0.512374
6aca1e39a17d0d01a5401b645aea2de77304f213
1,370
require 'spec_helper' describe Zuora::Objects::AmendRequest do describe "most persistence methods" do it "are not publicly available" do [:update, :destroy, :where, :find].each do |meth| subject.public_methods.should_not include(meth) end end end describe "generating a request" do before do subscription = FactoryGirl.build(:subscription) @amendment = FactoryGirl.build(:amendment) @amendment.subscription_id = subscription.id MockResponse.responds_with(:payment_method_credit_card_find_success) do product_rate_plans = [Zuora::Objects::ProductRatePlan.find('stub')] @prps = Zuora::Objects::RatePlan.new @prps.product_rate_plan_id = product_rate_plans[0].id @product_rate_plans = [@prps] end end it "handles applying amend failures messages" do MockResponse.responds_with(:amend_request_failure) do @amendment.subscription_id = '2c92c0f93a569878013a6778f0446b11' subject.amendment = @amendment subject.plans_and_charges = Array.new << { rate_plan: @product_rate_plans[0], charges: nil } amnd_resp = subject.create amnd_resp[:success].should == false amnd_resp[:errors][:message].should include('Invalid value for field SubscriptionId: 2c92c0f93a569878013a6778f0446b11') end end end end
34.25
127
0.70219
338b159aa05bc29eb6bb1513ae33ab5c39a0409e
162
class PagesController < ApplicationController def index p params[:controller] end def residential end def corporate end end
13.5
45
0.641975
030f693bc70242899aa43f8391beda6a1d64bf70
600
# frozen_string_literal: true Spree::HomeController.class_eval do before_action :get_homepage helper 'spree/blogs/posts' def index @searcher = build_searcher(params.merge(include_images: true)) @products = @searcher.retrieve_products.limit(8) @taxonomies = Spree::Taxonomy.includes(root: :children) render template: 'spree/pages/home' end private def get_homepage @page = Spree::Page.find_by_path('/') @posts = Spree::Post.web.limit(5) @config = Spree::ContentConfiguration.new end def accurate_title @page.meta_title unless @page.nil? end end
22.222222
66
0.718333
f78b818b79c3d97ecf533bfd608507c94feaac98
1,358
title 'Tests to confirm bison works as expected' plan_origin = ENV['HAB_ORIGIN'] plan_name = input('plan_name', value: 'bison') control 'core-plans-bison-works' do impact 1.0 title 'Ensure bison works as expected' desc ' Verify bison by ensuring that (1) its installation directory exists (2) it returns the expected version ' plan_installation_directory = command("hab pkg path #{plan_origin}/#{plan_name}") describe plan_installation_directory do its('exit_status') { should eq 0 } its('stdout') { should_not be_empty } #its('stderr') { should be_empty } end plan_pkg_version = plan_installation_directory.stdout.split("/")[5] bison_full_path = File.join(plan_installation_directory.stdout.strip, "bin/bison") describe command("#{bison_full_path} --version") do its('exit_status') { should eq 0 } its('stdout') { should_not be_empty } its('stdout') { should match /bison \(GNU Bison\) #{plan_pkg_version}/ } #its('stderr') { should be_empty } end yacc_full_path = File.join(plan_installation_directory.stdout.strip, "bin/yacc") describe command("#{yacc_full_path} --version") do its('exit_status') { should eq 0 } its('stdout') { should_not be_empty } its('stdout') { should match /bison \(GNU Bison\) #{plan_pkg_version}/ } #its('stderr') { should be_empty } end end
34.820513
84
0.698822
1af0c43678681497e182644029972f4f31b6c0c9
1,003
# frozen_string_literal: true require_relative './base' require_relative 'attributes/id' require_relative 'attributes/expiry' require_relative 'attributes/active' require_relative 'attributes/eta' module Warframe module Models # Sortie data model. # {https://api.warframestat.us/pc/sortie /:platform/sortie} class Sortie < Warframe::Models::Base include Warframe::Models::Attributes::ID include Warframe::Models::Attributes::ActiveBoth include Warframe::Models::Attributes::Expiration include Warframe::Models::Attributes::ETA # The boss for this part of the sortie. # @return [String] attr_reader :boss # The faction fighting you in this mission. # @return [String] attr_reader :faction # Modifiers active for this challenge. # @return [Array<OpenStruct>] attr_reader :variants # The reward pool which this is pulling from. # @return [String] attr_reader :reward_pool end end end
27.108108
63
0.695912
6a1850702b994b68a569e68c92d5a46e873310dc
1,529
# -*- encoding: utf-8 -*- # stub: builder 3.2.4 ruby lib Gem::Specification.new do |s| s.name = "builder".freeze s.version = "3.2.4" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Jim Weirich".freeze] s.date = "2019-12-10" s.description = "Builder provides a number of builder objects that make creating structured data\nsimple to do. Currently the following builder objects are supported:\n\n* XML Markup\n* XML Events\n".freeze s.email = "[email protected]".freeze s.extra_rdoc_files = ["CHANGES".freeze, "MIT-LICENSE".freeze, "README.md".freeze, "Rakefile".freeze, "builder.blurb".freeze, "builder.gemspec".freeze, "doc/releases/builder-1.2.4.rdoc".freeze, "doc/releases/builder-2.0.0.rdoc".freeze, "doc/releases/builder-2.1.1.rdoc".freeze] s.files = ["CHANGES".freeze, "MIT-LICENSE".freeze, "README.md".freeze, "Rakefile".freeze, "builder.blurb".freeze, "builder.gemspec".freeze, "doc/releases/builder-1.2.4.rdoc".freeze, "doc/releases/builder-2.0.0.rdoc".freeze, "doc/releases/builder-2.1.1.rdoc".freeze] s.homepage = "http://onestepback.org".freeze s.licenses = ["MIT".freeze] s.rdoc_options = ["--title".freeze, "Builder -- Easy XML Building".freeze, "--main".freeze, "README.rdoc".freeze, "--line-numbers".freeze] s.rubygems_version = "2.7.10".freeze s.summary = "Builders for MarkUp.".freeze s.installed_by_version = "2.7.10" if s.respond_to? :installed_by_version end
63.708333
278
0.714192
083e1a3ebdd4c5d1c02a69e1020e50f064c7954d
15,353
module IdentityCache module QueryAPI extend ActiveSupport::Concern included do |base| base.after_commit :expire_cache if Gem::Version.new(ActiveRecord::VERSION::STRING) < Gem::Version.new("4.0.4") base.after_touch :expire_cache end end module ClassMethods # Similar to ActiveRecord::Base#exists? will return true if the id can be # found in the cache or in the DB. def exists_with_identity_cache?(id) raise NotImplementedError, "exists_with_identity_cache? needs the primary index enabled" unless primary_cache_index_enabled !!fetch_by_id(id) end # Default fetcher added to the model on inclusion, it behaves like # ActiveRecord::Base.where(id: id).first def fetch_by_id(id) return unless id raise NotImplementedError, "fetching needs the primary index enabled" unless primary_cache_index_enabled if IdentityCache.should_cache? require_if_necessary do object = nil coder = IdentityCache.fetch(rails_cache_key(id)){ coder_from_record(object = resolve_cache_miss(id)) } object ||= record_from_coder(coder) IdentityCache.logger.error "[IDC id mismatch] fetch_by_id_requested=#{id} fetch_by_id_got=#{object.id} for #{object.inspect[(0..100)]} " if object && object.id != id object end else self.reorder(nil).where(primary_key => id).first end end # Default fetcher added to the model on inclusion, it behaves like # ActiveRecord::Base.find, will raise ActiveRecord::RecordNotFound exception # if id is not in the cache or the db. def fetch(id) fetch_by_id(id) or raise(ActiveRecord::RecordNotFound, "Couldn't find #{self.name} with ID=#{id}") end # Default fetcher added to the model on inclusion, if behaves like # ActiveRecord::Base.find_all_by_id def fetch_multi(*ids) raise NotImplementedError, "fetching needs the primary index enabled" unless primary_cache_index_enabled options = ids.extract_options! ids.flatten!(1) records = if IdentityCache.should_cache? require_if_necessary do cache_keys = ids.map {|id| rails_cache_key(id) } key_to_id_map = Hash[ cache_keys.zip(ids) ] key_to_record_map = {} coders_by_key = IdentityCache.fetch_multi(cache_keys) do |unresolved_keys| ids = unresolved_keys.map {|key| key_to_id_map[key] } records = find_batch(ids) found_records = records.compact found_records.each{ |record| record.send(:populate_association_caches) } key_to_record_map = found_records.index_by{ |record| rails_cache_key(record.id) } records.map {|record| coder_from_record(record) } end cache_keys.map{ |key| key_to_record_map[key] || record_from_coder(coders_by_key[key]) } end else find_batch(ids) end records.compact! prefetch_associations(options[:includes], records) if options[:includes] records end private def record_from_coder(coder) #:nodoc: if coder.present? && coder.has_key?(:class) record = coder[:class].allocate unless coder[:class].serialized_attributes.empty? coder = coder.dup coder['attributes'] = coder['attributes'].dup end record.init_with(coder) coder[:associations].each {|name, value| set_embedded_association(record, name, value) } if coder.has_key?(:associations) coder[:normalized_has_many].each {|name, ids| record.instance_variable_set(:"@#{record.class.cached_has_manys[name][:ids_variable_name]}", ids) } if coder.has_key?(:normalized_has_many) record end end def set_embedded_association(record, association_name, coder_or_array) #:nodoc: value = if IdentityCache.unmap_cached_nil_for(coder_or_array).nil? nil elsif (reflection = record.class.reflect_on_association(association_name)).collection? association = reflection.association_class.new(record, reflection) association.target = coder_or_array.map {|e| record_from_coder(e) } association.target.each {|e| association.set_inverse_instance(e) } association else record_from_coder(coder_or_array) end variable_name = record.class.send(:recursively_embedded_associations)[association_name][:records_variable_name] record.instance_variable_set(:"@#{variable_name}", IdentityCache.map_cached_nil_for(value)) end def get_embedded_association(record, association, options) #:nodoc: embedded_variable = record.instance_variable_get(:"@#{options[:records_variable_name]}") if IdentityCache.unmap_cached_nil_for(embedded_variable).nil? nil elsif record.class.reflect_on_association(association).collection? embedded_variable.map {|e| coder_from_record(e) } else coder_from_record(embedded_variable) end end def coder_from_record(record) #:nodoc: unless record.nil? coder = {:class => record.class } record.encode_with(coder) add_cached_associations_to_coder(record, coder) coder end end def add_cached_associations_to_coder(record, coder) klass = record.class if klass.include?(IdentityCache) if (recursively_embedded_associations = klass.send(:recursively_embedded_associations)).present? coder[:associations] = recursively_embedded_associations.each_with_object({}) do |(name, options), hash| hash[name] = IdentityCache.map_cached_nil_for(get_embedded_association(record, name, options)) end end if (cached_has_manys = klass.cached_has_manys).present? coder[:normalized_has_many] = cached_has_manys.each_with_object({}) do |(name, options), hash| hash[name] = record.instance_variable_get(:"@#{options[:ids_variable_name]}") unless options[:embed] == true end end end end def require_if_necessary #:nodoc: # mem_cache_store returns raw value if unmarshal fails rval = yield case rval when String rval = Marshal.load(rval) when Array rval.map!{ |v| v.kind_of?(String) ? Marshal.load(v) : v } end rval rescue ArgumentError => e if e.message =~ /undefined [\w\/]+ (\w+)/ ok = Kernel.const_get($1) rescue nil retry if ok end raise end def resolve_cache_miss(id) object = self.includes(cache_fetch_includes).reorder(nil).where(primary_key => id).try(:first) object.send(:populate_association_caches) if object object end def recursively_embedded_associations all_cached_associations.select do |cached_association, options| options[:embed] == true end end def all_cached_associations (cached_has_manys || {}).merge(cached_has_ones || {}).merge(cached_belongs_tos || {}) end def embedded_associations all_cached_associations.select do |cached_association, options| options[:embed] end end def cache_fetch_includes associations_for_identity_cache = recursively_embedded_associations.map do |child_association, options| child_class = reflect_on_association(child_association).try(:klass) child_includes = nil if child_class.respond_to?(:cache_fetch_includes, true) child_includes = child_class.send(:cache_fetch_includes) end if child_includes.blank? child_association else { child_association => child_includes } end end associations_for_identity_cache.compact end def find_batch(ids) @id_column ||= columns.detect {|c| c.name == primary_key} ids = ids.map{ |id| @id_column.type_cast(id) } records = where(primary_key => ids).includes(cache_fetch_includes).to_a records_by_id = records.index_by(&:id) ids.map{ |id| records_by_id[id] } end def prefetch_associations(associations, records) associations = hashify_includes_structure(associations) associations.each do |association, sub_associations| case when details = cached_has_manys[association] if details[:embed] == true child_records = records.map(&details[:cached_accessor_name].to_sym).flatten else ids_to_parent_record = records.each_with_object({}) do |record, hash| child_ids = record.send(details[:cached_ids_name]) child_ids.each do |child_id| hash[child_id] = record end end parent_record_to_child_records = Hash.new { |h, k| h[k] = [] } child_records = details[:association_class].fetch_multi(*ids_to_parent_record.keys) child_records.each do |child_record| parent_record = ids_to_parent_record[child_record.id] parent_record_to_child_records[parent_record] << child_record end parent_record_to_child_records.each do |parent_record, child_records| parent_record.send(details[:prepopulate_method_name], child_records) end end next_level_records = child_records when details = cached_belongs_tos[association] if details[:embed] == true raise ArgumentError.new("Embedded belongs_to associations do not support prefetching yet.") else ids_to_child_record = records.each_with_object({}) do |child_record, hash| parent_id = child_record.send(details[:foreign_key]) hash[parent_id] = child_record if parent_id.present? end parent_records = details[:association_class].fetch_multi(ids_to_child_record.keys) parent_records.each do |parent_record| child_record = ids_to_child_record[parent_record.id] child_record.send(details[:prepopulate_method_name], parent_record) end end next_level_records = parent_records when details = cached_has_ones[association] if details[:embed] == true parent_records = records.map(&details[:cached_accessor_name].to_sym) else raise ArgumentError.new("Non-embedded has_one associations do not support prefetching yet.") end next_level_records = parent_records else raise ArgumentError.new("Unknown cached association #{association} listed for prefetching") end if details && details[:association_class].respond_to?(:prefetch_associations, true) details[:association_class].send(:prefetch_associations, sub_associations, next_level_records) end end end def hashify_includes_structure(structure) case structure when nil {} when Symbol {structure => []} when Hash structure.clone when Array structure.each_with_object({}) do |member, hash| case member when Hash hash.merge!(member) when Symbol hash[member] = [] end end end end end private def populate_association_caches # :nodoc: self.class.send(:embedded_associations).each do |cached_association, options| send(options[:population_method_name]) reflection = options[:embed] == true && self.class.reflect_on_association(cached_association) if reflection && reflection.klass.respond_to?(:cached_has_manys) child_objects = Array.wrap(send(options[:cached_accessor_name])) child_objects.each{ |child| child.send(:populate_association_caches) } end end end def fetch_recursively_cached_association(ivar_name, association_name) # :nodoc: ivar_full_name = :"@#{ivar_name}" if IdentityCache.should_cache? populate_recursively_cached_association(ivar_name, association_name) assoc = IdentityCache.unmap_cached_nil_for(instance_variable_get(ivar_full_name)) assoc.is_a?(ActiveRecord::Associations::CollectionAssociation) ? assoc.reader : assoc else send(association_name.to_sym) end end def populate_recursively_cached_association(ivar_name, association_name) # :nodoc: ivar_full_name = :"@#{ivar_name}" value = instance_variable_get(ivar_full_name) return value unless value.nil? loaded_association = send(association_name) instance_variable_set(ivar_full_name, IdentityCache.map_cached_nil_for(loaded_association)) end def expire_primary_index # :nodoc: return unless self.class.primary_cache_index_enabled IdentityCache.logger.debug do extra_keys = if respond_to?(:updated_at) old_updated_at = old_values_for_fields([:updated_at]).first "expiring_last_updated_at=#{old_updated_at}" else "" end "[IdentityCache] expiring=#{self.class.name} expiring_id=#{id} #{extra_keys}" end IdentityCache.cache.delete(primary_cache_index_key) end def expire_secondary_indexes # :nodoc: return unless self.class.primary_cache_index_enabled cache_indexes.try(:each) do |fields| if self.destroyed? IdentityCache.cache.delete(secondary_cache_index_key_for_previous_values(fields)) else new_cache_index_key = secondary_cache_index_key_for_current_values(fields) IdentityCache.cache.delete(new_cache_index_key) if !was_new_record? old_cache_index_key = secondary_cache_index_key_for_previous_values(fields) IdentityCache.cache.delete(old_cache_index_key) unless old_cache_index_key == new_cache_index_key end end end end def expire_attribute_indexes # :nodoc: cache_attributes.try(:each) do |(attribute, fields)| unless was_new_record? old_cache_attribute_key = attribute_cache_key_for_attribute_and_previous_values(attribute, fields) IdentityCache.cache.delete(old_cache_attribute_key) end new_cache_attribute_key = attribute_cache_key_for_attribute_and_current_values(attribute, fields) if new_cache_attribute_key != old_cache_attribute_key IdentityCache.cache.delete(new_cache_attribute_key) end end end def expire_cache # :nodoc: expire_primary_index expire_secondary_indexes expire_attribute_indexes true end def was_new_record? # :nodoc: pk = self.class.primary_key !destroyed? && transaction_changed_attributes.has_key?(pk) && transaction_changed_attributes[pk].nil? end end end
38.672544
195
0.65466
f8e45aaa7e750577a359e56d7cc2c3b384e45b03
995
# frozen_string_literal: true module Cleanup module Deprecators # Used to deprecate methods with non-idiomatic getter names. # # There are methods in the code with non-idiomatic method names. Typically, # Ruby getters are named as nouns for the attribute they are returning. # Prefer User#status over User#get_status. # class GetDeprecator ## # Default message to display to developer when deprecated method called. MESSAGE = '%{deprecated_method} is deprecated. '\ 'Instead, you should use: %{new_method}. '\ "Read #{__FILE__} for more information." # Message printed to STDOUT when a deprecated method is called. def deprecation_warning(deprecated_method, _message, _backtrace = nil) new_method = deprecated_method.to_s.gsub(/^get_/, '') message = format(MESSAGE, deprecated_method: deprecated_method, new_method: new_method) Kernel.warn(message) end end end end
36.851852
95
0.684422
d5be8a0486b0c351ea212f77ae33f9d3cf1772c1
510
# Network configuration require 'spec_helper' describe file('/etc/sysconfig/network-scripts/ifcfg-eth0') do it { should be_file } end # Ugly hack to get around vbox still using biosdevname on 7.0. We fix it # during provisioning so device name is correct when building subsequent # images. I didn't like having to copy this same test everywhere to work # around one part of the build. if ENV['IMAGE_TYPE'] != nil describe command('ip link show eth0') do its(:exit_status) { should eq 0 } end end
30
73
0.741176
bf4968ad0ad7e58850946d6f5302e14ea4ff6093
1,261
# frozen_string_literal: true require 'forwardable' module Expire # All Backups go here class BackupList include Enumerable extend Forwardable def initialize(backups = []) # @backups = backups.sort.reverse @backups = backups end attr_reader :backups def_delegators :backups, :each, :empty?, :last, :length, :<< def one_per(noun) backups_per_noun = self.class.new return backups_per_noun unless any? reversed = sort.reverse backups_per_noun << reversed.first message = "same_#{noun}?" reversed.each do |backup| backups_per_noun << backup unless backup.send(message, backups_per_noun.last) end backups_per_noun end def most_recent(amount = 1) self.class.new(sort.reverse.first(amount)) end def newest backups.max end def oldest backups.min end def not_older_than(reference_time) sort.select { |backup| backup.time >= reference_time } end def expired self.class.new(backups.select(&:expired?)) end def expired_count expired.length end def keep self.class.new(backups.select(&:keep?)) end def keep_count keep.length end end end
18.014286
85
0.640761
ed7e783334ecbd1949336081b8132f0a006a1e56
1,113
module Fog module Metering class TeleFonica class Real def list_meters(options = []) data = { 'q' => [] } options.each do |opt| filter = {} ['field', 'op', 'value'].each do |key| filter[key] = opt[key] if opt[key] end data['q'] << filter unless filter.empty? end request( :body => Fog::JSON.encode(data), :expects => 200, :method => 'GET', :path => 'meters' ) end end class Mock def list_meters(_options = {}) response = Excon::Response.new response.status = 200 response.body = [{ 'user_id' => '1d5fd9eda19142289a60ed9330b5d284', 'name' => 'image.size', 'resource_id' => 'glance', 'project_id' => 'd646b40dea6347dfb8caee2da1484c56', 'type' => 'gauge', 'unit' => 'bytes' }] response end end end end end
23.680851
64
0.424079
abdb60ab09c57b9a07dd59e506efab0cfcaf65ea
2,840
# typed: false require_relative './test' class Vonage::VoiceTest < Vonage::Test def calls Vonage::Voice.new(config) end def calls_uri 'https://api.nexmo.com/v1/calls' end def call_uri 'https://api.nexmo.com/v1/calls/' + call_uuid end def test_create_method params = { to: [{type: 'phone', number: '14843331234'}], from: {type: 'phone', number: '14843335555'}, answer_url: ['https://example.com/answer'] } stub_request(:post, calls_uri).with(request(body: params)).to_return(response) assert_kind_of Vonage::Response, calls.create(params) end def test_list_method params = {status: 'completed'} stub_request(:get, calls_uri).with(request(query: params)).to_return(response) assert_kind_of Vonage::Voice::ListResponse, calls.list(params) end def test_get_method stub_request(:get, call_uri).with(request).to_return(response) assert_kind_of Vonage::Response, calls.get(call_uuid) end def test_update_method params = {action: 'hangup'} stub_request(:put, call_uri).with(request(body: params)).to_return(response) assert_kind_of Vonage::Response, calls.update(call_uuid, params) end def test_hangup_method params = {action: 'hangup'} stub_request(:put, call_uri).with(request(body: params)).to_return(response) assert_kind_of Vonage::Response, calls.hangup(call_uuid) end def test_mute_method params = {action: 'mute'} stub_request(:put, call_uri).with(request(body: params)).to_return(response) assert_kind_of Vonage::Response, calls.mute(call_uuid) end def test_unmute_method params = {action: 'unmute'} stub_request(:put, call_uri).with(request(body: params)).to_return(response) assert_kind_of Vonage::Response, calls.unmute(call_uuid) end def test_earmuff_method params = {action: 'earmuff'} stub_request(:put, call_uri).with(request(body: params)).to_return(response) assert_kind_of Vonage::Response, calls.earmuff(call_uuid) end def test_unearmuff_method params = {action: 'unearmuff'} stub_request(:put, call_uri).with(request(body: params)).to_return(response) assert_kind_of Vonage::Response, calls.unearmuff(call_uuid) end def test_transfer_method destination = {type: 'ncco', url: ['http://example.org/new-ncco.json']} params = {action: 'transfer', destination: destination} stub_request(:put, call_uri).with(request(body: params)).to_return(response) assert_kind_of Vonage::Response, calls.transfer(call_uuid, destination: destination) end def test_stream_method assert_kind_of Vonage::Voice::Stream, calls.stream end def test_talk_method assert_kind_of Vonage::Voice::Talk, calls.talk end def test_dtmf_method assert_kind_of Vonage::Voice::DTMF, calls.dtmf end end
25.132743
88
0.715493
edec2e6463ea378948e7dc9558d7427e95a56d38
2,511
CafeGrader::Application.configure do # Settings specified here will take precedence over those in config/application.rb # Code is not reloaded between requests config.cache_classes = true # Full error reports are disabled and caching is turned on config.consider_all_requests_local = false config.action_controller.perform_caching = true # Disable Rails's static asset server (Apache or nginx will already do this) config.serve_static_files = false # Compress JavaScripts and CSS config.assets.compress = true # Don't fallback to assets pipeline if a precompiled asset is missed config.assets.compile = false # Generate digests for assets URLs config.assets.digest = true # Defaults to nil and saved in location specified by config.assets.prefix # config.assets.manifest = YOUR_PATH # Specifies the header that your server uses for sending files # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # See everything in the log (default is :info) # config.log_level = :debug # Prepend all log lines with the following tags # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server # config.action_controller.asset_host = "http://assets.example.com" # Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added) # config.assets.precompile += %w( search.js ) # Disable delivery errors, bad email addresses will be ignored # config.action_mailer.raise_delivery_errors = false # Enable threaded mode # config.threadsafe! # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation can not be found) config.i18n.fallbacks = true # Send deprecation notices to registered listeners config.active_support.deprecation = :notify # Log the query plan for queries taking more than this (works # with SQLite, MySQL, and PostgreSQL) # config.active_record.auto_explain_threshold_in_seconds = 0.5 config.eager_load = true end
35.871429
104
0.759458
4abd5c1b8064dd9c588c13c21233b22af04bc290
302
class Notification def self.draft_for_review(draft: nil) if draft.in_review? && draft.friend.remote_clinic_lawyers.present? ReviewMailer.review_needed_email(draft).deliver_now elsif draft.in_review? ReviewMailer.lawyer_assignment_needed_email(draft).deliver_now end end end
30.2
70
0.781457
390c5b718e80766358c4dc8ef025b6aeb48e1cf0
1,933
require File.dirname(__FILE__) + '/../spec_helper' describe CalendarDateSelect::IncludesHelper do include ActionView::Helpers::TagHelper include ActionView::Helpers::AssetTagHelper include CalendarDateSelect::IncludesHelper describe "calendar_date_select_includes" do it "should include the specified locale" do calendar_date_select_includes(:locale => "fr").should include("calendar_date_select/locale/fr.js") end it "should include the specified style" do calendar_date_select_includes(:style => "blue").should include("calendar_date_select/blue.css") end it "should complain if you provide an illegitimate argument" do lambda { calendar_date_select_includes(:language => "fr") }.should raise_error(ArgumentError) end end describe "calendar_date_select_javascripts" do it "should return an array of javascripts" do calendar_date_select_javascripts.should == ["calendar_date_select/calendar_date_select"] end it "should return the :javascript_include of the specified format, if the specified format expects it" do CalendarDateSelect.stub!(:format).and_return(CalendarDateSelect::FORMATS[:hyphen_ampm]) calendar_date_select_javascripts.should == ["calendar_date_select/calendar_date_select", "calendar_date_select/format_hyphen_ampm"] end it "should blow up if an illegitimate argument is passed" do lambda { calendar_date_select_javascripts(:language => "fr") }.should raise_error(ArgumentError) end end describe "calendar_date_select_stylesheets" do it "should return an array of stylesheet" do calendar_date_select_javascripts.should == ["calendar_date_select/calendar_date_select"] end it "should blow up if an illegitimate argument is passed" do lambda { calendar_date_select_stylesheets(:css_version => "blue") }.should raise_error(ArgumentError) end end end
41.12766
137
0.756337
5df45ca9fdef0f71a54a4df7ae557da2a663aad5
475
require 'rails_helper' describe "asset_events/_condition_update_event_form.html.haml", :type => :view do it 'fields' do test_asset = create(:buslike_asset) assign(:asset, test_asset) assign(:asset_event, ConditionUpdateEvent.new(:asset => test_asset)) render expect(rendered).to have_field('asset_event_assessed_rating') expect(rendered).to have_field('asset_event_event_date') expect(rendered).to have_field('asset_event_comments') end end
31.666667
81
0.755789
388fbabb2a5086dd94ec2a89a99dd9b5c2c4c50b
9,044
=begin #Datadog API V2 Collection #Collection of all Datadog Public endpoints. The version of the OpenAPI document: 1.0 Contact: [email protected] Generated by: https://openapi-generator.tech Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2020-Present Datadog, Inc. =end require 'date' require 'time' module DatadogAPIClient::V2 # The attributes associated with the archive. class LogsArchiveCreateRequestAttributes # whether the object has unparsed attributes attr_accessor :_unparsed attr_accessor :destination # To store the tags in the archive, set the value \"true\". If it is set to \"false\", the tags will be deleted when the logs are sent to the archive. attr_accessor :include_tags # The archive name. attr_accessor :name # The archive query/filter. Logs matching this query are included in the archive. attr_accessor :query # An array of tags to add to rehydrated logs from an archive. attr_accessor :rehydration_tags # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'destination' => :'destination', :'include_tags' => :'include_tags', :'name' => :'name', :'query' => :'query', :'rehydration_tags' => :'rehydration_tags' } end # Returns all the JSON keys this model knows about def self.acceptable_attributes attribute_map.values end # Attribute type mapping. def self.openapi_types { :'destination' => :'LogsArchiveCreateRequestDestination', :'include_tags' => :'Boolean', :'name' => :'String', :'query' => :'String', :'rehydration_tags' => :'Array<String>' } end # List of attributes with nullable: true def self.openapi_nullable Set.new([ ]) end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `DatadogAPIClient::V2::LogsArchiveCreateRequestAttributes` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `DatadogAPIClient::V2::LogsArchiveCreateRequestAttributes`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'destination') self.destination = attributes[:'destination'] end if attributes.key?(:'include_tags') self.include_tags = attributes[:'include_tags'] else self.include_tags = false end if attributes.key?(:'name') self.name = attributes[:'name'] end if attributes.key?(:'query') self.query = attributes[:'query'] end if attributes.key?(:'rehydration_tags') if (value = attributes[:'rehydration_tags']).is_a?(Array) self.rehydration_tags = value end end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if @destination.nil? invalid_properties.push('invalid value for "destination", destination cannot be nil.') end if @name.nil? invalid_properties.push('invalid value for "name", name cannot be nil.') end if @query.nil? invalid_properties.push('invalid value for "query", query cannot be nil.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if @destination.nil? return false if @name.nil? return false if @query.nil? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && destination == o.destination && include_tags == o.include_tags && name == o.name && query == o.query && rehydration_tags == o.rehydration_tags end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [destination, include_tags, name, query, rehydration_tags].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) self.send("#{key}=", nil) elsif type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :Time Time.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when :Array # generic array, return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model # models (e.g. Pet) or oneOf klass = DatadogAPIClient::V2.const_get(type) res = klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) if res.instance_of? DatadogAPIClient::V2::UnparsedObject self._unparsed = true end res end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = self.class.openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
30.972603
234
0.630916
3975c51b31c16edcf8f4fef03098bde8368af513
5,486
require "spec_helper" describe "nginx::configuration" do let(:chef_run) do ChefSpec::SoloRunner.new.converge(described_recipe, "nginx::service") end it "creates the configuration directory" do expect(chef_run).to create_directory("/etc/nginx").with( owner: "root", group: "root", recursive: true ) end it "creates the `mime.types` file" do expect(chef_run).to create_cookbook_file("/etc/nginx/mime.types").with( source: "mime.types", owner: "root", group: "root", mode: "0644" ) file = chef_run.cookbook_file("/etc/nginx/mime.types") expect(file).to notify("service[nginx]").to(:restart) end it "creates the log directory" do expect(chef_run).to create_directory("/var/log/nginx").with( owner: "root", group: "root", recursive: true ) end it "creates the `nginx.conf` template" do expect(chef_run).to create_template("/etc/nginx/nginx.conf").with( source: "nginx.conf.erb", owner: "root", group: "root", mode: "0644" ) file = chef_run.template("/etc/nginx/nginx.conf") expect(file).to notify("service[nginx]").to(:restart) end %w[sites-available sites-enabled].each do |vhost_dir| it "creates the `#{vhost_dir}` directory" do expect(chef_run).to create_directory("/etc/nginx/#{vhost_dir}").with( owner: "root", group: "root", mode: "0755" ) end end context "default site" do let(:default_site) do "default" end context "when `skip_default_site` is false" do let(:chef_run) do ChefSpec::SoloRunner.new do |node| node.automatic_attrs["hostname"] = "chefspechostname" end.converge(described_recipe, "nginx::service") end it "creates the `default` template" do expect(chef_run).to create_nginx_site(default_site).with( host: "chefspechostname", root: "/var/www/nginx-default" ) end it "does not remove the default site configuration" do expect(chef_run).to_not delete_file( "/etc/nginx/sites-available/default" ) expect(chef_run).to_not delete_file("/etc/nginx/sites-enabled/default") end end context "when `skip_default_site` is true" do let(:chef_run) do ChefSpec::SoloRunner.new do |node| node.set["nginx"]["skip_default_site"] = true end.converge(described_recipe, "nginx::service") end it "does not create the `default` template" do expect(chef_run).to_not create_template(default_site) end it "removes the default site configuration" do expect(chef_run).to delete_file("/etc/nginx/sites-available/default") expect(chef_run).to delete_file("/etc/nginx/sites-enabled/default") end end end context "conf.d entries" do let(:custom_entries) do %w[foo bar baz] end let(:default_entries) do %w[buffers general gzip logs performance proxy ssl_session timeouts] end context "cookbook defaults" do it "creates the default templates" do default_entries.each do |entry| conf_file = "/etc/nginx/conf.d/#{entry}.conf" expect(chef_run).to create_template(conf_file).with( source: "#{entry}.conf.erb", owner: "root", group: "root", mode: "0644" ) tmpl = chef_run.template(conf_file) expect(tmpl).to notify("service[nginx]").to(:restart) end end end context "custom attributes" do let(:chef_run) do ChefSpec::SoloRunner.new do |node| node.set["nginx"]["conf_files"] = %w[foo bar baz] end.converge(described_recipe, "nginx::service") end it "creates the custom templates" do custom_entries.each do |entry| conf_file = "/etc/nginx/conf.d/#{entry}.conf" expect(chef_run).to create_template(conf_file).with( source: "#{entry}.conf.erb", owner: "root", group: "root", mode: "0644" ) tmpl = chef_run.template(conf_file) expect(tmpl).to notify("service[nginx]").to(:restart) end end it "does not create the default templates" do default_entries.each do |entry| conf_file = "/etc/nginx/conf.d/#{entry}.conf" expect(chef_run).to_not create_template(conf_file) end end end end context "nginx status" do let(:status_conf) do "/etc/nginx/conf.d/nginx_status.conf" end context "when `enable_stub_status` is true" do it "creates the `nginx_status.conf` template" do expect(chef_run).to create_template(status_conf).with( source: "nginx_status.conf.erb", owner: "root", group: "root", mode: "0644", variables: { port: 80 } ) tmpl = chef_run.template(status_conf) expect(tmpl).to notify("service[nginx]").to(:restart) end end context "when `enable_stub_status` is false" do let(:chef_run) do ChefSpec::SoloRunner.new do |node| node.set["nginx"]["enable_stub_status"] = false end.converge(described_recipe, "nginx::service") end it "does not create the `nginx_status.conf` template" do expect(chef_run).to_not create_template(status_conf) end end end end
27.989796
79
0.609005
5d73a61ebb16907043bec189a9e43380f87ad018
263
# frozen_string_literal: true # Returns the full path to the folder with the given name inside the current # Git workspace def git_folder folder_name "#{git_root_folder}/#{folder_name}" end def git_root_folder output_of 'git rev-parse --show-toplevel' end
20.230769
76
0.775665
085315e137ce8866457bae51e53d53960328af6c
1,697
require File.dirname(__FILE__) + '/../../spec_helper' require File.dirname(__FILE__) + '/fixtures/classes' describe "Kernel#`" do it "is a private method" do Kernel.should have_private_instance_method(:`) end it "returns the standard output of the executed sub-process" do ip = 'world' `echo disc #{ip}`.should == "disc world\n" end it "tries to convert the given argument to String using #to_str" do (obj = mock('echo test')).should_receive(:to_str).and_return("echo test") Kernel.`(obj).should == "test\n" end platform_is_not :windows do it "sets $? to the exit status of the executed sub-process" do ip = 'world' `echo disc #{ip}` $?.class.should == Process::Status $?.stopped?.should == false $?.exited?.should == true $?.exitstatus.should == 0 $?.success?.should == true `echo disc #{ip}; exit 99` $?.class.should == Process::Status $?.stopped?.should == false $?.exited?.should == true $?.exitstatus.should == 99 $?.success?.should == false end end platform_is :windows do it "sets $? to the exit status of the executed sub-process" do ip = 'world' `echo disc #{ip}` $?.class.should == Process::Status $?.stopped?.should == false $?.exited?.should == true $?.exitstatus.should == 0 $?.success?.should == true `echo disc #{ip}& exit 99` $?.class.should == Process::Status $?.stopped?.should == false $?.exited?.should == true $?.exitstatus.should == 99 $?.success?.should == false end end end describe "Kernel.`" do it "needs to be reviewed for spec completeness" end
28.762712
77
0.600471
1c6a22a03e7044718aa58816307469c6be98dbf6
6,380
=begin #Selling Partner API for Direct Fulfillment Payments #The Selling Partner API for Direct Fulfillment Payments provides programmatic access to a direct fulfillment vendor's invoice data. OpenAPI spec version: v1 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.26 =end require 'date' module AmzSpApi::VendorDirectFulfillmentPaymentsApiModel class PartyIdentification # Assigned Identification for the party. attr_accessor :party_id # Identification of the party by address. attr_accessor :address # Tax registration details of the entity. attr_accessor :tax_registration_details # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'party_id' => :'partyId', :'address' => :'address', :'tax_registration_details' => :'taxRegistrationDetails' } end # Attribute type mapping. def self.swagger_types { :'party_id' => :'String', :'address' => :'Address', :'tax_registration_details' => :'Array<TaxRegistrationDetail>' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'partyId') self.party_id = attributes[:'partyId'] end if attributes.has_key?(:'address') self.address = attributes[:'address'] end if attributes.has_key?(:'taxRegistrationDetails') if (value = attributes[:'taxRegistrationDetails']).is_a?(Array) self.tax_registration_details = value end end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new if @party_id.nil? invalid_properties.push('invalid value for "party_id", party_id cannot be nil.') end invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? return false if @party_id.nil? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && party_id == o.party_id && address == o.address && tax_registration_details == o.tax_registration_details end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [party_id, address, tax_registration_details].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime DateTime.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = AmzSpApi::VendorDirectFulfillmentPaymentsApiModel.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) next if value.nil? hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
29.953052
132
0.631975
62198266609eb49ae162597aae068cadfdc4a0c3
235
class StorageProvider::LocalProvider < StorageProvider::BaseProvider def default_environment_variables { 'DIRECTORY' => nil } end def required_environment_variables default_environment_variables.keys end end
19.583333
68
0.761702
87ffd250a40260c031612c1cb7fbcc85c88b4a13
78
module Keap module XMLRPC class ProductImage < Object end end end
11.142857
31
0.692308
79cfc554c4ea5082729d2d14a8898723c645ef8d
39,868
# # REST API Querying capabilities # - Paging - offset, limit # - Sorting - sort_by=:attr, sort_oder = asc|desc # - Filtering - filter[]=... # - Selecting Attributes - attributes=:attr1,:attr2,... # - Querying by Tag - by_tag=:tag_path (i.e. /department/finance) # - Expanding Results - expand=resources,:subcollection # - Resource actions # describe "Querying" do def create_vms_by_name(names) names.each.collect { |name| FactoryBot.create(:vm_vmware, :name => name) } end let(:vm1) { FactoryBot.create(:vm_vmware, :name => "vm1") } describe "Querying vms" do before { api_basic_authorize collection_action_identifier(:vms, :read, :get) } it "supports offset" do create_vms_by_name(%w(aa bb cc)) get api_vms_url, :params => { :offset => 2 } expect_query_result(:vms, 1, 3) end it "supports limit" do create_vms_by_name(%w(aa bb cc)) get api_vms_url, :params => { :limit => 2 } expect_query_result(:vms, 2, 3) end specify "a user cannot exceed the maximum allowed page size" do stub_settings_merge(:api => {:max_results_per_page => 2}) FactoryBot.create_list(:vm, 3) get api_vms_url, :params => { :limit => 3 } expect(response.parsed_body).to include("count" => 3, "subcount" => 2) end it "supports offset and limit" do create_vms_by_name(%w(aa bb cc)) get api_vms_url, :params => { :offset => 1, :limit => 1 } expect_query_result(:vms, 1, 3) end it "supports paging via offset and limit" do create_vms_by_name %w(aa bb cc dd ee) get api_vms_url, :params => { :offset => 0, :limit => 2, :sort_by => "name", :expand => "resources" } expect_query_result(:vms, 2, 5) expect_result_resources_to_match_hash([{"name" => "aa"}, {"name" => "bb"}]) get api_vms_url, :params => { :offset => 2, :limit => 2, :sort_by => "name", :expand => "resources" } expect_query_result(:vms, 2, 5) expect_result_resources_to_match_hash([{"name" => "cc"}, {"name" => "dd"}]) get api_vms_url, :params => { :offset => 4, :limit => 2, :sort_by => "name", :expand => "resources" } expect_query_result(:vms, 1, 5) expect_result_resources_to_match_hash([{"name" => "ee"}]) end it 'raises a BadRequestError for attributes that do not exist' do api_basic_authorize action_identifier(:vms, :read, :resource_actions, :get) get(api_vm_url(nil, vm1), :params => { :attributes => 'not_an_attribute' }) expected = { 'error' => a_hash_including( 'kind' => 'bad_request', 'message' => "Invalid attributes specified: not_an_attribute" ) } expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:bad_request) end it 'returns only id attributes if specified on a collection' do vm = FactoryBot.create(:vm) get(api_vms_url, :params => { :expand => :resources, :attributes => 'id' }) expected = { 'resources' => [{'href' => api_vm_url(nil, vm), 'id' => vm.id.to_s}] } expect(response.parsed_body).to include(expected) end it 'returns only id attributes if specified on a resource' do api_basic_authorize action_identifier(:vms, :read, :resource_actions, :get) get(api_vm_url(nil, vm1), :params => { :attributes => 'id' }) expect(response.parsed_body).to eq("href" => api_vm_url(nil, vm1), "id" => vm1.id.to_s) end it 'returns nil attributes when querying a resource' do api_basic_authorize action_identifier(:vms, :read, :resource_actions, :get) get(api_vm_url(nil, vm1)) expect(response.parsed_body).to include("id" => vm1.id.to_s, "retired" => nil, "smart" => nil) end it 'returns nil virtual attributes when querying a resource' do api_basic_authorize action_identifier(:vms, :read, :resource_actions, :get) get(api_vm_url(nil, vm1), :params => {:attributes => 'vmsafe_agent_port'}) expect(response.parsed_body).to include("id" => vm1.id.to_s, "vmsafe_agent_port" => nil) end it 'returns nil relationships when querying a resource' do api_basic_authorize action_identifier(:vms, :read, :resource_actions, :get) get(api_vm_url(nil, vm1), :params => {:attributes => 'direct_service'}) expect(response.parsed_body).to include("id" => vm1.id.to_s, "direct_service" => nil) end it 'returns nil attributes of relationships when querying a resource' do api_basic_authorize action_identifier(:vms, :read, :resource_actions, :get) zone = FactoryBot.create(:zone, :name => "query_zone") vm = FactoryBot.create(:vm_vmware, :host => FactoryBot.create(:host), :ems_id => FactoryBot.create(:ems_vmware, :zone => zone).id) get(api_vm_url(nil, vm), :params => {:attributes => 'ext_management_system.last_compliance_status'}) expect(response.parsed_body).to include("id" => vm.id.to_s, "ext_management_system" => {"last_compliance_status" => nil}) end it 'returns empty array for one-to-many relationships when querying a resource' do api_basic_authorize action_identifier(:vms, :read, :resource_actions, :get) get(api_vm_url(nil, vm1), :params => {:attributes => 'files'}) expect(response.parsed_body).to include("id" => vm1.id.to_s, "files" => []) end it "returns correct paging links" do create_vms_by_name %w(bb ff aa cc ee gg dd) get api_vms_url, :params => { :offset => 0, :limit => 2, :sort_by => "name", :expand => "resources" } expect_query_result(:vms, 2, 7) expect_result_resources_to_match_hash([{"name" => "aa"}, {"name" => "bb"}]) expect(response.parsed_body["links"].keys).to match_array(%w(self first next last)) links = response.parsed_body["links"] get(links["self"]) expect_query_result(:vms, 2, 7) expect_result_resources_to_match_hash([{"name" => "aa"}, {"name" => "bb"}]) get(links["next"]) expect_query_result(:vms, 2, 7) expect_result_resources_to_match_hash([{"name" => "cc"}, {"name" => "dd"}]) expect(response.parsed_body["links"].keys).to match_array(%w(self next previous first last)) get(links["last"]) expect_query_result(:vms, 1, 7) expect_result_resources_to_match_hash([{"name" => "gg"}]) previous = response.parsed_body["links"]["previous"] expect(response.parsed_body["links"].keys).to match_array(%w(self previous first last)) get(previous) expect_query_result(:vms, 2, 7) expect_result_resources_to_match_hash([{"name" => "ee"}, {"name" => "ff"}]) get api_vms_url, :params => { :offset => 4, :limit => 3, :sort_by => "name", :expand => "resources" } expect_query_result(:vms, 3, 7) expect_result_resources_to_match_hash([{"name" => "ee"}, {"name" => "ff"}, {"name" => "gg"}]) expect(response.parsed_body["links"].keys).to match_array(%w(self previous first last)) end it "returns `self`, `first` and `last` links when result set size < max results" do create_vms_by_name %w(aa bb) get api_vms_url expect(response.parsed_body).to include("links" => a_hash_including("self", "first", "last")) end it "returns the correct page count" do create_vms_by_name %w(aa bb cc dd) get api_vms_url, :params => { :offset => 0, :limit => 2 } expect(response.parsed_body['pages']).to eq(2) get api_vms_url, :params => { :offset => 0, :limit => 3 } expect(response.parsed_body['pages']).to eq(2) get api_vms_url, :params => { :offset => 0, :limit => 4 } expect(response.parsed_body['subquery_count']).to be_nil expect(response.parsed_body['pages']).to eq(1) get api_vms_url, :params => { :offset => 0, :limit => 4, :filter => ["name='aa'", "or name='bb'"] } expect(response.parsed_body['subquery_count']).to eq(2) expect(response.parsed_body['pages']).to eq(1) end it "returns the correct pages if filters are specified" do create_vms_by_name %w(aa bb cc) get api_vms_url, :params => { :sort_by => "name", :filter => ["name='aa'", "or name='bb'"], :expand => "resources", :offset => 0, :limit => 1 } expect_query_result(:vms, 1, 3) expect_result_resources_to_match_hash([{"name" => "aa"}]) expect(response.parsed_body["links"].keys).to match_array(%w(self next first last)) get response.parsed_body["links"]["next"] expect_query_result(:vms, 1, 3) expect_result_resources_to_match_hash([{"name" => "bb"}]) expect(response.parsed_body["links"].keys).to match_array(%w(self previous first last)) end it "returns the correct subquery_count" do create_vms_by_name %w(aa bb cc dd) get api_vms_url, :params => { :sort_by => "name", :filter => ["name='aa'", "or name='bb'", "or name='dd'"], :expand => "resources", :offset => 0, :limit => 1 } expect(response.parsed_body["subquery_count"]).to eq(3) expect_query_result(:vms, 1, 4) end end describe "Sorting vms by attribute" do before { api_basic_authorize collection_action_identifier(:vms, :read, :get) } %w[asc ascending].each do |sort_order| it "orders with sort_order of #{sort_order}" do create_vms_by_name %w[cc aa bb] get api_vms_url, :params => {:sort_by => "name", :sort_order => sort_order, :expand => "resources"} expect_query_result(:vms, 3, 3) expect_result_resources_to_match_hash([{"name" => "aa"}, {"name" => "bb"}, {"name" => "cc"}]) end end %w[desc descending].each do |sort_order| it "orders with sort_order of #{sort_order}" do create_vms_by_name %w[cc aa bb] get api_vms_url, :params => {:sort_by => "name", :sort_order => sort_order, :expand => "resources"} expect_query_result(:vms, 3, 3) expect_result_resources_to_match_hash([{"name" => "cc"}, {"name" => "bb"}, {"name" => "aa"}]) end end it "supports case insensitive ordering" do create_vms_by_name %w(B c a) get api_vms_url, :params => { :sort_by => "name", :sort_order => "asc", :sort_options => "ignore_case", :expand => "resources" } expect_query_result(:vms, 3, 3) expect_result_resources_to_match_hash([{"name" => "a"}, {"name" => "B"}, {"name" => "c"}]) end it "supports sorting with physical attributes" do FactoryBot.create(:vm_vmware, :vendor => "vmware", :name => "vmware_vm") FactoryBot.create(:vm_redhat, :vendor => "redhat", :name => "redhat_vm") get api_vms_url, :params => { :sort_by => "vendor", :sort_order => "asc", :expand => "resources" } expect_query_result(:vms, 2, 2) expect_result_resources_to_match_hash([{"name" => "redhat_vm"}, {"name" => "vmware_vm"}]) end it 'supports sql friendly virtual attributes' do host_foo = FactoryBot.create(:host, :name => 'foo') host_bar = FactoryBot.create(:host, :name => 'bar') host_zap = FactoryBot.create(:host, :name => 'zap') FactoryBot.create(:vm, :name => 'vm_foo', :host => host_foo) FactoryBot.create(:vm, :name => 'vm_bar', :host => host_bar) FactoryBot.create(:vm, :name => 'vm_zap', :host => host_zap) get api_vms_url, :params => { :sort_by => 'host_name', :sort_order => 'desc', :expand => 'resources' } expect_query_result(:vms, 3, 3) expect_result_resources_to_match_hash([{'name' => 'vm_zap'}, {'name' => 'vm_foo'}, {'name' => 'vm_bar'}]) end it 'does not support non sql friendly virtual attributes' do FactoryBot.create(:vm) get api_vms_url, :params => { :sort_by => 'aggressive_recommended_mem', :sort_order => 'asc' } expected = { 'error' => a_hash_including( 'message' => 'Vm cannot be sorted by aggressive_recommended_mem' ) } expect(response).to have_http_status(:bad_request) expect(response.parsed_body).to include(expected) end it 'allows sorting by asc when other filters are applied' do api_basic_authorize collection_action_identifier(:services, :read, :get) svc1, _svc2 = FactoryBot.create_list(:service, 2) dept = FactoryBot.create(:classification_department) FactoryBot.create(:classification_tag, :name => 'finance', :parent => dept) Classification.classify(svc1, 'department', 'finance') get( api_services_url, :params => { :sort_by => 'created_at', :filter => ['tags.name=/managed/department/finance'], :sort_order => 'asc', :limit => 20, :offset => 0 } ) expect(response).to have_http_status(:ok) expect(response.parsed_body['subcount']).to eq(1) end end describe "Filtering vms" do before { api_basic_authorize collection_action_identifier(:vms, :read, :get) } it "supports attribute equality test using double quotes" do _vm1, vm2 = create_vms_by_name(%w(aa bb)) get api_vms_url, :params => { :expand => "resources", :filter => ['name="bb"'] } expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm2.name, "guid" => vm2.guid}]) end it "supports attribute equality test using single quotes" do vm1, _vm2 = create_vms_by_name(%w(aa bb)) get api_vms_url, :params => { :expand => "resources", :filter => ["name='aa'"] } expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}]) end it "supports attribute pattern matching via %" do vm1, _vm2, vm3 = create_vms_by_name(%w(aa_B2 bb aa_A1)) get api_vms_url, :params => { :expand => "resources", :filter => ["name='aa%'"], :sort_by => "name" } expect_query_result(:vms, 2, 3) expect_result_resources_to_match_hash([{"name" => vm3.name, "guid" => vm3.guid}, {"name" => vm1.name, "guid" => vm1.guid}]) end it "supports attribute pattern matching via *" do vm1, _vm2, vm3 = create_vms_by_name(%w(aa_B2 bb aa_A1)) get api_vms_url, :params => { :expand => "resources", :filter => ["name='aa*'"], :sort_by => "name" } expect_query_result(:vms, 2, 3) expect_result_resources_to_match_hash([{"name" => vm3.name, "guid" => vm3.guid}, {"name" => vm1.name, "guid" => vm1.guid}]) end it "supports inequality test via !=" do vm1, _vm2, vm3 = create_vms_by_name(%w(aa bb cc)) get api_vms_url, :params => { :expand => "resources", :filter => ["name!='b%'"], :sort_by => "name" } expect_query_result(:vms, 2, 3) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}, {"name" => vm3.name, "guid" => vm3.guid}]) end it "supports NULL/nil equality test via =" do vm1, vm2 = create_vms_by_name(%w(aa bb)) vm2.update!(:retired => true) get api_vms_url, :params => { :expand => "resources", :filter => ["retired=NULL"] } expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}]) end it "supports NULL/nil inequality test via !=" do _vm1, vm2 = create_vms_by_name(%w(aa bb)) vm2.update!(:retired => true) get api_vms_url, :params => { :expand => "resources", :filter => ["retired!=nil"] } expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm2.name, "guid" => vm2.guid}]) end it "supports numerical less than comparison via <" do vm1, vm2, vm3 = create_vms_by_name(%w(aa bb cc)) get api_vms_url, :params => { :expand => "resources", :filter => ["id < #{vm3.id}"], :sort_by => "name" } expect_query_result(:vms, 2, 3) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}, {"name" => vm2.name, "guid" => vm2.guid}]) end it "supports numerical less than or equal comparison via <=" do vm1, vm2, _vm3 = create_vms_by_name(%w(aa bb cc)) get api_vms_url, :params => { :expand => "resources", :filter => ["id <= #{vm2.id}"], :sort_by => "name" } expect_query_result(:vms, 2, 3) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}, {"name" => vm2.name, "guid" => vm2.guid}]) end it "support greater than numerical comparison via >" do vm1, vm2 = create_vms_by_name(%w(aa bb)) get api_vms_url, :params => { :expand => "resources", :filter => ["id > #{vm1.id}"], :sort_by => "name" } expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm2.name, "guid" => vm2.guid}]) end it "supports greater or equal than numerical comparison via >=" do _vm1, vm2, vm3 = create_vms_by_name(%w(aa bb cc)) get api_vms_url, :params => { :expand => "resources", :filter => ["id >= #{vm2.id}"], :sort_by => "name" } expect_query_result(:vms, 2, 3) expect_result_resources_to_match_hash([{"name" => vm2.name, "guid" => vm2.guid}, {"name" => vm3.name, "guid" => vm3.guid}]) end it "supports compound logical OR comparisons" do vm1, vm2, vm3 = create_vms_by_name(%w(aa bb cc)) get( api_vms_url, :params => { :expand => "resources", :filter => ["id = #{vm1.id}", "or id > #{vm2.id}"], :sort_by => "name" } ) expect_query_result(:vms, 2, 3) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}, {"name" => vm3.name, "guid" => vm3.guid}]) end it "supports multiple logical AND comparisons" do vm1, _vm2 = create_vms_by_name(%w(aa bb)) get( api_vms_url, :params => { :expand => "resources", :filter => ["id = #{vm1.id}", "name = #{vm1.name}"] } ) expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}]) end it "supports multiple comparisons with both AND and OR" do vm1, vm2, vm3 = create_vms_by_name(%w(aa bb cc)) get( api_vms_url, :params => { :expand => "resources", :filter => ["id = #{vm1.id}", "name = #{vm1.name}", "or id > #{vm2.id}"], :sort_by => "name" } ) expect_query_result(:vms, 2, 3) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}, {"name" => vm3.name, "guid" => vm3.guid}]) end it "supports filtering by attributes of associations" do host1 = FactoryBot.create(:host, :name => "foo") host2 = FactoryBot.create(:host, :name => "bar") vm1 = FactoryBot.create(:vm_vmware, :name => "baz", :host => host1) _vm2 = FactoryBot.create(:vm_vmware, :name => "qux", :host => host2) get( api_vms_url, :params => { :expand => "resources", :filter => ["host.name='foo'"] } ) expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}]) end it "supports filtering by attributes of associations with paging" do host1 = FactoryBot.create(:host, :name => "foo") host2 = FactoryBot.create(:host, :name => "bar") vm1 = FactoryBot.create(:vm_vmware, :name => "baz", :host => host1) _vm2 = FactoryBot.create(:vm_vmware, :name => "qux", :host => host2) get( api_vms_url, :params => { :expand => "resources", :filter => ["host.name='foo'"], :offset => 0, :limit => 1 } ) expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm1.name, "guid" => vm1.guid}]) end it "does not support filtering by attributes of associations' associations" do get api_vms_url, :params => { :expand => "resources", :filter => ["host.hardware.memory_mb>1024"] } expect_bad_request(/Filtering of attributes with more than one association away is not supported/) end it "supports filtering by virtual string attributes" do host_a = FactoryBot.create(:host, :name => "aa") host_b = FactoryBot.create(:host, :name => "bb") vm_a = FactoryBot.create(:vm, :host => host_a) _vm_b = FactoryBot.create(:vm, :host => host_b) get(api_vms_url, :params => { :filter => ["host_name='aa'"], :expand => "resources" }) expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm_a.name, "guid" => vm_a.guid}]) end it "supports flexible filtering by virtual string attributes" do host_a = FactoryBot.create(:host, :name => "ab") host_b = FactoryBot.create(:host, :name => "cd") vm_a = FactoryBot.create(:vm, :host => host_a) _vm_b = FactoryBot.create(:vm, :host => host_b) get(api_vms_url, :params => { :filter => ["host_name='a%'"], :expand => "resources" }) expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm_a.name, "guid" => vm_a.guid}]) end it "supports filtering by virtual boolean attributes" do ems = FactoryBot.create(:ext_management_system) storage = FactoryBot.create(:storage) host = FactoryBot.create(:host, :storages => [storage]) _vm = FactoryBot.create(:vm, :host => host, :ext_management_system => ems) archived_vm = FactoryBot.create(:vm) get(api_vms_url, :params => { :filter => ["archived=true"], :expand => "resources" }) expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => archived_vm.name, "guid" => archived_vm.guid}]) end it "supports filtering by comparison of virtual integer attributes" do hardware_1 = FactoryBot.create(:hardware, :cpu_sockets => 4) hardware_2 = FactoryBot.create(:hardware, :cpu_sockets => 8) _vm_1 = FactoryBot.create(:vm, :hardware => hardware_1) vm_2 = FactoryBot.create(:vm, :hardware => hardware_2) get(api_vms_url, :params => { :filter => ["num_cpu > 4"], :expand => "resources" }) expect_query_result(:vms, 1, 2) expect_result_resources_to_match_hash([{"name" => vm_2.name, "guid" => vm_2.guid}]) end it "supports = with dates mixed with virtual attributes" do _vm_1 = FactoryBot.create(:vm, :retires_on => "2016-01-01", :vendor => "vmware") vm_2 = FactoryBot.create(:vm, :retires_on => "2016-01-02", :vendor => "vmware") _vm_3 = FactoryBot.create(:vm, :retires_on => "2016-01-02", :vendor => "openstack") get(api_vms_url, :params => { :filter => ["retires_on = 2016-01-02", "vendor_display = VMware"] }) expected = {"resources" => [{"href" => api_vm_url(nil, vm_2)}]} expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:ok) end it "supports > with dates mixed with virtual attributes" do _vm_1 = FactoryBot.create(:vm, :retires_on => "2016-01-01", :vendor => "vmware") vm_2 = FactoryBot.create(:vm, :retires_on => "2016-01-02", :vendor => "vmware") _vm_3 = FactoryBot.create(:vm, :retires_on => "2016-01-03", :vendor => "openstack") get(api_vms_url, :params => { :filter => ["retires_on > 2016-01-01", "vendor_display = VMware"] }) expected = {"resources" => [{"href" => api_vm_url(nil, vm_2)}]} expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:ok) end it "supports > with datetimes mixed with virtual attributes" do _vm_1 = FactoryBot.create(:vm, :last_scan_on => "2016-01-01T07:59:59Z", :vendor => "vmware") vm_2 = FactoryBot.create(:vm, :last_scan_on => "2016-01-01T08:00:00Z", :vendor => "vmware") _vm_3 = FactoryBot.create(:vm, :last_scan_on => "2016-01-01T08:00:00Z", :vendor => "openstack") get(api_vms_url, :params => { :filter => ["last_scan_on > 2016-01-01T07:59:59Z", "vendor_display = VMware"] }) expected = {"resources" => [{"href" => api_vm_url(nil, vm_2)}]} expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:ok) end it "supports < with dates mixed with virtual attributes" do _vm_1 = FactoryBot.create(:vm, :retires_on => "2016-01-01", :vendor => "openstack") vm_2 = FactoryBot.create(:vm, :retires_on => "2016-01-02", :vendor => "vmware") _vm_3 = FactoryBot.create(:vm, :retires_on => "2016-01-03", :vendor => "vmware") get(api_vms_url, :params => { :filter => ["retires_on < 2016-01-03", "vendor_display = VMware"] }) expected = {"resources" => [{"href" => api_vm_url(nil, vm_2)}]} expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:ok) end it "supports < with datetimes mixed with virtual attributes" do _vm_1 = FactoryBot.create(:vm, :last_scan_on => "2016-01-01T07:59:59Z", :vendor => "openstack") vm_2 = FactoryBot.create(:vm, :last_scan_on => "2016-01-01T07:59:59Z", :vendor => "vmware") _vm_3 = FactoryBot.create(:vm, :last_scan_on => "2016-01-01T08:00:00Z", :vendor => "vmware") get(api_vms_url, :params => { :filter => ["last_scan_on < 2016-01-01T08:00:00Z", "vendor_display = VMware"] }) expected = {"resources" => [{"href" => api_vm_url(nil, vm_2)}]} expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:ok) end it "does not support filtering with <= with datetimes" do get(api_vms_url, :params => { :filter => ["retires_on <= 2016-01-03"] }) expect(response.parsed_body).to include_error_with_message("Unsupported operator for datetime: <=") expect(response).to have_http_status(:bad_request) end it "does not support filtering with >= with datetimes" do get(api_vms_url, :params => { :filter => ["retires_on >= 2016-01-03"] }) expect(response.parsed_body).to include_error_with_message("Unsupported operator for datetime: >=") expect(response).to have_http_status(:bad_request) end it "does not support filtering with != with datetimes" do get(api_vms_url, :params => { :filter => ["retires_on != 2016-01-03"] }) expect(response.parsed_body).to include_error_with_message("Unsupported operator for datetime: !=") expect(response).to have_http_status(:bad_request) end it "will handle poorly formed datetimes in the filter" do get(api_vms_url, :params => { :filter => ["retires_on > foobar"] }) expect(response.parsed_body).to include_error_with_message("Bad format for datetime: foobar") expect(response).to have_http_status(:bad_request) end it "does not support filtering vms as a subcollection" do service = FactoryBot.create(:service) service << FactoryBot.create(:vm_vmware, :name => "foo") service << FactoryBot.create(:vm_vmware, :name => "bar") get(api_service_vms_url(nil, service), :params => { :filter => ["name=foo"] }) expect(response.parsed_body).to include_error_with_message("Filtering is not supported on vms subcollection") expect(response).to have_http_status(:bad_request) end it "can do fuzzy matching on strings with forward slashes" do tag_1 = FactoryBot.create(:classification, :name => "foo").tag _tag_2 = FactoryBot.create(:classification, :name => "bar") api_basic_authorize collection_action_identifier(:tags, :read, :get) get(api_tags_url, :params => { :filter => ["name='*/foo'"] }) expected = { "count" => 2, "subcount" => 1, "resources" => [{"href" => api_tag_url(nil, tag_1)}] } expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:ok) end it "returns a bad request if trying to filter on invalid attributes" do get(api_vms_url, :params => { :filter => ["destroy=true"] }) expected = { "error" => a_hash_including( "kind" => "bad_request", "message" => "Must filter on valid attributes for resource" ) } expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:bad_request) end end describe "Querying vm attributes" do it "supports requests specific attributes" do api_basic_authorize collection_action_identifier(:vms, :read, :get) vm = create_vms_by_name(%w(aa)).first get api_vms_url, :params => { :expand => "resources", :attributes => "href_slug,name,vendor" } expected = { "name" => "vms", "count" => 1, "subcount" => 1, "resources" => [ { "id" => vm.id.to_s, "href" => api_vm_url(nil, vm), "href_slug" => "vms/#{vm.id}", "name" => "aa", "vendor" => anything } ] } expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:ok) end end describe "Querying vms by tag" do it "is supported" do api_basic_authorize collection_action_identifier(:vms, :read, :get) vm1, _vm2, vm3 = create_vms_by_name(%w(aa bb cc)) dept = FactoryBot.create(:classification_department) FactoryBot.create(:classification_tag, :name => "finance", :description => "Finance", :parent => dept) Classification.classify(vm1, "department", "finance") Classification.classify(vm3, "department", "finance") get api_vms_url, :params => { :expand => "resources", :by_tag => "/department/finance" } expect_query_result(:vms, 2, 3) expect_result_resources_to_include_data("resources", "name" => [vm1.name, vm3.name]) end it "supports multiple comma separated tags" do api_basic_authorize collection_action_identifier(:vms, :read, :get) vm1, _vm2, vm3 = create_vms_by_name(%w(aa bb cc)) dept = FactoryBot.create(:classification_department) cc = FactoryBot.create(:classification_cost_center) FactoryBot.create(:classification_tag, :name => "finance", :description => "Finance", :parent => dept) FactoryBot.create(:classification_tag, :name => "cc01", :description => "Cost Center 1", :parent => cc) Classification.classify(vm1, "department", "finance") Classification.classify(vm1, "cc", "cc01") Classification.classify(vm3, "department", "finance") get api_vms_url, :params => { :expand => "resources", :by_tag => "/department/finance,/cc/cc01" } expect_query_result(:vms, 1, 3) expect_result_resources_to_include_data("resources", "name" => [vm1.name]) end end describe "Querying vms" do before { api_basic_authorize collection_action_identifier(:vms, :read, :get) } it "and sorted by name succeeeds with unreferenced class" do get api_vms_url, :params => { :sort_by => "name", :expand => "resources" } expect_query_result(:vms, 0, 0) end it "by invalid attribute" do get api_vms_url, :params => { :sort_by => "bad_attribute", :expand => "resources" } expect_bad_request("bad_attribute is not a valid attribute") end it "is supported without expanding resources" do create_vms_by_name(%w(aa bb)) get api_vms_url expected = { "name" => "vms", "count" => 2, "subcount" => 2, "resources" => Array.new(2) { {"href" => anything} } } expect(response.parsed_body).to include(expected) expect(response).to have_http_status(:ok) end it "supports expanding resources" do create_vms_by_name(%w(aa bb)) get api_vms_url, :params => { :expand => "resources" } expect_query_result(:vms, 2, 2) expect_result_resources_to_include_keys("resources", %w(id href guid name vendor)) end it "supports expanding resources and subcollections" do vm1 = create_vms_by_name(%w(aa)).first FactoryBot.create(:guest_application, :vm_or_template_id => vm1.id, :name => "LibreOffice") get api_vms_url, :params => { :expand => "resources,software" } expect_query_result(:vms, 1, 1) expect_result_resources_to_include_keys("resources", %w(id href guid name vendor software)) end it "supports suppressing resources" do FactoryBot.create(:vm) get(api_vms_url, :params => { :hide => "resources" }) expect(response.parsed_body).not_to include("resources") expect(response).to have_http_status(:ok) end end describe "Querying resources" do it "does not return actions if not entitled" do api_basic_authorize action_identifier(:vms, :read, :resource_actions, :get) get api_vm_url(nil, vm1) expect(response).to have_http_status(:ok) expect(response.parsed_body).to_not have_key("actions") end it "returns actions if authorized" do api_basic_authorize action_identifier(:vms, :edit), action_identifier(:vms, :read, :resource_actions, :get) get api_vm_url(nil, vm1) expect(response).to have_http_status(:ok) expect_result_to_have_keys(%w(id href name vendor actions)) end it "returns correct actions if authorized as such" do api_basic_authorize action_identifier(:vms, :suspend), action_identifier(:vms, :read, :resource_actions, :get) get api_vm_url(nil, vm1) expect(response).to have_http_status(:ok) expect_result_to_have_keys(%w(id href name vendor actions)) actions = response.parsed_body["actions"] expect(actions.size).to eq(1) expect(actions.first["name"]).to eq("suspend") end it 'returns correct actions on a collection' do api_basic_authorize(collection_action_identifier(:vms, :read, :get), action_identifier(:vms, :start), action_identifier(:vms, :stop)) get(api_vms_url) actions = response.parsed_body['actions'] expect(actions.size).to eq(3) expect(actions.collect { |a| a['name'] }).to match_array(%w(start stop query)) expect_result_to_have_keys(%w(name count subcount resources actions)) end it 'returns correct actions on a subcollection' do api_basic_authorize subcollection_action_identifier(:vms, :snapshots, :read, :get), subcollection_action_identifier(:vms, :snapshots, :delete, :post), subcollection_action_identifier(:vms, :snapshots, :create, :post) vm = FactoryBot.create(:vm) FactoryBot.create(:snapshot, :vm_or_template => vm) get(api_vm_snapshots_url(nil, vm)) actions = response.parsed_body['actions'] expect(actions.size).to eq(2) expect(actions.collect { |a| a['name'] }).to match_array(%w(create delete)) expect_result_to_have_keys(%w(name count subcount resources actions)) end it 'returns the correct actions on a subresource' do api_basic_authorize subcollection_action_identifier(:vms, :snapshots, :delete, :post), subcollection_action_identifier(:vms, :snapshots, :read, :get), subcollection_action_identifier(:vms, :snapshots, :create, :post) vm = FactoryBot.create(:vm) snapshot = FactoryBot.create(:snapshot, :vm_or_template => vm) get(api_vm_snapshot_url(nil, vm, snapshot)) actions = response.parsed_body['actions'] expect(actions.size).to eq(2) expect(actions.collect { |a| a['name'] }).to match_array(%w(delete delete)) expect_result_to_have_keys(%w(href id actions)) end it "returns multiple actions if authorized as such" do api_basic_authorize(action_identifier(:vms, :start), action_identifier(:vms, :stop), action_identifier(:vms, :read, :resource_actions, :get)) get api_vm_url(nil, vm1) expect(response).to have_http_status(:ok) expect_result_to_have_keys(%w(id href name vendor actions)) expect(response.parsed_body["actions"].collect { |a| a["name"] }).to match_array(%w(start stop)) end it "returns actions if asked for with physical attributes" do api_basic_authorize action_identifier(:vms, :start), action_identifier(:vms, :read, :resource_actions, :get) get api_vm_url(nil, vm1), :params => { :attributes => "name,vendor,actions" } expect(response).to have_http_status(:ok) expect_result_to_have_only_keys(%w(id href name vendor actions)) end it "does not return actions if asking for a physical attribute" do api_basic_authorize action_identifier(:vms, :start), action_identifier(:vms, :read, :resource_actions, :get) get api_vm_url(nil, vm1), :params => { :attributes => "name" } expect(response).to have_http_status(:ok) expect_result_to_have_only_keys(%w(id href name)) end it "does return actions if asking for virtual attributes" do api_basic_authorize action_identifier(:vms, :start), action_identifier(:vms, :read, :resource_actions, :get) get api_vm_url(nil, vm1), :params => { :attributes => "disconnected" } expect(response).to have_http_status(:ok) expect_result_to_have_keys(%w(id href name vendor disconnected actions)) end it "does not return actions if asking for physical and virtual attributes" do api_basic_authorize action_identifier(:vms, :start), action_identifier(:vms, :read, :resource_actions, :get) get api_vm_url(nil, vm1), :params => { :attributes => "name,disconnected" } expect(response).to have_http_status(:ok) expect_result_to_have_only_keys(%w(id href name disconnected)) end end describe 'OPTIONS /api/vms' do it 'returns the options information' do options(api_vms_url) expect_options_results(:vms, {}) end end describe "with optional collection_class" do before { api_basic_authorize collection_action_identifier(:vms, :read, :get) } it "fail with invalid collection_class specified" do get api_vms_url, :params => { :collection_class => "BogusClass" } expect_bad_request("Invalid collection_class BogusClass specified for the vms collection") end it "succeed with collection_class matching the collection class" do create_vms_by_name(%w(aa bb)) get api_vms_url, :params => { :collection_class => "Vm" } expect_query_result(:vms, 2, 2) end it "succeed with collection_class matching the collection class and returns subclassed resources" do FactoryBot.create(:vm_vmware, :name => "aa") FactoryBot.create(:vm_vmware_cloud, :name => "bb") FactoryBot.create(:vm_vmware_cloud, :name => "cc") get api_vms_url, :params => { :expand => "resources", :collection_class => "Vm" } expect_query_result(:vms, 3, 3) expect(response.parsed_body["resources"].collect { |vm| vm["name"] }).to match_array(%w(aa bb cc)) end it "succeed with collection_class and only returns subclassed resources" do FactoryBot.create(:vm_vmware, :name => "aa") FactoryBot.create(:vm_vmware_cloud, :name => "bb") vmcc = FactoryBot.create(:vm_vmware_cloud, :name => "cc") get api_vms_url, :params => { :expand => "resources", :collection_class => vmcc.class.name } expect_query_result(:vms, 2, 2) expect(response.parsed_body["resources"].collect { |vm| vm["name"] }).to match_array(%w(bb cc)) end end end
39.356367
165
0.628323
eddd8f8222684f075e033c518f737d22a7241de3
136
class RenameServicesServiceId < ActiveRecord::Migration[5.2] def change rename_column :bookings, :services, :service_id end end
22.666667
60
0.772059
e2666f56a5fc22b2285956468a391d89e0363f5b
741
require 'spec_helper' describe MetasploitDataModels::Search::Operation::Port::Number do context 'CONSTANTS' do context 'BITS' do subject(:bits) { described_class::BITS } it { should == 16 } end context 'MAXIMUM' do subject(:maxium) { described_class::MAXIMUM } it { should == 65535 } end context 'MINIMUM' do subject(:minimum) { described_class::MINIMUM } it { should == 0 } end context 'RANGE' do subject(:range) { described_class::RANGE } it { should == (0..65535) } end end context 'validations' do it { should ensure_inclusion_of(:value).in_range(described_class::RANGE) } end end
18.073171
78
0.580297
5dbf89faf73c467470ef82fe4c93aba830775b75
2,094
# The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. config.cache_classes = false config.action_view.cache_template_loading = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{1.hour.to_i}" } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false config.cache_store = :null_store # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Store uploaded files on the local file system in a temporary directory. config.active_storage.service = :test config.action_mailer.perform_caching = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test config.action_mailer.default_url_options = { host: 'example.com' } # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations. # config.action_view.raise_on_missing_translations = true config.active_record.sqlite3.represent_boolean_as_integer = true end
39.509434
85
0.776982
1a2c1e122a2fc0cb71e4ca227925c83003c489bb
479
#------------------------------------------------------------------------------ # # WARNING ! # # This is a generated file. DO NOT EDIT THIS FILE! Your changes will # be lost the next time this file is regenerated. # # This file was generated using asterisk-ari-client ruby gem. # #------------------------------------------------------------------------------ module Ari class BuildInfo < Model attr_reader :os, :kernel, :options, :machine, :date, :user end end
23.95
79
0.461378
08bbd331c30c0783ff7123b43c36d8a86fbdee0b
6,025
# frozen_string_literal: true module Solargraph module Parser module Legacy # A factory for generating chains from nodes. # class NodeChainer include NodeMethods Chain = Source::Chain # @param node [Parser::AST::Node] # @param filename [String] def initialize node, filename = nil, in_block = false @node = node @filename = filename @in_block = in_block ? 1 : 0 end # @return [Source::Chain] def chain links = generate_links(@node) Chain.new(links, @node, (Parser.is_ast_node?(@node) && @node.type == :splat)) end class << self # @param node [Parser::AST::Node] # @param filename [String] # @return [Source::Chain] def chain node, filename = nil, in_block = false NodeChainer.new(node, filename, in_block).chain end # @param code [String] # @return [Source::Chain] def load_string(code) node = Parser.parse(code.sub(/\.$/, '')) chain = NodeChainer.new(node).chain chain.links.push(Chain::Link.new) if code.end_with?('.') chain end end private # @param n [Parser::AST::Node] # @return [Array<Chain::Link>] def generate_links n return [] unless n.is_a?(::Parser::AST::Node) return generate_links(n.children[0]) if n.type == :begin return generate_links(n.children[0]) if n.type == :splat result = [] if n.type == :block @in_block += 1 result.concat generate_links(n.children[0]) @in_block -= 1 elsif n.type == :send if n.children[0].is_a?(::Parser::AST::Node) result.concat generate_links(n.children[0]) args = [] n.children[2..-1].each do |c| args.push NodeChainer.chain(c) end result.push Chain::Call.new(n.children[1].to_s, args, @in_block > 0 || block_passed?(n)) elsif n.children[0].nil? args = [] n.children[2..-1].each do |c| args.push NodeChainer.chain(c) end result.push Chain::Call.new(n.children[1].to_s, args, @in_block > 0 || block_passed?(n)) else raise "No idea what to do with #{n}" end elsif n.type == :csend if n.children[0].is_a?(::Parser::AST::Node) result.concat generate_links(n.children[0]) args = [] n.children[2..-1].each do |c| args.push NodeChainer.chain(c) end result.push Chain::QCall.new(n.children[1].to_s, args, @in_block > 0 || block_passed?(n)) elsif n.children[0].nil? args = [] n.children[2..-1].each do |c| args.push NodeChainer.chain(c) end result.push Chain::QCall.new(n.children[1].to_s, args, @in_block > 0 || block_passed?(n)) else raise "No idea what to do with #{n}" end elsif n.type == :self result.push Chain::Head.new('self') elsif n.type == :zsuper result.push Chain::ZSuper.new('super', @in_block > 0 || block_passed?(n)) elsif n.type == :super args = n.children.map { |c| NodeChainer.chain(c) } result.push Chain::Call.new('super', args, @in_block > 0 || block_passed?(n)) elsif n.type == :const const = unpack_name(n) result.push Chain::Constant.new(const) elsif [:lvar, :lvasgn].include?(n.type) result.push Chain::Call.new(n.children[0].to_s) elsif [:ivar, :ivasgn].include?(n.type) result.push Chain::InstanceVariable.new(n.children[0].to_s) elsif [:cvar, :cvasgn].include?(n.type) result.push Chain::ClassVariable.new(n.children[0].to_s) elsif [:gvar, :gvasgn].include?(n.type) result.push Chain::GlobalVariable.new(n.children[0].to_s) elsif n.type == :or_asgn result.concat generate_links n.children[1] elsif [:class, :module, :def, :defs].include?(n.type) # @todo Undefined or what? result.push Chain::UNDEFINED_CALL elsif n.type == :and result.concat generate_links(n.children.last) elsif n.type == :or result.push Chain::Or.new([NodeChainer.chain(n.children[0], @filename), NodeChainer.chain(n.children[1], @filename)]) elsif [:begin, :kwbegin].include?(n.type) result.concat generate_links(n.children[0]) elsif n.type == :block_pass result.push Chain::BlockVariable.new("&#{n.children[0].children[0].to_s}") elsif n.type == :hash result.push Chain::Hash.new('::Hash', hash_is_splatted?(n)) else lit = infer_literal_node_type(n) # if lit == '::Hash' # result.push Chain::Hash.new(lit, hash_is_splatted?(n)) # else result.push (lit ? Chain::Literal.new(lit) : Chain::Link.new) # end end result end def hash_is_splatted? node return false unless Parser.is_ast_node?(node) && node.type == :hash return false unless Parser.is_ast_node?(node.children.last) && node.children.last.type == :kwsplat return false if Parser.is_ast_node?(node.children.last.children[0]) && node.children.last.children[0].type == :hash true end def block_passed? node node.children.last.is_a?(::Parser::AST::Node) && node.children.last.type == :block_pass end end end end end
40.436242
130
0.524149
338d8c4d5330114a340a0cbdbf3e1b1f5d5d1fb8
1,160
module Deliveries module Couriers module Ups module JsonRequest private def call(body, method: :post, url_params: {}, query_params: {}) plain_response = HTTParty.public_send( method, api_endpoint % url_params, body: body&.to_json, query: query_params, headers: headers, debug_output: Deliveries.debug ? Deliveries.logger : nil, format: :plain ) response = JSON.parse plain_response, symbolize_names: true if response.dig(:response, :errors).present? error_code = response.dig(:response, :errors, 0, :code)&.to_i error_message = response.dig(:response, :errors, 0, :message) || 'Unknown error' raise APIError.new(error_message, error_code) end response end def headers { 'Content-Type': 'application/json', AccessLicenseNumber: Ups.config(:license_number), Username: Ups.config(:username), Password: Ups.config(:password) } end end end end end
28.292683
92
0.562069
085f25e296afdc620f49eee2d25c4094e031b2da
1,292
# frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = 'mitamae-plugin-resource-apt-repository' spec.version = '0.0.1' spec.authors = ['Moritz Heiber'] spec.email = ['[email protected]'] spec.summary = 'mitamae plugin resource apt_repository' spec.description = 'mitamae plugin resource apt_repository' spec.license = 'MIT' spec.homepage = 'https://github.com/moritzheiber/mitamae-plugin-resource-apt-repository' # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or # delete this section to allow pushing this gem to any host. if spec.respond_to?(:metadata) spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'" else raise 'RubyGems 2.0 or newer is required to protect against public gem pushes.' end spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = 'exe' spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ['lib'] spec.add_dependency 'mitamae', '~> 1.2' spec.add_development_dependency 'bundler', '~> 1.10' end
39.151515
104
0.674149
f79faf984674b3a77f8806d790078234fb89be21
333
class Squares SQUARE = 2 private_constant :SQUARE def initialize(number) @sum = (1..number).method(:sum) end def square_of_sum sum.call**SQUARE end def sum_of_squares sum.call { |number| number**SQUARE } end def difference square_of_sum - sum_of_squares end private attr_reader :sum end
13.32
40
0.678679
e2cd29bf95b68a39beda5f796b10a66a03449f45
311
class CreateGuideTaxa < ActiveRecord::Migration def change create_table :guide_taxa do |t| t.integer :guide_id t.integer :taxon_id t.string :name t.string :display_name t.timestamps end add_index :guide_taxa, :guide_id add_index :guide_taxa, :taxon_id end end
20.733333
47
0.678457
281d91c6a462aa28f66db2fe44f2d21032eb37bf
2,351
require 'spec_helper' describe 'collectd::plugin::exec', :type => :class do let :facts do { :osfamily => 'Debian', :concat_basedir => tmpfilename('collectd-exec'), :id => 'root', :kernel => 'Linux', :path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', :collectd_version => '5.0' } end context 'single command' do let :params do { :commands => { 'hello' => { 'user' => 'nobody', 'group' => 'users', 'exec' => ['/bin/echo', 'hello world'] } }, } end it 'Will create /etc/collectd.d/conf.d/exec-config.conf' do should contain_concat__fragment('collectd_plugin_exec_conf_header') .with(:content => /<Plugin exec>/, :target => '/etc/collectd/conf.d/exec-config.conf', :order => '00') end it 'Will create /etc/collectd.d/conf.d/exec-config' do should contain_concat__fragment('collectd_plugin_exec_conf_footer') .with(:content => %r{</Plugin>}, :target => '/etc/collectd/conf.d/exec-config.conf', :order => '99') end it 'includes exec statement' do should contain_concat__fragment('collectd_plugin_exec_conf_hello') .with(:content => %r{Exec "nobody:users" "/bin/echo" "hello world"}, :target => '/etc/collectd/conf.d/exec-config.conf',) end end context 'multiple commands' do let :params do { :commands => { 'hello' => { 'user' => 'nobody', 'group' => 'users', 'exec' => ['/bin/echo', 'hello world'] }, 'my_date' => { 'user' => 'nobody', 'group' => 'users', 'exec' => ['/bin/date'] } }, } end it 'includes echo statement' do should contain_concat__fragment('collectd_plugin_exec_conf_hello') .with(:content => %r{Exec "nobody:users" "/bin/echo" "hello world"}, :target => '/etc/collectd/conf.d/exec-config.conf',) end it 'includes date statement' do should contain_concat__fragment('collectd_plugin_exec_conf_my_date') .with(:content => %r{Exec "nobody:users" "/bin/date"}, :target => '/etc/collectd/conf.d/exec-config.conf',) end end end
32.652778
92
0.540621
391e14b9b60e3b2d09441d9464f126ed46aca38c
59
module Marvel module Api VERSION = "0.1.0" end end
9.833333
21
0.627119
5d8da2c7394c247f5d34b64178e6034fb628cf70
746
require 'active_support/concern' require 'rails/rack/logger' # Borrowed from [lograge](https://github.com/roidrage/lograge) # The MIT License (MIT) # Copyright (c) 2016 Mathias Meyer module Rails module Rack # Overwrites defaults of Rails::Rack::Logger that cause # unnecessary logging. # This effectively removes the log lines from the log # that say: # Started GET / for 192.168.2.1... class Logger # Overwrites Rails 3.2 code that logs new requests def call_app(*args) env = args.last @app.call(env) ensure ActiveSupport::LogSubscriber.flush_all! end # Overwrites Rails 3.0/3.1 code that logs new requests def before_dispatch(_env); end end end end
26.642857
62
0.671582
f88bf237301f1ee9dcb1be8a12ef5314612540fa
1,119
require 'rails_helper' describe 'Sub-group project issue boards', :feature, :js do let(:group) { create(:group) } let(:nested_group_1) { create(:group, parent: group) } let(:project) { create(:empty_project, group: nested_group_1) } let(:board) { create(:board, project: project) } let(:label) { create(:label, project: project) } let(:user) { create(:user) } let!(:list1) { create(:list, board: board, label: label, position: 0) } let!(:issue) { create(:labeled_issue, project: project, labels: [label]) } before do project.add_master(user) sign_in(user) visit project_board_path(project, board) wait_for_requests end it 'creates new label from sidebar' do find('.card').click page.within '.labels' do click_link 'Edit' click_link 'Create new label' end page.within '.dropdown-new-label' do fill_in 'new_label_name', with: 'test label' first('.suggest-colors-dropdown a').click click_button 'Create' wait_for_requests end page.within '.labels' do expect(page).to have_link 'test label' end end end
25.431818
76
0.659517
28bc43e7c61f0d5f729e81fbf02faa860883404b
86
module Clockpicker module Rails class Railtie < ::Rails::Railtie; end end end
14.333333
41
0.709302
26472bfad1ef524d75db7c2007d4e3fad84bb2aa
1,886
# # Author:: Adam Jacob (<[email protected]>) # Author:: Seth Chisamore (<[email protected]>) # Copyright:: Copyright (c) 2008, 2011 Opscode, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require 'chef/resource/file' require 'chef/provider/template' require 'chef/mixin/securable' class Chef class Resource class Template < Chef::Resource::File include Chef::Mixin::Securable provides :template, :on_platforms => :all def initialize(name, run_context=nil) super @resource_name = :template @action = "create" @source = "#{::File.basename(name)}.erb" @cookbook = nil @local = false @variables = Hash.new @provider = Chef::Provider::Template end def source(file=nil) set_or_return( :source, file, :kind_of => [ String ] ) end def variables(args=nil) set_or_return( :variables, args, :kind_of => [ Hash ] ) end def cookbook(args=nil) set_or_return( :cookbook, args, :kind_of => [ String ] ) end def local(args=nil) set_or_return( :local, args, :kind_of => [ TrueClass, FalseClass ] ) end end end end
24.493506
74
0.604454
ab7504cedac66e3b523253b6450c27ba8deaf867
1,342
# frozen_string_literal: true # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! module Google module Cloud module ResourceManager module V3 module TagBindings # Path helper methods for the TagBindings API. module Paths ## # Create a fully-qualified TagBinding resource string. # # The resource will be in the following format: # # `tagBindings/{tag_binding}` # # @param tag_binding [String] # # @return [::String] def tag_binding_path tag_binding: "tagBindings/#{tag_binding}" end extend self end end end end end end
27.958333
74
0.628912
e2b7f556405655081c7a78f142b0fe52a124f094
2,533
# Extracted from dm-validations 0.9.10 # # Copyright (c) 2007 Guy van den Berg # # 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. module CouchRest module Validation ## # # @author Guy van den Berg class AbsentFieldValidator < GenericValidator def initialize(field_name, options={}) super @field_name, @options = field_name, options end def call(target) value = target.send(field_name) return true if (value.nil? || (value.respond_to?(:empty?) && value.empty?)) error_message = @options[:message] || ValidationErrors.default_error_message(:absent, field_name) add_error(target, error_message, field_name) return false end end # class AbsentFieldValidator module ValidatesAbsent ## # # @example [Usage] # # class Page # # property :unwanted_attribute, String # property :another_unwanted, String # property :yet_again, String # # validates_absent :unwanted_attribute # validates_absent :another_unwanted, :yet_again # # # a call to valid? will return false unless # # all three attributes are blank # end # def validates_absent(*fields) opts = opts_from_validator_args(fields) add_validator_to_context(opts, fields, CouchRest::Validation::AbsentFieldValidator) end end # module ValidatesAbsent end # module Validation end # module CouchRest
33.773333
105
0.69246
032609b5788c1395e422226accb99502bbcdeb05
2,342
class Github::CheckSuite < ApplicationRecord BLOCKED_AUTHORS = %w[ tensorflow-copybara gatsbybot ].freeze attr_accessor :github_token, :github_run_id, :repository_full_name, :head_sha, :pull_request_number, :head_branch, :actor, :configuration, :custom_configuration_file, :custom_configuration_valid, :check_run_id, :conclusion, :started_at, :completed_at, :files_analysed_count, :spelling_mistakes_count, :invalid_words, :annotations, :file_name_extensions, :sender_type, :repository_private alias custom_configuration_valid? custom_configuration_valid alias custom_configuration_file? custom_configuration_file def initialize(github_token: nil, github_run_id: nil, repository_full_name: nil, head_branch: nil, head_sha: nil, pull_request_number: nil, actor: nil, sender_type: nil, repository_private: nil) @github_token = github_token @github_run_id = github_run_id @repository_full_name = repository_full_name @head_branch = head_branch @head_sha = head_sha @pull_request_number = pull_request_number @actor = actor @sender_type = sender_type @repository_private = repository_private @conclusion = 'pending' @configuration = nil @custom_configuration_file = false @custom_configuration_valid = false end def to_gid_param github_run_id end def analysable? return false if actor_banned? return false if gh_pages_branch? && !pull_request? true end def gh_pages_branch? head_branch.present? && head_branch.include?('gh-pages') end def pull_request? pull_request_number.present? end def custom_configuration_present_and_invalid? custom_configuration_file? && !custom_configuration_valid? end def time_processing @started_at = Time.zone.now yield @completed_at = Time.zone.now end def processing_duration return nil if @completed_at.nil? @completed_at.to_i - @started_at.to_i end private def actor_banned? sender_type == 'Bot' || actor.in?(BLOCKED_AUTHORS) end end
26.314607
196
0.660974
5ddd3e91eef65fe9c99e454040f1e4b4c47027e0
228
class AddSoapServiceArchivedAtField < ActiveRecord::Migration def self.up add_column :soap_services, :archived_at, :datetime, :default => nil end def self.down remove_column :soap_services, :archived_at end end
22.8
71
0.758772
bf2a7c3408187649c62dfe318b0bd39583854974
117
class Comment < ApplicationRecord belongs_to :coliving, optional: true belongs_to :coworking, optional: true end
23.4
39
0.794872
28629f3cb186c235d4b0567f364aae7d3839637b
578
$:.unshift(File.expand_path(File.join(File.dirname(__FILE__), "/../lib"))) ARGV << "-b" require "rubygems" require "bundler" Bundler.setup #require "vendor/gems/environment" require "ostruct" require "spec" require "spec/autorun" require "redis" require "merb" require "rack/cache" require "rack/cache/metastore" require "rack/cache/entitystore" require "redis-store" require "active_support" require "action_controller/session/abstract_store" require "cache/rails/redis_store" require "rack/session/rails" require "cache/sinatra/redis_store" $DEBUG = ENV["DEBUG"] === "true"
24.083333
74
0.762976
b9a859e17c52d40389cacee83f9a4d0d4070913f
167
# frozen_string_literal: true HOMEBREW_PREFIX = Pathname("/usr/local").freeze HOMEBREW_REPOSITORY = Pathname("/usr/local/Homebrew").freeze HOMEBREW_VERSION = "2.6.0"
27.833333
60
0.778443
bfd6a3a95f3bba43d3a18eabb491f59f243f3941
317
# frozen_string_literal: true class AddSystemToChatRooms < ActiveRecord::Migration[6.1] def change add_column(:chat_rooms, :system, :boolean, default: false, null: false) add_index(:chat_rooms, :user_id, unique: true, where: 'system = true', name: 'index_on_chat_rooms_user_id_where_system_true') end end
39.625
129
0.763407
bfb1ad3398c06bea6b58de3c9c3e49da4357ab39
1,318
class Glide < Formula desc "Simplified Go project management, dependency management, and vendoring" homepage "https://github.com/Masterminds/glide" url "https://github.com/Masterminds/glide/archive/v0.13.1.tar.gz" sha256 "84c4e365c9f76a3c8978018d34b4331b0c999332f628fc2064aa79a5a64ffc90" head "https://github.com/Masterminds/glide.git" bottle do cellar :any_skip_relocation sha256 "78889b92f507a115f040eacdbcc58822e411f11ba98c7ce5eef0b14eb17dc78b" => :mojave sha256 "caf9796752ea6c302aad5ccb6d2d415961e338743ad93a849c012654f1826057" => :high_sierra sha256 "31aa6f3b39c0a101dd94e9dda1a7d76fa6d22d8865effa0e96ae5d61d799233e" => :sierra sha256 "9a400081061df8e2cbd82463b763e20e2029df47f750a8622ba6e3e81f21fa66" => :el_capitan end depends_on "go" def install ENV["GOPATH"] = buildpath glidepath = buildpath/"src/github.com/Masterminds/glide" glidepath.install buildpath.children cd glidepath do system "go", "build", "-o", "glide", "-ldflags", "-X main.version=#{version}" bin.install "glide" prefix.install_metafiles end end test do assert_match version.to_s, shell_output("#{bin}/glide --version") system bin/"glide", "create", "--non-interactive", "--skip-import" assert_predicate testpath/"glide.yaml", :exist? end end
36.611111
93
0.751897
d56b398b529b08eb9f9738808a02b36b5bc15fe8
602
require 'pycall/error' module PyCall class PyError < Error def initialize(type, value, traceback) @type = type @value = value @traceback = traceback super("Exception occurred in Python") end attr_reader :type, :value, :traceback def to_s "#{type}: #{value}".tap do |msg| if (strs = format_traceback) msg << "\n" strs.each {|s| msg << s } end end end private def format_traceback return nil if traceback.nil? ::PyCall.import_module('traceback').format_tb(traceback) end end end
19.419355
62
0.584718
62cfef8ded87915a2bab727f3b612a0d2bcc7c1c
5,643
require 'simplecov' require 'rubygems' SimpleCov.start 'rails' do add_filter '/test/' add_filter '/config/' add_group 'Controllers', 'app/controllers' add_group 'Models', 'app/models' add_group 'Concerns', 'app/concerns' add_group 'Datatables', 'app/datatables' add_group 'Helpers', 'app/helpers' add_group 'Serializers', 'app/serializers' add_group 'Services', 'app/services' add_group 'Validators', 'app/validators' add_group 'Jobs', 'app/jobs' end SimpleCov.coverage_dir 'coverage/rspec' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} Capybara.register_driver :selenium do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end #Capybara.current_driver = :selenium #Capybara.javascript_driver = :poltergeist Capybara.javascript_driver = :selenium Capybara.ignore_hidden_elements = false Capybara.default_max_wait_time = 10 Capybara.save_path = "spec/artifacts" Capybara.asset_host = "http://localhost:3000" RSpec.configure do |config| config.include Devise::Test::ControllerHelpers, :type => :controller config.include Warden::Test::Helpers config.include ApplicationHelper config.include ActiveJob::TestHelper Warden.test_mode! Devise.setup do |config| config.stretches = 1 end # rspec-expectations config goes here. You can use an alternate # rspec-expectations config goes here. You can use an alternate # assertion/expectation library such as wrong or the stdlib/minitest # assertions if you prefer. config.expect_with :rspec do |expectations| # This option will default to `true` in RSpec 4. It makes the `description` # and `failure_message` of custom matchers include text for helper methods # defined using `chain`, e.g.: # be_bigger_than(2).and_smaller_than(4).description # # => "be bigger than 2 and smaller than 4" # ...rather than: # # => "be bigger than 2" expectations.include_chain_clauses_in_custom_matcher_descriptions = true end # rspec-mocks config goes here. You can use an alternate test double # library (such as bogus or mocha) by changing the `mock_with` option here. config.mock_with :rspec do |mocks| # Prevents you from mocking or stubbing a method that does not exist on # a real object. This is generally recommended, and will default to # `true` in RSpec 4. mocks.verify_partial_doubles = true end # This option will default to `:apply_to_host_groups` in RSpec 4 (and will # have no way to turn it off -- the option exists only for backwards # compatibility in RSpec 3). It causes shared context metadata to be # inherited by the metadata hash of host groups and examples, rather than # triggering implicit auto-inclusion in groups with matching metadata. config.shared_context_metadata_behavior = :apply_to_host_groups config.order = "random" config.before(:suite) do DatabaseCleaner.strategy = :truncation end config.before(:each) do DatabaseCleaner.start end config.after(:each) do DatabaseCleaner.clean Warden.test_reset! ActiveJob::Base.queue_adapter.enqueued_jobs = [] ActiveJob::Base.queue_adapter.performed_jobs = [] end # The settings below are suggested to provide a good initial experience # with RSpec, but feel free to customize to your heart's content. =begin # This allows you to limit a spec run to individual examples or groups # you care about by tagging them with `:focus` metadata. When nothing # is tagged with `:focus`, all examples get run. RSpec also provides # aliases for `it`, `describe`, and `context` that include `:focus` # metadata: `fit`, `fdescribe` and `fcontext`, respectively. config.filter_run_when_matching :focus # Allows RSpec to persist some state between runs in order to support # the `--only-failures` and `--next-failure` CLI options. We recommend # you configure your source control system to ignore this file. config.example_status_persistence_file_path = "spec/examples.txt" # Limits the available syntax to the non-monkey patched syntax that is # recommended. For more details, see: # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode config.disable_monkey_patching! # Many RSpec users commonly either run the entire suite or an individual # file, and it's useful to allow more verbose output when running an # individual spec file. if config.files_to_run.one? # Use the documentation formatter for detailed output, # unless a formatter has already been configured # (e.g. via a command-line flag). config.default_formatter = 'doc' end # Print the 10 slowest examples and example groups at the # end of the spec run, to help surface which specs are running # particularly slow. config.profile_examples = 10 # Run specs in random order to surface order dependencies. If you find an # order dependency and want to debug it, you can fix the order by providing # the seed, which is printed after each run. # --seed 1234 config.order = :random # Seed global randomization in this process using the `--seed` CLI option. # Setting this allows you to use `--seed` to deterministically reproduce # test failures related to randomization by passing the same `--seed` value # as the one that triggered the failure. Kernel.srand config.seed =end end
38.128378
92
0.737551
1d37cdc46fc8bbcb5e8f27edacfd656175ce2d35
2,719
require 'test_helper' # require 'test/model_stub' #require File.join(File.dirname(__FILE__), '../../lib/active_scaffold/data_structures/set.rb') class ActionColumnsTest < MiniTest::Test def setup @columns = ActiveScaffold::DataStructures::ActionColumns.new([:a, :b]) @columns.action = stub(:core => stub(:model_id => 'model_stub')) end def test_label refute_equal 'foo', @columns.label @columns.label = 'foo' assert_equal 'foo', @columns.label end def test_initialization assert @columns.include?(:a) assert @columns.include?(:b) refute @columns.include?(:c) end def test_exclude # exclude with a symbol assert @columns.include?(:b) @columns.exclude :b refute @columns.include?(:b) # exclude with a string assert @columns.include?(:a) @columns.exclude 'a' refute @columns.include?(:a) end def test_exclude_array # exclude with a symbol assert @columns.include?(:b) @columns.exclude [:a, :b] refute @columns.include?(:b) refute @columns.include?(:a) end def test_add # try adding a simple column using a string refute @columns.include?(:c) @columns.add 'c' assert @columns.include?(:c) # try adding a simple column using a symbol refute @columns.include?(:d) @columns.add :d assert @columns.include?(:d) # test that << also adds refute @columns.include?(:e) @columns << :e assert @columns.include?(:e) # try adding an array of columns refute @columns.include?(:f) @columns.add [:f, :g] assert @columns.include?(:f) assert @columns.include?(:g) end def test_length assert_equal 2, @columns.length end def test_add_subgroup # first, use @columns.add directly @c2 = ActiveScaffold::DataStructures::ActionColumns.new @columns.add @c2 assert @columns.any? { |c| c == @c2 } # then use the shortcut @columns.add_subgroup 'foo' do end assert @columns.any? { |c| c.respond_to? :label and c.label == 'foo' } end def test_block_config @columns.configure do |config| # we may use the config argument config.add :c # or we may not exclude :b add_subgroup 'my subgroup' do add :e end end assert @columns.include?(:c) refute @columns.include?(:b) @columns.each { |c| next unless c.is_a? ActiveScaffold::DataStructures::Columns assert c.include?(:e) assert_equal 'my subgroup', c.name } end def test_include @columns.add_subgroup 'foo' do add :c end assert @columns.include?(:a) assert @columns.include?(:b) assert @columns.include?(:c) refute @columns.include?(:d) end end
23.850877
94
0.641412
6176db2511e33a1c8892abb8974385ed01c01cf1
837
require File.dirname(__FILE__) + '/../../spec_helper' require 'matrix' describe "Matrix#square?" do it "returns true when the Matrix is square" do Matrix[ [1,2], [2,4] ].square?.should be_true Matrix[ [100,3,5], [9.5, 4.9, 8], [2,0,77] ].square?.should be_true end it "returns true when the Matrix has only one element" do Matrix[ [9] ].square?.should be_true end it "returns false when the Matrix is rectangular" do Matrix[ [1, 2] ].square?.should be_false end it "returns false when the Matrix is rectangular" do Matrix[ [1], [2] ].square?.should be_false end ruby_bug "redmine:1532", "1.8.7" do it "returns handles empty matrices" do Matrix[].square?.should be_true Matrix[[]].square?.should be_false Matrix.columns([[]]).square?.should be_false end end end
27
71
0.653524
7993fac5dd219a0ac2adfb397d42bc61e5b142af
2,675
# frozen_string_literal: true require 'spec_helper' RSpec.describe Projects::Analytics::CycleAnalytics::SummaryController do let_it_be(:user) { create(:user) } let_it_be(:group) { create(:group) } let_it_be(:project) { create(:project, group: group) } let(:params) { { namespace_id: project.namespace.to_param, project_id: project.to_param, created_after: '2010-01-01', created_before: '2020-01-02' } } before do sign_in(user) end describe 'GET "time_summary"' do let_it_be(:first_mentioned_in_commit_at) { Date.new(2015, 1, 1) } let_it_be(:closed_at) { Date.new(2015, 2, 1) } let_it_be(:closed_issue) do create(:issue, project: project, created_at: closed_at, closed_at: closed_at).tap do |issue| issue.metrics.update!(first_mentioned_in_commit_at: first_mentioned_in_commit_at) end end subject { get :time_summary, params: params } context 'when cycle_analytics_for_projects feature is available' do before do stub_licensed_features(cycle_analytics_for_projects: true, cycle_analytics_for_groups: true) Analytics::CycleAnalytics::GroupDataLoaderWorker.new.perform(group.id, 'Issue') project.add_reporter(user) end it 'succeeds' do subject expect(response).to be_successful end it 'returns correct value' do expected_cycle_time = (closed_at - first_mentioned_in_commit_at).to_i subject expect(json_response.last["value"].to_i).to eq(expected_cycle_time) end context 'when the use_vsa_aggregated_tables FF is off' do before do stub_feature_flags(use_vsa_aggregated_tables: false) end it 'returns correct value' do expected_cycle_time = (closed_at - first_mentioned_in_commit_at).to_i subject expect(json_response.last["value"].to_i).to eq(expected_cycle_time) end end context 'when analytics_disabled features are disabled' do it 'renders 404' do project.add_reporter(user) project.project_feature.update!(analytics_access_level: ProjectFeature::DISABLED) subject expect(response).to have_gitlab_http_status(:not_found) end end end context 'when user is not part of the project' do it 'renders 404' do subject expect(response).to have_gitlab_http_status(:not_found) end end context 'when the feature is not available' do it 'renders 404' do project.add_reporter(user) subject expect(response).to have_gitlab_http_status(:not_found) end end end end
27.864583
152
0.680374
b9e21c199f904807423026b35cd5c5c243d609e8
756
Crossbeams::MenuMigrations::Migrator.migration('Nspack') do up do add_program_function 'New', functional_area: 'Production', program: 'Reworks', url: '/production/reworks/reworks_run_types/bulk_update_pallet_dates/reworks_runs/new', group: 'Bulk Update Pallet Dates', seq: 32 add_program_function 'List', functional_area: 'Production', program: 'Reworks', url: '/production/reworks/reworks_run_types/bulk_update_pallet_dates', group: 'Bulk Update Pallet Dates', seq: 33 end down do drop_program_function 'New', functional_area: 'Production', program: 'Reworks', match_group: 'Bulk Update Pallet Dates' drop_program_function 'List', functional_area: 'Production', program: 'Reworks', match_group: 'Bulk Update Pallet Dates' end end
63
213
0.771164
ab24128f608a9fb5641dc0ae790049c1a90e6c87
537
actions :create, :delete default_action :create attribute :mode, :kind_of => String, :default => 'rsync' attribute :source, :kind_of => String, :required => true attribute :target, :kind_of => String, :required => true attribute :user, :kind_of => [String, NilClass] attribute :host, :kind_of => [String, NilClass] attribute :rsync_opts, :kind_of => [Array, NilClass] attribute :exclude, :kind_of => [Array, NilClass] attribute :exclude_from, :kind_of => [String, NilClass] attribute :cookbook, :kind_of => String, :default => 'lsyncd'
41.307692
61
0.716946
b9b85bb695907f05f6087c3ec1ee83ea59130729
1,122
require 'test_helper' class Manage::XformsControllerTest < ActionController::TestCase setup do @manage_xform = manage_xforms(:one) end test "should get index" do get :index assert_response :success assert_not_nil assigns(:manage_xforms) end test "should get new" do get :new assert_response :success end test "should create manage_xform" do assert_difference('Manage::Xform.count') do post :create, manage_xform: { } end assert_redirected_to manage_xform_path(assigns(:manage_xform)) end test "should show manage_xform" do get :show, id: @manage_xform assert_response :success end test "should get edit" do get :edit, id: @manage_xform assert_response :success end test "should update manage_xform" do patch :update, id: @manage_xform, manage_xform: { } assert_redirected_to manage_xform_path(assigns(:manage_xform)) end test "should destroy manage_xform" do assert_difference('Manage::Xform.count', -1) do delete :destroy, id: @manage_xform end assert_redirected_to manage_xforms_path end end
22.44
66
0.714795
ff6d3169f99a8bc9cb27e742f267459a36abda09
3,742
class Heartbeat < Formula desc "Lightweight Shipper for Uptime Monitoring" homepage "https://www.elastic.co/products/beats/heartbeat" url "https://github.com/elastic/beats.git", :tag => "v7.8.0", :revision => "f79387d32717d79f689d94fda1ec80b2cf285d30" head "https://github.com/elastic/beats.git" bottle do cellar :any_skip_relocation sha256 "3ead08eebb8bf137e99ad3bb4ddeb272c97925b36322acddc617c25294f70567" => :catalina sha256 "85a4feb68f6e1f5df44315eb5903c7fdcf0b52f39d674801544493722ff919a8" => :mojave sha256 "b0ba82526d992d5a6f00ca58d61bbc23026300bf69349526fefe5713c2ece417" => :high_sierra end depends_on "go" => :build depends_on "[email protected]" => :build resource "virtualenv" do url "https://files.pythonhosted.org/packages/b1/72/2d70c5a1de409ceb3a27ff2ec007ecdd5cc52239e7c74990e32af57affe9/virtualenv-15.2.0.tar.gz" sha256 "1d7e241b431e7afce47e77f8843a276f652699d1fa4f93b9d8ce0076fd7b0b54" end def install # remove non open source files rm_rf "x-pack" ENV["GOPATH"] = buildpath (buildpath/"src/github.com/elastic/beats").install buildpath.children xy = Language::Python.major_minor_version "python3" ENV.prepend_create_path "PYTHONPATH", buildpath/"vendor/lib/python#{xy}/site-packages" resource("virtualenv").stage do system Formula["[email protected]"].opt_bin/"python3", *Language::Python.setup_install_args(buildpath/"vendor") end ENV.prepend_path "PATH", buildpath/"vendor/bin" # for virtualenv ENV.prepend_path "PATH", buildpath/"bin" # for mage (build tool) cd "src/github.com/elastic/beats/heartbeat" do system "make", "mage" # prevent downloading binary wheels during python setup system "make", "PIP_INSTALL_COMMANDS=--no-binary :all", "python-env" system "mage", "-v", "build" ENV.deparallelize system "mage", "-v", "update" (etc/"heartbeat").install Dir["heartbeat.*", "fields.yml"] (libexec/"bin").install "heartbeat" prefix.install "_meta/kibana.generated" end prefix.install_metafiles buildpath/"src/github.com/elastic/beats" (bin/"heartbeat").write <<~EOS #!/bin/sh exec #{libexec}/bin/heartbeat \ --path.config #{etc}/heartbeat \ --path.data #{var}/lib/heartbeat \ --path.home #{prefix} \ --path.logs #{var}/log/heartbeat \ "$@" EOS end def post_install (var/"lib/heartbeat").mkpath (var/"log/heartbeat").mkpath end plist_options :manual => "heartbeat" def plist <<~EOS <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>Program</key> <string>#{opt_bin}/heartbeat</string> <key>RunAtLoad</key> <true/> </dict> </plist> EOS end test do port = free_port (testpath/"config/heartbeat.yml").write <<~EOS heartbeat.monitors: - type: tcp schedule: '@every 5s' hosts: ["localhost:#{port}"] check.send: "hello\\n" check.receive: "goodbye\\n" output.file: path: "#{testpath}/heartbeat" filename: heartbeat codec.format: string: '%{[monitor]}' EOS fork do exec bin/"heartbeat", "-path.config", testpath/"config", "-path.data", testpath/"data" end sleep 5 assert_match "hello", pipe_output("nc -l #{port}", "goodbye\n", 0) sleep 5 assert_match "\"status\":\"up\"", (testpath/"heartbeat/heartbeat").read end end
31.711864
141
0.644041
18499e1b445bae644d67d2ab1f0c9a05e378d7b2
745
# frozen_string_literal: true require 'diff/lcs' require "modern/app/router" require 'modern/util/trie_node' module Modern class App class TrieRouter < Router def initialize(inputs) super(inputs) @trie = build_trie(routes) end def resolve(http_method, path) trie_path = path.sub(%r|^/|, "").split("/") + [http_method.to_s.upcase] @trie.get(trie_path) end private def build_trie(routes) trie = Modern::Util::TrieNode.new routes.each do |route| route.path_matcher # pre-seed the path matcher trie.add(route.route_tokens + [route.http_method], route, raise_if_present: true) end trie end end end end
19.605263
91
0.614765
03291a272edc29834e6cb87a2b640df1e652d20b
349
require './plugins/plugins.rb' # BotSnack when someone high5s us class BotSnack < Plugin @@snacks = [ 'omm nom nom nom', '*puke*', 'MOAR!', '=.=' ] def response(_to, _from, msg) return unless relevant?(msg) return @@snacks[rand(0..@@snacks.length)] if msg =~ %r{botsnack}x nil end def test true end end
16.619048
69
0.593123
e900d86c2e40f6cc8e5fa3c1678b01f153d3aa8f
530
# == Schema Information # # Table name: user_team_project_relationships # # id :integer not null, primary key # project_id :integer # user_team_id :integer # greatest_access :integer # created_at :datetime not null # updated_at :datetime not null # # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :user_team_project_relationship do project user_team greatest_access { UsersProject::MASTER } end end
24.090909
68
0.679245
91ff458a4335c6df0aaf07781f97ee41644b0a7b
1,190
module Api module V3 module Dashboards module ChartParameters class Base attr_reader :country_id, :commodity_id, :context, :start_year, :end_year # @param params [Hash] # @option params [Integer] country_id # @option params [Integer] commodity_id # @option params [Integer] start_year # @option params [Integer] end_year def initialize(params) @country_id = params[:country_id] @commodity_id = params[:commodity_id] if @country_id && @commodity_id @context = Api::V3::Context.find_by_country_id_and_commodity_id!( @country_id, @commodity_id ) end @start_year = params[:start_year] @end_year = params[:end_year] end private def single_year? @start_year.present? && @end_year.present? && @start_year == @end_year end def ncont_attribute? @ncont_attribute.present? end end end end end end
26.444444
82
0.515126
1ced5a0bb423fd247d45cfd54faffd005d1bde36
1,531
class Zellij < Formula desc "Pluggable terminal workspace, with terminal multiplexer as the base feature" homepage "https://zellij.dev" url "https://github.com/zellij-org/zellij/archive/v0.14.0.tar.gz" sha256 "45ce99d0c13de562f27b46e9693ff0cdf1dba2d15568410fcb67c9b0e9d6b500" license "MIT" bottle do sha256 cellar: :any_skip_relocation, arm64_big_sur: "08e16118424fe0b21538fd19486ec1c8e27cf69ef4f100373b7696b90dc5c55d" sha256 cellar: :any_skip_relocation, big_sur: "4ee82bca930fcf51f290363466c590d4f1f7b596f6f45a39e132a3994f824cc0" sha256 cellar: :any_skip_relocation, catalina: "0445bb8917a1a3f4853cbb441505a6b337d83230e9904a1b4864f31a0ecc8c89" sha256 cellar: :any_skip_relocation, mojave: "cad649e3a7e036f926d7ea5a7fe949995100b99bc636931a9871d026729bd4ad" end depends_on "rust" => :build def install system "cargo", "install", *std_cargo_args bash_output = Utils.safe_popen_read(bin/"zellij", "setup", "--generate-completion", "bash") (bash_completion/"zellij").write bash_output zsh_output = Utils.safe_popen_read(bin/"zellij", "setup", "--generate-completion", "zsh") (zsh_completion/"_zellij").write zsh_output fish_output = Utils.safe_popen_read(bin/"zellij", "setup", "--generate-completion", "fish") (fish_completion/"zellij.fish").write fish_output end test do assert_match(/keybinds:.*/, shell_output("#{bin}/zellij setup --dump-config")) assert_match("zellij #{version}", shell_output("#{bin}/zellij --version")) end end
46.393939
122
0.758328
334cff9b6008735e3c587d253c41ddbd8e9c3f03
1,073
RSpec.describe Metasploit::Credential::Origin::Manual, type: :model do it_should_behave_like 'Metasploit::Concern.run' context 'associations' do it { is_expected.to have_many(:cores).class_name('Metasploit::Credential::Core').dependent(:destroy) } it { is_expected.to belong_to(:user).class_name('Mdm::User') } end context 'database' do context 'columns' do context 'foreign keys' do it { is_expected.to have_db_column(:user_id).of_type(:integer).with_options(null: false) } end it_should_behave_like 'timestamp database columns' end context 'indices' do context 'foreign keys' do it { is_expected.to have_db_index(:user_id) } end end end context 'factories' do context 'metasploit_credential_origin_manual' do subject(:metasploit_credential_origin_manual) do FactoryBot.build(:metasploit_credential_origin_manual) end it { is_expected.to be_valid } end end context 'validations' do it { is_expected.to validate_presence_of :user } end end
27.512821
106
0.701771
edaff40a4031658a85b311adc64e533862de85b4
153
class CreateTasks < ActiveRecord::Migration[6.0] def change create_table :tasks do |t| t.string :title t.timestamps end end end
15.3
48
0.653595
e2dd97f0cf4f54208b8c37923084bd500b830039
202
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf Mime::Type.register "application/pdf", :pdf
25.25
59
0.737624
03392c088147c7f0f9cd7114a4152275919cbb7b
3,941
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options) config.active_storage.service = :local # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "air-console_#{Rails.env}" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
41.484211
102
0.758183
e22389f40eed0c10100969b6eea3b7b2b57fb035
295
# frozen_string_literal: true require 'discourse_dev' require 'rails' module DiscourseDev class Railtie < Rails::Railtie railtie_name :discourse_dev rake_tasks do path = File.expand_path(__dir__) Dir.glob("#{path}/tasks/**/*.rake").each { |f| load f } end end end
18.4375
61
0.681356
bff247246fd098c7a70e19ab485d171e55cf57c9
7,450
#! /usr/bin/env ruby require 'spec_helper' require 'oregano/application/cert' describe Oregano::Application::Cert => true do before :each do @cert_app = Oregano::Application[:cert] Oregano::Util::Log.stubs(:newdestination) end it "should operate in master run_mode" do expect(@cert_app.class.run_mode.name).to equal(:master) end it "should declare a main command" do expect(@cert_app).to respond_to(:main) end Oregano::SSL::CertificateAuthority::Interface::INTERFACE_METHODS.reject{ |m| m == :destroy }.each do |method| it "should declare option --#{method}" do expect(@cert_app).to respond_to("handle_#{method}".to_sym) end end it "should set log level to info with the --verbose option" do @cert_app.handle_verbose(0) expect(Oregano::Log.level).to eq(:info) end it "should set log level to debug with the --debug option" do @cert_app.handle_debug(0) expect(Oregano::Log.level).to eq(:debug) end it "should set the fingerprint digest with the --digest option" do @cert_app.handle_digest(:digest) expect(@cert_app.digest).to eq(:digest) end it "should set cert_mode to :destroy for --clean" do @cert_app.handle_clean(0) expect(@cert_app.subcommand).to eq(:destroy) end it "should set all to true for --all" do @cert_app.handle_all(0) expect(@cert_app.all).to be_truthy end it "should set signed to true for --signed" do @cert_app.handle_signed(0) expect(@cert_app.signed).to be_truthy end it "should set human to true for --human-readable" do @cert_app.handle_human_readable(0) expect(@cert_app.options[:format]).to be :human end it "should set machine to true for --machine-readable" do @cert_app.handle_machine_readable(0) expect(@cert_app.options[:format]).to be :machine end it "should set interactive to true for --interactive" do @cert_app.handle_interactive(0) expect(@cert_app.options[:interactive]).to be_truthy end it "should set yes to true for --assume-yes" do @cert_app.handle_assume_yes(0) expect(@cert_app.options[:yes]).to be_truthy end Oregano::SSL::CertificateAuthority::Interface::INTERFACE_METHODS.reject { |m| m == :destroy }.each do |method| it "should set cert_mode to #{method} with option --#{method}" do @cert_app.send("handle_#{method}".to_sym, nil) expect(@cert_app.subcommand).to eq(method) end end describe "during setup" do before :each do Oregano::Log.stubs(:newdestination) Oregano::SSL::Host.stubs(:ca_location=) Oregano::SSL::CertificateAuthority.stubs(:new) end it "should set console as the log destination" do Oregano::Log.expects(:newdestination).with(:console) @cert_app.setup end it "should print oregano config if asked to in Oregano config" do Oregano.settings.stubs(:print_configs?).returns(true) Oregano.settings.expects(:print_configs).returns true expect { @cert_app.setup }.to exit_with 0 end it "should exit after printing oregano config if asked to in Oregano config" do Oregano.settings.stubs(:print_configs?).returns(true) expect { @cert_app.setup }.to exit_with 1 end it "should set the CA location to 'only'" do Oregano::SSL::Host.expects(:ca_location=).with(:only) @cert_app.setup end it "should create a new certificate authority" do Oregano::SSL::CertificateAuthority.expects(:new) @cert_app.setup end it "should set the ca_location to :local if the cert_mode is generate" do @cert_app.subcommand = 'generate' Oregano::SSL::Host.expects(:ca_location=).with(:local) @cert_app.setup end it "should set the ca_location to :local if the cert_mode is destroy" do @cert_app.subcommand = 'destroy' Oregano::SSL::Host.expects(:ca_location=).with(:local) @cert_app.setup end it "should set the ca_location to :only if the cert_mode is print" do @cert_app.subcommand = 'print' Oregano::SSL::Host.expects(:ca_location=).with(:only) @cert_app.setup end end describe "when running" do before :each do @cert_app.all = false @ca = stub_everything 'ca' @cert_app.ca = @ca @cert_app.command_line.stubs(:args).returns([]) @iface = stub_everything 'iface' Oregano::SSL::CertificateAuthority::Interface.stubs(:new).returns(@iface) end it "should delegate to the CertificateAuthority" do @iface.expects(:apply) @cert_app.main end it "should delegate with :all if option --all was given" do @cert_app.handle_all(0) Oregano::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| to[:to] == :all } @cert_app.main end it "should delegate to ca.apply with the hosts given on command line" do @cert_app.command_line.stubs(:args).returns(["host"]) Oregano::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| to[:to] == ["host"]} @cert_app.main end it "should send the currently set digest" do @cert_app.command_line.stubs(:args).returns(["host"]) @cert_app.handle_digest(:digest) Oregano::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| to[:digest] == :digest} @cert_app.main end it "should revoke cert if cert_mode is clean" do @cert_app.subcommand = :destroy @cert_app.command_line.stubs(:args).returns(["host"]) Oregano::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| cert_mode == :revoke } Oregano::SSL::CertificateAuthority::Interface.expects(:new).returns(@iface).with { |cert_mode,to| cert_mode == :destroy } @cert_app.main end end describe "when identifying subcommands" do before :each do @cert_app.all = false @ca = stub_everything 'ca' @cert_app.ca = @ca end %w{list revoke generate sign print verify fingerprint}.each do |cmd| short = cmd[0,1] [cmd, "--#{cmd}", "-#{short}"].each do |option| # In our command line '-v' was eaten by 'verbose', so we can't consume # it here; this is a special case from our otherwise standard # processing. --daniel 2011-02-22 next if option == "-v" it "should recognise '#{option}'" do args = [option, "fun.example.com"] @cert_app.command_line.stubs(:args).returns(args) @cert_app.parse_options expect(@cert_app.subcommand).to eq(cmd.to_sym) expect(args).to eq(["fun.example.com"]) end end end %w{clean --clean -c}.each do |ugly| it "should recognise the '#{ugly}' option as destroy" do args = [ugly, "fun.example.com"] @cert_app.command_line.stubs(:args).returns(args) @cert_app.parse_options expect(@cert_app.subcommand).to eq(:destroy) expect(args).to eq(["fun.example.com"]) end end it "should print help and exit if there is no subcommand" do args = [] @cert_app.command_line.stubs(:args).returns(args) @cert_app.stubs(:help).returns("I called for help!") @cert_app.expects(:puts).with("I called for help!") expect { @cert_app.parse_options }.to exit_with 0 expect(@cert_app.subcommand).to be_nil end end end
30.912863
127
0.665369
87e009149353a58609ff9dc8ad2e92ac276a4517
125
module V1 class Base < ApplicationAPI version "v1", :using => :path mount SampleAPI mount SecretAPI end end
13.888889
33
0.664
bf0ccfd831d4dedfc6a74df02d0b48ed26c05102
594
require 'test/unit' require File.dirname(__FILE__) + '/../bin/translate' class GoogleTranslateTest < Test::Unit::TestCase def setup @translate = File.dirname(__FILE__) + '/../bin/translate.rb' end def test_trying_to_translate assert_equal("Teste", `ruby #{@translate} Test`.strip!) end def test_trying_to_translate_from_portuguese_to_english assert_equal("Hello world", `ruby #{@translate} 'Olá mundo' en`.strip!) end def test_trying_to_translate_from_spanish_to_english assert_equal("Hola mundo", `ruby #{@translate} 'Olá mundo' es`.strip!) end end
28.285714
75
0.720539
f87efd992d819014413e81ce02c2d9efbd742250
2,566
# Wraps CanCan functionality to load resources via a polymorphic parent. # See CanCan wiki article on nested resources for more. module PolymorphicAuthorizable extend ActiveSupport::Concern included do def parent_resource_name params[:resource_type].singularize end def parent_resource_class parent_resource_name.classify.constantize end def parent_resource variable_name = "@#{parent_resource_class.model_name.element}" @parent = instance_variable_get(variable_name) || instance_variable_set(variable_name, parent_resource_class.find(params[:resource_id])) end end class_methods do # Loads and authorizes a resource via an associated polymorphic relation. # Note that authorization takes place on the parent, not the current resource. def polymorphic_load_and_authorize_resource(resource_name, **options) options[:through] = :parent_resource authorize_polymorphic_resource load_resource(resource_name, options) _make_collection_accessible(resource_name) end # Authorizes the polymorphic parent resource. Takes the stance that if a user is authorized # to :read the parent then, by extension, they should also be able to view the children. def authorize_polymorphic_resource before_action do authorize! :read, parent_resource end end # Because we're authorizing via the parent we have no rules defined in the ability file. # Collection routes are handled via Model.accessible_by(ability) which will generate a SQL # predicate that always equates to false in this situation. Typically, we would have a :can # rule with a hash of conditions, but that wont work here because the 'parent' resource is # not available within the ability. To work around this, we extract the predicates used for # the parent binding (i.e. from loading :though another resource) and use these to create a # new WHERE clause, sans 't' = 'f'. # For more info see: # CanCan::ModelAdditions (:accessible_by) # CanCan::ModelAdapters::ActiveRecordAdapter (:database_records, :conditions, :false_sql) def _make_collection_accessible(resource_name) variable_name = "@#{resource_name.to_s.pluralize}" before_action only: [:index, :index_new] do relation = instance_variable_get(variable_name) conditions = relation.where_values_hash relation = relation.unscope(:where).where(conditions) instance_variable_set(variable_name, relation) end end end end
40.09375
95
0.740842
8732d8a5f59bc58d5f3773ebd3635287423866a5
1,561
Gem::Specification.new do |s| s.name = "mongrel_cluster_rolling_restart" s.version = "0.1.1" s.date = "2008-09-24" s.summary = "Allows for a mongrel cluster to be restarted in a rolling fashion" s.description = "Mongrel Cluster Rolling Restart allows for a mongrel cluster to be restarted in a rolling fashion, one mongrel at a time" s.authors = ["Cameron Booth"] s.email = "[email protected]" s.homepage = "http://github.com/cdb/mongrel_cluster_rolling_restart" s.files = ["History.txt", "Manifest.txt", "README.txt", "Rakefile", "lib/mongrel_cluster_rolling_restart.rb", "recipes/mongrel_cluster_rolling_restart.rb", "tasks/mongrel_cluster_rolling_restart.rake", "test/test_mongrel_cluster_rolling_restart.rb"] s.test_files = ["test/test_mongrel_cluster_rolling_restart.rb"] s.rdoc_options = ["--main", "README.txt"] s.has_rdoc = true s.extra_rdoc_files = ["History.txt", "Manifest.txt", "README.txt"] s.require_paths = ["lib"] s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.add_dependency("mongrel", [">= 1.1.4"]) s.add_dependency("mongrel_cluster", [">= 1.0.5"]) if s.respond_to? :specification_version then current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION s.specification_version = 2 if current_version >= 3 then s.add_development_dependency(%q<hoe>, [">= 1.7.0"]) else s.add_dependency(%q<hoe>, [">= 1.7.0"]) end else s.add_dependency(%q<hoe>, [">= 1.7.0"]) end end
38.073171
251
0.699552
bb118ce682f2041675af2f457712a3ca1a81dfb9
8,216
require 'spec_helper' describe TeamStats do let(:team) { Fabricate(:team) } before do allow_any_instance_of(Map).to receive(:update_png!) end context 'with no activities' do let(:stats) { team.stats } context '#stats' do it 'aggregates stats' do expect(stats.count).to eq 0 end end context '#to_slack' do it 'defaults to no activities' do expect(stats.to_slack).to eq({ text: 'There are no activities in this channel.' }) end end end context 'with activities' do let!(:user1) { Fabricate(:user, team: team) } let!(:user2) { Fabricate(:user, team: team) } let!(:club) { Fabricate(:club, team: team) } let!(:swim_activity) { Fabricate(:swim_activity, user: user2) } let!(:ride_activity1) { Fabricate(:ride_activity, user: user1) } let!(:ride_activity2) { Fabricate(:ride_activity, user: user1) } let!(:club_activity) { Fabricate(:club_activity, club: club) } let!(:activity1) { Fabricate(:user_activity, user: user1) } let!(:activity2) { Fabricate(:user_activity, user: user1) } let!(:activity3) { Fabricate(:user_activity, user: user2) } context '#stats' do let(:stats) { team.stats } it 'returns stats sorted by count' do expect(stats.keys).to eq %w[Run Ride Swim] expect(stats.values.map(&:count)).to eq [4, 2, 1] end it 'aggregates stats' do expect(stats['Ride'].to_h).to eq( { distance: [ride_activity1, ride_activity2].map(&:distance).compact.sum, moving_time: [ride_activity1, ride_activity2].map(&:moving_time).compact.sum, elapsed_time: [ride_activity1, ride_activity2].map(&:elapsed_time).compact.sum, pr_count: 0, calories: 0, total_elevation_gain: 0 } ) expect(stats['Run'].to_h).to eq( { distance: [activity1, activity2, activity3, club_activity].map(&:distance).compact.sum, moving_time: [activity1, activity2, activity3, club_activity].map(&:moving_time).compact.sum, elapsed_time: [activity1, activity2, activity3, club_activity].map(&:elapsed_time).compact.sum, pr_count: [activity1, activity2, activity3, club_activity].map(&:pr_count).compact.sum, calories: [activity1, activity2, activity3, club_activity].map(&:calories).compact.sum, total_elevation_gain: [activity1, activity2, activity3, club_activity].map(&:total_elevation_gain).compact.sum } ) expect(stats['Swim'].to_h).to eq( { distance: swim_activity.distance, moving_time: swim_activity.moving_time, elapsed_time: swim_activity.elapsed_time, pr_count: 0, calories: 0, total_elevation_gain: 0 } ) end context 'with activities from another team' do let!(:another_activity) { Fabricate(:user_activity, user: user1) } let!(:another_team_activity) { Fabricate(:user_activity, user: Fabricate(:user, team: Fabricate(:team))) } it 'does not include that activity' do expect(stats.values.map(&:count)).to eq [5, 2, 1] end end end context '#to_slack' do let(:stats) { team.stats } it 'includes all activities' do expect(stats.to_slack[:attachments].count).to eq(3) end end end context 'with activities across multiple channels' do let!(:user) { Fabricate(:user, team: team) } let!(:user_activity) { Fabricate(:user_activity, user: user) } let!(:club1) { Fabricate(:club, team: team, channel_id: 'channel1') } let!(:club1_activity) { Fabricate(:club_activity, club: club1) } let!(:club2) { Fabricate(:club, team: team, channel_id: 'channel2') } let!(:club2_activity) { Fabricate(:club_activity, club: club2) } context '#stats' do context 'all channels' do let!(:stats) { team.stats } let!(:activities) { [user_activity, club1_activity, club2_activity] } it 'returns stats for all activities' do expect(stats['Run'].to_h).to eq( { distance: activities.map(&:distance).compact.sum, moving_time: activities.map(&:moving_time).compact.sum, elapsed_time: activities.map(&:elapsed_time).compact.sum, pr_count: activities.map(&:pr_count).compact.sum, calories: activities.map(&:calories).compact.sum, total_elevation_gain: activities.map(&:total_elevation_gain).compact.sum } ) end end context 'in channel with bragged club activity' do before do allow_any_instance_of(Slack::Web::Client).to receive(:chat_postMessage).and_return(ts: 'ts') club1_activity.brag! end context 'stats' do let(:stats) { team.stats(channel_id: club1.channel_id) } let(:activities) { [club1_activity] } it 'returns stats for all activities' do expect(stats['Run'].to_h).to eq( { distance: activities.map(&:distance).compact.sum, moving_time: activities.map(&:moving_time).compact.sum, elapsed_time: activities.map(&:elapsed_time).compact.sum, pr_count: activities.map(&:pr_count).compact.sum, calories: activities.map(&:calories).compact.sum, total_elevation_gain: activities.map(&:total_elevation_gain).compact.sum } ) end end end context 'in channel with bragged user activity' do before do allow_any_instance_of(Team).to receive(:slack_channels).and_return(['id' => club1_activity.club.channel_id]) allow_any_instance_of(User).to receive(:user_deleted?).and_return(false) allow_any_instance_of(User).to receive(:user_in_channel?).and_return(true) allow_any_instance_of(Slack::Web::Client).to receive(:chat_postMessage).and_return(ts: 'ts') user_activity.brag! end context 'stats' do let(:stats) { team.stats(channel_id: club1_activity.club.channel_id) } let(:activities) { [user_activity] } it 'returns stats for all activities' do expect(stats['Run'].to_h).to eq( { distance: activities.map(&:distance).compact.sum, moving_time: activities.map(&:moving_time).compact.sum, elapsed_time: activities.map(&:elapsed_time).compact.sum, pr_count: activities.map(&:pr_count).compact.sum, calories: activities.map(&:calories).compact.sum, total_elevation_gain: activities.map(&:total_elevation_gain).compact.sum } ) end end end context 'in channel with bragged user and club activities' do before do allow_any_instance_of(Team).to receive(:slack_channels).and_return(['id' => club1_activity.club.channel_id]) allow_any_instance_of(User).to receive(:user_deleted?).and_return(false) allow_any_instance_of(User).to receive(:user_in_channel?).and_return(true) allow_any_instance_of(Slack::Web::Client).to receive(:chat_postMessage).and_return(ts: 'ts') club1_activity.brag! user_activity.brag! end context 'stats' do let(:stats) { team.stats(channel_id: club1.channel_id) } let(:activities) { [user_activity, club1_activity] } it 'returns stats for all activities' do expect(stats['Run'].to_h).to eq( { distance: activities.map(&:distance).compact.sum, moving_time: activities.map(&:moving_time).compact.sum, elapsed_time: activities.map(&:elapsed_time).compact.sum, pr_count: activities.map(&:pr_count).compact.sum, calories: activities.map(&:calories).compact.sum, total_elevation_gain: activities.map(&:total_elevation_gain).compact.sum } ) end end end end end end
44.410811
122
0.614167
4a1f3d859208fac5ccf2fc15a6cab2163f85dd01
111
platform_is :windows do require 'win32ole' describe 'WIN32OLE_EVENT#on_event_with_outargs' do end end
12.333333
52
0.774775
082a2c5669a3e2dff37af20777fb235a1adcc7b3
4,130
module Worker class Matching class DryrunError < StandardError attr :engine def initialize(engine) @engine = engine end end def initialize(options={}) @options = options reload 'all' end def process(payload, metadata, delivery_info) payload.symbolize_keys! case payload[:action] when 'submit' submit build_order(payload[:order]) when 'cancel' cancel build_order(payload[:order]) when 'reload' reload payload[:market] else Rails.logger.fatal "Unknown action: #{payload[:action]}" end end def submit(order) engines[order.market.id].submit(order) end def cancel(order) engines[order.market.id].cancel(order) end def reload(market) if market == 'all' Market.all.each {|market| initialize_engine market } Rails.logger.info "All engines reloaded." else initialize_engine Market.find(market) Rails.logger.info "#{market} engine reloaded." end rescue DryrunError => e # stop started engines engines.each {|id, engine| engine.shift_gears(:dryrun) unless engine == e.engine } Rails.logger.fatal "#{market} engine failed to start. Matched during dryrun:" e.engine.queue.each do |trade| Rails.logger.info trade[1].inspect end end def build_order(attrs) ::Matching::OrderBookManager.build_order attrs end def initialize_engine(market) create_engine market load_orders market start_engine market end def create_engine(market) engines[market.id] = ::Matching::Engine.new(market, @options) end def load_orders(market) ::Order.active.with_currency(market.id).order('id asc').each do |order| submit build_order(order.to_matching_attributes) end end def start_engine(market) engine = engines[market.id] if engine.mode == :dryrun if engine.queue.empty? engine.shift_gears :run else accept = ENV['ACCEPT_MINUTES'] ? ENV['ACCEPT_MINUTES'].to_i : 30 order_ids = engine.queue .map {|args| [args[1][:ask_id], args[1][:bid_id]] } .flatten.uniq orders = Order.where('created_at < ?', accept.minutes.ago).where(id: order_ids) if orders.exists? # there're very old orders matched, need human intervention raise DryrunError, engine else # only buffered orders matched, just publish trades and continue engine.queue.each {|args| AMQPQueue.enqueue(*args) } engine.shift_gears :run end end else Rails.logger.info "#{market.id} engine already started. mode=#{engine.mode}" end end def engines @engines ||= {} end # dump limit orderbook def on_usr1 engines.each do |id, eng| dump_file = File.join('/', 'tmp', "limit_orderbook_#{id}") limit_orders = eng.limit_orders File.open(dump_file, 'w') do |f| f.puts "ASK" limit_orders[:ask].keys.reverse.each do |k| f.puts k.to_s('F') limit_orders[:ask][k].each {|o| f.puts "\t#{o.label}" } end f.puts "-"*40 limit_orders[:bid].keys.reverse.each do |k| f.puts k.to_s('F') limit_orders[:bid][k].each {|o| f.puts "\t#{o.label}" } end f.puts "BID" end puts "#{id} limit orderbook dumped to #{dump_file}." end end # dump market orderbook def on_usr2 engines.each do |id, eng| dump_file = File.join('/', 'tmp', "market_orderbook_#{id}") market_orders = eng.market_orders File.open(dump_file, 'w') do |f| f.puts "ASK" market_orders[:ask].each {|o| f.puts "\t#{o.label}" } f.puts "-"*40 market_orders[:bid].each {|o| f.puts "\t#{o.label}" } f.puts "BID" end puts "#{id} market orderbook dumped to #{dump_file}." end end end end
27.171053
89
0.582082
bfa4b167902e52b7c4de29537ea951f72bb4c100
156
FactoryGirl.define do factory :user do email { Faker::Internet.email } password 'fakepassword' password_confirmation 'fakepassword' end end
19.5
40
0.730769
7ab993126bc1bd2ecd9a950eb5774442176c3791
667
module Airbrake module Filters # Replaces root directory with a label. # @api private class RootDirectoryFilter # @return [String] PROJECT_ROOT_LABEL = '/PROJECT_ROOT'.freeze # @return [Integer] attr_reader :weight def initialize(root_directory) @root_directory = root_directory @weight = 100 end # @macro call_filter def call(notice) notice[:errors].each do |error| error[:backtrace].each do |frame| next unless (file = frame[:file]) file.sub!(/\A#{@root_directory}/, PROJECT_ROOT_LABEL) end end end end end end
22.233333
65
0.592204
269c9b63f65d17357966659d612bc83708489aea
1,767
require 'test_helper' class TriggersControllerTest < ActionController::TestCase context "a non-admin logged in user" do setup do @user = login @user.update_attributes(:admin => 0) assert [email protected]? end should "be redirected" do get :index assert_redirected_to "/tasks/list" end end context "a logged in admin user" do setup do @user = login @user.update_attributes(:admin => 1) assert @user.admin? end should "get index" do get :index assert_response :success assert_not_nil assigns(:triggers) end should "get new" do get :new assert_response :success assert_not_nil assigns(:trigger) end should "create trigger" do filter = TaskFilter.make(:user => @user, :company => @user.company) assert_difference('Trigger.count') do post(:create, :trigger => { :task_filter_id => filter.id, :fire_on => "create" }) end assert_not_nil assigns(:trigger) assert_redirected_to triggers_path end context "with an existing trigger" do setup do @trigger = Trigger.make(:company => @user.company) end should "destroy trigger" do assert_difference('Trigger.count', -1) do delete :destroy, :id => @trigger.to_param end assert_redirected_to triggers_path end should "get edit" do get :edit, :id => @trigger.to_param assert_response :success end should "update trigger" do put :update, :id => @trigger.to_param, :trigger => { :fire_on => "AAAA" } assert_redirected_to triggers_path assert_equal "AAAA", @trigger.reload.fire_on end end end end
24.205479
81
0.615733
28ddeed306163557abe056d89d9221d0a1e2ea9a
234
module ApplicationHelper # Returns the full title on a per-page basis. def full_title(page_title = '') base_title = "Ruby on Rails Tutorial Sample App" if page_title.empty? base_title else page_title + " | " + base_title end end end
19.5
48
0.760684
ff57e3b0e0e843bd046f64abeadcc5ab8a4ca24f
1,565
module BatchRollback class Railtie < Rails::Railtie rake_tasks do namespace :batch_rollback do task :pre_migrate do ActiveRecord::SchemaMigration.create_table ENV["BR_CURRENT_VERSION"] = ActiveRecord::SchemaMigration.all_versions.last end task :post_migrate do all_versions = ActiveRecord::SchemaMigration.all_versions current_version = ENV.delete("BR_CURRENT_VERSION") target_version = all_versions.last step = all_versions.index(target_version) - (all_versions.index(current_version) || -1) next if step == 0 MigrationStep.create_table MigrationStep.create!( current_version: current_version, target_version: target_version, step: step, ) end task :pre_rollback do next if ENV.has_key?("STEP") MigrationStep.create_table current_version = ActiveRecord::SchemaMigration.all_versions.last migration_step = MigrationStep.where(target_version: current_version).last next if migration_step.nil? ENV["STEP"] = migration_step.step.to_s end end if Rake::Task.task_defined?("db:migrate") Rake::Task["db:migrate"].enhance(["batch_rollback:pre_migrate"]) do Rake::Task["batch_rollback:post_migrate"].invoke end end if Rake::Task.task_defined?("db:rollback") Rake::Task["db:rollback"].enhance(["batch_rollback:pre_rollback"]) end end end end
31.938776
97
0.640895
bf7befde654a216ed3a3d5727a6dc57d0b2db8be
946
cask 'miniconda' do version '4.7.10' sha256 'c8b31ea37b0b6a3e2fb19990ef895ab5cf1c095f8e9138defac95ee88e70920d' # repo.anaconda.com/miniconda was verified as official when first introduced to the cask url "https://repo.anaconda.com/miniconda/Miniconda3-#{version}-MacOSX-x86_64.sh" name 'Continuum Analytics Miniconda' homepage 'https://conda.io/miniconda.html' auto_updates true container type: :naked installer script: { executable: "Miniconda3-#{version}-MacOSX-x86_64.sh", args: ['-b', '-p', "#{caskroom_path}/base"], } binary "#{caskroom_path}/base/condabin/conda" uninstall delete: "#{caskroom_path}/base" zap trash: [ '~/.condarc', '~/.conda', '~/.continuum', ] caveats <<~EOS Please run the following to setup your shell: conda init "$(basename "${SHELL}")" EOS end
28.666667
90
0.614165