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
03a98f45592dffdb17d7586473d67b4f612d50f7
652
class Experience < ApplicationRecord belongs_to :head EXP_TYPE_COMPANY = 0 EXP_TYPE_SCHOOL = 1 EXP_TYPES = [ EXP_TYPE_COMPANY, EXP_TYPE_SCHOOL ] validates :head, presence: true validates :place, presence: true validates :title, presence: true validates :exp_type, presence: true, inclusion: {in: EXP_TYPES} validates :year_start, numericality: { only_integer: true }, allow_nil: false validates :year_end, numericality: { only_integer: true }, allow_nil: true before_save :on_before_save def on_before_save ye = (self.year_end || "0").to_i ye = nil if ye == 0 # FE side self.year_end = ye end end
23.285714
79
0.707055
87788c8f878a106addf8dfa5bfbacc6a7b728638
272
Then /^I should see error in provider side fields:$/ do |table| table.rows.each do |field| assert has_xpath?(".//*[ label[normalize-space(text()) = '#{field.first}'] ]/..//p[@class='inline-errors']"), "Field '#{field.first}' with error not found" end end
38.857143
113
0.625
abae52d8a41951b36317e37602113190a3c040f3
8,912
require 'erb' module YARD module Generators class Base include Helpers::BaseHelper include Helpers::FilterHelper class << self def template_paths @@template_paths ||= [TEMPLATE_ROOT] end ## # Convenience method to registering a template path. # Equivalent to calling: # GeneratorName.template_paths.unshift(path) # # @param [String] path # the pathname to look for the template # # @see template_paths def register_template_path(path) template_paths.unshift(path) end def before_section(*args) if args.size == 1 before_section_filters.push [nil, args.first] elsif args.size == 2 before_section_filters.push(args) else raise ArgumentError, "before_section takes a generator followed by a Proc/lambda or Symbol referencing the method name" end end def before_section_filters @before_section_filters ||= [] end def before_generate(meth) before_generate_filters.push(meth) end def before_generate_filters @before_generate_filters ||= [] end def before_list(meth) before_list_filters.push(meth) end def before_list_filters @before_list_filters ||= [] end end # Creates a generator by adding extra options # to the options hash. # # @example [Creates a new MethodSummaryGenerator for public class methods] # G(MethodSummaryGenerator, :scope => :class, :visibility => :public) # # @param [Class] generator # the generator class to use. # # @option opts :ignore_serializer [Boolean] (true) whether or not the serializer is ignored. # def G(generator, opts = {}) opts = SymbolHash[:ignore_serializer => true].update(opts) generator.new(options, opts) end attr_reader :format, :template, :verifier attr_reader :serializer, :ignore_serializer attr_reader :options attr_reader :current_object def initialize(opts = {}, extra_opts = {}) opts = SymbolHash[ :format => :html, :template => :default, :markup => :rdoc, :serializer => nil, :verifier => nil ].update(opts).update(extra_opts) @options = opts @format = options[:format] @template = options[:template] @serializer = options[:serializer] @ignore_serializer = options[:ignore_serializer] @verifier = options[:verifier] extend Helpers::HtmlHelper if format == :html end def generator_name self.class.to_s.split("::").last.gsub(/Generator$/, '').downcase end def generate(*list, &block) output = "" list = list.flatten @current_object = Registry.root return output if FalseClass === run_before_list(list) serializer.before_serialize if serializer && !ignore_serializer list.each do |object| next unless object && object.is_a?(CodeObjects::Base) objout = "" @current_object = object next if call_verifier(object).is_a?(FalseClass) next if run_before_generate(object).is_a?(FalseClass) objout << render_sections(object, &block) if serializer && !ignore_serializer && !objout.empty? serializer.serialize(object, objout) end output << objout end if serializer && !ignore_serializer serializer.after_serialize(output) end output end protected def call_verifier(object) if verifier.is_a?(Symbol) send(verifier, object) elsif verifier.respond_to?(:call) verifier.call(self, object) end end def run_before_list(list) self.class.before_list_filters.each do |meth| meth = method(meth) if meth.is_a?(Symbol) result = meth.call *(meth.arity == 0 ? [] : [list]) return result if result.is_a?(FalseClass) end end def run_before_generate(object) self.class.before_generate_filters.each do |meth| meth = method(meth) if meth.is_a?(Symbol) result = meth.call *(meth.arity == 0 ? [] : [object]) return result if result.is_a?(FalseClass) end end def run_before_sections(section, object) result = before_section(section, object) return result if result.is_a?(FalseClass) self.class.before_section_filters.each do |info| result, sec, meth = nil, *info if sec.nil? || sec == section meth = method(meth) if meth.is_a?(Symbol) args = [section, object] if meth.arity == 1 args = [object] elsif meth.arity == 0 args = [] end result = meth.call(*args) log.debug("Calling before section filter for %s%s with `%s`, result = %s" % [ self.class.class_name, section.inspect, object, result.is_a?(FalseClass) ? 'fail' : 'pass' ]) end return result if result.is_a?(FalseClass) end end def sections_for(object); [] end def before_section(section, object); end def render_sections(object, sections = nil) sections ||= sections_for(object) || [] data = "" sections.each_with_index do |section, index| next if section.is_a?(Array) data << if sections[index+1].is_a?(Array) render_section(section, object) do |obj| tmp, @current_object = @current_object, obj out = render_sections(obj, sections[index+1]) @current_object = tmp out end else render_section(section, object) end end data end def render_section(section, object, &block) begin if section.is_a?(Class) && section <= Generators::Base opts = options.dup opts.update(:ignore_serializer => true) sobj = section.new(opts) sobj.generate(object, &block) elsif section.is_a?(Generators::Base) section.generate(object, &block) elsif section.is_a?(Symbol) || section.is_a?(String) return "" if run_before_sections(section, object).is_a?(FalseClass) if section.is_a?(Symbol) if respond_to?(section) if method(section).arity != 1 send(section, &block) else send(section, object, &block) end || "" else # treat it as a String render(object, section, &block) end else render(object, section, &block) end else type = section.is_a?(String) || section.is_a?(Symbol) ? 'section' : 'generator' log.warn "Ignoring invalid #{type} '#{section}' in #{self.class}" "" end end end def render(object, file = nil, locals = {}, &block) if object.is_a?(Symbol) object, file, locals = current_object, object, (file||{}) end path = template_path(file.to_s + '.erb', generator_name) filename = find_template(path) if filename begin render_method(object, filename, locals, &block) rescue => e log.error "#{e.class.class_name}: #{e.message}" log.error "in generator #{self.class}: #{filename}" log.error e.backtrace[0..10].join("\n") exit end else log.warn "Cannot find template `#{path}`" "" end end def render_method(object, filename, locals = {}, &block) l = locals.map {|k,v| "#{k} = locals[#{k.inspect}]" }.join(";") src = erb("<% #{l} %>" + File.read(filename)).src instance_eval(src, filename, 1) end def erb(str) ERB.new(str, nil, '<>') end def template_path(file, generator = generator_name) File.join(template.to_s, generator, format.to_s, file.to_s) end def find_template(path) self.class.template_paths.each do |basepath| f = File.join(basepath, path) return f if File.file?(f) end nil end end end end
30.83737
131
0.541741
915884bac32fc2278993271aaf0410b6c0d42f8a
2,090
# This is an example test for Sauce Labs and Appium. # It expects SAUCE_USERNAME and SAUCE_ACCESS_KEY to be set in your environment. # # Before this test will work, you may need to do: # # gem install rspec selenium-webdriver rest-client # # Run with: # # rspec sauce_example.rb require 'rspec' require 'selenium-webdriver' require 'json' require 'rest_client' APP_PATH = 'http://appium.s3.amazonaws.com/TestApp6.0.app.zip' SAUCE_USERNAME = ENV['SAUCE_USERNAME'] SAUCE_ACCESS_KEY = ENV['SAUCE_ACCESS_KEY'] AUTH_DETAILS = "#{SAUCE_USERNAME}:#{SAUCE_ACCESS_KEY}" # This is the test itself describe "Computation" do before(:each) do @driver = Selenium::WebDriver.for(:remote, :desired_capabilities => capabilities, :url => server_url) end after(:each) do # Get the success by checking for assertion exceptions, # and log them against the job, which is exposed by the session_id job_id = @driver.send(:bridge).session_id update_job_success(job_id, example.exception.nil?) @driver.quit end it "should add two numbers" do values = [rand(10), rand(10)] expected_sum = values.reduce(&:+) elements = @driver.find_elements(:tag_name, 'textField') elements.each_with_index do |element, index| element.send_keys values[index] end @driver.find_elements(:tag_name, 'button')[0].click @driver.find_elements(:tag_name, 'staticText')[0].text.should eq expected_sum.to_s end end def capabilities { 'browserName' => 'iOS 6.0', 'platform' => 'Mac 10.8', 'device' => 'iPhone Simulator', 'app' => APP_PATH, 'name' => 'Ruby Example for Appium', } end def server_url "http://#{AUTH_DETAILS}@ondemand.saucelabs.com:80/wd/hub" end def rest_jobs_url "https://#{AUTH_DETAILS}@saucelabs.com/rest/v1/#{SAUCE_USERNAME}/jobs" end # Because WebDriver doesn't have the concept of test failure, use the Sauce # Labs REST API to record job success or failure def update_job_success(job_id, success) RestClient.put "#{rest_jobs_url}/#{job_id}", {"passed" => success}.to_json, :content_type => :json end
29.027778
105
0.710048
62fe58a69d86d9c2a2b2b94cdf380871a1d67139
212
# frozen_string_literal: true class CreateFields < ActiveRecord::Migration[5.0] def change create_table :fields do |t| t.string :name_en t.string :name_pl t.timestamps end end end
16.307692
49
0.674528
26f7cc624989e9e1efb741479d1a23ed7962e7dd
333
Paperclip::Attachment.default_options[:url] = ':s3_domain_url' Paperclip::Attachment.default_options[:path] = '/:class/:attachment/:id_partition/:style/:filename' Paperclip::Attachment.default_options[:s3_host_name] = 's3.amazonaws.com' Mime::Type.unregister(:pdf) Mime::Type.register "application/force-download", :pdf, [], %w(pdf)
55.5
99
0.768769
0807ded13aaff865424c9f019f0cf232c26abdc1
287
class CreatePublishes < ActiveRecord::Migration[6.1] def change create_table :publishes do |t| t.datetime :PublishDate t.references :publisher, null: false, foreign_key: true t.references :book, null: false, foreign_key: true t.timestamps end end end
26.090909
61
0.69338
395b38a25c38a750104b797cd45cf2857ac30372
6,667
require 'rails_helper' include AuthHelper include Requests::JsonHelpers RSpec.describe UsersController, :type => :controller do render_views describe 'GET index' do context 'not logged in as admin' do before { get :index } it { should redirect_to new_session_path(continue: request.fullpath) } end context "logged in as admin" do let!(:user) { manager_basic_login } let!(:user_outside_organization) { FactoryBot.create(:pro_user) } let!(:user_inside_organization) { FactoryBot.create(:pro_user, organization: user.organization) } before { get :index } it { expect(assigns(:users)).to match_array([user, user_inside_organization]) } end end describe 'GET edit' do context 'not logged in as admin' do before { get :edit, params: { id: 0 } } it { should redirect_to new_session_path(continue: request.fullpath) } end context 'logged in as admin' do let!(:user) { manager_basic_login } before { get :edit, params: { id: user.id } } it { should render_template 'edit' } end end describe 'post create' do context 'not logged in as admin' do before { post 'create' } it { should redirect_to new_session_path } end context "logged in as admin" do let!(:user) { manager_basic_login } context 'with incorrect parameters' do it "retuns 302" do post 'create', params: { user: {key: "value"} } expect(response.status).to eq(200) expect(response).to render_template('index') expect(User.count).to eq(1) end end context 'with correct parameters' do let(:sms_service) { spy } before do allow(SmsNotificationService).to receive(:new).and_return(sms_service) end subject do post 'create', params: { user: {email: "[email protected]", first_name:"tester", last_name:"tested", phone:'+33102030405'}, send_sms: '1' } end context 'for a new user' do before { subject } it { expect(response.status).to eq(302) } it { expect(User.last.first_name).to eq "tester" } it { expect(User.last.last_name).to eq "tested" } it { expect(User.last.phone).to eq "+33102030405" } it { expect(User.last.email).to eq "[email protected]" } it { expect(User.last.organization).to eq user.organization } it { expect(sms_service).to have_received(:send_notification) } end context 'for an existing user' do before do create :public_user, phone: "+33102030405", first_name: "existing", last_name: nil, email: nil subject end it { expect(response.status).to eq(302) } it { expect(User.last.first_name).to eq "existing" } it { expect(User.last.last_name).to eq "tested" } it { expect(User.last.phone).to eq "+33102030405" } it { expect(User.last.email).to eq "[email protected]" } it { expect(User.last.organization).to eq user.organization } it { expect(sms_service).to_not have_received(:send_notification) } end end it "doesn't sends sms" do expect_any_instance_of(SmsNotificationService).to_not receive(:send_notification) post 'create', params: { user: {email: "[email protected]", first_name:"tester", last_name:"tested", phone:'+33102030405'}, send_sms: "0" } end context 'with incorrect parameters' do let!(:user_already_exist) { FactoryBot.create(:pro_user, phone: '+33102030405') } it "never sends sms" do expect_any_instance_of(SmsNotificationService).to_not receive(:send_notification) post 'create', params: { user: {email: "[email protected]", first_name:"tester", last_name:"tested", phone:'+33102030405'}, send_sms: "1" } end end end end describe 'put update' do context 'with incorrect user id' do it "retuns 404" do admin_basic_login expect { put 'update', params: { id: 1, user: {key: "value"} } }.to raise_error(ActiveRecord::RecordNotFound) end end context "logged in" do let!(:user) { admin_basic_login } context 'with correct user id and parameters' do before do put 'update', params: { id: user.id, user: {email: "change#{user.email}", first_name:"change#{user.first_name}", last_name:"change#{user.last_name}"} } end it { expect(response.status).to eq(302) } it { expect(User.find(user.id).first_name).to eq "change#{user.first_name}" } it { expect(User.find(user.id).last_name).to eq "change#{user.last_name}" } it { expect(User.find(user.id).email).to eq "change#{user.email}" } it { expect(User.find(user.id).organization).to eq user.organization } end end end describe 'delete destroy' do context 'with incorrect user id' do it "retuns 404" do admin_basic_login expect { delete 'destroy', params: { id: 1 } }.to raise_error(ActiveRecord::RecordNotFound) end end context 'with correct user id' do it "Redirects" do user = admin_basic_login delete 'destroy', params: { id: user.id } expect(response.status).to eq(302) end it "removes the user from the organization and disable it's pro features" do admin = admin_basic_login user = create :pro_user, organization: admin.organization delete 'destroy', params: { id: user.id } deleted_user = User.find_by(id: user.id) expect(deleted_user.organization_id).to eq(nil) expect(deleted_user.user_type).to eq('public') end end end describe '#send_sms' do let!(:user) { admin_basic_login } let!(:target_user) { FactoryBot.create(:pro_user, organization: user.organization) } context 'the user exists' do before { post 'send_sms', params: { id: target_user.id } } it { expect(response.status).to eq(302) } it "sends sms" do UserServices::SmsCode.any_instance.stub(:code) { "666666" } expect_any_instance_of(SmsNotificationService).to receive(:send_notification).with(target_user.phone, "666666 est votre code de connexion Entourage. Bienvenue dans le réseau solidaire.", 'regenerate') post 'send_sms', params: { id: target_user.id } end end context 'the user does not exists' do it "retuns 404" do expect { post 'send_sms', params: { id: 0 } }.to raise_error(ActiveRecord::RecordNotFound) end end end end
35.462766
208
0.627869
acbdf356eebcb439e1fc09ffd82110a6645269b7
77
require_relative '../../../../stdlib/rdoc/markup/' + File.basename(__FILE__)
38.5
76
0.675325
18f52a8ec4525007e65af7c5a438d620ef9f31c0
894
cask "logos" do version "9.3.0.0052" sha256 "569e175d9a2092744044cee82e467ce50edac3e7ebac6410cd51491e9113279d" url "https://downloads.logoscdn.com/LBS#{version.major}/Installer/#{version}/LogosMac.dmg", verified: "downloads.logoscdn.com/" name "Logos" desc "Bible study software" homepage "https://www.logos.com/" livecheck do url "https://clientservices.logos.com/update/v1/feed/logos#{version.major}-mac/stable.xml" strategy :page_match regex(%r{<logos:version[^>]*>(\d+(?:\.\d+)*)</logos:version>}i) end auto_updates true depends_on macos: ">= :mojave" app "Logos.app" uninstall launchctl: "com.logos.LogosIndexer", quit: "com.logos.Logos" zap trash: [ "~/Library/Preferences/com.logos.LogosIndexer.plist", "~/Library/Preferences/com.logos.LogosCEF.plist", "~/Library/Preferences/com.logos.Logos.plist", ] end
28.83871
94
0.689038
08d5191ddc965b8a59c25159129e9f64d63763fc
1,823
module Cms::Extensions::ColumnValuesRelation extend ActiveSupport::Concern class LiquidExports < SS::Liquidization::LiquidExportsBase def key?(name) find_value(name).present? end def [](method_or_key) find_value(method_or_key) || super end def find_value(id_or_name) if id_or_name.is_a?(Integer) @delegatee[id_or_name] else @delegatee.find { |val| [val.id.to_s, val.name].include?(id_or_name) } end end delegate :each, to: :@delegatee delegate :fetch, to: :@delegatee end def to_liquid LiquidExports.new(self.order_by(order: 1, name: 1).to_a.reject { |value| value.instance_of?(Cms::Column::Value::Base) }) end def move_up(value_id) copy = Array(self.order_by(order: 1, name: 1).to_a) index = copy.index { |value| value.id == value_id } if index && index > 0 copy[index - 1], copy[index] = copy[index], copy[index - 1] end copy.each_with_index { |value, index| value.order = index } end def move_down(value_id) copy = Array(self.order_by(order: 1, name: 1).to_a) index = copy.index { |value| value.id == value_id } if index && index < copy.length - 1 copy[index], copy[index + 1] = copy[index + 1], copy[index] end copy.each_with_index { |value, index| value.order = index } end def move_at(source_id, destination_index) copy = Array(self.order_by(order: 1, name: 1).to_a) source_index = copy.index { |value| value.id == source_id } return if !source_index || source_index == destination_index destination_index = 0 if destination_index < 0 destination_index = -1 if destination_index >= copy.length copy.insert(destination_index, copy.delete_at(source_index)) copy.each_with_index { |value, index| value.order = index } end end
30.898305
124
0.665387
ac153cee7ea380398c3473646daf58bf408f59e3
762
module SoupCMS module Api module Resolver module Markdown class LinkRef < Base def resolve(html) doc = Nokogiri::HTML.fragment(html) links = doc.css('a') links.each do |link| next unless link['href'].start_with?('ref:') ref_href = link['href'] link['href'] = resolve_link(ref_href) end doc.to_html end def resolve_link(ref_href) ref_doc, continue = ValueReferenceResolver.new.resolve(ref_href, context) return ref_href if ref_doc == ref_href SoupCMS::Api::Enricher::UrlEnricher.new(context).enrich(ref_doc)['url'] end end end end end end
23.8125
85
0.543307
e238a88ff7569110d0be734ddab5fb7a52283eab
137
module LoanTypesHelper def all_loan_type LoanType.all.collect { |x| [x.name.to_s + ' - ' + x.interest_rate.to_s, x.id] } end end
19.571429
83
0.671533
f7050d7f8fbba8a6903a12db746de735a4290d23
6,315
# encoding: utf-8 # This file is distributed under New Relic's license terms. # See https://github.com/newrelic/newrelic-ruby-agent/blob/main/LICENSE for complete details. if NewRelic::Agent::Instrumentation::RackHelpers.version_supported? && defined? Rack require File.join(File.dirname(__FILE__), 'example_app') require 'new_relic/rack/browser_monitoring' require 'new_relic/rack/agent_hooks' class RackAutoInstrumentationTest < Minitest::Test include MultiverseHelpers setup_and_teardown_agent include Rack::Test::Methods def builder_class if defined? Puma::Rack::Builder Puma::Rack::Builder else Rack::Builder end end def app builder_class.app do use MiddlewareOne use MiddlewareTwo, 'the correct tag' do |headers| headers['MiddlewareTwoBlockTag'] = 'the block tag' end use MiddlewareThree, tag: 'the correct tag' use NewRelic::Rack::BrowserMonitoring use NewRelic::Rack::AgentHooks run ExampleApp.new end end def test_middleware_gets_used get '/' assert last_response.headers['MiddlewareOne'] assert last_response.headers['MiddlewareTwo'] assert last_response.headers['MiddlewareThree'] end def test_status_code_is_preserved get '/' assert_equal 200, last_response.status end def test_header_is_preserved get '/' assert last_response.headers['ExampleApp'] end def test_body_is_preserved get '/' assert_equal 'A barebones rack app.', last_response.body end def test_non_agent_middlewares_do_not_record_metrics_if_disabled_by_config with_config(:disable_middleware_instrumentation => true) do get '/' end assert_metrics_recorded_exclusive( [ "Apdex", "ApdexAll", "HttpDispatcher", "Middleware/all", "Apdex/Middleware/Rack/NewRelic::Rack::AgentHooks/call", "Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call", "Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call", "Middleware/Rack/NewRelic::Rack::AgentHooks/call", "WebTransactionTotalTime", "WebTransactionTotalTime/Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call", ["Middleware/Rack/NewRelic::Rack::AgentHooks/call", "Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call"], ["Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call", "Controller/Middleware/Rack/NewRelic::Rack::AgentHooks/call"], 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/all', 'Supportability/API/recording_web_transaction?', 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/allWeb' ], :ignore_filter => /^(Supportability|Logging)/ ) end def test_middlewares_record_metrics NewRelic::Agent.agent.stats_engine.reset! get '/' assert_metrics_recorded_exclusive( [ "Apdex", "ApdexAll", "HttpDispatcher", "Middleware/all", "Apdex/Rack/ExampleApp/call", "Controller/Rack/ExampleApp/call", "Middleware/Rack/MiddlewareOne/call", "Middleware/Rack/MiddlewareTwo/call", "Middleware/Rack/MiddlewareThree/call", "Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call", "Middleware/Rack/NewRelic::Rack::AgentHooks/call", "Nested/Controller/Rack/ExampleApp/call", "Supportability/API/browser_timing_header", "WebTransactionTotalTime", "WebTransactionTotalTime/Controller/Rack/ExampleApp/call", ["Middleware/Rack/NewRelic::Rack::BrowserMonitoring/call", "Controller/Rack/ExampleApp/call"], ["Middleware/Rack/NewRelic::Rack::AgentHooks/call", "Controller/Rack/ExampleApp/call"], ["Middleware/Rack/MiddlewareOne/call", "Controller/Rack/ExampleApp/call"], ["Middleware/Rack/MiddlewareTwo/call", "Controller/Rack/ExampleApp/call"], ["Middleware/Rack/MiddlewareThree/call", "Controller/Rack/ExampleApp/call"], ["Nested/Controller/Rack/ExampleApp/call", "Controller/Rack/ExampleApp/call"], 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/all', 'Supportability/API/recording_web_transaction?', 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/allWeb' ], :ignore_filter => /^(Supportability|Logging)/ ) end def test_middlewares_record_queue_time t0 = nr_freeze_process_time advance_process_time(5.0) get '/', {}, { 'HTTP_X_REQUEST_START' => "t=#{t0.to_f}" } assert_metrics_recorded( 'WebFrontend/QueueTime' => { :total_call_time => 5.0 } ) end def test_middleware_that_returns_early_records_middleware_rollup_metric get '/?return-early=true' assert_metrics_recorded_exclusive( [ "Apdex", "ApdexAll", "HttpDispatcher", "Middleware/all", "Apdex/Middleware/Rack/MiddlewareTwo/call", "Controller/Middleware/Rack/MiddlewareTwo/call", "Middleware/Rack/MiddlewareOne/call", "Middleware/Rack/MiddlewareTwo/call", "WebTransactionTotalTime", "WebTransactionTotalTime/Controller/Middleware/Rack/MiddlewareTwo/call", ["Middleware/Rack/MiddlewareOne/call", "Controller/Middleware/Rack/MiddlewareTwo/call"], ["Middleware/Rack/MiddlewareTwo/call", "Controller/Middleware/Rack/MiddlewareTwo/call"], 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/all', 'DurationByCaller/Unknown/Unknown/Unknown/HTTP/allWeb', 'Logging/lines', 'Logging/lines/INFO', 'Logging/lines/WARN', 'Logging/size', 'Logging/size/INFO', 'Logging/size/WARN', ], :ignore_filter => /^Supportability/ ) end def test_middleware_that_returns_early_middleware_all_has_correct_call_times nr_freeze_process_time get '/?return-early=true' assert_metrics_recorded('Middleware/all' => { :total_exclusive_time => 3.0, :call_count => 2 }) end def test_middleware_created_with_args_works get '/' assert_equal('the correct tag', last_response.headers['MiddlewareTwoTag']) assert_equal('the block tag', last_response.headers['MiddlewareTwoBlockTag']) end def test_middleware_created_with_kwargs_works get '/' assert_equal('the correct tag', last_response.headers['MiddlewareThreeTag']) end end end
34.508197
129
0.699762
1dd34f89ee370cf4f1ed6623a00429400d81694b
2,833
# # Copyright (C) 2014 eNovance SAS <[email protected]> # # Author: Emilien Macchi <[email protected]> # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. require 'spec_helper' describe 'openstacklib::messaging::rabbitmq' do let (:title) { 'nova' } shared_examples 'openstacklib::messaging::rabbitmq examples' do let :params do {} end context 'with default parameters' do it { should contain_rabbitmq_user('guest').with( :admin => false, :password => 'guest', :provider => 'rabbitmqctl', )} it { should contain_rabbitmq_user_permissions('guest@/').with( :configure_permission => '.*', :write_permission => '.*', :read_permission => '.*', :provider => 'rabbitmqctl', )} it { should contain_rabbitmq_vhost('/').with( :provider => 'rabbitmqctl', )} end context 'with custom parameters' do before :each do params.merge!( :userid => 'nova', :password => 'secrete', :virtual_host => '/nova', :is_admin => true, :configure_permission => '.nova', :write_permission => '.nova', :read_permission => '.nova' ) end it { should contain_rabbitmq_user('nova').with( :admin => true, :password => 'secrete', :provider => 'rabbitmqctl', )} it { should contain_rabbitmq_user_permissions('nova@/nova').with( :configure_permission => '.nova', :write_permission => '.nova', :read_permission => '.nova', :provider => 'rabbitmqctl', )} it { should contain_rabbitmq_vhost('/nova').with( :provider => 'rabbitmqctl', )} end context 'when disabling vhost management' do before :each do params.merge!( :manage_vhost => false ) end it { should_not contain_rabbitmq_vhost('/') } end end on_supported_os({ :supported_os => OSDefaults.get_supported_os }).each do |os,facts| context "on #{os}" do let (:facts) do facts.merge!(OSDefaults.get_facts()) end it_behaves_like 'openstacklib::messaging::rabbitmq examples' end end end
28.33
75
0.591246
bf3ea6cabc077d7112da3c6e384a73cd490e5e24
936
#!/usr/bin/env ruby file_path = File.expand_path("../input", __FILE__) input = File.readlines(file_path) keypad = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] x = nil keypad = [[x, x, 1, x, x], [x, 2, 3, 4, x], [5, 6, 7, 8, 9], [x, "A", "B", "C", x], [x, x, "D", x, x]] current_button = [2, 0] code = [] movements = { "U" => [-1, 0], "D" => [ 1, 0], "R" => [ 0, 1], "L" => [ 0, -1] } input.each do |line| line.strip.split("").each do |movement| next_button = [ current_button[0] + movements[movement][0], current_button[1] + movements[movement][1] ] current_button = next_button if next_button.all? { |i| (0..keypad.length-1).include?(i) } && keypad[next_button[0]] && keypad[next_button[0]][next_button[1]] end code << keypad[current_button[0]][current_button[1]] end puts "The bathroom code is #{code.join}"
23.4
161
0.507479
26956f4eb702b8b057e311eec685a1a9a07d1b3c
3,354
# 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 "helper" require "gapic/grpc/service_stub" require "google/cloud/metastore/v1alpha/dataproc_metastore" class ::Google::Cloud::Metastore::V1alpha::DataprocMetastore::ClientPathsTest < Minitest::Test def test_backup_path grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure ::Gapic::ServiceStub.stub :new, nil do client = ::Google::Cloud::Metastore::V1alpha::DataprocMetastore::Client.new do |config| config.credentials = grpc_channel end path = client.backup_path project: "value0", location: "value1", service: "value2", backup: "value3" assert_equal "projects/value0/locations/value1/services/value2/backups/value3", path end end def test_location_path grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure ::Gapic::ServiceStub.stub :new, nil do client = ::Google::Cloud::Metastore::V1alpha::DataprocMetastore::Client.new do |config| config.credentials = grpc_channel end path = client.location_path project: "value0", location: "value1" assert_equal "projects/value0/locations/value1", path end end def test_metadata_import_path grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure ::Gapic::ServiceStub.stub :new, nil do client = ::Google::Cloud::Metastore::V1alpha::DataprocMetastore::Client.new do |config| config.credentials = grpc_channel end path = client.metadata_import_path project: "value0", location: "value1", service: "value2", metadata_import: "value3" assert_equal "projects/value0/locations/value1/services/value2/metadataImports/value3", path end end def test_network_path grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure ::Gapic::ServiceStub.stub :new, nil do client = ::Google::Cloud::Metastore::V1alpha::DataprocMetastore::Client.new do |config| config.credentials = grpc_channel end path = client.network_path project: "value0", network: "value1" assert_equal "projects/value0/global/networks/value1", path end end def test_service_path grpc_channel = ::GRPC::Core::Channel.new "localhost:8888", nil, :this_channel_is_insecure ::Gapic::ServiceStub.stub :new, nil do client = ::Google::Cloud::Metastore::V1alpha::DataprocMetastore::Client.new do |config| config.credentials = grpc_channel end path = client.service_path project: "value0", location: "value1", service: "value2" assert_equal "projects/value0/locations/value1/services/value2", path end end end
39
124
0.724806
393adfca672c06e455a1fc81e89bf4654bd3f917
8,097
# frozen_string_literal: true require "rails_helper" describe Types::EveMarketGroupType do describe "get market groups" do let!(:eve_type_1) do create(:eve_type, type_id: 400, market_group: eve_market_group_1) end let!(:eve_type_2) do create(:eve_type, type_id: 500, market_group: eve_market_group_2) end let!(:eve_market_group_1) do create(:eve_market_group, market_group_id: 123, name_en: "EN: name 1", name_de: "DE: name 1", name_fr: "FR: name 1", name_ja: "JA: name 1", name_ru: "RU: name 1", name_ko: "KO: name 1", description_en: "EN: description 1", description_de: "DE: description 1", description_fr: "FR: description 1", description_ja: "JA: description 1", description_ru: "RU: description 1", description_ko: "KO: description 1", parent_group_id: nil) end let!(:eve_market_group_2) do create(:eve_market_group, market_group_id: 321, name_en: "EN: name 2", name_de: "DE: name 2", name_fr: "FR: name 2", name_ja: "JA: name 2", name_ru: "RU: name 2", name_ko: "KO: name 2", description_en: "EN: description 2", description_de: "DE: description 2", description_fr: "FR: description 2", description_ja: "JA: description 2", description_ru: "RU: description 2", description_ko: "KO: description 2", parent_group: eve_market_group_1) end let(:query) do %( { marketGroups(first: 2) { edges { node { id name description parentGroupId parentGroup { id } types(first: 1) { edges { node { id } cursor } pageInfo { endCursor hasNextPage hasPreviousPage startCursor } } } cursor } pageInfo { endCursor hasNextPage hasPreviousPage startCursor } } } ) end let(:result) { EvemonkSchema.execute(query).as_json } specify do expect(result).to eq("data" => { "marketGroups" => { "edges" => [ { "node" => { "id" => "123", "name" => { "en" => "EN: name 1", "de" => "DE: name 1", "fr" => "FR: name 1", "ja" => "JA: name 1", "ru" => "RU: name 1", "ko" => "KO: name 1" }, "description" => { "en" => "EN: description 1", "de" => "DE: description 1", "fr" => "FR: description 1", "ja" => "JA: description 1", "ru" => "RU: description 1", "ko" => "KO: description 1" }, "parentGroupId" => nil, "parentGroup" => nil, "types" => { "edges" => [ { "node" => { "id" => "400" }, "cursor" => "MQ" } ], "pageInfo" => { "endCursor" => "MQ", "hasNextPage" => false, "hasPreviousPage" => false, "startCursor" => "MQ" } } }, "cursor" => "MQ" }, { "node" => { "id" => "321", "name" => { "en" => "EN: name 2", "de" => "DE: name 2", "fr" => "FR: name 2", "ja" => "JA: name 2", "ru" => "RU: name 2", "ko" => "KO: name 2" }, "description" => { "en" => "EN: description 2", "de" => "DE: description 2", "fr" => "FR: description 2", "ja" => "JA: description 2", "ru" => "RU: description 2", "ko" => "KO: description 2" }, "parentGroupId" => 123, "parentGroup" => { "id" => "123" }, "types" => { "edges" => [ { "node" => { "id" => "500" }, "cursor" => "MQ" } ], "pageInfo" => { "endCursor" => "MQ", "hasNextPage" => false, "hasPreviousPage" => false, "startCursor" => "MQ" } } }, "cursor" => "Mg" } ], "pageInfo" => { "endCursor" => "Mg", "hasNextPage" => false, "hasPreviousPage" => false, "startCursor" => "MQ" } } }) end end describe "get market group by id" do let!(:eve_type) do create(:eve_type, type_id: 400, market_group: eve_market_group) end let!(:eve_market_group) do create(:eve_market_group, market_group_id: 123, name_en: "EN: name 1", name_de: "DE: name 1", name_fr: "FR: name 1", name_ja: "JA: name 1", name_ru: "RU: name 1", name_ko: "KO: name 1", description_en: "EN: description 1", description_de: "DE: description 1", description_fr: "FR: description 1", description_ja: "JA: description 1", description_ru: "RU: description 1", description_ko: "KO: description 1", parent_group_id: nil) end let(:query) do %( { marketGroup(id: 123) { id name description parentGroupId parentGroup { id } types(first: 1) { edges { node { id } cursor } pageInfo { endCursor hasNextPage hasPreviousPage startCursor } } } } ) end let(:result) { EvemonkSchema.execute(query).as_json } specify do expect(result).to eq("data" => { "marketGroup" => { "id" => "123", "name" => { "en" => "EN: name 1", "de" => "DE: name 1", "fr" => "FR: name 1", "ja" => "JA: name 1", "ru" => "RU: name 1", "ko" => "KO: name 1" }, "description" => { "en" => "EN: description 1", "de" => "DE: description 1", "fr" => "FR: description 1", "ja" => "JA: description 1", "ru" => "RU: description 1", "ko" => "KO: description 1" }, "parentGroupId" => nil, "parentGroup" => nil, "types" => { "edges" => [ { "node" => { "id" => "400" }, "cursor" => "MQ" } ], "pageInfo" => { "endCursor" => "MQ", "hasNextPage" => false, "hasPreviousPage" => false, "startCursor" => "MQ" } } } }) end end end
27.35473
57
0.358281
03554bc3a931ccb50b9de328b62a3e828f7085b3
473
# frozen_string_literal: true require 'spec_helper' RSpec.describe Rumale::LinearModel::Loss::EpsilonInsensitive do let(:y) { Numo::DFloat[4, 1, 1, 3] } let(:t) { Numo::DFloat[4, 3, 2, 1] } let(:loss) { described_class.new(epsilon: 1).loss(y, t) } let(:dout) { described_class.new(epsilon: 1).dloss(y, t) } it 'calculates epsilon insensitive loss', :aggregate_failures do expect(loss).to eq(0.5) expect(dout).to eq(Numo::DFloat[0, -1, 0, 1]) end end
29.5625
66
0.668076
e26f997272cab7678ef80b1d8662f16c478a8efc
2,318
# frozen_string_literal: true require 'spec_helper' describe RemarkAce do describe '#to_s' do it 'should be remark string' do rmk = RemarkAce.new(' foo-bar _ baz @@ COMMENT') expect(rmk.to_s).to eq 'remark foo-bar _ baz @@ COMMENT' end end describe '#==' do before(:all) do @rmk1 = RemarkAce.new('asdfjklj;') @rmk2 = RemarkAce.new('asdfjklj;') @rmk3 = RemarkAce.new('asd f j klj;') end it 'should be true when same comment' do expect(@rmk1 == @rmk2).to be_truthy end it 'should be false when different comment' do expect(@rmk1 == @rmk3).to be_falsey end end describe '#contains?' do it 'should be always false' do rmk = RemarkAce.new('asdfjklj;') expect( rmk.contains?( src_ip: '192.168.4.4', dst_ip: '172.30.240.33' ) ).to be_falsey # with empty argments expect(rmk.contains?).to be_falsey end end end describe EvaluateAce do describe '#to_s' do it 'should be evaluate term' do evl = EvaluateAce.new( recursive_name: 'foobar_baz' ) expect(evl.to_s).to be_aclstr('evaluate foobar_baz') end it 'raise error if not specified recursive name' do expect do EvaluateAce.new( number: 30 ) end.to raise_error(AclArgumentError) end end describe '#==' do before(:all) do @evl1 = EvaluateAce.new(recursive_name: 'foo_bar') @evl2 = EvaluateAce.new(recursive_name: 'foo_bar') @evl3 = EvaluateAce.new(recursive_name: 'foo_baz') end it 'should be true when same evaluate name' do expect(@evl1 == @evl2).to be_truthy end it 'should be false when different evaluate name' do expect(@evl1 == @evl3).to be_falsey end end describe '#contains?' do it 'should be false' do skip('match by evaluate is not implemented yet') evl = EvaluateAce.new( recursive_name: 'asdf_0-98' ) expect( evl.contains?( src_ip: '192.168.4.4', dst_ip: '172.30.240.33' ) ).to be_falsey # with empty argments expect(evl.contains?).to be_falsey end end end ### Local variables: ### mode: Ruby ### coding: utf-8-unix ### indent-tabs-mode: nil ### End:
22.72549
62
0.599223
79a80d00fe26311ec25460d1b7426b0d29fcb269
426
require 'sidekiq' require 'enquiry/services/mailchimp' module Enquiry class MailchimpWorker include Sidekiq::Worker def perform(mailchimp_params) mailchimp_params = Enquiry::Utils.symbolize_keys(mailchimp_params) MailchimpService.add_contact_to_list( mailchimp_params[:list_id], mailchimp_params[:email], merge_params: mailchimp_params[:merge_params] ) end end end
22.421053
72
0.7277
0343ab16cd3dd965db3123082030c19d74cba128
850
Gem::Specification.new do |spec| spec.name = "embulk-filter-amazon_rekognition" spec.version = "0.1.2" spec.authors = ["toyama0919"] spec.summary = "Amazon Rekognition filter plugin for Embulk" spec.description = "Amazon Rekognition" spec.email = ["[email protected]"] spec.licenses = ["MIT"] spec.homepage = "https://github.com/toyama0919/embulk-filter-amazon_rekognition" spec.files = `git ls-files`.split("\n") + Dir["classpath/*.jar"] spec.test_files = spec.files.grep(%r{^(test|spec)/}) spec.require_paths = ["lib"] spec.add_dependency 'aws-sdk' spec.add_dependency 'addressable' spec.add_development_dependency 'embulk', ['>= 0.8.18'] spec.add_development_dependency 'bundler', ['>= 1.10.6'] spec.add_development_dependency 'rake', ['>= 10.0'] end
38.636364
87
0.655294
381fe1bc75e0704faeffc78dfc138727c8386de6
4,970
# coding: utf-8 # vim: et ts=2 sw=2 RSpec.describe HrrRbSsh::Message::SSH_MSG_CHANNEL_OPEN_CONFIRMATION do let(:id){ 'SSH_MSG_CHANNEL_OPEN_CONFIRMATION' } let(:value){ 91 } describe "::ID" do it "is defined" do expect(described_class::ID).to eq id end end describe "::VALUE" do it "is defined" do expect(described_class::VALUE).to eq value end end context "when 'channel type' is \"session\"" do let(:message){ { :'message number' => value, :'recipient channel' => 1, :'sender channel' => 2, :'initial window size' => 3, :'maximum packet size' => 4, } } let(:payload){ [ HrrRbSsh::DataType::Byte.encode(message[:'message number']), HrrRbSsh::DataType::Uint32.encode(message[:'recipient channel']), HrrRbSsh::DataType::Uint32.encode(message[:'sender channel']), HrrRbSsh::DataType::Uint32.encode(message[:'initial window size']), HrrRbSsh::DataType::Uint32.encode(message[:'maximum packet size']), ].join } let(:complementary_message){ { 'channel type' => 'session', } } describe ".encode" do it "returns payload encoded" do expect(described_class.encode(message, complementary_message)).to eq payload end end describe ".decode" do it "returns message decoded" do expect(described_class.decode(payload, complementary_message)).to eq message end end end context "when 'channel type' is \"x11\"" do let(:message){ { :'message number' => value, :'recipient channel' => 1, :'sender channel' => 2, :'initial window size' => 3, :'maximum packet size' => 4, } } let(:payload){ [ HrrRbSsh::DataType::Byte.encode(message[:'message number']), HrrRbSsh::DataType::Uint32.encode(message[:'recipient channel']), HrrRbSsh::DataType::Uint32.encode(message[:'sender channel']), HrrRbSsh::DataType::Uint32.encode(message[:'initial window size']), HrrRbSsh::DataType::Uint32.encode(message[:'maximum packet size']), ].join } let(:complementary_message){ { 'channel type' => 'x11', } } describe ".encode" do it "returns payload encoded" do expect(described_class.encode(message, complementary_message)).to eq payload end end describe ".decode" do it "returns message decoded" do expect(described_class.decode(payload, complementary_message)).to eq message end end end context "when 'channel type' is \"forwarded-tcpip\"" do let(:message){ { :'message number' => value, :'recipient channel' => 1, :'sender channel' => 2, :'initial window size' => 3, :'maximum packet size' => 4, } } let(:payload){ [ HrrRbSsh::DataType::Byte.encode(message[:'message number']), HrrRbSsh::DataType::Uint32.encode(message[:'recipient channel']), HrrRbSsh::DataType::Uint32.encode(message[:'sender channel']), HrrRbSsh::DataType::Uint32.encode(message[:'initial window size']), HrrRbSsh::DataType::Uint32.encode(message[:'maximum packet size']), ].join } let(:complementary_message){ { 'channel type' => 'forwarded-tcpip', } } describe ".encode" do it "returns payload encoded" do expect(described_class.encode(message, complementary_message)).to eq payload end end describe ".decode" do it "returns message decoded" do expect(described_class.decode(payload, complementary_message)).to eq message end end end context "when 'channel type' is \"direct-tcpip\"" do let(:message){ { :'message number' => value, :'recipient channel' => 1, :'sender channel' => 2, :'initial window size' => 3, :'maximum packet size' => 4, } } let(:payload){ [ HrrRbSsh::DataType::Byte.encode(message[:'message number']), HrrRbSsh::DataType::Uint32.encode(message[:'recipient channel']), HrrRbSsh::DataType::Uint32.encode(message[:'sender channel']), HrrRbSsh::DataType::Uint32.encode(message[:'initial window size']), HrrRbSsh::DataType::Uint32.encode(message[:'maximum packet size']), ].join } let(:complementary_message){ { 'channel type' => 'direct-tcpip', } } describe ".encode" do it "returns payload encoded" do expect(described_class.encode(message, complementary_message)).to eq payload end end describe ".decode" do it "returns message decoded" do expect(described_class.decode(payload, complementary_message)).to eq message end end end end
28.238636
84
0.588732
6acbf46eb209dc7e633b0f1fd4c9656b4d508a81
1,819
class Spinach::Features::AdminSettings < Spinach::FeatureSteps include SharedAuthentication include SharedPaths include SharedAdmin include Gitlab::CurrentSettings step 'I modify settings and save form' do uncheck 'Gravatar enabled' fill_in 'Home page URL', with: 'https://about.gitlab.com/' fill_in 'Help page text', with: 'Example text' click_button 'Save' end step 'I should see application settings saved' do expect(current_application_settings.gravatar_enabled).to be_falsey expect(current_application_settings.home_page_url).to eq "https://about.gitlab.com/" expect(page).to have_content "Application settings saved successfully" end step 'I click on "Service Templates"' do click_link 'Service Templates' end step 'I click on "Slack" service' do click_link 'Slack' end step 'I check all events and submit form' do page.check('Active') page.check('Push events') page.check('Tag push events') page.check('Comments') page.check('Issues events') page.check('Merge Request events') click_on 'Save' end step 'I fill out Slack settings' do fill_in 'Webhook', with: 'http://localhost' fill_in 'Username', with: 'test_user' fill_in 'Channel', with: '#test_channel' end step 'I should see service template settings saved' do expect(page).to have_content 'Application settings saved successfully' end step 'I should see all checkboxes checked' do page.all('input[type=checkbox]').each do |checkbox| expect(checkbox).to be_checked end end step 'I should see Slack settings saved' do expect(find_field('Webhook').value).to eq 'http://localhost' expect(find_field('Username').value).to eq 'test_user' expect(find_field('Channel').value).to eq '#test_channel' end end
30.316667
88
0.715228
e2fde44c2f2c371824939cf52b7d38411e0ec52d
9,429
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX - License - Identifier: Apache - 2.0 # This code example determines of the users available to you in # AWS Identity and Access Management (IAM), how many of them are associated # with a policy that provides administrator privileges. # # This code example begins running by calling the custom run_me function. # This function calls the custom function is_user_admin?, which in turn # calls the following custom functions: # - user_has_admin_policy? # - user_has attached_policy? # - user_has_admin_from_group? # The custom user_has_admin_from_group? function calls the following # custom functions: # - group_has_admin_policy? # - group_has_attached_policy? require 'aws-sdk-iam' # Determines whether the specified user in # AWS Identity and Access Management (IAM) is associated with a policy that # provides administrator privileges. # # Prerequisites: # - The existing user in IAM. # # @param user [Aws::IAM::User] The specified user. # @param admin_access [String] The name of the administrator-related policy # to search for, for example 'AdministratorAccess'. # @return [Boolean] true if the specified user is associated with a policy that # provides administrator privileges; otherwise, false. # @example # client = Aws::IAM::Client.new # users = client.get_account_authorization_details(filter: ['User']).user_detail_list # exit 1 unless user_has_admin_policy?(users[0], 'AdministratorAccess') def user_has_admin_policy?(user, admin_access) policies = user.user_policy_list policies.each do |p| return true if p.policy_name == admin_access end return false end # Determines whether the specified user in # AWS Identity and Access Management (IAM) has a policy attached that # provides administrator privileges. # # Prerequisites: # - The existing user in IAM. # # @param user [Aws::IAM::User] The specified user. # @param admin_access [String] The name of the administrator-related policy # to search for, for example 'AdministratorAccess'. # @return [Boolean] true if the specified user has a policy attached that # provides administrator privileges; otherwise, false. # @example # client = Aws::IAM::Client.new # users = client.get_account_authorization_details(filter: ['User']).user_detail_list # exit 1 unless user_has_attached_policy?(users[0], 'AdministratorAccess') def user_has_attached_policy?(user, admin_access) attached_policies = user.attached_managed_policies attached_policies.each do |p| return true if p.policy_name == admin_access end return false end # Determines whether the specified group in # AWS Identity and Access Management (IAM) is associated with a policy that # provides administrator privileges. # # Prerequisites: # - The existing group in IAM. # # @param client [Aws::IAM::Client] An initialized IAM client. # @param group [Aws::IAM::Group] The specified group. # @param admin_access [String] The name of the administrator-related policy # to search for, for example 'AdministratorAccess'. # @return [Boolean] true if the specified group is associated with a policy that # provides administrator privileges; otherwise, false. # @example # client = Aws::IAM::Client.new # groups = client.list_groups_for_user(user_name: 'Mary') # exit 1 unless group_has_admin_policy?(client, groups[0], 'AdministratorAccess') def group_has_admin_policy?(client, group, admin_access) resp = client.list_group_policies( group_name: group.group_name ) resp.policy_names.each do |name| return true if name == admin_access end return false end # Determines whether the specified group in # AWS Identity and Access Management (IAM) has a policy attached that # provides administrator privileges. # # Prerequisites: # - The existing group in IAM. # # @param client [Aws::IAM::Client] An initialized IAM client. # @param group [Aws::IAM::Group] The specified group. # @param admin_access [String] The name of the administrator-related policy # to search for, for example 'AdministratorAccess'. # @return [Boolean] true if the specified group has a policy attached that # provides administrator privileges; otherwise, false. # @example # client = Aws::IAM::Client.new # groups = client.list_groups_for_user(user_name: 'Mary') # exit 1 unless group_has_attached_policy?(client, groups[0], 'AdministratorAccess') def group_has_attached_policy?(client, group, admin_access) resp = client.list_attached_group_policies( group_name: group.group_name # required ) resp.attached_policies.each do |policy| return true if policy.policy_name == admin_access end return false end # Determines whether the specified user in # AWS Identity and Access Management (IAM) is associated with a group # that has administrator privileges. # # Prerequisites: # - The existing user in IAM. # # @param client [Aws::IAM::Client] An initialized IAM client. # @param user [Aws::IAM::User] The specified user. # @param admin_access [String] The name of the administrator-related policy # to search for, for example 'AdministratorAccess'. # @return [Boolean] true if the specified user is associated with a group that # has administrator privileges; otherwise, false. # @example # client = Aws::IAM::Client.new # users = client.get_account_authorization_details(filter: ['User']).user_detail_list # exit 1 unless user_has_admin_from_group?(client, users[0], 'AdministratorAccess') def user_has_admin_from_group?(client, user, admin_access) resp = client.list_groups_for_user( user_name: user.user_name ) resp.groups.each do |group| return true if group_has_admin_policy?(client, group, admin_access) return true if group_has_attached_policy?(client, group, admin_access) end return false end # Determines whether the specified user in # AWS Identity and Access Management (IAM) has administrator privileges. # # Prerequisites: # - The existing user in IAM. # # @param client [Aws::IAM::Client] An initialized IAM client. # @param user [Aws::IAM::User] The specified user. # @param admin_access [String] The name of the administrator-related policy # to search for, for example 'AdministratorAccess'. # @return [Boolean] true if the specified user has administrator privileges; # otherwise, false. # @example # client = Aws::IAM::Client.new # users = client.get_account_authorization_details(filter: ['User']).user_detail_list # exit 1 unless is_user_admin?(client, users[0], 'AdministratorAccess') def is_user_admin?(client, user, admin_access) return true if user_has_admin_policy?(user, admin_access) return true if user_has_attached_policy?(user, admin_access) return true if user_has_admin_from_group?(client, user, admin_access) return false end # Determines how many of the available users in # AWS Identity and Access Management (IAM) have administrator privileges. # # Prerequisites: # - One or more existing users in IAM. # # @param client [Aws::IAM::Client] An initialized IAM client. # @param users [Array] A list of users of type Aws::IAM::Types::UserDetail. # @param admin_access [String] The name of the administrator-related policy # to search for, for example 'AdministratorAccess'. # @return [Integer] The number of available users who have # administrator privileges. # @example # client = Aws::IAM::Client.new # puts get_admin_count( # client, # client.get_account_authorization_details(filter: ['User']).user_detail_list, # 'AdministratorAccess' # ) def get_admin_count(client, users, admin_access) num_admins = 0 users.each do |user| is_admin = is_user_admin?(client, user, admin_access) if is_admin puts user.user_name num_admins += 1 end end num_admins end # Full example call: def run_me client = Aws::IAM::Client.new num_users = 0 num_admins = 0 access_admin = 'AdministratorAccess' puts 'Getting the list of available users...' details = client.get_account_authorization_details(filter: ['User']) users = details.user_detail_list unless users.count.positive? puts 'No available users found. Stopping program.' exit 1 end num_users += users.count puts 'Getting the list of available users who are associated with the ' \ "policy '#{access_admin}'..." more_admins = get_admin_count(client, users, access_admin) num_admins += more_admins unless num_admins.positive? puts 'No available users found yet who are associated with the ' \ "policy '#{access_admin}'. Looking for more available " \ 'users...' end more_users = details.is_truncated while more_users details = client.get_account_authorization_details( filter: ['User'], marker: details.marker ) users = details.user_detail_list num_users += users.count more_admins = get_admin_count(client, users, access_admin) num_admins += more_admins more_users = details.is_truncated end puts "Out of #{num_users} available user(s), found #{num_admins} " \ 'available user(s) who is/are associated with the policy ' \ "'#{access_admin}'." end run_me if $PROGRAM_NAME == __FILE__
35.052045
88
0.727225
1a430e8cd088913c01a212567f6cb72d3fdd46ad
106
require 'sidebar' require 'authors_sidebar' AuthorsSidebar.view_root = File.dirname(__FILE__) + '/views'
21.2
60
0.783019
081c30b4c7e7a568f647fe387435fec9aa832fc7
6,282
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. require 'date' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # Parameters detailing how to provision the source for the given Channel. # This class has direct subclasses. If you are using this class as input to a service operations then you should favor using a subclass over the base class class Mysql::Models::CreateChannelSourceDetails # **[Required]** The specific source identifier. # @return [String] attr_accessor :source_type # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'source_type': :'sourceType' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'source_type': :'String' # rubocop:enable Style/SymbolLiteral } end # rubocop:disable Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity, Metrics/AbcSize # Given the hash representation of a subtype of this class, # use the info in the hash to return the class of the subtype. def self.get_subtype(object_hash) type = object_hash[:'sourceType'] # rubocop:disable Style/SymbolLiteral return 'OCI::Mysql::Models::CreateChannelSourceFromMysqlDetails' if type == 'MYSQL' # TODO: Log a warning when the subtype is not found. 'OCI::Mysql::Models::CreateChannelSourceDetails' end # rubocop:enable Metrics/CyclomaticComplexity, Layout/EmptyLines, Metrics/PerceivedComplexity, Metrics/AbcSize # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Initializes the object # @param [Hash] attributes Model attributes in the form of hash # @option attributes [String] :source_type The value to assign to the {#source_type} property 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 } self.source_type = attributes[:'sourceType'] if attributes[:'sourceType'] raise 'You cannot provide both :sourceType and :source_type' if attributes.key?(:'sourceType') && attributes.key?(:'source_type') self.source_type = attributes[:'source_type'] if attributes[:'source_type'] end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # Checks equality by comparing each attribute. # @param [Object] other the other object to be compared def ==(other) return true if equal?(other) self.class == other.class && source_type == other.source_type end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # @see the `==` method # @param [Object] other the other object to be compared def eql?(other) self == other end # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [source_type].hash end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # 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 =~ /^Array<(.*)>/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) public_method("#{key}=").call( attributes[self.class.attribute_map[key]] .map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? public_method("#{key}=").call( OCI::Internal::Util.convert_to_type(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 # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s 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 = public_method(attr).call next if value.nil? && !instance_variable_defined?("@#{attr}") hash[param] = _to_hash(value) end hash end private # 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 # rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
36.736842
245
0.685132
39a1240c61dcb0eb8b4407c44831f458dfcfa31f
5,484
class Module # Provides a delegate class method to easily expose contained objects' public methods # as your own. Pass one or more methods (specified as symbols or strings) # and the name of the target object via the <tt>:to</tt> option (also a symbol # or string). At least one method and the <tt>:to</tt> option are required. # # Delegation is particularly useful with Active Record associations: # # class Greeter < ActiveRecord::Base # def hello # 'hello' # end # # def goodbye # 'goodbye' # end # end # # class Foo < ActiveRecord::Base # belongs_to :greeter # delegate :hello, :to => :greeter # end # # Foo.new.hello # => "hello" # Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c> # # Multiple delegates to the same target are allowed: # # class Foo < ActiveRecord::Base # belongs_to :greeter # delegate :hello, :goodbye, :to => :greeter # end # # Foo.new.goodbye # => "goodbye" # # Methods can be delegated to instance variables, class variables, or constants # by providing them as a symbols: # # class Foo # CONSTANT_ARRAY = [0,1,2,3] # @@class_array = [4,5,6,7] # # def initialize # @instance_array = [8,9,10,11] # end # delegate :sum, :to => :CONSTANT_ARRAY # delegate :min, :to => :@@class_array # delegate :max, :to => :@instance_array # end # # Foo.new.sum # => 6 # Foo.new.min # => 4 # Foo.new.max # => 11 # # Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value # is <tt>true</tt>, the delegate methods are prefixed with the name of the object being # delegated to. # # Person = Struct.new(:name, :address) # # class Invoice < Struct.new(:client) # delegate :name, :address, :to => :client, :prefix => true # end # # john_doe = Person.new('John Doe', 'Vimmersvej 13') # invoice = Invoice.new(john_doe) # invoice.client_name # => "John Doe" # invoice.client_address # => "Vimmersvej 13" # # It is also possible to supply a custom prefix. # # class Invoice < Struct.new(:client) # delegate :name, :address, :to => :client, :prefix => :customer # end # # invoice = Invoice.new(john_doe) # invoice.customer_name # => 'John Doe' # invoice.customer_address # => 'Vimmersvej 13' # # If the delegate object is +nil+ an exception is raised, and that happens # no matter whether +nil+ responds to the delegated method. You can get a # +nil+ instead with the +:allow_nil+ option. # # class Foo # attr_accessor :bar # def initialize(bar = nil) # @bar = bar # end # delegate :zoo, :to => :bar # end # # Foo.new.zoo # raises NoMethodError exception (you called nil.zoo) # # class Foo # attr_accessor :bar # def initialize(bar = nil) # @bar = bar # end # delegate :zoo, :to => :bar, :allow_nil => true # end # # Foo.new.zoo # returns nil # def delegate(*methods) options = methods.pop unless options.is_a?(Hash) && to = options[:to] raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, :to => :greeter).' end prefix, allow_nil = options.values_at(:prefix, :allow_nil) if prefix == true && to =~ /^[^a-z_]/ raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.' end method_prefix = \ if prefix "#{prefix == true ? to : prefix}_" else '' end file, line = caller.first.split(':', 2) line = line.to_i methods.each do |method| # Attribute writer methods only accept one argument. Makes sure []= # methods still accept two arguments. definition = (method =~ /[^\]]=$/) ? 'arg' : '*args, &block' if allow_nil module_eval(<<-EOS, file, line - 2) def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block) if #{to} || #{to}.respond_to?(:#{method}) # if client || client.respond_to?(:name) #{to}.#{method}(#{definition}) # client.name(*args, &block) end # end end # end EOS else exception = %(raise "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: \#{self.inspect}") module_eval(<<-EOS, file, line - 1) def #{method_prefix}#{method}(#{definition}) # def customer_name(*args, &block) #{to}.#{method}(#{definition}) # client.name(*args, &block) rescue NoMethodError # rescue NoMethodError if #{to}.nil? # if client.nil? #{exception} # # add helpful message to the exception else # else raise # raise end # end end # end EOS end end end end
34.929936
155
0.53337
0319e2a3eb437d0083a3537e0358b13811add039
82
# Module to hold the RedTube API Client module RedtubeApi VERSION = "0.1.0" end
16.4
39
0.731707
08ae0e9f64769c2191114bef798411045e22f649
3,119
require 'spec_helper' # see documentation here: https://www.keepalived.org/manpage.html def vrrp_script_file_name(name) "/etc/keepalived/conf.d/00_keepalived_vrrp_script__#{name}__.conf" end platforms = %w(debian ubuntu centos) platforms.each do |platform| describe "keepalived_vrrp_script on #{platform}" do step_into :keepalived_vrrp_script platform platform context 'Create a base config correctly' do cached(:subject) { chef_run } script_name = 'foobar' file_name = vrrp_script_file_name(script_name) recipe do keepalived_vrrp_script script_name do script script_name end end it('should render an empty config file') do is_expected.to render_file(file_name).with_content(/#{script_name}\s+\{.*\}/m) end it 'creates the config file with the owner, group and mode' do is_expected.to create_template(file_name).with( owner: 'root', group: 'root', mode: '0640' ) end end context 'When given inputs for interval, weight and script' do cached(:subject) { chef_run } script_name = 'chk_haproxy' file_name = vrrp_script_file_name(script_name) recipe do keepalived_vrrp_script script_name do script '/usr/local/bin/chk-haproxy.sh' interval 2 weight 50 end end it('should render a config file with the script correctly') do is_expected.to render_file(file_name).with_content(%r{script\s/usr/local/bin/chk-haproxy\.sh}) end it('should render a config file with the interval correctly') do is_expected.to render_file(file_name).with_content(/interval\s2/) end it('should render a config file with the weight correctly') do is_expected.to render_file(file_name).with_content(/weight\s50/) end end context 'When given inputs for timeout, fall, rise and user' do cached(:subject) { chef_run } script_name = 'chk_haproxy' file_name = vrrp_script_file_name(script_name) recipe do keepalived_vrrp_script script_name do script '/usr/local/bin/chk-haproxy.sh' timeout 10 fall 20 rise 30 user 'scriptUser' end end it('should render a config file with the script correctly') do is_expected.to render_file(file_name).with_content(%r{script\s/usr/local/bin/chk-haproxy\.sh}) end it('should render a config file with the timeout correctly') do is_expected.to render_file(file_name).with_content(/timeout\s10/) end it('should render a config file with the fall correctly') do is_expected.to render_file(file_name).with_content(/fall\s20/) end it('should render a config file with the rise correctly') do is_expected.to render_file(file_name).with_content(/rise\s30/) end it('should render a config file with the user correctly') do is_expected.to render_file(file_name).with_content(/user\sscriptUser/) end end end end
33.537634
102
0.663995
e9e754fce9b5b5132085a26b017e9436f5385de6
874
# coding: utf-8 require_relative './button' require_relative './label' module WS ### ■WSのウィンドウ用のスーパークラス■ ### class WSWindowBase < WSLightContainer ### ■ウィンドウの定義■ ### # Mix-In include WindowFocus # 公開インスタンス attr_accessor :border_width # ウィンドウボーダーの幅 attr_reader :window_focus # ウィンドウ上のフォーカスを持つコントロール # 初期化 def initialize(tx, ty, sx, sy, caption = "WindowTitle") super(tx, ty, sx, sy) @caption = caption @border_width = default_border_width ## オートレイアウトでコントロールの位置を決める ## Layout#objで元のコンテナを参照できる #layout(:vbox) do # self.margin_top = self.margin_left = self.margin_right = self.margin_bottom = self.obj.border_width # add client, true, true #end end # ボーダー幅のデフォルト値 def default_border_width return 3 end end end
21.85
108
0.620137
f89e7c6d1232b7a8e1966a770841ebd5a8ef9237
507
require File.expand_path('../boot', __FILE__) require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module PlylstIt class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. end end
31.6875
82
0.757396
bfb9c84a762663df3d6c01a4a589025c25a9f00d
5,175
verbose = $VERBOSE $VERBOSE = nil class Model FILE_DIGEST = Digest::MD5.hexdigest(File.open(__FILE__).read) def self.model_name @_model_name ||= ActiveModel::Name.new(self) end def initialize(hash = {}) @attributes = hash end def cache_key "#{self.class.name.downcase}/#{self.id}-#{self.updated_at.strftime("%Y%m%d%H%M%S%9N")}" end def serializable_hash(options = nil) @attributes end def read_attribute_for_serialization(name) if name == :id || name == 'id' id else @attributes[name] end end def id @attributes[:id] || @attributes['id'] || object_id end ### Helper methods, not required to be serializable # # Convenience for adding @attributes readers and writers def method_missing(meth, *args) if meth.to_s =~ /^(.*)=$/ @attributes[$1.to_sym] = args[0] elsif @attributes.key?(meth) @attributes[meth] else super end end def cache_key_with_digest "#{cache_key}/#{FILE_DIGEST}" end def updated_at @attributes[:updated_at] ||= DateTime.now.to_time end end class Profile < Model end class ProfileSerializer < ActiveModel::Serializer attributes :name, :description def arguments_passed_in? instance_options[:my_options] == :accessible end end class ProfilePreviewSerializer < ActiveModel::Serializer attributes :name end Post = Class.new(Model) Like = Class.new(Model) Author = Class.new(Model) Bio = Class.new(Model) Blog = Class.new(Model) Role = Class.new(Model) User = Class.new(Model) Location = Class.new(Model) Place = Class.new(Model) Tag = Class.new(Model) VirtualValue = Class.new(Model) Comment = Class.new(Model) do # Uses a custom non-time-based cache key def cache_key "#{self.class.name.downcase}/#{self.id}" end end module Spam; end Spam::UnrelatedLink = Class.new(Model) PostSerializer = Class.new(ActiveModel::Serializer) do cache key: 'post', expires_in: 0.1, skip_digest: true attributes :id, :title, :body has_many :comments belongs_to :blog belongs_to :author def blog Blog.new(id: 999, name: 'Custom blog') end def custom_options instance_options end end SpammyPostSerializer = Class.new(ActiveModel::Serializer) do attributes :id has_many :related def self.root_name 'posts' end end CommentSerializer = Class.new(ActiveModel::Serializer) do cache expires_in: 1.day, skip_digest: true attributes :id, :body belongs_to :post belongs_to :author def custom_options instance_options end end AuthorSerializer = Class.new(ActiveModel::Serializer) do cache key: 'writer', skip_digest: true attribute :id attribute :name has_many :posts has_many :roles has_one :bio end RoleSerializer = Class.new(ActiveModel::Serializer) do cache only: [:name], skip_digest: true attributes :id, :name, :description, :slug def slug "#{name}-#{id}" end belongs_to :author end LikeSerializer = Class.new(ActiveModel::Serializer) do attributes :id, :time belongs_to :likeable end LocationSerializer = Class.new(ActiveModel::Serializer) do cache only: [:place], skip_digest: true attributes :id, :lat, :lng belongs_to :place def place 'Nowhere' end end PlaceSerializer = Class.new(ActiveModel::Serializer) do attributes :id, :name has_many :locations end BioSerializer = Class.new(ActiveModel::Serializer) do cache except: [:content], skip_digest: true attributes :id, :content, :rating belongs_to :author end BlogSerializer = Class.new(ActiveModel::Serializer) do cache key: 'blog' attributes :id, :name belongs_to :writer has_many :articles end PaginatedSerializer = Class.new(ActiveModel::Serializer::ArraySerializer) do def json_key 'paginated' end end AlternateBlogSerializer = Class.new(ActiveModel::Serializer) do attribute :id attribute :name, key: :title end CustomBlogSerializer = Class.new(ActiveModel::Serializer) do attribute :id attribute :special_attribute has_many :articles end CommentPreviewSerializer = Class.new(ActiveModel::Serializer) do attributes :id belongs_to :post end AuthorPreviewSerializer = Class.new(ActiveModel::Serializer) do attributes :id has_many :posts end PostPreviewSerializer = Class.new(ActiveModel::Serializer) do def self.root_name 'posts' end attributes :title, :body, :id has_many :comments, serializer: CommentPreviewSerializer belongs_to :author, serializer: AuthorPreviewSerializer end PostWithTagsSerializer = Class.new(ActiveModel::Serializer) do attributes :id has_many :tags end PostWithCustomKeysSerializer = Class.new(ActiveModel::Serializer) do attributes :id has_many :comments, key: :reviews belongs_to :author, key: :writer has_one :blog, key: :site end VirtualValueSerializer = Class.new(ActiveModel::Serializer) do attributes :id has_many :reviews, virtual_value: [{ id: 1 }, { id: 2 }] has_one :maker, virtual_value: { id: 1 } def reviews end def maker end end Spam::UnrelatedLinkSerializer = Class.new(ActiveModel::Serializer) do cache only: [:id] attributes :id end $VERBOSE = verbose
19.751908
91
0.71343
9182ff177b2e61d2bdd5658ef6e69bfa3a724036
1,016
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) Gem::Specification.new do |spec| spec.name = "razor-mk-agent" spec.version = "009" spec.authors = ["Puppet"] spec.email = ["[email protected]"] spec.description = "The agent for Razor Microkernels" spec.summary = "The OS-independent bits of a Razor Microkernel" spec.homepage = "" spec.license = "ASL2" spec.files = `git ls-files`.split($/) spec.bindir = "bin" spec.executables = ['mk'] spec.test_files = spec.files.grep(%r{^spec/}) spec.require_paths = ["lib"] # @todo lutter 2013-08-20: we really do depend on facter, but because of # how we build the microkernel, we can't fulfill it from rubygems, and # use the RPM packaged facter instead which is not a rubygem # spec.add_dependency "facter" spec.add_development_dependency "bundler", "~> 1.3" spec.add_development_dependency "rake" end
35.034483
74
0.652559
1a216fae893cf5c6626c6aead050ad6ecfca5cdd
475
class SessionsController < ApplicationController def new end def create @user = User.find_by(email: params[:session][:email]) if @user && @user.authenticate(params[:session][:password]) session[:user_id] = @user.id redirect_to user_path(@user.id) else flash.now[:danger] = 'Invalid email/password combination' render 'new' end end def destroy reset_session @current_user = nil redirect_to root_path end end
19.791667
63
0.667368
1cf2e311ed1daf62dc2ca86ed7fcc2642afff7c5
2,502
module OrgTodoist class Calendar attr_reader :cal def initialize client_id, client_sec, calendar_id @cal = Google::Calendar.new(:client_id => client_id, :client_secret => client_sec, :calendar => calendar_id, :redirect_url => "urn:ietf:wg:oauth:2.0:oob") @authorized = false end def try_authorize return true if @authorized authorize end def authorize refresh_token=ENV['CAL_REFRESH_TOKEN'] if refresh_token cal.login_with_refresh_token(refresh_token) else interactive_authorize end @authorized = true end def post_plan title, start_at, stop_at try_authorize event = cal.create_event do |e| e.title = title e.start_time = start_at e.end_time = stop_at end p event # log.logged_to_calendar! event end # --------- for setup -------------------------------------------------- def interactive_authorize # A user needs to approve access in order to work with their calendars. puts "Visit the following web page in your browser and approve access." puts cal.authorize_url system("open '#{cal.authorize_url}'") puts "\nCopy the code that Google returned and paste it here:" # Pass the ONE TIME USE access code here to login and get a refresh token that you can use for access from now on. refresh_token = cal.login_with_auth_code( $stdin.gets.chomp ) puts "\nMake sure you SAVE YOUR REFRESH TOKEN so you don't have to prompt the user to approve access again." puts "your refresh token is:\n\t#{refresh_token}\n" puts "Press return to continue" $stdin.gets.chomp puts "Do you want to try GET and POST? (y/n)" try_api = $stdin.gets.chomp if try_api == 'y' test_refresh_token end end def test_refresh_token event = cal.create_event do |e| e.title = 'A Cool Event' e.start_time = Time.now e.end_time = Time.now + (60 * 60) # seconds * min end puts event event = cal.find_or_create_event_by_id(event.id) do |e| e.title = 'An Updated Cool Event' e.end_time = Time.now + (60 * 60 * 2) # seconds * min * hours end puts event # All events puts cal.events # Query events puts cal.find_events('Cool') end end end
30.144578
120
0.593525
01328cb6234b3b19a57b5fad944a5d17f395ea1f
1,115
class Cc65 < Formula desc "6502 C compiler" homepage "https://cc65.github.io/cc65/" url "https://github.com/cc65/cc65/archive/V2.17.tar.gz" sha256 "73b89634655bfc6cef9aa0b8950f19657a902ee5ef0c045886e418bb116d2eac" head "https://github.com/cc65/cc65.git" bottle do # sha256 "d8238bad77a894edec5e5caefd7ae6c738177a04455024a7c2cb3d44db3a4d85" => :mojave sha256 "12c9533c600dda022dc121f51f668648cd89a98e407e02aeb2119c21d8e8cc54" => :high_sierra sha256 "f470bfeec0cc01b3da7656945e401815a852f2d6fbca5197f9dd41dc3391a539" => :sierra sha256 "46e8dc043981d55e0b62e77cd12dae35b1ab13b3164f1510010e73bbe8ee76a9" => :el_capitan end conflicts_with "grc", :because => "both install `grc` binaries" def install system "make", "PREFIX=#{prefix}" system "make", "install", "PREFIX=#{prefix}" end def caveats <<~EOS Library files have been installed to: #{pkgshare} EOS end test do (testpath/"foo.c").write "int main (void) { return 0; }" system bin/"cl65", "foo.c" # compile and link assert_predicate testpath/"foo", :exist? # binary end end
30.972222
93
0.726457
03b16eccd7df6ca1d26b17ef45ff51f682a0192d
52
json.partial! "products/product", product: @product
26
51
0.769231
ff3b7a65ce1f025ea8656ead34c47d975ec23506
1,451
module Api class CoursesController < ApplicationController respond_to :json load_and_authorize_resource include Response def graphql @course = Course.find(params[:course_id]) query = params[:query] accept = params[:accept] results = perform_graphql_query(query,accept) json_response(results.to_hash) end def commits @course = Course.find(params[:course_id]) json_response(@course.commits) end def orphans @course = Course.find(params[:course_id]) orphan_author_emails = @course.orphan_author_emails.map{ |k,v| {email: k, count: v} } orphan_author_names = @course.orphan_author_names.map{ |k,v| {name: k, count: v} } response = { course: @course, orphan_author_emails: orphan_author_emails, orphan_author_names: orphan_author_names } json_response(response) end private def perform_graphql_query(graphql_query_string, accept) puts("perform graphqlquery") data = { :query => graphql_query_string }.to_json options = accept ? { :headers => { :accept => accept } } : {} result = github_machine_user.send :request, :post, '/graphql', data, options result end def github_machine_user Octokit_Wrapper::Octokit_Wrapper.machine_user end respond_to :json load_and_authorize_resource def index end end end
25.017241
122
0.653343
5d6193d0daea197e336a6bfa12337f19deed6f60
389
cask 'soundsource' do version '4.0.0' sha256 '1a5bc1dc714e8cec80aebf92d14b200fc094e8066ca5bf49b8a41a6a37788ae5' url 'https://rogueamoeba.com/soundsource/download/SoundSource.zip' appcast 'https://rogueamoeba.com/soundsource/releasenotes.php' name 'SoundSource' homepage 'https://rogueamoeba.com/soundsource/' depends_on macos: '>= :el_capitan' app 'SoundSource.app' end
27.785714
75
0.77635
111685ba60e57ebc3bf0e97b7069051434010044
153
require 'jcropper' require 'rails' module Jcropper class Railtie < Rails::Railtie rake_tasks do load "tasks/jcropper.rake" end end end
15.3
32
0.699346
fff3b6b367348b553a60178e7b18454b41efa43b
1,389
module Connect module ControllerAdditions extend ActiveSupport::Concern included do include Connect::ControllerAdditions::Helper helper Connect::ControllerAdditions::Helper end module Helper def current_access_token @current_token ||= request.env[Rack::OAuth2::Server::Resource::ACCESS_TOKEN] end def current_oauth_scopes token = (current_access_token && current_access_token.scopes) || [] end def has_oauth_scope? scope current_oauth_scopes.detect{|s| s.name == scope} end end def require_user_access_token require_access_token raise Rack::OAuth2::Server::Resource::Bearer::Unauthorized.new(:invalid_token, 'User token is required') unless current_access_token.account end def require_client_access_token require_access_token raise Rack::OAuth2::Server::Resource::Bearer::Unauthorized.new(:invalid_token, 'Client token is required') if current_access_token.account end def require_access_token if current_access_token.nil? raise Rack::OAuth2::Server::Resource::Bearer::Unauthorized.new end if !current_access_token.accessible? required_scopes raise Rack::OAuth2::Server::Resource::Bearer::Forbidden.new(:insufficient_scope) end end def required_scopes nil # as default end end end
28.346939
146
0.708423
6a5c057384fed4789523270cd4cc9e297edfbaa1
4,813
require 'active_support/core_ext/module/attribute_accessors' module ActiveRecord module AttributeMethods module Dirty # :nodoc: extend ActiveSupport::Concern include ActiveModel::Dirty included do if self < ::ActiveRecord::Timestamp raise "You cannot include Dirty after Timestamp" end class_attribute :partial_writes, instance_writer: false self.partial_writes = true end # Attempts to +save+ the record and clears changed attributes if successful. def save(*) if status = super changes_applied end status end # Attempts to <tt>save!</tt> the record and clears changed attributes if successful. def save!(*) super.tap do changes_applied end end # <tt>reload</tt> the record and clears changed attributes. def reload(*) super.tap do reset_changes end end def initialize_dup(other) # :nodoc: super init_changed_attributes end def changed? super || changed_in_place.any? end def changed super | changed_in_place end def attribute_changed?(attr_name, options = {}) result = super # We can't change "from" something in place. Only setters can define # "from" and "to" result ||= changed_in_place?(attr_name) unless options.key?(:from) result end def changes_applied super store_original_raw_attributes end def reset_changes super original_raw_attributes.clear end private def initialize_internals_callback super init_changed_attributes end def init_changed_attributes @changed_attributes = nil # Intentionally avoid using #column_defaults since overridden defaults (as is done in # optimistic locking) won't get written unless they get marked as changed self.class.columns.each do |c| attr, orig_value = c.name, c.default changed_attributes[attr] = orig_value if _field_changed?(attr, orig_value) end end # Wrap write_attribute to remember original attribute value. def write_attribute(attr, value) attr = attr.to_s old_value = old_attribute_value(attr) result = super store_original_raw_attribute(attr) save_changed_attribute(attr, old_value) result end def raw_write_attribute(attr, value) attr = attr.to_s result = super original_raw_attributes[attr] = value result end def save_changed_attribute(attr, old_value) if attribute_changed?(attr) changed_attributes.delete(attr) unless _field_changed?(attr, old_value) else changed_attributes[attr] = old_value if _field_changed?(attr, old_value) end end def old_attribute_value(attr) if attribute_changed?(attr) changed_attributes[attr] else clone_attribute_value(:read_attribute, attr) end end def _update_record(*) partial_writes? ? super(keys_for_partial_write) : super end def _create_record(*) partial_writes? ? super(keys_for_partial_write) : super end # Serialized attributes should always be written in case they've been # changed in place. def keys_for_partial_write changed end def _field_changed?(attr, old_value) new_value = read_attribute(attr) raw_value = read_attribute_before_type_cast(attr) column_for_attribute(attr).changed?(old_value, new_value, raw_value) end def changed_in_place self.class.attribute_names.select do |attr_name| changed_in_place?(attr_name) end end def changed_in_place?(attr_name) type = type_for_attribute(attr_name) old_value = original_raw_attribute(attr_name) value = read_attribute(attr_name) type.changed_in_place?(old_value, value) end def original_raw_attribute(attr_name) original_raw_attributes.fetch(attr_name) do read_attribute_before_type_cast(attr_name) end end def original_raw_attributes @original_raw_attributes ||= {} end def store_original_raw_attribute(attr_name) type = type_for_attribute(attr_name) value = type.type_cast_for_database(read_attribute(attr_name)) original_raw_attributes[attr_name] = value end def store_original_raw_attributes attribute_names.each do |attr| store_original_raw_attribute(attr) end end end end end
26.445055
93
0.641388
112a5f1bce236eb6ab70db2c6ee21564ca25d79b
3,028
# frozen_string_literal: true module GraphQL module DSL ## # This mixin help to reuse selections sets module SelectionSet ## # Declare new GraphQL field # # This method can help to avoid name collisions i.e. +__field(:object_id)+ # # @param name [String, Symbol] field name # @param __alias [String, Symbol, nil] field alias # @param __directives [Array] list of directives # @param arguments [Hash] field arguments # @param block [Proc] declare sub-fields # # @return [void] # # @example Declare fields use __field method (i.e. use GraphQL query) # query = GraphQL::DSL.query { # __field(:field1, id: 1) { # __field(:subfield1, id: 1) # __field(:subfield2, id: 2) # } # } # # @example Declare fields use DSL (i.e. use GraphQL query) # query = GraphQL::DSL.query { # field1 id: 1 { # subfield1 id: 1 # subfield2 id: 2 # } # } def __field(name, __alias: nil, __directives: [], **arguments, &block) # rubocop:disable Lint/UnderscorePrefixedVariableName @__nodes << Field.new(name, __alias, arguments, __directives, &block) end ### # Insert GraphQL fragment # # @param name [String, Symbol] fragment name # @param __directives [Array] list of directives # # @return [void] # # @example Insert fragment with +fragment1+ name # query = GraphQL::DSL.query { # field1 id: 1 { # __fragment :fragment1 # } # } def __fragment(name, __directives: []) # rubocop:disable Lint/UnderscorePrefixedVariableName @__nodes << FragmentSpread.new(name, __directives) end ### # Insert GraphQL inline fragment # # @param type [String, Symbol, nil] fragment type # @param __directives [Array] list of directives # @param block [Proc] declare DSL for sub-fields # # @return [void] def __inline_fragment(type, __directives: [], &block) # rubocop:disable Lint/UnderscorePrefixedVariableName @__nodes << InlineFragment.new(type, __directives, &block) end private ## # Allow to respond to method missing at any case. def respond_to_missing?(_method_name, _include_private = false) true end ## # Declare new GraphQL field # # @example Declare fields (i.e. use GraphQL query) # query = GraphQL::DSL.query { # items { # id # title # } # } # # puts query.to_gql # # { # # items # # { # # id # # title # # } # # } # # @see #__field def method_missing(name, *args, &block) arguments = args.empty? ? {} : args[0] __field(name, **arguments, &block) end end end end
28.299065
130
0.543593
79174fd58f2d007a08a2f28f07fe4332a91ee519
1,842
# -*- encoding: utf-8 -*- # stub: machinist 2.0 ruby lib Gem::Specification.new do |s| s.name = "machinist".freeze s.version = "2.0" s.required_rubygems_version = Gem::Requirement.new(">= 0".freeze) if s.respond_to? :required_rubygems_version= s.require_paths = ["lib".freeze] s.authors = ["Pete Yandell".freeze] s.date = "2012-01-13" s.email = ["[email protected]".freeze] s.homepage = "http://github.com/notahat/machinist".freeze s.rubyforge_project = "machinist".freeze s.rubygems_version = "2.6.10".freeze s.summary = "Fixtures aren't fun. Machinist is.".freeze s.installed_by_version = "2.6.10" if s.respond_to? :installed_by_version if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<activerecord>.freeze, [">= 0"]) s.add_development_dependency(%q<mysql>.freeze, [">= 0"]) s.add_development_dependency(%q<rake>.freeze, [">= 0"]) s.add_development_dependency(%q<rcov>.freeze, [">= 0"]) s.add_development_dependency(%q<rspec>.freeze, [">= 0"]) s.add_development_dependency(%q<rdoc>.freeze, [">= 0"]) else s.add_dependency(%q<activerecord>.freeze, [">= 0"]) s.add_dependency(%q<mysql>.freeze, [">= 0"]) s.add_dependency(%q<rake>.freeze, [">= 0"]) s.add_dependency(%q<rcov>.freeze, [">= 0"]) s.add_dependency(%q<rspec>.freeze, [">= 0"]) s.add_dependency(%q<rdoc>.freeze, [">= 0"]) end else s.add_dependency(%q<activerecord>.freeze, [">= 0"]) s.add_dependency(%q<mysql>.freeze, [">= 0"]) s.add_dependency(%q<rake>.freeze, [">= 0"]) s.add_dependency(%q<rcov>.freeze, [">= 0"]) s.add_dependency(%q<rspec>.freeze, [">= 0"]) s.add_dependency(%q<rdoc>.freeze, [">= 0"]) end end
39.191489
112
0.637894
91441aa9829be709eb1d2db56cb9c59f1769ab59
341
class Subject < ActiveRecord::Base def records Record.where("metadata->'650' @> '[{\"0\" : \"#{identifier}\"}]'::jsonb") end def related_subjects @related_subjects ||= begin if related_identifiers.length > 0 Subject.where(identifier: related_identifiers) else [] end end end end
14.826087
77
0.59824
26a31e827e2537268524ee761ed8615dadcb8f20
2,427
# frozen_string_literal: true class SchemesController < ApplicationController before_action :authenticate_user!, except: :show before_action :set_scheme, except: %i[create new] before_action :process_scheme_params, only: %i[create] before_action :set_channel, only: %i[show] before_action :set_app def show if @channel redirect_to channel_path(@channel) else redirect_to new_app_scheme_channel_path(@scheme.app, @scheme), alert: t('schemes.show.empty_channel') end end def new @title = t('schemes.new.title', app: @app.name) @scheme = Scheme.new authorize @scheme end def create channels = scheme_params.delete(:channel_attributes)[:name].reject(&:empty?) @scheme = Scheme.new(scheme_params) authorize @scheme @scheme.app = @app return render :new unless @scheme.save create_channels(channels) redirect_to app_path(@app), notice: t('activerecord.success.create', key: t('schemes.title')) end def edit @title = t('schemes.edit.title', app: @app.name) end def update @scheme.update(scheme_params) redirect_to app_path(@app) end def destroy @scheme.destroy redirect_to app_path(@app) end protected def create_channels(channels) return if channels.empty? channels.each do |channel_name| @scheme.channels.create name: channel_name, device_type: channel_name.downcase.to_sym end end def set_app @app = App.find(params[:app_id]) end def set_scheme @scheme = Scheme.find(params[:id]) authorize @scheme end def scheme_params @scheme_params ||= params.require(:scheme) .permit(:name, channel_attributes: { name: [] }) end def set_channel from_channel, segment = from_channel? unless from_channel @channel = @scheme.latest_channel return end previouse_channel = Channel.friendly.find(segment[:id]) @channel = @scheme.channels.find_by(device_type: previouse_channel.device_type) end def process_scheme_params @channels = scheme_params[:channel_attributes][:name].reject(&:empty?) end def from_channel? return [false, nil] unless referer = request.referer return [false, nil] unless segment = Rails.application.routes.recognize_path(referer) from_channel = segment[:controller] == 'channels' && segment[:action] == 'show' [from_channel, segment] end end
24.515152
107
0.695509
7988bdcbf684e0cf0f5140ecdb5d68144aaef8d6
5,454
require 'chef/provider/lwrp_base' require 'shellwords' require_relative 'helpers' require_relative 'helpers_rhel' class Chef class Provider class MysqlService class Rhel < Chef::Provider::MysqlService use_inline_resources if defined?(use_inline_resources) def whyrun_supported? true end include MysqlCookbook::Helpers::Rhel include Opscode::Mysql::Helpers action :create do unless sensitive_supported? Chef::Log.debug("Sensitive attribute disabled, chef-client version #{Chef::VERSION} is lower than 11.14.0") end # we need to enable the yum-mysql-community repository to get packages unless node['platform_version'].to_i == 5 case new_resource.parsed_version when '5.5' recipe_eval do run_context.include_recipe 'yum-mysql-community::mysql55' end when '5.6' recipe_eval do run_context.include_recipe 'yum-mysql-community::mysql56' end end end package new_resource.parsed_package_name do action new_resource.parsed_package_action version new_resource.parsed_package_version end directory include_dir do owner 'mysql' group 'mysql' mode '0750' recursive true action :create end directory run_dir do owner 'mysql' group 'mysql' mode '0755' recursive true action :create end directory new_resource.parsed_data_dir do owner 'mysql' group 'mysql' mode '0755' recursive true action :create end service service_name do supports :restart => true action [:start, :enable] end execute 'wait for mysql' do command "until [ -S #{socket_file} ] ; do sleep 1 ; done" timeout 10 action :run end template '/etc/mysql_grants.sql' do sensitive true if sensitive_supported? cookbook 'mysql' source 'grants/grants.sql.erb' owner 'root' group 'root' mode '0600' variables(:config => new_resource) action :create notifies :run, 'execute[install-grants]' end execute 'install-grants' do sensitive true if sensitive_supported? cmd = "#{prefix_dir}/bin/mysql" cmd << ' -u root ' cmd << "#{pass_string} < /etc/mysql_grants.sql" command cmd action :nothing notifies :run, 'execute[create root marker]' end template "#{base_dir}/etc/my.cnf" do if new_resource.parsed_template_source.nil? source "#{new_resource.parsed_version}/my.cnf.erb" cookbook 'mysql' else source new_resource.parsed_template_source end owner 'mysql' group 'mysql' mode '0600' variables( :base_dir => base_dir, :data_dir => new_resource.parsed_data_dir, :include_dir => include_dir, :lc_messages_dir => lc_messages_dir, :pid_file => pid_file, :port => new_resource.parsed_port, :socket_file => socket_file, :enable_utf8 => new_resource.parsed_enable_utf8 ) action :create notifies :run, 'bash[move mysql data to datadir]' notifies :restart, "service[#{service_name}]" end bash 'move mysql data to datadir' do user 'root' code <<-EOH service #{service_name} stop \ && for i in `ls #{base_dir}/var/lib/mysql | grep -v mysql.sock` ; do mv #{base_dir}/var/lib/mysql/$i #{new_resource.parsed_data_dir} ; done EOH action :nothing creates "#{new_resource.parsed_data_dir}/ibdata1" creates "#{new_resource.parsed_data_dir}/ib_logfile0" creates "#{new_resource.parsed_data_dir}/ib_logfile1" end execute 'assign-root-password' do sensitive true if sensitive_supported? cmd = "#{prefix_dir}/bin/mysqladmin" cmd << ' -u root password ' cmd << Shellwords.escape(new_resource.parsed_server_root_password) command cmd action :run only_if "#{prefix_dir}/bin/mysql -u root -e 'show databases;'" end execute 'create root marker' do sensitive true if sensitive_supported? cmd = '/bin/echo' cmd << " '#{Shellwords.escape(new_resource.parsed_server_root_password)}'" cmd << ' > /etc/.mysql_root' cmd << ' ;/bin/chmod 0600 /etc/.mysql_root' command cmd action :nothing end end action :restart do service service_name do supports :restart => true action :restart end end action :reload do service service_name do action :reload end end end end end end
31.165714
153
0.540337
8788a3eebbf8ccddc8e4fa4ec1288e608c1b8ac9
2,373
class Imake < Formula desc "Build automation system written for X11" homepage "https://xorg.freedesktop.org" url "https://xorg.freedesktop.org/releases/individual/util/imake-1.0.8.tar.bz2" sha256 "b8d2e416b3f29cd6482bcffaaf19286d32917a164d07102a0e531ccd41a2a702" license "MIT" revision 3 bottle do sha256 arm64_big_sur: "7eafaa82ad84b47d8f4bd76bdca5ccfa065f622ea31b1d2c05fb316af8f60015" sha256 big_sur: "c382f4319ca3b0138c5d20bfeea095d76ca9c972e166550b58f259f03a5d267c" sha256 catalina: "fadd526555076cbe59ef74e14456c732a084230e3bf23a78df259f222b11b4fc" sha256 mojave: "211e42f25de025770eae0cf3b5ca2c5f03821a809009e0111115f808cd498ab1" sha256 high_sierra: "582ea346c5d5caaa38795e2221172358b584e22cfe25ec48cacf78467272b257" end depends_on "pkg-config" => :build depends_on "xorgproto" => :build depends_on "gcc" resource "xorg-cf-files" do url "https://xorg.freedesktop.org/releases/individual/util/xorg-cf-files-1.0.6.tar.bz2" sha256 "4dcf5a9dbe3c6ecb9d2dd05e629b3d373eae9ba12d13942df87107fdc1b3934d" end def install ENV.deparallelize # imake runtime is broken when used with clang's cpp gcc_major_ver = Formula["gcc"].any_installed_version.major cpp_program = Formula["gcc"].opt_bin/"cpp-#{gcc_major_ver}" (buildpath/"imakemdep.h").append_lines [ "#define DEFAULT_CPP \"#{cpp_program}\"", "#undef USE_CC_E", ] inreplace "imake.man", /__cpp__/, cpp_program # also use gcc's cpp during buildtime to pass ./configure checks ENV["RAWCPP"] = cpp_program system "./configure", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" resource("xorg-cf-files").stage do # Fix for different X11 locations. inreplace "X11.rules", "define TopXInclude /**/", "define TopXInclude -I#{HOMEBREW_PREFIX}/include" system "./configure", "--with-config-dir=#{lib}/X11/config", "--prefix=#{HOMEBREW_PREFIX}" system "make", "install" end end test do # Use pipe_output because the return code is unimportant here. output = pipe_output("#{bin}/imake -v -s/dev/null -f/dev/null -T/dev/null 2>&1") gcc_major_ver = Formula["gcc"].any_installed_version.major assert_match "#{Formula["gcc"].opt_bin}/cpp-#{gcc_major_ver}", output end end
38.901639
92
0.71555
18b0a8499129a3acb9ae431852675c6445366851
291
class Cms::Column::Base include SS::Document include SS::Model::Column include Cms::Addon::Column::Layout include SS::Reference::Site store_in collection: 'cms_columns' def alignment_options %w(flow center).map { |v| [ I18n.t("cms.options.alignment.#{v}"), v ] } end end
22.384615
75
0.687285
ed99c67ba7c2e38f142a1c2b7198c5738e112c85
2,000
require 'test_helper' class TestOperatorSkipWhile < Minitest::Test include Rx::MarbleTesting def test_ignore_values_until_block_falsy source = cold(' -123456|') expected = msgs('------456|') source_subs = subs(' ^ !') actual = scheduler.configure do source.skip_while { |x| x < 4 } end assert_msgs expected, actual assert_subs source_subs, source end end class TestOperatorSkipWhileWithIndex < Minitest::Test include Rx::MarbleTesting def test_ignore_values_until_block_falsy source = cold(' -54321|') expected = msgs('------21|') source_subs = subs(' ^ !') actual = scheduler.configure do source.skip_while_with_index { |x, i| x > i } end assert_msgs expected, actual assert_subs source_subs, source end def test_stops_calling_block_after_false call_count = 0 source = cold(' -54321|') scheduler.configure do source.skip_while_with_index do |x, i| call_count += 1 x > i end end assert_equal 4, call_count end def test_respects_nil_as_value source = cold(' -a|', a: nil) expected = msgs('---a|', a: nil) source_subs = subs(' ^ !') actual = scheduler.configure do source.skip_while_with_index { |x, _| false } end assert_msgs expected, actual assert_subs source_subs, source end def test_erroring_block source = cold(' -1') expected = msgs('---#') source_subs = subs(' ^!') actual = scheduler.configure do source.skip_while_with_index { |_, _| raise error } end assert_msgs expected, actual assert_subs source_subs, source end def test_propagates_error source = cold(' -#') expected = msgs('---#') source_subs = subs(' ^!') actual = scheduler.configure do source.skip_while_with_index { |x, i| [i, x] } end assert_msgs expected, actual assert_subs source_subs, source end end
22.727273
57
0.629
f8b940650b58a4ca6a4e27311395401343baf1cf
542
Puppet::Type.newtype(:mysql_database) do @doc = 'Manage MySQL databases.' ensurable autorequire(:file) { '/root/.my.cnf' } autorequire(:class) { 'mysql::server' } newparam(:name, namevar: true) do desc 'The name of the MySQL database to manage.' end newproperty(:charset) do desc 'The CHARACTER SET setting for the database' defaultto :utf8 newvalue(%r{^\S+$}) end newproperty(:collate) do desc 'The COLLATE setting for the database' defaultto :utf8_general_ci newvalue(%r{^\S+$}) end end
21.68
53
0.667897
1ccc99d3095734f68f2b5b35cb8c2a301ca3cb5b
1,626
# frozen_string_literal: true require_relative "lib/rails_sortable/version" Gem::Specification.new do |spec| spec.name = "rails_sortable" spec.version = RailsSortable::VERSION spec.authors = ["Conor Devine"] spec.email = ["[email protected]"] spec.summary = "A gem for sorting activerecord objects based on https://github.com/itmammoth/rails_sortable" spec.homepage = "https://github.com/cdevine49/rails_sortable" spec.license = "MIT" spec.required_ruby_version = Gem::Requirement.new(">= 2.4.0") spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'" spec.metadata["homepage_uri"] = spec.homepage spec.metadata["source_code_uri"] = "https://github.com/cdevine49/rails_sortable/tree/v#{RailsSortable::VERSION}" spec.metadata["changelog_uri"] = "https://github.com/cdevine49/rails_sortable/releases/tag/v#{RailsSortable::VERSION}" # Specify which files should be added to the gem when it is released. # The `git ls-files -z` loads the files in the RubyGem that have been added into git. spec.files = Dir.chdir(File.expand_path(__dir__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] # Uncomment to register a new dependency of your gem # spec.add_dependency "example-gem", "~> 1.0" # For more information and examples about making a new gem, checkout our # guide at: https://bundler.io/guides/creating_gem.html end
43.945946
120
0.698032
3396321c3b8fdff1bf783a00d03840657c594da4
1,534
Pod::Spec.new do |s| s.name = "ADXLibrary-Cauly" s.version = "1.9.1" s.summary = "ADX Library for iOS" s.license = {"type"=>"MIT", "file"=>"LICENSE"} s.authors = {"Chiung Choi"=>"[email protected]"} s.homepage = "https://github.com/adxcorp/AdxLibrary_iOS" s.description = "ADX Library for iOS" s.source = { :git => 'https://github.com/adxcorp/AdxLibrary_iOS_Release.git', :tag => s.version.to_s } s.ios.deployment_target = '10.0' s.frameworks = 'Accelerate', 'AdSupport', 'AudioToolbox', 'AVFoundation', 'CFNetwork', 'CoreGraphics', 'CoreMotion', 'CoreMedia', 'CoreTelephony', 'Foundation', 'GLKit', 'MobileCoreServices', 'MediaPlayer', 'QuartzCore', 'StoreKit', 'SystemConfiguration', 'UIKit', 'VideoToolbox', 'WebKit' s.dependency 'mopub-ios-sdk', '5.17.0' s.dependency 'Google-Mobile-Ads-SDK', '8.5.0' s.ios.vendored_framework = 'ios/ADXLibrary-Cauly.framework' s.library = 'z', 'sqlite3', 'xml2', 'c++' s.pod_target_xcconfig = { 'ENABLE_BITCODE' => 'NO', 'OTHER_LDFLAGS' => '-ObjC', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64'} s.user_target_xcconfig = { 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'arm64' } end
36.52381
132
0.509126
1a2fbe85527466675a60bc7afc88ee89d5103a4a
1,835
# frozen_string_literal: true require 'mini_nrepl/clj' module MiniNrepl # Clojure fn's atop Clj module CljLib include Clj extend self # rubocop:disable ModuleFunction # @param path [String] Path to clojure file with ns declaration # @return [String] Clojure code to read ns name from given filesystem path def read_ns(path) # rubocop:disable MethodLength do_( require_ns('clojure.tools.namespace.parse'), let( { 'read-ns' => fn(['path'], thread_last( '(clojure.java.io/reader path)', '(java.io.PushbackReader.)', '(clojure.tools.namespace.parse/read-ns-decl)' )), 'extract-ns-name' => fn(['ns-form'], '(when ns-form (nth ns-form 1))') }, thread_last( to_clj(path), '(read-ns)', '(extract-ns-name)' ) ) ) end def read_ns_from_code(code) do_( require_ns('clojure.tools.namespace.parse'), let( { 'read-ns' => fn(['code'], thread_last( '(java.io.StringReader. code)', '(clojure.java.io/reader)', '(java.io.PushbackReader.)', '(clojure.tools.namespace.parse/read-ns-decl)' )), 'extract-ns-name' => fn(['ns-form'], '(when ns-form (nth ns-form 1))') }, thread_last( to_clj(code), '(read-ns)', '(extract-ns-name)' ) ) ) end end end
28.671875
78
0.429428
ff7a0c8b0e8b8664774e6e29e743169fcf0d8589
184
# frozen_string_literal: true require 'tencentcloud-sdk-common' require_relative 'v20201127/client' require_relative 'v20201127/models' module TencentCloud module Apcas end end
15.333333
35
0.815217
bb24420247aadbd59d4faa30419805cb2c2e78cf
188
module Sinatra module Helpers def current_user @user = User.find(session[:user_id]) end def is_logged_in? !!session[:user_id] end end end
14.461538
43
0.574468
1d9f3ab8ad84dad2c6435da48b8ec16e62aab865
323
require "notification_file_lookup" module NotificationHelper include ActionView::Helpers::TagHelper def banner_notification if node = Static.banner content_tag(:section, "<div>#{node[:file]}</div>", {:id => "banner-notification", :class => node[:colour]}, false) else '' end end end
21.533333
71
0.659443
bbedc70481f9eedff49e4174bbca13d331d32006
3,726
class PetAdoptions::CLI BUDDIES = ["Dogs", "Cats","Rabbits", "Birds", "Equine", "Pigs", "Barnyard", "Small"] def call puts "\nWelcome to PetAdoptions. Where you can find your next Bud".light_blue puts "-----------------------------------------------------------" start end def start puts "\n Please check out the list of all buddies, and, wish you the very best in your search for your next Best Buddy! (Please enter a number)".cyan puts "-----------------------------------------------------------------------------------------------------------------------------------------\n" puts " " BUDDIES.each.with_index(1) do |buddy, number| puts "#{number}. #{buddy}" end puts " " user_input = numbers(gets.chomp) if !user_input.between?(0,BUDDIES.size-1) puts "\n Sorry. Please try again.\n".red start end puts "\n Thank you. Just a moment as we look up the list of available #{BUDDIES[user_input].downcase}...".light_magenta @tribe_member = tribe_memeber_definition(user_input) BuddyCount.new(BUDDIES[user_input], @tribe_member) display_allbuddies end def display_allbuddies if @tribe_member == Small puts "\n\nAVAILABLE SMALL & FURRY ANIMALS FOR ADOPTION:".light_blue else puts "\n\nAVAILABLE #{@tribe_member.to_s.upcase} FOR ADOPTION:".light_blue end puts "Name - Breed - Age".light_magenta puts "-----------------------------" buddy_gang = @tribe_member.all buddy_gang.each.with_index(1) {|bud, num| puts "#{num}. #{bud.name} - #{bud.breed} - #{bud.age}"} puts "\nWhich pet would you like more information on? (Please enter a number)".cyan puts " " buddy_number = numbers(gets.chomp) if buddy_number < 0 || buddy_number >= buddy_gang.size puts "I'm sorry, that was an incorrect entry. Please try again.".red display_allbuddies end BuddyCount.additonal_features_of_buds(buddy_number, @tribe_member) display(buddy_number) end def display(num) bud=@tribe_member.all[num] if bud.species == "small-furry".light_blue puts "\n#{bud.name.upcase} - Small & Furry".light_blue else puts "\n#{bud.name.upcase} - #{bud.species.capitalize}" end puts "------------------------------" puts "Breed:".green+ " #{bud.breed}" puts "Age:".green+ " #{bud.age}" puts "Color:".green + " #{bud.color}" puts "Sex:".green + " #{bud.sex}" puts "Size:".green + "#{bud.size}\n\n" puts "Description:".green + "#{bud.description}\n\n" puts "Love to adopt more buds like #{bud.name}, visit www.bestfriends.org #{bud.url}" repeat? end def repeat? puts "\n\nWould you like to search more adoptable buddies? (Please enter a number)\n".cyan puts "1. Yes. Take me back to the list of buddies #{@tribe_member.to_s.downcase}.".light_magenta puts "2. Take me to the main menu.".light_magenta puts "3. No, I'm done.\n\n".light_magenta user_input = gets.chomp if user_input == "1" display_allbuddies elsif user_input == "2" start elsif user_input == "3" exit else puts "Sorry! Incorrect entry. Pleae try again!".red repeat? end end def numbers(user_input) user_input.to_i - 1 end def tribe_memeber_definition(user_input) Object.const_get("#{BUDDIES[user_input]}") end end
27.397059
155
0.545894
01d82fb5e43ee243aa9861f20db8d382db5bba7c
5,868
# == Ruby Version Manager - Ruby API # # Provides a wrapper around the command line api implemented as part of the api. # If you're not familiar with rvm, please read https://rvm.beginrescueend.com/ # first. # # == Usage # # When using the rvm ruby api, you gain access to most of the commands, including the set # functionality. As a side node, the RVM module provides access to most of the api # both via direct api wrappers (of the form <tt><tool>_<action></tt> - e.g. +alias_create+, # +gemset_use+ and +wrapper+). # # == The Environment Model # # The RVM ruby api is implemented using an environment model. Each environment maps directly # to some ruby string interpretable by rvm (e.g. +ree+, +ruby-1.8.7-p174+, +system+, +rbx@rails+ # and so on) and is considered a sandboxed environment (for commands like use etc) in which you # can deal with rvm. it's worth noting that a single environment can have multiple environment # instances and for the most part creating of these instances is best handled by the RVM.environment # and RVM.environments methods. # # Each Environment (and instance of RVM::Environment) provides access to the rvm ruby api (in some # cases, the api may not directly be related to the current ruby - but for simplicity / consistency # purposes, they are still implemented as methods of RVM::Environment). # # When you perform an action with side effects (e.g. RVM::Environment#gemset_use or RVM::Environment#use) # this will mutate the ruby string of the given environment (hence, an environment is considered mutable). # # Lastly, for the actual command line work, RVM::Environment works with an instance of RVM::Shell::AbstractWrapper. # This performs logic (such as correctly escaping strings, calling the environment and such) in a way that # is both reusable and simplified. # # By default, method_missing is used on the RVM module to proxy method calls to RVM.current (itself # calling RVM::Environment.current), meaning things like RVM.gemset_name, RVM.alias_create and the like # work. This is considered the 'global' instance and should be avoided unless needed directly. # # RVM::Environment.current will first attempt to use the current ruby string (determined by # +ENV['GEM_HOME']+ but will fall back to using the rubies load path if that isn't available). # # In many cases, (e.g. +alias+, +list+ and the like) there is a more ruby-like wrapper class, # typically available via <tt>RVM::Environment#<action></tt>. # # == Side Notes # # In the cases this api differs, see the RVM::Environment class for more information. # # You can check the name of a given environment in two ways - RVM::Environment#environment_name # for the short version / the version set by RVM::Environment#use, RVM::Environment#gemset_use # or RVM.environment. If you wish to get the full, expanded string (which has things such as # the actual version of the selected ruby), you instead with to use RVM::Environment#expanded_name. # # Lastly, If you do need to pass environment variables to a specific environment, please use # RVM::Environment.new, versus RVM.environment # module RVM VERSION = "1.9.2" require "rvm/errors" require "rvm/shell" require "rvm/environment" require "rvm/version" class << self # Returns the current global environment. def current Environment.current end # Reset the current global environment to the default / what it was # when the process first started. def reset_current! Environment.reset_current! end # Returns an array of multiple environments. If given # a block, will yield each time with the given environment. # # RVM.environments("ree@rails3,rbx@rails3") do |env| # puts "Full environment: #{env.expanded_name}" # end # # => "ree-1.8.7@rails3" # # => "rbx-1.1.0@rails3" # Suppose that you are installed rbx 1.1.0 # # Alternatively, you can use the more ruby-like fashion: # # RVM.environments("ree@rails3", "rbx@rails3") do |env| # puts "Full environment: #{env.expanded_name}" # end # def environments(*names, &blk) # Normalize the names before using them on for the environment. names.flatten.join(",").split(",").uniq.map do |n| environment(n, &blk) end end # Returns the environment with the given name. # If passed a block, will yield with that as the single argument. # # RVM.environment("ree@rails3") do |env| # puts "Gemset is #{env.gemset.name}" # end # def environment(name) # TODO: Maintain an Environment cache. # The cache needs to track changes via use etc though. env = Environment.new(name) yield env if block_given? env end # Merges items into the default config, essentially # setting environment variables passed to child processes: # # RVM.merge_config!({ # :some_shell_variable => "me", # }) # def merge_config!(config = {}) Environment.merge_config!(config) end # Returns the current 'best guess' value for rvm_path. def path Environment.rvm_path end # Shortcut to set rvm_path. Will set it on all new instances # but wont affect currently running environments. def path=(value) Environment.rvm_path = value end private def cache_method_call(name) class_eval <<-END, __FILE__, __LINE__ def #{name}(*args, &blk) current.__send__(:#{name}, *args, &blk) end END end # Proxies methods to the current environment, creating a # method before dispatching to speed up future calls. def method_missing(name, *args, &blk) if current.respond_to?(name) cache_method_call name current.__send__ name, *args, &blk else super end end end end
36.447205
115
0.694274
21d7f260e3da0d26289930ca5d4f7e49492287f9
1,419
class Cvsutils < Formula desc "CVS utilities for use in working directories" homepage "https://www.red-bean.com/cvsutils/" url "https://www.red-bean.com/cvsutils/releases/cvsutils-0.2.6.tar.gz" sha256 "174bb632c4ed812a57225a73ecab5293fcbab0368c454d113bf3c039722695bb" license "GPL-2.0" bottle do sha256 cellar: :any_skip_relocation, catalina: "f8637db7bc660a9953b96bca2e68d1ba7c56bd0766e0ef12bc6b0b42d972ae3a" sha256 cellar: :any_skip_relocation, mojave: "e497ac1ba036fec1ccd8d34b2ec6262f9721ab805d0636f073c5406ef4fbd922" sha256 cellar: :any_skip_relocation, high_sierra: "102456ac28b63271b03a5722e8421d6273005c54203f4f818678be065479463b" sha256 cellar: :any_skip_relocation, sierra: "d1f2e13e0df6dbb767a04f7e206114c119f9e6435f227e07e14b4d200e6aba8f" sha256 cellar: :any_skip_relocation, el_capitan: "f8e35c8b0ed2db868e7dd12f653c20d7d2709059fb5a773fd49084a2655f4ca0" sha256 cellar: :any_skip_relocation, yosemite: "ccefce4b4a1053e9a32e4f43318c7bf73c7154f0bee1be1cf1777e8fd3e8eabf" sha256 cellar: :any_skip_relocation, mavericks: "ab6140058099bdc798e0e294640504035d5c976a8752742044a161c416e2e31e" end def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}" system "make", "install" end test do system "#{bin}/cvsu", "--help" end end
48.931034
120
0.766737
79cf54b55d5d0d251ae6f0e0cc3dfeacdaa1de32
943
class RelatedTagQuery attr_reader :query def initialize(query) @query = query.strip end def tags if query =~ /\*/ pattern_matching_tags elsif query.present? related_tags else [] end end def wiki_page_tags results = wiki_page.try(:tags) || [] results.reject! do |name| name =~ /^(?:list_of_|tag_group|pool_group|howto:|about:|help:|template:)/ end results end def tags_for_html tags end def to_json {:query => query, :tags => tags, :wiki_page_tags => wiki_page_tags}.to_json end protected def pattern_matching_tags Tag.name_matches(query).where("post_count > 0").order("post_count desc").limit(50).sort_by {|x| x.name}.map(&:name) end def related_tags tag = Tag.named(query.strip).first if tag tag.related_tag_array.map(&:first) else [] end end def wiki_page WikiPage.titled(query).first end end
17.462963
119
0.640509
035335a1d335ac50c631b99d5e8550b3ac105f63
445
# frozen-string-literal: true require 'bundler/setup' require 'holidays_api_client' require 'webmock/rspec' require 'i18n' RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = '.rspec_status' # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
23.421053
66
0.759551
bb65e8f6482a4f555c3b955656aba0e69ed23815
735
# frozen_string_literal: true Datadog.configure do |c| enabled = ENV['DATADOG_ENABLED'] == 'true' hostname = ENV.fetch('DATADOG_TRACE_AGENT_HOSTNAME', 'localhost') debug = ENV['DATADOG_DEBUG'] == 'true' c.tracer enabled: enabled, hostname: hostname, distributed_tracing: true, debug: debug c.use :rails, service_name: 'exchange', distributed_tracing: true, controller_service: 'exchange.controller', cache_service: 'exchange.cache', database_service: 'exchange.postgres' c.use :graphql, service_name: 'exchange.graphql', schemas: [ExchangeSchema] c.use :redis, service_name: 'exchange.redis' c.use :sidekiq, service_name: 'exchange.sidekiq' c.use :http, service_name: 'exchange.http', distributed_tracing: true end
49
182
0.756463
f8ed2d15b5265315cb85420be8274c6381510da2
475
# coding: utf-8 # overwrite db:migarate task 'db:migrate' => :environment do ENV['RAILS_ENV'] ||= 'development' sh "bundle exec ridgepole -c config/database.yml -f db/Schemafile -E#{ENV['RAILS_ENV']} --apply" sh 'bin/rake db:schema:dump' # test用に schema.rb ファイルを作成しておく end task 'db:migrate:dryrun' => :environment do ENV['RAILS_ENV'] ||= 'development' sh "bundle exec ridgepole -c config/database.yml -f db/Schemafile -E#{ENV['RAILS_ENV']} --apply --dry-run" end
33.928571
108
0.696842
bbdd991a6b88f1e80d8a6dc7dbd9602c95e192e5
1,217
require 'spec_helper' describe 'Xdelivery::API::Response::Base' do describe "當沒有登入的情況 ..." do before do @data = "{\"status\":false}" stub_request(:any, Xdelivery::API::Base::BASE_URL).to_return(body: @data, status: 401) @http_response = begin RestClient.get(Xdelivery::API::Base::BASE_URL) rescue RestClient::ExceptionWithResponse => e e.response end @response = Xdelivery::API::Response::Orders.new(@http_response) end it "#auth? == false" do assert_equal false, @response.auth? end it "#status? == false" do assert_equal false, @response.status? end end describe "當正常登入的情況 ..." do before do @data = "{\"status\":true}" stub_request(:any, Xdelivery::API::Base::BASE_URL).to_return(body: @data, status: 200) @http_response = begin RestClient.get(Xdelivery::API::Base::BASE_URL) rescue RestClient::ExceptionWithResponse => e e.response end @response = Xdelivery::API::Response::Orders.new(@http_response) end it "#auth? == true" do assert @response.auth? end it "#status? == false" do assert @response.status? end end end
25.354167
92
0.618735
5dae980f04f6624a165db3cac57d66d288a8f9be
99
class RemoveTermsTable < ActiveRecord::Migration[6.0] def change drop_table :terms end end
16.5
53
0.747475
7a54353a61f3a8963f8d08647c4b80b63971dd08
260
# Add your variables here first_number = 5 second_number = 6 sum = first_number + second_number difference = first_number - second_number sum = first_number + second_number product = first_number * second_number quotient = first_number / second_number
16.25
41
0.780769
f77bded1c86db4688da4cd65b386bffe3161d3a9
6,018
# Copyright © 2011-2019 MUSC Foundation for Research Development # All rights reserved. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with the distribution. # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, # BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT # SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR # TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. module AssociatedUsersHelper def new_authorized_user_button(opts={}) unless in_dashboard? && !opts[:permission] url = in_dashboard? ? new_dashboard_associated_user_path(protocol_id: opts[:protocol_id]) : new_associated_user_path(srid: opts[:srid]) link_to url, remote: true, class: 'btn btn-success' do icon('fas', 'plus mr-2') + t('authorized_users.new') end end end def authorized_user_actions(pr, opts={}) content_tag :div, class: 'd-flex justify-content-center' do raw([ edit_authorized_user_button(pr, opts), delete_authorized_user_button(pr, opts) ].join('')) end end def edit_authorized_user_button(pr, opts={}) unless in_dashboard? && !opts[:permission] url = in_dashboard? ? edit_dashboard_associated_user_path(pr) : edit_associated_user_path(pr, srid: opts[:srid]) link_to icon('far', 'edit'), url, remote: true, class: 'btn btn-warning mr-1 edit-authorized-user' end end def delete_authorized_user_button(pr, opts={}) unless in_dashboard? && !opts[:permission] data = { id: pr.id, toggle: 'tooltip', placement: 'right', boundary: 'window' } if current_user.id == pr.identity_id if (in_dashboard? && (current_user.catalog_overlord? || opts[:admin])) || (!in_dashboard? && current_user.catalog_overlord?) # Warn of removing current user but won't redirect if # - in dashboard and current user is an overlord/admin or # - not in dashboard and current user is an overlord data[:batch_select] = { checkConfirm: 'true', checkConfirmSwalText: t('authorized_users.delete.self_remove_warning') } else # User will be redirected because they will no longer have # permission on this protocol data[:batch_select] = { checkConfirm: 'true', checkConfirmSwalText: t('authorized_users.delete.self_remove_redirect_warning') } end end button_tag(icon('fas', 'trash-alt'), type: 'button', title: pr.primary_pi? ? t(:authorized_users)[:delete][:pi_tooltip] : t(:authorized_users)[:delete][:tooltip], class: ["btn btn-danger actions-button delete-authorized-user", pr.primary_pi? ? 'disabled' : ''], data: data ) end end # Generates state for portion of Authorized User form concerned with their # professional organizations. # professional_organization - Last professional organization selected in form. # Pass a falsy value for initial state. def professional_organization_state(professional_organization) if professional_organization { dont_submit_selected: professional_organization.parents, submit_selected: professional_organization, dont_submit_unselected: professional_organization.children } else { dont_submit_selected: [], submit_selected: nil, dont_submit_unselected: ProfessionalOrganization.where(parent_id: nil) } end end # Generate a dropdown for choosing a professional organization. # choices_from - If a ProfessionalOrganization, returns a select populated # with it (as selected option) and its siblings. Otherwise, choices_from # should be a collection of ProfessionalOrganizations to be presented as # options. def professional_organization_dropdown(form: nil, choices_from:) select_class = 'selectpicker' if choices_from.kind_of?(ProfessionalOrganization) options = options_from_collection_for_select(choices_from.self_and_siblings.order(:name), 'id', 'name', choices_from.id) select_id = "select-pro-org-#{choices_from.org_type}" else options = options_from_collection_for_select(choices_from.order(:name), 'id', 'name') select_id = "select-pro-org-#{choices_from.first.org_type}" end if form form.select(:professional_organization_id, options, { include_blank: true }, class: select_class, id: select_id) else select_tag(nil, options, include_blank: true, class: select_class, id: select_id) end end # Convert ProfessionalOrganization's org_type to a label for Authorized Users # form. def org_type_label(professional_organization) professional_organization.org_type.capitalize end end
44.25
145
0.706215
4a688da30f05fc455960284fa3ca0038bc6484e6
3,709
# 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: 20170505175400) do create_table "arts", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t| t.string "hash_code", limit: 64, null: false t.string "mimetype", limit: 128, null: false t.binary "bytes", limit: 16777215, null: false t.datetime "created_at" t.datetime "updated_at" t.index ["hash_code"], name: "index_arts_on_hash_code", unique: true, using: :btree end create_table "buffer_records", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t| t.string "on_behalf_of" t.boolean "bot_queued" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "track_id" t.index ["track_id"], name: "index_buffer_records_on_track_id", using: :btree end create_table "history_records", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t| t.string "on_behalf_of" t.boolean "bot_queued" t.datetime "played_time" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "track_id" t.index ["track_id"], name: "index_history_records_on_track_id", using: :btree end create_table "hmac_keys", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t| t.string "public_key", limit: 36, null: false t.string "private_key", limit: 36, null: false t.string "description" t.index ["private_key"], name: "index_hmac_keys_on_private_key", unique: true, using: :btree t.index ["public_key"], name: "index_hmac_keys_on_public_key", unique: true, using: :btree end create_table "persistent_settings", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t| t.string "key", null: false t.string "value", null: false t.index ["key"], name: "index_persistent_settings_on_key", unique: true, using: :btree end create_table "skips", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t| t.string "on_behalf_of" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "history_record_id" t.index ["history_record_id"], name: "index_skips_on_history_record_id", using: :btree end create_table "tracks", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=latin1" do |t| t.string "absolute_path", null: false t.string "artist" t.string "album" t.string "title" t.string "uploader" t.integer "length" t.datetime "created_at" t.datetime "updated_at" t.integer "art_id" t.index ["absolute_path"], name: "index_tracks_on_absolute_path", unique: true, using: :btree t.index ["art_id"], name: "index_tracks_on_art_id", using: :btree end add_foreign_key "buffer_records", "tracks" add_foreign_key "history_records", "tracks" add_foreign_key "skips", "history_records" add_foreign_key "tracks", "arts" end
44.154762
109
0.709625
6a09427ccd5758cb90960218d6d6de82afb4cd6e
5,885
# # Author:: Adam Jacob (<[email protected]) # Copyright:: Copyright 2009-2016, Chef Software Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require "chef/knife" require "chef/application" require "mixlib/log" require "ohai/config" require "chef/monkey_patches/net_http.rb" class Chef::Application::Knife < Chef::Application NO_COMMAND_GIVEN = "You need to pass a sub-command (e.g., knife SUB-COMMAND)\n" banner "Usage: knife sub-command (options)" option :config_file, :short => "-c CONFIG", :long => "--config CONFIG", :description => "The configuration file to use", :proc => lambda { |path| File.expand_path(path, Dir.pwd) } option :config_option, :long => "--config-option OPTION=VALUE", :description => "Override a single configuration option", :proc => lambda { |option, existing| (existing ||= []) << option existing } verbosity_level = 0 option :verbosity, :short => "-V", :long => "--verbose", :description => "More verbose output. Use twice for max verbosity", :proc => Proc.new { verbosity_level += 1 }, :default => 0 option :color, :long => "--[no-]color", :boolean => true, :default => true, :description => "Use colored output, defaults to enabled" option :environment, :short => "-E ENVIRONMENT", :long => "--environment ENVIRONMENT", :description => "Set the Chef environment (except for in searches, where this will be flagrantly ignored)" option :editor, :short => "-e EDITOR", :long => "--editor EDITOR", :description => "Set the editor to use for interactive commands", :default => ENV["EDITOR"] option :disable_editing, :short => "-d", :long => "--disable-editing", :description => "Do not open EDITOR, just accept the data as is", :boolean => true, :default => false option :help, :short => "-h", :long => "--help", :description => "Show this message", :on => :tail, :boolean => true option :node_name, :short => "-u USER", :long => "--user USER", :description => "API Client Username" option :client_key, :short => "-k KEY", :long => "--key KEY", :description => "API Client Key", :proc => lambda { |path| File.expand_path(path, Dir.pwd) } option :chef_server_url, :short => "-s URL", :long => "--server-url URL", :description => "Chef Server URL" option :yes, :short => "-y", :long => "--yes", :description => "Say yes to all prompts for confirmation" option :defaults, :long => "--defaults", :description => "Accept default values for all questions" option :print_after, :long => "--print-after", :description => "Show the data after a destructive operation" option :format, :short => "-F FORMAT", :long => "--format FORMAT", :description => "Which format to use for output", :default => "summary" option :local_mode, :short => "-z", :long => "--local-mode", :description => "Point knife commands at local repository instead of server", :boolean => true option :chef_zero_host, :long => "--chef-zero-host HOST", :description => "Host to start chef-zero on" option :chef_zero_port, :long => "--chef-zero-port PORT", :description => "Port (or port range) to start chef-zero on. Port ranges like 1000,1010 or 8889-9999 will try all given ports until one works." option :listen, :long => "--[no-]listen", :description => "Whether a local mode (-z) server binds to a port", :boolean => false option :version, :short => "-v", :long => "--version", :description => "Show chef version", :boolean => true, :proc => lambda { |v| puts "Chef: #{::Chef::VERSION}" }, :exit => 0 option :fips, :long => "--[no-]fips", :description => "Enable fips mode", :boolean => true, :default => nil # Run knife def run Mixlib::Log::Formatter.show_time = false validate_and_parse_options quiet_traps Chef::Knife.run(ARGV, options) exit 0 end private def quiet_traps trap("TERM") do exit 1 end trap("INT") do exit 2 end end def validate_and_parse_options # Checking ARGV validity *before* parse_options because parse_options # mangles ARGV in some situations if no_command_given? print_help_and_exit(1, NO_COMMAND_GIVEN) elsif no_subcommand_given? if want_help? || want_version? print_help_and_exit(0) else print_help_and_exit(2, NO_COMMAND_GIVEN) end end end def no_subcommand_given? ARGV[0] =~ /^-/ end def no_command_given? ARGV.empty? end def want_help? ARGV[0] =~ /^(--help|-h)$/ end def want_version? ARGV[0] =~ /^(--version|-v)$/ end def print_help_and_exit(exitcode = 1, fatal_message = nil) Chef::Log.error(fatal_message) if fatal_message begin parse_options rescue OptionParser::InvalidOption => e puts "#{e}\n" end puts opt_parser puts Chef::Knife.list_commands exit exitcode end end
27.119816
149
0.603738
1ca0df14ef099d48bd7252205c1309af30652f2b
1,959
# Main AWS loader file. The intent is for this to be # loaded only if AWS resources are needed. require 'aws-sdk' # TODO: split once ADK v3 is in use require 'resource_support/aws/aws_backend_factory_mixin' require 'resource_support/aws/aws_resource_mixin' require 'resource_support/aws/aws_singular_resource_mixin' require 'resource_support/aws/aws_plural_resource_mixin' require 'resource_support/aws/aws_backend_base' # Load all AWS resources # TODO: loop over and load entire directory # for f in ls lib/resources/aws/*; do t=$(echo $f | cut -c 5- | cut -f1 -d. ); echo "require '${t}'"; done require 'resources/aws/aws_cloudtrail_trail' require 'resources/aws/aws_cloudtrail_trails' require 'resources/aws/aws_cloudwatch_alarm' require 'resources/aws/aws_cloudwatch_log_metric_filter' require 'resources/aws/aws_config_delivery_channel' require 'resources/aws/aws_config_recorder' require 'resources/aws/aws_ec2_instance' require 'resources/aws/aws_iam_access_key' require 'resources/aws/aws_iam_access_keys' require 'resources/aws/aws_iam_group' require 'resources/aws/aws_iam_groups' require 'resources/aws/aws_iam_password_policy' require 'resources/aws/aws_iam_policies' require 'resources/aws/aws_iam_policy' require 'resources/aws/aws_iam_role' require 'resources/aws/aws_iam_root_user' require 'resources/aws/aws_iam_user' require 'resources/aws/aws_iam_users' require 'resources/aws/aws_kms_key' require 'resources/aws/aws_kms_keys' require 'resources/aws/aws_rds_instance' require 'resources/aws/aws_route_table' require 'resources/aws/aws_s3_bucket' require 'resources/aws/aws_s3_bucket_object' require 'resources/aws/aws_security_group' require 'resources/aws/aws_security_groups' require 'resources/aws/aws_sns_subscription' require 'resources/aws/aws_sns_topic' require 'resources/aws/aws_sns_topics' require 'resources/aws/aws_subnet' require 'resources/aws/aws_subnets' require 'resources/aws/aws_vpc' require 'resources/aws/aws_vpcs'
40.8125
106
0.827973
3378837ce7a307f25676bcdb13e0742a6dccd16e
329
# lib/generators/plutus/plutus_generator.rb require 'rails/generators' require 'rails/generators/migration' require_relative 'base_generator' module Plutus class ScopeGenerator < BaseGenerator def create_migration_file migration_template 'scope_migration.rb', 'db/migrate/scope_plutus_accounts.rb' end end end
25.307692
84
0.802432
21e9db9b87d3e99ddd215bdc95c0c9ac653071a0
462
cask 'clipy' do version '1.0.7' sha256 'f1d060033e6fb18bc8fbab33f35ff3d7245edf905a2018fe0fbbb25d80c65c67' url "https://github.com/Clipy/Clipy/releases/download/#{version}/Clipy_#{version}.dmg" appcast 'https://clipy-app.com/appcast.xml', checkpoint: 'baf6a41c333410ae8d4b43bffa5b5cd3c0b17c884cf5084d43217368da81db01' name 'Clipy' homepage 'https://clipy-app.com/' license :mit depends_on macos: '>= :mavericks' app 'Clipy.app' end
28.875
88
0.746753
bb8980f0b8075610e631d1fff5d09942839e6653
1,535
require 'zip' class ZipFileExtractor OUTPUT_PATH = File.join('public', 'spree_themes') IGNORED_FILES_REGEX = /\/(\.|__)/ attr_reader :file_path, :theme def initialize(file_path, theme) @file_path = file_path @theme = theme end def extract FileUtils.mkdir_p(OUTPUT_PATH) parse_file end private def parse_file Zip::File.open(file_path) do |zip_file| zip_file.each do |file| ## [::NASTY HACK::] ## For some zipfiles(including downloaded zip from github), ## whole folder is extracted instead of files withing folder ## so files extracted to output path is invalid. temp_path = "#{ theme.name }/" next if file.name == temp_path filename = (file.name.include? temp_path) ? file.name.sub(temp_path, '') : file.name filepath = File.join(output_path, filename) next if filepath =~ IGNORED_FILES_REGEX unless File.exist?(filepath) FileUtils::mkdir_p(File.dirname(filepath)) zip_file.extract(file, filepath) end generate_template(filepath) if File.file?(filepath) end end end def output_path @output_path ||= File.join(OUTPUT_PATH, file_name) end def file_name @file_name ||= File.basename(file_path, file_extension) end def file_extension File.extname(file_path) end def generate_template(filepath) TemplateGeneratorService.new(filepath, theme).generate end end
24.758065
94
0.637134
ace35dda53ea3c5a36f36d6bab90c3a3ee0bc2c6
4,005
require "abstract_unit" module ActionDispatch module Routing class RouteSetTest < ActiveSupport::TestCase class SimpleApp def initialize(response) @response = response end def call(env) [ 200, { "Content-Type" => "text/plain" }, [response] ] end end setup do @set = RouteSet.new end test "not being empty when route is added" do assert empty? draw do get "foo", to: SimpleApp.new("foo#index") end assert_not empty? end test "url helpers are added when route is added" do draw do get "foo", to: SimpleApp.new("foo#index") end assert_equal "/foo", url_helpers.foo_path assert_raises NoMethodError do assert_equal "/bar", url_helpers.bar_path end draw do get "foo", to: SimpleApp.new("foo#index") get "bar", to: SimpleApp.new("bar#index") end assert_equal "/foo", url_helpers.foo_path assert_equal "/bar", url_helpers.bar_path end test "url helpers are updated when route is updated" do draw do get "bar", to: SimpleApp.new("bar#index"), as: :bar end assert_equal "/bar", url_helpers.bar_path draw do get "baz", to: SimpleApp.new("baz#index"), as: :bar end assert_equal "/baz", url_helpers.bar_path end test "url helpers are removed when route is removed" do draw do get "foo", to: SimpleApp.new("foo#index") get "bar", to: SimpleApp.new("bar#index") end assert_equal "/foo", url_helpers.foo_path assert_equal "/bar", url_helpers.bar_path draw do get "foo", to: SimpleApp.new("foo#index") end assert_equal "/foo", url_helpers.foo_path assert_raises NoMethodError do assert_equal "/bar", url_helpers.bar_path end end test "only_path: true with *_url and no :host option" do draw do get "foo", to: SimpleApp.new("foo#index") end assert_equal "/foo", url_helpers.foo_url(only_path: true) end test "only_path: false with *_url and no :host option" do draw do get "foo", to: SimpleApp.new("foo#index") end assert_raises ArgumentError do assert_equal "http://example.com/foo", url_helpers.foo_url(only_path: false) end end test "only_path: false with *_url and local :host option" do draw do get "foo", to: SimpleApp.new("foo#index") end assert_equal "http://example.com/foo", url_helpers.foo_url(only_path: false, host: "example.com") end test "only_path: false with *_url and global :host option" do @set.default_url_options = { host: "example.com" } draw do get "foo", to: SimpleApp.new("foo#index") end assert_equal "http://example.com/foo", url_helpers.foo_url(only_path: false) end test "explicit keys win over implicit keys" do draw do resources :foo do resources :bar, to: SimpleApp.new("foo#show") end end assert_equal "/foo/1/bar/2", url_helpers.foo_bar_path(1, 2) assert_equal "/foo/1/bar/2", url_helpers.foo_bar_path(2, foo_id: 1) end test "having an optional scope with resources" do draw do scope "(/:foo)" do resources :users end end assert_equal "/users/1", url_helpers.user_path(1) assert_equal "/users/1", url_helpers.user_path(1, foo: nil) assert_equal "/a/users/1", url_helpers.user_path(1, foo: "a") end private def draw(&block) @set.draw(&block) end def url_helpers @set.url_helpers end def empty? @set.empty? end end end end
25.673077
105
0.571036
bfc3b12b13966a3804a5e4b0a0b6b8800c574026
1,167
class Fortio < Formula desc "HTTP and gRPC load testing and visualization tool and server" homepage "https://fortio.org/" url "https://github.com/fortio/fortio.git", tag: "v1.6.8", revision: "55f745ffeee860b7dc4006474260627632fae388" license "Apache-2.0" bottle do sha256 "f7d300df19352a45900b7e0cf9199ef9507a37f4f97e99e764627537aab3b751" => :catalina sha256 "24452c59e23335fd4767f26df3bd0529d761cdf80a694efa520cff6c43ecfd0d" => :mojave sha256 "3fa5b77b0b7fc149780d6e8372f7f3c0cb268e6f78577f0aa729dfcff9218835" => :high_sierra end depends_on "go" => :build def install system "make", "official-build", "OFFICIAL_BIN=#{bin}/fortio", "LIB_DIR=#{lib}" lib.install "ui/static", "ui/templates" end test do assert_match version.to_s, shell_output("#{bin}/fortio version -s") port = free_port begin pid = fork do exec bin/"fortio", "server", "-http-port", port.to_s end sleep 2 output = shell_output("#{bin}/fortio load http://localhost:#{port}/ 2>&1") assert_match /^All\sdone/, output.lines.last ensure Process.kill("SIGTERM", pid) end end end
30.710526
93
0.69066
62b18a027a3b400b9bafdeb4ed2ca6dcee47c04f
173
begin require 'dke/ruby_provider' rescue LoadError warn('Your dke RubyGem is missing or out of date.', 'Install the latest version using `gem install dke`.') end
24.714286
61
0.722543
ac581b56fd59aa98819081894821d82a7b1dbc9c
2,480
module Fech # Fech:SearchResult is a class representing a search result # from Fech::Search. class SearchResult attr_reader :committee_name, :committee_id, :filing_id, :form_type, :period, :date_filed, :description, :amended_by, :amendment # @param [Hash] attrs The attributes of the search result. def initialize(attrs) @date_format = '%m/%d/%Y' @committee_name = attrs[:committee_name] @committee_id = attrs[:committee_id] @filing_id = attrs[:filing_id].sub(/FEC-/, '').to_i @form_type = attrs[:form_type] @period = parse_period(attrs[:from], attrs[:to]) @date_filed = Date.strptime(attrs[:date_filed], @date_format) @description = parse_description(attrs) @amended_by = attrs[:amended_by] @amendment = parse_form_type(attrs[:form_type]) end # Parse the strings representing a filing period. # @param [String] period a string representing a filing period # @return [Hash, nil] a hash representing the start and end # of a filing period. def parse_period(from, to) return unless valid_date(from.to_s) && valid_date(to.to_s) from = Date.strptime(from, @date_format) to = Date.strptime(to, @date_format) {from: from, to: to} end def parse_description(attrs) if attrs[:form_type] == 'F1A' or attrs[:form_type] == 'F1N' description = 'STATEMENT OF ORGANIZATION' elsif attrs[:form_type] == 'F2A' or attrs[:form_type] == 'F2N' description = "STATEMENT OF CANDIDACY" elsif attrs[:form_type] == 'F5A' or attrs[:form_type] == 'F5N' description = "REPORT OF INDEPENDENT EXPENDITURES MADE" elsif attrs[:form_type] == 'F1M' description = "NOTIFICATION OF MULTICANDIDATE STATUS" elsif attrs[:form_type] == 'F13' description = "INAUGURAL COMMITTEE DONATIONS" else description = attrs[:description].strip end description end # Checks form_type to see if a filing is an amendment # and returns a boolean. def parse_form_type(form_type) if form_type.end_with?('A') true else false end end # Check whether a date string is valid def valid_date(s) s.match(/\d\d?\/\d\d?\/\d{4}/) end # The Fech filing object for this search result # @return [Fech::Filing] def filing(opts={}) Fech::Filing.new(self.filing_id, opts) end end end
33.513514
131
0.6375
391478eae5f458895ab6c92745249f762efa9593
1,047
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'prpr/code_pipeline/version' Gem::Specification.new do |spec| spec.name = "prpr-code_pipeline" spec.version = Prpr::CodePipeline::VERSION spec.authors = ["kokuyouwind"] spec.email = ["[email protected]"] spec.summary = "Prpr plugin to deplay module via AWS CodePipeline" spec.description = "When someone merge PR to deployment/XXX, deploy it" spec.homepage = "https://github.com/kokuyouwind/prpr-code_pipeline" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_dependency "prpr" spec.add_dependency "aws-sdk", "~> 2" spec.add_development_dependency "bundler", "~> 1.10" spec.add_development_dependency "rake", "~> 10.0" end
38.777778
104
0.657116
211103786492b9f9d239f6f83e00d4680a37dd82
1,529
module Spaceship class UpdateChecker UPDATE_URL = "https://fastlane-refresher.herokuapp.com/spaceship" def self.ensure_spaceship_version return if defined?(SpecHelper) # is this running via tests return if ENV["FASTLANE_SKIP_UPDATE_CHECK"] require 'faraday' require 'json' response = Faraday.get(UPDATE_URL) return if response.nil? || response.body.to_s.length == 0 version = JSON.parse(response.body)["version"] puts "Comparing spaceship version (remote #{version} - local #{Spaceship::VERSION})" if $verbose return if Gem::Version.new(version) <= Gem::Version.new(Spaceship::VERSION) show_update_message(Spaceship::VERSION, version) rescue => ex puts ex.to_s if $verbose puts "Couldn't verify that spaceship is up to date" end def self.show_update_message(local_version, live_version) puts "---------------------------------------------".red puts "-------------------WARNING-------------------".red puts "---------------------------------------------".red puts "You're using an old version of spaceship" puts "To ensure spaceship and fastlane works" puts "update to the latest version." puts "" puts "Run `[sudo] gem update spaceship`" puts "" puts "or `bundle update` if you use bundler." puts "" puts "You're on spaceship version: #{local_version}".yellow puts "Latest spaceship version : #{live_version}".yellow puts "" end end end
35.55814
102
0.607587
4a276a52764cd6257f42f62b15df5eed8f1e4723
69
require 'rails_helper' RSpec.describe Category, type: :model do end
13.8
40
0.782609
ab4899a06db6883dedc1afb92492e8879f69a19a
460
require "spec_helper" require "circleci/env/command/vault/read" describe Circleci::Env::Command::Vault::Read do let(:cmd) { Circleci::Env::Command::Vault::Read.new(name: "name", password: "pass") } describe "#run" do it "should call read" do allow(cmd).to receive(:read).with("name", "pass").and_return("secret value") expect{ cmd.run }.to output("Read secret variable from secret/name.vault\nsecret value\n").to_stdout end end end
32.857143
106
0.691304
26a32036766861bd6c45a39fae2f18e846ff03a1
2,185
# # loader.rb - # $Release Version: 0.9.6$ # $Revision$ # by Keiju ISHITSUKA([email protected]) # # -- # # # module IRB class LoadAbort < Exception;end module IrbLoader @RCS_ID='-$Id$-' alias ruby_load load alias ruby_require require def irb_load(fn, priv = nil) path = search_file_from_ruby_path(fn) raise LoadError, "No such file to load -- #{fn}" unless path load_file(path, priv) end def search_file_from_ruby_path(fn) if /^#{Regexp.quote(File::Separator)}/ =~ fn return fn if File.exist?(fn) return nil end for path in $: if File.exist?(f = File.join(path, fn)) return f end end return nil end def source_file(path) irb.suspend_name(path, File.basename(path)) do irb.suspend_input_method(FileInputMethod.new(path)) do |back_io| irb.signal_status(:IN_LOAD) do if back_io.kind_of?(FileInputMethod) irb.eval_input else begin irb.eval_input rescue LoadAbort print "load abort!!\n" end end end end end end def load_file(path, priv = nil) irb.suspend_name(path, File.basename(path)) do if priv ws = WorkSpace.new(Module.new) else ws = WorkSpace.new end irb.suspend_workspace(ws) do irb.suspend_input_method(FileInputMethod.new(path)) do |back_io| irb.signal_status(:IN_LOAD) do # p irb.conf if back_io.kind_of?(FileInputMethod) irb.eval_input else begin irb.eval_input rescue LoadAbort print "load abort!!\n" end end end end end end end def old back_io = @io back_path = @irb_path back_name = @irb_name back_scanner = @irb.scanner begin @io = FileInputMethod.new(path) @irb_name = File.basename(path) @irb_path = path @irb.signal_status(:IN_LOAD) do if back_io.kind_of?(FileInputMethod) @irb.eval_input else begin @irb.eval_input rescue LoadAbort print "load abort!!\n" end end end ensure @io = back_io @irb_name = back_name @irb_path = back_path @irb.scanner = back_scanner end end end end
18.208333
66
0.625172
bbf35e3c2450bc77797668c8b50360cebfc506c7
244
# frozen_string_literal: true class CreateTicketScannings < ActiveRecord::Migration[4.2] def change create_table :ticket_scannings do |t| t.integer :physical_ticket_id, null: false t.timestamps null: false end end end
20.333333
58
0.729508
6ac30b4eaf00f4cea838b5888fa88c1c2298fae6
75
# frozen_string_literal: true module FoundersToolkit::Auth::Emailable end
15
39
0.826667
62fd07ba25c59c301921d472aab6c24d2b73a16a
2,884
# coding: utf-8 require_relative "levenshtein/experiment" require_relative "levenshtein/iterative_with_two_matrix_rows" require_relative "levenshtein/iterative_with_two_matrix_rows_optimized" require_relative "levenshtein/iterative_with_full_matrix" require_relative "levenshtein/recursive" require_relative "levenshtein/trie_node" require_relative "levenshtein/trie_radix_tree" require_relative "levenshtein/trie_radix_tree_ext" require_relative "levenshtein/iterative_with_two_matrix_rows_ext" if RUBY_ENGINE == "ruby" module StringMetric # Levenshtein Distance implementation # # @see https://en.wikipedia.org/wiki/Levenshtein_distance module Levenshtein STRATEGIES = { experiment: Experiment, full_matrix: IterativeWithFullMatrix, recursive: Recursive, two_matrix_rows: IterativeWithTwoMatrixRows, two_matrix_rows_v2: IterativeWithTwoMatrixRowsOptimized } if RUBY_ENGINE == "ruby" STRATEGIES[:two_matrix_rows_ext] = IterativeWithTwoMatrixRowsExt end # Levenshtein Distance of two strings # # @param from [String] the first string # @param to [String] the second string # @param options [Hash] options # @option options [Fixnum, Float] :max_distance If this option is passed then # levenstein distance is trimmed to this value (if greater) # @option options [Fixnum, Float] :insertion_cost If this option is passed then # new insertion cost is taken into account (by default is 1) # @option options [Fixnum, Float] :deletion_cost If this option is passed then # new deletion cost is taken into account (by default is 1) # @option options [Fixnum, Float] :substitution_cost If this option is passed then # new substitution cost is taken into account (be default is 1) # @option options [Symbol] :strategy The desired strategy for Levenshtein # distance. Supported strategies are :recursive, :two_matrix_rows, # :full_matrix, :two_matrix_rows_v2 and :experiment. The default strategy # is :two_matrix_rows_v2 for MRI and :two_matrix_rows for other platforms. # One should not depend on :experiment strategy. # @return [Fixnum, Float] the Levenshtein Distance def distance(from, to, options = {}) strategy = pick_strategy(options[:strategy]) || Levenshtein.default_strategy args = [from, to, options] strategy.distance(*args) end module_function :distance # Currently the default strategy is set to IterativeWithTwoMatrixRows def default_strategy if RUBY_ENGINE == "ruby" pick_strategy(:two_matrix_rows_ext) else pick_strategy(:two_matrix_rows) end end module_function :default_strategy def pick_strategy(symbol) STRATEGIES[symbol] end module_function :pick_strategy private_class_method :pick_strategy end end
38.453333
90
0.742718
e833257dc84a0929380f9e7b1b6a5ca802c0d655
8,138
require 'spec_helper' describe Conjur::CLI::Complete, wip: true do def expects_completions_for string, point=nil expect(described_class.new("conjur #{string}",point) .completions .map { |c| c.chomp ' ' }) end describe 'conjur bash completion' do describe 'for conjur subcommands beginning' do before(:each) { expect(Conjur::Command).not_to receive :api } context 'with "conjur gr"' do it { expects_completions_for('gr').to include 'group' } end context 'with "conjur group"' do it { expects_completions_for('group').to contain_exactly 'group' } end context 'with "conjur p"' do it { expects_completions_for('p').to include 'plugin', 'pubkeys' } end context 'with "conjur host l"' do it { expects_completions_for('host l').to include 'layers', 'list' } end end describe 'for deprecated subcommands such as `conjur field`' do it { expects_completions_for('fi').not_to include 'field' } end describe 'for command flags beginning' do before(:each) { expect(Conjur::Command).not_to receive :api } context 'conjur -' do it { expects_completions_for('-').to include '--version' } end context 'conjur role memberships -' do it { expects_completions_for('role memberships -') .to include '-s', '--system'} end context 'conjur audit all -' do it { expects_completions_for('audit all -s -') .to include '-f', '--follow', '-l', '--limit=', '-o', '--offset=', '-s', '--short' } end end describe 'for arguments' do let (:api) { double('api') } before(:each) { expect(Conjur::Command).to receive(:api).at_least(:once).and_return api } describe 'expecting a resource' do let (:users) { ['Tweedledum', 'Tweedledee'] } let (:groups) { ['sharks', 'jets'] } let (:layers) { ['limbo', 'lust', 'gluttony', 'greed', 'anger', 'heresy', 'violence', 'fraud', 'treachery'] } let (:variables) { ['id/superman', 'id/batman', 'id/spiderman'] } let (:hosts) { ['skynet', 'hal9000', 'deep-thought'] } def mock_resources fake_results = yield.map { |result| double('resource', :attributes => { 'id' => result }) } expect(Conjur::Command.api).to receive(:resources) .once.and_return fake_results end context 'with kind "user"' do before(:each) { mock_resources { users.map { |user| "user:#{user}" }}} it { expects_completions_for('user show ') .to contain_exactly(*users) } end context 'with kind "group"' do before(:each) { mock_resources { groups.map { |group| "group:#{group}" }} } context 'for a command' do it { expects_completions_for('group show ') .to contain_exactly(*groups) } end end context 'with kind "layer"' do before(:each) { mock_resources { layers.map { |layer| "layer:#{layer}" }} } it { expects_completions_for('layer show ') .to contain_exactly(*layers) } end context 'with kind "variable"' do before(:each) { mock_resources { variables.map { |variable| "variable:#{variable}" }} } it { expects_completions_for('variable show ') .to contain_exactly(*variables) } end context 'with kind "host"' do before(:each) { mock_resources { hosts.map { |host| "host:#{host}" }} } it { expects_completions_for('host show ') .to contain_exactly(*hosts) } end context 'without kind specified' do let (:resources) { (users+groups+layers+variables+hosts) .map { |res| "arbitrarykind:#{res}" }} before(:each) { mock_resources { resources }} it 'should show all resources with their reported kinds' do expects_completions_for('resource show ') .to contain_exactly(*resources) end end end describe 'expecting a role' do let (:roles) { ['layer:population/tire', 'host:bubs-4k', 'user:strongbad', 'user:strongsad', 'user:strongmad']} before(:each) { role_doubles = roles.map { |role| double('role', :roleid => role) } expect(api).to receive(:current_role).once .and_return double('current_role', :all => role_doubles) } it { expects_completions_for('role memberships ') .to contain_exactly(*roles) } it 'completes colon separated values per-token' do expects_completions_for('layer list --role=host:b') .to contain_exactly 'bubs-4k' end it 'recognizes shell-escaped colons' do expects_completions_for('role members layer\:pop') .to contain_exactly 'layer:population/tire' end end end describe 'completes mid-line' do it 'tolerates garbage flags and arguments' do expect(described_class.new('conjur omg --lol wat pu').completions) .to include 'pubkeys ' end end end end describe Conjur::CLI::Complete::Resource do describe 'splits resource ids' do describe '#initialize(resource_string)' do describe 'accepts long or brief ids' do context 'gratuitous id (4+ tokens)' do it 'raises an ArgumentError' do expect { described_class.new '1:2:3:4' }.to raise_error ArgumentError end end context 'long id (3 tokens)' do it 'stores all 3 tokens' do dummy_string = 'acct:kind:name' dummy = described_class.new dummy_string expect(dummy.account).to eq 'acct' expect(dummy.kind).to eq 'kind' expect(dummy.name).to eq 'name' end end context 'brief id (2 tokens)' do it 'stores tokens in kind and name' do dummy = described_class.new 'kind:name' expect(dummy.account).to eq nil expect(dummy.kind).to eq 'kind' expect(dummy.name).to eq 'name' end end context 'tiny id (1 token)' do it 'stores token in name' do dummy = described_class.new 'name' expect(dummy.account).to eq nil expect(dummy.kind).to eq nil expect(dummy.name).to eq 'name' end end end it 'hides the account by default' do expect(described_class.new('a:b:c').include_account).to eq false expect(described_class.new('a:b:c', true).include_account).to eq true end end describe '#to_ary' do context 'account not important' do it 'hides account when converting to array' do dummy = described_class.new 'a:b:c' expect(dummy.to_ary).to eq ['b','c'] end end context 'account is important' do it 'includes account when converting to array' do dummy = described_class.new 'a:b:c', true expect(dummy.to_ary).to eq ['a','b','c'] end end end describe '#to_s' do context 'account not important' do it 'hides account when converting to string' do dummy = described_class.new 'test:user:admin' expect(dummy.to_s).to eq 'user:admin' end end context 'account is important' do it 'includes account when converting to string' do dummy = described_class.new 'test:user:admin', true expect(dummy.to_s).to eq 'test:user:admin' end end end end end
33.628099
82
0.549767
7a892e69d8474fb7e5ba3d908c43977e8fc29103
3,304
require 'spec_helper' describe PensioAPI::Transaction do before :each do stub_pensio_response('/merchant/API/payments', 'payments') stub_pensio_response('/merchant/API/getTerminals', 'get_terminals') stub_pensio_response('/merchant/API/refundCapturedReservation', 'refund_captured_reservation') end let(:transaction) { PensioAPI::Transaction.find.first } describe 'reader attributes' do describe '.captured_amount' do specify { expect(transaction.status).to be_an_instance_of(String) } end describe '.captured_amount' do specify { expect(transaction.captured_amount).to be_an_instance_of(BigDecimal) } end describe '.reserved_amount' do specify { expect(transaction.reserved_amount).to be_an_instance_of(BigDecimal) } end describe '.refunded_amount' do specify { expect(transaction.refunded_amount).to be_an_instance_of(BigDecimal) } end describe '.recurring_default_amount' do specify { expect(transaction.recurring_default_amount).to be_an_instance_of(BigDecimal) } end describe '.merchant_currency' do specify { expect(transaction.merchant_currency).to be_an_instance_of(Integer) } end describe '.card_holder_currency' do specify { expect(transaction.card_holder_currency).to be_an_instance_of(Integer) } end describe '.chargeback_events' do specify { expect(transaction.chargeback_events).to be_an_instance_of(Array) } end end describe '.find' do describe 'object mapping' do let(:response) { PensioAPI::Transaction.find } it 'returns an instance of PensioAPI::Responses::Transaction' do expect(response).to be_an_instance_of(PensioAPI::Responses::Transaction) end it 'maps transactions to transaction objects' do expect(response.all? { |r| r.class == PensioAPI::Transaction }).to be true end specify { expect(response.transactions.length).to eq(1) } end end describe '.to_reservation' do it 'returns a PensioAPI::Reservation object' do expect(transaction.to_reservation).to be_an_instance_of(PensioAPI::Reservation) end end describe '.to_subscription' do it 'returns a PensioAPI::Subscription object' do expect(transaction.to_subscription).to be_an_instance_of(PensioAPI::Subscription) end end describe '.terminal' do it 'returns a PensioAPI::Terminal object' do expect(transaction.terminal).to be_an_instance_of(PensioAPI::Terminal) end end describe '.refund' do let(:response) { transaction.refund } specify { expect(response).to be_an_instance_of(PensioAPI::Responses::Refund) } end describe '.captured?' do context 'when the full reserved amount has been captured' do it 'returns true' do expect(transaction).to be_captured end end context 'when the full reserved amount has not been captured' do it 'returns false' do allow(transaction).to receive(:captured_amount).and_return(BigDecimal('0')) expect(transaction).to_not be_captured end end end describe '.billing_address' do it 'returns a PensioAPI::BillingAddress object' do expect(transaction.billing_address).to be_an_instance_of(PensioAPI::BillingAddress) end end end
31.169811
98
0.721852
bbdf2ee87b3134b840886618799bba0755b1a41b
1,755
require 'hanami/routes' require 'hanami/routing/default' module Hanami # @since 0.9.0 # @api private module Components # @since 0.9.0 # @api private module App # hanami-router configuration for a single Hanami application in the project. # # @since 0.9.0 # @api private class Routes # Configure hanami-router for a single Hanami application in the project. # # @param app [Hanami::Configuration::App] a Hanami application # # @since 0.9.0 # @api private def self.resolve(app) namespace = app.namespace routes = application_routes(app) if namespace.routes.nil? # rubocop:disable Style/IfUnlessModifier namespace.routes = Hanami::Routes.new(routes) end Components.resolved("#{app.app_name}.routes", routes) end # @since 0.9.0 # @api private def self.application_routes(app) # rubocop:disable Metrics/MethodLength config = app.configuration namespace = app.namespace resolver = Hanami::Routing::EndpointResolver.new(pattern: config.controller_pattern, namespace: namespace) default_app = Hanami::Routing::Default.new options = { resolver: resolver, default_app: default_app, scheme: config.scheme, host: config.host, port: config.port, prefix: config.path_prefix, force_ssl: config.force_ssl } options[:parsers] = config.body_parsers if config.body_parsers.any? Hanami::Router.new(options, &config.routes) end end end end end
29.25
119
0.585755
91ad6097c36fc94ac18cd12aa46dcae1a42b5f85
144
class AbsoluteDateTimeRoot include Neo4j::ActiveNode property :name, type: String, constraint: :unique id_property :uuid, auto: :uuid end
24
51
0.770833
f7a4d5381040c4feecc762cc577e1714fba99ee6
1,620
class ServicesController < ApplicationController def search @categories = Service.categories end def index results = Geocoder.search(params[:postcode], region: "gb") if results.length > 0 @top_result = Service .where("recommended = TRUE AND category && ARRAY[?]::varchar[]", params[:categories]) .limit(1) @result = results.first.formatted_address @coordinates = Geocoder.coordinates(params[:postcode]) if @top_result.length > 0 if params[:categories] @services = Service .where("category && ARRAY[?]::varchar[] AND id != ?", params[:categories], @top_result[0].id) .near(results.first.coordinates, 200) else @services = Service .where("id != ?", @top_result[0].id) .near(results.first.coordinates, 200) end else if params[:categories] @services = Service .where("category && ARRAY[?]::varchar[]", params[:categories]) .near(results.first.coordinates, 200) else @services = Service .near(results.first.coordinates, 200) end end else redirect_to search_services_path, :notice => "Couldn't find any services near that location. Please make sure your location is a valid Mid Sussex area." end end end
37.674419
164
0.507407
6a964b83b8d77cca5654e15fc80730ab6b88ddba
278
require 'rails_helper' RSpec.describe "home/show.html.erb", type: :view do let(:vehicle) { create(:vehicle) } before do assign(:vehicle,vehicle) render 'home/show.html.erb' end it "should render the table" do expect(rendered).to include(vehicle.vin) end end
21.384615
51
0.701439
089e02de2b753a5543e5b35c5f278eccad76e809
555
namespace :db do namespace :second_base do task "drop:_unsafe" do SecondBase.on_base { Rake::Task['db:drop:_unsafe'].execute } end namespace :migrate do task :reset => ['db:second_base:drop:_unsafe', 'db:second_base:create', 'db:second_base:migrate'] end end end %w{ drop:_unsafe }.each do |name| task = Rake::Task["db:#{name}"] rescue nil next unless task && SecondBase::Railtie.run_with_db_tasks? task.enhance do Rake::Task["db:load_config"].invoke Rake::Task["db:second_base:#{name}"].invoke end end
24.130435
103
0.672072
395f32600605e1097ca1afb9fb823c49af05b1d0
1,149
=begin #EVE Swagger Interface #An OpenAPI for EVE Online OpenAPI spec version: 0.8.6 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.3.1 =end require 'spec_helper' require 'json' require 'date' # Unit tests for EVEOpenAPI::GetUniverseAsteroidBeltsAsteroidBeltIdNotFound # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'GetUniverseAsteroidBeltsAsteroidBeltIdNotFound' do before do # run before each test @instance = EVEOpenAPI::GetUniverseAsteroidBeltsAsteroidBeltIdNotFound.new end after do # run after each test end describe 'test an instance of GetUniverseAsteroidBeltsAsteroidBeltIdNotFound' do it 'should create an instance of GetUniverseAsteroidBeltsAsteroidBeltIdNotFound' do expect(@instance).to be_instance_of(EVEOpenAPI::GetUniverseAsteroidBeltsAsteroidBeltIdNotFound) end end describe 'test attribute "error"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
26.72093
103
0.781549
e88c9518122556bc0bf5945e5170a3847eef90a1
155
class CountryVersion < PaperTrail::Version include VersionSession self.table_name = :log_countries self.sequence_name = :log_countries_id_seq end
25.833333
44
0.8
4a9729f011b76eff429809992456fa2208326bfd
1,271
class Tile38 < Formula desc "In-memory geolocation data store, spatial index, and realtime geofence" homepage "http://tile38.com" url "https://github.com/tidwall/tile38/archive/1.9.1.tar.gz" sha256 "58ea936660105e5bcceedc05e9a4382bb9696d4f7a84edfe83cad09734a2164d" head "https://github.com/tidwall/tile38.git" bottle do cellar :any_skip_relocation sha256 "b2d3df688127a085ad14f81dd9cbad43218360b893b58673128c64fbb5708ae3" => :high_sierra sha256 "6b50ff3c6d0d7ccc7e4d22947e77795fedeed4dee0bd81b8f8090e6b9cd91791" => :sierra sha256 "858bfb5f4b5e4fd3fc8d1e6abbaf11b3d4edc4d7cda9f2c65a207379271f41ff" => :el_capitan sha256 "a56ee5e85dc8d70f9cfb83abea0ef41ff0f59b3ffdeb9aaf1203f76b8bea592e" => :yosemite end depends_on "go" => :build depends_on "godep" => :build def datadir var/"tile38/data" end def install ENV["GOPATH"] = buildpath system "make" bin.install "tile38-cli", "tile38-server" end def post_install # Make sure the data directory exists datadir.mkpath end def caveats; <<~EOS Data directory created at #{datadir}. To start the server: tile38-server -d #{datadir} To connect: tile38-cli EOS end test do system bin/"tile38-cli", "-h" end end
26.479167
93
0.732494
28702026900fbb3584f1299d345769721c8f5ab0
1,028
namespace "check" do desc "Check that the require files match the about_* files" task :abouts do about_files = Dir['src/about_*.rb'].size about_requires = `grep require src/path_to_enlightenment.rb | wc -l`.to_i puts "Checking path_to_enlightenment completeness" puts "# of about files: #{about_files}" puts "# of about requires: #{about_requires}" if about_files > about_requires puts "*** There seems to be requires missing in the path to enlightenment" else puts "OK" end puts end desc "Check that asserts have __ replacements" task :asserts do puts "Checking for asserts missing the replacement text:" begin sh "egrep -n 'assert( |_)' src/about_* | egrep -v '__|_n_|project|about_assert' | egrep -v ' *#'" puts puts "Examine the above lines for missing __ replacements" rescue RuntimeError => ex puts "OK" end puts end end desc "Run some simple consistancy checks" task :check => ["check:abouts", "check:asserts"]
30.235294
103
0.672179
18c343a9c272a40d8d9e8cc7a54de91848ac8fbc
750
# Set RAILS_ROOT and load the environment if it's not already loaded. unless defined?(Rails) ENV["RAILS_ROOT"] = File.expand_path("../example", __FILE__) require File.expand_path("../example/config/environment", __FILE__) end Teaspoon.configure do |config| config.driver = ENV['TEASPOON_DRIVER'] || "selenium" config.mount_at = "/teaspoon" config.root = TurboGraft::Engine.root config.asset_paths = ["test/javascripts", "test/javascripts/fixtures"] config.fixture_paths = ["test/javascripts/fixtures"] config.suite do |suite| suite.use_framework :mocha suite.matcher = "{test/javascripts,app/assets}/**/*_test.{js,js.coffee,coffee,coffee.erb}" suite.helper = "test_helper" suite.stylesheets = ["teaspoon"] end end
35.714286
94
0.725333
38cbd2fcd504625d858dd9671715b60f23876224
2,504
# frozen_string_literal: true require 'slack' module Slackify # Where the configuration for Slackify lives class Configuration attr_reader :custom_message_subtype_handlers, :slack_bot_token, :unhandled_handler, :custom_event_type_handlers attr_accessor :handlers, :slack_secret_token, :slack_client, :approved_bot_ids def initialize @slack_bot_token = nil @slack_secret_token = nil @handlers = generate_handlers @slack_client = nil @custom_message_subtype_handlers = {} @custom_event_type_handlers = {} @unhandled_handler = Handlers::UnhandledHandler @approved_bot_ids = [] end # Set your own unhandled handler def unhandled_handler=(handler) raise HandlerNotSupported, "#{handler.class} is not a subclass of Slackify::Handlers::Base" unless handler < Handlers::Base @unhandled_handler = handler end # Remove unhandled handler. The bot will not reply if the message doesn't # match any regex def remove_unhandled_handler @unhandled_handler = nil end # Set the token that we will use to connect to slack def slack_bot_token=(token) @slack_bot_token = token @slack_client = Slack::Web::Client.new(token: token).freeze end # Set a handler for a specific message subtype # That handler will have to implement `self.handle_event(params)` # see https://api.slack.com/events/message def custom_message_subtype_handlers=(event_subtype_hash) @custom_message_subtype_handlers = event_subtype_hash.with_indifferent_access end # Set a handler for a event type # That handler will have to implement `self.handle_event(params)` # see https://api.slack.com/events def custom_event_type_handlers=(event_type_hash) @custom_event_type_handlers = event_type_hash.with_indifferent_access end private # Convert a hash to a list of lambda functions that will be called to handle # the user messages def generate_handlers generated_handlers = [] read_handlers_yaml.each do |handler_hash| handler = Handlers::Factory.for(handler_hash) generated_handlers << handler end generated_handlers end # Reads the config/handlers.yml configuration def read_handlers_yaml raise 'config/handlers.yml does not exist' unless File.exist?("#{Rails.root}/config/handlers.yml") YAML.load_file("#{Rails.root}/config/handlers.yml") || [] end end end
32.102564
115
0.716853