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
6ad1acdcd9d5139def267eebbddb4aeebac3e4a2
204
class ChangeGameStatusDefaultAsPending < ActiveRecord::Migration def up change_column_default(:games, :status, 'pending') end def down change_column_default(:games, :status, nil) end end
20.4
64
0.75
4a0435d7e969b0ef40f1ee84e50045a9304543a3
3,644
Given(/^You are in the Compliance page$/) do visit AutomationHomePage on(LoginPage).login_yml on(LandingPage).menus.when_present(10).click sleep(1) on(LandingPage).compliance.when_present(10).click sleep(3) end And(/^you see Reg$/) do expect(on(CompliancePage).reg0.present?).to be_truthy end And(/^you click on Reg$/) do on(CompliancePage).reg0.when_present(10).click end Then(/^you scroll down and hover over Executives and it says MB and not CT$/) do expect(on(CompliancePage).CTExecutives.present?).to be_falsey expect(on(CompliancePage).MBExecutives.present?).to be_truthy on(CompliancePage).MBExecutives.when_present(10).hover end =begin And(/^I see MERS$/) do expect(on(CompliancePage).MERS.present?).to be_truthy expect(on(CompliancePage).reg0.present?).to be_truthy expect(on(CompliancePage).HMDA.present?).to be_truthy end When(/^I click on MERS$/) do on(CompliancePage).MERS.when_present(10).click end Then(/^I get MERS drop down selections$/) do on(CompliancePage).dataImports.when_present(10).hover on(CompliancePage).MERSMonthlyData.when_present(10).click on(CompliancePage).MERS.when_present(10).click on(CompliancePage).dataImports.when_present(10).hover on(CompliancePage).DMIMonthlyData.when_present(10).click on(CompliancePage).MERS.when_present(10).click on(CompliancePage).dataImports.when_present(10).hover on(CompliancePage).acquiredLoansSource.when_present(10).click on(CompliancePage).MERS.when_present(10).click on(CompliancePage).dataImports.when_present(10).hover on(CompliancePage).DMIXrefImports.when_present(10).click on(CompliancePage).MERS.when_present(10).click on(CompliancePage).reconciliation.when_present(10).click on(CompliancePage).MERS.when_present(10).click on(CompliancePage).biennialReviews.when_present(10).click on(CompliancePage).MERS.when_present(10).click on(CompliancePage).MERSOrganizations.when_present(10).click on(CompliancePage).MERS.when_present(10).click on(CompliancePage).exceptionList.when_present(10).click on(CompliancePage).reg0.when_present(10).click on(CompliancePage).reg0Reports.when_present(10).click on(CompliancePage).reg0.when_present(10).click #renamed in CTMWEB-5273 # on(CompliancePage).CTExecutives.when_present(10).click on(CompliancePage).MBExecutives.when_present(10).click sleep(2) on(CompliancePage).HMDA.when_present(10).click on(CompliancePage).reportableEvents.when_present(10).click sleep(3) on(CompliancePage).HMDA.when_present(10).click on(CompliancePage).purchasedLoans.when_present(10).click sleep(3) on(CompliancePage).HMDA.when_present(10).click on(CompliancePage).investorCodes.when_present(10).click sleep(3) on(CompliancePage).HMDA.when_present(10).click on(CompliancePage).exceptions.when_present(10).click sleep(3) on(CompliancePage).HMDA.when_present(10).click on(CompliancePage).exceptionReports.when_present(10).click sleep(3) on(CompliancePage).HMDA.when_present(10).click on(CompliancePage).reportFilters.when_present(10).click sleep(3) #on(CompliancePage).HMDA.when_present(10).click #on(CompliancePage).quarterlyAnnualProcess.when_present(10).click #sleep(3) #on(CompliancePage).HMDA.when_present(10).click #on(CompliancePage).dataChangeReport.when_present(10).click #sleep(3) on(CompliancePage).HMDA.when_present(10).click on(CompliancePage).HPMLLoansReport.when_present(10).click sleep(3) on(CompliancePage).HMDA.when_present(10).click on(CompliancePage).nonReportableLoans.when_present(10).click =end
37.958333
80
0.768386
01d56f1de4498aa3982f6a7ef107864d7b99d15e
1,133
# frozen_string_literal: true lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "email_inquire/version" Gem::Specification.new do |spec| spec.name = "email_inquire" spec.version = EmailInquire::VERSION spec.authors = ["Maxime Garcia"] spec.email = ["[email protected]"] spec.summary = "Library to validate email for format, common typos and one-time email providers" spec.description = spec.summary spec.homepage = "https://github.com/maximeg/email_inquire" spec.license = "MIT" spec.required_ruby_version = ">= 2.3.0" spec.files = `git ls-files -z`.split("\x0").reject do |f| f.match(%r{^(test|spec|features)/}) end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_runtime_dependency("damerau-levenshtein", "~> 1.2") spec.add_development_dependency("bundler", "~> 1.15") spec.add_development_dependency("rake", "~> 10.0") spec.add_development_dependency("rspec", "~> 3.7.0") spec.add_development_dependency("rubocop", "0.52.0") end
32.371429
98
0.697264
e2aefbe1b33fdcb347732fc0936ac9cf2cd4c746
217
# archiveable_id - integer # archiveable_type - string # archive_number - string # archived_at - datetime class Poly < ActiveRecord::Base archival_record belongs_to :archiveable, polymorphic: true end
18.083333
44
0.741935
2664f81171b4546c886e3b81ec2f627b75d7c8c6
459
class DeviseControllers::ConfirmationsController < Devise::ConfirmationsController include DeviseHelper protected def after_confirmation_path_for(resource_name, resource) sign_in resource profile_path end # The path used after confirmation. # def after_confirmation_path_for(resource_name, resource) if signed_in?(resource_name) signed_in_root_path(resource) else new_session_path(resource_name) end end end
21.857143
82
0.77342
2696f0057086db42d22af14b857d3011fc6e47ec
7,571
# frozen_string_literal: true module OmniauthMacros # The mock_auth configuration allows you to set per-provider (or default) # authentication hashes to return during integration testing. ENV['OSEM_GOOGLE_KEY'] = 'test key google' ENV['OSEM_GOOGLE_SECRET'] = 'test secret google' ENV['OSEM_FACEBOOK_KEY'] = 'test key facebook' ENV['OSEM_FACEBOOK_SECRET'] = 'test secret facebook' ENV['OSEM_SUSE_KEY'] = 'test key suse' ENV['OSEM_SUSE_SECRET'] = 'test secret suse' ENV['OSEM_GITHUB_KEY'] = 'test key github' ENV['OSEM_GITHUB_SECRET'] = 'test secret github' ENV['OSEM_DISCOURSE_KEY'] = 'test key discourse' ENV['OSEM_DISCOURSE_SECRET'] = 'test secret discourse' def mock_auth_new_user OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new( provider: 'google', uid: 'google-test-uid-1', info: { name: 'new user name', email: '[email protected]' }, credentials: { token: 'mock_token', secret: 'mock_secret' } ) end def mock_auth_new_user_fb OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new( provider: 'facebook', uid: 'facebook-test-uid-1', info: { name: 'new user fb name', email: '[email protected]' }, credentials: { token: 'mock_token', secret: 'mock_secret' } ) end def mock_auth_existing_user_participant # The mock_auth configuration allows you to set per-provider (or default) # authentication hashes to return during integration testing. OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new( provider: 'google', uid: 'google-test-uid-participant-1', info: { name: 'existing user participant name', email: '[email protected]' }, credentials: { token: 'mock_token', secret: 'mock_secret' } ) end def mock_auth_existing_user_admin # The mock_auth configuration allows you to set per-provider (or default) # authentication hashes to return during integration testing. OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new( provider: 'google', uid: 'google-test-uid-admin-1', info: { name: 'existing user admin name', email: '[email protected]' }, credentials: { token: 'mock_token', secret: 'mock_secret' } ) end # We use these mock accounts to ensure that the ones which are available in # development are valid, to test omniauth actions and verify that a mock # account is available for every supported omniauth provider. # These must be identical to the ones in /config/environments/development.rb # Remember to keep them in sync with development.rb # # Note that the method length check is disabled to allow for better formatting # of the user params. # rubocop:disable Metrics/MethodLength def mock_auth_accounts OmniAuth.config.mock_auth[:facebook] = OmniAuth::AuthHash.new( provider: 'facebook', uid: 'facebook-test-uid-1', info: { name: 'facebook user', email: '[email protected]', username: 'user_facebook' }, credentials: { token: 'fb_mock_token', secret: 'fb_mock_secret' } ) OmniAuth.config.mock_auth[:google] = OmniAuth::AuthHash.new( provider: 'google', uid: 'google-test-uid-1', info: { name: 'google user', email: '[email protected]', username: 'user_google' }, credentials: { token: 'google_mock_token', secret: 'google_mock_secret' } ) OmniAuth.config.mock_auth[:suse] = OmniAuth::AuthHash.new( provider: 'suse', uid: 'suse-test-uid-1', info: { name: 'suse user', email: '[email protected]', username: 'user_suse' }, credentials: { token: 'suse_mock_token', secret: 'suse_mock_secret' } ) OmniAuth.config.mock_auth[:github] = OmniAuth::AuthHash.new( provider: 'github', uid: 'github-test-uid-1', info: { name: 'github user', email: '[email protected]', username: 'user_github' }, credentials: { token: 'github_mock_token', secret: 'github_mock_secret' } ) OmniAuth.config.mock_auth[:discourse] = OmniAuth::AuthHash.new( provider: 'discourse', uid: 'discourse-test-uid-1', info: { name: 'discourse user', email: '[email protected]', username: 'user_discourse' }, credentials: { token: 'discourse_mock_token', secret: 'discourse_mock_secret' } ) end # rubocop:enable Metrics/MethodLength end
43.763006
80
0.397834
1a0afb56b4fb042a1af8d9e9e195552a4d9dec7d
659
module Gitlab module CycleAnalytics class PlanStage < BaseStage def start_time_attrs @start_time_attrs ||= [issue_metrics_table[:first_associated_with_milestone_at], issue_metrics_table[:first_added_to_board_at]] end def end_time_attrs @end_time_attrs ||= issue_metrics_table[:first_mentioned_in_commit_at] end def name :plan end def title s_('CycleAnalyticsStage|Plan') end def legend _("Related Commits") end def description _("Time before an issue starts implementation") end end end end
21.258065
88
0.622155
2639bd9c453377b015af6d560bb7053f700082a1
4,486
module Purchasing def purchase(customer, subscriber, invoice=nil, product=nil) subscription_product = product.nil? ? subscriber.subscription_plan.product : product if subscription_product.has_variants? variant = if subscription_product.default_variant.present? and subscription_product.in_stock? subscription_product.default_variant else subscription_product.variants.find { |v| v.stock_control? == false or v.stock > 0 } end subscription_product = variant if variant.present? end ActiveRecord::Base.transaction do # Allow exception to propogate up so that Stripe queues and retries, as that saves us # having to build a queuing and failed order workflow, thanks Stripe.com. note = if invoice.present? "Created for Stripe invoice #{invoice.id}" elsif subscriber.stripe_id.present? "Created for Stripe subscriber #{subscriber.stripe_id}" else "Created for customer #{customer.id}" end order = Shoppe::Order.create(notes: note, currency: subscriber.currency) order.customer = customer # All billing and delivery details need to be copied to the order. Shoppe requirement. order.first_name = customer.first_name.presence || '-' order.last_name = customer.last_name.presence || '-' # Try to use the billing address if there is one, otherwise use the first address registered address = customer.addresses.billing.first || customer.addresses.ordered.first order.billing_address1 = address.address1 order.billing_address2 = address.address2 order.billing_address3 = address.address3 order.billing_address4 = address.address4 order.billing_postcode = address.postcode order.billing_country = address.country # Try to use any delivery_address if there is one. Next try to use the delivery address. # If there is none and there is more than 1 address use the last address (otherwise we # default delivery to biiling). address = subscriber.delivery_address || customer.addresses.delivery.first if address.nil? address = customer.addresses.last if customer.addresses.count > 1 end if address.present? order.delivery_name = subscriber.recipient_name.presence || customer.full_name order.delivery_address1 = address.address1 order.delivery_address2 = address.address2 order.delivery_address3 = address.address3 order.delivery_address4 = address.address4 order.delivery_postcode = address.postcode order.delivery_country = address.country order.separate_delivery_address = true end order.email_address = subscriber.recipient_email.presence || customer.email order.phone_number = subscriber.recipient_phone.presence || customer.phone order.order_items.add_item(subscription_product, 1) # Add any unclaimed gifts subscriber.subscriber_gifts.unclaimed.each do |gift| order.order_items.add_item(gift.product, 1) gift.update claimed: true end order.delivery_service = order.available_delivery_services.first delivery_service_price = order.delivery_service_prices.first if delivery_service_price.present? order.delivery_price = delivery_service_price.try(:price) || 0 order.delivery_tax_rate = delivery_service_price.tax_rate.try(:rate) || 0 end # Save subscription stripe id to order, will come in handy for applications order.properties[:subscription] = subscriber.stripe_id # Allow errors to propogate back to Stripe so we don't silently forget this order order.save # Need to reload the order as the order_items do not instantly get mapped order.reload order.payments.create(amount: subscription_product.price(subscriber.currency), method: 'Subscription Reallocation', reference: subscriber.stripe_id || "subscriber #{subscriber.id}", refundable: false, confirmed: true) new_balance = subscriber.balance - subscription_product.price(subscriber.currency) subscriber.update balance: [0, new_balance].max subscriber.orders << order order.proceed_to_confirm order.confirm! subscriber.save end end end
42.320755
101
0.690816
5dbfe5b8dcaec872888a9480d899a1e9b3a131bd
91
Pry.config.prompt = lambda do |context, nesting, pry| "[timeywimey] #{context} > " end
22.75
54
0.659341
1d058051089e58b51bd418b961481bce9f0ba297
648
class AnswersController < ApplicationController http_basic_authenticate_with name: "admin", password: "password", only: :destroy def create @question = Question.find(params[:question_id]) @answer = @question.answers.create(answer_params) if @question.movie? == @answer.reallife render :wrong else render :correct end end def destroy @question = Question.find(params[:question_id]) @answer = @question.answers.find(params[:id]) @answer.destroy redirect_to question_path(@question) end private def answer_params params.require(:answer).permit(:reallife, :movie) end end
23.142857
82
0.695988
0873732161424ff6d545e5308e6016166793a26d
5,149
# # Be sure to run `pod spec lint HTCountDownButton.podspec' to ensure this is a # valid spec and to remove all comments including this before submitting the spec. # # To learn more about Podspec attributes see http://docs.cocoapods.org/specification.html # To see working Podspecs in the CocoaPods repo see https://github.com/CocoaPods/Specs/ # Pod::Spec.new do |s| # โ€•โ€•โ€• Spec Metadata โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # # # These will help people to find your library, and whilst it # can feel like a chore to fill in it's definitely to your advantage. The # summary should be tweet-length, and the description more in depth. # s.name = "HTCountDownButton" s.version = "1.0" s.summary = "่ฟ™ๆ˜ฏไธ€ไธช็ฎ€ๅ•็š„ๅ€’่ฎกๆ—ถๆŒ‰้’ฎ,ๅˆ†ไธค็งๅฝขๅผ,ไธ€็งๆ˜ฏ็ปงๆ‰ฟ็š„button,ไธ€็งๆ˜ฏlabel็š„ๅˆ†็ฑป,ๅฎž็Žฐๆ–นๅผ็›ธๅŒ." # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC HTCountDownButton ๆ˜ฏไธ€ไธชๅ€’่ฎกๆ—ถ็š„ๆŒ‰้’ฎๅ’Œlabelๅˆ†็ฑป DESC s.homepage = "https://github.com/KingXcode/HTCountDownButton" # s.screenshots = "www.example.com/screenshots_1.gif", "www.example.com/screenshots_2.gif" # โ€•โ€•โ€• Spec License โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # # # Licensing your code is important. See http://choosealicense.com for more info. # CocoaPods will detect a license file if there is a named LICENSE* # Popular ones are 'MIT', 'BSD' and 'Apache License, Version 2.0'. # s.license = "MIT" # s.license = { :type => "MIT", :file => "FILE_LICENSE" } # โ€•โ€•โ€• Author Metadata โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # # # Specify the authors of the library, with email addresses. Email addresses # of the authors are extracted from the SCM log. E.g. $ git log. CocoaPods also # accepts just a name if you'd rather not provide an email address. # # Specify a social_media_url where others can refer to, for example a twitter # profile URL. # s.author = { "niesiyang" => "[email protected]" } # Or just: s.author = "niesiyang" # s.authors = { "niesiyang" => "[email protected]" } # s.social_media_url = "http://twitter.com/niesiyang" # โ€•โ€•โ€• Platform Specifics โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # # # If this Pod runs only on iOS or OS X, then specify the platform and # the deployment target. You can optionally include the target after the platform. # # s.platform = :ios # s.platform = :ios, "7.0" # When using multiple platforms # s.ios.deployment_target = "5.0" # s.osx.deployment_target = "10.7" # s.watchos.deployment_target = "2.0" # s.tvos.deployment_target = "9.0" # โ€•โ€•โ€• Source Location โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # # # Specify the location from where the source should be retrieved. # Supports git, hg, bzr, svn and HTTP. # s.source = { :git => "https://github.com/KingXcode/HTCountDownButton.git", :tag => "#{s.version}" } # โ€•โ€•โ€• Source Code โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # # # CocoaPods is smart about how it includes source code. For source files # giving a folder will include any swift, h, m, mm, c & cpp files. # For header files it will include any header in the folder. # Not including the public_header_files will make all headers public. # s.source_files = "HTCountDownButton" s.exclude_files = "UIKit" # s.public_header_files = "HTCountDownButton/**/*.h" # โ€•โ€•โ€• Resources โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # # # A list of resources included with the Pod. These are copied into the # target bundle with a build phase script. Anything else will be cleaned. # You can preserve files from being cleaned, please don't preserve # non-essential files like tests, examples and documentation. # # s.resource = "icon.png" # s.resources = "Resources/*.png" # s.preserve_paths = "FilesToSave", "MoreFilesToSave" # โ€•โ€•โ€• Project Linking โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # # # Link your library with frameworks, or libraries. Libraries do not include # the lib prefix of their name. # # s.framework = "SomeFramework" # s.frameworks = "SomeFramework", "AnotherFramework" # s.library = "iconv" # s.libraries = "iconv", "xml2" # โ€•โ€•โ€• Project Settings โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€•โ€• # # # If your library depends on compiler flags you can set them in the xcconfig hash # where they will only apply to your library. If you depend on other Podspecs # you can include multiple dependencies to ensure it works. s.requires_arc = true # s.xcconfig = { "HEADER_SEARCH_PATHS" => "$(SDKROOT)/usr/include/libxml2" } # s.dependency "JSONKit", "~> 1.4" end
37.311594
107
0.597203
210ec161599822c65811ae952fae286084e2b096
222
puts "Hello World!" print "Please input your string:" user_input = gets.chomp user_input.downcase! if user_input.include? "s" puts user_input.gsub!(/s/, "th") else puts "No ss found!" end 30.times {print "Ruby!"}
15.857143
35
0.693694
1d04aab94aa8eb06fef7ce8bd7875127ae73eadb
140
class AddRoleToUserProfile < ActiveRecord::Migration[5.0] def change add_column :user_profiles, :role, :integer, default: 0 end end
23.333333
58
0.75
796bbe4caecda661d94f6acf44da61d7362112a4
369
require "open-uri" class Musicbrainz def initialize(mbid:) @mbid = mbid end def call # mbid = "56d2735d-abc7-4070-9c3f-bc27593d922d" url = "https://musicbrainz.org/ws/2/recording/#{@mbid}?inc=releases&fmt=json" raw = URI.open(url, "User-Agent" => "curl/7.54.0").read response = JSON.parse raw response["releases"][0]["date"] end end
21.705882
81
0.644986
28084a93ed7a74fdf3c4f472179fb33d3243a91f
333
$LOAD_PATH.unshift(File.expand_path('../', __FILE__)) require 'spec_helper' require 'netlink' describe Netlink::NlMsgHdr do describe '#payload_len' do it 'should return the length of the message minus header length' do hdr = Netlink::NlMsgHdr.new hdr.len += 10 hdr.payload_len.should == 10 end end end
23.785714
71
0.693694
08970c78f4f8c1230b8a66f03b8551f24b11e1f4
861
# # Cookbook Name:: oneview_test_api300_synergy # Recipe:: logical_interconnect_remove_from_scopes # # (c) Copyright 2017 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. # oneview_logical_interconnect 'LogicalInterconnect1' do client node['oneview_test']['client'] scopes ['Scope1', 'Scope2'] action :remove_from_scopes end
39.136364
84
0.782811
080b9ab1559d60fa29dbd2a2c82eda55ef27faef
792
module OData module Core module Segments class EntityTypeSegment < OData::Core::Segment include OData::Core::Countable attr_reader :entity_type def initialize(query, entity_type, value = nil) @entity_type = entity_type super(query, value || (@entity_type.is_a?(OData::AbstractSchema::EntityType) ? @entity_type.plural_name : @entity_type)) end def self.can_follow?(anOtherSegment) false end def execute!(acc, options = nil) return [] if @entity_type.blank? @entity_type.find_all end def valid?(results) countable? ? results.is_a?(Array) : !results.blank? end end # EntityTypeSegment end # Segments end # Core end # OData
24.75
130
0.609848
bb27eafce56521bff24e7d2c975cb1d1fa1d52fb
59
module Resque class Pool VERSION = "0.7.0" end end
9.833333
21
0.627119
ff2f6ba9ad98655d76a21f5ad859d71b54973cb3
2,619
#-- copyright # OpenProject is an open source project management software. # Copyright (C) 2012-2020 the OpenProject GmbH # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License version 3. # # OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows: # Copyright (C) 2006-2017 Jean-Philippe Lang # Copyright (C) 2010-2013 the ChiliProject Team # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # See docs/COPYRIGHT.rdoc for more details. #++ require 'spec_helper' module Redmine describe UnifiedDiff do before do @diff = Redmine::UnifiedDiff.new(<<-DIFF --- old.js Thu May 11 14:24:58 2014 +++ new.js Thu May 11 14:25:02 2014 @@ -0,0 +1,1 @@ +<script>someMethod();</script> @@ -1,2 +1,2 @@ -text text +text modified DIFF ) end it 'should have 1 modified file' do expect(@diff.size).to eq(1) end it 'should have 3 diff items' do expect(@diff.first.size).to eq(3) end it 'should parse the HTML entities correctly' do expect(@diff.first.first.line_right).to eq('<script>someMethod();</script>') end end describe 'unified diff html eescape' do let(:diff) do Redmine::UnifiedDiff.new(<<~DIFF diff --git a/asdf b/asdf index 7f6361d..3c52e50 100644 --- a/asdf +++ b/asdf @@ -1,4 +1,4 @@ Test 1 -Test 2 <_> pouet +Test 2 >_> pouet Test 3 Test 4 DIFF ) end subject do [].tap do |lines| diff.first.each_line { |_,l| lines << [l.html_line_left, l.html_line_right] } end end it 'should correctly escape elements' do expect(subject[1]).to eq(["Test 2 <span>&lt;</span>_&gt; pouet", "<span></span>"]) expect(subject[2]).to eq(["<span></span>", "Test 2 <span>&gt;</span>_&gt; pouet"]) end end end
29.761364
91
0.649866
385ee95b715a8820df8903f88c05ff26abec4f5b
899
module RailsNewIo class HtmlDataAttributeGenerator def initialize(item_name, menu_card_in_all_states, menu_card_id) @item_name = item_name @menu_card_in_all_states = menu_card_in_all_states @menu_card_id = menu_card_id end def html_data_attributes @menu_card_in_all_states[@item_name].each_with_object([]) { |(base_state_name, base_state_display_state), html_data_attributes| html_data_attributes << html_data_attribute(base_state_name, base_state_display_state[:checked]) }.join(" ").html_safe end private def html_data_attribute(base_state_name, base_state_value) attribute_code = <<-CODE #{attribute_name(base_state_name)}="#{base_state_value}" CODE attribute_code.squish.tr(" ", "") end def attribute_name(base_state_name) "data-#{base_state_name}".downcase.dasherize end end end
29.966667
133
0.728587
e9816eb03dea370f6362508fd1f1dd6b3dbe3650
1,161
require "spec_helper" RSpec.describe Adjudication::Engine::Claim do describe 'duplicate? method' do it "must have an npi length of 10 characters" do provider = Adjudication::Providers::Provider.new provider.npi = "0123456789" expect(provider.valid?).to eq(true) end it "must not have an NPI length of more than 10 characters" do provider = Adjudication::Providers::Provider.new provider.npi = "012345679989" expect(provider.valid?).to eq(false) end it "must not have an NPI length of less than 10 characters" do provider = Adjudication::Providers::Provider.new provider.npi = "01234589" expect(provider.valid?).to eq(false) end it "must not have an NPI length that does not exist - is nil" do provider = Adjudication::Providers::Provider.new provider.npi = nil expect(provider.valid?).to eq(false) end it "must have an NPI that contains only numbers " do provider = Adjudication::Providers::Provider.new provider.npi = "123r567890" expect(provider.valid?).to eq(false) end end end
24.702128
68
0.653747
4a3d3b935d8d0be536c8909d12cf797d88ab5154
1,554
require 'facebook/messenger/configuration/app_secret_proof_calculator' module Facebook module Messenger class Configuration module Providers # This is the base configuration provider. # User can overwrite this class to customize the environment variables # Be sure to implement all the functions as it raises # NotImplementedError errors. class Base # A default caching implentation of generating the app_secret_proof # for a given page_id def app_secret_proof_for(page_id = nil) return unless fetch_app_secret_proof_enabled? memo_key = [app_secret_for(page_id), access_token_for(page_id)] memoized_app_secret_proofs[memo_key] ||= calculate_app_secret_proof(*memo_key) end def valid_verify_token?(*) raise NotImplementedError end def app_secret_for(*) raise NotImplementedError end def access_token_for(*) raise NotImplementedError end private def calculate_app_secret_proof(app_secret, access_token) Facebook::Messenger::Configuration::AppSecretProofCalculator.call( app_secret, access_token ) end def memoized_app_secret_proofs @memoized_app_secret_proofs ||= {} end def fetch_app_secret_proof_enabled? false end end end end end end
28.254545
80
0.617761
1a5f223f8c3b1ccb234433a0a0bd2db3c1983fdd
1,331
class SessionsController < ApplicationController # This is required because of a quirk the "developer" authentication # strategy. We'll remove this when we move to a "real" provider. skip_before_action :verify_authenticity_token, only: :create skip_before_action :require_login, only: [:new, :create, :destroy] def new end def create #binding.pry if params[:email].nil? #omniauth Github strategy: omniauth_data = request.env['omniauth.auth'] name = omniauth_data[:info][:name] email = omniauth_data[:info][:email] user = User.find_by(uid: omniauth_data[:uid]) if user.nil? user = User.new user.apply_omniauth(omniauth_data) user.save end session[:user_id] = user.id session[:omniauth_data] = omniauth_data redirect_to root_path else user = User.find_by(email: params[:email]) if user.nil? redirect_to "/signin", alert: "No such email found." elsif user.authenticate(params[:password]) session[:user_id] = user.id redirect_to user_path(user) else flash[:notice] = "Incorrect password." redirect_to "/signin", alert: "Incorrect password." end end end def destroy # params.raise.inspect session.clear redirect_to root_url end end
28.934783
70
0.659654
b974b27254938c60b65d8ecf0c166b2607a462c0
1,156
require 'test_helper' describe Cassandra::Utils::Stats::Health do before do @checker = Cassandra::Utils::Stats::Health.new end describe :run! do it 'succeeds if node is NORMAL and thrift and gossip are running' do @checker.stub :nodetool_netstats, 'Mode: NORMAL' do @checker.stub :nodetool_info, "Gossip active: true\nThrift active: true\n" do @checker.run!.must_equal true end end end it 'fails if gossip is down' do @checker.stub :nodetool_netstats, 'Mode: NORMAL' do @checker.stub :nodetool_info, "Gossip active: false\nThrift active: true\n" do @checker.run!.must_equal false end end end it 'fails if thrift is down' do @checker.stub :nodetool_netstats, 'Mode: NORMAL' do @checker.stub :nodetool_info, "Gossip active: true\nThrift active: false\n" do @checker.run!.must_equal false end end end it 'skips thrift and gossip checks if node is not NORMAL' do @checker.stub :nodetool_netstats, 'Mode: JOINING' do @checker.run!.must_equal true end end end end
30.421053
86
0.639273
4a248cbe36e80b1fb2ffafbd1b7ae23a8c68e4ac
415
# encoding: utf-8 module FriendlyId module Helpers # Calculate expected result size for find_some_with_friendly (taken from # active_record/base.rb) def expected_size(ids_and_names, options) #:nodoc:# size = options[:offset] ? ids_and_names.size - options[:offset] : ids_and_names.size size = options[:limit] if options[:limit] && size > options[:limit] size end end end
27.666667
90
0.689157
e275c13b8f811b71e2cd83b3f7ec70c7035ddcdd
53
class HeapAPI::Client include HeapAPI::Helpers end
13.25
26
0.792453
bb90e764f1f975006aef6f12e92454c1c59acefa
5,112
require 'rails_helper' include ActiveSupport::Testing::TimeHelpers RSpec.describe Api::Url, type: :model do before do travel_to Time.local(2021) end after do travel_back Api::Url.destroy_all end describe '#new' do it "is valid with a slug and a valid original_Api::Url" do url = Api::Url.new(slug: 'slug1', original_url: 'https://www.goldbelly.com') expect(url).to be_valid url.destroy end it "is not valid without a slug" do url = Api::Url.new(slug: nil, original_url: 'https://www.goldbelly.com') expect(url).to_not be_valid end it "is not valid with a duplicate slug" do url = Api::Url.create(slug: 'slug1', original_url: 'https://www.goldbelly.com') url2 = Api::Url.create(slug: 'slug1', original_url: 'https://www.goldbelly.com') expect(url2).to_not be_valid end it "is not valid with a slug longer than 32 characters" do url = Api::Url.new(slug: 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz', original_url: 'https://www.goldbelly.com') expect(url).to_not be_valid end it "is not valid without an original_url" do url = Api::Url.new(slug: 'slug1', original_url: nil) expect(url).to_not be_valid end it "is not valid with a malformed url" do url = Api::Url.new(slug: 'slug1', original_url: 'http:/cnn.com') expect(url).to_not be_valid end it "is not valid with a malformed url" do url = Api::Url.new(slug: 'slug1', original_url: 'thisisjustaword') expect(url).to_not be_valid end it "accepts an optional expiration time in the future" do url = Api::Url.new(slug: 'slug1', original_url: 'https://www.goldbelly.com', expiration: Time.now + 1.day) expect(url).to be_valid end it "does not accept an expiration time in the past" do url = Api::Url.new(slug: 'slug1', original_url: 'https://www.goldbelly.com', expiration: Time.now - 1.day) expect(url).to_not be_valid end it "sets a default expiration if one is not given" do url = Api::Url.new(slug: 'slug1', original_url: nil) expect(url.expiration).to eq Time.now + 2.years end it "accepts an optional user_id" do url = Api::Url.new(slug: 'slug1', original_url: 'https://www.goldbelly.com', expiration: Time.now + 1.day, user_id: '123') expect(url.user_id).to eq '123' end end describe '#prep_user_slug' do it 'removes invalid special characters in user slug' do params = { slug: 'abc$#!@?&' } Api::Url.prep_user_slug(params) expect(params[:slug]).to eq 'abc' end end describe '#prep_random_slug' do it 'generates a random 6 character slug' do params = { original_url: 'https://www.goldbelly.com' } Api::Url.prep_random_slug(params) expect(params[:slug]).to eq 'TZ95L5' end end describe '#generate_slug' do it 'generates a random 6 character slug for the user' do slug = Api::Url.generate_slug('https://www.goldbelly.com') expect(slug).to eq 'TZ95L5' end end describe '#generate_slug' do it 'generates a unique random 6 character slug for each original url' do slug1 = Api::Url.generate_slug('https://www.goldbelly.com') slug2 = Api::Url.generate_slug('https://www.google.com') expect(slug1).to_not eq slug2 end end describe '#generate_slug' do it 'generates a unique random 6 character slug for same url if time is different' do slug1 = Api::Url.generate_slug('https://www.goldbelly.com') travel_to Time.local(2020) slug2 = Api::Url.generate_slug('https://www.goldbelly.com') expect(slug1).to_not eq slug2 end end describe '#cost' do it 'calculates the correct slug cost for goly' do url = Api::Url.new(slug: 'goly', original_url: 'https://www.goldbelly.com') expect(url.cost).to eq 5 end it 'calculates the correct slug cost for oely' do url = Api::Url.new(slug: 'oely', original_url: 'https://www.goldbelly.com') expect(url.cost).to eq 6 end it 'calculates the correct slug cost for gole' do url = Api::Url.new(slug: 'gole', original_url: 'https://www.google.com') expect(url.cost).to eq 6 end it 'calculates the correct slug cost for goog' do url = Api::Url.new(slug: 'goog', original_url: 'https://www.google.com') expect(url.cost).to eq 8 end end describe '#suggested_slug' do it 'suggests the cheapest possible slug for goldbelly' do url = Api::Url.new(original_url: 'goldbelly') expect(url.suggested_slug).to eq 'gldb' end it 'suggests the cheapest possible slug for google' do url = Api::Url.new(original_url: 'google') expect(url.suggested_slug).to eq 'gloe' end it 'suggests the cheapest possible slug for hi' do url = Api::Url.new(original_url: 'hi') expect(url.suggested_slug).to eq 'hihh' end it 'suggests the cheapest possible slug for ae' do url = Api::Url.new(original_url: 'ae') expect(url.suggested_slug).to eq 'aeaa' end end end
32.56051
129
0.65669
b918e176662d3628f169eb49d437f7e2bc14148d
5,607
require File.expand_path('../../../Util/platform.rb', __FILE__) module Applocale class CompareStringFile attr_reader :in_multiline_comments, :platform, :file1, :file2, :errorlist, :print_result, :lang def initialize(platform, file1, file2, lang = nil, print_result = true) @platform = platform @file1 = file1 @file2 = file2 @errorlist = Array.new() @platform = platform @print_result = print_result @lang = lang end def self.compare(lang_path_obj) Applocale::CompareStringFile.new(lang_path_obj.platform, lang_path_obj.filepath1, lang_path_obj.filepath2, lang_path_obj.lang, false).compare end def compare obj1 = {} obj2 = {} if @platform == Platform::IOS obj1 = parse_ios_file(@file1) obj2 = parse_ios_file(@file2) elsif @platform == Platform::ANDROID obj1 = parse_aos_file(@file1) obj2 = parse_aos_file(@file2) end missingkeyInObj2 = Array.new mismatch = Array.new duplicateKey = Array.new notSame = {} nobj2 = obj2 obj1.each do |key, value| if nobj2[key].nil? missingkeyInObj2.push(key) else obj1Value = value obj2Value = obj2[key] if obj1Value.length != obj2Value.length mismatch.push(key) elsif obj1Value.length != 1 duplicateKey.push(key) elsif obj1Value[0] != obj2Value[0] notSame[key] = {obj1: obj1Value[0],obj2: obj2Value[0]} end end nobj2.delete(key) end missingKeyInObj1 = nobj2.keys notSameKeys = notSame.keys comparison_result = Applocale::Config::LangPathComparisonResult.init(@platform, @lang, @file1, @file2, notSameKeys, duplicateKey, mismatch, missingKeyInObj1, missingkeyInObj2) if @print_result puts "==> not Same value:" notSame.each do |key, value| puts "key = #{key}" puts "#{value[:obj1]}<" puts "#{value[:obj2]}<" end puts "==> duplicateKey" puts duplicateKey puts "==> mismatch" puts mismatch puts "==> missingkeyInObj2" puts missingkeyInObj2 puts "==> missingKeyInObj1" puts missingKeyInObj1 end comparison_result end def parse_aos_file(strings_path) strings_keys = {} return if !File.exist? strings_path puts "Start to Parse xml file: \"#{strings_path}\" ...".green xml_doc = Nokogiri::XML(File.open(strings_path)) string_nodes = xml_doc.xpath("//string") string_nodes.each do |node| key = node["name"] value = node.content if !key.nil? && key.strip.length > 0 if strings_keys[key].nil? strings_keys[key] = Array.new end strings_keys[key].push(value) # if @strings_keys[key].nil? # @strings_keys[key] = Hash.new # @keys_list.push(key) # end # if @strings_keys[key][lang.to_s].nil? # @strings_keys[key][lang.to_s] = Hash.new # @strings_keys[key][lang.to_s][:value] = self.remove_escape(lang, key, value) # else # error = ErrorUtil::ParseLocalizedError::DuplicateKey.new(key, -1, strings_path, lang, -1).raise # end end end return strings_keys end def parse_ios_file(path) strings_keys = {} begin IO.foreach(path, mode: 'r:bom|utf-8') {|line| line.strip! match = line.match(/"(.*?)" = "(.*)";/) unless match.nil? key = match.captures[0] value = match.captures[1] if strings_keys[key].nil? strings_keys[key] = Array.new end strings_keys[key].push(value) end } rescue Exception => e puts e.message ErrorUtil::ParseLocalizedError::InvalidFile.new(file1).raise end return strings_keys end def parse_token(linenum, line, sep, file) n = 0 in_value = false in_quote = false in_escape = false value = "" for ch in line.chars prech = "" prech = line.chars[n-1] if n > 0 n += 1 if @in_multiline_comments if "#{prech}#{ch}" == "*/" @in_multiline_comments = false in_value = false value = "" end next end if not in_value if ch == "\"" in_quote = true in_value = true elsif ch != " " and ch != "\t" and ch != sep in_value = true value << ch end next end if in_escape value << prech value << ch in_escape = false elsif ch == "\\" in_escape = true elsif in_quote if ch == "\"" break else value << ch end else if ch == " " or ch == "\t" or ch == sep n -= 1 break elsif "#{prech}#{ch}" == "/*" @in_multiline_comments = true elsif "#{prech}#{ch}" == "//" return value, "" elsif ch == "#" return value, "" elsif "#{prech}#{ch}".length > 1 error = ErrorUtil::ParseLocalizedError::WrongFormat.new(file, "", linenum) @errorlist.push(error) return value, "" else value << ch end end end return value, line[n..-1] end end end
27.35122
181
0.531835
ff78fdc738349fdc99a8d9180513263ec26d7214
2,478
# frozen_string_literal: true module HTML class Pipeline class AtMentionFilter < Filter DEFAULT_IGNORED_ANCESTOR_TAGS = %w(pre code tt a style).freeze # @param context [Hash] # @options context :users_provider [#call(usernames)] given usernames, returns a list of users. def initialize(doc, context = nil, result = nil) super doc, context, result @users_provider = context[:users_provider] @view_context = context[:view_context] end def call return doc unless @users_provider process_text_nodes! do |node| content = node.to_html next unless content.include?('@') highlight! content node.replace content end doc end # @return [Array<Thredded.user_class>] users that were @-mentioned def mentioned_users return [] unless @users_provider names = [] process_text_nodes! { |node| names.concat mentioned_names(node.to_html) } names.uniq! @users_provider.call(names) end private MATCH_NAME_RE = /(?:^|[\s>])@([\w]+|"[\w ]+")(?=\W|$)/ def mentioned_names(text_node_html) text_node_html.scan(MATCH_NAME_RE).map(&:first).map { |m| m.start_with?('"') ? m[1..-2] : m } end def highlight!(text_node_html) names = mentioned_names(text_node_html) return unless names.present? @users_provider.call(names).each do |user| name = user.to_s maybe_quoted_name = name.include?(' ') ? %("#{name}") : name url = Thredded.user_path(@view_context, user) text_node_html.gsub!( /(^|[\s>])(@#{Regexp.escape maybe_quoted_name})([^a-z\d]|$)/i, %(\\1<a href="#{ERB::Util.html_escape url}">@#{ERB::Util.html_escape maybe_quoted_name}</a>\\3) ) end end # Yields text nodes that should be processed. def process_text_nodes! doc.search('.//text()').each do |node| next if has_ancestor?(node, ignored_ancestor_tags) yield node end end # Return ancestor tags to stop the at-mention highlighting. # # @return [Array<String>] Ancestor tags. def ignored_ancestor_tags if @context[:ignored_ancestor_tags] DEFAULT_IGNORED_ANCESTOR_TAGS | @context[:ignored_ancestor_tags] else DEFAULT_IGNORED_ANCESTOR_TAGS end end end end end
31.769231
107
0.602502
915d214d0b9ed695ee3e9b825e6521d2f27ac46d
829
require_relative 'spec_utils.rb' require 'rspec' require './lib/commit_score_writer' require './lib/joy_config' SUBJECT = "This is the subject line without a body" SCORE = 5 describe 'Commit Score Writer' do context 'given no commit message' do it 'should throw an argument error' do expect {GitCommitScoreWriter.write}.to raise_error(ArgumentError) end end context 'given a commit message with a subject and score' do before(:each) do @message = CommitMessage.new @message.subject = SUBJECT @message.score = SCORE end it 'should write a subject and score' do GitCommitScoreWriter.write(@message) expect(get_scores[SUBJECT]).to eq(SCORE) end end end def get_scores config = JoyConfig.new file = File.read(config.score_file_name) JSON.parse(file) end
23.685714
71
0.712907
6a4a5375d182854eadefe6d47c699518873c2c92
1,630
# frozen_string_literal: true class Fisk module Instructions # Instruction MULSS: Multiply Scalar Single-Precision Floating-Point Values MULSS = Instruction.new("MULSS", [ # mulss: xmm, xmm Form.new([ OPERAND_TYPES[23], OPERAND_TYPES[24], ].freeze, [ Class.new(Fisk::Encoding) { def encode buffer, operands add_prefix(buffer, operands, 0xF3, true) + add_rex(buffer, operands, false, 0, operands[0].rex_value, 0, operands[1].rex_value) + add_opcode(buffer, 0x0F, 0) + add_opcode(buffer, 0x59, 0) + add_modrm(buffer, 3, operands[0].op_value, operands[1].op_value, operands) + 0 end }.new.freeze, ].freeze).freeze, # mulss: xmm, m32 Form.new([ OPERAND_TYPES[23], OPERAND_TYPES[14], ].freeze, [ Class.new(Fisk::Encoding) { def encode buffer, operands add_prefix(buffer, operands, 0xF3, true) + add_rex(buffer, operands, false, 0, operands[0].rex_value, operands[1].rex_value, operands[1].rex_value) + add_opcode(buffer, 0x0F, 0) + add_opcode(buffer, 0x59, 0) + add_modrm(buffer, 0, operands[0].op_value, operands[1].op_value, operands) + 0 end }.new.freeze, ].freeze).freeze, ].freeze).freeze end end
28.103448
79
0.497546
1aeb6b90433d0a46b3e072fa875ecb3b4a83aca9
1,217
require 'colored' module Rapid # Utility functions for logging # # Rapid::Logger defines a method, #default_logger, that provides a sensible # logging format for Rapid. module Logger # Constructs the default Rapid logger configuration def self.default_logger # TODO: Allow redirecting output = STDERR ::Logger.new(output).tap do |logger| logger.formatter = proc do |severity, datetime, _progname, msg| [format_date(datetime, output), format_severity(severity, output), msg].join(' ') + "\n" end end end private # Colourises the severity if the logging output is a terminal def self.format_severity(severity, output) "[#{output.is_a?(String) ? severity : coloured_severity(severity)}]" end def self.format_date(datetime, output) dt = datetime.strftime('%d/%m/%y %H:%M:%S') output.is_a?(String) ? dt : dt.green end SEVERITIES = { 'DEBUG' => :green, 'INFO' => :blue, 'WARN' => :yellow, 'ERROR' => :red, 'FATAL' => :magenta } def self.coloured_severity(severity) severity.send(SEVERITIES.fetch(severity, :white)) end end end
25.893617
77
0.620378
79486c81809c9f84c743fd9f796bfb12697d2666
9,705
require 'spec_helper' require 'napa/cli/model' describe Napa::CLI::Model do let(:test_output_directory) { 'spec/tmp' } let(:version) { '20000101000000' } silence_thor before do allow_any_instance_of(described_class).to receive(:model_output_directory).and_return(test_output_directory) allow_any_instance_of(described_class).to receive(:migration_output_directory).and_return(test_output_directory) allow_any_instance_of(described_class).to receive(:factory_output_directory).and_return(test_output_directory) allow_any_instance_of(described_class).to receive(:model_spec_output_directory).and_return(test_output_directory) allow_any_instance_of(described_class).to receive(:version).and_return(version) end after do FileUtils.rm_rf(test_output_directory) end describe 'Car model' do before do model = Napa::CLI::Model.new([ 'Car', 'transmission_type:references', 'has_navigation:boolean' ], [ '--parent=Vehicle' ]) model.invoke_all # The migration should not be created because a parent model is specified. @migration_file = File.join(test_output_directory, "#{version}_create_cars.rb") expected_model_file = File.join(test_output_directory, 'car.rb') @model_content = File.read(expected_model_file) expected_model_spec_file = File.join(test_output_directory, 'car_spec.rb') @model_spec_content = File.read(expected_model_spec_file) expected_factory_file = File.join(test_output_directory, 'cars.rb') @factory_content = File.read(expected_factory_file) end describe 'migration' do it 'is not created' do expect(File.exists?(@migration_file)).to eq(false) end end describe 'model' do it 'creates a model class' do expect(@model_content).to match(/class Car/) end it 'model inherits from ActiveRecord::Base' do expect(@model_content).to match(/Car < Vehicle/) end it 'adds belongs_to association for references attributes' do expect(@model_content).to match(/belongs_to :transmission_type/) end end describe 'model spec' do it 'loads the spec_helper' do expect(@model_spec_content).to match(/require 'spec_helper'/) end it 'describes the model' do expect(@model_spec_content).to match(/describe Car/) end it 'tests the creation of an model instance' do expect(@model_spec_content).to match(/car = create :car/) end it 'creates a pending test' do expect(@model_spec_content).to match(/pending\('.*'\)/) end end describe 'factory' do it 'creates a factory for the model' do expect(@factory_content).to match(/factory :car/) end it 'creates a stub for each attribute' do expect(@factory_content).to match(/association :transmission_type/) expect(@factory_content).to match(/has_navigation false/) end end after do FileUtils.rm_rf(test_output_directory) end end describe 'User model' do before do Napa::CLI::Model.new([ 'User', 'username:string:index', 'password:digest', 'referrer:references', 'birth_date:date:index' ]).invoke_all expected_migration_file = File.join(test_output_directory, "#{version}_create_users.rb") @migration_content = File.read(expected_migration_file) expected_model_file = File.join(test_output_directory, 'user.rb') @model_content = File.read(expected_model_file) expected_model_spec_file = File.join(test_output_directory, 'user_spec.rb') @model_spec_content = File.read(expected_model_spec_file) expected_factory_file = File.join(test_output_directory, 'users.rb') @factory_content = File.read(expected_factory_file) end describe 'migration' do it 'creates a creates a camelized migration class' do expect(@migration_content).to match(/class CreateUsers/) end it 'creates a table for the new model' do expect(@migration_content).to match(/create_table :users/) end it 'adds the specified columns' do expect(@migration_content).to match(/t.string :username/) end it 'adds the specified associations' do expect(@migration_content).to match(/t.references :referrer/) end it 'adds password digest column' do expect(@migration_content).to match(/t.string :password_digest/) end it 'adds the necessary indexes' do expect(@migration_content).to match(/add_index :users, :username/) expect(@migration_content).to match(/:referrer, index: true/) expect(@migration_content).to match(/add_index :users, :birth_date/) end end describe 'model' do it 'creates a model class' do expect(@model_content).to match(/class User/) end it 'model inherits from ActiveRecord::Base' do expect(@model_content).to match(/User < ActiveRecord::Base/) end it 'adds has_secure_password for password digest attributes' do expect(@model_content).to match(/has_secure_password/) end end describe 'model spec' do it 'loads the spec_helper' do expect(@model_spec_content).to match(/require 'spec_helper'/) end it 'describes the model' do expect(@model_spec_content).to match(/describe User/) end it 'tests the creation of an model instance' do expect(@model_spec_content).to match(/user = create :user/) end it 'creates a pending test' do expect(@model_spec_content).to match(/pending\('.*'\)/) end end describe 'factory' do it 'creates a factory for the model' do expect(@factory_content).to match(/factory :user/) end it 'creates a stub for each attribute' do expect(@factory_content).to match(/username "MyString"/) expect(@factory_content).to match(/password "password"/) expect(@factory_content).to match(/association :referrer/) expect(@factory_content).to match(/birth_date { Date.today }/) end it 'creates a confirmation for password attributes' do expect(@factory_content).to match(/password_confirmation "password"/) end end after do FileUtils.rm_rf(test_output_directory) end end describe 'Gender model' do before do model = Napa::CLI::Model.new([ 'Gender', 'name:string', 'personal_characteristic:belongs_to{polymorphic}' ], [ '--no-timestamps' ]) model.invoke_all expected_migration_file = File.join(test_output_directory, "#{version}_create_genders.rb") @migration_content = File.read(expected_migration_file) expected_model_file = File.join(test_output_directory, 'gender.rb') @model_content = File.read(expected_model_file) expected_model_spec_file = File.join(test_output_directory, 'gender_spec.rb') @model_spec_content = File.read(expected_model_spec_file) expected_factory_file = File.join(test_output_directory, 'genders.rb') @factory_content = File.read(expected_factory_file) end describe 'migration' do it 'creates a migration class' do expect(@migration_content).to match(/class CreateGenders/) end it 'creates a table for the new model' do expect(@migration_content).to match(/create_table :genders/) end it 'adds the specified columns' do expect(@migration_content).to match(/t.string :name/) end it 'adds the specified associations' do expect(@migration_content).to match(/t.belongs_to :personal_characteristic/) end it 'sets up the polymorphic associations' do expect(@migration_content).to match(/:personal_characteristic, polymorphic: true/) end it 'does NOT add timestamps to the table' do expect(@migration_content).to_not match(/t.timestamps/) end end describe 'model' do it 'creates a model class' do expect(@model_content).to match(/class Gender/) end it 'model inherits from ActiveRecord::Base' do expect(@model_content).to match(/Gender < ActiveRecord::Base/) end it 'adds belongs_to associations' do expect(@model_content).to match(/belongs_to :personal_characteristic/) end it 'sets up polymorphic associations' do expect(@model_content).to match(/:personal_characteristic, polymorphic: true/) end end describe 'model spec' do it 'loads the spec_helper' do expect(@model_spec_content).to match(/require 'spec_helper'/) end it 'describes the model' do expect(@model_spec_content).to match(/describe Gender/) end it 'tests the creation of an model instance' do expect(@model_spec_content).to match(/gender = create :gender/) end it 'creates a pending test' do expect(@model_spec_content).to match(/pending\('.*'\)/) end end describe 'factory' do it 'creates a factory for the model' do expect(@factory_content).to match(/factory :gender/) end it 'creates a stub for each attribute' do expect(@factory_content).to match(/name "MyString"/) end end after do FileUtils.rm_rf(test_output_directory) end end end
32.567114
117
0.65729
918a65b8aaa8c395355ae8ae560014ee69b29bf7
2,391
require 'spec_helper' describe BetfairNg::API::Operations::Betting::ListClearedOrders do include SharedHelper::Config include SharedHelper::Stubs describe "Operation" do before do stub :certlogin stub :list_cleared_orders end subject { BetfairNg::API::Operations::Betting::ListClearedOrders::Operation.new( config: config, session: session ) } describe "#endpoint" do it "has proper value" do expect(subject.endpoint).to eq('https://api.betfair.com/exchange/betting/json-rpc/v1') end end describe "#perform" do before do session.create end it 'returns valid response' do subject.perform expect(subject.http_code).to eq("200") expect(subject.success?).to be true expect(subject.http_data.result).not_to be_empty expect(subject.http_data.result.keys).to eq(["clearedOrders", "moreAvailable"]) expect(subject.http_data.result["clearedOrders"]).to eq([{"eventTypeId"=>"1", "eventId"=>"27393661", "marketId"=>"1.117733825", "selectionId"=>1561969, "handicap"=>0.0, "betId"=>"47793528580", "placedDate"=>"2015-03-20T14:17:39.000Z", "persistenceType"=>"LAPSE", "orderType"=>"LIMIT", "side"=>"BACK", "priceRequested"=>2.7, "settledDate"=>"2015-03-20T14:49:51.000Z", "betCount"=>1, "priceMatched"=>2.7, "priceReduced"=>false, "sizeSettled"=>4.66, "profit"=>-4.66}]) end end describe "#serialize" do it "properly sets the classes" do subject.perform expect(subject.data.class).to be_kind_of(Class) expect(subject.data.keys).to eq([:cleared_orders, :more_available]) end end describe "#request_params" do it "returns a proper hash with default values" do expect(subject.request[:params]).to eq({betStatus: :SETTLED}) expect(subject.request(bet_ids: [1,2,3])[:params]).to eq({betStatus: :SETTLED, betIds: ["1", "2", "3"]}) expect{subject.request(bet_ids: [1,2,3], group_by: 'asdf')[:params]}.to raise_error(ArgumentError) expect(subject.request(bet_ids: [1,2,3], group_by: 'EVENT_TYPE')[:params]).to eq({betStatus: :SETTLED, betIds: ["1", "2", "3"], groupBy: 'EVENT_TYPE'}) expect(subject.request(bet_ids: [1,2,3], group_by: :EVENT_TYPE)[:params]).to eq({betStatus: :SETTLED, betIds: ["1", "2", "3"], groupBy: 'EVENT_TYPE'}) end end end end
41.947368
473
0.654956
38070dda61a32688a462705f2af2f99c6644a1d7
1,267
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'coloral/version' Gem::Specification.new do |spec| spec.name = "coloral" spec.version = Coloral::VERSION spec.authors = ["Patrick Metcalfe"] spec.email = ["[email protected]"] spec.summary = "The best way to create, convert, or manipulate colors in Ruby using helpful color functions." spec.description = "A library to manipulate colors. If you have ever worked with colors before in Sass or a photo-editing program then you'll fit right in! RGB, HSV, HSL, and Hex are all supported with more on the way and you can manipulate colors' alpha, saturation, brightness, hue, etc. in an easy and intuitive way." spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.required_ruby_version = '~> 2.0' spec.add_development_dependency "bundler", ">= 1.6.2" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec" end
46.925926
324
0.681926
7a3bf2a560fa7d6dd169512cd1a27dcf40bda1b6
1,027
# # different ways to create a socket: # ctx.bind(:xreq, 'tcp://127.0.0.1:6666') # ctx.bind('xreq', 'tcp://127.0.0.1:6666') # ctx.bind(ZMQ::XREQ, 'tcp://127.0.0.1:6666') # module EventMachine module ZeroMQ class Context def initialize(threads_or_context) if threads_or_context.is_a?(ZMQ::Context) @context = threads_or_context else @context = ZMQ::Context.new(threads_or_context) end end ## # Create a socket in this context. # # @param [Integer] socket_type One of ZMQ::REQ, ZMQ::REP, ZMQ::PULL, ZMQ::PUSH, # ZMQ::ROUTER, ZMQ::DEALER # # def socket(socket_type) zmq_socket = @context.socket(socket_type) fd = [] if zmq_socket.getsockopt(ZMQ::FD, fd) < 0 raise "Unable to get socket FD: #{ZMQ::Util.error_string}" end EM.watch(fd[0], EventMachine::ZeroMQ::Socket, zmq_socket, socket_type) end end end end
24.452381
85
0.564752
f700dfe19d607846af1cb0892d50f94c497c4530
6,139
# Copyright 2012 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'spec_helper' require 'google/api_client' fixtures_path = File.expand_path('../../../fixtures', __FILE__) describe Google::APIClient::KeyUtils do it 'should read PKCS12 files from the filesystem' do if RUBY_PLATFORM == 'java' && RUBY_VERSION.start_with?('1.8') pending "Reading from PKCS12 not supported on jruby 1.8.x" end path = File.expand_path('files/privatekey.p12', fixtures_path) key = Google::APIClient::KeyUtils.load_from_pkcs12(path, 'notasecret') expect(key).not_to eq(nil) end it 'should read PKCS12 files from loaded files' do if RUBY_PLATFORM == 'java' && RUBY_VERSION.start_with?('1.8') pending "Reading from PKCS12 not supported on jruby 1.8.x" end path = File.expand_path('files/privatekey.p12', fixtures_path) content = File.read(path) key = Google::APIClient::KeyUtils.load_from_pkcs12(content, 'notasecret') expect(key).not_to eq(nil) end it 'should read PEM files from the filesystem' do path = File.expand_path('files/secret.pem', fixtures_path) key = Google::APIClient::KeyUtils.load_from_pem(path, 'notasecret') expect(key).not_to eq(nil) end it 'should read PEM files from loaded files' do path = File.expand_path('files/secret.pem', fixtures_path) content = File.read(path) key = Google::APIClient::KeyUtils.load_from_pem(content, 'notasecret') expect(key).not_to eq(nil) end end describe Google::APIClient::JWTAsserter do include ConnectionHelpers before do @key = OpenSSL::PKey::RSA.new 2048 end it 'should generate valid JWTs' do asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key) jwt = asserter.to_authorization.to_jwt expect(jwt).not_to eq(nil) claim = JWT.decode(jwt, @key.public_key, true) claim = claim[0] if claim[0] expect(claim["iss"]).to eq('client1') expect(claim["scope"]).to eq('scope1 scope2') end it 'should allow impersonation' do conn = stub_connection do |stub| stub.post('/o/oauth2/token') do |env| params = Addressable::URI.form_unencode(env[:body]) JWT.decode(params.assoc("assertion").last, @key.public_key) expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer']) [200, {}, '{ "access_token" : "1/abcdef1234567890", "token_type" : "Bearer", "expires_in" : 3600 }'] end end asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key) auth = asserter.authorize('[email protected]', { :connection => conn }) expect(auth).not_to eq(nil?) expect(auth.person).to eq('[email protected]') conn.verify end it 'should send valid access token request' do conn = stub_connection do |stub| stub.post('/o/oauth2/token') do |env| params = Addressable::URI.form_unencode(env[:body]) JWT.decode(params.assoc("assertion").last, @key.public_key) expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer']) [200, {}, '{ "access_token" : "1/abcdef1234567890", "token_type" : "Bearer", "expires_in" : 3600 }'] end end asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key) auth = asserter.authorize(nil, { :connection => conn }) expect(auth).not_to eq(nil?) expect(auth.access_token).to eq("1/abcdef1234567890") conn.verify end it 'should be refreshable' do conn = stub_connection do |stub| stub.post('/o/oauth2/token') do |env| params = Addressable::URI.form_unencode(env[:body]) JWT.decode(params.assoc("assertion").last, @key.public_key) expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer']) [200, {}, '{ "access_token" : "1/abcdef1234567890", "token_type" : "Bearer", "expires_in" : 3600 }'] end stub.post('/o/oauth2/token') do |env| params = Addressable::URI.form_unencode(env[:body]) JWT.decode(params.assoc("assertion").last, @key.public_key) expect(params.assoc("grant_type")).to eq(['grant_type','urn:ietf:params:oauth:grant-type:jwt-bearer']) [200, {}, '{ "access_token" : "1/0987654321fedcba", "token_type" : "Bearer", "expires_in" : 3600 }'] end end asserter = Google::APIClient::JWTAsserter.new('client1', 'scope1 scope2', @key) auth = asserter.authorize(nil, { :connection => conn }) expect(auth).not_to eq(nil?) expect(auth.access_token).to eq("1/abcdef1234567890") auth.fetch_access_token!(:connection => conn) expect(auth.access_token).to eq("1/0987654321fedcba") conn.verify end end describe Google::APIClient::ComputeServiceAccount do include ConnectionHelpers it 'should query metadata server' do conn = stub_connection do |stub| stub.get('/computeMetadata/v1beta1/instance/service-accounts/default/token') do |env| expect(env.url.host).to eq('metadata') [200, {}, '{ "access_token" : "1/abcdef1234567890", "token_type" : "Bearer", "expires_in" : 3600 }'] end end service_account = Google::APIClient::ComputeServiceAccount.new auth = service_account.fetch_access_token!({ :connection => conn }) expect(auth).not_to eq(nil?) expect(auth["access_token"]).to eq("1/abcdef1234567890") conn.verify end end
36.111765
110
0.660694
2824d825c35c143d162e7dbb172524c9bba58c45
2,097
require 'handlebars_assets' require 'handlebars_assets/config' require 'handlebars_assets/tilt_handlebars' require 'handlebars_assets/handlebars' require 'test/unit' module SprocketsScope # Try to act like sprockets. def make_scope(root, file) Class.new do define_method(:logical_path) { pathname.to_s.gsub(root + '/', '').gsub(/\..*/, '') } define_method(:pathname) { Pathname.new(root) + file } define_method(:root_path) { root } end.new end end module CompilerSupport include HandlebarsAssets::Unindent def compile_hbs(source) compiler_src = Pathname(HandlebarsAssets::Config.compiler_path).join(HandlebarsAssets::Config.compiler).read ExecJS.compile(compiler_src).call('Handlebars.precompile', source, HandlebarsAssets::Config.options) end def hbs_compiled(template_name, source) compiled_hbs = compile_hbs(source) template_namespace = HandlebarsAssets::Config.template_namespace unindent <<-END_EXPECTED (function() { this.#{template_namespace} || (this.#{template_namespace} = {}); this.#{template_namespace}[#{template_name.dump}] = Handlebars.template(#{compiled_hbs}); return this.#{template_namespace}[#{template_name.dump}]; }).call(this); END_EXPECTED end def hbs_compiled_partial(partial_name, source) compiled_hbs = compile_hbs(source) unindent <<-END_EXPECTED (function() { Handlebars.registerPartial(#{partial_name.dump}, Handlebars.template(#{compiled_hbs})); }).call(this); END_EXPECTED end end module HandlebarsAssets module Config extend self def reset! @compiler = nil @compiler_path = nil @haml_options = nil @known_helpers = nil @known_helpers_only = nil @options = nil @patch_files = nil @patch_path = nil @path_prefix = nil @template_namespace = nil @ember = nil end end class Handlebars def self.reset! @context = nil @source = nil @patch_path = nil @path = nil @assets_path = nil end end end
24.670588
112
0.679065
1dc378126481a1ddcd543d46583d84f15434aaf3
132
require 'rails_helper' RSpec.describe LmsInstance, :type => :model do pending "add some examples to (or delete) #{__FILE__}" end
22
56
0.734848
21ef8a794c2eaef2c8a409f27ac61dd37b88a46b
1,233
# frozen_string_literal: true class UnconfirmableUser include Mongoid::Document include Mongoid::Timestamps include Mongoid::Locker field :locker_locked_at, type: Time field :locker_locked_until, type: Time locker locked_at_field: :locker_locked_at, locked_until_field: :locker_locked_until ## User Info field :name, type: String field :nickname, type: String field :image, type: String ## Database authenticatable field :email, type: String, default: '' field :encrypted_password, type: String, default: '' ## Recoverable field :reset_password_token, type: String field :reset_password_sent_at, type: Time field :reset_password_redirect_url, type: String field :allow_password_change, type: Boolean, default: false ## Rememberable field :remember_created_at, type: Time ## Required field :provider, type: String field :uid, type: String, default: '' ## Tokens field :tokens, type: Hash, default: {} # Include default devise modules. devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable include DeviseJwtAuth::Concerns::User end
27.4
67
0.706407
f8d913a2b0d54e7a8ae74d7e1b58b3ce51ea7b97
1,666
NULL = nil module Ragweed; end module Ragweed::Wraptux;end module Ragweed::Wraptux::Ptrace TRACE_ME = 0 PEEK_TEXT = 1 PEEK_DATA = 2 PEEK_USER = 3 POKE_TEXT = 4 POKE_DATA = 5 POKE_USER = 6 CONTINUE = 7 KILL = 8 STEP = 9 GETREGS = 12 SETREGS = 13 ATTACH = 16 DETACH = 17 SYSCALL = 24 SETOPTIONS = 0x4200 GETEVENTMSG = 0x4201 GETSIGINFO = 0x4202 SETSIGINFO = 0x4203 end module Ragweed::Wraptux::Ptrace::SetOptions TRACESYSGOOD = 0x00000001 TRACEFORK = 0x00000002 TRACEVFORK = 0x00000004 TRACECLONE = 0x00000008 TRACEEXEC = 0x00000010 TRACEVFORKDONE = 0x00000020 TRACEEXIT = 0x00000040 MASK = 0x0000007f end module Ragweed::Wraptux::Ptrace::EventCodes FORK = 1 VFORK = 2 CLONE = 3 EXEC = 4 VFORK_DONE = 5 EXIT = 6 end # @deprecated Use ::Signal module Ragweed::Wraptux::Signal SIGHUP = 1 SIGINT = 2 SIGQUIT = 3 SIGILL = 4 SIGTRAP = 5 SIGABRT = 6 SIGIOT = 6 SIGBUS = 7 SIGFPE = 8 SIGKILL = 9 SIGUSR1 = 10 SIGSEGV = 11 SIGUSR2 = 12 SIGPIPE = 13 SIGALRM = 14 SIGTERM = 15 SIGSTKFLT = 16 SIGCHLD = 17 SIGCONT = 18 SIGSTOP = 19 SIGTSTP = 20 SIGTTIN = 21 SIGTTOU = 22 SIGURG = 23 SIGXCPU = 24 SIGXFSZ = 25 SIGVTALRM = 26 SIGPROF = 27 SIGWINCH = 28 SIGIO = 29 SIGPOLL = SIGIO #SIGLOST = 29 SIGPWR = 30 SIGSYS = 31 SIGUNUSED = 31 end module Ragweed::Wraptux::Wait NOHANG = 1 UNTRACED = 2 EXITED = 4 STOPPED = 8 CONTINUED = 10 NOWWAIT = 20 end module Ragweed::Wraptux::PagePermissions PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PROT_EXEC = 0x4 PROT_GROWSDOWN = 0x01000000 PROT_GROWSUP = 0x02000000 end
16.174757
43
0.664466
26b23787dd1a883ba66467890581a4d9c17f3ce5
26,516
module Sass module Selector # An operator-separated sequence of # {SimpleSequence simple selector sequences}. class Sequence < AbstractSequence # Sets the line of the Sass template on which this selector was declared. # This also sets the line for all child selectors. # # @param line [Fixnum] # @return [Fixnum] def line=(line) members.each {|m| m.line = line if m.is_a?(SimpleSequence)} @line = line end # Sets the name of the file in which this selector was declared, # or `nil` if it was not declared in a file (e.g. on stdin). # This also sets the filename for all child selectors. # # @param filename [String, nil] # @return [String, nil] def filename=(filename) members.each {|m| m.filename = filename if m.is_a?(SimpleSequence)} filename end # The array of {SimpleSequence simple selector sequences}, operators, and # newlines. The operators are strings such as `"+"` and `">"` representing # the corresponding CSS operators, or interpolated SassScript. Newlines # are also newline strings; these aren't semantically relevant, but they # do affect formatting. # # @return [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>] attr_reader :members # @param seqs_and_ops [Array<SimpleSequence, String|Array<Sass::Tree::Node, String>>] # See \{#members} def initialize(seqs_and_ops) @members = seqs_and_ops end # Resolves the {Parent} selectors within this selector # by replacing them with the given parent selector, # handling commas appropriately. # # @param super_cseq [CommaSequence] The parent selector # @param implicit_parent [Boolean] Whether the the parent # selector should automatically be prepended to the resolved # selector if it contains no parent refs. # @return [CommaSequence] This selector, with parent references resolved # @raise [Sass::SyntaxError] If a parent selector is invalid def resolve_parent_refs(super_cseq, implicit_parent) members = @members.dup nl = (members.first == "\n" && members.shift) contains_parent_ref = contains_parent_ref? return CommaSequence.new([self]) if !implicit_parent && !contains_parent_ref unless contains_parent_ref old_members, members = members, [] members << nl if nl members << SimpleSequence.new([Parent.new], false) members += old_members end CommaSequence.new(Sass::Util.paths(members.map do |sseq_or_op| next [sseq_or_op] unless sseq_or_op.is_a?(SimpleSequence) sseq_or_op.resolve_parent_refs(super_cseq).members end).map do |path| Sequence.new(path.map do |seq_or_op| next seq_or_op unless seq_or_op.is_a?(Sequence) seq_or_op.members end.flatten) end) end # Returns whether there's a {Parent} selector anywhere in this sequence. # # @return [Boolean] def contains_parent_ref? members.any? do |sseq_or_op| next false unless sseq_or_op.is_a?(SimpleSequence) next true if sseq_or_op.members.first.is_a?(Parent) sseq_or_op.members.any? do |sel| sel.is_a?(Pseudo) && sel.selector && sel.selector.contains_parent_ref? end end end # Non-destructively extends this selector with the extensions specified in a hash # (which should come from {Sass::Tree::Visitors::Cssize}). # # @param extends [Sass::Util::SubsetMap{Selector::Simple => # Sass::Tree::Visitors::Cssize::Extend}] # The extensions to perform on this selector # @param parent_directives [Array<Sass::Tree::DirectiveNode>] # The directives containing this selector. # @param replace [Boolean] # Whether to replace the original selector entirely or include # it in the result. # @param seen [Set<Array<Selector::Simple>>] # The set of simple sequences that are currently being replaced. # @param original [Boolean] # Whether this is the original selector being extended, as opposed to # the result of a previous extension that's being re-extended. # @return [Array<Sequence>] A list of selectors generated # by extending this selector with `extends`. # These correspond to a {CommaSequence}'s {CommaSequence#members members array}. # @see CommaSequence#do_extend def do_extend(extends, parent_directives, replace, seen, original) extended_not_expanded = members.map do |sseq_or_op| next [[sseq_or_op]] unless sseq_or_op.is_a?(SimpleSequence) extended = sseq_or_op.do_extend(extends, parent_directives, replace, seen) # The First Law of Extend says that the generated selector should have # specificity greater than or equal to that of the original selector. # In order to ensure that, we record the original selector's # (`extended.first`) original specificity. extended.first.add_sources!([self]) if original && !has_placeholder? extended.map {|seq| seq.members} end weaves = Sass::Util.paths(extended_not_expanded).map {|path| weave(path)} trim(weaves).map {|p| Sequence.new(p)} end # Unifies this with another selector sequence to produce a selector # that matches (a subset of) the intersection of the two inputs. # # @param other [Sequence] # @return [CommaSequence, nil] The unified selector, or nil if unification failed. # @raise [Sass::SyntaxError] If this selector cannot be unified. # This will only ever occur when a dynamic selector, # such as {Parent} or {Interpolation}, is used in unification. # Since these selectors should be resolved # by the time extension and unification happen, # this exception will only ever be raised as a result of programmer error def unify(other) base = members.last other_base = other.members.last return unless base.is_a?(SimpleSequence) && other_base.is_a?(SimpleSequence) return unless (unified = other_base.unify(base)) woven = weave([members[0...-1], other.members[0...-1] + [unified]]) CommaSequence.new(woven.map {|w| Sequence.new(w)}) end # Returns whether or not this selector matches all elements # that the given selector matches (as well as possibly more). # # @example # (.foo).superselector?(.foo.bar) #=> true # (.foo).superselector?(.bar) #=> false # @param cseq [Sequence] # @return [Boolean] def superselector?(seq) _superselector?(members, seq.members) end # @see AbstractSequence#to_s def to_s @members.join(" ").gsub(/ ?\n ?/, "\n") end # Returns a string representation of the sequence. # This is basically the selector string. # # @return [String] def inspect members.map {|m| m.inspect}.join(" ") end # Add to the {SimpleSequence#sources} sets of the child simple sequences. # This destructively modifies this sequence's members array, but not the # child simple sequences. # # @param sources [Set<Sequence>] def add_sources!(sources) members.map! {|m| m.is_a?(SimpleSequence) ? m.with_more_sources(sources) : m} end # Converts the subject operator "!", if it exists, into a ":has()" # selector. # # @retur [Sequence] def subjectless pre_subject = [] has = [] subject = nil members.each do |sseq_or_op| if subject has << sseq_or_op elsif sseq_or_op.is_a?(String) || !sseq_or_op.subject? pre_subject << sseq_or_op else subject = sseq_or_op.dup subject.members = sseq_or_op.members.dup subject.subject = false has = [] end end return self unless subject unless has.empty? subject.members << Pseudo.new(:class, 'has', nil, CommaSequence.new([Sequence.new(has)])) end Sequence.new(pre_subject + [subject]) end private # Conceptually, this expands "parenthesized selectors". That is, if we # have `.A .B {@extend .C}` and `.D .C {...}`, this conceptually expands # into `.D .C, .D (.A .B)`, and this function translates `.D (.A .B)` into # `.D .A .B, .A .D .B`. For thoroughness, `.A.D .B` would also be # required, but including merged selectors results in exponential output # for very little gain. # # @param path [Array<Array<SimpleSequence or String>>] # A list of parenthesized selector groups. # @return [Array<Array<SimpleSequence or String>>] A list of fully-expanded selectors. def weave(path) # This function works by moving through the selector path left-to-right, # building all possible prefixes simultaneously. prefixes = [[]] path.each do |current| next if current.empty? current = current.dup last_current = [current.pop] prefixes = prefixes.map do |prefix| sub = subweave(prefix, current) next [] unless sub sub.map {|seqs| seqs + last_current} end.flatten(1) end prefixes end # This interweaves two lists of selectors, # returning all possible orderings of them (including using unification) # that maintain the relative ordering of the input arrays. # # For example, given `.foo .bar` and `.baz .bang`, # this would return `.foo .bar .baz .bang`, `.foo .bar.baz .bang`, # `.foo .baz .bar .bang`, `.foo .baz .bar.bang`, `.foo .baz .bang .bar`, # and so on until `.baz .bang .foo .bar`. # # Semantically, for selectors A and B, this returns all selectors `AB_i` # such that the union over all i of elements matched by `AB_i X` is # identical to the intersection of all elements matched by `A X` and all # elements matched by `B X`. Some `AB_i` are elided to reduce the size of # the output. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Array<Array<SimpleSequence or String>>] def subweave(seq1, seq2) return [seq2] if seq1.empty? return [seq1] if seq2.empty? seq1, seq2 = seq1.dup, seq2.dup return unless (init = merge_initial_ops(seq1, seq2)) return unless (fin = merge_final_ops(seq1, seq2)) # Make sure there's only one root selector in the output. root1 = has_root?(seq1.first) && seq1.shift root2 = has_root?(seq2.first) && seq2.shift if root1 && root2 return unless (root = root1.unify(root2)) seq1.unshift root seq2.unshift root elsif root1 seq2.unshift root1 elsif root2 seq1.unshift root2 end seq1 = group_selectors(seq1) seq2 = group_selectors(seq2) lcs = Sass::Util.lcs(seq2, seq1) do |s1, s2| next s1 if s1 == s2 next unless s1.first.is_a?(SimpleSequence) && s2.first.is_a?(SimpleSequence) next s2 if parent_superselector?(s1, s2) next s1 if parent_superselector?(s2, s1) next unless must_unify?(s1, s2) next unless (unified = Sequence.new(s1).unify(Sequence.new(s2))) unified.members.first.members if unified.members.length == 1 end diff = [[init]] until lcs.empty? diff << chunks(seq1, seq2) {|s| parent_superselector?(s.first, lcs.first)} << [lcs.shift] seq1.shift seq2.shift end diff << chunks(seq1, seq2) {|s| s.empty?} diff += fin.map {|sel| sel.is_a?(Array) ? sel : [sel]} diff.reject! {|c| c.empty?} Sass::Util.paths(diff).map {|p| p.flatten}.reject {|p| path_has_two_subjects?(p)} end # Extracts initial selector combinators (`"+"`, `">"`, `"~"`, and `"\n"`) # from two sequences and merges them together into a single array of # selector combinators. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Array<String>, nil] If there are no operators in the merged # sequence, this will be the empty array. If the operators cannot be # merged, this will be nil. def merge_initial_ops(seq1, seq2) ops1, ops2 = [], [] ops1 << seq1.shift while seq1.first.is_a?(String) ops2 << seq2.shift while seq2.first.is_a?(String) newline = false newline ||= !!ops1.shift if ops1.first == "\n" newline ||= !!ops2.shift if ops2.first == "\n" # If neither sequence is a subsequence of the other, they cannot be # merged successfully lcs = Sass::Util.lcs(ops1, ops2) return unless lcs == ops1 || lcs == ops2 (newline ? ["\n"] : []) + (ops1.size > ops2.size ? ops1 : ops2) end # Extracts final selector combinators (`"+"`, `">"`, `"~"`) and the # selectors to which they apply from two sequences and merges them # together into a single array. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Array<SimpleSequence or String or # Array<Array<SimpleSequence or String>>] # If there are no trailing combinators to be merged, this will be the # empty array. If the trailing combinators cannot be merged, this will # be nil. Otherwise, this will contained the merged selector. Array # elements are [Sass::Util#paths]-style options; conceptually, an "or" # of multiple selectors. # @comment # rubocop:disable MethodLength def merge_final_ops(seq1, seq2, res = []) ops1, ops2 = [], [] ops1 << seq1.pop while seq1.last.is_a?(String) ops2 << seq2.pop while seq2.last.is_a?(String) # Not worth the headache of trying to preserve newlines here. The most # important use of newlines is at the beginning of the selector to wrap # across lines anyway. ops1.reject! {|o| o == "\n"} ops2.reject! {|o| o == "\n"} return res if ops1.empty? && ops2.empty? if ops1.size > 1 || ops2.size > 1 # If there are multiple operators, something hacky's going on. If one # is a supersequence of the other, use that, otherwise give up. lcs = Sass::Util.lcs(ops1, ops2) return unless lcs == ops1 || lcs == ops2 res.unshift(*(ops1.size > ops2.size ? ops1 : ops2).reverse) return res end # This code looks complicated, but it's actually just a bunch of special # cases for interactions between different combinators. op1, op2 = ops1.first, ops2.first if op1 && op2 sel1 = seq1.pop sel2 = seq2.pop if op1 == '~' && op2 == '~' if sel1.superselector?(sel2) res.unshift sel2, '~' elsif sel2.superselector?(sel1) res.unshift sel1, '~' else merged = sel1.unify(sel2) res.unshift [ [sel1, '~', sel2, '~'], [sel2, '~', sel1, '~'], ([merged, '~'] if merged) ].compact end elsif (op1 == '~' && op2 == '+') || (op1 == '+' && op2 == '~') if op1 == '~' tilde_sel, plus_sel = sel1, sel2 else tilde_sel, plus_sel = sel2, sel1 end if tilde_sel.superselector?(plus_sel) res.unshift plus_sel, '+' else merged = plus_sel.unify(tilde_sel) res.unshift [ [tilde_sel, '~', plus_sel, '+'], ([merged, '+'] if merged) ].compact end elsif op1 == '>' && %w[~ +].include?(op2) res.unshift sel2, op2 seq1.push sel1, op1 elsif op2 == '>' && %w[~ +].include?(op1) res.unshift sel1, op1 seq2.push sel2, op2 elsif op1 == op2 merged = sel1.unify(sel2) return unless merged res.unshift merged, op1 else # Unknown selector combinators can't be unified return end return merge_final_ops(seq1, seq2, res) elsif op1 seq2.pop if op1 == '>' && seq2.last && seq2.last.superselector?(seq1.last) res.unshift seq1.pop, op1 return merge_final_ops(seq1, seq2, res) else # op2 seq1.pop if op2 == '>' && seq1.last && seq1.last.superselector?(seq2.last) res.unshift seq2.pop, op2 return merge_final_ops(seq1, seq2, res) end end # @comment # rubocop:enable MethodLength # Takes initial subsequences of `seq1` and `seq2` and returns all # orderings of those subsequences. The initial subsequences are determined # by a block. # # Destructively removes the initial subsequences of `seq1` and `seq2`. # # For example, given `(A B C | D E)` and `(1 2 | 3 4 5)` (with `|` # denoting the boundary of the initial subsequence), this would return # `[(A B C 1 2), (1 2 A B C)]`. The sequences would then be `(D E)` and # `(3 4 5)`. # # @param seq1 [Array] # @param seq2 [Array] # @yield [a] Used to determine when to cut off the initial subsequences. # Called repeatedly for each sequence until it returns true. # @yieldparam a [Array] A final subsequence of one input sequence after # cutting off some initial subsequence. # @yieldreturn [Boolean] Whether or not to cut off the initial subsequence # here. # @return [Array<Array>] All possible orderings of the initial subsequences. def chunks(seq1, seq2) chunk1 = [] chunk1 << seq1.shift until yield seq1 chunk2 = [] chunk2 << seq2.shift until yield seq2 return [] if chunk1.empty? && chunk2.empty? return [chunk2] if chunk1.empty? return [chunk1] if chunk2.empty? [chunk1 + chunk2, chunk2 + chunk1] end # Groups a sequence into subsequences. The subsequences are determined by # strings; adjacent non-string elements will be put into separate groups, # but any element adjacent to a string will be grouped with that string. # # For example, `(A B "C" D E "F" G "H" "I" J)` will become `[(A) (B "C" D) # (E "F" G "H" "I" J)]`. # # @param seq [Array] # @return [Array<Array>] def group_selectors(seq) newseq = [] tail = seq.dup until tail.empty? head = [] begin head << tail.shift end while !tail.empty? && head.last.is_a?(String) || tail.first.is_a?(String) newseq << head end newseq end # Given two selector sequences, returns whether `seq1` is a # superselector of `seq2`; that is, whether `seq1` matches every # element `seq2` matches. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Boolean] def _superselector?(seq1, seq2) seq1 = seq1.reject {|e| e == "\n"} seq2 = seq2.reject {|e| e == "\n"} # Selectors with leading or trailing operators are neither # superselectors nor subselectors. return if seq1.last.is_a?(String) || seq2.last.is_a?(String) || seq1.first.is_a?(String) || seq2.first.is_a?(String) # More complex selectors are never superselectors of less complex ones return if seq1.size > seq2.size return seq1.first.superselector?(seq2.last, seq2[0...-1]) if seq1.size == 1 _, si = Sass::Util.enum_with_index(seq2).find do |e, i| return if i == seq2.size - 1 next if e.is_a?(String) seq1.first.superselector?(e, seq2[0...i]) end return unless si if seq1[1].is_a?(String) return unless seq2[si + 1].is_a?(String) # .foo ~ .bar is a superselector of .foo + .bar return unless seq1[1] == "~" ? seq2[si + 1] != ">" : seq1[1] == seq2[si + 1] # .foo > .baz is not a superselector of .foo > .bar > .baz or .foo > # .bar .baz, despite the fact that .baz is a superselector of .bar > # .baz and .bar .baz. Same goes for + and ~. return if seq1.length == 3 && seq2.length > 3 return _superselector?(seq1[2..-1], seq2[si + 2..-1]) elsif seq2[si + 1].is_a?(String) return unless seq2[si + 1] == ">" return _superselector?(seq1[1..-1], seq2[si + 2..-1]) else return _superselector?(seq1[1..-1], seq2[si + 1..-1]) end end # Like \{#_superselector?}, but compares the selectors in the # context of parent selectors, as though they shared an implicit # base simple selector. For example, `B` is not normally a # superselector of `B A`, since it doesn't match `A` elements. # However, it is a parent superselector, since `B X` is a # superselector of `B A X`. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Boolean] def parent_superselector?(seq1, seq2) base = Sass::Selector::SimpleSequence.new([Sass::Selector::Placeholder.new('<temp>')], false) _superselector?(seq1 + [base], seq2 + [base]) end # Returns whether two selectors must be unified to produce a valid # combined selector. This is true when both selectors contain the same # unique simple selector such as an id. # # @param seq1 [Array<SimpleSequence or String>] # @param seq2 [Array<SimpleSequence or String>] # @return [Boolean] def must_unify?(seq1, seq2) unique_selectors = seq1.map do |sseq| next [] if sseq.is_a?(String) sseq.members.select {|sel| sel.unique?} end.flatten.to_set return false if unique_selectors.empty? seq2.any? do |sseq| next false if sseq.is_a?(String) sseq.members.any? do |sel| next unless sel.unique? unique_selectors.include?(sel) end end end # Removes redundant selectors from between multiple lists of # selectors. This takes a list of lists of selector sequences; # each individual list is assumed to have no redundancy within # itself. A selector is only removed if it's redundant with a # selector in another list. # # "Redundant" here means that one selector is a superselector of # the other. The more specific selector is removed. # # @param seqses [Array<Array<Array<SimpleSequence or String>>>] # @return [Array<Array<SimpleSequence or String>>] def trim(seqses) # Avoid truly horrific quadratic behavior. TODO: I think there # may be a way to get perfect trimming without going quadratic. return seqses.flatten(1) if seqses.size > 100 # Keep the results in a separate array so we can be sure we aren't # comparing against an already-trimmed selector. This ensures that two # identical selectors don't mutually trim one another. result = seqses.dup # This is n^2 on the sequences, but only comparing between # separate sequences should limit the quadratic behavior. seqses.each_with_index do |seqs1, i| result[i] = seqs1.reject do |seq1| # The maximum specificity of the sources that caused [seq1] to be # generated. In order for [seq1] to be removed, there must be # another selector that's a superselector of it *and* that has # specificity greater or equal to this. max_spec = _sources(seq1).map do |seq| spec = seq.specificity spec.is_a?(Range) ? spec.max : spec end.max || 0 result.any? do |seqs2| next if seqs1.equal?(seqs2) # Second Law of Extend: the specificity of a generated selector # should never be less than the specificity of the extending # selector. # # See https://github.com/nex3/sass/issues/324. seqs2.any? do |seq2| spec2 = _specificity(seq2) spec2 = spec2.begin if spec2.is_a?(Range) spec2 >= max_spec && _superselector?(seq2, seq1) end end end end result.flatten(1) end def _hash members.reject {|m| m == "\n"}.hash end def _eql?(other) other.members.reject {|m| m == "\n"}.eql?(members.reject {|m| m == "\n"}) end private def path_has_two_subjects?(path) subject = false path.each do |sseq_or_op| next unless sseq_or_op.is_a?(SimpleSequence) next unless sseq_or_op.subject? return true if subject subject = true end false end def _sources(seq) s = Set.new seq.map {|sseq_or_op| s.merge sseq_or_op.sources if sseq_or_op.is_a?(SimpleSequence)} s end def extended_not_expanded_to_s(extended_not_expanded) extended_not_expanded.map do |choices| choices = choices.map do |sel| next sel.first.to_s if sel.size == 1 "#{sel.join ' '}" end next choices.first if choices.size == 1 && !choices.include?(' ') "(#{choices.join ', '})" end.join ' ' end def has_root?(sseq) sseq.is_a?(SimpleSequence) && sseq.members.any? {|sel| sel.is_a?(Pseudo) && sel.normalized_name == "root"} end end end end
39.933735
99
0.591228
03e4cf2b70e7b8e98298713a1252c7f9ab07c134
2,279
describe ApplicationHelper::Button::InstanceAttach do describe '#disabled?' do it "when there are available volumes, then the button is enabled" do view_context = setup_view_context_with_sandbox({}) tenant = FactoryBot.create(:cloud_tenant_openstack) volume = FactoryBot.create(:cloud_volume_openstack, :cloud_tenant => tenant, :status => 'available') record = FactoryBot.create(:vm_openstack, :cloud_tenant => tenant) button = described_class.new(view_context, {}, {"record" => record}, {}) expect(button.disabled?).to be false end it "when there are no available volumes then the button is disabled" do view_context = setup_view_context_with_sandbox({}) tenant = FactoryBot.create(:cloud_tenant_openstack) volume = FactoryBot.create(:cloud_volume_openstack, :cloud_tenant => tenant, :status => 'in-use') record = FactoryBot.create(:vm_openstack, :cloud_tenant => tenant) button = described_class.new(view_context, {}, {"record" => record}, {}) expect(button.disabled?).to be true end end describe '#calculate_properties' do it "when there are no available volumes then the button has the error in the title" do view_context = setup_view_context_with_sandbox({}) tenant = FactoryBot.create(:cloud_tenant_openstack) volume = FactoryBot.create(:cloud_volume_openstack, :cloud_tenant => tenant, :status => 'in-use') record = FactoryBot.create(:vm_openstack, :cloud_tenant => tenant) button = described_class.new(view_context, {}, {"record" => record}, {}) button.calculate_properties expect(button[:title]).to eq("There are no Cloud Volumes available to attach to this Instance.") end it "when there are available volumes, the button has no error in the title" do view_context = setup_view_context_with_sandbox({}) tenant = FactoryBot.create(:cloud_tenant_openstack) volume = FactoryBot.create(:cloud_volume_openstack, :cloud_tenant => tenant, :status => 'available') record = FactoryBot.create(:vm_openstack, :cloud_tenant => tenant) button = described_class.new(view_context, {}, {"record" => record}, {}) button.calculate_properties expect(button[:title]).to be nil end end end
50.644444
106
0.706889
18ce52871007d56bf4a0d07fd5d2d105869e2e15
358
# encoding: utf-8 # frozen_string_literal: true class String #:nodoc: unless method_defined?(:ascii_only?) # Backport from Ruby 1.9 checks for non-us-ascii characters. def ascii_only? self !~ MATCH_NON_US_ASCII end MATCH_NON_US_ASCII = /[^\x00-\x7f]/ end unless method_defined?(:bytesize) alias :bytesize :length end end
19.888889
64
0.692737
39611a9dfdb0e2aa5bde681cb40bbd2aa8921a9d
7,832
# # Cookbook Name:: networking # Recipe:: default # # Copyright 2010, OpenStreetMap Foundation. # Copyright 2009, Opscode, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # = Requires # * node[:networking][:nameservers] require "ipaddr" node[:networking][:interfaces].each do |name, interface| if interface[:role] && (role = node[:networking][:roles][interface[:role]]) if role[interface[:family]] node.set[:networking][:interfaces][name][:prefix] = role[interface[:family]][:prefix] node.set[:networking][:interfaces][name][:gateway] = role[interface[:family]][:gateway] end node.set[:networking][:interfaces][name][:metric] = role[:metric] node.set[:networking][:interfaces][name][:zone] = role[:zone] end prefix = node[:networking][:interfaces][name][:prefix] # rubocop:disable Style/RedundantParentheses node.set[:networking][:interfaces][name][:netmask] = (~IPAddr.new(interface[:address]).mask(0)).mask(prefix) node.set[:networking][:interfaces][name][:network] = IPAddr.new(interface[:address]).mask(prefix) # rubocop:enable Style/RedundantParentheses end template "/etc/network/interfaces" do source "interfaces.erb" owner "root" group "root" mode 0644 end execute "hostname" do action :nothing command "/bin/hostname -F /etc/hostname" end template "/etc/hostname" do source "hostname.erb" owner "root" group "root" mode 0644 notifies :run, "execute[hostname]" end template "/etc/hosts" do source "hosts.erb" owner "root" group "root" mode 0644 end link "/etc/resolv.conf" do action :delete link_type :symbolic to "/run/resolvconf/resolv.conf" only_if { File.symlink?("/etc/resolv.conf") } end template "/etc/resolv.conf" do source "resolv.conf.erb" owner "root" group "root" mode 0644 end node.interfaces(:role => :internal) do |interface| if interface[:gateway] && interface[:gateway] != interface[:address] search(:node, "networking_interfaces*address:#{interface[:gateway]}") do |gateway| next unless gateway[:openvpn] gateway[:openvpn][:tunnels].each_value do |tunnel| if tunnel[:peer][:address] # ~FC023 route tunnel[:peer][:address] do netmask "255.255.255.255" gateway interface[:gateway] device interface[:interface] end end next unless tunnel[:peer][:networks] tunnel[:peer][:networks].each do |network| route network[:address] do netmask network[:netmask] gateway interface[:gateway] device interface[:interface] end end end end end end zones = {} search(:node, "networking:interfaces").collect do |n| next if n[:fqdn] == node[:fqdn] n.interfaces.each do |interface| next unless interface[:role] == "external" && interface[:zone] zones[interface[:zone]] ||= {} zones[interface[:zone]][interface[:family]] ||= [] zones[interface[:zone]][interface[:family]] << interface[:address] end end package "shorewall" service "shorewall" do action [:enable, :start] supports :restart => true status_command "shorewall status" end template "/etc/default/shorewall" do source "shorewall-default.erb" owner "root" group "root" mode 0644 notifies :restart, "service[shorewall]" end template "/etc/shorewall/shorewall.conf" do source "shorewall.conf.erb" owner "root" group "root" mode 0644 notifies :restart, "service[shorewall]" end template "/etc/shorewall/zones" do source "shorewall-zones.erb" owner "root" group "root" mode 0644 variables :type => "ipv4" notifies :restart, "service[shorewall]" end template "/etc/shorewall/interfaces" do source "shorewall-interfaces.erb" owner "root" group "root" mode 0644 notifies :restart, "service[shorewall]" end template "/etc/shorewall/hosts" do source "shorewall-hosts.erb" owner "root" group "root" mode 0644 variables :zones => zones notifies :restart, "service[shorewall]" end template "/etc/shorewall/policy" do source "shorewall-policy.erb" owner "root" group "root" mode 0644 notifies :restart, "service[shorewall]" end template "/etc/shorewall/rules" do source "shorewall-rules.erb" owner "root" group "root" mode 0644 variables :rules => [] notifies :restart, "service[shorewall]" end template "/etc/logrotate.d/shorewall" do source "logrotate.shorewall.erb" owner "root" group "root" mode 0644 variables :name => "shorewall" end firewall_rule "limit-icmp-echo" do action :accept family :inet source "net" dest "fw" proto "icmp" dest_ports "echo-request" rate_limit "s:1/sec:5" end %w(ucl ic bm).each do |zone| firewall_rule "accept-openvpn-#{zone}" do action :accept family :inet source zone dest "fw" proto "udp" dest_ports "1194:1196" source_ports "1194:1196" end end if node[:roles].include?("gateway") template "/etc/shorewall/masq" do source "shorewall-masq.erb" owner "root" group "root" mode 0644 notifies :restart, "service[shorewall]" end else file "/etc/shorewall/masq" do action :delete notifies :restart, "service[shorewall]" end end unless node.interfaces(:family => :inet6).empty? package "shorewall6" service "shorewall6" do action [:enable, :start] supports :restart => true status_command "shorewall6 status" end template "/etc/default/shorewall6" do source "shorewall-default.erb" owner "root" group "root" mode 0644 notifies :restart, "service[shorewall6]" end template "/etc/shorewall6/shorewall6.conf" do source "shorewall6.conf.erb" owner "root" group "root" mode 0644 notifies :restart, "service[shorewall6]" end template "/etc/shorewall6/zones" do source "shorewall-zones.erb" owner "root" group "root" mode 0644 variables :type => "ipv6" notifies :restart, "service[shorewall6]" end template "/etc/shorewall6/interfaces" do source "shorewall6-interfaces.erb" owner "root" group "root" mode 0644 notifies :restart, "service[shorewall6]" end template "/etc/shorewall6/hosts" do source "shorewall6-hosts.erb" owner "root" group "root" mode 0644 variables :zones => zones notifies :restart, "service[shorewall6]" end template "/etc/shorewall6/policy" do source "shorewall-policy.erb" owner "root" group "root" mode 0644 notifies :restart, "service[shorewall6]" end template "/etc/shorewall6/rules" do source "shorewall-rules.erb" owner "root" group "root" mode 0644 variables :rules => [] notifies :restart, "service[shorewall6]" end template "/etc/logrotate.d/shorewall6" do source "logrotate.shorewall.erb" owner "root" group "root" mode 0644 variables :name => "shorewall6" end firewall_rule "limit-icmp6-echo" do action :accept family :inet6 source "net" dest "fw" proto "ipv6-icmp" dest_ports "echo-request" rate_limit "s:1/sec:5" end end firewall_rule "accept-http" do action :accept source "net" dest "fw" proto "tcp:syn" dest_ports "http" end firewall_rule "accept-https" do action :accept source "net" dest "fw" proto "tcp:syn" dest_ports "https" end
22.967742
110
0.675689
21dbe7f33d9ee63cd16bbc6e40ff05e79a378a81
2,272
require "test_helper" require "fluent/plugin/out_remote_syslog" class RemoteSyslogOutputTest < Test::Unit::TestCase def setup Fluent::Test.setup end def create_driver(conf = CONFIG) Fluent::Test::Driver::Output.new(Fluent::RemoteSyslogOutput).configure(conf) end def test_configure d = create_driver %[ @type remote_syslog hostname foo.com host example.com port 5566 severity debug program minitest ] loggers = d.instance.instance_variable_get(:@senders) assert_equal loggers, [] assert_equal "example.com", d.instance.instance_variable_get(:@host) assert_equal 5566, d.instance.instance_variable_get(:@port) assert_equal "debug", d.instance.instance_variable_get(:@severity) end def test_write d = create_driver %[ @type remote_syslog hostname foo.com host example.com port 5566 severity debug program minitest <format> @type single_value message_key message </format> ] mock.proxy(RemoteSyslogSender::UdpSender).new("example.com", 5566, whinyerrors: true, program: "minitest") do |sender| mock.proxy(sender).transmit("foo", facility: "user", severity: "debug", program: "minitest", hostname: "foo.com") end d.run do d.feed("tag", Fluent::EventTime.now, {"message" => "foo"}) end end def test_write_tcp d = create_driver %[ @type remote_syslog hostname foo.com host example.com port 5566 severity debug program minitest protocol tcp <format> @type single_value message_key message </format> ] any_instance_of(RemoteSyslogSender::TcpSender) do |klass| mock(klass).connect end mock.proxy(RemoteSyslogSender::TcpSender).new("example.com", 5566, tls: false, whinyerrors: true, program: "minitest", packet_size: 1024, timeout: nil, timeout_exception: false, keep_alive: false, keep_alive_cnt: nil, keep_alive_idle: nil, keep_alive_intvl: nil) do |sender| mock(sender).transmit("foo", facility: "user", severity: "debug", program: "minitest", hostname: "foo.com") end d.run do d.feed("tag", Fluent::EventTime.now, {"message" => "foo"}) end end end
26.729412
278
0.664613
2622a68e458871f90b6d99168cc0bded47441c06
585
module HealthDataStandards class Facility include Mongoid::Document include Mongoid::Attributes::Dynamic store_in collection: 'facilities' field :name, type: String field :code, type: Hash field :start_time, type: Integer field :end_time, type: Integer embeds_many :addresses, as: :locatable embeds_many :telecoms, as: :contactable def shift_dates(date_diff) self.start_time = (self.start_time.nil?) ? nil : self.start_time + date_diff self.end_time = (self.end_time.nil?) ? nil : self.end_time + date_diff end end end
25.434783
82
0.697436
ac1f2d7bcce431d170cb3d7dac54f5d87485cf16
8,303
require 'date' module Phrase class MemberUpdateParameters # Update strategy, can be any of set, add, remove. If provided, it will set, add or remove given spaces, projects and locale ids from users access list. attr_accessor :strategy # Member role, can be any of of Admin, ProjectManager, Developer, Designer, Translator attr_accessor :role # List of project ids the user has access to. attr_accessor :project_ids # List of locale ids the user has access to. attr_accessor :locale_ids # List of default locales for the user. attr_accessor :default_locale_codes # List of spaces the user is assigned to. attr_accessor :space_ids # Additional permissions depending on member role. Available permissions are <code>create_upload</code> and <code>review_translations</code> attr_accessor :permissions # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'strategy' => :'strategy', :'role' => :'role', :'project_ids' => :'project_ids', :'locale_ids' => :'locale_ids', :'default_locale_codes' => :'default_locale_codes', :'space_ids' => :'space_ids', :'permissions' => :'permissions' } end # Attribute type mapping. def self.openapi_types { :'strategy' => :'String', :'role' => :'String', :'project_ids' => :'String', :'locale_ids' => :'String', :'default_locale_codes' => :'Array<String>', :'space_ids' => :'Array<String>', :'permissions' => :'Hash<String, 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 `Phrase::MemberUpdateParameters` 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 `Phrase::MemberUpdateParameters`. 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?(:'strategy') self.strategy = attributes[:'strategy'] end if attributes.key?(:'role') self.role = attributes[:'role'] end if attributes.key?(:'project_ids') self.project_ids = attributes[:'project_ids'] end if attributes.key?(:'locale_ids') self.locale_ids = attributes[:'locale_ids'] end if attributes.key?(:'default_locale_codes') if (value = attributes[:'default_locale_codes']).is_a?(Array) self.default_locale_codes = value end end if attributes.key?(:'space_ids') if (value = attributes[:'space_ids']).is_a?(Array) self.space_ids = value end end if attributes.key?(:'permissions') if (value = attributes[:'permissions']).is_a?(Hash) self.permissions = value end end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && strategy == o.strategy && role == o.role && project_ids == o.project_ids && locale_ids == o.locale_ids && default_locale_codes == o.default_locale_codes && space_ids == o.space_ids && permissions == o.permissions 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 [strategy, role, project_ids, locale_ids, default_locale_codes, space_ids, permissions].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) 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 Phrase.const_get(type).build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = self.class.openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
31.69084
208
0.618572
3992506c738aeb528f637ac969cd989e69c14298
120
class Empresa < Organizacao def nome_do_tipo "Empresa" end def nome_da_classe "empresa" end end
10.909091
29
0.65
e9c8ea974c64a57b6ad67d7a9205a48952e28b6e
131
FactoryBot.define do factory :element do tag { "para" } content { "Hello world!" } identifier { "ch01_1" } end end
16.375
30
0.610687
38f30b1b5054016980eed346cd758d777cd755f8
628
cask "epic" do arch = Hardware::CPU.intel? ? "mac" : "macarm" version "91.0.4472.114" if Hardware::CPU.intel? sha256 "52f388b4da04a26a7c5c732eaf8688e0f2bd0a6c34cd10dffe781d38ae974053" else sha256 "79951fee34ba9b9bffea5e03b8217776467e65a737d2054ae38b4f76114acb71" end url "https://cdn.epicbrowser.com/v#{version.major}/#{arch}/epic_#{version}.dmg" name "Epic Privacy Browser" desc "Private, secure web browser" homepage "https://www.epicbrowser.com/" livecheck do url "https://epicbrowser.com/thank_you.php" regex(%r{href=.*?/epic[._-]v?(\d+(?:\.\d+)+)\.dmg}i) end app "Epic.app" end
26.166667
81
0.700637
e9b417d6b8a1f1558305758c0f347e84798f53f0
3,949
# frozen_string_literal: true module Alchemy module JsonApi class PagesController < JsonApi::BaseController before_action :load_page_for_cache_key, only: :show def index allowed = [:page_layout, :urlname] jsonapi_filter(page_scope, allowed) do |filtered_pages| @pages = filtered_pages.result if [email protected]?(&:cache_page?) render_pages_json(allowed) && return elsif stale?(last_modified: @pages.maximum(:published_at), etag: @pages.max_by(&:cache_key)&.cache_key) render_pages_json(allowed) end end expires_in cache_duration, { public: @pages.none?(&:restricted?) }.merge(caching_options) end def show if [email protected]_page? render(jsonapi: api_page(load_page)) && return end if stale?(last_modified: last_modified_for(@page), etag: @page.cache_key) # Only load page with all includes when browser cache is stale render jsonapi: api_page(load_page) end expires_in cache_duration, { public: [email protected]? }.merge(caching_options) end private def render_pages_json(allowed) # Only load pages with all includes when browser cache is stale jsonapi_filter(page_scope_with_includes, allowed) do |filtered| # decorate with our page model that has a eager loaded elements collection filtered_pages = filtered.result.map { |page| api_page(page) } jsonapi_paginate(filtered_pages) do |paginated| render jsonapi: paginated end end end def cache_duration ENV.fetch("ALCHEMY_JSON_API_CACHE_DURATION", 3).to_i.hours end def caching_options { must_revalidate: true } end # Get page w/o includes to get cache key def load_page_for_cache_key @page = page_scope.where(id: params[:path]). or(page_scope.where(urlname: params[:path])).first! end def last_modified_for(page) page.published_at end def jsonapi_meta(pages) pagination = jsonapi_pagination_meta(pages) { pagination: pagination.presence, total: page_scope.count, }.compact end def load_page @page = load_page_by_id || load_page_by_urlname || raise(ActiveRecord::RecordNotFound) end def load_page_by_id return unless params[:path] =~ /\A\d+\z/ page_scope_with_includes.find_by(id: params[:path]) end def load_page_by_urlname page_scope_with_includes.find_by(urlname: params[:path]) end def page_scope base_page_scope.contentpages end def page_scope_with_includes page_scope. includes( [ :legacy_urls, { language: { nodes: [:parent, :children, { page: { language: { site: :languages } } }] } }, { page_version_type => { elements: [ :nested_elements, { contents: { essence: :ingredient_association } }, { ingredients: :related_object }, ], }, }, ] ) end def page_version_type :public_version end def api_page(page) Alchemy::JsonApi::Page.new(page, page_version_type: page_version_type) end def base_page_scope # cancancan is not able to merge our complex AR scopes for logged in users if can?(:edit_content, ::Alchemy::Page) Alchemy::Language.current.pages.joins(page_version_type) else Alchemy::Language.current.pages.published.joins(page_version_type) end end def jsonapi_serializer_class(_resource, _is_collection) ::Alchemy::JsonApi::PageSerializer end end end end
29.251852
113
0.605217
edcb99c89d87bdfecabc56bbe36ab4636ebdcd0b
1,711
class UniversalCtags < Formula desc "Maintained ctags implementation" homepage "https://github.com/universal-ctags/ctags" url "https://github.com/universal-ctags/ctags/archive/refs/tags/p5.9.20210620.0.tar.gz" version "p5.9.20210620.0" sha256 "2506c01cf02cfe50c97bd41bb5aa4056884cc0ad927ba41333be4738c0052c2d" license "GPL-2.0-only" head "https://github.com/universal-ctags/ctags.git" livecheck do url :stable regex(/^(p\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any, arm64_big_sur: "5632da55343589f261b5bd82581009a54d5a8e53a44c689f1a02f87a3c2251be" sha256 cellar: :any, big_sur: "7b1c55a1b6c7d08c0b965f3c87d12027e8bfb1905f18f3e00ceb53c025cabef6" sha256 cellar: :any, catalina: "b377c06540006c2abea0cea609adee1c5208ec9df29261e910d93ef2707346c6" sha256 cellar: :any, mojave: "8f96d9c527d3a76afae3c08f7da8fb30e7daea27789b270827af0e96f98cd955" end depends_on "autoconf" => :build depends_on "automake" => :build depends_on "docutils" => :build depends_on "pkg-config" => :build depends_on "jansson" depends_on "libyaml" uses_from_macos "libxml2" conflicts_with "ctags", because: "this formula installs the same executable as the ctags formula" def install system "./autogen.sh" system "./configure", *std_configure_args system "make" system "make", "install" end test do (testpath/"test.c").write <<~EOS #include <stdio.h> #include <stdlib.h> void func() { printf("Hello World!"); } int main() { func(); return 0; } EOS system bin/"ctags", "-R", "." assert_match(/func.*test\.c/, File.read("tags")) end end
28.516667
106
0.686733
1a5d8efe61645cea2f3dd8076aca4cfd44dcc7f2
379
class Simulation < ActiveRecord::Base has_paper_trail belongs_to :user belongs_to :farm belongs_to :weather belongs_to :soil validates_presence_of :name, :start_on, :end_on validates_presence_of :farm_id, message: "must be selected" validates_presence_of :weather_id, message: "must be selected" validates_presence_of :soil_id, message: "must be selected" end
31.583333
64
0.783641
7958ad7e24fe921a36e10812d407d2fe1b9c8419
31,525
require 'spec_helper' describe 'Filter issues', js: true, feature: true do include Devise::Test::IntegrationHelpers include FilteredSearchHelpers let!(:group) { create(:group) } let!(:project) { create(:project, group: group) } let!(:user) { create(:user, username: 'joe') } let!(:user2) { create(:user, username: 'jane') } let!(:label) { create(:label, project: project) } let!(:wontfix) { create(:label, project: project, title: "Won't fix") } let!(:bug_label) { create(:label, project: project, title: 'bug') } let!(:caps_sensitive_label) { create(:label, project: project, title: 'CaPs') } let!(:milestone) { create(:milestone, title: "8", project: project, start_date: 2.days.ago) } let!(:multiple_words_label) { create(:label, project: project, title: "Two words") } let!(:closed_issue) { create(:issue, title: 'bug that is closed', project: project, state: :closed) } def expect_no_issues_list page.within '.issues-list' do expect(page).not_to have_selector('.issue') end end def expect_issues_list_count(open_count, closed_count = 0) all_count = open_count + closed_count expect(page).to have_issuable_counts(open: open_count, closed: closed_count, all: all_count) page.within '.issues-list' do expect(page).to have_selector('.issue', count: open_count) end end def select_search_at_index(pos) evaluate_script("el = document.querySelector('.filtered-search'); el.focus(); el.setSelectionRange(#{pos}, #{pos});") end before do project.team << [user, :master] project.team << [user2, :master] group.add_developer(user) group.add_developer(user2) sign_in(user) create(:issue, project: project) create(:issue, project: project, title: "Bug report 1") create(:issue, project: project, title: "Bug report 2") create(:issue, project: project, title: "issue with 'single quotes'") create(:issue, project: project, title: "issue with \"double quotes\"") create(:issue, project: project, title: "issue with !@\#{$%^&*()-+") create(:issue, project: project, title: "issue by assignee", milestone: milestone, author: user, assignees: [user]) create(:issue, project: project, title: "issue by assignee with searchTerm", milestone: milestone, author: user, assignees: [user]) issue = create(:issue, title: "Bug 2", project: project, milestone: milestone, author: user, assignees: [user]) issue.labels << bug_label issue_with_caps_label = create(:issue, title: "issue by assignee with searchTerm and label", project: project, milestone: milestone, author: user, assignees: [user]) issue_with_caps_label.labels << caps_sensitive_label issue_with_everything = create(:issue, title: "Bug report foo was possible", project: project, milestone: milestone, author: user, assignees: [user]) issue_with_everything.labels << bug_label issue_with_everything.labels << caps_sensitive_label multiple_words_label_issue = create(:issue, title: "Issue with multiple words label", project: project) multiple_words_label_issue.labels << multiple_words_label future_milestone = create(:milestone, title: "future", project: project, due_date: Time.now + 1.month) create(:issue, title: "Issue with future milestone", milestone: future_milestone, project: project) visit namespace_project_issues_path(project.namespace, project) end describe 'filter issues by author' do context 'only author' do it 'filters issues by searched author' do input_filtered_search("author:@#{user.username}") expect_tokens([{ name: 'author', value: user.username }]) expect_issues_list_count(5) expect_filtered_search_input_empty end it 'filters issues by invalid author' do skip('to be tested, issue #26546') end it 'filters issues by multiple authors' do skip('to be tested, issue #26546') end end context 'author with other filters' do let(:search_term) { 'issue' } it 'filters issues by searched author and text' do input_filtered_search("author:@#{user.username} #{search_term}") expect_tokens([{ name: 'author', value: user.username }]) expect_issues_list_count(3) expect_filtered_search_input(search_term) end it 'filters issues by searched author, assignee and text' do input_filtered_search("author:@#{user.username} assignee:@#{user.username} #{search_term}") expect_tokens([ { name: 'author', value: user.username }, { name: 'assignee', value: user.username } ]) expect_issues_list_count(3) expect_filtered_search_input(search_term) end it 'filters issues by searched author, assignee, label, and text' do input_filtered_search("author:@#{user.username} assignee:@#{user.username} label:~#{caps_sensitive_label.title} #{search_term}") expect_tokens([ { name: 'author', value: user.username }, { name: 'assignee', value: user.username }, { name: 'label', value: caps_sensitive_label.title } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end it 'filters issues by searched author, assignee, label, milestone and text' do input_filtered_search("author:@#{user.username} assignee:@#{user.username} label:~#{caps_sensitive_label.title} milestone:%#{milestone.title} #{search_term}") expect_tokens([ { name: 'author', value: user.username }, { name: 'assignee', value: user.username }, { name: 'label', value: caps_sensitive_label.title }, { name: 'milestone', value: milestone.title } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end end it 'sorting' do skip('to be tested, issue #26546') end end describe 'filter issues by assignee' do context 'only assignee' do it 'filters issues by searched assignee' do input_filtered_search("assignee:@#{user.username}") expect_tokens([{ name: 'assignee', value: user.username }]) expect_issues_list_count(5) expect_filtered_search_input_empty end it 'filters issues by no assignee' do input_filtered_search('assignee:none') expect_tokens([{ name: 'assignee', value: 'none' }]) expect_issues_list_count(8, 1) expect_filtered_search_input_empty end it 'filters issues by invalid assignee' do skip('to be tested, issue #26546') end it 'filters issues by multiple assignees' do skip('to be tested, issue #26546') end end context 'assignee with other filters' do let(:search_term) { 'searchTerm' } it 'filters issues by searched assignee and text' do input_filtered_search("assignee:@#{user.username} #{search_term}") expect_tokens([{ name: 'assignee', value: user.username }]) expect_issues_list_count(2) expect_filtered_search_input(search_term) end it 'filters issues by searched assignee, author and text' do input_filtered_search("assignee:@#{user.username} author:@#{user.username} #{search_term}") expect_tokens([ { name: 'assignee', value: user.username }, { name: 'author', value: user.username } ]) expect_issues_list_count(2) expect_filtered_search_input(search_term) end it 'filters issues by searched assignee, author, label, text' do input_filtered_search("assignee:@#{user.username} author:@#{user.username} label:~#{caps_sensitive_label.title} #{search_term}") expect_tokens([ { name: 'assignee', value: user.username }, { name: 'author', value: user.username }, { name: 'label', value: caps_sensitive_label.title } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end it 'filters issues by searched assignee, author, label, milestone and text' do input_filtered_search("assignee:@#{user.username} author:@#{user.username} label:~#{caps_sensitive_label.title} milestone:%#{milestone.title} #{search_term}") expect_tokens([ { name: 'assignee', value: user.username }, { name: 'author', value: user.username }, { name: 'label', value: caps_sensitive_label.title }, { name: 'milestone', value: milestone.title } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end end context 'sorting' do it 'sorts' do skip('to be tested, issue #26546') end end end describe 'filter issues by label' do let(:search_term) { 'bug' } context 'only label' do it 'filters issues by searched label' do input_filtered_search("label:~#{bug_label.title}") expect_tokens([{ name: 'label', value: bug_label.title }]) expect_issues_list_count(2) expect_filtered_search_input_empty end it 'filters issues by no label' do input_filtered_search('label:none') expect_tokens([{ name: 'label', value: 'none' }]) expect_issues_list_count(9, 1) expect_filtered_search_input_empty end it 'filters issues by invalid label' do skip('to be tested, issue #26546') end it 'filters issues by multiple labels' do input_filtered_search("label:~#{bug_label.title} label:~#{caps_sensitive_label.title}") expect_tokens([ { name: 'label', value: bug_label.title }, { name: 'label', value: caps_sensitive_label.title } ]) expect_issues_list_count(1) expect_filtered_search_input_empty end it 'filters issues by label containing special characters' do special_label = create(:label, project: project, title: '!@#{$%^&*()-+[]<>?/:{}|\}') special_issue = create(:issue, title: "Issue with special character label", project: project) special_issue.labels << special_label input_filtered_search("label:~#{special_label.title}") expect_tokens([{ name: 'label', value: special_label.title }]) expect_issues_list_count(1) expect_filtered_search_input_empty end it 'does not show issues' do new_label = create(:label, project: project, title: 'new_label') input_filtered_search("label:~#{new_label.title}") expect_tokens([{ name: 'label', value: new_label.title }]) expect_no_issues_list() expect_filtered_search_input_empty end end context 'label with multiple words' do it 'special characters' do special_multiple_label = create(:label, project: project, title: "Utmost |mp0rt@nce") special_multiple_issue = create(:issue, title: "Issue with special character multiple words label", project: project) special_multiple_issue.labels << special_multiple_label input_filtered_search("label:~'#{special_multiple_label.title}'") # filtered search defaults quotations to double quotes expect_tokens([{ name: 'label', value: "\"#{special_multiple_label.title}\"" }]) expect_issues_list_count(1) expect_filtered_search_input_empty end it 'single quotes' do input_filtered_search("label:~'#{multiple_words_label.title}'") expect_tokens([{ name: 'label', value: "\"#{multiple_words_label.title}\"" }]) expect_issues_list_count(1) expect_filtered_search_input_empty end it 'double quotes' do input_filtered_search("label:~\"#{multiple_words_label.title}\"") expect_tokens([{ name: 'label', value: "\"#{multiple_words_label.title}\"" }]) expect_issues_list_count(1) expect_filtered_search_input_empty end it 'single quotes containing double quotes' do double_quotes_label = create(:label, project: project, title: 'won"t fix') double_quotes_label_issue = create(:issue, title: "Issue with double quotes label", project: project) double_quotes_label_issue.labels << double_quotes_label input_filtered_search("label:~'#{double_quotes_label.title}'") expect_tokens([{ name: 'label', value: "'#{double_quotes_label.title}'" }]) expect_issues_list_count(1) expect_filtered_search_input_empty end it 'double quotes containing single quotes' do single_quotes_label = create(:label, project: project, title: "won't fix") single_quotes_label_issue = create(:issue, title: "Issue with single quotes label", project: project) single_quotes_label_issue.labels << single_quotes_label input_filtered_search("label:~\"#{single_quotes_label.title}\"") expect_tokens([{ name: 'label', value: "\"#{single_quotes_label.title}\"" }]) expect_issues_list_count(1) expect_filtered_search_input_empty end end context 'label with other filters' do it 'filters issues by searched label and text' do input_filtered_search("label:~#{caps_sensitive_label.title} #{search_term}") expect_tokens([{ name: 'label', value: caps_sensitive_label.title }]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end it 'filters issues by searched label, author and text' do input_filtered_search("label:~#{caps_sensitive_label.title} author:@#{user.username} #{search_term}") expect_tokens([ { name: 'label', value: caps_sensitive_label.title }, { name: 'author', value: user.username } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end it 'filters issues by searched label, author, assignee and text' do input_filtered_search("label:~#{caps_sensitive_label.title} author:@#{user.username} assignee:@#{user.username} #{search_term}") expect_tokens([ { name: 'label', value: caps_sensitive_label.title }, { name: 'author', value: user.username }, { name: 'assignee', value: user.username } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end it 'filters issues by searched label, author, assignee, milestone and text' do input_filtered_search("label:~#{caps_sensitive_label.title} author:@#{user.username} assignee:@#{user.username} milestone:%#{milestone.title} #{search_term}") expect_tokens([ { name: 'label', value: caps_sensitive_label.title }, { name: 'author', value: user.username }, { name: 'assignee', value: user.username }, { name: 'milestone', value: milestone.title } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end end context 'multiple labels with other filters' do it 'filters issues by searched label, label2, and text' do input_filtered_search("label:~#{bug_label.title} label:~#{caps_sensitive_label.title} #{search_term}") expect_tokens([ { name: 'label', value: bug_label.title }, { name: 'label', value: caps_sensitive_label.title } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end it 'filters issues by searched label, label2, author and text' do input_filtered_search("label:~#{bug_label.title} label:~#{caps_sensitive_label.title} author:@#{user.username} #{search_term}") expect_tokens([ { name: 'label', value: bug_label.title }, { name: 'label', value: caps_sensitive_label.title }, { name: 'author', value: user.username } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end it 'filters issues by searched label, label2, author, assignee and text' do input_filtered_search("label:~#{bug_label.title} label:~#{caps_sensitive_label.title} author:@#{user.username} assignee:@#{user.username} #{search_term}") expect_tokens([ { name: 'label', value: bug_label.title }, { name: 'label', value: caps_sensitive_label.title }, { name: 'author', value: user.username }, { name: 'assignee', value: user.username } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end it 'filters issues by searched label, label2, author, assignee, milestone and text' do input_filtered_search("label:~#{bug_label.title} label:~#{caps_sensitive_label.title} author:@#{user.username} assignee:@#{user.username} milestone:%#{milestone.title} #{search_term}") expect_tokens([ { name: 'label', value: bug_label.title }, { name: 'label', value: caps_sensitive_label.title }, { name: 'author', value: user.username }, { name: 'assignee', value: user.username }, { name: 'milestone', value: milestone.title } ]) expect_issues_list_count(1) expect_filtered_search_input(search_term) end end context 'issue label clicked' do before do find('.issues-list .issue .issue-info a .label', text: multiple_words_label.title).click end it 'filters' do expect_issues_list_count(1) end it 'displays in search bar' do expect_tokens([{ name: 'label', value: "\"#{multiple_words_label.title}\"" }]) expect_filtered_search_input_empty end end context 'sorting' do it 'sorts' do skip('to be tested, issue #26546') end end end describe 'filter issues by milestone' do context 'only milestone' do it 'filters issues by searched milestone' do input_filtered_search("milestone:%#{milestone.title}") expect_tokens([{ name: 'milestone', value: milestone.title }]) expect_issues_list_count(5) expect_filtered_search_input_empty end it 'filters issues by no milestone' do input_filtered_search("milestone:none") expect_tokens([{ name: 'milestone', value: 'none' }]) expect_issues_list_count(7, 1) expect_filtered_search_input_empty end it 'filters issues by upcoming milestones' do input_filtered_search("milestone:upcoming") expect_tokens([{ name: 'milestone', value: 'upcoming' }]) expect_issues_list_count(1) expect_filtered_search_input_empty end it 'filters issues by started milestones' do input_filtered_search("milestone:started") expect_tokens([{ name: 'milestone', value: 'started' }]) expect_issues_list_count(5) expect_filtered_search_input_empty end it 'filters issues by invalid milestones' do skip('to be tested, issue #26546') end it 'filters issues by multiple milestones' do skip('to be tested, issue #26546') end it 'filters issues by milestone containing special characters' do special_milestone = create(:milestone, title: '!@\#{$%^&*()}', project: project) create(:issue, title: "Issue with special character milestone", project: project, milestone: special_milestone) input_filtered_search("milestone:%#{special_milestone.title}") expect_tokens([{ name: 'milestone', value: special_milestone.title }]) expect_issues_list_count(1) expect_filtered_search_input_empty end it 'does not show issues' do new_milestone = create(:milestone, title: "new", project: project) input_filtered_search("milestone:%#{new_milestone.title}") expect_tokens([{ name: 'milestone', value: new_milestone.title }]) expect_no_issues_list() expect_filtered_search_input_empty end end context 'milestone with other filters' do let(:search_term) { 'bug' } it 'filters issues by searched milestone and text' do input_filtered_search("milestone:%#{milestone.title} #{search_term}") expect_tokens([{ name: 'milestone', value: milestone.title }]) expect_issues_list_count(2) expect_filtered_search_input(search_term) end it 'filters issues by searched milestone, author and text' do input_filtered_search("milestone:%#{milestone.title} author:@#{user.username} #{search_term}") expect_tokens([ { name: 'milestone', value: milestone.title }, { name: 'author', value: user.username } ]) expect_issues_list_count(2) expect_filtered_search_input(search_term) end it 'filters issues by searched milestone, author, assignee and text' do input_filtered_search("milestone:%#{milestone.title} author:@#{user.username} assignee:@#{user.username} #{search_term}") expect_tokens([ { name: 'milestone', value: milestone.title }, { name: 'author', value: user.username }, { name: 'assignee', value: user.username } ]) expect_issues_list_count(2) expect_filtered_search_input(search_term) end it 'filters issues by searched milestone, author, assignee, label and text' do input_filtered_search("milestone:%#{milestone.title} author:@#{user.username} assignee:@#{user.username} label:~#{bug_label.title} #{search_term}") expect_tokens([ { name: 'milestone', value: milestone.title }, { name: 'author', value: user.username }, { name: 'assignee', value: user.username }, { name: 'label', value: bug_label.title } ]) expect_issues_list_count(2) expect_filtered_search_input(search_term) end end context 'sorting' do it 'sorts' do skip('to be tested, issue #26546') end end end describe 'filter issues by text' do context 'only text' do it 'filters issues by searched text' do search = 'Bug' input_filtered_search(search) expect_issues_list_count(4, 1) expect_filtered_search_input(search) end it 'filters issues by multiple searched text' do search = 'Bug report' input_filtered_search(search) expect_issues_list_count(3) expect_filtered_search_input(search) end it 'filters issues by case insensitive searched text' do search = 'bug report' input_filtered_search(search) expect_issues_list_count(3) expect_filtered_search_input(search) end it 'filters issues by searched text containing single quotes' do search = '\'single quotes\'' input_filtered_search(search) expect_issues_list_count(1) expect_filtered_search_input(search) end it 'filters issues by searched text containing double quotes' do search = '"double quotes"' input_filtered_search(search) expect_issues_list_count(1) expect_filtered_search_input(search) end it 'filters issues by searched text containing special characters' do search = '!@#{$%^&*()-+' input_filtered_search(search) expect_issues_list_count(1) expect_filtered_search_input(search) end it 'does not show any issues' do search = 'testing' input_filtered_search(search) expect_no_issues_list() expect_filtered_search_input(search) end end context 'searched text with other filters' do it 'filters issues by searched text and author' do # After searching, all search terms are placed at the end input_filtered_search("bug author:@#{user.username}") expect_issues_list_count(2) expect_filtered_search_input('bug') end it 'filters issues by searched text, author and more text' do input_filtered_search("bug author:@#{user.username} report") expect_issues_list_count(1) expect_filtered_search_input('bug report') end it 'filters issues by searched text, author and assignee' do input_filtered_search("bug author:@#{user.username} assignee:@#{user.username}") expect_issues_list_count(2) expect_filtered_search_input('bug') end it 'filters issues by searched text, author, more text and assignee' do input_filtered_search("bug author:@#{user.username} report assignee:@#{user.username}") expect_issues_list_count(1) expect_filtered_search_input('bug report') end it 'filters issues by searched text, author, more text, assignee and even more text' do input_filtered_search("bug author:@#{user.username} report assignee:@#{user.username} foo") expect_issues_list_count(1) expect_filtered_search_input('bug report foo') end it 'filters issues by searched text, author, assignee and label' do input_filtered_search("bug author:@#{user.username} assignee:@#{user.username} label:~#{bug_label.title}") expect_issues_list_count(2) expect_filtered_search_input('bug') end it 'filters issues by searched text, author, text, assignee, text, label and text' do input_filtered_search("bug author:@#{user.username} assignee:@#{user.username} report label:~#{bug_label.title} foo") expect_issues_list_count(1) expect_filtered_search_input('bug report foo') end it 'filters issues by searched text, author, assignee, label and milestone' do input_filtered_search("bug author:@#{user.username} assignee:@#{user.username} label:~#{bug_label.title} milestone:%#{milestone.title}") expect_issues_list_count(2) expect_filtered_search_input('bug') end it 'filters issues by searched text, author, text, assignee, text, label, text, milestone and text' do input_filtered_search("bug author:@#{user.username} assignee:@#{user.username} report label:~#{bug_label.title} milestone:%#{milestone.title} foo") expect_issues_list_count(1) expect_filtered_search_input('bug report foo') end it 'filters issues by searched text, author, assignee, multiple labels and milestone' do input_filtered_search("bug author:@#{user.username} assignee:@#{user.username} label:~#{bug_label.title} label:~#{caps_sensitive_label.title} milestone:%#{milestone.title}") expect_issues_list_count(1) expect_filtered_search_input('bug') end it 'filters issues by searched text, author, text, assignee, text, label1, text, label2, text, milestone and text' do input_filtered_search("bug author:@#{user.username} assignee:@#{user.username} report label:~#{bug_label.title} label:~#{caps_sensitive_label.title} milestone:%#{milestone.title} foo") expect_issues_list_count(1) expect_filtered_search_input('bug report foo') end end context 'sorting' do it 'sorts by oldest updated' do create(:issue, title: '3 days ago', project: project, author: user, created_at: 3.days.ago, updated_at: 3.days.ago) old_issue = create(:issue, title: '5 days ago', project: project, author: user, created_at: 5.days.ago, updated_at: 5.days.ago) input_filtered_search('days ago') expect_issues_list_count(2) sort_toggle = find('.filtered-search-wrapper .dropdown-toggle') sort_toggle.click find('.filtered-search-wrapper .dropdown-menu li a', text: 'Oldest updated').click wait_for_requests expect(find('.issues-list .issue:first-of-type .issue-title-text a')).to have_content(old_issue.title) end end end describe 'retains filter when switching issue states' do before do input_filtered_search('bug') # This ensures that the search is performed expect_issues_list_count(4, 1) end it 'open state' do find('.issues-state-filters a', text: 'Closed').click wait_for_requests find('.issues-state-filters a', text: 'Open').click wait_for_requests expect(page).to have_selector('.issues-list .issue', count: 4) end it 'closed state' do find('.issues-state-filters a', text: 'Closed').click wait_for_requests expect(page).to have_selector('.issues-list .issue', count: 1) expect(find('.issues-list .issue:first-of-type .issue-title-text a')).to have_content(closed_issue.title) end it 'all state' do find('.issues-state-filters a', text: 'All').click wait_for_requests expect(page).to have_selector('.issues-list .issue', count: 5) end end describe 'RSS feeds' do it 'updates atom feed link for project issues' do visit namespace_project_issues_path(project.namespace, project, milestone_title: milestone.title, assignee_id: user.id) link = find_link('Subscribe') params = CGI.parse(URI.parse(link[:href]).query) auto_discovery_link = find('link[type="application/atom+xml"]', visible: false) auto_discovery_params = CGI.parse(URI.parse(auto_discovery_link[:href]).query) expect(params).to include('rss_token' => [user.rss_token]) expect(params).to include('milestone_title' => [milestone.title]) expect(params).to include('assignee_id' => [user.id.to_s]) expect(auto_discovery_params).to include('rss_token' => [user.rss_token]) expect(auto_discovery_params).to include('milestone_title' => [milestone.title]) expect(auto_discovery_params).to include('assignee_id' => [user.id.to_s]) end it 'updates atom feed link for group issues' do visit issues_group_path(group, milestone_title: milestone.title, assignee_id: user.id) link = find('.nav-controls a', text: 'Subscribe') params = CGI.parse(URI.parse(link[:href]).query) auto_discovery_link = find('link[type="application/atom+xml"]', visible: false) auto_discovery_params = CGI.parse(URI.parse(auto_discovery_link[:href]).query) expect(params).to include('rss_token' => [user.rss_token]) expect(params).to include('milestone_title' => [milestone.title]) expect(params).to include('assignee_id' => [user.id.to_s]) expect(auto_discovery_params).to include('rss_token' => [user.rss_token]) expect(auto_discovery_params).to include('milestone_title' => [milestone.title]) expect(auto_discovery_params).to include('assignee_id' => [user.id.to_s]) end end context 'URL has a trailing slash' do before do visit "#{namespace_project_issues_path(project.namespace, project)}/" end it 'milestone dropdown loads milestones' do input_filtered_search("milestone:", submit: false) within('#js-dropdown-milestone') do expect(page).to have_selector('.filter-dropdown .filter-dropdown-item', count: 2) end end it 'label dropdown load labels' do input_filtered_search("label:", submit: false) within('#js-dropdown-label') do expect(page).to have_selector('.filter-dropdown .filter-dropdown-item', count: 5) end end end end
36.699651
192
0.659794
1cc4a7c290b00646aa20047add1bf23dd15d2e9c
4,667
require 'active_support' module Tiun::Base extend ActiveSupport::Concern included do #attr_accessor :params #define_callbacks :subscribe # include Kaminari::ConfigurationMethods #class_attribute :_helpers #self._helpers = Module.new #include ActiveSupport::Configurable #config_accessor :co # helper_method :cookies if defined?(helper_method) # around_perform do |job, block, _| # I18n.with_locale(I18n.locale.to_s, &block) # include Pundit # before_action :authenticate_user! # before_action :set_tokens, only: %i(index) # before_action :set_page, only: %i(index) # before_action :set_locales before_action :new_object, only: %i(create) before_action :fetch_object, only: %i(show update destroy) before_action :fetch_objects, only: %i(index) # before_action :authorize! rescue_from ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, ActiveRecord::RecordNotFound, with: :unprocessable_entity # has_scope :with_token, only: %i(index all) # has_scope :with_tokens, only: %i(index), type: :array end # GET /<objects>/ def index respond_to do |format| format.json { render :index, json: @objects, locales: @locales, serializer: objects_serializer, total: @objects.total_count, page: @page, each_serializer: object_serializer } format.html { render :index } end rescue ActionView::MissingTemplate head :ok, content_type: "text/html" ;end # POST /<objects>/create def create @object.save! render json: @object, serializer: object_serializer, locales: @locales ;end # PUT /<objects>/1 def update @object.update!( permitted_params ) render json: @object, serializer: object_serializer, locales: @locales ;end # GET /<objects>/1 def show respond_to do |format| format.json { render :show, json: @object, locales: @locales, serializer: object_serializer } ;end;end # DELETE /<objects>/1 def destroy @object.destroy respond_to do |format| format.json { render :show, json: @object, locales: @locales, serializer: object_serializer } ;end;end def ql @list = apply_scopes(model) respond_to do |format| format.json { render :index, json: @list.limit(500), locales: @locales, serializer: Tiun::AutocompleteSerializer, total: @calendaries.count, each_serializer: Tiun::QlSerializer } end;end def dashboard settings = { settings: Tiun.settings, locales: @locales } render inline: react_component('Dashboard', settings), layout: 'tiun' end protected def model_name @model_name ||= self.class.to_s.gsub(/.*::/, "").gsub("Controller", "").singularize end def model model_name.constantize end def object_serializer @serializer_name ||= "#{model_name}Serializer" @serializer_name.constantize end def objects_serializer Tiun::ListSerializer.new(model: model) end def apply_scopes model model end def policy_name @policy_name ||= Object.const_get(model.name + "Policy") rescue NameError @policy_name = Object.const_get("Tiun::#{model.name}Policy") end def authorize! binding.pry if !policy_name.new(current_user, @object).send(action_name + '?') raise Tiun::Policy::NotAuthorizedError, "not allowed to do #{action_name} this #{@object.inspect}" ;end;end def unprocessable_entity e errors = @object.errors.any? && @object.errors || e.to_s render json: errors, status: :unprocessable_entity ;end def set_page @page ||= (params[:page] || 1).to_i ;end def set_locales @locales ||= [ I18n.locale ] ;end def set_tokens @tokens ||= params[:with_tokens] || [] ;end def new_object @object = model.new( permitted_params ) ;end def fetch_objects @objects = apply_scopes( model ).page( params[:page] ) ;end def fetch_object if params[:slug] @object ||= model.by_slug(params[:slug]) else @object ||= model.find(params[:id]) ;end || raise(ActiveRecord::RecordNotFound) ;end;end
30.703947
116
0.6036
edf0baea9af93b76ed82102585e8958c73fcc945
6,713
=begin #NSX-T Manager API #VMware NSX-T Manager REST API OpenAPI spec version: 2.5.1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.7 =end require 'date' module NSXT # An endpoint to connect to NSX-Intelligence broker. Either FQDN or IP address can be used in the endpoint info. class IntelligenceBrokerEndpointInfo # The port number where the broker is listening to. attr_accessor :port # The IP address or the full qualified domain name of broker. attr_accessor :address # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'port' => :'port', :'address' => :'address' } end # Attribute type mapping. def self.swagger_types { :'port' => :'Integer', :'address' => :'String' } 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?(:'port') self.port = attributes[:'port'] end if attributes.has_key?(:'address') self.address = attributes[:'address'] 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 @port.nil? invalid_properties.push('invalid value for "port", port cannot be nil.') end if @port > 65535 invalid_properties.push('invalid value for "port", must be smaller than or equal to 65535.') end if @port < 1 invalid_properties.push('invalid value for "port", must be greater than or equal to 1.') end if @address.nil? invalid_properties.push('invalid value for "address", address 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 @port.nil? return false if @port > 65535 return false if @port < 1 return false if @address.nil? true end # Custom attribute writer method with validation # @param [Object] port Value to be assigned def port=(port) if port.nil? fail ArgumentError, 'port cannot be nil' end if port > 65535 fail ArgumentError, 'invalid value for "port", must be smaller than or equal to 65535.' end if port < 1 fail ArgumentError, 'invalid value for "port", must be greater than or equal to 1.' end @port = port 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 && port == o.port && address == o.address 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 [port, address].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 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 = NSXT.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
28.688034
115
0.615373
03b4d56685a875ec51effc9136572cdff4c1d7ee
1,581
# # Be sure to run `pod lib lint TSBezierPathView.podspec' to ensure this is a # valid spec before submitting. # # Any lines starting with a # are optional, but their use is encouraged # To learn more about a Podspec see https://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'TSBezierPathView' s.version = '1.0.0' s.summary = '็บฟๆก็ป˜ๅˆถ' # This description is used to generate tags and improve search results. # * Think: What does it do? Why did you write it? What is the focus? # * Try to keep it short, snappy and to the point. # * Write the description between the DESC delimiters below. # * Finally, don't worry about the indent, CocoaPods strips it! s.description = <<-DESC 1๏ผš็ป˜ๅˆถๆŸฑ็Šถๅ›พ 2๏ผš็ป˜ๅˆถๆŠ˜็บฟๅ›พ DESC s.homepage = 'https://github.com/winfast' # s.screenshots = 'www.example.com/screenshots_1', 'www.example.com/screenshots_2' s.license = { :type => 'MIT', :file => 'LICENSE' } s.author = { 'winfast' => '[email protected]' } s.source = { :git => 'https://github.com/winfast/TSBezierPathView.git', :tag => s.version.to_s } # s.social_media_url = 'https://twitter.com/<TWITTER_USERNAME>' s.ios.deployment_target = '8.0' s.source_files = 'TSBezierPathView/Classes/**/*' s.dependency 'Masonry' # s.resource_bundles = { # 'TSBezierPathView' => ['TSBezierPathView/Assets/*.png'] # } # s.public_header_files = 'Pod/Classes/**/*.h' # s.frameworks = 'UIKit', 'MapKit' # s.dependency 'AFNetworking', '~> 2.3' end
35.931818
108
0.636939
086244926e26b697044d1f0423ac2982eaa25e7b
31
module SfaccountHelper end
7.75
23
0.774194
4aca2d1ffcab328b4adfecce304326341d996918
8,388
# Copyright (c) 2009-2012 VMware, Inc. module Bosh::Director class ProblemScanner AGENT_TIMEOUT = 10 # seconds attr_reader :event_log, :logger @queue = :normal # @param [String] deployment_name Deployment name def initialize(deployment) @deployment = deployment @instance_manager = Api::InstanceManager.new @problem_lock = Mutex.new @agent_disks = {} #temp @event_log = Config.event_log @logger = Config.logger end def begin_stage(stage_name, n_steps) event_log.begin_stage(stage_name, n_steps) logger.info(stage_name) end def track_and_log(task, log = true) event_log.track(task) do |ticker| logger.info(task) if log yield ticker if block_given? end end def reset(vms=nil) if vms vms.each do |job, index| instance = @instance_manager.find_by_name(@deployment.name, job, index) Models::DeploymentProblem.where(deployment: deployment, :resource_id => instance.vm.id, :state => "open").update(state: "closed") end else Models::DeploymentProblem.where(state: "open", deployment: deployment).update(state: "closed") end end def scan_disks disks = Models::PersistentDisk.eager(:instance).all.select do |disk| disk.instance && disk.instance.deployment_id == deployment.id end results = Hash.new(0) begin_stage("Scanning #{disks.size} persistent disks", 2) track_and_log("Looking for inactive disks") do disks.each do |disk| scan_result = scan_disk(disk) results[scan_result] += 1 end end track_and_log("#{results[:ok]} OK, " + "#{results[:inactive]} inactive, " + "#{results[:mount_info_mismatch]} mount-info mismatch") end def scan_vms(vms=nil) if vms vm_list = [] vms.each do |job, index| instance = @instance_manager.find_by_name(@deployment.name, job, index) vm_list << instance.vm end vms = vm_list else vms = Models::Vm.eager(:instance).filter(deployment: deployment).all end begin_stage("Scanning #{vms.size} VMs", 2) results = Hash.new(0) lock = Mutex.new track_and_log("Checking VM states") do ThreadPool.new(:max_threads => Config.max_threads).wrap do |pool| vms.each do |vm| pool.process do scan_result = scan_vm(vm) lock.synchronize { results[scan_result] += 1 } end end end end track_and_log("#{results[:ok]} OK, " + "#{results[:unresponsive]} unresponsive, " + "#{results[:missing]} missing, " + "#{results[:unbound]} unbound, " + "#{results[:out_of_sync]} out of sync") end def scan_disk(disk) # inactive disks unless disk.active logger.info("Found inactive disk: #{disk.id}") problem_found(:inactive_disk, disk) return :inactive end disk_cid = disk.disk_cid vm_cid = nil if disk.instance && disk.instance.vm vm_cid = disk.instance.vm.cid end if vm_cid.nil? # With the db dependencies this should not happen. logger.warn("Disk #{disk_cid} is not associated to any VM. " + "Skipping scan") return :ok end owner_vms = get_disk_owners(disk_cid) || [] # active disk is not mounted or mounted more than once -or- # the disk is mounted on a vm that is different form the record. if owner_vms.size != 1 || owner_vms.first != vm_cid logger.info("Found problem in mount info: " + "active disk #{disk_cid} mounted on " + "#{owner_vms.join(', ')}") problem_found(:mount_info_mismatch, disk, :owner_vms => owner_vms) return :mount_info_mismatch end :ok end def scan_vm(vm) agent_options = { :timeout => AGENT_TIMEOUT, :retry_methods => {:get_state => 0} } instance = nil mounted_disk_cid = nil @problem_lock.synchronize do instance = vm.instance mounted_disk_cid = instance.persistent_disk_cid if instance end agent = AgentClient.with_defaults(vm.agent_id, agent_options) begin state = agent.get_state # gather mounted disk info. (used by scan_disk) begin disk_list = agent.list_disk mounted_disk_cid = disk_list.first rescue Bosh::Director::RpcTimeout => e mounted_disk_cid = nil rescue RuntimeError => e # For old agents that doesn't implement list_disk we assume the disk is mounted logger.info("agent.list_disk failed on agent #{vm.agent_id}") end add_disk_owner(mounted_disk_cid, vm.cid) if mounted_disk_cid return :out_of_sync if is_out_of_sync_vm?(vm, instance, state) return :unbound if is_unbound_instance_vm?(vm, instance, state) :ok rescue Bosh::Director::RpcTimeout # We add the disk to avoid a duplicate problem when timeouts fetching agent status (unresponsive_agent and # mount_info_mismatch) add_disk_owner(mounted_disk_cid, vm.cid) if mounted_disk_cid begin unless cloud.has_vm?(vm.cid) logger.info("Missing VM #{vm.cid}") problem_found(:missing_vm, vm) return :missing end rescue Bosh::Clouds::NotImplemented end logger.info("Found unresponsive agent #{vm.agent_id}") problem_found(:unresponsive_agent, vm) :unresponsive end end def problem_found(type, resource, data = {}) @problem_lock.synchronize do similar_open_problems = Models::DeploymentProblem. filter(:deployment_id => deployment.id, :type => type.to_s, :resource_id => resource.id, :state => "open").all if similar_open_problems.size > 1 raise CloudcheckTooManySimilarProblems, "More than one problem of type `#{type}' " + "exists for resource #{type} #{resource.id}" end if similar_open_problems.empty? problem = Models::DeploymentProblem. create(:type => type.to_s, :resource_id => resource.id, :state => "open", :deployment_id => deployment.id, :data => data, :counter => 1) logger.info("Created problem #{problem.id} (#{problem.type})") else # This assumes we are running with deployment lock acquired, # so there is no possible update conflict problem = similar_open_problems[0] problem.data = data problem.last_seen_at = Time.now problem.counter += 1 problem.save logger.info("Updated problem #{problem.id} (#{problem.type}), " + "count is now #{problem.counter}") end end end private attr_reader :deployment def is_out_of_sync_vm?(vm, instance, state) job = state["job"] ? state["job"]["name"] : nil index = state["index"] if state["deployment"] != deployment.name || (instance && (instance.job != job || instance.index != index)) problem_found(:out_of_sync_vm, vm, :deployment => state["deployment"], :job => job, :index => index) true else false end end def is_unbound_instance_vm?(vm, instance, state) job = state["job"] ? state["job"]["name"] : nil index = state["index"] if job && !instance logger.info("Found unbound VM #{vm.agent_id}") problem_found(:unbound_instance_vm, vm, :job => job, :index => index) true else false end end def add_disk_owner(disk_cid, vm_cid) @agent_disks[disk_cid] ||= [] @agent_disks[disk_cid] << vm_cid end def get_disk_owners(disk_cid) @agent_disks[disk_cid] end def cloud Config.cloud end end end
31.182156
114
0.577611
1cd358112e5381c0fbc35e819ff6476308ce0873
367
require "spec_helper" describe "brightbox servers" do describe "update" do let(:output) { FauxIO.new { Brightbox.run(argv) } } let(:stdout) { output.stdout } let(:stderr) { output.stderr } context "" do let(:argv) { %w(servers update) } it "does not error" do expect { output }.to_not raise_error end end end end
19.315789
55
0.607629
03e1b949b7a1a522cb85e91449295081217e9b52
4,818
# frozen_string_literal: true def env ENV["APP_ENV"] || ENV["RACK_ENV"] end def test_env? env == "test" end def development_env? env == "development" end class InitialSchema < ActiveRecord::Migration[7.0] def change create_table :tags, if_not_exists: true do |t| t.string :name, null: false end create_table :alerts, if_not_exists: true do |t| t.string :title, null: false t.string :description, null: true t.string :source, null: false t.timestamps end create_table :artifacts, if_not_exists: true do |t| t.string :data, null: false t.string :data_type, null: false t.belongs_to :alert, foreign_key: true t.timestamps end create_table :taggings, if_not_exists: true do |t| t.integer :tag_id t.integer :alert_id end add_index :taggings, :tag_id, if_not_exists: true add_index :taggings, [:tag_id, :alert_id], unique: true, if_not_exists: true end end class AddeSourceToArtifactSchema < ActiveRecord::Migration[7.0] def change add_column :artifacts, :source, :string, if_not_exists: true end end class EnrichmentsSchema < ActiveRecord::Migration[7.0] def change create_table :autonomous_systems, if_not_exists: true do |t| t.integer :asn, null: false t.belongs_to :artifact, foreign_key: true end create_table :geolocations, if_not_exists: true do |t| t.string :country, null: false t.string :country_code, null: false t.belongs_to :artifact, foreign_key: true end create_table :whois_records, if_not_exists: true do |t| t.string :domain, null: false t.date :created_on t.date :updated_on t.date :expires_on t.json :registrar t.json :contacts t.belongs_to :artifact, foreign_key: true end create_table :dns_records, if_not_exists: true do |t| t.string :resource, null: false t.string :value, null: false t.belongs_to :artifact, foreign_key: true end create_table :reverse_dns_names, if_not_exists: true do |t| t.string :name, null: false t.belongs_to :artifact, foreign_key: true end end end class EnrichmentCreatedAtSchema < ActiveRecord::Migration[7.0] def change # Add created_at column because now it is able to enrich an atrifact after the creation add_column :autonomous_systems, :created_at, :datetime, if_not_exists: true add_column :geolocations, :created_at, :datetime, if_not_exists: true add_column :whois_records, :created_at, :datetime, if_not_exists: true add_column :dns_records, :created_at, :datetime, if_not_exists: true add_column :reverse_dns_names, :created_at, :datetime, if_not_exists: true end end class RuleSchema < ActiveRecord::Migration[7.0] def change create_table :rules, id: :string, if_not_exists: true do |t| t.string :title, null: false t.string :description, null: false t.json :data, null: false t.timestamps end end end class AddeMetadataToArtifactSchema < ActiveRecord::Migration[7.0] def change add_column :artifacts, :metadata, :json, if_not_exists: true end end def adapter return "postgresql" if Mihari.config.database.start_with?("postgresql://", "postgres://") return "mysql2" if Mihari.config.database.start_with?("mysql2://") "sqlite3" end module Mihari class Database class << self include Memist::Memoizable # # DB migraration # # @param [Symbol] direction # def migrate(direction) ActiveRecord::Migration.verbose = false [ InitialSchema, AddeSourceToArtifactSchema, EnrichmentsSchema, EnrichmentCreatedAtSchema, # v4 RuleSchema, AddeMetadataToArtifactSchema ].each { |schema| schema.migrate direction } end memoize :migrate unless test_env? # # Establish DB connection # def connect return if ActiveRecord::Base.connected? case adapter when "postgresql", "mysql2" ActiveRecord::Base.establish_connection(Mihari.config.database) else ActiveRecord::Base.establish_connection( adapter: adapter, database: Mihari.config.database ) end ActiveRecord::Base.logger = Logger.new($stdout) if development_env? migrate :up rescue StandardError # Do nothing end # # Close DB connection(s) # def close return unless ActiveRecord::Base.connected? ActiveRecord::Base.clear_active_connections! end # # Destory DB # def destroy! return unless ActiveRecord::Base.connected? migrate :down end end end end
25.357895
91
0.660232
3338df4c80728137a53da2a11fea82ffcd744224
5,702
require File.dirname(__FILE__) + '/spec_helper.rb' describe "Twitter::Base" do before do @base = Twitter::Base.new('foo', 'bar') end describe "being initialized" do it "should require email and password" do lambda { Twitter::Base.new }.should raise_error(ArgumentError) end end describe "timelines" do it "should bomb if given invalid timeline" do lambda { @base.timeline(:fakeyoutey) }.should raise_error(Twitter::UnknownTimeline) end it "should default to friends timeline" do @base.should_receive(:call).with("friends_timeline", {:auth=>true, :args=>{}, :since=>nil}) @base.should_receive(:statuses) @base.timeline end it "should be able to retrieve friends timeline" do data = open(File.dirname(__FILE__) + '/fixtures/friends_timeline.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) @base.timeline(:friends).size.should == 3 end it "should be able to retrieve public timeline" do data = open(File.dirname(__FILE__) + '/fixtures/public_timeline.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) @base.timeline(:public).size.should == 6 end it "should be able to retrieve user timeline" do data = open(File.dirname(__FILE__) + '/fixtures/user_timeline.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) @base.timeline(:user).size.should == 19 end end describe "friends and followers" do it "should be able to get friends" do data = open(File.dirname(__FILE__) + '/fixtures/friends.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) @base.friends.size.should == 25 end it "should be able to get friends without latest status" do data = open(File.dirname(__FILE__) + '/fixtures/friends_lite.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) @base.friends(:lite => true).size.should == 15 end it "should be able to get all friends" do data = open(File.dirname(__FILE__) + '/fixtures/friends.xml').read @base.should_receive(:request). with("statuses/friends.xml?page=0&", {:auth=>true}). and_return(Hpricot::XML(data)) @base.should_receive(:request). with("statuses/friends.xml?page=1&", {:auth=>true}). and_return(Hpricot::XML("")) @base.all_friends.size.should == 25 end it "should be able to get friends for another user" do data = open(File.dirname(__FILE__) + '/fixtures/friends_for.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) timeline = @base.friends_for(20) timeline.size.should == 24 timeline.first.name.should == 'Jack Dorsey' end it "should be able to get all friends for another user" do data = open(File.dirname(__FILE__) + '/fixtures/friends_for.xml').read @base.should_receive(:request). with("statuses/friends.xml?page=0&id=20&", {:auth=>true}). and_return(Hpricot::XML(data)) @base.should_receive(:request). with("statuses/friends.xml?page=1&id=20&", {:auth=>true}). and_return(Hpricot::XML("")) timeline = @base.all_friends_for(20) timeline.size.should == 24 timeline.first.name.should == 'Jack Dorsey' end it "should be able to get followers" do data = open(File.dirname(__FILE__) + '/fixtures/followers.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) timeline = @base.followers timeline.size.should == 29 timeline.first.name.should == 'Blaine Cook' end it "should be able to create a friendship" do data = open(File.dirname(__FILE__) + '/fixtures/friendship_created.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) user = @base.create_friendship('jnunemaker') end it "should bomb if friendship already exists" do data = open(File.dirname(__FILE__) + '/fixtures/friendship_already_exists.xml').read response = Net::HTTPForbidden.new("1.1", '403', '') response.stub!(:body).and_return(data) @base.should_receive(:response).and_return(response) lambda { @base.create_friendship('billymeltdown') }.should raise_error(Twitter::AlreadyFollowing) end end it "should be able to get single status" do data = open(File.dirname(__FILE__) + '/fixtures/status.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) @base.status(803478581).created_at.should == 'Sun May 04 23:36:14 +0000 2008' end it "should be able to get single user" do data = open(File.dirname(__FILE__) + '/fixtures/user.xml').read @base.should_receive(:request).and_return(Hpricot::XML(data)) @base.user('4243').name.should == 'John Nunemaker' end describe "rate limit status" do before do @data = open(File.dirname(__FILE__) + '/fixtures/rate_limit_status.xml').read @base.stub!(:request).and_return(Hpricot::XML(@data)) end it "should request the status" do @base.should_receive(:request).and_return(Hpricot::XML(@data)) @base.rate_limit_status end it "should have an hourly limit" do @base.rate_limit_status.hourly_limit.should == 20 end it "should have a reset time in seconds" do @base.rate_limit_status.reset_time_in_seconds.should == 1214757610 end it "should have a reset time" do @base.rate_limit_status.reset_time.should == Time.parse('2008-06-29T16:40:10+00:00') end it "should have remaining hits" do @base.rate_limit_status.remaining_hits.should == 5 end end end
37.513158
103
0.672571
f822d937dabde4a3ecebc74faea63e07af24ce17
1,108
class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you may want to use :null_session instead. protect_from_forgery with: :exception before_filter :configure_permitted_parameters, if: :devise_controller? #private #def current_user # @current_user ||= User.find_by(id: session[:user_id]) #end #def signed_in? # !!current_user #end #helper_method :current_user, :signed_in? #def current_user=(user) # @current_user = user # session[:user_id] = user.nil? ? nil : user.id #end #rescue_from AbstractController::ActionNotFound do | exception | # redirect_to root_url, :alert => exception.message #end #rescue_from ActiveRecord::RecordNotFound do | exception | # redirect_to root_url, :alert => exception.message #end rescue_from CanCan::AccessDenied do | exception | redirect_to root_url, :alert => exception.message end protected def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password, :password_confirmation) } end end
27.02439
106
0.731047
3875b0420f423eaec7a7cc1e59ba586449e905dd
279
require 'action_view' module ActionView module Helpers class FormBuilder def autocomplete_select(method, path, label_or_options = nil, *args) text_field(method, @template.autocomplete_select_options(path, label_or_options, args)) end end end end
23.25
95
0.734767
5d758386727a16d5976ca014285b8bd80e78bec2
1,045
require 'test_helper' class DocumentsControllerTest < ActionDispatch::IntegrationTest setup do @document = documents(:one) end test "should get index" do get documents_url assert_response :success end test "should get new" do get new_document_url assert_response :success end test "should create document" do assert_difference('Document.count') do post documents_url, params: { document: { } } end assert_redirected_to document_url(Document.last) end test "should show document" do get document_url(@document) assert_response :success end test "should get edit" do get edit_document_url(@document) assert_response :success end test "should update document" do patch document_url(@document), params: { document: { } } assert_redirected_to document_url(@document) end test "should destroy document" do assert_difference('Document.count', -1) do delete document_url(@document) end assert_redirected_to documents_url end end
21.326531
63
0.714833
1a0ff945997c1f3bf8d702d97852a95c52c9c96c
148
class CreateQueSchema < ActiveRecord::Migration[7.0] def up Que.migrate!(version: 6) end def down Que.migrate!(version: 0) end end
14.8
52
0.675676
01dfe14e570dc62a2990a914b404a0dfba903e6c
15,190
# frozen_string_literal: true # Assuming you have not yet modified this file, each configuration option below # is set to its default value. Note that some are commented out while others # are not: uncommented lines are intended to protect your configuration from # breaking changes in upgrades (i.e., in the event that future versions of # Devise change the default values for those options). # # Use this hook to configure devise mailer, warden hooks and so forth. # Many of these configuration options can be set straight in your model. Devise.setup do |config| # The secret key used by Devise. Devise uses this key to generate # random tokens. Changing this key will render invalid all existing # confirmation, reset password and unlock tokens in the database. # Devise will use the `secret_key_base` as its `secret_key` # by default. You can change it below and use your own secret key. # config.secret_key = 'b3fa0c6f8d41841e94001a3b5cc9b653e9c71f74cfa4c5c4f33b2afc992e1df2f7c903a4e76dff3fb3a2d53482245d336b4de7003e1f0edde9e72ebbf1a66270' # ==> Controller configuration # Configure the parent class to the devise controllers. # config.parent_controller = 'DeviseController' # ==> Mailer Configuration # Configure the e-mail address which will be shown in Devise::Mailer, # note that it will be overwritten if you use your own mailer class # with default "from" parameter. config.mailer_sender = '[email protected]' # Configure the class responsible to send e-mails. # config.mailer = 'Devise::Mailer' # Configure the parent class responsible to send e-mails. # config.parent_mailer = 'ActionMailer::Base' # ==> ORM configuration # Load and configure the ORM. Supports :active_record (default) and # :mongoid (bson_ext recommended) by default. Other ORMs may be # available as additional gems. require 'devise/orm/active_record' # ==> Configuration for any authentication mechanism # Configure which keys are used when authenticating a user. The default is # just :email. You can configure it to use [:username, :subdomain], so for # authenticating a user, both parameters are required. Remember that those # parameters are used only when authenticating and not when retrieving from # session. If you need permissions, you should implement that in a before filter. # You can also supply a hash where the value is a boolean determining whether # or not authentication should be aborted when the value is not present. # config.authentication_keys = [:email] # Configure parameters from the request object used for authentication. Each entry # given should be a request method and it will automatically be passed to the # find_for_authentication method and considered in your model lookup. For instance, # if you set :request_keys to [:subdomain], :subdomain will be used on authentication. # The same considerations mentioned for authentication_keys also apply to request_keys. # config.request_keys = [] # Configure which authentication keys should be case-insensitive. # These keys will be downcased upon creating or modifying a user and when used # to authenticate or find a user. Default is :email. config.case_insensitive_keys = [:email] # Configure which authentication keys should have whitespace stripped. # These keys will have whitespace before and after removed upon creating or # modifying a user and when used to authenticate or find a user. Default is :email. config.strip_whitespace_keys = [:email] # Tell if authentication through request.params is enabled. True by default. # It can be set to an array that will enable params authentication only for the # given strategies, for example, `config.params_authenticatable = [:database]` will # enable it only for database (email + password) authentication. # config.params_authenticatable = true # Tell if authentication through HTTP Auth is enabled. False by default. # It can be set to an array that will enable http authentication only for the # given strategies, for example, `config.http_authenticatable = [:database]` will # enable it only for database authentication. # For API-only applications to support authentication "out-of-the-box", you will likely want to # enable this with :database unless you are using a custom strategy. # The supported strategies are: # :database = Support basic authentication with authentication key + password # config.http_authenticatable = false # If 401 status code should be returned for AJAX requests. True by default. # config.http_authenticatable_on_xhr = true # The realm used in Http Basic Authentication. 'Application' by default. # config.http_authentication_realm = 'Application' # It will change confirmation, password recovery and other workflows # to behave the same regardless if the e-mail provided was right or wrong. # Does not affect registerable. # config.paranoid = true # By default Devise will store the user in session. You can skip storage for # particular strategies by setting this option. # Notice that if you are skipping storage for all authentication paths, you # may want to disable generating routes to Devise's sessions controller by # passing skip: :sessions to `devise_for` in your config/routes.rb config.skip_session_storage = [:http_auth] # By default, Devise cleans up the CSRF token on authentication to # avoid CSRF token fixation attacks. This means that, when using AJAX # requests for sign in and sign up, you need to get a new CSRF token # from the server. You can disable this option at your own risk. # config.clean_up_csrf_token_on_authentication = true # When false, Devise will not attempt to reload routes on eager load. # This can reduce the time taken to boot the app but if your application # requires the Devise mappings to be loaded during boot time the application # won't boot properly. # config.reload_routes = true # ==> Configuration for :database_authenticatable # For bcrypt, this is the cost for hashing the password and defaults to 12. If # using other algorithms, it sets how many times you want the password to be hashed. # The number of stretches used for generating the hashed password are stored # with the hashed password. This allows you to change the stretches without # invalidating existing passwords. # # Limiting the stretches to just one in testing will increase the performance of # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use # a value less than 10 in other environments. Note that, for bcrypt (the default # algorithm), the cost increases exponentially with the number of stretches (e.g. # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation). config.stretches = Rails.env.test? ? 1 : 12 # Set up a pepper to generate the hashed password. # config.pepper = '9b2eb29c31bcd2785e975c90db77f277573c77344bc0f3416c768b29f0bfc445ee3b258fde70480fd49d2a781f384183c331e173881d7609155c3ae74e378c94' # Send a notification to the original email when the user's email is changed. # config.send_email_changed_notification = false # Send a notification email when the user's password is changed. # config.send_password_change_notification = false # ==> Configuration for :confirmable # A period that the user is allowed to access the website even without # confirming their account. For instance, if set to 2.days, the user will be # able to access the website for two days without confirming their account, # access will be blocked just in the third day. # You can also set it to nil, which will allow the user to access the website # without confirming their account. # Default is 0.days, meaning the user cannot access the website without # confirming their account. # config.allow_unconfirmed_access_for = 2.days # A period that the user is allowed to confirm their account before their # token becomes invalid. For example, if set to 3.days, the user can confirm # their account within 3 days after the mail was sent, but on the fourth day # their account can't be confirmed with the token any more. # Default is nil, meaning there is no restriction on how long a user can take # before confirming their account. # config.confirm_within = 3.days # If true, requires any email changes to be confirmed (exactly the same way as # initial account confirmation) to be applied. Requires additional unconfirmed_email # db field (see migrations). Until confirmed, new email is stored in # unconfirmed_email column, and copied to email column on successful confirmation. config.reconfirmable = true # Defines which key will be used when confirming an account # config.confirmation_keys = [:email] # ==> Configuration for :rememberable # The time the user will be remembered without asking for credentials again. # config.remember_for = 2.weeks # Invalidates all the remember me tokens when the user signs out. config.expire_all_remember_me_on_sign_out = true # If true, extends the user's remember period when remembered via cookie. # config.extend_remember_period = false # Options to be passed to the created cookie. For instance, you can set # secure: true in order to force SSL only cookies. # config.rememberable_options = {} # ==> Configuration for :validatable # Range for password length. config.password_length = 6..128 # Email regex used to validate email formats. It simply asserts that # one (and only one) @ exists in the given string. This is mainly # to give user feedback and not to assert the e-mail validity. config.email_regexp = /\A[^@\s]+@[^@\s]+\z/ # ==> Configuration for :timeoutable # The time you want to timeout the user session without activity. After this # time the user will be asked for credentials again. Default is 30 minutes. # config.timeout_in = 30.minutes # ==> Configuration for :lockable # Defines which strategy will be used to lock an account. # :failed_attempts = Locks an account after a number of failed attempts to sign in. # :none = No lock strategy. You should handle locking by yourself. # config.lock_strategy = :failed_attempts # Defines which key will be used when locking and unlocking an account # config.unlock_keys = [:email] # Defines which strategy will be used to unlock an account. # :email = Sends an unlock link to the user email # :time = Re-enables login after a certain amount of time (see :unlock_in below) # :both = Enables both strategies # :none = No unlock strategy. You should handle unlocking by yourself. # config.unlock_strategy = :both # Number of authentication tries before locking an account if lock_strategy # is failed attempts. # config.maximum_attempts = 20 # Time interval to unlock the account if :time is enabled as unlock_strategy. # config.unlock_in = 1.hour # Warn on the last attempt before the account is locked. # config.last_attempt_warning = true # ==> Configuration for :recoverable # # Defines which key will be used when recovering the password for an account # config.reset_password_keys = [:email] # Time interval you can reset your password with a reset password key. # Don't put a too small interval or your users won't have the time to # change their passwords. config.reset_password_within = 6.hours # When set to false, does not sign a user in automatically after their password is # reset. Defaults to true, so a user is signed in automatically after a reset. # config.sign_in_after_reset_password = true # ==> Configuration for :encryptable # Allow you to use another hashing or encryption algorithm besides bcrypt (default). # You can use :sha1, :sha512 or algorithms from others authentication tools as # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20 # for default behavior) and :restful_authentication_sha1 (then you should set # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper). # # Require the `devise-encryptable` gem when using anything other than bcrypt # config.encryptor = :sha512 # ==> Scopes configuration # Turn scoped views on. Before rendering "sessions/new", it will first check for # "users/sessions/new". It's turned off by default because it's slower if you # are using only default views. # config.scoped_views = false # Configure the default scope given to Warden. By default it's the first # devise role declared in your routes (usually :user). # config.default_scope = :user # Set this configuration to false if you want /users/sign_out to sign out # only the current scope. By default, Devise signs out all scopes. # config.sign_out_all_scopes = true # ==> Navigation configuration # Lists the formats that should be treated as navigational. Formats like # :html, should redirect to the sign in page when the user does not have # access, but formats like :xml or :json, should return 401. # # If you have any extra navigational formats, like :iphone or :mobile, you # should add them to the navigational formats lists. # # The "*/*" below is required to match Internet Explorer requests. # config.navigational_formats = ['*/*', :html] # The default HTTP method used to sign out a resource. Default is :delete. config.sign_out_via = :delete # ==> OmniAuth # Add a new OmniAuth provider. Check the wiki for more information on setting # up on your models and hooks. # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo' # ==> Warden configuration # If you want to use other strategies, that are not supported by Devise, or # change the failure app, you can configure them inside the config.warden block. # # config.warden do |manager| # manager.intercept_401 = false # manager.default_strategies(scope: :user).unshift :some_external_strategy # end # ==> Mountable engine configurations # When using Devise inside an engine, let's call it `MyEngine`, and this engine # is mountable, there are some extra configurations to be taken into account. # The following options are available, assuming the engine is mounted as: # # mount MyEngine, at: '/my_engine' # # The router that invoked `devise_for`, in the example above, would be: # config.router_name = :my_engine # # When using OmniAuth, Devise cannot automatically set OmniAuth path, # so you need to do it manually. For the users scope, it would be: # config.omniauth_path_prefix = '/my_engine/users/auth' # ==> Turbolinks configuration # If your app is using Turbolinks, Turbolinks::Controller needs to be included to make redirection work correctly: # # ActiveSupport.on_load(:devise_failure_app) do # include Turbolinks::Controller # end # ==> Configuration for :registerable # When set to false, does not sign a user in automatically after their password is # changed. Defaults to true, so a user is signed in automatically after changing a password. # config.sign_in_after_change_password = true end
48.685897
154
0.752535
08c0c805448fdd41b9aae22697a7caa6e5d6b18b
52,653
# frozen_string_literal: true require_relative 'test_helper' context 'Attributes' do default_logger = Asciidoctor::LoggerManager.logger setup do Asciidoctor::LoggerManager.logger = (@logger = Asciidoctor::MemoryLogger.new) end teardown do Asciidoctor::LoggerManager.logger = default_logger end context 'Assignment' do test 'creates an attribute' do doc = document_from_string(':frog: Tanglefoot') assert_equal 'Tanglefoot', doc.attributes['frog'] end test 'requires a space after colon following attribute name' do doc = document_from_string 'foo:bar' assert_nil doc.attributes['foo'] end # NOTE AsciiDoc Python recognizes this entry test 'does not recognize attribute entry if name contains colon' do input = ':foo:bar: baz' doc = document_from_string input refute doc.attr?('foo:bar') assert_equal 1, doc.blocks.size assert_equal :paragraph, doc.blocks[0].context end # NOTE AsciiDoc Python recognizes this entry test 'does not recognize attribute entry if name ends with colon' do input = ':foo:: bar' doc = document_from_string input refute doc.attr?('foo:') assert_equal 1, doc.blocks.size assert_equal :dlist, doc.blocks[0].context end # NOTE AsciiDoc Python does not recognize this entry test 'allows any word character defined by Unicode in an attribute name' do [['cafรฉ', 'a coffee shop'], ['ุณู…ู†', %(ุณุงุฒู…ุงู† ู…ุฑุฏู…ู†ู‡ุงุฏ)]].each do |(name, value)| str = <<~EOS :#{name}: #{value} {#{name}} EOS result = convert_string_to_embedded str # NOTE truffleruby adds \n to the beginning of a paragraph containing multibyte chars # see https://github.com/oracle/truffleruby/issues/1543 #assert_includes result, %(<p>#{value}</p>) assert_includes result, value end end test 'creates an attribute by fusing a legacy multi-line value' do str = <<~'EOS' :description: This is the first + Ruby implementation of + AsciiDoc. EOS doc = document_from_string(str) assert_equal 'This is the first Ruby implementation of AsciiDoc.', doc.attributes['description'] end test 'creates an attribute by fusing a multi-line value' do str = <<~'EOS' :description: This is the first \ Ruby implementation of \ AsciiDoc. EOS doc = document_from_string(str) assert_equal 'This is the first Ruby implementation of AsciiDoc.', doc.attributes['description'] end test 'honors line break characters in multi-line values' do str = <<~'EOS' :signature: Linus Torvalds + \ Linux Hacker + \ [email protected] EOS doc = document_from_string(str) assert_equal %(Linus Torvalds +\nLinux Hacker +\[email protected]), doc.attributes['signature'] end test 'should allow pass macro to surround a multi-line value that contains line breaks' do str = <<~'EOS' :signature: pass:a[{author} + \ {title} + \ {email}] EOS doc = document_from_string str, attributes: { 'author' => 'Linus Torvalds', 'title' => 'Linux Hacker', 'email' => '[email protected]' } assert_equal %(Linus Torvalds +\nLinux Hacker +\[email protected]), (doc.attr 'signature') end test 'should delete an attribute that ends with !' do doc = document_from_string(":frog: Tanglefoot\n:frog!:") assert_nil doc.attributes['frog'] end test 'should delete an attribute that ends with ! set via API' do doc = document_from_string(":frog: Tanglefoot", attributes: { 'frog!' => '' }) assert_nil doc.attributes['frog'] end test 'should delete an attribute that begins with !' do doc = document_from_string(":frog: Tanglefoot\n:!frog:") assert_nil doc.attributes['frog'] end test 'should delete an attribute that begins with ! set via API' do doc = document_from_string(":frog: Tanglefoot", attributes: { '!frog' => '' }) assert_nil doc.attributes['frog'] end test 'should delete an attribute set via API to nil value' do doc = document_from_string(":frog: Tanglefoot", attributes: { 'frog' => nil }) assert_nil doc.attributes['frog'] end test "doesn't choke when deleting a non-existing attribute" do doc = document_from_string(':frog!:') assert_nil doc.attributes['frog'] end test "replaces special characters in attribute value" do doc = document_from_string(":xml-busters: <>&") assert_equal '&lt;&gt;&amp;', doc.attributes['xml-busters'] end test "performs attribute substitution on attribute value" do doc = document_from_string(":version: 1.0\n:release: Asciidoctor {version}") assert_equal 'Asciidoctor 1.0', doc.attributes['release'] end test 'assigns attribute to empty string if substitution fails to resolve attribute' do input = ':release: Asciidoctor {version}' document_from_string input, attributes: { 'attribute-missing' => 'drop-line' } assert_message @logger, :WARN, 'dropping line containing reference to missing attribute: version' end test 'assigns multi-line attribute to empty string if substitution fails to resolve attribute' do input = <<~'EOS' :release: Asciidoctor + {version} EOS doc = document_from_string input, attributes: { 'attribute-missing' => 'drop-line' } assert_equal '', doc.attributes['release'] assert_message @logger, :WARN, 'dropping line containing reference to missing attribute: version' end test 'resolves attributes inside attribute value within header' do input = <<~'EOS' = Document Title :big: big :bigfoot: {big}foot {bigfoot} EOS result = convert_string_to_embedded input assert_includes result, 'bigfoot' end test 'resolves attributes and pass macro inside attribute value outside header' do input = <<~'EOS' = Document Title content :big: pass:a,q[_big_] :bigfoot: {big}foot {bigfoot} EOS result = convert_string_to_embedded input assert_includes result, '<em>big</em>foot' end test 'should limit maximum size of attribute value if safe mode is SECURE' do expected = 'a' * 4096 input = <<~EOS :name: #{'a' * 5000} {name} EOS result = convert_inline_string input assert_equal expected, result assert_equal 4096, result.bytesize end test 'should handle multibyte characters when limiting attribute value size' do expected = 'ๆ—ฅๆœฌ' input = <<~'EOS' :name: ๆ—ฅๆœฌ่ชž {name} EOS # see https://github.com/oracle/truffleruby/issues/1563 input = String.new input, encoding: ::Encoding::UTF_8 if RUBY_ENGINE == 'truffleruby' result = convert_inline_string input, attributes: { 'max-attribute-value-size' => 6 } assert_equal expected, result assert_equal 6, result.bytesize end test 'should not mangle multibyte characters when limiting attribute value size' do expected = 'ๆ—ฅๆœฌ' input = <<~'EOS' :name: ๆ—ฅๆœฌ่ชž {name} EOS # see https://github.com/oracle/truffleruby/issues/1563 input = String.new input, encoding: ::Encoding::UTF_8 if RUBY_ENGINE == 'truffleruby' result = convert_inline_string input, attributes: { 'max-attribute-value-size' => 8 } assert_equal expected, result assert_equal 6, result.bytesize end test 'should allow maximize size of attribute value to be disabled' do expected = 'a' * 5000 input = <<~EOS :name: #{'a' * 5000} {name} EOS result = convert_inline_string input, attributes: { 'max-attribute-value-size' => nil } assert_equal expected, result assert_equal 5000, result.bytesize end test 'resolves user-home attribute if safe mode is less than SERVER' do input = <<~'EOS' :imagesdir: {user-home}/etc/images {imagesdir} EOS output = convert_inline_string input, safe: :safe assert_equal %(#{Asciidoctor::USER_HOME}/etc/images), output end test 'user-home attribute resolves to . if safe mode is SERVER or greater' do input = <<~'EOS' :imagesdir: {user-home}/etc/images {imagesdir} EOS output = convert_inline_string input, safe: :server assert_equal './etc/images', output end test "apply custom substitutions to text in passthrough macro and assign to attribute" do doc = document_from_string(":xml-busters: pass:[<>&]") assert_equal '<>&', doc.attributes['xml-busters'] doc = document_from_string(":xml-busters: pass:none[<>&]") assert_equal '<>&', doc.attributes['xml-busters'] doc = document_from_string(":xml-busters: pass:specialcharacters[<>&]") assert_equal '&lt;&gt;&amp;', doc.attributes['xml-busters'] end test 'should not recognize pass macro with invalid substitution list in attribute value' do [',', '42', 'a,'].each do |subs| doc = document_from_string %(:pass-fail: pass:#{subs}[whale]) assert_equal %(pass:#{subs}[whale]), doc.attributes['pass-fail'] end end test "attribute is treated as defined until it's not" do input = <<~'EOS' :holygrail: ifdef::holygrail[] The holy grail has been found! endif::holygrail[] :holygrail!: ifndef::holygrail[] Buggers! What happened to the grail? endif::holygrail[] EOS output = convert_string input assert_xpath '//p', output, 2 assert_xpath '(//p)[1][text() = "The holy grail has been found!"]', output, 1 assert_xpath '(//p)[2][text() = "Buggers! What happened to the grail?"]', output, 1 end test 'attribute set via API overrides attribute set in document' do doc = document_from_string(':cash: money', attributes: { 'cash' => 'heroes' }) assert_equal 'heroes', doc.attributes['cash'] end test 'attribute set via API cannot be unset by document' do doc = document_from_string(':cash!:', attributes: { 'cash' => 'heroes' }) assert_equal 'heroes', doc.attributes['cash'] end test 'attribute soft set via API using modifier on name can be overridden by document' do doc = document_from_string(':cash: money', attributes: { 'cash@' => 'heroes' }) assert_equal 'money', doc.attributes['cash'] end test 'attribute soft set via API using modifier on value can be overridden by document' do doc = document_from_string(':cash: money', attributes: { 'cash' => 'heroes@' }) assert_equal 'money', doc.attributes['cash'] end test 'attribute soft set via API using modifier on name can be unset by document' do doc = document_from_string(':cash!:', attributes: { 'cash@' => 'heroes' }) assert_nil doc.attributes['cash'] doc = document_from_string(':cash!:', attributes: { 'cash@' => true }) assert_nil doc.attributes['cash'] end test 'attribute soft set via API using modifier on value can be unset by document' do doc = document_from_string(':cash!:', attributes: { 'cash' => 'heroes@' }) assert_nil doc.attributes['cash'] end test 'attribute unset via API cannot be set by document' do [ { 'cash!' => '' }, { '!cash' => '' }, { 'cash' => nil }, ].each do |attributes| doc = document_from_string(':cash: money', attributes: attributes) assert_nil doc.attributes['cash'] end end test 'attribute soft unset via API can be set by document' do [ { 'cash!@' => '' }, { '!cash@' => '' }, { 'cash!' => '@' }, { '!cash' => '@' }, { 'cash' => false }, ].each do |attributes| doc = document_from_string(':cash: money', attributes: attributes) assert_equal 'money', doc.attributes['cash'] end end test 'can soft unset built-in attribute from API and still override in document' do [ { 'sectids!@' => '' }, { '!sectids@' => '' }, { 'sectids!' => '@' }, { '!sectids' => '@' }, { 'sectids' => false }, ].each do |attributes| doc = document_from_string '== Heading', attributes: attributes refute doc.attr?('sectids') assert_css '#_heading', (doc.convert header_footer: false), 0 doc = document_from_string %(:sectids:\n\n== Heading), attributes: attributes assert doc.attr?('sectids') assert_css '#_heading', (doc.convert header_footer: false), 1 end end test 'backend and doctype attributes are set by default in default configuration' do input = <<~'EOS' = Document Title Author Name content EOS doc = document_from_string input expect = { 'backend' => 'html5', 'backend-html5' => '', 'backend-html5-doctype-article' => '', 'outfilesuffix' => '.html', 'basebackend' => 'html', 'basebackend-html' => '', 'basebackend-html-doctype-article' => '', 'doctype' => 'article', 'doctype-article' => '', 'filetype' => 'html', 'filetype-html' => '', } expect.each do |key, val| assert doc.attributes.key? key assert_equal val, doc.attributes[key] end end test 'backend and doctype attributes are set by default in custom configuration' do input = <<~'EOS' = Document Title Author Name content EOS doc = document_from_string input, doctype: 'book', backend: 'docbook' expect = { 'backend' => 'docbook5', 'backend-docbook5' => '', 'backend-docbook5-doctype-book' => '', 'outfilesuffix' => '.xml', 'basebackend' => 'docbook', 'basebackend-docbook' => '', 'basebackend-docbook-doctype-book' => '', 'doctype' => 'book', 'doctype-book' => '', 'filetype' => 'xml', 'filetype-xml' => '', } expect.each do |key, val| assert doc.attributes.key? key assert_equal val, doc.attributes[key] end end test 'backend attributes are updated if backend attribute is defined in document and safe mode is less than SERVER' do input = <<~'EOS' = Document Title Author Name :backend: docbook :doctype: book content EOS doc = document_from_string input, safe: Asciidoctor::SafeMode::SAFE expect = { 'backend' => 'docbook5', 'backend-docbook5' => '', 'backend-docbook5-doctype-book' => '', 'outfilesuffix' => '.xml', 'basebackend' => 'docbook', 'basebackend-docbook' => '', 'basebackend-docbook-doctype-book' => '', 'doctype' => 'book', 'doctype-book' => '', 'filetype' => 'xml', 'filetype-xml' => '', } expect.each do |key, val| assert doc.attributes.key?(key) assert_equal val, doc.attributes[key] end refute doc.attributes.key?('backend-html5') refute doc.attributes.key?('backend-html5-doctype-article') refute doc.attributes.key?('basebackend-html') refute doc.attributes.key?('basebackend-html-doctype-article') refute doc.attributes.key?('doctype-article') refute doc.attributes.key?('filetype-html') end test 'backend attributes defined in document options overrides backend attribute in document' do doc = document_from_string(':backend: docbook5', safe: Asciidoctor::SafeMode::SAFE, attributes: { 'backend' => 'html5' }) assert_equal 'html5', doc.attributes['backend'] assert doc.attributes.key? 'backend-html5' assert_equal 'html', doc.attributes['basebackend'] assert doc.attributes.key? 'basebackend-html' end test 'can only access a positional attribute from the attributes hash' do node = Asciidoctor::Block.new nil, :paragraph, attributes: { 1 => 'position 1' } assert_nil node.attr(1) refute node.attr?(1) assert_equal 'position 1', node.attributes[1] end test 'attr should not retrieve attribute from document if not set on block' do doc = document_from_string 'paragraph', :attributes => { 'name' => 'value' } para = doc.blocks[0] assert_nil para.attr 'name' end test 'attr looks for attribute on document if fallback name is true' do doc = document_from_string 'paragraph', :attributes => { 'name' => 'value' } para = doc.blocks[0] assert_equal 'value', (para.attr 'name', nil, true) end test 'attr uses fallback name when looking for attribute on document' do doc = document_from_string 'paragraph', :attributes => { 'alt-name' => 'value' } para = doc.blocks[0] assert_equal 'value', (para.attr 'name', nil, 'alt-name') end test 'attr? should not check for attribute on document if not set on block' do doc = document_from_string 'paragraph', :attributes => { 'name' => 'value' } para = doc.blocks[0] refute para.attr? 'name' end test 'attr? checks for attribute on document if fallback name is true' do doc = document_from_string 'paragraph', :attributes => { 'name' => 'value' } para = doc.blocks[0] assert para.attr? 'name', nil, true end test 'attr? checks for fallback name when looking for attribute on document' do doc = document_from_string 'paragraph', :attributes => { 'alt-name' => 'value' } para = doc.blocks[0] assert para.attr? 'name', nil, 'alt-name' end test 'set_attr should set value to empty string if no value is specified' do node = Asciidoctor::Block.new nil, :paragraph, attributes: {} node.set_attr 'foo' assert_equal '', (node.attr 'foo') end test 'remove_attr should remove attribute and return previous value' do doc = empty_document node = Asciidoctor::Block.new doc, :paragraph, attributes: { 'foo' => 'bar' } assert_equal 'bar', (node.remove_attr 'foo') assert_nil node.attr('foo') end test 'set_attr should not overwrite existing key if overwrite is false' do node = Asciidoctor::Block.new nil, :paragraph, attributes: { 'foo' => 'bar' } assert_equal 'bar', (node.attr 'foo') node.set_attr 'foo', 'baz', false assert_equal 'bar', (node.attr 'foo') end test 'set_attr should overwrite existing key by default' do node = Asciidoctor::Block.new nil, :paragraph, attributes: { 'foo' => 'bar' } assert_equal 'bar', (node.attr 'foo') node.set_attr 'foo', 'baz' assert_equal 'baz', (node.attr 'foo') end test 'set_attr should set header attribute in loaded document' do input = <<~'EOS' :uri: http://example.org {uri} EOS doc = Asciidoctor.load input, attributes: { 'uri' => 'https://github.com' } doc.set_attr 'uri', 'https://google.com' output = doc.convert assert_xpath '//a[@href="https://google.com"]', output, 1 end test 'set_attribute should set attribute if key is not locked' do doc = empty_document refute doc.attr? 'foo' res = doc.set_attribute 'foo', 'baz' assert res assert_equal 'baz', (doc.attr 'foo') end test 'set_attribute should not set key if key is locked' do doc = empty_document attributes: { 'foo' => 'bar' } assert_equal 'bar', (doc.attr 'foo') res = doc.set_attribute 'foo', 'baz' refute res assert_equal 'bar', (doc.attr 'foo') end test 'set_attribute should update backend attributes' do doc = empty_document attributes: { 'backend' => 'html5@' } assert_equal '', (doc.attr 'backend-html5') res = doc.set_attribute 'backend', 'docbook5' assert res refute doc.attr? 'backend-html5' assert_equal '', (doc.attr 'backend-docbook5') end test 'verify toc attribute matrix' do expected_data = <<~'EOS' #attributes |toc|toc-position|toc-placement|toc-class toc | |nil |auto |nil toc=header | |nil |auto |nil toc=beeboo | |nil |auto |nil toc=left | |left |auto |toc2 toc2 | |left |auto |toc2 toc=right | |right |auto |toc2 toc=preamble | |content |preamble |nil toc=macro | |content |macro |nil toc toc-placement=macro toc-position=left | |content |macro |nil toc toc-placement! | |content |macro |nil EOS expected = expected_data.lines.map do |l| next if l.start_with? '#' l.split('|').map {|e| (e = e.strip) == 'nil' ? nil : e } end.compact expected.each do |expect| raw_attrs, toc, toc_position, toc_placement, toc_class = expect attrs = Hash[*raw_attrs.split.map {|e| e.include?('=') ? e.split('=', 2) : [e, ''] }.flatten] doc = document_from_string '', attributes: attrs toc ? (assert doc.attr?('toc', toc)) : (refute doc.attr?('toc')) toc_position ? (assert doc.attr?('toc-position', toc_position)) : (refute doc.attr?('toc-position')) toc_placement ? (assert doc.attr?('toc-placement', toc_placement)) : (refute doc.attr?('toc-placement')) toc_class ? (assert doc.attr?('toc-class', toc_class)) : (refute doc.attr?('toc-class')) end end end context 'Interpolation' do test "convert properly with simple names" do html = convert_string(":frog: Tanglefoot\n:my_super-hero: Spiderman\n\nYo, {frog}!\nBeat {my_super-hero}!") assert_xpath %(//p[text()="Yo, Tanglefoot!\nBeat Spiderman!"]), html, 1 end test 'attribute lookup is not case sensitive' do input = <<~'EOS' :He-Man: The most powerful man in the universe He-Man: {He-Man} She-Ra: {She-Ra} EOS result = convert_string_to_embedded input, attributes: { 'She-Ra' => 'The Princess of Power' } assert_xpath '//p[text()="He-Man: The most powerful man in the universe"]', result, 1 assert_xpath '//p[text()="She-Ra: The Princess of Power"]', result, 1 end test "convert properly with single character name" do html = convert_string(":r: Ruby\n\nR is for {r}!") assert_xpath %(//p[text()="R is for Ruby!"]), html, 1 end test "collapses spaces in attribute names" do input = <<~'EOS' Main Header =========== :My frog: Tanglefoot Yo, {myfrog}! EOS output = convert_string input assert_xpath '(//p)[1][text()="Yo, Tanglefoot!"]', output, 1 end test 'ignores lines with bad attributes if attribute-missing is drop-line' do input = <<~'EOS' :attribute-missing: drop-line This is blah blah {foobarbaz} all there is. EOS output = convert_string_to_embedded input para = xmlnodes_at_css 'p', output, 1 refute_includes 'blah blah', para.content assert_message @logger, :WARN, 'dropping line containing reference to missing attribute: foobarbaz' end test "attribute value gets interpretted when converting" do doc = document_from_string(":google: http://google.com[Google]\n\n{google}") assert_equal 'http://google.com[Google]', doc.attributes['google'] output = doc.convert assert_xpath '//a[@href="http://google.com"][text() = "Google"]', output, 1 end test 'should drop line with reference to missing attribute if attribute-missing attribute is drop-line' do input = <<~'EOS' :attribute-missing: drop-line Line 1: This line should appear in the output. Line 2: Oh no, a {bogus-attribute}! This line should not appear in the output. EOS output = convert_string_to_embedded input assert_match(/Line 1/, output) refute_match(/Line 2/, output) assert_message @logger, :WARN, 'dropping line containing reference to missing attribute: bogus-attribute' end test 'should not drop line with reference to missing attribute by default' do input = <<~'EOS' Line 1: This line should appear in the output. Line 2: A {bogus-attribute}! This time, this line should appear in the output. EOS output = convert_string_to_embedded input assert_match(/Line 1/, output) assert_match(/Line 2/, output) assert_match(/\{bogus-attribute\}/, output) end test 'should drop line with attribute unassignment by default' do input = <<~'EOS' :a: Line 1: This line should appear in the output. Line 2: {set:a!}This line should not appear in the output. EOS output = convert_string_to_embedded input assert_match(/Line 1/, output) refute_match(/Line 2/, output) end test 'should not drop line with attribute unassignment if attribute-undefined is drop' do input = <<~'EOS' :attribute-undefined: drop :a: Line 1: This line should appear in the output. Line 2: {set:a!}This line should appear in the output. EOS output = convert_string_to_embedded input assert_match(/Line 1/, output) assert_match(/Line 2/, output) refute_match(/\{set:a!\}/, output) end test 'should drop line that only contains attribute assignment' do input = <<~'EOS' Line 1 {set:a} Line 2 EOS output = convert_string_to_embedded input assert_xpath %(//p[text()="Line 1\nLine 2"]), output, 1 end test 'should drop line that only contains unresolved attribute when attribute-missing is drop' do input = <<~'EOS' Line 1 {unresolved} Line 2 EOS output = convert_string_to_embedded input, attributes: { 'attribute-missing' => 'drop' } assert_xpath %(//p[text()="Line 1\nLine 2"]), output, 1 end test "substitutes inside unordered list items" do html = convert_string(":foo: bar\n* snort at the {foo}\n* yawn") assert_xpath %(//li/p[text()="snort at the bar"]), html, 1 end test 'substitutes inside section title' do output = convert_string(":prefix: Cool\n\n== {prefix} Title\n\ncontent") assert_xpath '//h2[text()="Cool Title"]', output, 1 assert_css 'h2#_cool_title', output, 1 end test 'interpolates attribute defined in header inside attribute entry in header' do input = <<~'EOS' = Title Author Name :attribute-a: value :attribute-b: {attribute-a} preamble EOS doc = document_from_string(input, parse_header_only: true) assert_equal 'value', doc.attributes['attribute-b'] end test 'interpolates author attribute inside attribute entry in header' do input = <<~'EOS' = Title Author Name :name: {author} preamble EOS doc = document_from_string(input, parse_header_only: true) assert_equal 'Author Name', doc.attributes['name'] end test 'interpolates revinfo attribute inside attribute entry in header' do input = <<~'EOS' = Title Author Name 2013-01-01 :date: {revdate} preamble EOS doc = document_from_string(input, parse_header_only: true) assert_equal '2013-01-01', doc.attributes['date'] end test 'attribute entries can resolve previously defined attributes' do input = <<~'EOS' = Title Author Name v1.0, 2010-01-01: First release! :a: value :a2: {a} :revdate2: {revdate} {a} == {a2} {revdate} == {revdate2} EOS doc = document_from_string input assert_equal '2010-01-01', doc.attr('revdate') assert_equal '2010-01-01', doc.attr('revdate2') assert_equal 'value', doc.attr('a') assert_equal 'value', doc.attr('a2') output = doc.convert assert_includes output, 'value == value' assert_includes output, '2010-01-01 == 2010-01-01' end test 'should warn if unterminated block comment is detected in document header' do input = <<~'EOS' = Document Title :foo: bar //// :hey: there content EOS doc = document_from_string input assert_nil doc.attr('hey') assert_message @logger, :WARN, '<stdin>: line 3: unterminated comment block', Hash end test 'substitutes inside block title' do input = <<~'EOS' :gem_name: asciidoctor .Require the +{gem_name}+ gem To use {gem_name}, the first thing to do is to import it in your Ruby source file. EOS output = convert_string_to_embedded input, attributes: { 'compat-mode' => '' } assert_xpath '//*[@class="title"]/code[text()="asciidoctor"]', output, 1 input = <<~'EOS' :gem_name: asciidoctor .Require the `{gem_name}` gem To use {gem_name}, the first thing to do is to import it in your Ruby source file. EOS output = convert_string_to_embedded input assert_xpath '//*[@class="title"]/code[text()="asciidoctor"]', output, 1 end test 'sets attribute until it is deleted' do input = <<~'EOS' :foo: bar Crossing the {foo}. :foo!: Belly up to the {foo}. EOS output = convert_string_to_embedded input assert_xpath '//p[text()="Crossing the bar."]', output, 1 assert_xpath '//p[text()="Belly up to the bar."]', output, 0 end test 'should allow compat-mode to be set and unset in middle of document' do input = <<~'EOS' :foo: bar [[paragraph-a]] `{foo}` :compat-mode!: [[paragraph-b]] `{foo}` :compat-mode: [[paragraph-c]] `{foo}` EOS result = convert_string_to_embedded input, attributes: { 'compat-mode' => '@' } assert_xpath '/*[@id="paragraph-a"]//code[text()="{foo}"]', result, 1 assert_xpath '/*[@id="paragraph-b"]//code[text()="bar"]', result, 1 assert_xpath '/*[@id="paragraph-c"]//code[text()="{foo}"]', result, 1 end test 'does not disturb attribute-looking things escaped with backslash' do html = convert_string(":foo: bar\nThis is a \\{foo} day.") assert_xpath '//p[text()="This is a {foo} day."]', html, 1 end test 'does not disturb attribute-looking things escaped with literals' do html = convert_string(":foo: bar\nThis is a +++{foo}+++ day.") assert_xpath '//p[text()="This is a {foo} day."]', html, 1 end test 'does not substitute attributes inside listing blocks' do input = <<~'EOS' :forecast: snow ---- puts 'The forecast for today is {forecast}' ---- EOS output = convert_string(input) assert_match(/\{forecast\}/, output) end test 'does not substitute attributes inside literal blocks' do input = <<~'EOS' :foo: bar .... You insert the text {foo} to expand the value of the attribute named foo in your document. .... EOS output = convert_string(input) assert_match(/\{foo\}/, output) end test 'does not show docdir and shows relative docfile if safe mode is SERVER or greater' do input = <<~'EOS' * docdir: {docdir} * docfile: {docfile} EOS docdir = Dir.pwd docfile = File.join(docdir, 'sample.adoc') output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SERVER, attributes: { 'docdir' => docdir, 'docfile' => docfile } assert_xpath '//li[1]/p[text()="docdir: "]', output, 1 assert_xpath '//li[2]/p[text()="docfile: sample.adoc"]', output, 1 end test 'shows absolute docdir and docfile paths if safe mode is less than SERVER' do input = <<~'EOS' * docdir: {docdir} * docfile: {docfile} EOS docdir = Dir.pwd docfile = File.join(docdir, 'sample.adoc') output = convert_string_to_embedded input, safe: Asciidoctor::SafeMode::SAFE, attributes: { 'docdir' => docdir, 'docfile' => docfile } assert_xpath %(//li[1]/p[text()="docdir: #{docdir}"]), output, 1 assert_xpath %(//li[2]/p[text()="docfile: #{docfile}"]), output, 1 end test 'assigns attribute defined in attribute reference with set prefix and value' do input = '{set:foo:bar}{foo}' output = convert_string_to_embedded input assert_xpath '//p', output, 1 assert_xpath '//p[text()="bar"]', output, 1 end test 'assigns attribute defined in attribute reference with set prefix and no value' do input = "{set:foo}\n{foo}yes" output = convert_string_to_embedded input assert_xpath '//p', output, 1 assert_xpath '//p[normalize-space(text())="yes"]', output, 1 end test 'assigns attribute defined in attribute reference with set prefix and empty value' do input = "{set:foo:}\n{foo}yes" output = convert_string_to_embedded input assert_xpath '//p', output, 1 assert_xpath '//p[normalize-space(text())="yes"]', output, 1 end test 'unassigns attribute defined in attribute reference with set prefix' do input = <<~'EOS' :attribute-missing: drop-line :foo: {set:foo!} {foo}yes EOS output = convert_string_to_embedded input assert_xpath '//p', output, 1 assert_xpath '//p/child::text()', output, 0 end end context "Intrinsic attributes" do test "substitute intrinsics" do Asciidoctor::INTRINSIC_ATTRIBUTES.each_pair do |key, value| html = convert_string("Look, a {#{key}} is here") # can't use Nokogiri because it interprets the HTML entities and we can't match them assert_match(/Look, a #{Regexp.escape(value)} is here/, html) end end test "don't escape intrinsic substitutions" do html = convert_string('happy{nbsp}together') assert_match(/happy&#160;together/, html) end test "escape special characters" do html = convert_string('<node>&</node>') assert_match(/&lt;node&gt;&amp;&lt;\/node&gt;/, html) end test 'creates counter' do input = '{counter:mycounter}' doc = document_from_string input output = doc.convert assert_equal 1, doc.attributes['mycounter'] assert_xpath '//p[text()="1"]', output, 1 end test 'creates counter silently' do input = '{counter2:mycounter}' doc = document_from_string input output = doc.convert assert_equal 1, doc.attributes['mycounter'] assert_xpath '//p[text()="1"]', output, 0 end test 'creates counter with numeric seed value' do input = '{counter2:mycounter:10}' doc = document_from_string input doc.convert assert_equal 10, doc.attributes['mycounter'] end test 'creates counter with character seed value' do input = '{counter2:mycounter:A}' doc = document_from_string input doc.convert assert_equal 'A', doc.attributes['mycounter'] end test 'increments counter with numeric value' do input = <<~'EOS' :mycounter: 1 {counter:mycounter} {mycounter} EOS doc = document_from_string input output = doc.convert assert_equal 2, doc.attributes['mycounter'] assert_xpath '//p[text()="2"]', output, 2 end test 'increments counter with character value' do input = <<~'EOS' :mycounter: @ {counter:mycounter} {mycounter} EOS doc = document_from_string input output = doc.convert assert_equal 'A', doc.attributes['mycounter'] assert_xpath '//p[text()="A"]', output, 2 end test 'counter uses 0 as seed value if seed attribute is nil' do input = <<~'EOS' :mycounter: {counter:mycounter} {mycounter} EOS doc = document_from_string input output = doc.convert header_footer: false assert_equal 1, doc.attributes['mycounter'] assert_xpath '//p[text()="1"]', output, 2 end test 'counter value can be reset by attribute entry' do input = <<~'EOS' :mycounter: before: {counter:mycounter} {counter:mycounter} {counter:mycounter} :mycounter!: after: {counter:mycounter} EOS doc = document_from_string input output = doc.convert header_footer: false assert_equal 1, doc.attributes['mycounter'] assert_xpath '//p[text()="before: 1 2 3"]', output, 1 assert_xpath '//p[text()="after: 1"]', output, 1 end test 'nested document should use counter from parent document' do input = <<~'EOS' .Title for Foo image::foo.jpg[] [cols="2*a"] |=== | .Title for Bar image::bar.jpg[] | .Title for Baz image::baz.jpg[] |=== .Title for Qux image::qux.jpg[] EOS output = convert_string_to_embedded input assert_xpath '//div[@class="title"]', output, 4 assert_xpath '//div[@class="title"][text() = "Figure 1. Title for Foo"]', output, 1 assert_xpath '//div[@class="title"][text() = "Figure 2. Title for Bar"]', output, 1 assert_xpath '//div[@class="title"][text() = "Figure 3. Title for Baz"]', output, 1 assert_xpath '//div[@class="title"][text() = "Figure 4. Title for Qux"]', output, 1 end end context 'Block attributes' do test 'parses attribute names as name token' do input = <<~'EOS' [normal,foo="bar",_foo="_bar",foo1="bar1",foo-foo="bar-bar",foo.foo="bar.bar"] content EOS block = block_from_string input assert_equal 'bar', block.attr('foo') assert_equal '_bar', block.attr('_foo') assert_equal 'bar1', block.attr('foo1') assert_equal 'bar-bar', block.attr('foo-foo') assert_equal 'bar.bar', block.attr('foo.foo') end test 'positional attributes assigned to block' do input = <<~'EOS' [quote, author, source] ____ A famous quote. ____ EOS doc = document_from_string(input) qb = doc.blocks.first assert_equal 'quote', qb.style assert_equal 'author', qb.attr('attribution') assert_equal 'author', qb.attr(:attribution) assert_equal 'author', qb.attributes['attribution'] assert_equal 'source', qb.attributes['citetitle'] end test 'normal substitutions are performed on single-quoted positional attribute' do input = <<~'EOS' [quote, author, 'http://wikipedia.org[source]'] ____ A famous quote. ____ EOS doc = document_from_string(input) qb = doc.blocks.first assert_equal 'quote', qb.style assert_equal 'author', qb.attr('attribution') assert_equal 'author', qb.attr(:attribution) assert_equal 'author', qb.attributes['attribution'] assert_equal '<a href="http://wikipedia.org">source</a>', qb.attributes['citetitle'] end test 'normal substitutions are performed on single-quoted named attribute' do input = <<~'EOS' [quote, author, citetitle='http://wikipedia.org[source]'] ____ A famous quote. ____ EOS doc = document_from_string(input) qb = doc.blocks.first assert_equal 'quote', qb.style assert_equal 'author', qb.attr('attribution') assert_equal 'author', qb.attr(:attribution) assert_equal 'author', qb.attributes['attribution'] assert_equal '<a href="http://wikipedia.org">source</a>', qb.attributes['citetitle'] end test 'normal substitutions are performed once on single-quoted named title attribute' do input = <<~'EOS' [title='*title*'] content EOS output = convert_string_to_embedded input assert_xpath '//*[@class="title"]/strong[text()="title"]', output, 1 end test 'attribute list may not begin with space' do input = <<~'EOS' [ quote] ____ A famous quote. ____ EOS doc = document_from_string input b1 = doc.blocks.first assert_equal ['[ quote]'], b1.lines end test 'attribute list may begin with comma' do input = <<~'EOS' [, author, source] ____ A famous quote. ____ EOS doc = document_from_string input qb = doc.blocks.first assert_equal 'quote', qb.style assert_equal 'author', qb.attributes['attribution'] assert_equal 'source', qb.attributes['citetitle'] end test 'first attribute in list may be double quoted' do input = <<~'EOS' ["quote", "author", "source", role="famous"] ____ A famous quote. ____ EOS doc = document_from_string input qb = doc.blocks.first assert_equal 'quote', qb.style assert_equal 'author', qb.attributes['attribution'] assert_equal 'source', qb.attributes['citetitle'] assert_equal 'famous', qb.attributes['role'] end test 'first attribute in list may be single quoted' do input = <<~'EOS' ['quote', 'author', 'source', role='famous'] ____ A famous quote. ____ EOS doc = document_from_string input qb = doc.blocks.first assert_equal 'quote', qb.style assert_equal 'author', qb.attributes['attribution'] assert_equal 'source', qb.attributes['citetitle'] assert_equal 'famous', qb.attributes['role'] end test 'attribute with value None without quotes is ignored' do input = <<~'EOS' [id=None] paragraph EOS doc = document_from_string input para = doc.blocks.first refute para.attributes.key?('id') end test 'role? returns true if role is assigned' do input = <<~'EOS' [role="lead"] A paragraph EOS doc = document_from_string input p = doc.blocks.first assert p.role? end test 'role? does not return true if role attribute is set on document' do input = <<~'EOS' :role: lead A paragraph EOS doc = document_from_string input p = doc.blocks.first refute p.role? end test 'role? can check for exact role name match' do input = <<~'EOS' [role="lead"] A paragraph EOS doc = document_from_string input p = doc.blocks.first assert p.role?('lead') p2 = doc.blocks.last refute p2.role?('final') end test 'has_role? can check for precense of role name' do input = <<~'EOS' [role="lead abstract"] A paragraph EOS doc = document_from_string input p = doc.blocks.first refute p.role?('lead') assert p.has_role?('lead') end test 'has_role? does not look for role defined as document attribute' do input = <<~'EOS' :role: lead abstract A paragraph EOS doc = document_from_string input p = doc.blocks.first refute p.has_role?('lead') end test 'roles returns array of role names' do input = <<~'EOS' [role="story lead"] A paragraph EOS doc = document_from_string input p = doc.blocks.first assert_equal ['story', 'lead'], p.roles end test 'roles returns empty array if role attribute is not set' do input = 'a paragraph' doc = document_from_string input p = doc.blocks.first assert_equal [], p.roles end test 'roles does not return value of roles document attribute' do input = <<~'EOS' :role: story lead A paragraph EOS doc = document_from_string input p = doc.blocks.first assert_equal [], p.roles end test "Attribute substitutions are performed on attribute list before parsing attributes" do input = <<~'EOS' :lead: role="lead" [{lead}] A paragraph EOS doc = document_from_string(input) para = doc.blocks.first assert_equal 'lead', para.attributes['role'] end test 'id, role and options attributes can be specified on block style using shorthand syntax' do input = <<~'EOS' [literal#first.lead%step] A literal paragraph. EOS doc = document_from_string(input) para = doc.blocks.first assert_equal :literal, para.context assert_equal 'first', para.attributes['id'] assert_equal 'lead', para.attributes['role'] assert para.attributes.key?('step-option') refute para.attributes.key?('options') end test 'id, role and options attributes can be specified using shorthand syntax on block style using multiple block attribute lines' do input = <<~'EOS' [literal] [#first] [.lead] [%step] A literal paragraph. EOS doc = document_from_string(input) para = doc.blocks.first assert_equal :literal, para.context assert_equal 'first', para.attributes['id'] assert_equal 'lead', para.attributes['role'] assert para.attributes.key?('step-option') refute para.attributes.key?('options') end test 'multiple roles and options can be specified in block style using shorthand syntax' do input = <<~'EOS' [.role1%option1.role2%option2] Text EOS doc = document_from_string input para = doc.blocks.first assert_equal 'role1 role2', para.attributes['role'] assert para.attributes.key?('option1-option') assert para.attributes.key?('option2-option') refute para.attributes.key?('options') end test 'options specified using shorthand syntax on block style across multiple lines should be additive' do input = <<~'EOS' [%option1] [%option2] Text EOS doc = document_from_string input para = doc.blocks.first assert para.attributes.key?('option1-option') assert para.attributes.key?('option2-option') refute para.attributes.key?('options') end test 'roles specified using shorthand syntax on block style across multiple lines should be additive' do input = <<~'EOS' [.role1] [.role2.role3] Text EOS doc = document_from_string input para = doc.blocks.first assert_equal 'role1 role2 role3', para.attributes['role'] end test 'setting a role using the role attribute replaces any existing roles' do input = <<~'EOS' [.role1] [role=role2] [.role3] Text EOS doc = document_from_string input para = doc.blocks.first assert_equal 'role2 role3', para.attributes['role'] end test 'setting a role using the shorthand syntax on block style should not clear the ID' do input = <<~'EOS' [#id] [.role] Text EOS doc = document_from_string input para = doc.blocks.first assert_equal 'id', para.id assert_equal 'role', para.role end test 'a role can be added using add_role when the node has no roles' do input = 'A normal paragraph' doc = document_from_string(input) para = doc.blocks.first res = para.add_role 'role1' assert res assert_equal 'role1', para.attributes['role'] assert para.has_role? 'role1' end test 'a role can be added using add_role when the node already has a role' do input = <<~'EOS' [.role1] A normal paragraph EOS doc = document_from_string(input) para = doc.blocks.first res = para.add_role 'role2' assert res assert_equal 'role1 role2', para.attributes['role'] assert para.has_role? 'role1' assert para.has_role? 'role2' end test 'a role is not added using add_role if the node already has that role' do input = <<~'EOS' [.role1] A normal paragraph EOS doc = document_from_string(input) para = doc.blocks.first res = para.add_role 'role1' refute res assert_equal 'role1', para.attributes['role'] assert para.has_role? 'role1' end test 'an existing role can be removed using remove_role' do input = <<~'EOS' [.role1.role2] A normal paragraph EOS doc = document_from_string(input) para = doc.blocks.first res = para.remove_role 'role1' assert res assert_equal 'role2', para.attributes['role'] assert para.has_role? 'role2' refute para.has_role?('role1') end test 'roles are removed when last role is removed using remove_role' do input = <<~'EOS' [.role1] A normal paragraph EOS doc = document_from_string(input) para = doc.blocks.first res = para.remove_role 'role1' assert res refute para.role? assert_nil para.attributes['role'] refute para.has_role? 'role1' end test 'roles are not changed when a non-existent role is removed using remove_role' do input = <<~'EOS' [.role1] A normal paragraph EOS doc = document_from_string(input) para = doc.blocks.first res = para.remove_role 'role2' refute res assert_equal 'role1', para.attributes['role'] assert para.has_role? 'role1' refute para.has_role?('role2') end test 'roles are not changed when using remove_role if the node has no roles' do input = 'A normal paragraph' doc = document_from_string(input) para = doc.blocks.first res = para.remove_role 'role1' refute res assert_nil para.attributes['role'] refute para.has_role?('role1') end test 'option can be specified in first position of block style using shorthand syntax' do input = <<~'EOS' [%interactive] - [x] checked EOS doc = document_from_string input list = doc.blocks.first assert list.attributes.key? 'interactive-option' refute list.attributes.key? 'options' end test 'id and role attributes can be specified on section style using shorthand syntax' do input = <<~'EOS' [dedication#dedication.small] == Section Content. EOS output = convert_string_to_embedded input assert_xpath '/div[@class="sect1 small"]', output, 1 assert_xpath '/div[@class="sect1 small"]/h2[@id="dedication"]', output, 1 end test 'id attribute specified using shorthand syntax should not create a special section' do input = <<~'EOS' [#idname] == Section content EOS doc = document_from_string input, backend: 'docbook' section = doc.blocks[0] refute_nil section assert_equal :section, section.context refute section.special output = doc.convert assert_css 'article:root > section', output, 1 assert_css 'article:root > section[xml|id="idname"]', output, 1 end test "Block attributes are additive" do input = <<~'EOS' [id='foo'] [role='lead'] A paragraph. EOS doc = document_from_string(input) para = doc.blocks.first assert_equal 'foo', para.id assert_equal 'lead', para.attributes['role'] end test "Last wins for id attribute" do input = <<~'EOS' [[bar]] [[foo]] == Section paragraph [[baz]] [id='coolio'] === Section EOS doc = document_from_string(input) sec = doc.first_section assert_equal 'foo', sec.id subsec = sec.blocks.last assert_equal 'coolio', subsec.id end test "trailing block attributes transfer to the following section" do input = <<~'EOS' [[one]] == Section One paragraph [[sub]] // try to mess this up! === Sub-section paragraph [role='classy'] //// block comment //// == Section Two content EOS doc = document_from_string(input) section_one = doc.blocks.first assert_equal 'one', section_one.id subsection = section_one.blocks.last assert_equal 'sub', subsection.id section_two = doc.blocks.last assert_equal 'classy', section_two.attr(:role) end end end
31.509874
150
0.613754
3318d5cf900026fb6f3275778967d850542da754
447
class CreateUnitOfMeasures < ActiveRecord::Migration[5.0] def change create_table :unit_of_measures do |t| t.string :name, null: false t.string :description t.string :code, null: false t.integer :uom_type, default: 0, null: false t.decimal :ratio, precision: 8, scale: 2, null: false t.integer :uom_category_id t.timestamps end add_index :unit_of_measures, :code, :unique => true end end
27.9375
59
0.668904
e8997ea5b917df561b30fabd92a4ea4423bb3f2e
76
json.extract! @post, :id, :title, :body, :user_id, :created_at, :updated_at
38
75
0.697368
617306862fe45bc407eb7fdd59387eb3e7b0784f
500
require 'pact/provider/rspec' require_relative "provider_states_for_zoo_app" class AnimalService def call env response_body = {} if env['PATH_INFO'] == '/alligators' response_body = {'name' => 'Bob'}.to_json end [200, {'Content-Type' => 'application/json'}, [response_body]] end end Pact.service_provider 'Animal Service' do app do AnimalService.new end honours_pact_with "Zoo App" do pact_uri '../zoo-app/spec/pacts/zoo_app-animal_service.json' end end
20.833333
66
0.696
e9eccf61a4f46600029f7fc75589dfc39dfbd716
1,258
module Idv class SsnForm include ActiveModel::Model ATTRIBUTES = [:ssn].freeze attr_accessor :ssn validates :ssn, presence: true validates_format_of :ssn, with: /\A\d{3}-?\d{2}-?\d{4}\z/, message: I18n.t('idv.errors.pattern_mismatch.ssn'), allow_blank: false def self.model_name ActiveModel::Name.new(self, nil, 'Ssn') end def initialize(user) @user = user end def submit(params) consume_params(params) FormResponse.new(success: valid?, errors: errors, extra: extra_analytics_attributes) end def ssn_is_unique? return false if ssn.nil? @ssn_is_unique ||= DuplicateSsnFinder.new( ssn: ssn, user: @user, ).ssn_is_unique? end def extra_analytics_attributes { ssn_is_unique: ssn_is_unique?, } end private def consume_params(params) params.each do |key, value| raise_invalid_ssn_parameter_error(key) unless ATTRIBUTES.include?(key.to_sym) send("#{key}=", value) end end def raise_invalid_ssn_parameter_error(key) raise ArgumentError, "#{key} is an invalid ssn attribute" end end end
22.070175
90
0.605723
33b2616e723b0b66a956bc1069b71e953677d5d4
1,576
module Overviews class Engine < ::Rails::Engine engine_name :overviews include OpenProject::Plugins::ActsAsOpEngine initializer 'overviews.menu' do ::Redmine::MenuManager.map(:project_menu) do |menu| menu.push(:overview, { controller: '/overviews/overviews', action: 'show' }, caption: :'overviews.label', param: :project_id, first: true, icon: 'icon2 icon-info1') end end initializer 'overviews.permissions' do OpenProject::AccessControl.permission(:view_project) .actions .push('overviews/overviews/show') OpenProject::AccessControl.map do |ac_map| ac_map.project_module nil do |map| map.permission :manage_overview, 'overviews/overviews': ['show'], public: true end end end initializer 'overviews.patches' do unless ::OpenProject::TextFormatting::Formats::Markdown::TextileConverter .included_modules .include?(Overviews::Patches::TextileConverterPatch) ::OpenProject::TextFormatting::Formats::Markdown::TextileConverter.include(Overviews::Patches::TextileConverterPatch) end end initializer 'overviews.conversion' do require Rails.root.join('config', 'constants', 'ar_to_api_conversions') Constants::ARToAPIConversions.add('grids/overview': 'grid') end config.to_prepare do Overviews::GridRegistration.register! end end end
30.901961
125
0.623731
ffbaf2f5a859ea2677d2d6291329c57216acab04
907
# frozen_string_literal: true RSpec::Matchers.define :have_mime_type do |expected| match do |actual| @actual = actual.mime_type values_match?(expected, @actual) end failure_message do |actual| msg = [] msg << %(expected that response of "#{resource}" has mime type "#{expected}", but has "#{actual}".) msg << if proxy.nil? || proxy.empty? %(No proxy was used.) else %(It was fetched via proxy "#{proxy}".) end msg.join ' ' end failure_message_when_negated do msg = [] msg << %(expected that response of "#{resource}" does not have mime type "#{expected}".) msg << if proxy.nil? || proxy.empty? %(No proxy was used.) else %(It was fetched via proxy "#{proxy}".) end msg.join ' ' end end RSpec::Matchers.alias_matcher :be_of_mime_type, :have_mime_type
23.868421
103
0.584344
189ef5ae950b400148242d60aeb93728b32c89e3
673
$:.unshift(File.dirname(__FILE__)) unless $:.include?(File.dirname(__FILE__)) || $:.include?(File.expand_path(File.dirname(__FILE__))) require 'active_support/all' require 'rubigen/base' require 'rubigen/lookup' require 'rubigen/commands' RubiGen::Base.send(:include, RubiGen::Lookup) RubiGen::Base.send(:include, RubiGen::Commands) # Set up a default logger for convenience. require 'rubigen/simple_logger' RubiGen::Base.logger = RubiGen::SimpleLogger.new(STDOUT) # Use self as default lookup algorithm # If your framework needs to subclass RubiGen::Base, then # assign it to #active after initialising rubigen and your code. RubiGen::Base.active = RubiGen::Base
30.590909
94
0.76523
213885dfe79de7966d3367960a5742c14cc2720f
146
class AddApiTitleToYoutubeVideos < ActiveRecord::Migration def change add_column :youtube_videos, :api_title, :string, after: :id end end
24.333333
63
0.773973
d5dc06bc221b9873071fe207e2bc007c7bd1ccf4
535
# Get twilio-ruby from twilio.com/docs/ruby/install require 'rubygems' # This line not needed for ruby > 1.8 require 'twilio-ruby' # Get your Account Sid and Auth Token from twilio.com/user/account account_sid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' auth_token = 'your_auth_token' @client = Twilio::REST::Client.new account_sid, auth_token # Get an object from its sid. If you do not have a sid, # check out the list resource examples on this page @call = @client.account.calls.get('CA42ed11f93dc08b952027ffbc406d0868') puts @call.to
38.214286
71
0.779439
ac96aa3c0db8ab37928b5b3fc289ede517e775e7
1,870
# frozen_string_literal: true # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! require "gapic/common" require "gapic/config" require "gapic/config/method" require "google/ads/google_ads/version" require "google/ads/google_ads/v7/services/dynamic_search_ads_search_term_view_service/credentials" require "google/ads/google_ads/v7/services/dynamic_search_ads_search_term_view_service/paths" require "google/ads/google_ads/v7/services/dynamic_search_ads_search_term_view_service/client" module Google module Ads module GoogleAds module V7 module Services ## # Service to fetch dynamic search ads views. # # To load this service and instantiate a client: # # require "google/ads/google_ads/v7/services/dynamic_search_ads_search_term_view_service" # client = ::Google::Ads::GoogleAds::V7::Services::DynamicSearchAdsSearchTermViewService::Client.new # module DynamicSearchAdsSearchTermViewService end end end end end end helper_path = ::File.join __dir__, "dynamic_search_ads_search_term_view_service", "helpers.rb" require "google/ads/google_ads/v7/services/dynamic_search_ads_search_term_view_service/helpers" if ::File.file? helper_path
35.961538
123
0.745455
e8748f9a6dd5e9e1689059f0fc51a3a998b0528d
1,405
# frozen_string_literal: true # installer for dotfiles # author: Playstay require 'optparse' require 'pathname' require 'fileutils' LN_OPTION = { verbose: true }.freeze def link_files(source, destination, fileutil, ignore_files) source.each_child do |dir| next if ignore_files.include?(dir.basename.to_s) next if dir.basename.to_s.end_with?('~') if dir.directory? link_files(dir, destination, fileutil, ignore_files) next end copy_file(destination, dir, fileutil) end end def copy_file(destination, dir, fileutil) # FIXME: Pathnameใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นใŒ่ฆชใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใฎใŸใ‚ไปฎๆƒณใฎใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใ‚’ๆŒ‡ๅฎšใ—ใชใ„ใจใ„ใ‘ใชใ„ target_dir = dir.expand_path(destination + './hoge') fileutil.makedirs(target_dir.parent.to_s, **LN_OPTION) unless target_dir.exist? fileutil.ln_s(dir.expand_path.to_s, target_dir.to_s, **LN_OPTION) end def ignore_list(additional = nil) ignore_files = Pathname.new('./.default_ignore').readlines(chomp: true) ignore_files.append(additional) unless additional.nil? ignore_files end opt = OptionParser.new dest_dir = Pathname(ENV['HOME']) fileutil = FileUtils opt.on('-d DIRECTORY', '--directory DIRECTORY', 'install specificied directory') do |dir| dest_dir = Pathname(dir) end opt.on('-D', '--debug') do |_v| fileutil = FileUtils::DryRun end opt.parse(ARGV) # ็ตถๅฏพใƒ‘ใ‚นใงใฏๅฎŸ่ฃ…ใŒ้›ฃใ—ใ„ใฎใง็›ธๅฏพใƒ‘ใ‚นใงๅฎŸ่ฃ… source_dir = Pathname('../') link_files(source_dir, dest_dir, fileutil, ignore_list)
24.224138
89
0.744484
014d4d3dc3c758ad3c06c82f524db0e894876e97
4,190
# frizen_string_literal: true require 'redis' require 'connection_pool' require_relative './middleware_chain' module MultiBackgroundJob class Config class << self private def attribute_accessor(field, validator: nil, normalizer: nil, default: nil) normalizer ||= :"normalize_#{field}" validator ||= :"validate_#{field}" define_method(field) do unless instance_variable_defined?(:"@#{field}") fallback = config_from_yaml[field.to_s] || default return if fallback.nil? send(:"#{field}=", fallback.respond_to?(:call) ? fallback.call : fallback) end instance_variable_get(:"@#{field}") end define_method(:"#{field}=") do |value| value = send(normalizer, field, value) if respond_to?(normalizer, true) send(validator, field, value) if respond_to?(validator, true) instance_variable_set(:"@#{field}", value) end end end # Path to the YAML file with configs attr_accessor :config_path # ConnectionPool options for redis attribute_accessor :redis_pool_size, default: 5, normalizer: :normalize_to_int, validator: :validate_greater_than_zero attribute_accessor :redis_pool_timeout, default: 5, normalizer: :normalize_to_int, validator: :validate_greater_than_zero # Namespace used to manage internal data like unique job verification data. attribute_accessor :redis_namespace, default: 'multi-bg' # List of configurations to be passed along to the Redis.new attribute_accessor :redis_config, default: {} # A Hash with all workers definitions. The worker class name must be the main hash key # Example: # "Accounts::ConfirmationEmailWorker": # retry: false # queue: "mailer" # "Elastic::BatchIndex": # retry: 5 # queue: "elasticsearch" # adapter: "faktory" attribute_accessor :workers, default: {} # Does not validate if it's when set to false attribute_accessor :strict, default: true alias strict? strict # Global disable the unique_job_active attribute_accessor :unique_job_active, default: false alias unique_job_active? unique_job_active def worker_options(class_name) class_name = class_name.to_s if strict? && !workers.key?(class_name) raise NotDefinedWorker.new(class_name) end workers.fetch(class_name, {}) end def redis_pool { size: redis_pool_size, timeout: redis_pool_timeout, } end def middleware @middleware ||= MiddlewareChain.new yield @middleware if block_given? @middleware end def config_path=(value) @config_from_yaml = nil @config_path = value end private def normalize_to_int(_attribute, value) value.to_i end def validate_greater_than_zero(attribute, value) return if value > 0 raise InvalidConfig, format( 'The %<value>p for %<attr>s is not valid. It must be greater than zero', value: value, attr: attribute, ) end def normalize_redis_config(_attribute, value) case value when String { url: value } when Hash value.each_with_object({}) { |(k, v), r| r[k.to_sym] = v } else value end end def validate_redis_config(attribute, value) return if value.is_a?(Hash) raise InvalidConfig, format( 'The %<value>p for %<attr>i is not valid. It must be a Hash with the redis initialization options. ' + 'See https://github.com/redis/redis-rb for all available options', value: value, attr: attribute, ) end def normalize_workers(_, value) return unless value.is_a?(Hash) hash = {} value.each do |class_name, opts| hash[class_name.to_s] = MultiJson.load(MultiJson.dump(opts), symbolize_names: true) end hash end def config_from_yaml @config_from_yaml ||= begin config_path ? YAML.load_file(config_path) : {} rescue Errno::ENOENT, Errno::ESRCH {} end end end end
27.385621
125
0.643198
87b50894691650535eb17d642ed8cf9962f29435
86
module Ravelry module Errors class Configuration < StandardError; end end end
14.333333
44
0.755814
01c54558c58f055b0933c1836320c350f2989f4a
945
require 'sidekiq-scheduler' require_relative 'job_presenter' module SidekiqScheduler # Hook into *Sidekiq::Web* Sinatra app which adds a new '/recurring-jobs' page module Web VIEW_PATH = File.expand_path('../../../web/views', __FILE__) def self.registered(app) app.get '/recurring-jobs' do @presented_jobs = JobPresenter.build_collection(Sidekiq.schedule!) erb File.read(File.join(VIEW_PATH, 'recurring_jobs.erb')) end app.get '/recurring-jobs/:name/enqueue' do schedule = Sidekiq.get_schedule(params[:name]) SidekiqScheduler::Scheduler.enqueue_job(schedule) redirect "#{root_path}recurring-jobs" end app.get '/recurring-jobs/:name/toggle' do Sidekiq.reload_schedule! SidekiqScheduler::Scheduler.toggle_job_enabled(params[:name]) redirect "#{root_path}recurring-jobs" end end end end require_relative 'extensions/web'
27
80
0.687831
ed0523517b678de01864bf6b070b9cb37797743b
61
class Car < ActiveRecord::Base include Storext.model end
10.166667
30
0.754098
080c36033bf623830770f99d6782f4ac1417f93d
764
Pod::Spec.new do |s| s.name = 'Stacksift' s.version = '0.3.5' s.summary = 'Capture and submit crashes to Stacksift' s.homepage = 'https://github.com/stacksift/SDK' s.license = { :type => 'BSD-3-Clause', :file => 'LICENSE' } s.author = { 'Matt Massicotte' => '[email protected]' } s.social_media_url = 'https://twitter.com/chimehq' s.source = { :git => 'https://github.com/stacksift/SDK.git', :tag => s.version } s.source_files = 'Sources/**/*.swift' s.osx.deployment_target = '10.13' s.ios.deployment_target = '12.0' s.tvos.deployment_target = '12.0' s.cocoapods_version = '>= 1.4.0' s.swift_version = '5.0' s.dependency 'Wells', '~> 0.1.4' s.dependency 'Impact', '~> 0.3.8' end
30.56
89
0.592932
4adf2c708f8d7d0d4d877ce4d428d499c37f04fd
824
class StudentDistributionResolver < ApplicationQuery include AuthorizeReviewer property :course_id property :coach_id property :coach_notes property :tags def student_distribution course.levels.map do |level| teams = TeamsResolver.filter_by_coach(teams_in_level(level), coach_id) teams = TeamsResolver.filter_by_coach_notes(teams, coach_notes) teams = TeamsResolver.filter_by_tags(teams, tags) team_ids = teams.select(:id).distinct(:id) students_in_level = Founder.where(startup: team_ids).count { id: level.id, number: level.number, students_in_level: students_in_level, teams_in_level: team_ids.count, unlocked: level.unlocked? } end end private def teams_in_level(level) level.startups.active end end
24.235294
76
0.709951
39e466268d1789a15a9228adfac52c34635e24d8
2,146
# encoding: UTF-8 # This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # Note that this schema.rb definition is the authoritative source for your # database schema. If you need to create the application database on another # system, you should be using db:schema:load, not running all the migrations # from scratch. The latter is a flawed and unsustainable approach (the more migrations # you'll amass, the slower it'll run and the greater likelihood for issues). # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 20150817161700) do create_table "accounts", force: :cascade do |t| t.string "business", null: false t.string "contact" t.integer "age" t.date "last_contact_on" t.datetime "created_at", null: false t.datetime "updated_at", null: false end create_table "bulky_bulk_updates", force: :cascade do |t| t.text "ids", null: false t.text "updates", null: false t.integer "initiated_by_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "bulky_bulk_updates", ["initiated_by_id"], name: "index_bulky_bulk_updates_on_initiated_by_id" create_table "bulky_updated_records", force: :cascade do |t| t.integer "bulk_update_id", null: false t.integer "updatable_id", null: false t.string "updatable_type", null: false t.text "updatable_changes", null: false t.string "error_message" t.text "error_backtrace" t.datetime "created_at", null: false t.datetime "updated_at", null: false end add_index "bulky_updated_records", ["bulk_update_id"], name: "index_bulky_updated_records_on_bulk_update_id" add_index "bulky_updated_records", ["updatable_type", "updatable_id"], name: "index_bulky_updated_records_on_updatable_type_and_updatable_id" end
42.92
143
0.715284
795d7831e1f388a15b7dd8554c6bf84c2201dc51
190
class GoogleApi include HTTParty base_uri 'https://www.googleapis.com' def verify_id_token(id_token) self.class.get('/oauth2/v3/tokeninfo', query: {id_token: id_token}) end end
21.111111
71
0.736842
211a119025331f3148d3c48d5dc279fb1defb57f
183
module Magnum module TimeZone class Minute def initialize(start_time,end_time) @start_time = start_time @end_time = end_time end end end end
14.076923
41
0.63388
f817ba9aa85de13f094d7ae115ea385b17845a1f
1,306
require "spec_helper" RSpec.describe Endpoints::Infections do include Committee::Test::Methods include Rack::Test::Methods def app Routes end def schema_path "./schema/schema.json" end describe 'POST /infections/:id' do before do @negan = Survivor.create(name:'Negan',age:50,gender:'male',password:'password') @wilson = Survivor.create(name:'Wilson',age:40,gender:'male',password:'password') @negan.updated_at @wilson.updated_at @negan.save @wilson.save end context 'with logged on user' do before do post '/login', {name: 'Negan', password: 'password'} end it 'returns created status code and conforms to schema' do header "Content-Type", "application/json" post "/infections/#{@wilson.id}", MultiJson.encode({}) assert_equal 201, last_response.status assert_schema_conform end end context 'with non-logged on user' do before do post '/logout' end it 'returns unauthorized status code and conforms to schema' do header "Content-Type", "application/json" post "/infections/#{@wilson.id}", MultiJson.encode({}) assert_equal 401, last_response.status assert_schema_conform end end end end
25.607843
87
0.643185
ace4004c5e812146214dc7da8f50d37dea0ae89b
56
json.data do json.things_to_measure @measurements end
14
38
0.821429
1a0b0f7a27c3af4456cf4665f3efe5f289791a8e
3,934
# encoding: utf-8 # # This file is a part of Redmine Invoices (redmine_contacts_invoices) plugin, # invoicing plugin for Redmine # # Copyright (C) 2011-2013 Kirill Bezrukov # http://www.redminecrm.com/ # # redmine_contacts_invoices is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # redmine_contacts_invoices is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with redmine_contacts_invoices. If not, see <http://www.gnu.org/licenses/>. module ExpensesHelper def expense_status_tag(expense) status_tag = content_tag(:span, expense_status_name(expense.status_id)) content_tag(:span, status_tag, :class => "tag-label-color expense-status #{expense_status_name(expense.status_id, true).to_s}") end def expense_status_name(status, code=false) return (code ? "draft" : l(:label_expense_status_draft)) unless collection_expense_statuses.map{|v| v[1]}.include?(status) status_data = collection_expense_statuses.select{|s| s[1] == status }.first[0] status_name = collection_expense_status_names.select{|s| s[1] == status}.first[0] return (code ? status_name : status_data) end def collection_expense_status_names [[:draft, Expense::DRAFT_EXPENSE], [:new, Expense::NEW_EXPENSE], [:billed, Expense::BILLED_EXPENSE], [:paid, Expense::PAID_EXPENSE]] end def collection_expense_statuses [[l(:label_expense_status_draft), Expense::DRAFT_EXPENSE], [l(:label_expense_status_new), Expense::NEW_EXPENSE], [l(:label_expense_status_billed), Expense::BILLED_EXPENSE], [l(:label_expense_status_paid), Expense::PAID_EXPENSE]] end def collection_for_expense_status_for_select(status_id) collection = collection_expense_statuses.map{|s| [s[0], s[1].to_s]} collection.insert 0, [l(:label_open_issues), "o"] collection.insert 0, [l(:label_all), ""] options_for_select(collection, status_id) end def expenses_is_no_filters (params[:status_id] == 'o' && (params[:period].blank? || params[:period] == 'all') && params[:contact_id].blank? && params[:is_billable].blank?) end def expenses_to_csv(expenses) decimal_separator = l(:general_csv_decimal_separator) encoding = 'utf-8' export = FCSV.generate(:col_sep => l(:general_csv_separator)) do |csv| # csv header fields headers = [ "#", 'Expense date', 'Price', 'Currency', 'Description', 'Contact', 'Status', 'Created', 'Updated' ] custom_fields = ExpenseCustomField.all custom_fields.each {|f| headers << f.name} # Description in the last column csv << headers.collect {|c| Redmine::CodesetUtil.from_utf8(c.to_s, encoding) } # csv lines expenses.each do |expense| fields = [expense.id, format_date(expense.expense_date), expense.price, expense.currency, expense.description, !expense.contact.blank? ? expense.contact.name : '', expense.status, format_date(expense.created_at), format_date(expense.updated_at) ] expense.custom_field_values.each {|custom_value| fields << RedmineContacts::CSVUtils.csv_custom_value(custom_value) } csv << fields.collect {|c| Redmine::CodesetUtil.from_utf8(c.to_s, encoding) } end end export end end
38.194175
148
0.665735
03b56cc8d1a1c8c5131a70a8f68e24178071cb48
263
module OpenActive module Models module Schema class ArriveAction < ::OpenActive::Models::Schema::MoveAction # @!attribute type # @return [String] def type "schema:ArriveAction" end end end end end
18.785714
67
0.585551
7a62a19db1c61e53632a794eca4678e78572ee5f
288
require_relative '../setup.rb' require_relative '../src/shared/system.rb' FILES = ['./src/compiler/_requires.rb'].freeze check = ARGV.last == '--check' FILES.each do |file| if check psystem("sort #{file} | diff #{file} -") else psystem("sort #{file} -o #{file}") end end
19.2
46
0.631944
01ae4e2b14cc7efff12624562b1ce75227608551
232
require 'aruba/cucumber' Before do copy File.join(aruba.config.fixtures_path_prefix, 'blueprint.apib'), 'blueprint.apib' copy File.join(aruba.config.fixtures_path_prefix, 'invalid_blueprint.apib'), 'invalid_blueprint.apib' end
33.142857
103
0.797414
f77c2327618c83a32a3280e4b9e18530d328747f
7,095
# Este controlador tiene la finalidad de hacer contenido por paginas, ej la lista de invasoras class PaginasController < ApplicationController skip_before_action :set_locale layout Proc.new{['exoticas_invasoras_paginado'].include?(action_name) ? false : 'application_b3'} # La pagina cuando entran por get def exoticas_invasoras lee_csv @tabla_exoticas[:cabeceras] = ['', 'Nombre cientรญfico', 'Familia', 'Grupo', 'Ambiente', 'Origen', 'Presencia', 'Estatus', 'Instrumento legal', 'Ficha'] end # La resultados que provienen del paginado def exoticas_invasoras_paginado lee_csv render partial: 'exoticas_invasoras' end protected def lee_csv @tabla_exoticas = {} @tabla_exoticas[:datos] = [] opciones_posibles opciones_seleccionadas file = File.dirname(__FILE__) << '/../../public/exoticas_invasoras/exoticas-invasoras.csv' exoticas_url = '/pdfs/exoticas_invasoras/' instrumentos_url = '/pdfs/exoticas_invasoras/instrumentos_legales/' exoticas_dir = File.dirname(__FILE__) << '/../../public' << exoticas_url inst_dir = File.dirname(__FILE__) << '/../../public' << instrumentos_url csv_text = File.read(file) csv = CSV.parse(csv_text, :headers => true) @por_pagina = 30 @pagina = params[:pagina].present? ? params[:pagina].to_i : 1 @totales = 0 # Cuenta los que han pasado el filtro csv.each_with_index do |row, index| next unless condiciones_filtros(row) @totales+= 1 next if (@por_pagina*(@pagina-1)+1) > @totales || @por_pagina*@pagina < @totales # Por si esta fuera de rango del paginado pdf = false datos = [] t = if row['enciclovida_id'].present? begin Especie.find(row['enciclovida_id']) rescue nil end else nil end if t datos << t.adicional.try(:foto_principal) datos << t if familia = t.ancestors.left_joins(:categoria_taxonomica).where("#{CategoriaTaxonomica.attribute_alias(:nombre_categoria_taxonomica)} = 'familia'") datos << familia.first.nombre_cientifico else datos << nil end datos << row['Grupo'] pdf_path = exoticas_dir + t.nombre_cientifico + '.pdf' pdf = exoticas_url + t.nombre_cientifico + '.pdf' if File.exist?(pdf_path) else # Para poner una foto de la carpeta, si es que tiene if row['Creditos Fotos'].present? nombre = "#{row['Nombre cientรญfico']}.jpg" foto = Rails.root.join('public','fotos_invasoras', nombre) if File.exists?(foto) foto_url = "/fotos_invasoras/#{nombre}" datos << foto_url else datos << nil end else datos << nil end datos << row['Nombre cientรญfico'] datos << row['Familia'] datos << row['Grupo'] pdf_path = exoticas_dir + row['Nombre cientรญfico'] + '.pdf' pdf = exoticas_url + row['Nombre cientรญfico'] + '.pdf' if File.exist?(pdf_path) end # End con id enciclovida datos << row['Ambiente'] #datos << row['DistribuciรณnNativa'] #datos << row['DistribuciรณnInvasora'] datos << row['Origen'] datos << row['Presencia'] datos << row['Estatus'] instrumentos = [] if row['Regulada por otros instrumentos'].present? row['Regulada por otros instrumentos'].split('/').each do |inst| inst = inst.strip pdf_inst_path = inst_dir + inst + '.pdf' if File.exist?(pdf_inst_path) pdf_inst = instrumentos_url + inst + '.pdf' instrumentos << {nombre: inst, pdf: pdf_inst} else # Por si esta mal renombrado el pdf instrumentos << {nombre: 'No existe pdf', pdf: nil} end end # End each do end datos << instrumentos pdf.present? ? datos << pdf : datos << nil @tabla_exoticas[:datos] << datos end # End each row # El paginado @paginas = @totales%@por_pagina == 0 ? @totales/@por_pagina : (@totales/@por_pagina) +1 end def opciones_posibles @select = {} @select[:grupos] = ['Algas y protoctistas', 'Anfibios', 'Arรกcnidos', 'Aves', 'Crustรกceos', 'Hongos', 'Insectos', 'Mamรญferos', 'Moluscos', 'Otros invertebrados', 'Peces', 'Plantas', 'Reptiles', 'Virus y bacterias'] @select[:origenes] = ['Criptogรฉnica', 'Exรณtica', 'Nativa', 'Nativa/Exรณtica', 'Se desconoce'] @select[:presencias] = ['Ausente', 'Confinado', 'Indeterminada', 'Por confirmar', 'Presente', 'Se desconoce'] @select[:instrumentos_legales] = ['Acuerdo enfermedades y plagas SAGARPA 2016', 'Acuerdo especies exรณticas SEMARNAT', 'MOD NOM-005-FITO-1995', 'NOM-016-SEMARNAT-2013', 'NOM-043-FITO-1999'] @select[:ambientes] = ['Dulceacuรญcola', 'Marino', 'Salobre', 'Terrestre', 'Se desconoce'] # Se necesita estandarizar @select[:estatus] = ['Invasora', 'No invasora'] @select[:fichas] = ['Sรญ', 'No'] end def opciones_seleccionadas @selected = {} if params[:grupo].present? @selected[:grupo] = {} @selected[:grupo][:valor] = params[:grupo] @selected[:grupo][:nom_campo] = 'Grupo' end if params[:origen].present? @selected[:origen] = {} @selected[:origen][:valor] = params[:origen] @selected[:origen][:nom_campo] = 'Origen' end if params[:presencia].present? @selected[:presencia] = {} @selected[:presencia][:valor] = params[:presencia] @selected[:presencia][:nom_campo] = 'Presencia' end if params[:instrumento].present? @selected[:instrumento] = {} @selected[:instrumento][:valor] = params[:instrumento] @selected[:instrumento][:nom_campo] = 'Regulada por otros instrumentos' end if params[:ambiente].present? @selected[:ambiente] = {} @selected[:ambiente][:valor] = params[:ambiente] @selected[:ambiente][:nom_campo] = 'Ambiente' end if params[:estatus].present? @selected[:estatus] = {} @selected[:estatus][:valor] = params[:estatus] @selected[:estatus][:nom_campo] = 'Estatus' end if params[:ficha].present? @selected[:ficha] = {} @selected[:ficha][:valor] = params[:ficha] @selected[:ficha][:nom_campo] = 'Ficha' end end def condiciones_filtros(row) @selected.each do |campo, v| # Compara que las condiciones se cumplan if v[:nom_campo] == 'Ficha' if v[:valor] == 'Sรญ' if row[v[:nom_campo]].blank? return false end else if row[v[:nom_campo]].present? return false end end else if row[v[:nom_campo]].blank? # Si es vacio entonces no coincide return false end val_params = v[:valor].split('/') val_excel = row[v[:nom_campo]].gsub('/ ', '/').split('/') return false unless (val_params & val_excel).present? end end # End @selected.each true end end
32.695853
217
0.603383
b94fb400393c29d4c96cb060614b3acd37294e96
1,069
cask 'mullvadvpn-beta' do version '2019.7-beta1' sha256 '71f0322c35bcd93b9f29dcf58a8e88b409fb143cd52abf5edd254ef4f3aa45d9' # github.com/mullvad/mullvadvpn-app was verified as official when first introduced to the cask url "https://github.com/mullvad/mullvadvpn-app/releases/download/#{version}/MullvadVPN-#{version}.pkg" appcast 'https://github.com/mullvad/mullvadvpn-app/releases.atom' name 'Mullvad' homepage 'https://mullvad.net/' conflicts_with cask: 'mullvadvpn' pkg "MullvadVPN-#{version}.pkg" uninstall pkgutil: 'net.mullvad.vpn', quit: 'net.mullvad.vpn', launchctl: 'net.mullvad.daemon' zap trash: [ '~/Library/Application Support/Mullvad VPN', '~/Library/Application Support/com.apple.sharedfilelist/com.apple.LSSharedFileList.ApplicationRecentDocuments/net.mullvad.vpn.sfl*', '~/Library/Logs/Mullvad VPN', '~/Library/Preferences/net.mullvad.vpn.plist', '~/Library/Preferences/net.mullvad.vpn.helper.plist', ] end
39.592593
147
0.684752
1d908db0972b2e62cc9a4dfc9710b1ec7edaf086
3,129
class UsersController < ApplicationController get '/' do redirect to '/login' end get '/signup' do if logged_in? flash[:signed_up] = "You already have an account and are logged in." redirect to "/users/#{current_user.slug}" else erb :'/users/signup' end end post '/signup' do if params[:password] != params[:password_confirmation] flash[:password_mismatch] = "Passwords do not match. Please try again." redirect to '/signup' elsif params[:email].downcase != params[:email_confirmation].downcase flash[:email_mismatch] = "Email addresses do not match. Please try again." redirect to '/signup' elsif User.find_by(email: params[:email]) flash[:email_already_in_use] = "An account with this email address already exists. Please try again." redirect to '/signup' elsif User.find_by(username: params[:username]) flash[:username_already_in_use] = "An account with this username already exists. Please try again." redirect to '/signup' elsif params[:password] == params[:password_confirmation] && params[:email] == params[:email_confirmation] user = User.create(name: params[:name], username: params[:username].downcase, email: params[:email].downcase, email_confirmation: params[:email_confirmation].downcase, password: params[:password], password_confirmation: params[:password_confirmation]) session[:user_id] = user.id flash[:new_account_success] = "Account creation successful. You are now logged in." redirect to "/users/#{user.slug}" end end get '/login' do if logged_in? redirect to "/users/#{current_user.slug}" else erb :'/users/login' end end post '/login' do user = User.find_by(:email => params[:email]) if user.try(:authenticate, params[:password]) session[:user_id] = user.id redirect to "/users/#{current_user.slug}" else flash[:login_failure] = "Email or password did not match our records. Please try again." redirect "/login" end end get '/logout' do if logged_in? session.clear redirect to '/login' else erb :'/users/login' end end get '/users/:slug' do if logged_in? if current_user.id == User.find_by_slug(params[:slug]).id @user = current_user reservations = Reservation.all @reservations = reservations.sort_by { |reservation| reservation.date } erb :'/users/show' else flash[:view_other_user_account] = "You cannot view another user's account page." redirect to "/users/#{current_user.slug}" end else flash[:view_account_failure] = "You must be logged in to view your account page." redirect to '/login' end end end
38.158537
263
0.590284
381753d7e88d7d378649fbd6784e3ffd3f117f29
2,678
require 'formula' class Openssl < Formula homepage 'http://openssl.org' url 'https://www.openssl.org/source/openssl-1.0.1f.tar.gz' mirror 'http://mirrors.ibiblio.org/openssl/source/openssl-1.0.1f.tar.gz' sha256 '6cc2a80b17d64de6b7bac985745fdaba971d54ffd7d38d3556f998d7c0c9cb5a' bottle do sha1 "2687c0abb5e23d765bbd0024a010e36b05a8939e" => :mavericks sha1 "dcaee2f1e51e8d0da7614e6dab4fc334f736d0de" => :mountain_lion sha1 "4fabb39f5db46e8e62bf0b05e0133cd7e717860a" => :lion end keg_only :provided_by_osx, "The OpenSSL provided by OS X is too old for some software." def install args = %W[./Configure --prefix=#{prefix} --openssldir=#{openssldir} zlib-dynamic shared ] if MacOS.prefer_64_bit? args << "darwin64-x86_64-cc" << "enable-ec_nistp_64_gcc_128" # -O3 is used under stdenv, which results in test failures when using clang inreplace 'Configure', %{"darwin64-x86_64-cc","cc:-arch x86_64 -O3}, %{"darwin64-x86_64-cc","cc:-arch x86_64 -Os} setup_makedepend_shim else args << "darwin-i386-cc" end system "perl", *args ENV.deparallelize system "make", "depend" if MacOS.prefer_64_bit? system "make" system "make", "test" system "make", "install", "MANDIR=#{man}", "MANSUFFIX=ssl" end def setup_makedepend_shim path = buildpath/"brew/makedepend" path.write <<-EOS.undent #!/bin/sh exec "#{ENV.cc}" -M "$@" EOS path.chmod 0755 ENV.prepend_path 'PATH', path.parent end def openssldir etc/"openssl" end def cert_pem openssldir/"cert.pem" end def osx_cert_pem openssldir/"osx_cert.pem" end def write_pem_file system "security find-certificate -a -p /Library/Keychains/System.keychain > '#{osx_cert_pem}.tmp'" system "security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> '#{osx_cert_pem}.tmp'" system "mv", "-f", "#{osx_cert_pem}.tmp", osx_cert_pem end def post_install openssldir.mkpath if cert_pem.exist? write_pem_file else cert_pem.unlink if cert_pem.symlink? write_pem_file openssldir.install_symlink 'osx_cert.pem' => 'cert.pem' end end test do (testpath/'testfile.txt').write("This is a test file") expected_checksum = "91b7b0b1e27bfbf7bc646946f35fa972c47c2d32" system "#{bin}/openssl", 'dgst', '-sha1', '-out', 'checksum.txt', 'testfile.txt' open("checksum.txt") do |f| checksum = f.read(100).split("=").last.strip assert_equal checksum, expected_checksum end end end
27.326531
127
0.662061
f7eb7f3ce3752d941233a2ad3c5a634781f828ce
402
# -*- coding: utf-8 -*- #-- # Copyright (C) 2004 Mauricio Julio Fernรกndez Pradier # See LICENSE.txt for additional licensing information. #++ module Gem::Package::FSyncDir private ## # make sure this hits the disc def fsync_dir(dirname) dir = open dirname, 'r' dir.fsync rescue # ignore IOError if it's an unpatched (old) Ruby ensure dir.close if dir rescue nil end end
16.75
57
0.674129