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
91a3a222805a1c4aadf5355433999d5f0c4c8f12
409
require 'rubygems' require 'selenium-webdriver' driver = Selenium::WebDriver.for :firefox driver.get "http://google.com" element = driver.find_element :name => "q" element.send_keys "Cheese!" element.submit puts "Page title is #{driver.title}" wait = Selenium::WebDriver::Wait.new(:timeout => 10) wait.until { driver.title.downcase.start_with? "cheese!" } puts "Page title is #{driver.title}" driver.quit
24.058824
58
0.738386
030c54f75c5b05deb42f1b01f166b80124c8dd77
704
# frozen_string_literal: true require "date" class Date NOT_SET = Object.new # :nodoc: def to_s(format = NOT_SET) # :nodoc: if formatter = DATE_FORMATS[format] ActiveSupport::Deprecation.warn( "Date#to_s(#{format.inspect}) is deprecated. Please use Date#to_formatted_s(#{format.inspect}) instead." ) if formatter.respond_to?(:call) formatter.call(self).to_s else strftime(formatter) end elsif format == NOT_SET to_default_s else ActiveSupport::Deprecation.warn( "Date#to_s(#{format.inspect}) is deprecated. Please use Date#to_formatted_s(#{format.inspect}) instead." ) to_default_s end end end
26.074074
112
0.65483
7a9f6a02d0e171a639d148ba3ea5518a6770f245
5,926
# sexp-ruby - A simple Ruby library for parsing and validating s-expressions # Copyright (c) 2007-2015 Ingo Ruhnke <[email protected]> # # This software is provided 'as-is', without any express or implied # warranty. In no event will the authors be held liable for any damages # arising from the use of this software. # # Permission is granted to anyone to use this software for any purpose, # including commercial applications, and to alter it and redistribute it # freely, subject to the following restrictions: # # 1. The origin of this software must not be misrepresented; you must not # claim that you wrote the original software. If you use this software # in a product, an acknowledgment in the product documentation would be # appreciated but is not required. # 2. Altered source versions must be plainly marked as such, and must not be # misrepresented as being the original software. # 3. This notice may not be removed or altered from any source distribution. require_relative "value.rb" module SExp class Token attr_reader :type, :text, :line, :column def initialize(type, text, line, column) @type = type @text = text @line = line @column = column end def inspect return "[#{@type.inspect}, #{@text.inspect}, #{@line}, #{@column}]" end end class TextIO attr_reader :text, :line, :column, :pos def initialize(text) @text = text @line = 1 @column = 1 @pos = 0 end def peek() return @text[@pos] end def advance() # Line/Column counting if peek() == "\n" then @line += 1 @column = 1 else @column += 1 end @pos += 1 end def eof? return !(@pos < @text.length) end end class Lexer def initialize(text) @io = TextIO.new(text) @statefunc = method(:look_for_token) @last_c = nil @tokens = [] @token_start = @io.pos @advance = true end def tokenize() while not @io.eof? do c = @io.peek() @statefunc.call(c) if @advance then @last_c = c @io.advance else @advance = true end end @statefunc.call(nil) return @tokens end def look_for_token(c) if c == nil # eof elsif is_digit(c) or is_sign(c) or c == "." then @statefunc = method(:parse_integer_or_real) elsif c == "\"" then @statefunc = method(:parse_string) elsif c == "#" then @statefunc = method(:parse_boolean) elsif is_letter(c) or is_special_initial(c) then @statefunc = method(:parse_symbol) elsif is_whitespace(c) then @statefunc = method(:parse_whitespace) elsif c == ";" then @statefunc = method(:parse_comment) elsif c == ")" then submit(:list_end, true) elsif c == "(" then submit(:list_start, true) else raise "#{@io.line}:#{@io.column}: unexpected character #{c.inspect}" end end def parse_integer_or_real(c) if is_digit(c) then # ok elsif c == ?. then @statefunc = method(:parse_real) else if @token_start == @io.pos - 1 and not is_digit(@io.text[@token_start]) then raise "#{@io.line}:#{@io.column}: '#{@io.text[@token_start].chr}' must be followed by digit" else submit(:integer, false) end end end def parse_boolean(c) if c == "t" or c == "f" then submit(:boolean, true) else raise "#{@line}:#{@column}: expected 'f' or 't', got '#{c.chr}" end end def parse_real(c) if ("0".."9").member?(c) then # ok else submit(:real, false) end end def parse_symbol(c) if is_letter(c) or is_digit(c) or is_special_subsequent(c) or is_special_initial(c) then # ok else submit(:symbol, false) end end def parse_string(c) if (c == "\"" and @last_c != "\\") then submit(:string, true) end end def parse_whitespace(c) if not is_whitespace(c) then submit(:whitespace, false) end end def parse_comment(c) if c == "\n" then submit(:comment, true) end end def submit(type, include_current_character) @statefunc = method(:look_for_token) if include_current_character then current_token = @io.text[@token_start..(@io.pos)] @token_start = @io.pos+1 else current_token = @io.text[@token_start..(@io.pos-1)] @token_start = @io.pos @advance = false end # FIXME: line:column refers to the end of the token, not the start case type when :string @tokens << Token.new(:string, current_token[1..-2]. gsub("\\n", "\n"). gsub("\\\"", "\""). gsub("\\t", "\t"), @io.line, @io.column) when :list_start @tokens << Token.new(:list_start, current_token, @io.line, @io.column) when :list_end @tokens << Token.new(:list_end, current_token, @io.line, @io.column) else @tokens << Token.new(type, current_token, @io.line, @io.column) end end def is_digit(c) return ("0".."9").member?(c) end def is_letter(c) return (("a".."z").member?(c) or ("A".."Z").member?(c)) end def is_whitespace(c) return [" ", "\n", "\t"].member?(c) end def is_special_initial(c) return ["!", "$", "%", "&", "*", "/", ":", "<", "=", ">", "?", "^", "_", "~"].member?(c) end def is_special_subsequent(c) return ["+", "-", ".", "@"].member?(c) end def is_sign(c) return ["+", "-"].member?(c) end end end # EOF #
24.589212
102
0.551131
f75812be673fda30792eafa2828e4e0e64f93c47
1,130
name "necrosan" description "Master role applied to necrosan" default_attributes( :networking => { :interfaces => { :external_ipv4 => { :interface => "ens18", :role => :external, :family => :inet, :address => "80.67.167.77", :prefix => "32", :gateway => "10.0.6.1" }, :external_ipv6 => { :interface => "ens18", :role => :external, :family => :inet6, :address => "2a0b:cbc0:110d:1::1c", :prefix => "64", :gateway => "2a0b:cbc0:110d:1::1" } } }, :squid => { :cache_mem => "7500 MB", :cache_dir => "coss /store/squid/coss-01 128000 block-size=8192 max-size=262144 membufs=80" }, :tilecache => { :tile_parent => "france.render.openstreetmap.org", :tile_siblings => [ # "necrosan.openstreetmap.org", "nepomuk.openstreetmap.org", "noomoahk.openstreetmap.org", "norbert.openstreetmap.org", "ladon.openstreetmap.org", "culebre.openstreetmap.org", "gorynych.openstreetmap.org" ] } ) run_list( "role[milkywan]", "role[tilecache]" )
24.042553
95
0.548673
9161efa6ea822be2a77fad68d255346be4fbf213
6,024
# # Author:: Mike Dodge (<[email protected]>) # Copyright:: Copyright (c) 2015 Facebook, Inc. # License:: Apache License, Version 2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # require "chef/resource" class Chef class Resource class Launchd < Chef::Resource resource_name :launchd provides :launchd description "Use the launchd resource to manage system-wide services (daemons) and per-user services (agents) on the macOS platform." introduced "12.8" default_action :create allowed_actions :create, :create_if_missing, :delete, :enable, :disable, :restart property :label, String, identity: true, name_property: true property :backup, [Integer, FalseClass], desired_state: false property :cookbook, String, desired_state: false property :group, [String, Integer] property :plist_hash, Hash property :mode, [String, Integer] property :owner, [String, Integer] property :path, String property :source, String property :session_type, String # StartCalendarInterval has some gotchas so we coerce it to help sanity # check. According to `man 5 launchd.plist`: # StartCalendarInterval <dictionary of integers or array of dictionaries of integers> # ... Missing arguments are considered to be wildcard. # What the man page doesn't state, but what was observed (OSX 10.11.5, launchctrl v3.4.0) # Is that keys that are specified, but invalid, will also be treated as a wildcard # this means that an entry like: # { "Hour"=>0, "Weekday"=>"6-7"} # will not just run on midnight of Sat and Sun, rather it will run _every_ midnight. property :start_calendar_interval, [Hash, Array], coerce: proc { |type| # Coerce into an array of hashes to make validation easier array = if type.is_a?(Array) type else [type] end # Check to make sure that our array only has hashes unless array.all? { |obj| obj.is_a?(Hash) } error_msg = "start_calendar_interval must be a single hash or an array of hashes!" raise Chef::Exceptions::ValidationFailed, error_msg end # Make sure the hashes don't have any incorrect keys/values array.each do |entry| allowed_keys = %w{Minute Hour Day Weekday Month} unless entry.keys.all? { |key| allowed_keys.include?(key) } failed_keys = entry.keys.reject { |k| allowed_keys.include?(k) }.join(", ") error_msg = "The following key(s): #{failed_keys} are invalid for start_calendar_interval, must be one of: #{allowed_keys.join(", ")}" raise Chef::Exceptions::ValidationFailed, error_msg end unless entry.values.all? { |val| val.is_a?(Integer) } failed_values = entry.values.reject { |val| val.is_a?(Integer) }.join(", ") error_msg = "Invalid value(s) (#{failed_values}) for start_calendar_interval item. Values must be integers!" raise Chef::Exceptions::ValidationFailed, error_msg end end # Don't return array if we only have one entry if array.size == 1 array.first else array end } property :type, String, default: "daemon", coerce: proc { |type| type = type ? type.downcase : "daemon" types = %w{daemon agent} unless types.include?(type) error_msg = "type must be daemon or agent" raise Chef::Exceptions::ValidationFailed, error_msg end type } # Apple LaunchD Keys property :abandon_process_group, [ TrueClass, FalseClass ] property :debug, [ TrueClass, FalseClass ] property :disabled, [ TrueClass, FalseClass ], default: false property :enable_globbing, [ TrueClass, FalseClass ] property :enable_transactions, [ TrueClass, FalseClass ] property :environment_variables, Hash property :exit_timeout, Integer property :hard_resource_limits, Hash property :inetd_compatibility, Hash property :init_groups, [ TrueClass, FalseClass ] property :keep_alive, [ TrueClass, FalseClass, Hash ] property :launch_only_once, [ TrueClass, FalseClass ] property :ld_group, String property :limit_load_from_hosts, Array property :limit_load_to_hosts, Array property :limit_load_to_session_type, [ Array, String ] property :low_priority_io, [ TrueClass, FalseClass ] property :mach_services, Hash property :nice, Integer property :on_demand, [ TrueClass, FalseClass ] property :process_type, String property :program, String property :program_arguments, Array property :queue_directories, Array property :root_directory, String property :run_at_load, [ TrueClass, FalseClass ] property :sockets, Hash property :soft_resource_limits, Array property :standard_error_path, String property :standard_in_path, String property :standard_out_path, String property :start_interval, Integer property :start_on_mount, [ TrueClass, FalseClass ] property :throttle_interval, Integer property :time_out, Integer property :umask, Integer property :username, String property :wait_for_debugger, [ TrueClass, FalseClass ] property :watch_paths, Array property :working_directory, String end end end
41.260274
146
0.667497
083b165dcecdf5e376db5588e8bfd8846d13d86e
271
require 'active_support/deprecation' require 'active_support/core_ext/module/attribute_accessors' ActiveSupport::Deprecation.warn( "The cattr_* method definitions have been moved into active_support/core_ext/module/attribute_accessors. Please require that instead." )
38.714286
136
0.841328
260ba6993256fbfcd32bafc8cc87eba3c873cb35
1,507
require 'spec_helper' require_relative 'shared_examples' describe BRDocuments::IE::AL do before :all do @format_examples = { '240000048' => '24.000.004-8' } @valid_numbers = %w( 240000048 24.000.004-8 24.000004.8 24000004-8 24.810989-8 24.840219-6 24.838692-1 24.885944-7 24.860732-4 24.817955-1 24.577875-6 24.757527-5 24.864992-2 ) @invalid_numbers = %w( 24.000.004-80 124.000.004-8 ) @valid_verify_digits = { [8] => %w(24.000.004 24.000004 24000004 24.007.177-8 24.007.177 24007177), [4] => %w(24.209.925-4 24.209.925 24209925) } @valid_existent_numbers = [ '24.000.004-8', # Exemplo Sintegra '24.007.177-8', # COMPANHIA ENERGETICA DE ALAGOAS - CEA '24.209.925-4', # VIVO S/A '24.009.599-5', # BANCO DO ESTADO DE ALAGOAS S A ] end include_examples "IE basic specs" it 'must generate a number with valid company type digit' do 10.times { number = described_class.generate expect(described_class.company_type(number)).to_not be_nil } end it 'must handle companies type methods' do expect(described_class.company_type('24.864992-2')).to eq('Micro-Empresa') expect(described_class.company_type('24.577875-6')).to eq('Substituta') expect(described_class.company_type_digit('24.577875-6')).to eq('5') expect(described_class.company_type_digit('24.885944-7')).to eq('8') end end
24.306452
80
0.627074
1a5ff22d5d98cb5caa96262f4b6eb4806a5229ae
10,626
RSpec.describe Metasploit::Model::Association::Tree do context 'expand' do subject(:expand) { described_class.expand(associations) } context 'with Array<Hash>' do let(:associations) { [ { first_parent: :first_child }, { second_parent: :second_child } ] } it 'merges hashes' do expect(expand).to have_key(:first_parent) first_child_tree = expand[:first_parent] expect(first_child_tree).to have_key(:first_child) expect(first_child_tree[:first_child]).to be_nil expect(expand).to have_key(:second_parent) second_child_tree = expand[:second_parent] expect(second_child_tree).to have_key(:second_child) expect(second_child_tree[:second_child]).to be_nil end end context 'with Array<Symbol>' do let(:associations) { [ :first, :second ] } it 'expands to Hash{Symbol => nil}' do expect(expand).to have_key(:first) expect(expand[:first]).to be_nil expect(expand).to have_key(:second) expect(expand[:second]).to be_nil end end context 'with Hash<Symbol>' do let(:associations) { { parent: :child } } it 'expands to Hash{Symbol => Hash{Symbol => nil}}' do expect(expand).to have_key(:parent) child_tree = expand[:parent] expect(child_tree).to have_key(:child) expect(child_tree[:child]).to be_nil end end context 'with Symbol' do let(:associations) { :symbol } it 'expands to Hash{Symbol => nil}' do expect(expand).to have_key(:symbol) expect(expand[:symbol]).to be_nil end end end context 'merge' do subject(:merge) { described_class.merge(first, second) } context 'first' do context 'with nil' do let(:first) { nil } context 'second' do context 'with nil' do let(:second) { nil } it { is_expected.to be_nil } end context 'without nil' do let(:second) { double('second') } it 'returns second' do expect(merge).to eq(second) end end end end context 'without nil' do let(:first) { { common: { first_common_child: nil }, first: { first_child: nil } } } context 'second' do context 'with nil' do let(:second) { nil } it 'returns first' do expect(merge).to eq(first) end end context 'without nil' do let(:second) { { common: { second_common_child: nil }, second: { second_child: nil } } } it 'merges trees under common keys' do expect(merge).to have_key(:common) common_tree = merge[:common] expect(common_tree).to have_key(:first_common_child) expect(common_tree[:first_common_child]).to be_nil expect(common_tree).to have_key(:second_common_child) expect(common_tree[:second_common_child]).to be_nil end it 'reuses uncommon keys' do expect(merge[:first]).to eq(first[:first]) expect(merge[:second]).to eq(second[:second]) end end end end end end context 'operators' do subject(:operators) { described_class.operators( expanded, class: klass ) } let(:near_class) { Class.new { include Metasploit::Model::Search search_attribute :near_boolean, type: :boolean search_attribute :near_string, type: :string }.tap { |klass| stub_const('NearClass', klass) } } let(:klass) { near_class = self.near_class Class.new do include Metasploit::Model::Association association :near_classes, class_name: near_class.name end } context 'with Hash{Symbol => nil}' do let(:expanded) { { near_classes: nil } } it 'includes a Metasploit::Model::Search::Operator::Association for each non-association operator on the associated class' do near_classes_near_boolean = operators.find { |o| o.name == :'near_classes.near_boolean' } expect(near_classes_near_boolean).to be_a Metasploit::Model::Search::Operator::Association expect(near_classes_near_boolean.association).to eq(:near_classes) expect(near_classes_near_boolean.klass).to eq(klass) near_boolean = near_classes_near_boolean.source_operator expect(near_boolean).to eq(near_class.search_operator_by_name.fetch(:near_boolean)) near_classes_near_string = operators.find { |o| o.name == :'near_classes.near_string' } expect(near_classes_near_string).to be_a Metasploit::Model::Search::Operator::Association expect(near_classes_near_string.association).to eq(:near_classes) expect(near_classes_near_string.klass).to eq(klass) near_string = near_classes_near_string.source_operator expect(near_string).to eq(near_class.search_operator_by_name.fetch(:near_string)) end end context 'with Hash{Symbol => Hash}' do let(:expanded) { { near_classes: { far_class: nil } } } let(:far_class) { Class.new { include Metasploit::Model::Search search_attribute :far_integer, type: :integer }.tap { |klass| stub_const('FarClass', klass) } } let(:near_class) { super().tap { |klass| far_class = self.far_class klass.class_eval do include Metasploit::Model::Association association :far_class, class_name: far_class.name end } } it 'includes a Metasploit::Model::Search::Operator::Association for each non-association operator on the near class' do near_classes_near_boolean = operators.find { |o| o.name == :'near_classes.near_boolean' } expect(near_classes_near_boolean).to be_a Metasploit::Model::Search::Operator::Association expect(near_classes_near_boolean.association).to eq(:near_classes) expect(near_classes_near_boolean.klass).to eq(klass) near_boolean = near_classes_near_boolean.source_operator expect(near_boolean).to eq(near_class.search_operator_by_name.fetch(:near_boolean)) near_classes_near_string = operators.find { |o| o.name == :'near_classes.near_string' } expect(near_classes_near_string).to be_a Metasploit::Model::Search::Operator::Association expect(near_classes_near_string.association).to eq(:near_classes) expect(near_classes_near_string.klass).to eq(klass) near_string = near_classes_near_string.source_operator expect(near_string).to eq(near_class.search_operator_by_name.fetch(:near_string)) end it 'includes Metasploit::Model::Search::Operator::Association for each non-association operator on the far class' do near_classes_far_class_far_integer = operators.find { |o| o.name == :'near_classes.far_class.far_integer' } expect(near_classes_far_class_far_integer).to be_a Metasploit::Model::Search::Operator::Association expect(near_classes_far_class_far_integer.association).to eq(:near_classes) expect(near_classes_far_class_far_integer.klass).to eq(klass) far_class_far_integer = near_classes_far_class_far_integer.source_operator expect(far_class_far_integer).to be_a Metasploit::Model::Search::Operator::Association expect(far_class_far_integer.association).to eq(:far_class) expect(far_class_far_integer.klass).to eq(near_class) far_integer = far_class_far_integer.source_operator expect(far_integer).to eq(far_class.search_operator_by_name.fetch(:far_integer)) end end context 'with nil' do let(:expanded) { nil } it { is_expected.to eq([]) } end end context 'reflect_on_association_on_class' do subject(:reflect_on_association_on_class) { described_class.reflect_on_association_on_class(association, klass) } let(:association) { :associated_things } let(:klass) { Class.new } context 'klass' do context 'responds to reflect_on_association' do let(:klass) { super().tap { |klass| klass.send(:include, Metasploit::Model::Association) } } context 'with association' do # # lets # let(:associated_class) { Class.new.tap { |klass| stub_const('AssociatedThing', klass) } } let(:klass) { super().tap { |klass| klass.association association, class_name: associated_class.name } } it 'returns reflection with associated class as klass' do expect(reflect_on_association_on_class.klass).to eq(associated_class) end end context 'without association' do it 'raises a Metasploit::Model::Association::Error on association and klass' do expect { reflect_on_association_on_class }.to raise_error(Metasploit::Model::Association::Error) { |error| expect(error.model).to eq(klass) expect(error.name).to eq(association) } end end end context 'does not respond to reflect_on_association' do it 'raises NameError with instructions for using Metasploit::Model::Association' do expect { reflect_on_association_on_class }.to raise_error(NameError) { |error| expect(error.message).to include 'Metasploit::Model::Association' } end end end end end
27.744125
131
0.582063
f818d93964bf1d8340915a8f678e92b41d99499d
89
# frozen_string_literal: true class AdminAccessDeniedException < SmartvpnException; end
22.25
57
0.853933
03ab1cfb3e301715c1de5dd962db9ec6fc13a970
4,020
module Rpush module Client module ActiveModel module Apns module Notification APNS_DEFAULT_EXPIRY = 1.day.to_i APNS_PRIORITY_IMMEDIATE = 10 APNS_PRIORITY_CONSERVE_POWER = 5 APNS_PRIORITIES = [APNS_PRIORITY_IMMEDIATE, APNS_PRIORITY_CONSERVE_POWER] def self.included(base) base.instance_eval do validates :device_token, presence: true validates :badge, numericality: true, allow_nil: true validates :priority, inclusion: { in: APNS_PRIORITIES }, allow_nil: true validates_with Rpush::Client::ActiveModel::Apns::DeviceTokenFormatValidator validates_with Rpush::Client::ActiveModel::Apns::BinaryNotificationValidator base.const_set('APNS_DEFAULT_EXPIRY', APNS_DEFAULT_EXPIRY) unless base.const_defined?('APNS_DEFAULT_EXPIRY') base.const_set('APNS_PRIORITY_IMMEDIATE', APNS_PRIORITY_IMMEDIATE) unless base.const_defined?('APNS_PRIORITY_IMMEDIATE') base.const_set('APNS_PRIORITY_CONSERVE_POWER', APNS_PRIORITY_CONSERVE_POWER) unless base.const_defined?('APNS_PRIORITY_CONSERVE_POWER') end end def device_token=(token) write_attribute(:device_token, token.delete(" <>")) unless token.nil? end MDM_KEY = '__rpush_mdm__' def mdm=(magic) self.data = (data || {}).merge(MDM_KEY => magic) end MUTABLE_CONTENT_KEY = '__rpush_mutable_content__' def mutable_content=(bool) return unless bool self.data = (data || {}).merge(MUTABLE_CONTENT_KEY => true) end CONTENT_AVAILABLE_KEY = '__rpush_content_available__' def content_available=(bool) return unless bool self.data = (data || {}).merge(CONTENT_AVAILABLE_KEY => true) end def as_json(options = nil) # rubocop:disable Metrics/AbcSize, Metrics/PerceivedComplexity json = ActiveSupport::OrderedHash.new if data && data.key?(MDM_KEY) json['mdm'] = data[MDM_KEY] else json['aps'] = ActiveSupport::OrderedHash.new json['aps']['alert'] = alert if alert json['aps']['badge'] = badge if badge json['aps']['sound'] = sound if sound json['aps']['category'] = category if category json['aps']['url-args'] = url_args if url_args if data && data[MUTABLE_CONTENT_KEY] json['aps']['mutable-content'] = 1 end if data && data[CONTENT_AVAILABLE_KEY] json['aps']['content-available'] = 1 end if data non_aps_attributes = data.reject { |k, _| k == CONTENT_AVAILABLE_KEY || k == MUTABLE_CONTENT_KEY } non_aps_attributes.each { |k, v| json[k.to_s] = v } end end json end def to_binary(options = {}) frame_payload = payload frame_id = options[:for_validation] ? 0 : send(options.fetch(:id_attribute, :id)) frame = "" frame << [1, 32, device_token].pack("cnH*") frame << [2, frame_payload.bytesize, frame_payload].pack("cna*") frame << [3, 4, frame_id].pack("cnN") frame << [4, 4, expiry ? Time.now.to_i + expiry.to_i : 0].pack("cnN") frame << [5, 1, priority_for_frame].pack("cnc") [2, frame.bytesize].pack("cN") + frame end private def priority_for_frame # It is an error to use APNS_PRIORITY_IMMEDIATE for a notification that only contains content-available. if as_json['aps'].try(:keys) == ['content-available'] APNS_PRIORITY_CONSERVE_POWER else priority || APNS_PRIORITY_IMMEDIATE end end end end end end end
38.653846
149
0.579353
bb53a2440d4aa6034bdbe3e618ab35372d45f4dc
2,164
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = true # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true config.action_mailer.default_url_options = { :host => 'your_production_app.com' } config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = true config.action_mailer.default :charset => "utf-8" config.action_mailer.smtp_settings = { address: "smtp.gmail.com", port: 587, domain: "gmail.com", authentication: "plain", enable_starttls_auto: true, user_name: ENV["GMAIL_USERNAME"], password: ENV["GMAIL_PASSWORD"] } end
36.677966
85
0.752311
33192fae39f0c890d368949162a896975b58efde
937
require "rails_helper" RSpec.describe Exchanges::BrokerApplicantsHelper, dbclean: :after_each, :type => :helper do context "sort_by_latest_transition_time" do let(:person1) {FactoryGirl.create(:person, :with_broker_role)} let(:person2) {FactoryGirl.create(:person, :with_broker_role)} let(:person3) {FactoryGirl.create(:person, :with_broker_role)} let(:people) {Person.exists(broker_role: true)} it "returns people array sorted by broker_role.latest_transition_time" do person1.broker_role.workflow_state_transitions.first.update_attributes(created_at: Time.now - 6.days) person2.broker_role.workflow_state_transitions.first.update_attributes(created_at: Time.now - 1.days) person3.broker_role.workflow_state_transitions.first.update_attributes(created_at: Time.now - 2.days) expect(helper.sort_by_latest_transition_time(people).to_a).to eq([person2, person3, person1]) end end end
49.315789
107
0.77588
1d54a9f0f8a7054eae35834a773bcb12f4a2871b
2,043
# frozen_string_literal: true require "ams_lazy_relationships/core/lazy_relationship_meta" module AmsLazyRelationships::Core module LazyRelationshipMethod # This method defines a new lazy relationship on the serializer and a method # with `lazy_` prefix. # # @param name [Symbol] The name of the lazy relationship. It'll be used # to define lazy_ method. # # @param loader [Object] An object responding to `load(record)` method. # By default the AR association loader is used. # The loader should either lazy load (e.g. use BatchLoader) the data or # perform a very light action, because it might be called more than once # when serializing the data. # # @param load_for [Symbol] Optionally you can delegate the loading to # a method defined by `load_for` symbol. # It is useful e.g. when the loaded object is a decorated object and the # real AR model is accessible by calling the decorator's method. def lazy_relationship(name, loader: nil, load_for: nil) @lazy_relationships ||= {} name = name.to_sym loader ||= begin current_model_class = self.name.demodulize.gsub("Serializer", "") AmsLazyRelationships::Loaders::Association.new(current_model_class, name) end lrm = LazyRelationshipMeta.new( name: name, loader: loader, reflection: find_reflection(name), load_for: load_for ) @lazy_relationships[name] = lrm define_method :"lazy_#{name}" do self.class.send(:load_lazy_relationship, lrm, object) end end private def find_reflection(name) version = AmsLazyRelationships::Core.ams_version # In 0.10.3 this private API has changed again return _reflections[name] if version >= Gem::Version.new("0.10.3") # In 0.10.0.rc2 this private API has changed return _reflections.find { |r| r.name.to_sym == name } if version >= Gem::Version.new("0.10.0.rc2") _associations[name] end end end
33.491803
105
0.673519
f8e1325e2f16d27e94f020d15a238143a3e457dc
18,634
# Encoding: utf-8 # IBM WebSphere Application Server Liberty Buildpack # Copyright IBM Corp. 2014, 2016 # # 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 'liberty_buildpack/diagnostics/logger_factory' require 'liberty_buildpack/repository/configured_item' require 'liberty_buildpack/repository/repository_utils' module LibertyBuildpack::Services #----------------------------------- # A class of static utility methods #----------------------------------- class Utils #--------------------------------------------------------------------- # A utility method that can be used by most service classes to generate runtime-vars.xml entries. Services with json that does not follow normal conventions # might not be able to use this utility method and should provide the proper implementation in the service class. For services with json with non-String values # it is possible to customize how the property values are converted into a String by provding a code block that does the translation. For example: # # Utils.parse_compliant_vcap_service(doc.root, vcap_services) do | name, value | # if name == 'credentials.scope' # value = value.join(' ') # else # value # end # end # # By default, properties of Array type are converted into a comma separated String. # # @param [REXML::Element] element - the root element for the runtime-vars.xml doc. A new sub-element will be written to this doc for each cloud variable generated. # @param [Hash] properties - the vcap_services data for the service instance. # return a hash of cloud variables that mirrors what was written to runtime-vars.xml for use in the service implementation, as appropriate. #----------------------------------------------------------------------- def self.parse_compliant_vcap_service(element, properties) hash_to_return = {} properties.keys.each do |property| if properties[property].class == String # base attribute. Create cloud form of variable and add to runtime_vars and hash. # To make life easier for the user, add a special key into the return hash to make it easier to find the name of the service. hash_to_return['service_name'] = properties[property] if property == 'name' name = "cloud.services.#{properties['name']}.#{property}" value = block_given? ? yield(property, properties[property]) : properties[property] add_runtime_var(element, hash_to_return, name, value) elsif properties[property].class == Hash && property == 'credentials' # credentials. Create cloud form of variable and add to runtime_vars and hash properties[property].keys.each do |subproperty| name = "cloud.services.#{properties['name']}.connection.#{subproperty}" value = properties[property][subproperty] if block_given? value = yield("#{property}.#{subproperty}", value) elsif value.is_a?(Array) value = value.join(', ') end add_runtime_var(element, hash_to_return, name, value) end # each subproperty end end hash_to_return end #------------------------------------------------------------------------------------ # a method to get a cloud property substitution variable. # # @param [Hash] properties - the hash of cloud variables generated by the Utils.parse_compliant_vcap_service method. # @param [String] service_name - the name of the calling service, for debug purposes. # @param [String] prop_name - the basic property name, in cloud form. Something like cloud.service.*.port, cloud.service.*.host,, etc # @param [String] prop_name_alias - the alias if the property has one (e.g. host and hostname are considered aliases.) # return the ant-style cloud variable. # @raise if the property does not exist in properties. #------------------------------------------------------------------------------------ def self.get_cloud_property(properties, service_name, prop_name, prop_name_alias = nil) return "${#{prop_name}}" if properties.key?(prop_name) return "${#{prop_name_alias}}" if prop_name_alias.nil? == false && properties.key?(prop_name_alias) raise "Resource #{service_name} does not contain a #{prop_name} property" end #------------------------------------------------------------------------------------ # A utility method to to add features into the server.xml featureManager. The features # parameter can be specified as an array, for example ['jdbc-4.0'] or as a hash. If the # parameter is specified as a hash value, it must contain 'if', 'then', and 'else' mappings. # The function will check if any of the features specified under the 'if' mapping exist in # the server.xml. If a single match is found, the function will add the features under the # 'then' mapping into the featureManager. Otherwise, the features under the 'else' mapping # will be added. # # @param [REXML::Element] doc - the root element of the server.xml document. # @param features - an array or hash of features to add to the featureManager. #------------------------------------------------------------------------------------ def self.add_features(doc, features) raise 'invalid parameters' if doc.nil? || features.nil? current_features = get_features(doc) if features.is_a?(Hash) condition_features = features['if'] condition_true_features = features['then'] condition_false_features = features['else'] raise 'Invalid feature condition' if condition_features.nil? || condition_true_features.nil? || condition_false_features.nil? if shared_elements?(current_features, condition_features) add_features_sub(doc, current_features, condition_true_features) else add_features_sub(doc, current_features, condition_false_features) end elsif features.is_a?(Array) add_features_sub(doc, current_features, features) else raise 'Invalid feature expression type' end end #---------------------------------------------------------------------------------------- # A Utility method that ensures bootstrap.properties exists in the server directory and contains specified property # # @param [String] server_dir - the name of the server dir. # @param [String] property - The property, e.g. 'websphere.log.provider=binaryLogging-1.0' # @param [Regexp] reg_ex - The Regexp used to search an existing bootstrap.properties for a property, e.g. /websphere.log.provider[\s]*=[\s]*binaryLogging-1.0/ #--------------------------------------------------------------------------------------- def self.update_bootstrap_properties(server_dir, property, reg_ex) raise 'invalid parameters' if server_dir.nil? || property.nil? || reg_ex.nil? bootstrap = File.join(server_dir, 'bootstrap.properties') if File.exist?(bootstrap) == false File.open(bootstrap, 'w') { |file| file.write(property) } else bootstrap_contents = File.readlines(bootstrap) bootstrap_contents.each do |line| return if (line =~ reg_ex).nil? == false end File.open(bootstrap, 'a') { |file| file.write(property) } end end #------------------------------------------------- # Return true if the specified array contains a single logical configuration element. A logical Element may be partitioned over multiple # physical Elements with the same configuration id # # @param [Array<REXML::Element>] elements_array - The non-null array containing the elements to check. # @ return true if the array describes a single logical element, false otherwise #------------------------------------------------- def self.logical_singleton?(elements_array) return true if elements_array.length == 1 id = elements_array[0].attribute('id') elements_array[1..(elements_array.length - 1)].each do |element| my_id = element.attribute('id') return false if my_id != id end true end #------------------------------------------------------------------------------------ # Utility method that searches an Element array that defines a single logical configuration stanza for the named attribute and # updates it to the specified value. # - if multiple instances of the attribute are found, all are updated. (User error in the provided xml) # - if the attribute is not found, then add it to an arbitrary element. # # @param [ARRAY<REXML::Element>] element_array - the non-null Element array # @param [String] name - the non-null attribute name. # @param [String] value - the value. #------------------------------------------------------------------------------------ def self.find_and_update_attribute(element_array, name, value) found = false element_array.each do |element| # Liberty allows the logical stanza to be partitioned over multiple physical stanzas. Well-formed xml will declare a given attribute once, at most. # We handle xml that is not well formed by searching all partitions and updating all instances, to ensure the value is applied. unless element.attribute(name).nil? element.add_attribute(name, value) found = true end end # Attribute was not found, add it. Add it to last element. element_array[-1].add_attribute(name, value) unless found end #------------------------------------------------------------------------------------ # Utility method that searches an Element array that defines a single logical Element for the named attribute and returns the last value. # If the attribute is defined multiple times, the value of the last instance is returned. # # @param [ARRAY<REXML::Element>] element_array - the non-null Element array # @param [String] name - the non-null attribute name. #------------------------------------------------------------------------------------ def self.find_attribute(element_array, name) retval = nil element_array.each do |element| if element.attribute(name).nil? == false retval = element.attribute(name).value end end retval end #--------------------------------------------------- # A utility method that returns an array of all application/webApplication Elements # # @param [REXML::Element] doc - the root Element of the server.xml document. #--------------------------------------------------- def self.get_applications(doc) applications = [] apps = doc.elements.to_a('//application') apps.each { |app| applications.push(app) } webapps = doc.elements.to_a('//webApplication') webapps.each { |webapp| applications.push(webapp) } applications end #------------------------------- # Return the api visibility setting from the classloader for the single configured application. Nil is returned if there is not exactly one app configured, if the one app does # not configure a classloader, or if the api visibility is not set. # # @param [REXML::Element] doc - the root Element of the server.xml document. #------------------------------- def self.get_api_visibility(doc) apps = Utils.get_applications(doc) unless apps.length == 1 LibertyBuildpack::Diagnostics::LoggerFactory.get_logger.warn("Unable to determine classloader visibility as there are #{apps.length} apps") return end classloaders = apps[0].get_elements('classloader') return nil if classloaders.empty? # At present, Liberty only supports one classloader per app, but that may change. Visibility may only be specified on one classloader, if multiples exist. classloaders.each do |classloader| return classloader.attribute('apiTypeVisibility').value if classloader.attribute('apiTypeVisibility').nil? == false end nil end #------------------------------------------------------------------------------------ # A Utility method to add a library to the single application. The method silently returns if there is not exactly one application. # The classloader will be created if the one application does not already contain a classloader element. # # @param [REXML::Element] doc - the root Element of the server.xml doc. # @param [String] debug_name - the non-null name of the calling service, used for serviceability. # @param [String] lib_id - the non-null id for the shared library #------------------------------------------------------------------------------------ def self.add_library_to_app_classloader(doc, debug_name, lib_id) # Get a list of all applications. If there is more than one application, we do not know which application to add the library to. apps = Utils.get_applications(doc) unless apps.length == 1 LibertyBuildpack::Diagnostics::LoggerFactory.get_logger.warn("Unable to add a shared library for service #{debug_name}. There are #{apps.length} applications") return end classloaders = apps[0].get_elements('classloader') # At present, Liberty only allows a single classloader element per application However, assume this may change in the future, handle partitioned classloader. if classloaders.empty? classloader_element = REXML::Element.new('classloader', apps[0]) classloader_element.add_attribute('commonLibraryRef', lib_id) return end classloaders.each do |classloader| next if classloader.attribute('commonLibraryRef').nil? # commonLibraryRef contain a comma-separated string of library ids. cur_value = classloader.attribute('commonLibraryRef').value return if cur_value.include?(lib_id) classloader.add_attribute('commonLibraryRef', "#{cur_value},#{lib_id}") return end classloaders[0].add_attribute('commonLibraryRef', lib_id) end private #------------------------------------------- # Add a runtime var to runtime-vars.xml. A new Element named 'variable' will be added to the runtime-vars doc and the new Element will have an attribute of name, value # # @param [REXML::Element] element - the root element of runtime-vars.xml # @param [Hash] instance_hash - a hash passed in by the user to which the name-value pair is added. # @param [String] name - the non-null name of the attribute to add # @param [String] value - the non-null value of the attribute #--------------------------------------------- def self.add_runtime_var(element, instance_hash, name, value) new_element = REXML::Element.new('variable', element) new_element.add_attribute('name', name) new_element.add_attribute('value', value) instance_hash[name] = value end #---------------------------------------------------------------------------------------- # Determine which client jars need to be downloaded for this service to function properly. # Look up the client jars based on the 'client_jar_key', 'client_jar_url', or 'driver' information in the plugin configuration. # # @param config - plugin configuration. # @param urls - an array containing the available download urls for client jars # return - a non-null array of urls. Will be empty if nothing needs to be downloaded. #----------------------------------------------------------------------------------------- def self.get_urls_for_client_jars(config, urls) logger = LibertyBuildpack::Diagnostics::LoggerFactory.get_logger client_jar_key = config['client_jar_key'] if client_jar_key.nil? || urls[client_jar_key].nil? # client_jar_key not found - check for client_jar_url client_jar_url = config['client_jar_url'] if client_jar_url.nil? # client_jar_url not found - check for driver repository = config['driver'] if repository.nil? # driver not found logger.debug('No client_jar_key, client_jar_url, or driver defined.') return [] else # driver found version, driver_uri = LibertyBuildpack::Repository::ConfiguredItem.find_item(repository) logger.debug("Found driver: version: #{version}, url: #{driver_uri}") return [driver_uri] end else # client_jar_url found logger.debug("Found client_jar_url: #{client_jar_url}") utils = LibertyBuildpack::Repository::RepositoryUtils.new return [utils.resolve_uri(client_jar_url)] end else # client_jar_key found logger.debug("Found client_jar_key: #{urls[client_jar_key]}") return [urls[client_jar_key]] end end def self.get_features(doc) managers = doc.elements.to_a('//featureManager') features = Set.new managers.each do |manager| elements = manager.get_elements('feature') elements.each do |element| features.add(element.text) end end features end def self.add_features_sub(doc, current_features, features) additional_features = Set.new features.each do |feature| additional_features.add(feature) unless current_features.include?(feature) end managers = doc.elements.to_a('//featureManager') if managers.empty? manager = REXML::Element.new('featureManager', doc.root) else manager = managers.first end additional_features.each do |feature| element = REXML::Element.new('feature', manager) element.add_text(feature) end end def self.shared_elements?(array1, array2) array2.each do |element| return true if array1.include?(element) end false end end end
50.63587
179
0.623108
263158c4dfd99e36be83cdc38b4723215a0faf43
4,644
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "matchr_api_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
45.087379
114
0.762274
034c40a0436ea448f11ff7afc04e91d1ee5cfe15
127
class CourseSerializer < ActiveModel::Serializer attributes :id, :name, :description, :teacher_id belongs_to :teacher end
25.4
50
0.779528
0124ae7c5a4ea02588cde34320b387a1b6345b3c
995
require "rails_helper" describe "PreviewUserMentions API", :json_api do context "GET /preview_user_mentions/" do def make_request_for_preview(preview) get "#{host}/preview_user_mentions/", preview_id: preview.id end let(:preview_a) { create(:preview) } let(:preview_b) { create(:preview) } before do create_list(:preview_user_mention, 4, preview: preview_a) create_list(:preview_user_mention, 1, preview: preview_b) end it "fetches mentions of specified status for specified post" do make_request_for_preview(preview_a) expect(last_response.status).to eq 200 expect(json). to serialize_collection(preview_a.preview_user_mentions.all). with(PreviewUserMentionSerializer) make_request_for_preview(preview_b) expect(last_response.status).to eq 200 expect(json). to serialize_collection(preview_b.preview_user_mentions.all). with(PreviewUserMentionSerializer) end end end
31.09375
69
0.721608
7addb50ba0b86de4a5e2ac1b1c85a547844c0457
300
require 'fileutils' module Umakadata # A class that represents Vocabulary Prefix # # @since 1.0.0 class VocabularyPrefix class << self EXCLUDE_PATTERNS = [ /www.openlinksw.com/ ].freeze def exclude_patterns EXCLUDE_PATTERNS end end end end
15.789474
45
0.633333
ace9be155bc616c011be64cd9ed1b2306cf0249a
705
Pod::Spec.new do |s| s.name = 'PDKTZipArchive' s.version = '0.4.1' s.summary = 'Utility class for zipping and unzipping files on iOS and Mac.' s.description = 'PDKTZipArchive is a simple utility class for zipping and unzipping files on iOS and Mac.' s.homepage = 'https://github.com/Produkt/PDKTZipArchive' s.license = { :type => 'MIT', :file => 'LICENSE.txt' } s.author = { 'Sam Soffes' => '[email protected]' } s.source = { :git => 'https://github.com/Produkt/PDKTZipArchive.git', :tag => "v#{s.version}" } s.ios.deployment_target = '8.0' s.source_files = 'PDKTZipArchive/*', 'PDKTZipArchive/minizip/*' s.library = 'z' s.requires_arc = true end
47
109
0.629787
5d63a45e83871c80bc10c25215a5d1d6dff54f94
1,061
lib = File.expand_path("../lib", __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require "jason_view_tool/version" Gem::Specification.new do |spec| spec.name = "jason_view_tool" spec.version = JasonViewTool::VERSION spec.authors = ["Jason Woo"] spec.email = ["[email protected]"] spec.summary = %q{Various view specific method for applications I use.} spec.description = %q{Provides generated HTML data for Rails applications.} spec.homepage = "https://github.com/jasonwwoo/jason_view_tool" spec.license = "MIT" spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) } end spec.bindir = "exe" spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) } spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.16" spec.add_development_dependency "rake", "~> 10.0" spec.add_development_dependency "rspec", "~> 3.0" end
37.892857
85
0.655985
f726be1396b3e5e122b7aa5081ccf5d5b2a3a438
41
module Multipart module Post end end
8.2
16
0.756098
619ba82c08af74eced9307de027d89e0247ac132
566
# frozen_string_literal: true # Filters a collection based on the internal members aggregator class DuplicateFileIterator include Enumerable def initialize(collection = [], duplicates: true) @collection = collection @duplicates = duplicates end def each(&block) grouped = @collection.group_by(&:aggregator) # How does this class know about the members internals...? coupling...? if @duplicates grouped.select { |k, v| v.length > 1 }.each(&block) else grouped.select { |k, v| v.length == 1 }.each(&block) end end end
25.727273
120
0.687279
7a6c42f76da3060994a2f6a59a84f268c89645ac
4,742
require File.dirname(__FILE__) + '/../spec_helper' include PreferenceFactory describe Preference, "by default" do before(:each) do @preference = Preference.new end it "should not have an attribute" do @preference.attribute.should be_blank end it "should not have an owner" do @preference.owner.should be_nil end it "should not have an owner type" do @preference.owner_type.should be_blank end it "should not have a group association" do @preference.group_id.should be_nil end it "should not have a group type" do @preference.group_type.should be_nil end it "should not have a value" do @preference.value.should be_blank end it "should not have a definition" do @preference.definition.should be_nil end end describe Preference, "as a Class" do it "should be able to split nil groups" do group_id, group_type = Preference.split_group(nil) group_id.should be_nil group_type.should be_nil end it "should be able to split non ActiveRecord groups" do group_id, group_type = Preference.split_group('car') group_id.should be_nil group_type.should == 'car' end it "should be able to split ActiveRecord groups" do user = mock_model(Product) group_id, group_type = Preference.split_group(user) group_id.should == user.id group_type.should == 'Product' end end # -- See Issue #86 =begin describe Preference, "after being created" do before(:each) do User.preference :notifications, :boolean @preference = new_preference end it "should have an owner" do @preference.owner.should_not be_nil end it "should have a definition" do @preference.definition.should_not be_nil end it "should have a value" do @preference.value.should_not be_nil end it "should not have a group association" do @preference.group.should be_nil end after(:each) do User.preference_definitions.delete('notifications') User.default_preferences.delete('notifications') end end =end describe Preference, "in general" do it "should be valid with valid attributes" do preference = new_preference preference.should be_valid end it "should require an attribute" do preference = new_preference(:attribute => nil) preference.should_not be_valid preference.errors_on(:attribute).length.should == 1 end it "should have an owner_id and owner_type" do preference = new_preference(:owner => nil) preference.should_not be_valid preference.errors_on(:owner_id).length.should == 1 preference.errors_on(:owner_type).length.should == 1 end it "should not require a group" do preference = new_preference(:group => nil) preference.should be_valid end it "should not require a group_id even when a group_type is specified" do preference = new_preference(:group => nil) preference.group_type = 'Product' preference.should be_valid end it "should require a group type when a group_id is specified" do preference = new_preference(:group => nil) preference.group_id = 1 preference.should_not be_valid preference.errors_on(:group_type).length.should == 1 end end describe Preference, "with basic group" do it "should have a group association" do preference = create_preference(:group_type => 'car') preference.group.should == 'car' end end describe Preference, "with ActiveRecord group" do it "should have a group association" do product = create_product preference = create_preference(:group => product) preference.group.should == product end end # -- See Issue #86 =begin describe Preference, "with boolean attribute" do before(:each) do User.preference :notifications, :boolean @preference = new_preference(:attribute => 'notifications', :value => nil) end it "should type_cast nil values" do @preference.value.should be_nil end it "should type_cast numeric values" do @preference.value = 0 @preference.value.should be_false @preference.value = 1 @preference.value.should be_true @preference.value = 3 @preference.value.should be_false end it "should type_cast boolean values" do @preference.value = false @preference.value.should be_false @preference.value = true @preference.value.should be_true end it "should type_cast string values" do @preference.value = "false" @preference.value.should be_false @preference.value = "true" @preference.value.should be_true @preference.value = "hello" @preference.value.should be_false end after(:each) do User.preference_definitions.delete('notifications') User.default_preferences.delete('notifications') end end =end
25.632432
78
0.717841
87bfd4f168d2e06c25d6c52c573e9470cc8262b4
1,470
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Consumption::Mgmt::V2019_05_01 module Models # # The details of the error. # class ErrorDetails include MsRestAzure # @return [String] Error code. attr_accessor :code # @return [String] Error message indicating why the operation failed. attr_accessor :message # # Mapper for ErrorDetails class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ErrorDetails', type: { name: 'Composite', class_name: 'ErrorDetails', model_properties: { code: { client_side_validation: true, required: false, read_only: true, serialized_name: 'code', type: { name: 'String' } }, message: { client_side_validation: true, required: false, read_only: true, serialized_name: 'message', type: { name: 'String' } } } } } end end end end
24.915254
75
0.504082
26bdc6b8c2c42adc0ff1fc3d2bb1c790cb275e97
2,078
# frozen_string_literal: true describe Api::V3::DecisionReview::ContestableIssueFinder, :all_dbs do include IntakeHelpers def lookup(ids = {}) Api::V3::DecisionReview::ContestableIssueFinder.new( { decision_review_class: decision_review_class, veteran: veteran, receipt_date: receipt_date, benefit_type: benefit_type }.merge(ids) ) end let(:decision_review_class) { HigherLevelReview } let!(:veteran) do Generators::Veteran.build( file_number: file_number, first_name: first_name, last_name: last_name ) end let(:file_number) { "55555555" } let(:first_name) { "Jane" } let(:last_name) { "Doe" } let(:receipt_date) { Time.zone.today - 6.days } let(:benefit_type) { "compensation" } let!(:rating) { generate_rating(veteran, promulgation_date, profile_date) } let(:promulgation_date) { receipt_date - 10.days } let(:profile_date) { (receipt_date - 8.days).to_datetime } let(:contestable_issues) do ContestableIssueGenerator.new( decision_review_class.new( veteran_file_number: veteran.file_number, receipt_date: receipt_date, benefit_type: benefit_type ) ).contestable_issues end describe "#found?" do it "find a veteran's rating issues" do rating.issues.each do |issue| expect(lookup(rating_issue_id: issue.reference_id).found?).to eq true end end end describe "#contestable_issue" do it "return the correct contestable issue" do ContestableIssueGenerator.new( decision_review_class.new( veteran_file_number: veteran.file_number, receipt_date: receipt_date, benefit_type: benefit_type ) ).contestable_issues.each do |ci| expect( lookup(rating_issue_id: ci.rating_issue_reference_id).contestable_issue.as_json ).to eq ci.as_json expect( lookup(rating_issue_id: " #{ci.rating_issue_reference_id}").contestable_issue.as_json ).to eq ci.as_json end end end end
28.861111
97
0.674206
d508a32eb0291e9c05f63d5e1bd5912a34cf4bbb
4,993
class Chef module Formatters # Handles basic indentation and colorization tasks class IndentableOutputStream attr_reader :out attr_reader :err attr_accessor :indent attr_reader :line_started attr_accessor :current_stream attr_reader :semaphore def initialize(out, err) @out, @err = out, err @indent = 0 @line_started = false @semaphore = Mutex.new end # pastel.decorate is a lightweight replacement for highline.color def pastel @pastel ||= begin require "pastel" Pastel.new end end # Print the start of a new line. This will terminate any existing lines and # cause indentation but will not move to the next line yet (future 'print' # and 'puts' statements will stay on this line). # # @param string [String] # @param args [Array<Hash,Symbol>] def start_line(string, *args) print(string, from_args(args, start_line: true)) end # Print a line. This will continue from the last start_line or print, # or start a new line and indent if necessary. # # @param string [String] # @param args [Array<Hash,Symbol>] def puts(string, *args) print(string, from_args(args, end_line: true)) end # Print an entire line from start to end. This will terminate any existing # lines and cause indentation. # # @param string [String] # @param args [Array<Hash,Symbol>] def puts_line(string, *args) print(string, from_args(args, start_line: true, end_line: true)) end # Print a raw chunk def <<(obj) print(obj) end # Print a string. # # == Arguments # string: string to print. # options: a hash with these possible options: # - :stream => OBJ: unique identifier for a stream. If two prints have # different streams, they will print on separate lines. # Otherwise, they will stay together. # - :start_line => BOOLEAN: if true, print will begin on a blank (indented) line. # - :end_line => BOOLEAN: if true, current line will be ended. # - :name => STRING: a name to prefix in front of a stream. It will be printed # once (with the first line of the stream) and subsequent lines # will be indented to match. # # == Alternative # # You may also call print('string', :red) (https://github.com/piotrmurach/pastel#3-supported-colors) def print(string, *args) options = from_args(args) # Make sure each line stays a unit even with threads sending output semaphore.synchronize do if should_start_line?(options) move_to_next_line end print_string(string, options) if should_end_line?(options) move_to_next_line end end end private def should_start_line?(options) options[:start_line] || @current_stream != options[:stream] end def should_end_line?(options) options[:end_line] && @line_started end def from_args(colors, merge_options = {}) if colors.size == 1 && colors[0].is_a?(Hash) merge_options.merge(colors[0]) else merge_options.merge({ colors: colors }) end end def print_string(string, options) if string.empty? if options[:end_line] print_line("", options) end else string.lines.each do |line| print_line(line, options) end end end def print_line(line, options) indent_line(options) # Note that the next line will need to be started if line[-1..-1] == "\n" @line_started = false end if Chef::Config[:color] && options[:colors] @out.print pastel.decorate(line, *options[:colors]) else @out.print line end end def move_to_next_line if @line_started @out.puts "" @line_started = false end end def indent_line(options) unless @line_started # Print indents. If there is a stream name, either print it (if we're # switching streams) or print enough blanks to match # the indents. if options[:name] if @current_stream != options[:stream] @out.print "#{(" " * indent)}[#{options[:name]}] " else @out.print " " * (indent + 3 + options[:name].size) end else # Otherwise, just print indents. @out.print " " * indent end if @current_stream != options[:stream] @current_stream = options[:stream] end @line_started = true end end end end end
28.695402
106
0.569798
26f29358871309db3a785a4151eadbf1e9f1c910
3,120
describe RuboCop::Cop::Migration::UnsafeMigration do subject(:cop) { described_class.new } before do inspect_source(cop, source) end shared_examples "valid code" do it "doesn't register an offense" do expect(cop.offenses).to be_empty end end context "a non-migration class" do let(:source) do <<-SOURCE class MyModel < ActiveRecord::Base end SOURCE end it_behaves_like "valid code" end context "a valid migration class" do let(:source) do <<-SOURCE class AddSomeColumnToUsers < ActiveRecord::Migration[5.0] def change add_column :users, :some_id, :integer add_index :users, :some_id, algorithm: :concurrently add_reference :users, :something, index: false end end SOURCE end it_behaves_like "valid code" end context "a method that by default triggers a `safety_assured` warning in StrongMigrations" do [ "add_column :users, :abc, :json", "add_index :users, [:a, :b, :c, :d], algorithm: :concurrently", "change_table :users", "execute 'something'", "remove_column :users, :abc", ].each do |statement| context "#{statement}" do let(:source) do <<-SOURCE class AddSomeColumnToUsers < ActiveRecord::Migration def change #{statement} end end SOURCE end it_behaves_like "valid code" end end end context "add_index non-concurrently" do let(:source) do <<-SOURCE class AddSomeColumnToUsers < ActiveRecord::Migration def change add_column :users, :some_id, :integer add_index :users, :some_id end end SOURCE end it "registers an offense" do expect(cop.offenses.size).to eq(1) expect(cop.offenses.first.message).to match(/\AAdding a non-concurrent index/) expect(cop.highlights).to eq(["add_index :users, :some_id"]) end end context "add_reference with an index non-concurrently" do let(:source) do <<-SOURCE class AddSomeColumnToUsers < ActiveRecord::Migration def change add_reference :users, :something, index: true end end SOURCE end it "registers an offense" do expect(cop.offenses.size).to eq(1) expect(cop.offenses.first.message).to match(/\AAdding a non-concurrent index/) expect(cop.highlights).to eq(["add_reference :users, :something, index: true"]) end end context "add_column with default value" do let(:source) do <<-SOURCE class AddSomeColumnToUsers < ActiveRecord::Migration def change add_column :users, :schmuck, :boolean, default: false end end SOURCE end it "registers an offense" do expect(cop.offenses.size).to eq(1) expect(cop.offenses.first.message).to match(/\AAdding a column with a non-null default/) expect(cop.highlights).to eq(["add_column :users, :schmuck, :boolean, default: false"]) end end end
26
95
0.621474
e24ce551b91fbcb1733acd43ebf4c6f27a91a4f4
1,517
Pod::Spec.new do |s| s.name = "STPopup" s.version = "1.7.1" s.summary = "STPopup provides STPopupController, which works just like UINavigationController in form sheet/bottom sheet style, for both iPhone and iPad." s.description = <<-DESC - Extend your view controller from UIViewController, build it in your familiar way. - Push/Pop view controller in to/out of popup view stack, and set navigation items by using self.navigationItem.leftBarButtonItem and rightBarButtonItem, just like you are using UINavigationController. - Support both "Form Sheet" and "Bottom Sheet" style. - Work well with storyboard(including segue). - Customize UI by using UIAppearance. - Auto-reposition of popup view when keyboard is showing up, make sure your UITextField/UITextView won't be covered by the keyboard. - Drag navigation bar to dismiss popup view. - Support both portrait and landscape orientation, and both iPhone and iPad. DESC s.homepage = "https://github.com/kevin0571/STPopup" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "Kevin Lin" => "[email protected]" } s.platform = :ios, "7.0" s.source = { :git => "https://github.com/kevin0571/STPopup.git", :tag => s.version } s.source_files = "STPopup/*.{h,m}" s.public_header_files = "STPopup/*.h" end
56.185185
221
0.625577
612df2dfe48b05448237185c2e22f1953fe8210a
1,406
require 'spec_helper' describe FacetParser do context "with a select facet definition" do let(:facet_definition) { { 'type' => "text", 'filterable' => true, 'display_as_result_metadata' => true, 'name' => "Case type", 'key' => "case_type", 'preposition' => "of type", 'allowed_values' => [ { 'label' => "Airport price control reviews", 'value' => "airport-price-control-reviews" }, { 'label' => "Market investigations", 'value' => "market-investigations" }, { 'label' => "Remittals", 'value' => "remittals" } ], } } subject { FacetParser.parse(facet_definition) } specify { expect(subject).to be_a OptionSelectFacet } specify { expect(subject.name).to eql("Case type") } specify { expect(subject.key).to eql("case_type") } specify { expect(subject.preposition).to eql("of type") } it "should build a list of allowed values" do expect(subject.allowed_values[0]['label']).to eql("Airport price control reviews") expect(subject.allowed_values[0]['value']).to eql("airport-price-control-reviews") expect(subject.allowed_values[2]['label']).to eql("Remittals") expect(subject.allowed_values[2]['value']).to eql("remittals") end end end
31.954545
88
0.571835
117ac0601678d7879cecf1c097ce59c2182287f0
170
# frozen_string_literal: true require "mini_magick" Riiif::Image.file_resolver = RiiifResolver.new Riiif::Image.file_resolver.base_path = Figgy.config["derivative_path"]
34
70
0.823529
62097b7d7b3f3af175204ef21ad2be0d0a6ed394
1,191
SlackRubyBotServer::Events.configure do |config| config.on :command, '/evening_standup' do |command| include Keeper_pre_standup include Evening_Standup_Commands include Both_Standup_Commands team_id = command[:team_id] user_id = command[:user_id] standup = Standup_Check.find_by(user_id: user_id, date_of_stand: Date.today, team: team_id) json_blocks = get_json_evening if !standup.nil? && standup.evening_stand if command[:text] == '-e' json_blocks.unshift(edit_options_alternative_options) else json_blocks.unshift(edit_options) end standup_containing_initial = [ standup.evening_first, standup.evening_second, standup.evening_third, standup.evening_fourth, standup.PRs_and_estimation ] 0.upto(4) do |numbers| json_blocks[numbers * 3 + 2][:element] = json_blocks[numbers * 3 + 2][:element].merge( { "initial_value": standup_containing_initial[numbers] } ) end end { "blocks": json_blocks } end end
29.775
66
0.606213
214bfd046f95d7816827428c5f3dca9ac042ee68
4,850
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false # Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"] # or in config/master.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :local # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store config.cache_store = :redis_cache_store, { url: ENV['REDIS_URL'] } # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "coaches_directory_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Inserts middleware to perform automatic connection switching. # The `database_selector` hash is used to pass options to the DatabaseSelector # middleware. The `delay` is used to determine how long to wait after a write # to send a subsequent read to the primary. # # The `database_resolver` class is used by the middleware to determine which # database is appropriate to use based on the time delay. # # The `database_resolver_context` class is used by the middleware to set # timestamps for the last write to the primary. The resolver uses the context # class timestamps to determine how long to wait before reading from the # replica. # # By default Rails will store a last write timestamp in the session. The # DatabaseSelector middleware is designed as such you can define your own # strategy for connection switching and pass that into the middleware through # these configuration options. # config.active_record.database_selector = { delay: 2.seconds } # config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver # config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session end
45.327103
114
0.761856
03099f456abed6b4abf2eecdfd72272a51c797ba
738
# # To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html # Pod::Spec.new do |s| s.name = 'flutter_tts' s.version = '0.0.1' s.summary = 'A flutter text to speech plugin.' s.description = <<-DESC A flutter text to speech plugin DESC s.homepage = 'https://github.com/dlutton/flutter_tts' s.license = { :file => '../LICENSE' } s.author = { 'tundralabs' => '[email protected]' } s.source = { :path => '.' } s.source_files = 'Classes/**/*' s.public_header_files = 'Classes/**/*.h' s.dependency 'Flutter' s.ios.deployment_target = '8.0' s.swift_version = '4.2' s.static_framework = true end
32.086957
83
0.567751
bb7542dadf9e27c7616d8542e4ae4d025cb705d0
387
class CreateItems < ActiveRecord::Migration[5.0] def change create_table :items do |t| t.string :title t.string :code t.string :item_type t.string :state t.string :reference t.string :domain t.string :description t.string :mac t.string :serie t.integer :quantity t.float :value t.timestamps end end end
20.368421
48
0.607235
bb734ba9334ec16f88575bda058e29345179ad71
2,890
# 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: 20170515045838) do create_table "assignments", force: :cascade do |t| t.string "title" t.text "statement" t.integer "course_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["course_id"], name: "index_assignments_on_course_id" end create_table "courses", force: :cascade do |t| t.string "title" t.string "code" t.integer "person_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.integer "quota" t.index ["person_id"], name: "index_courses_on_person_id" end create_table "enrollments", force: :cascade do |t| t.integer "person_id" t.integer "course_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["course_id"], name: "index_enrollments_on_course_id" t.index ["person_id"], name: "index_enrollments_on_person_id" end create_table "grades", force: :cascade do |t| t.float "value" t.integer "person_id" t.integer "assignment_id" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.index ["assignment_id"], name: "index_grades_on_assignment_id" t.index ["person_id"], name: "index_grades_on_person_id" end create_table "people", force: :cascade do |t| t.string "first_name" t.string "last_name" t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.boolean "is_professor" t.string "encrypted_password", default: "", null: false t.string "reset_password_token" t.datetime "reset_password_sent_at" t.datetime "remember_created_at" t.integer "sign_in_count", default: 0, null: false t.datetime "current_sign_in_at" t.datetime "last_sign_in_at" t.string "current_sign_in_ip" t.string "last_sign_in_ip" t.index ["email"], name: "index_people_on_email", unique: true t.index ["reset_password_token"], name: "index_people_on_reset_password_token", unique: true end end
39.054054
96
0.695848
39e99c66a9cb9fc6245f5c8f0b4a091587a5eabc
500
require './test/app_helper' require './test/vcr_helper' class AppRoutesProblemsTest < Minitest::Test include Rack::Test::Methods def app Xapi::App end def test_full_problems_list get '/problems' options = { format: :json, name: 'get_full_problems_list' } Approvals.verify(last_response.body, options) end def test_single_problem get '/problems/one' options = { format: :json, name: 'get_all_leaps' } Approvals.verify(last_response.body, options) end end
21.73913
63
0.71
618496bd63ae402bd8f164badd75791e0c7cf769
303
class SearchableField attr_accessor :name, :field_type, :association_name, :associated_klass def initialize(name, field_type, association_name, associated_klass) @name = name @field_type = field_type @association_name = association_name @associated_klass = associated_klass end end
30.3
71
0.778878
38d640ee19ed9f5a4a498381d9e2285f1977e95a
779
AssetSync.configure do |config| config.fog_provider = 'AWS' config.aws_access_key_id = ENV['AWS_ACCESS_KEY_ID'] config.aws_secret_access_key = ENV['AWS_SECRET_ACCESS_KEY'] config.fog_directory = ENV['FOG_DIRECTORY'] # Increase upload performance by configuring your region # config.fog_region = 'eu-west-1' # # Don't delete files from the store config.existing_remote_files = "keep" # # Automatically replace files with their equivalent gzip compressed version config.gzip_compression = true # # Use the Rails generated 'manifest.yml' file to produce the list of files to # upload instead of searching the assets directory. config.manifest = true # # Fail silently. Useful for environments such as Heroku config.fail_silently = true end
35.409091
80
0.75353
033be7d15f8cc09a6cae7cf0931a440dbd5fbd4a
2,506
describe Travis::API::V3::Services::Installation::Find, set_app: true do let(:user) { Travis::API::V3::Models::User.find_by_login('svenfuchs') } let!(:installation) { Travis::API::V3::Models::Installation.create(owner_type: 'User', owner_id: user.id, github_id: 789) } let(:token) { Travis::Api::App::AccessToken.create(user: user, app_id: 1) } let(:headers) {{ 'HTTP_AUTHORIZATION' => "token #{token}" }} before { user.save! } describe "authenticated as user with access" do before { get("/v3/installation/#{installation.github_id}", {}, headers) } example { expect(last_response).to be_ok } example { expect(JSON.load(body)).to be == { "@type" => "installation", "@href" => "/v3/installation/#{installation.github_id}", "@representation" => "standard", "id" => installation.id, "github_id" => installation.github_id, "owner" => { "@type"=>"user", "@href"=>"/v3/user/#{user.id}", "@representation"=>"minimal", "id"=>user.id, "login"=>user.login, "vcs_type" => user.vcs_type } }} end describe "authenticated as user with access, including installation.owner" do before { get("/v3/installation/#{installation.github_id}?include=installation.owner", {}, headers) } example { expect(last_response).to be_ok } example { expect(JSON.load(body)).to be == { "@type" => "installation", "@href" => "/v3/installation/#{installation.github_id}", "@representation" => "standard", "id" => installation.id, "github_id" => installation.github_id, "owner" => { "@type" => "user", "@href" => "/v3/user/#{user.id}", "@representation" => "standard", "@permissions" => { "read" => true, "sync" => true }, "id" => 1, "login" => user.login, "name" => user.name, "email" => "[email protected]", "github_id" => nil, "vcs_id" => user.vcs_id, "vcs_type" => user.vcs_type, "avatar_url" => "https://0.gravatar.com/avatar/07fb84848e68b96b69022d333ca8a3e2", "is_syncing" => nil, "synced_at" => nil, "education" => nil, "allow_migration" => false, "recently_signed_up" => false, "secure_user_hash" => nil, } }} end end
38.553846
125
0.53352
1d9b1a4463becd96891cec68ea56f3fbfc2744ad
21,277
describe ManageIQ::Providers::Redhat::InfraManager do it ".ems_type" do expect(described_class.ems_type).to eq('rhevm') end it ".description" do expect(described_class.description).to eq('Red Hat Virtualization') end describe ".metrics_collector_queue_name" do it "returns the correct queue name" do worker_queue = ManageIQ::Providers::Redhat::InfraManager::MetricsCollectorWorker.default_queue_name expect(described_class.metrics_collector_queue_name).to eq(worker_queue) end end describe "rhevm_metrics_connect_options" do let(:ems) { FactoryBot.create(:ems_redhat, :hostname => "some.thing.tld") } it "rhevm_metrics_connect_options fetches configuration and allows overrides" do expect(ems.rhevm_metrics_connect_options[:host]).to eq("some.thing.tld") expect(ems.rhevm_metrics_connect_options(:hostname => "different.tld")[:host]) .to eq("different.tld") end it "rhevm_metrics_connect_options fetches the default database name" do expect(ems.rhevm_metrics_connect_options[:database]) .to eq(ems.class.default_history_database_name) end context "non default metrics database name" do let(:ems) do FactoryBot.create(:ems_redhat, :hostname => "some.thing.tld", :connection_configurations => [{:endpoint => {:role => :metrics, :path => "some.database"}}]) end it "fetches the set database name" do expect(ems.rhevm_metrics_connect_options[:database]).to eq("some.database") end end end context "#vm_reconfigure" do context "version 4" do context "#vm_reconfigure" do before do _guid, _server, zone = EvmSpecHelper.create_guid_miq_server_zone @ems = FactoryBot.create(:ems_redhat_with_authentication, :zone => zone) @vm = FactoryBot.create(:vm_redhat, :ext_management_system => @ems) @rhevm_vm_attrs = double('rhevm_vm_attrs') allow(@ems).to receive(:highest_supported_api_version).and_return(4) stub_settings_merge(:ems => { :ems_redhat => { :use_ovirt_engine_sdk => use_ovirt_engine_sdk } }) @v4_strategy_instance = instance_double(ManageIQ::Providers::Redhat::InfraManager::OvirtServices::Strategies::V4) allow(ManageIQ::Providers::Redhat::InfraManager::OvirtServices::Strategies::V4) .to receive(:new) .and_return(@v4_strategy_instance) end context "use_ovirt_engine_sdk is set to true" do let(:use_ovirt_engine_sdk) { true } it 'sends vm_reconfigure to the right ovirt_services' do expect(@v4_strategy_instance).to receive(:vm_reconfigure).with(@vm, {}) @ems.vm_reconfigure(@vm) end end context "use_ovirt_engine_sdk is set to false" do let(:use_ovirt_engine_sdk) { false } it 'sends vm_reconfigure to the right ovirt_services' do expect(@v4_strategy_instance).to receive(:vm_reconfigure).with(@vm, {}) @ems.vm_reconfigure(@vm) end end end end context "version 3" do before do _guid, _server, zone = EvmSpecHelper.create_guid_miq_server_zone @ems = FactoryBot.create(:ems_redhat_with_authentication, :zone => zone) @hw = FactoryBot.create(:hardware, :memory_mb => 1024, :cpu_sockets => 2, :cpu_cores_per_socket => 1) @vm = FactoryBot.create(:vm_redhat, :ext_management_system => @ems) @cores_per_socket = 2 @num_of_sockets = 3 @rhevm_vm_attrs = double('rhevm_vm_attrs') stub_settings_merge(:ems => { :ems_redhat => { :use_ovirt_engine_sdk => false } }) allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:name).and_return('myvm') allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:memory).and_return(4.gigabytes) allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:memory_policy, :guaranteed).and_return(2.gigabytes) # TODO: Add tests for when the highest_supported_api_version is 4 allow(@ems).to receive(:supported_api_versions).and_return(%w(3)) @rhevm_vm = double('rhevm_vm') allow(@rhevm_vm).to receive(:attributes).and_return(@rhevm_vm_attrs) allow(@vm).to receive(:with_provider_object).and_yield(@rhevm_vm) end it "cpu_topology=" do spec = { "numCPUs" => @cores_per_socket * @num_of_sockets, "numCoresPerSocket" => @cores_per_socket } expect(@rhevm_vm).to receive(:cpu_topology=).with(:cores => @cores_per_socket, :sockets => @num_of_sockets) @ems.vm_reconfigure(@vm, :spec => spec) end it 'updates the current and persistent configuration if the VM is up' do spec = { 'memoryMB' => 8.gigabytes / 1.megabyte } allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:status, :state).and_return('up') expect(@rhevm_vm).to receive(:update_memory).with(8.gigabytes, 2.gigabytes, :next_run => true) expect(@rhevm_vm).to receive(:update_memory).with(8.gigabytes, nil) @ems.vm_reconfigure(@vm, :spec => spec) end it 'updates only the persistent configuration when the VM is down' do spec = { 'memoryMB' => 8.gigabytes / 1.megabyte } allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:status, :state).and_return('down') expect(@rhevm_vm).to receive(:update_memory).with(8.gigabytes, 2.gigabytes) @ems.vm_reconfigure(@vm, :spec => spec) end it 'adjusts the increased memory to the next 256 MiB multiple if the VM is up' do spec = { 'memoryMB' => 8.gigabytes / 1.megabyte + 1 } adjusted = 8.gigabytes + 256.megabytes allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:status, :state).and_return('up') expect(@rhevm_vm).to receive(:update_memory).with(adjusted, 2.gigabytes, :next_run => true) expect(@rhevm_vm).to receive(:update_memory).with(adjusted, nil) @ems.vm_reconfigure(@vm, :spec => spec) end it 'adjusts reduced memory to the next 256 MiB multiple if the VM is up' do spec = { 'memoryMB' => 8.gigabytes / 1.megabyte - 1 } adjusted = 8.gigabytes allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:status, :state).and_return('up') expect(@rhevm_vm).to receive(:update_memory).with(adjusted, 2.gigabytes, :next_run => true) expect(@rhevm_vm).to receive(:update_memory).with(adjusted, nil) @ems.vm_reconfigure(@vm, :spec => spec) end it 'adjusts the guaranteed memory if it is larger than the virtual memory if the VM is up' do spec = { 'memoryMB' => 1.gigabyte / 1.megabyte } adjusted = 1.gigabyte allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:status, :state).and_return('up') expect(@rhevm_vm).to receive(:update_memory).with(1.gigabyte, adjusted, :next_run => true) expect(@rhevm_vm).to receive(:update_memory).with(1.gigabyte, nil) @ems.vm_reconfigure(@vm, :spec => spec) end it 'adjusts the guaranteed memory if it is larger than the virtual memory if the VM is down' do spec = { 'memoryMB' => 1.gigabyte / 1.megabyte } adjusted = 1.gigabyte allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:status, :state).and_return('down') expect(@rhevm_vm).to receive(:update_memory).with(1.gigabyte, adjusted) @ems.vm_reconfigure(@vm, :spec => spec) end it 'cpu_topology from set_number_of_cpus with number of sockets >= 1' do allow(@vm).to receive(:cpu_cores_per_socket).and_return(2) options = { :user_event => "Console Request Action [vm_set_number_of_cpus], VM [#{@vm.name}]", :value => 2 } expect(@rhevm_vm).to receive(:cpu_topology=).with(:sockets => 1) @ems.vm_set_num_cpus(@vm, options) end it 'cpu_topology from set_number_of_cpus with number of sockets < 1' do allow(@vm).to receive(:cpu_cores_per_socket).and_return(2) options = { :user_event => "Console Request Action [vm_set_number_of_cpus], VM [#{@vm.name}]", :value => 1 } expect(@rhevm_vm).to receive(:cpu_topology=).with(:cores => 1, :sockets => 1) @ems.vm_set_num_cpus(@vm, options) end it 'adjusts memory from set_memory' do options = { :user_event => "Console Request Action [vm_set_memory], VM [#{@vm.name}]", :value => 2048 } allow(@rhevm_vm_attrs).to receive(:fetch_path).with(:status, :state).and_return('down') expect(@rhevm_vm).to receive(:update_memory).with(2.gigabytes, 2.gigabytes) @ems.vm_set_memory(@vm, options) end end end context ".make_ems_ref" do it "removes the /ovirt-engine prefix" do expect(described_class.make_ems_ref("/ovirt-engine/api/vms/123")).to eq("/api/vms/123") end it "does not remove the /api prefix" do expect(described_class.make_ems_ref("/api/vms/123")).to eq("/api/vms/123") end end context ".extract_ems_ref_id" do it "extracts the resource ID from the href" do expect(described_class.extract_ems_ref_id("/ovirt-engine/api/vms/123")).to eq("123") end end context "api versions" do require 'ovirtsdk4' let(:ems) { FactoryBot.create(:ems_redhat_with_authentication) } context 'when parsing database api_version' do let(:ems) { FactoryBot.create(:ems_redhat, :api_version => api_version) } subject(:supported_api_versions) { ems.supported_api_versions } context "version 4.2" do let(:api_version) { "4.2.0" } it 'returns versions 3 and 4' do expect(supported_api_versions).to match_array(%w(3 4)) end end context "version 3.6.1" do let(:api_version) { "3.6.1" } it 'returns versions 3' do expect(supported_api_versions).to match_array(%w(3)) end end context "version 4.2.0-0.0.master.20170917124606.gita804ef7.el7.centos" do let(:api_version) { "4.2.0-0.0.master.20170917124606.gita804ef7.el7.centos" } it 'returns versions 3 and 4' do expect(supported_api_versions).to match_array(%w(3 4)) end end context "version 4.2.1.3" do let(:api_version) { "4.2.1.3" } it 'returns versions 3 and 4' do expect(supported_api_versions).to match_array(%w(3 4)) end end context "version 4.2.1a" do let(:api_version) { "4.2.1a" } it 'returns versions 3 and 4' do expect(supported_api_versions).to match_array(%w(3 4)) end end context "version 4.3" do let(:api_version) { "4.3" } it 'returns versions 3 and 4' do expect(supported_api_versions).to match_array(%w(3 4)) end end context "version 5.5" do let(:api_version) { "5.5" } it 'returns empty array' do expect(supported_api_versions).to match_array([]) end end end context 'when probing provider directly' do subject(:supported_api_versions) { ems.supported_api_versions } context "#supported_api_versions" do it 'calls the OvirtSDK4::Probe.probe' do expect(OvirtSDK4::Probe).to receive(:probe).and_return([]) supported_api_versions end it 'properly parses ProbeResults' do allow(OvirtSDK4::Probe).to receive(:probe) .and_return([OvirtSDK4::ProbeResult.new(:version => '3'), OvirtSDK4::ProbeResult.new(:version => '4')]) expect(supported_api_versions).to match_array(%w(3 4)) end end end describe "#supports_the_api_version?" do it "returns the supported api versions" do allow(ems).to receive(:supported_api_versions).and_return([3]) expect(ems.supports_the_api_version?(3)).to eq(true) expect(ems.supports_the_api_version?(6)).to eq(false) end end end context "supported features" do let(:ems) { FactoryBot.create(:ems_redhat) } let(:supported_api_versions) { [3, 4] } context "#process_api_features_support" do before(:each) do allow(SupportsFeatureMixin).to receive(:guard_queryable_feature).and_return(true) allow(described_class).to receive(:api_features) .and_return('3' => %w(feature1 feature3), '4' => %w(feature2 feature3)) described_class.process_api_features_support allow(ems).to receive(:supported_api_versions).and_return(supported_api_versions) end context "no versions supported" do let(:supported_api_versions) { [] } it 'supports the right features' do expect(ems.supports_feature1?).to be_falsey expect(ems.supports_feature2?).to be_falsey expect(ems.supports_feature3?).to be_falsey end end context "version 3 supported" do let(:supported_api_versions) { [3] } it 'supports the right features' do expect(ems.supports_feature1?).to be_truthy expect(ems.supports_feature2?).to be_falsey expect(ems.supports_feature3?).to be_truthy end end context "version 4 supported" do let(:supported_api_versions) { [4] } it 'supports the right features' do expect(ems.supports_feature1?).to be_falsey expect(ems.supports_feature2?).to be_truthy expect(ems.supports_feature3?).to be_truthy end end context "all versions supported" do let(:supported_api_versions) { [3, 4] } it 'supports the right features' do expect(ems.supports_feature1?).to be_truthy expect(ems.supports_feature2?).to be_truthy expect(ems.supports_feature3?).to be_truthy end end end end context "#version_at_least?" do let(:api_version) { "4.2" } let(:ems) { FactoryBot.create(:ems_redhat, :api_version => api_version) } context "api version is higher or equal than checked version" do it 'supports the right features' do expect(ems.version_at_least?("4.1")).to be_truthy ems.api_version = "4.1.3.2-0.1.el7" expect(ems.version_at_least?("4.1")).to be_truthy ems.api_version = "4.2.0_master" expect(ems.version_at_least?("4.1")).to be_truthy ems.api_version = "4.2.1_master" expect(ems.version_at_least?("4.2.0")).to be_truthy end end context "api version is lowergit than checked version" do let(:api_version) { "4.0" } it 'supports the right features' do expect(ems.version_at_least?("4.1")).to be_falsey ems.api_version = "4.0.3.2-0.1.el7" expect(ems.version_at_least?("4.1")).to be_falsey ems.api_version = "4.0.0_master" expect(ems.version_at_least?("4.1")).to be_falsey ems.api_version = "4.0.1_master" expect(ems.version_at_least?("4.0.2")).to be_falsey end end context "api version not set" do let(:api_version) { nil } it 'always return false' do expect(ems.version_at_least?("10.1")).to be_falsey expect(ems.version_at_least?("0")).to be_falsey end end end context ".raw_connect" do let(:options) do { :username => 'user', :password => 'pword' } end let(:v4_connection) { double(OvirtSDK4::Connection) } let(:v3_connection) { double(Ovirt::Service) } before do allow(v3_connection).to receive(:disconnect) end it "works with version 4" do expect(described_class).to receive(:raw_connect_v4).and_return(v4_connection) expect(v4_connection).to receive(:test).with(hash_including(:raise_exception => true)) .and_return(true) described_class.raw_connect(options) end it "works with version 3" do expect(described_class).to receive(:raw_connect_v4).and_return(v4_connection) expect(v4_connection).to receive(:test).with(hash_including(:raise_exception => true)) .and_raise(OvirtSDK4::Error.new('Something failed')) expect(described_class).to receive(:raw_connect_v3).and_return(v3_connection) expect(v3_connection).to receive(:api).and_return(nil) described_class.raw_connect(options) end it "always closes the V3 connection" do expect(described_class).to receive(:raw_connect_v4).and_return(v4_connection) expect(v4_connection).to receive(:test).with(hash_including(:raise_exception => true)) .and_raise(OvirtSDK4::Error.new('Something failed')) expect(described_class).to receive(:raw_connect_v3).and_return(v3_connection) expect(v3_connection).to receive(:api).and_return(nil) expect(v3_connection).to receive(:disconnect) described_class.raw_connect(options) end it "decrypts the password" do allow(described_class).to receive(:raw_connect_v4).and_return(v4_connection) expect(v4_connection).to receive(:test).with(hash_including(:raise_exception => true)) .and_return(true) expect(MiqPassword).to receive(:try_decrypt).with(options[:password]) described_class.raw_connect(options) end end context "network manager validations" do let(:api_version) { "4.2" } before do @ems = FactoryBot.create(:ems_redhat, :api_version => api_version) @provider = double(:authentication_url => 'https://hostname.usersys.redhat.com:35357/v2.0') @providers = double("providers", :sort_by => [@provider], :first => @provider) allow(@ems).to receive(:ovirt_services).and_return(double(:collect_external_network_providers => @providers)) @ems.ensure_managers end it "does not create orphaned network_manager" do expect(ExtManagementSystem.count).to eq(2) same_ems = ExtManagementSystem.find(@ems.id) allow(same_ems).to receive(:ovirt_services).and_return(double(:collect_external_network_providers => @providers)) @ems.destroy expect(ExtManagementSystem.count).to eq(0) same_ems.hostname = "dummy-mandatory" same_ems.ensure_managers expect(ExtManagementSystem.count).to eq(0) end context "network manager url is valid" do it "returns the correct hostname" do expect(@ems.network_manager.hostname).to eq "hostname.usersys.redhat.com" end it "returns the correct port" do expect(@ems.network_manager.port).to eq(35357) end it "returns the correct version" do expect(@ems.network_manager.api_version).to eq("v2") end it "returns the correct security protocol" do expect(@ems.network_manager.security_protocol).to eq("ssl") end end it "removes network manager" do zone = FactoryBot.create(:zone) allow(MiqServer).to receive(:my_zone).and_return(zone.name) allow(@ems).to receive(:ovirt_services).and_return(double(:collect_external_network_providers => {})) expect(ExtManagementSystem.count).to eq(2) @ems.ensure_managers deliver_queue_messages expect(ExtManagementSystem.count).to eq(1) end def deliver_queue_messages MiqQueue.order(:id).each do |queue_message| status, message, result = queue_message.deliver queue_message.delivered(status, message, result) end end end context 'catalog types' do let(:ems) { FactoryBot.create(:ems_redhat) } it "#supported_catalog_types" do expect(ems.supported_catalog_types).to eq(%w(redhat)) end end context 'vm_migration' do before do @ems = FactoryBot.create(:ems_redhat) @vm = FactoryBot.create(:vm_redhat, :ext_management_system => @ems) service = double allow(service).to receive(:migrate).with(:host => {:id => "11089411-53a2-4337-8613-7c1d411e8ae8"}) allow(@ems).to receive(:with_version4_vm_service).and_return(service) end it "succeeds migration" do ems_event = FactoryBot.create(:ems_event, :event_type => "VM_MIGRATION_DONE", :message => "migration done", :ext_management_system => @ems, :vm => @vm, :timestamp => Time.zone.now + 1) @vm.ems_events << ems_event expect { @ems.vm_migrate(@vm, {:host => "/ovirt-engine/api/hosts/11089411-53a2-4337-8613-7c1d411e8ae8"}, 1) }.to_not raise_error end it "fails migration" do ems_event = FactoryBot.create(:ems_event, :event_type => "VM_MIGRATION_FAILED_FROM_TO", :message => "migration failed", :ext_management_system => @ems, :vm => @vm, :timestamp => Time.zone.now + 1) @vm.ems_events << ems_event expect { @ems.vm_migrate(@vm, {:host => "/ovirt-engine/api/hosts/11089411-53a2-4337-8613-7c1d411e8ae8"}, 1) }.to raise_error(ManageIQ::Providers::Redhat::InfraManager::OvirtServices::Error) end it "never receives an event" do expect { @ems.vm_migrate(@vm, {:host => "/ovirt-engine/api/hosts/11089411-53a2-4337-8613-7c1d411e8ae8"}, 1, 2) }.to raise_error(ManageIQ::Providers::Redhat::InfraManager::OvirtServices::Error) end end end
39.474954
202
0.653147
7a8228678b50eb2f1a1638dc0027ceef892aa62a
42
module FakeDynamo VERSION = "0.0.1" end
10.5
19
0.690476
bfd767a94519c8663cd84fc46d49103807941965
3,238
# frozen_string_literal: true # code by MSP-Greg # file is included all scripts in the repo require 'json' require 'net/http' module JsonPrIssueBase fn_cred = ARGV[0] if File.exist? fn_cred cred = JSON.parse(File.read fn_cred, mode: 'rb:UTF-8') else puts "Filename passed as ARGV doesn't exist!" exit end OWNER = cred['owner'] REPO = cred['repo'] HISTORY = cred['history'] TKN = cred['token'] LABELS = cred['labels'] ROWS = 100 # gql_request query, limit of 100 if !File.exist? HISTORY puts 'History filename in json file doesn\'t exist!' exit elsif TKN.length != 40 puts 'token must be 40 characters!' exit elsif !(OWNER.is_a?(::String) && REPO.is_a?(::String) && !OWNER.empty? && !REPO.empty?) puts 'owner and repo must be non-empty strings!' exit end # creates a hash of the issue or pr data def create_obj(item, type) { 'opened' => item[:createdAt], 'closed' => item[:closedAt], 'state' => item[:state], 'type' => type, # remove [ci skip] type strings 'title' => item[:title].gsub(/\s*\[[a-z ]+\]\s*/, ''), 'author' => item.dig(:author, :name), 'user_name' => "@#{item.dig :author, :login}" } end # get the GraphQL data from GitHub given the query def gql_request(query, filename: nil) body = {} body['query'] = query data = nil Net::HTTP.start('api.github.com', 443, use_ssl: true) do |http| http.verify_mode = OpenSSL::SSL::VERIFY_PEER data = run_request http, query if data if filename File.write "#{__dir__}/#{filename}", resp.body, mode: 'wb:UTF-8' end else return nil end end data end # open a connection and pass to block def http_connection Net::HTTP.start('api.github.com', 443, use_ssl: true) do |http| http.verify_mode = OpenSSL::SSL::VERIFY_PEER yield http end end def run_request(http, query) body = {} body['query'] = query req = Net::HTTP::Post.new '/graphql' req['Authorization'] = "Bearer #{TKN}" req['Accept'] = 'application/json' req['Content-Type'] = 'application/json' req.body = JSON.generate body resp = http.request req if Net::HTTPSuccess === resp JSON.parse resp.body, symbolize_names: true else nil end end # prints debug info if the GitHub API finds and error def print_error(data, gql) puts 'Error retrieving GraphQL data' puts gql pp data exit end # returns the gql_request query string for issues or PR's def gql_query_str(obj, filter) <<~GRAPHQL query { repository(owner: "#{OWNER}", name: "#{REPO}") { #{obj}(#{filter}) { edges { node { number createdAt closedAt state title author { ... on User { login name } } } } pageInfo { endCursor hasNextPage } } } } GRAPHQL end end
23.985185
89
0.546016
4a4fb9477992e8624f8405ad518b567cf1d86f74
441
rspec_module = defined?(RSpec::Core) ? 'RSpec' : 'Spec' # for RSpec 1 compatability Kernel.const_get(rspec_module)::Matchers.define :be_able_to do |*args| match do |ability| ability.can?(*args) end failure_message_for_should do |ability| "expected to be able to #{args.map(&:inspect).join(" ")}" end failure_message_for_should_not do |ability| "expected not to be able to #{args.map(&:inspect).join(" ")}" end end
29.4
84
0.69161
38304a87449afde51a52471d2905ebc624d9c450
95
# frozen_string_literal: true module BlackHole def self.method_missing(*) self end end
13.571429
29
0.747368
384c9a1f7fb86dccdcfb20bcd950b3ab549da8e9
2,481
# frozen_string_literal: true RSpec.describe RuboCop::Cop::Lint::RequireParentheses do subject(:cop) { described_class.new } it 'registers an offense for missing parentheses around expression with ' \ '&& operator' do expect_offense(<<-RUBY.strip_indent) if day.is? 'monday' && month == :jan ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses in the method call to avoid confusion about precedence. foo end RUBY end it 'registers an offense for missing parentheses around expression with ' \ '|| operator' do expect_offense(<<-RUBY.strip_indent) day_is? 'tuesday' || true ^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses in the method call to avoid confusion about precedence. RUBY end it 'registers an offense for missing parentheses around expression in ' \ 'ternary' do expect_offense(<<-RUBY.strip_indent) wd.include? 'tuesday' && true == true ? a : b ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Use parentheses in the method call to avoid confusion about precedence. RUBY end it 'accepts missing parentheses around expression with + operator' do expect_no_offenses(<<-RUBY.strip_indent) if day_is? 'tuesday' + rest end RUBY end it 'accepts method calls without parentheses followed by keyword and/or' do expect_no_offenses(<<-RUBY.strip_indent) if day.is? 'tuesday' and month == :jan end if day.is? 'tuesday' or month == :jan end RUBY end it 'accepts method calls that are all operations' do expect_no_offenses(<<-RUBY.strip_indent) if current_level == max + 1 end RUBY end it 'accepts condition that is not a call' do expect_no_offenses(<<-RUBY.strip_indent) if @debug end RUBY end it 'accepts parentheses around expression with boolean operator' do expect_no_offenses(<<-RUBY.strip_indent) if day.is?('tuesday' && true == true) end RUBY end it 'accepts method call with parentheses in ternary' do expect_no_offenses("wd.include?('tuesday' && true == true) ? a : b") end it 'accepts missing parentheses when method is not a predicate' do expect_no_offenses("weekdays.foo 'tuesday' && true == true") end it 'accepts calls to methods that are setters' do expect_no_offenses('s.version = @version || ">= 1.8.5"') end it 'accepts calls to methods that are operators' do expect_no_offenses('a[b || c]') end end
29.188235
115
0.645304
79a5491ba0172d64ae7378c23635f860b263c467
6,383
=begin #Hydrogen Integration API #The Hydrogen Integration API OpenAPI spec version: 1.3.1 Contact: [email protected] Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.21 =end require 'date' module IntegrationApi class UpdateCardClientResponseVO attr_accessor :message attr_accessor :nucleus_client_id attr_accessor :vendor_name attr_accessor :vendor_request_data attr_accessor :vendor_response # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'message' => :'message', :'nucleus_client_id' => :'nucleus_client_id', :'vendor_name' => :'vendor_name', :'vendor_request_data' => :'vendor_request_data', :'vendor_response' => :'vendor_response' } end # Attribute type mapping. def self.swagger_types { :'message' => :'String', :'nucleus_client_id' => :'String', :'vendor_name' => :'String', :'vendor_request_data' => :'Object', :'vendor_response' => :'Object' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'message') self.message = attributes[:'message'] end if attributes.has_key?(:'nucleus_client_id') self.nucleus_client_id = attributes[:'nucleus_client_id'] end if attributes.has_key?(:'vendor_name') self.vendor_name = attributes[:'vendor_name'] end if attributes.has_key?(:'vendor_request_data') self.vendor_request_data = attributes[:'vendor_request_data'] end if attributes.has_key?(:'vendor_response') self.vendor_response = attributes[:'vendor_response'] end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && message == o.message && nucleus_client_id == o.nucleus_client_id && vendor_name == o.vendor_name && vendor_request_data == o.vendor_request_data && vendor_response == o.vendor_response end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [message, nucleus_client_id, vendor_name, vendor_request_data, vendor_response].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime value when :Date value when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = IntegrationApi.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
29.279817
107
0.626351
38834648e5a60ab50b9304edc6a19c8ff7f53c4c
806
require 'spec_helper' describe Alchemy::EssencesHelper do let(:element) { FactoryGirl.create(:element, :create_contents_after_create => true) } before do element.content_by_name('intro').essence.update_attributes(:body => 'hello!') end it "should render an essence" do content = element.content_by_name('intro') render_essence(content).should match(/hello!/) end it "should render an essence view" do content = element.content_by_name('intro') render_essence_view(content).should match(/hello!/) end it "should render an essence view by name" do render_essence_view_by_name(element, 'intro').should match(/hello!/) end it "should render an essence view by type" do render_essence_view_by_type(element, 'EssenceText').should match(/hello!/) end end
26.866667
87
0.729529
7af9e34a2e3b6a6a1e8c0b17049103872e3c978c
996
BASE_PATH = 'https://raw.githubusercontent.com/weh/can-has-templates-for/master' puts <<INFO ------------------===<<{ WARNING }>>===------------------ Make Sure RVM Setup is correct: rvm use 2.2.0@blog_gemset INFO unless no?('Ready? [yes]') apply "#{BASE_PATH}/rails/database.rb" unless no?('Setup MySQL Database? [yes]') unless no?('Base Stuff (haml, simple form. rspec, capybara)? [yes]') apply "#{BASE_PATH}/rails/base.rb" apply "#{BASE_PATH}/rails/assets.rb" apply "#{BASE_PATH}/rails/gitignore.rb" end # bootstrap apply "#{BASE_PATH}/rails/devise.rb" if yes?('Devise? [no]') apply "#{BASE_PATH}/rails/capistrano.rb" unless no?('Capistrano? [yes]') # Reorganize Gemfile Structure run "gem install bundler-reorganizer" run "bundler-reorganizer Gemfile" apply "#{BASE_PATH}/rails/doc.rb" unless no?('README and CHANGELOG? [yes]') apply "#{BASE_PATH}/rails/git.rb" after_bundle do rake 'db:migrate' unless no?('Migrate Database [yes]') end end
29.294118
82
0.658635
e2c523b96f7f4fb918ffa5d174c493892ac5fb8a
5,169
require 'spec_helper' describe Wyatt::Netsuite::Records::Builder do let(:builder_class) { Wyatt::Netsuite::Records::Builder } let(:builder) { builder_class.new(record_name, schema_file_path) } let(:record_name) { "foo_bar_baz" } let(:record_class_name) { "FooBarBaz" } let(:schema_file_path) { "/some/file/path.yml" } let(:field_hash) do { 'required' => { 'required_field1' => String, 'required_field2' => Fixnum }, 'optional' => { 'optional_field1' => String, 'optional_field2' => Fixnum } } end let(:raw_yaml_string) do "required:\n" + " required_field1: String\n" + " required_field2: Fixnum\n" + "optional:\n" + " optional_field1: String\n" + " optional_field2: Fixnum" end describe ".define_record" do let(:define_record) { builder_class.define_record(record_name, schema_file_path) } let(:builder_mock) { mock } before do builder_class.stub(:new) { builder_mock } builder_mock.stub(:parse_yaml) builder_mock.stub(:define_class_constant) builder_mock.stub(:add_required_fields) builder_mock.stub(:add_optional_fields) end it "should initialize a new Builder" do builder_class.should_receive(:new).with(record_name, schema_file_path) define_record end it "should call parse yaml" do builder_mock.should_receive(:parse_yaml) define_record end it "should call define_class_constant" do builder_mock.should_receive(:define_class_constant) define_record end it "should call add_required_fields" do builder_mock.should_receive(:add_required_fields) define_record end it "should call add_optional_fields" do builder_mock.should_receive(:add_optional_fields) define_record end end describe "#initialize" do before do builder_class.any_instance.stub(:constantize_record_name) { record_class_name } end it "should call constantize_record_name" do builder_class.any_instance.should_receive(:constantize_record_name).once.with(record_name) builder end it "should set record_class_name with the class-ified version" do builder.record_class_name.should == record_class_name end it "should set schema_file_path" do builder.schema_file_path.should == schema_file_path end end describe "#constantize_record_name" do it "should return a valid class-ified string" do builder.constantize_record_name(record_name).should == record_class_name end end describe "#parse_yaml" do let(:parse_yaml) { builder.parse_yaml } before do File.stub(:read) { raw_yaml_string } YAML.stub(:load) { field_hash } end it "should call File.read" do File.should_receive(:read).once.with(schema_file_path) parse_yaml end it "should call YAML::load" do YAML.should_receive(:load).once.with(raw_yaml_string) parse_yaml end it "should set the raw yaml string" do parse_yaml builder.raw_yaml_string.should == raw_yaml_string end it "should call set the field hash" do parse_yaml builder.field_hash.should == field_hash end end describe "#define_class_constant" do let(:define_class_constant) { builder.define_class_constant } let(:fetch_constant) do Wyatt::Netsuite::Records.const_get(record_class_name) end before do define_class_constant end it "should define a new class constant" do expect { fetch_constant }.to_not raise_error end it "should inherit the new class from Wyatt::Core::Record" do fetch_constant.superclass.should == Wyatt::Core::Record end it "should cause the new class to respond to new" do fetch_constant.should respond_to(:new) end it "should set the record_class" do builder.record_class.should == fetch_constant end end describe "#add_field" do let(:mock_class) { Class.new } let(:field_name) { 'field1' } let(:type) { 'String' } let(:type_constant) { String } let(:add_field) { builder.add_field(field_name, type) } before do stub_const("Wyatt::Netsuite::Records::#{record_class_name}", mock_class) builder.stub(:record_class) { Wyatt::Netsuite::Records.const_get(record_class_name) } builder.stub(:type_constant) { type_constant } mock_class.stub(:add_field_to_class) end it "should call type_constant" do builder.should_receive(:type_constant).once.with(type) add_field end it "should call add_field_to_class" do mock_class.should_receive(:add_field_to_class).once.with(field_name, type_constant) add_field end end describe "#type_constant" do let(:type) { 'String' } let(:type_constant) { builder.type_constant(type) } it "should call Object.const_get with the given type string" do Object.should_receive(:const_get).once.with(type) type_constant end end end
25.716418
96
0.670923
0131da5fca5b000d6a71bbde19182921d803fc61
176
class UserMailer < Devise::Mailer def activation_instructions(record, token, opts = {}) @token = token devise_mail(record, :activation_instructions, opts) end end
22
55
0.727273
380b48fcb835dde2111d9a2d4370fa56d9ea917e
2,729
#!/usr/bin/env ruby require 'rex/post/meterpreter/extensions/sniffer/tlv' require 'rex/proto/smb/utils' module Rex module Post module Meterpreter module Extensions module Sniffer ### # # This meterpreter extension can be used to capture remote traffic # ### class Sniffer < Extension def initialize(client) super(client, 'sniffer') client.register_extension_aliases( [ { 'name' => 'sniffer', 'ext' => self }, ]) end # Enumerate the remote sniffable interfaces def interfaces() ifaces = [] ifacei = 0 request = Packet.create_request('sniffer_interfaces') response = client.send_request(request) response.each(TLV_TYPE_SNIFFER_INTERFACES) { |p| vals = p.tlvs.map{|x| x.value } iface = { } ikeys = %W{idx name description type mtu wireless usable dhcp} ikeys.each_index { |i| iface[ikeys[i]] = vals[i] } ifaces << iface } return ifaces end # Start a packet capture on an opened interface def capture_start(intf,maxp=200000) request = Packet.create_request('sniffer_capture_start') request.add_tlv(TLV_TYPE_SNIFFER_INTERFACE_ID, intf.to_i) request.add_tlv(TLV_TYPE_SNIFFER_PACKET_COUNT, maxp.to_i) response = client.send_request(request) end # Stop an active packet capture def capture_stop(intf) request = Packet.create_request('sniffer_capture_stop') request.add_tlv(TLV_TYPE_SNIFFER_INTERFACE_ID, intf.to_i) response = client.send_request(request) end # Retrieve stats about a current capture def capture_stats(intf) request = Packet.create_request('sniffer_capture_stats') request.add_tlv(TLV_TYPE_SNIFFER_INTERFACE_ID, intf.to_i) response = client.send_request(request) { :packets => response.get_tlv_value(TLV_TYPE_SNIFFER_PACKET_COUNT), :bytes => response.get_tlv_value(TLV_TYPE_SNIFFER_BYTE_COUNT), } end # Buffer the current capture to a readable buffer def capture_dump(intf) request = Packet.create_request('sniffer_capture_dump') request.add_tlv(TLV_TYPE_SNIFFER_INTERFACE_ID, intf.to_i) response = client.send_request(request, 3600) { :packets => response.get_tlv_value(TLV_TYPE_SNIFFER_PACKET_COUNT), :bytes => response.get_tlv_value(TLV_TYPE_SNIFFER_BYTE_COUNT), } end # Retrieve the packet data for the specified capture def capture_dump_read(intf, len=16384) request = Packet.create_request('sniffer_capture_dump_read') request.add_tlv(TLV_TYPE_SNIFFER_INTERFACE_ID, intf.to_i) request.add_tlv(TLV_TYPE_SNIFFER_BYTE_COUNT, len.to_i) response = client.send_request(request, 3600) { :bytes => response.get_tlv_value(TLV_TYPE_SNIFFER_BYTE_COUNT), :data => response.get_tlv_value(TLV_TYPE_SNIFFER_PACKET) } end end end; end; end; end; end
27.019802
69
0.749725
03677dfd3bfffd6a94521c60610e749dcdae258e
710
# frozen_string_literal: true require 'generators/warclight/install_generator' module Warclight ## # Warclight Update generator. This subclasses the Install generator, so this is # intended to override behavior in the install generator that can allow the # downstream application to choose if they want to take our changes or not and # can choose to see a diff of our changes to help them decide. class Update < Warclight::Install source_root File.expand_path('../templates', __FILE__) def create_blacklight_catalog copy_file 'catalog_controller.rb', 'app/controllers/catalog_controller.rb' end def solr_config directory '../../../../solr', 'solr' end end end
30.869565
81
0.738028
e8df7f5c203bdcfc41bc9c7a8437156759a86572
2,592
class MongoCxxDriver < Formula desc "C++ driver for MongoDB" homepage "https://github.com/mongodb/mongo-cxx-driver" url "https://github.com/mongodb/mongo-cxx-driver/archive/r3.6.7.tar.gz" sha256 "a9244d3117d4029a2f039dece242eef10e34502e4600e2afa968ab53589e6de7" license "Apache-2.0" head "https://github.com/mongodb/mongo-cxx-driver.git", branch: "master" livecheck do url :stable regex(/^[rv]?(\d+(?:\.\d+)+)$/i) end bottle do sha256 cellar: :any, arm64_monterey: "e953ef9f1244187c03e35b5c63cc56fe78a346b6961375883bfdb20882389ff3" sha256 cellar: :any, arm64_big_sur: "fe2c413af917d8fbc92cf070ac83de24056be996536f548a15e68378016da14a" sha256 cellar: :any, monterey: "58f58441db39bc316d2ff5cfedcdb4d3318c0319b90e8aeb415e72c0e4236fe0" sha256 cellar: :any, big_sur: "ae970fe199ed4e7231b1fa8415837b0ccb410773b553d6874d6fe678e1c889b5" sha256 cellar: :any, catalina: "89bfe3a25e19f9f35547b5c97f69d012d4bffa8a2197f309f64ba0f3f7cf5832" sha256 cellar: :any_skip_relocation, x86_64_linux: "ad20629b2d1cfc86305d17e7932e326bbfd8db3cec28c5a1fc676169cb785c28" end depends_on "cmake" => :build depends_on "mongo-c-driver" def install # We want to avoid shims referencing in examples, # but we need to have examples/CMakeLists.txt file to make cmake happy pkgshare.install "examples" (buildpath / "examples/CMakeLists.txt").write "" mongo_c_prefix = Formula["mongo-c-driver"].opt_prefix system "cmake", ".", *std_cmake_args, "-DBUILD_VERSION=#{version}", "-DLIBBSON_DIR=#{mongo_c_prefix}", "-DLIBMONGOC_DIR=#{mongo_c_prefix}", "-DCMAKE_INSTALL_RPATH=#{rpath}" system "make" system "make", "install" end test do mongo_c_include = Formula["mongo-c-driver"] system ENV.cc, "-o", "test", pkgshare/"examples/bsoncxx/builder_basic.cpp", "-I#{include}/bsoncxx/v_noabi", "-I#{mongo_c_include}/libbson-1.0", "-L#{lib}", "-lbsoncxx", "-std=c++11", "-lstdc++" system "./test" system ENV.cc, "-o", "test", pkgshare/"examples/mongocxx/connect.cpp", "-I#{include}/mongocxx/v_noabi", "-I#{include}/bsoncxx/v_noabi", "-I#{mongo_c_include}/libmongoc-1.0", "-I#{mongo_c_include}/libbson-1.0", "-L#{lib}", "-lmongocxx", "-lbsoncxx", "-std=c++11", "-lstdc++" assert_match "No suitable servers", shell_output("./test mongodb://0.0.0.0 2>&1", 1) end end
42.491803
123
0.65625
e80d80762d21e0e7041b29ad3fdc7d498ad716d4
1,850
# Medium is a module used to interact with the Medium v1 API module Medium # Users class is used to interact with the Users API endpoint of Medium class Users # Initialize a new Medium::Users client # # @param client [#get] The network client to use while retrieving data from # the Users resource. # @return [Medium::Users] Returns a Medium::Users instance def initialize(client) @client = client end # Returns details of the user who has granted permission to the application. # # @return [Hash] The response is a User object within a data envelope. # Example response: # ``` # HTTP/1.1 200 OK # Content-Type: application/json; charset=utf-8 # { # "data": { # "id": "123456789exampleid", # "username": "kkirsche", # "name": "Kevin Kirsche", # "url": "https://medium.com/@kkirsche", # "imageUrl": "https://images.medium.com/somewhere.png" # } # } # ``` def me response = @client.get 'me' Medium::Client.validate response end # Returns an array of a user's publications. # # @return [Array] The response is an array of Publication objects within a data envelope. # Example response: # ``` # HTTP/1.1 200 OK # Content-Type: application/json; charset=utf-8 # { # "data": { # "id": "123456789exampleid", # "name": "Awesome Publication", # "description": "My amazing publication", # "url": "https://medium.com/awesome-publication", # "imageUrl": "https://images.medium.com/somewhere.png" # } # } # ``` def publications() response = @client.get "users/#{me['data']['id']}/publications" Medium::Client.validate response end end end
31.355932
93
0.581622
e27ee0c3221851daab5cc27f3e70ae4ad31f6d6b
19,910
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Monitor::Mgmt::V2017_10_01_preview # # Composite Swagger for Application Insights Management Client # class ComponentCurrentPricingPlan include MsRestAzure # # Creates and initializes a new instance of the ComponentCurrentPricingPlan class. # @param client service class for accessing basic functionality. # def initialize(client) @client = client end # @return [ApplicationInsightsManagementClient] reference to the ApplicationInsightsManagementClient attr_reader :client # # Returns the current pricing plan setting for an Application Insights # component. # # @param resource_group_name [String] The name of the resource group. The name # is case insensitive. # @param resource_name [String] The name of the Application Insights component # resource. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ApplicationInsightsComponentPricingPlan] operation results. # def get(resource_group_name, resource_name, custom_headers:nil) response = get_async(resource_group_name, resource_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # Returns the current pricing plan setting for an Application Insights # component. # # @param resource_group_name [String] The name of the resource group. The name # is case insensitive. # @param resource_name [String] The name of the Application Insights component # resource. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def get_with_http_info(resource_group_name, resource_name, custom_headers:nil) get_async(resource_group_name, resource_name, custom_headers:custom_headers).value! end # # Returns the current pricing plan setting for an Application Insights # component. # # @param resource_group_name [String] The name of the resource group. The name # is case insensitive. # @param resource_name [String] The name of the Application Insights component # resource. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def get_async(resource_group_name, resource_name, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90 fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1 fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, "'@client.api_version' should satisfy the constraint - 'MinLength': '1'" if [email protected]_version.nil? && @client.api_version.length < 1 fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'MinLength': '1'" if [email protected]_id.nil? && @client.subscription_id.length < 1 fail ArgumentError, 'resource_name is nil' if resource_name.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/pricingPlans/current' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'subscriptionId' => @client.subscription_id,'resourceName' => resource_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:get, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Monitor::Mgmt::V2017_10_01_preview::Models::ApplicationInsightsComponentPricingPlan.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Replace current pricing plan for an Application Insights component. # # @param resource_group_name [String] The name of the resource group. The name # is case insensitive. # @param resource_name [String] The name of the Application Insights component # resource. # @param pricing_plan_properties [ApplicationInsightsComponentPricingPlan] # Properties that need to be specified to update current pricing plan for an # Application Insights component. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ApplicationInsightsComponentPricingPlan] operation results. # def create_and_update(resource_group_name, resource_name, pricing_plan_properties, custom_headers:nil) response = create_and_update_async(resource_group_name, resource_name, pricing_plan_properties, custom_headers:custom_headers).value! response.body unless response.nil? end # # Replace current pricing plan for an Application Insights component. # # @param resource_group_name [String] The name of the resource group. The name # is case insensitive. # @param resource_name [String] The name of the Application Insights component # resource. # @param pricing_plan_properties [ApplicationInsightsComponentPricingPlan] # Properties that need to be specified to update current pricing plan for an # Application Insights component. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def create_and_update_with_http_info(resource_group_name, resource_name, pricing_plan_properties, custom_headers:nil) create_and_update_async(resource_group_name, resource_name, pricing_plan_properties, custom_headers:custom_headers).value! end # # Replace current pricing plan for an Application Insights component. # # @param resource_group_name [String] The name of the resource group. The name # is case insensitive. # @param resource_name [String] The name of the Application Insights component # resource. # @param pricing_plan_properties [ApplicationInsightsComponentPricingPlan] # Properties that need to be specified to update current pricing plan for an # Application Insights component. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def create_and_update_async(resource_group_name, resource_name, pricing_plan_properties, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90 fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1 fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, "'@client.api_version' should satisfy the constraint - 'MinLength': '1'" if [email protected]_version.nil? && @client.api_version.length < 1 fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'MinLength': '1'" if [email protected]_id.nil? && @client.subscription_id.length < 1 fail ArgumentError, 'resource_name is nil' if resource_name.nil? fail ArgumentError, 'pricing_plan_properties is nil' if pricing_plan_properties.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Monitor::Mgmt::V2017_10_01_preview::Models::ApplicationInsightsComponentPricingPlan.mapper() request_content = @client.serialize(request_mapper, pricing_plan_properties) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/pricingPlans/current' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'subscriptionId' => @client.subscription_id,'resourceName' => resource_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:put, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Monitor::Mgmt::V2017_10_01_preview::Models::ApplicationInsightsComponentPricingPlan.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end # # Update current pricing plan for an Application Insights component. # # @param resource_group_name [String] The name of the resource group. The name # is case insensitive. # @param resource_name [String] The name of the Application Insights component # resource. # @param pricing_plan_properties [ApplicationInsightsComponentPricingPlan] # Properties that need to be specified to update current pricing plan for an # Application Insights component. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [ApplicationInsightsComponentPricingPlan] operation results. # def update(resource_group_name, resource_name, pricing_plan_properties, custom_headers:nil) response = update_async(resource_group_name, resource_name, pricing_plan_properties, custom_headers:custom_headers).value! response.body unless response.nil? end # # Update current pricing plan for an Application Insights component. # # @param resource_group_name [String] The name of the resource group. The name # is case insensitive. # @param resource_name [String] The name of the Application Insights component # resource. # @param pricing_plan_properties [ApplicationInsightsComponentPricingPlan] # Properties that need to be specified to update current pricing plan for an # Application Insights component. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [MsRestAzure::AzureOperationResponse] HTTP response information. # def update_with_http_info(resource_group_name, resource_name, pricing_plan_properties, custom_headers:nil) update_async(resource_group_name, resource_name, pricing_plan_properties, custom_headers:custom_headers).value! end # # Update current pricing plan for an Application Insights component. # # @param resource_group_name [String] The name of the resource group. The name # is case insensitive. # @param resource_name [String] The name of the Application Insights component # resource. # @param pricing_plan_properties [ApplicationInsightsComponentPricingPlan] # Properties that need to be specified to update current pricing plan for an # Application Insights component. # @param [Hash{String => String}] A hash of custom headers that will be added # to the HTTP request. # # @return [Concurrent::Promise] Promise object which holds the HTTP response. # def update_async(resource_group_name, resource_name, pricing_plan_properties, custom_headers:nil) fail ArgumentError, 'resource_group_name is nil' if resource_group_name.nil? fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MaxLength': '90'" if !resource_group_name.nil? && resource_group_name.length > 90 fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'MinLength': '1'" if !resource_group_name.nil? && resource_group_name.length < 1 fail ArgumentError, "'resource_group_name' should satisfy the constraint - 'Pattern': '^[-\w\._\(\)]+$'" if !resource_group_name.nil? && resource_group_name.match(Regexp.new('^^[-\w\._\(\)]+$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, "'@client.api_version' should satisfy the constraint - 'MinLength': '1'" if [email protected]_version.nil? && @client.api_version.length < 1 fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.nil? fail ArgumentError, "'@client.subscription_id' should satisfy the constraint - 'MinLength': '1'" if [email protected]_id.nil? && @client.subscription_id.length < 1 fail ArgumentError, 'resource_name is nil' if resource_name.nil? fail ArgumentError, 'pricing_plan_properties is nil' if pricing_plan_properties.nil? request_headers = {} request_headers['Content-Type'] = 'application/json; charset=utf-8' # Set Headers request_headers['x-ms-client-request-id'] = SecureRandom.uuid request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::Monitor::Mgmt::V2017_10_01_preview::Models::ApplicationInsightsComponentPricingPlan.mapper() request_content = @client.serialize(request_mapper, pricing_plan_properties) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.insights/components/{resourceName}/pricingPlans/current' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'resourceGroupName' => resource_group_name,'subscriptionId' => @client.subscription_id,'resourceName' => resource_name}, query_params: {'api-version' => @client.api_version}, body: request_content, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:patch, path_template, options) promise = promise.then do |result| http_response = result.response status_code = http_response.status response_content = http_response.body unless status_code == 200 error_model = JSON.load(response_content) fail MsRestAzure::AzureOperationError.new(result.request, http_response, error_model) end result.request_id = http_response['x-ms-request-id'] unless http_response['x-ms-request-id'].nil? result.correlation_request_id = http_response['x-ms-correlation-request-id'] unless http_response['x-ms-correlation-request-id'].nil? result.client_request_id = http_response['x-ms-client-request-id'] unless http_response['x-ms-client-request-id'].nil? # Deserialize Response if status_code == 200 begin parsed_response = response_content.to_s.empty? ? nil : JSON.load(response_content) result_mapper = Azure::Monitor::Mgmt::V2017_10_01_preview::Models::ApplicationInsightsComponentPricingPlan.mapper() result.body = @client.deserialize(result_mapper, parsed_response) rescue Exception => e fail MsRest::DeserializationError.new('Error occurred in deserializing the response', e.message, e.backtrace, result) end end result end promise.execute end end end
52.671958
206
0.720844
1a5d2573059ec57a06d8413d74ff0b477f251f95
747
# encoding: BINARY class MQTT::SN::Packet::Connect < MQTT::SN::Packet attr_accessor :keep_alive attr_accessor :client_id DEFAULTS = { :request_will => false, :clean_session => true, :keep_alive => 15 } # Get serialisation of packet's body def encode_body if @client_id.nil? || @client_id.empty? || @client_id.length > 23 raise 'Invalid client identifier when serialising packet' end [encode_flags, 0x01, keep_alive, client_id].pack('CCna*') end def parse_body(buffer) flags, protocol_id, self.keep_alive, self.client_id = buffer.unpack('CCna*') if protocol_id != 0x01 raise ParseException, "Unsupported protocol ID number: #{protocol_id}" end parse_flags(flags) end end
23.34375
80
0.685408
abd69fede2842731ecbb954e21a9697f587e0d2a
1,093
points = [] folds = [] File.readlines("input2.txt").collect(&:chomp).reject(&:empty?).each do |line| if line.start_with?("fold along") axis, point = line.split(" ")[-1].split("=") folds << [axis, point.to_i] else points << line.split(",").collect(&:to_i) end end folds.each do |axis, point| puts "processing #{axis} #{point}" fpoints = points.dup case axis when "x" points = fpoints.reject { |x, y| x.eql?(point) }.collect do |x1, y1| if x1 > point [2 * point - x1, y1] else [x1, y1] end end when "y" points = fpoints.reject { |x, y| x.eql?(point) }.collect do |x1, y1| if y1 > point [x1, 2 * point - y1] else [x1, y1] end end else raise "not supported" end points.uniq! end puts "---" mx = points.collect { |x, y| x }.max + 1 my = points.collect { |x, y| y }.max + 1 a = Array.new(mx) { Array.new(my) { " " } } points.each do |x, y| a[x][y] = "#" end my.times do |y| mx.times do |x| print a[x][y] end print ("\n") end puts "that reads" puts "JPZCUAUR"
19.175439
77
0.538884
7a9b24c62f4b1d5cff210c78c41807c62d6eae21
27,395
# frozen_string_literal: true require 'rspec_api_documentation/dsl' require 'helpers/acceptance_spec_helper' # https://github.com/zipmark/rspec_api_documentation resource 'AudioEventComments' do # set header header 'Accept', 'application/json' header 'Content-Type', 'application/json' header 'Authorization', :authentication_token # default format let(:format) { 'json' } create_entire_hierarchy # TODO: sort out what these tests should actually test # TODO: don't forget about reference audio events let(:audio_event_reference) { FactoryBot.create( :audio_event, id: 99_998, creator: writer_user, audio_recording: audio_recording, is_reference: true ) } let!(:comment_other) { FactoryBot.create( :comment, id: 99_874, comment: 'the no access comment text', creator: no_access_user, audio_event: audio_event_reference ) # different audio_event } let!(:comment_reader) { FactoryBot.create( :comment, id: 99_875, comment: 'the reader comment text', creator: reader_user, audio_event: audio_event ) } let!(:comment_writer) { AudioEventComment.where(creator: writer_user, audio_event: audio_event).first } let!(:comment_owner) { FactoryBot.create( :comment, id: 99_877, comment: 'the owner comment text', creator: owner_user, audio_event: audio_event ) } let(:post_attributes) { { comment: 'new comment content' } } let(:post_attributes_flag_report) { { flag: 'report' } } let(:post_attributes_flag_nil) { { flag: nil } } ################################ # LIST ################################ get '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:expected_unordered_ids) { AudioEventComment.where(audio_event_id: audio_event.id).pluck(:id) } let(:authentication_token) { admin_token } standard_request_options(:get, 'LIST (as admin)', :ok, { expected_json_path: 'data/0/comment', data_item_count: 3 }) end get '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:expected_unordered_ids) { AudioEventComment.where(audio_event_id: audio_event.id).pluck(:id) } let(:authentication_token) { owner_token } standard_request_options(:get, 'LIST (as owner)', :ok, { expected_json_path: 'data/0/comment', data_item_count: 3 }) end get '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:expected_unordered_ids) { AudioEventComment.where(audio_event_id: audio_event.id).pluck(:id) } let(:authentication_token) { writer_token } standard_request_options(:get, 'LIST (as writer)', :ok, { expected_json_path: 'data/0/comment', data_item_count: 3 }) end get '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:expected_unordered_ids) { AudioEventComment.where(audio_event_id: audio_event.id).pluck(:id) } let(:authentication_token) { reader_token } standard_request_options(:get, 'LIST (as reader)', :ok, { expected_json_path: 'data/0/comment', data_item_count: 3 }) end get '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:expected_unordered_ids) { AudioEventComment.where(audio_event_id: audio_event.id).pluck(:id) } let(:authentication_token) { no_access_token } standard_request_options(:get, 'LIST (as other)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end get '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:authentication_token) { no_access_token } standard_request_options(:get, 'LIST (as other token, reader comment)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end get '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:authentication_token) { invalid_token } standard_request_options(:get, 'LIST (invalid token)', :unauthorized, { expected_json_path: get_json_error_path(:sign_up) }) end get '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } standard_request_options(:get, 'LIST (as anonymous user)', :unauthorized, { remove_auth: true, expected_json_path: get_json_error_path(:sign_up) }) end ################################ # CREATE ################################ post '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { admin_token } standard_request_options(:post, 'CREATE (as admin)', :created, { expected_json_path: 'data/comment' }) end post '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { owner_token } standard_request_options(:post, 'CREATE (as owner)', :created, { expected_json_path: 'data/comment' }) end post '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { writer_token } standard_request_options(:post, 'CREATE (as writer)', :created, { expected_json_path: 'data/comment' }) end post '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { reader_token } standard_request_options(:post, 'CREATE (as reader)', :created, { expected_json_path: 'data/comment' }) end post '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { no_access_token } standard_request_options(:post, 'CREATE (as other token)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end post '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { invalid_token } standard_request_options(:post, 'CREATE (invalid token)', :unauthorized, { expected_json_path: get_json_error_path(:sign_up) }) end post '/audio_events/:audio_event_id/comments' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } standard_request_options(:post, 'CREATE (as anonymous user)', :unauthorized, { remove_auth: true, expected_json_path: get_json_error_path(:sign_up) }) end ################################ # Show ################################ get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { admin_token } standard_request_options(:get, 'SHOW (as admin)', :ok, { expected_json_path: ['data/updated_at', 'data/comment'] }) end get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { owner_token } standard_request_options(:get, 'SHOW (as owner)', :ok, { expected_json_path: 'data/comment' }) end get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { writer_token } standard_request_options(:get, 'SHOW (as writer)', :ok, { expected_json_path: 'data/comment' }) end get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { reader_token } standard_request_options(:get, 'SHOW (as reader)', :ok, { expected_json_path: ['data/created_at', 'data/comment'] }) end get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { writer_token } standard_request_options(:get, 'SHOW (as writer)', :ok, { expected_json_path: 'data/comment' }) end get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { no_access_token } standard_request_options(:get, 'SHOW (as other user)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_writer.id } let(:authentication_token) { no_access_token } standard_request_options(:get, 'SHOW (as other user showing writer comment)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_other.id } let(:authentication_token) { writer_token } standard_request_options(:get, 'SHOW (as writer showing other comment)', :ok, { expected_json_path: 'data/comment' }) end get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { invalid_token } standard_request_options(:get, 'SHOW (as invalid user)', :unauthorized, { expected_json_path: get_json_error_path(:sign_up) }) end get '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } standard_request_options(:get, 'SHOW (as anonymous user)', :unauthorized, { remove_auth: true, expected_json_path: get_json_error_path(:sign_up) }) end ################################ # Update ################################ put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { admin_token } standard_request_options(:put, 'UPDATE (as admin)', :ok, { expected_json_path: 'data/comment' }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { owner_token } standard_request_options(:put, 'UPDATE (as owner)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_owner.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { owner_token } standard_request_options(:put, 'UPDATE (as owner updating own comment)', :ok, { expected_json_path: 'data/comment' }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { writer_token } standard_request_options(:put, 'UPDATE (as writer)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { reader_token } standard_request_options(:put, 'UPDATE (as reader)', :ok, { expected_json_path: 'data/comment' }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { no_access_token } standard_request_options(:put, 'UPDATE (as other user)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { invalid_token } standard_request_options(:put, 'UPDATE (as invalid user)', :unauthorized, { expected_json_path: get_json_error_path(:sign_up) }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_owner.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } standard_request_options(:put, 'UPDATE (as anonymous user, owner comment)', :unauthorized, { remove_auth: true, expected_json_path: get_json_error_path(:sign_up) }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_writer.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } standard_request_options(:put, 'UPDATE (as anonymous user, writer comment)', :unauthorized, { remove_auth: true, expected_json_path: get_json_error_path(:sign_up) }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } standard_request_options(:put, 'UPDATE (as anonymous user, reader comment)', :unauthorized, { remove_auth: true, expected_json_path: get_json_error_path(:sign_up) }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_other.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } standard_request_options(:put, 'UPDATE (as anonymous user, other comment)', :unauthorized, { remove_auth: true, expected_json_path: get_json_error_path(:sign_up) }) end # user can only update their own comments put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_writer.id } let(:raw_post) { { audio_event_comment: post_attributes }.to_json } let(:authentication_token) { no_access_token } standard_request_options(:put, 'UPDATE (as other updating comment created by writer)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_writer.id } let(:raw_post) { { audio_event_comment: post_attributes_flag_report }.to_json } let(:authentication_token) { writer_token } standard_request_options(:put, 'UPDATE (as writer updating flag to report for comment created by writer)', :ok, { expected_json_path: 'data/flag', response_body_content: 'report' }) end put '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_writer.id } let(:raw_post) { { audio_event_comment: post_attributes_flag_nil }.to_json } let(:authentication_token) { writer_token } standard_request_options(:put, 'UPDATE (as writer updating flag to nil for comment created by writer)', :ok, { expected_json_path: 'data/flag', response_body_content: '"flag":null' }) end ################################ # Destroy ################################ delete '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { admin_token } standard_request_options(:delete, 'DESTROY (as admin)', :no_content, { expected_response_has_content: false, expected_response_content_type: nil }) end delete '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_writer.id } let(:authentication_token) { owner_token } standard_request_options(:delete, 'DESTROY (as owner)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end delete '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_owner.id } let(:authentication_token) { owner_token } standard_request_options(:delete, 'DESTROY (as owner destroying own comment)', :no_content, { expected_response_has_content: false, expected_response_content_type: nil }) end delete '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { writer_token } standard_request_options(:delete, 'DESTROY (as writer)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end delete '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { reader_token } standard_request_options(:delete, 'DESTROY (as reader)', :no_content, { expected_response_has_content: false, expected_response_content_type: nil }) end delete '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { no_access_token } standard_request_options(:delete, 'DESTROY (as no access user)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end delete '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } let(:authentication_token) { invalid_token } standard_request_options(:delete, 'DESTROY (invalid token)', :unauthorized, { expected_json_path: get_json_error_path(:sign_up) }) end delete '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_reader.id } standard_request_options(:delete, 'DESTROY (as anonymous user)', :unauthorized, { remove_auth: true, expected_json_path: get_json_error_path(:sign_up) }) end # users can only delete their own comments delete '/audio_events/:audio_event_id/comments/:id' do parameter :audio_event_id, 'Requested audio event id (in path/route)', required: true parameter :id, 'Requested audio event comment id (in path/route)', required: true let(:audio_event_id) { audio_event.id } let(:id) { comment_writer.id } let(:authentication_token) { no_access_token } standard_request_options(:delete, 'DESTROY (as other deleting comment created by writer)', :forbidden, { expected_json_path: get_json_error_path(:permissions) }) end ##################### # Filter ##################### post '/audio_event_comments/filter' do let(:authentication_token) { reader_token } let(:raw_post) { { 'filter' => { 'comment' => { 'contains' => 'comment' } }, 'projection' => { 'include' => ['id', 'audio_event_id', 'comment'] } }.to_json } standard_request_options(:post, 'FILTER (as reader)', :ok, { expected_json_path: 'meta/filter/comment', data_item_count: 4, response_body_content: ['"the owner comment text"', '"the reader comment text"', '"the no access comment text"', '"comment":"comment text '], invalid_content: '"project_ids":[{"id":' }) end post '/audio_event_comments/filter' do # anonymous users cannot access any audio event comments, # even if the audio event is a reference. let(:raw_post) { { 'filter' => { 'comment' => { 'contains' => 'comment' } }, 'projection' => { 'include' => ['id', 'audio_event_id', 'comment'] } }.to_json } standard_request_options(:post, 'FILTER (as anonymous user)', :unauthorized, { remove_auth: true, expected_json_path: get_json_error_path(:sign_up) }) end end
49.990876
187
0.70345
5d821376863ce579b9438611456bc85641a8e939
1,365
=begin #GraphHopper Directions API #You use the GraphHopper Directions API to add route planning, navigation and route optimization to your software. E.g. the Routing API has turn instructions and elevation data and the Route Optimization API solves your logistic problems and supports various constraints like time window and capacity restrictions. Also it is possible to get all distances between all locations with our fast Matrix API. OpenAPI spec version: 1.0.0 Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.0-SNAPSHOT =end require 'spec_helper' require 'json' require 'date' # Unit tests for GraphHopperClient::Configuration # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'Configuration' do before do # run before each test @instance = GraphHopperClient::Configuration.new end after do # run after each test end describe 'test an instance of Configuration' do it 'should create an instance of Configuration' do expect(@instance).to be_instance_of(GraphHopperClient::Configuration) end end describe 'test attribute "routing"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
31.744186
403
0.769231
08c30a96290d4cf597efce088d7b2e199b21c591
411
# just for compatibility; requiring "md5" is obsoleted # # $RoughId: md5.rb,v 1.4 2001/07/13 15:38:27 knu Exp $ # $Id: md5.rb 12007 2007-03-06 10:09:51Z knu $ require 'digest/md5' class MD5 < Digest::MD5 class << self alias orig_new new def new(str = nil) if str orig_new.update(str) else orig_new end end def md5(*args) new(*args) end end end
17.125
54
0.593674
18b2bfa22aeaf9595555ebc0959060abb9463e88
376
cask :v1 => 'mongochef' do version '3.1.0' sha256 '6c67fbad534bba6815c2ce665f91e8e5dc8700f597b6b4cf47789a99db62ed97' url "https://cdn.3t.io/mongochef/mac/#{version}/MongoChef.dmg" name 'MongoChef' homepage 'https://3t.io/mongochef/' # License is free for personal use (gratis) and paid for business use (commercial) license :other app '3T MongoChef.app' end
28.923077
84
0.739362
1c8ec26bfc963590cd021978d4f96056dbb7ae4a
891
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'recording a new maneuver score' do let(:judge) { create :user, :judge } let(:maneuver) { create :maneuver } let(:participant) { create :participant } let(:mp) do ManeuverParticipant.find_by maneuver_id: maneuver, participant_id: participant end before do when_current_user_is judge visit new_maneuver_participant_path maneuver: maneuver.name, participant: participant.number end it 'increases maneuver participant count by one' do expect { click_on 'Save & next' }.to change(ManeuverParticipant, :count).by(1) end it 'records the creator' do click_on 'Save & next' when_current_user_is :admin visit maneuver_participant_path(mp) expect(page).to have_text "recorded by #{judge.name}" end end
28.741935
82
0.67789
262d8da9fc57ca3ba534891e3faa5930aa9fd45e
1,650
module TD::Types # Represents a local file. # # @attr path [TD::Types::String, nil] Local path to the locally available file part; may be empty. # @attr can_be_downloaded [Boolean] True, if it is possible to download or generate the file. # @attr can_be_deleted [Boolean] True, if the file can be deleted. # @attr is_downloading_active [Boolean] True, if the file is currently being downloaded (or a local copy is being # generated by some other means). # @attr is_downloading_completed [Boolean] True, if the local copy is fully available. # @attr download_offset [Integer] Download will be started from this offset. # downloaded_prefix_size is calculated from this offset. # @attr downloaded_prefix_size [Integer] If is_downloading_completed is false, then only some prefix of the file # starting from download_offset is ready to be read. # downloaded_prefix_size is the size of that prefix in bytes. # @attr downloaded_size [Integer] Total downloaded file size, in bytes. # Can be used only for calculating download progress. # The actual file size may be bigger, and some parts of it may contain garbage. class LocalFile < Base attribute :path, TD::Types::String.optional.default(nil) attribute :can_be_downloaded, TD::Types::Bool attribute :can_be_deleted, TD::Types::Bool attribute :is_downloading_active, TD::Types::Bool attribute :is_downloading_completed, TD::Types::Bool attribute :download_offset, TD::Types::Coercible::Integer attribute :downloaded_prefix_size, TD::Types::Coercible::Integer attribute :downloaded_size, TD::Types::Coercible::Integer end end
56.896552
115
0.750303
1aa9ceafdf529778544bf3d77aa1df535906afb0
782
=begin Copyright 2012-2013 inBloom, Inc. and its affiliates. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =end require 'rubygems' # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exists?(ENV['BUNDLE_GEMFILE'])
30.076923
72
0.772379
91d2e3dd625d7be8283ac9be4117877f5ed1a032
193
{ 'info' => { 'url' => 'http://eruditeum.com/mantis', 'username' => 'test_admin', 'password' => 'test_password' }, 'parameters' => { 'issue_attachment_id' => '000001', } }
17.545455
43
0.533679
f7c07c3d834a3832847de4df3344ec8cefeffcf9
859
# frozen_string_literal: true module Clowne module Declarations class Trait # :nodoc: all def initialize @blocks = [] end def extend_with(block) @blocks << block end def compiled return @compiled if instance_variable_defined?(:@compiled) @compiled = compile end alias declarations compiled def dup self.class.new.tap do |duped| blocks.each { |b| duped.extend_with(b) } end end private attr_reader :blocks def compile anonymous_cloner = Class.new(Clowne::Cloner) blocks.each do |block| anonymous_cloner.instance_eval(&block) end anonymous_cloner.declarations end end end end Clowne::Declarations.add :trait do |name, &block| register_trait name, block end
17.895833
66
0.605355
911bad8822717a2bf79192f3fc1450fae514b36c
844
require 'swiftcore/swiftiplied_mongrel' require 'merb-core/rack/handler/mongrel' module Merb module Rack class SwiftipliedMongrel < Mongrel # Starts Mongrel as swift. # # ==== Parameters # opts<Hash>:: Options for Mongrel (see below). # # ==== Options (opts) # :host<String>:: The hostname that Mongrel should serve. # :port<Fixnum>:: The port Mongrel should bind to. # :app<String>>:: The application name. def self.start(opts={}) Merb.logger.warn!("Using SwiftipliedMongrel adapter") Merb::Dispatcher.use_mutex = false server = ::Mongrel::HttpServer.new(opts[:host], opts[:port].to_i) Merb::Server.change_privilege server.register('/', ::Merb::Rack::Handler::Mongrel.new(opts[:app])) server.run.join end end end end
32.461538
76
0.626777
030253554ffd0701290cd2e657522d134017ecc5
93
class FavoriteSerializer < ActiveModel::Serializer attributes :id, :issue_id, :user_id end
23.25
50
0.795699
e827520f09f10eac5ab8ef5c786075d722273bd8
1,649
# frozen_string_literal: true module Effective class Representative < ActiveRecord::Base attr_accessor :new_representative_user_action acts_as_role_restricted log_changes(to: :organization) if respond_to?(:log_changes) belongs_to :organization, polymorphic: true, counter_cache: true belongs_to :user, polymorphic: true accepts_nested_attributes_for :organization accepts_nested_attributes_for :user effective_resource do roles_mask :integer timestamps end scope :sorted, -> { order(:id) } scope :deep, -> { includes(:user, :organization) } before_validation(if: -> { user && user.new_record? }) do user.password ||= SecureRandom.base64(12) + '!@#123abcABC-' end after_commit(on: [:create, :destroy], if: -> { user.class.respond_to?(:effective_memberships_owner?) }) do user.representatives.reload user.update_member_role! end validates :organization, presence: true validates :user, presence: true validates :user_id, if: -> { user_id && user_type && organization_id && organization_type }, uniqueness: { scope: [:organization_id, :organization_type], message: 'already belongs to this organization' } def to_s user.to_s end def build_user(attributes = {}) raise('please assign user_type first') if user_type.blank? self.user = user_type.constantize.new(attributes) end def build_organization(attributes = {}) raise('please assign organization_type first') if organization_type.blank? self.organization = organization_type.constantize.new(attributes) end end end
28.929825
116
0.70285
391f37aab82b7b6147339129e3c99f7c82223448
652
# Usage examples: # folder.documents.should be_contiguous # folder.documents.should be_contiguous.starting_at(1) RSpec::Matchers.define :be_contiguous do match do |array| @start ||= 0 array.each_with_index do |current, index| current.reload.position.should == index + @start end end def starting_at(start) @start = start self end failure_message_for_should do |actual| message = "expected that" actual.each do |current| message << " [#{current.id}, #{current.position}]" end message << " would be contiguous" message << " (starting at #{@start})" if @start > 0 message end end
23.285714
56
0.661043
87c3f5248f4e910f7b4270977dad8eb16f352da0
956
require 'spec_helper' require 'browser/location' require 'browser/socket' describe Browser::Socket do # FIXME: find out why it doesn't work inline ws = "ws://#{$window.location.host}/socket" it 'creates a socket' do promise = Promise.new Browser::Socket.new ws do |s| s.on :open do |e| expect(e.target).to be_a(Browser::Socket) promise.resolve end end promise end it 'receives messages' do promise = Promise.new Browser::Socket.new ws do |s| s.on :message do |e| expect(e.data).to eq('lol') promise.resolve end end promise end it 'sends messages' do promise = Promise.new Browser::Socket.new ws do |s| s.on :message do |e| e.off s.print 'omg' s.on :message do |e| expect(e.data).to eq('omg') promise.resolve end end end promise end end if Browser::Socket.supported?
19.916667
49
0.588912
bb445bb7fc9d93446f685a99d950c2bef3cbb7fa
6,071
class Hazelcast < Formula desc "Hazelcast is a streaming and memory-first application platform for fast, stateful, data-intensive workloads on-premises, at the edge or as a fully managed cloud service." homepage "https://github.com/hazelcast/hazelcast-command-line" url "https://repo.maven.apache.org/maven2/com/hazelcast/hazelcast-distribution/5.1.1/hazelcast-distribution-5.1.1.tar.gz" sha256 "20b5532d6f135145c4a0f8e713309a1a118099a40b6674f0f5183e8867b17263" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "hazelcast-enterprise", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "hazelcast-enterprise-snapshot", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "hazelcast-enterprise-devel", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "hazelcast-enterprise-5.1", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "hazelcast-enterprise-5.0", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "[email protected]", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "hazelcast-5.1", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "hazelcast-5.0", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "hazelcast-snapshot", because: "you can install only a single hazelcast or hazelcast-enterprise package" conflicts_with "hazelcast-devel", because: "you can install only a single hazelcast or hazelcast-enterprise package" depends_on "openjdk" => :recommended def install libexec.install Dir["*"] Dir["#{libexec}/bin/hz*"].each do |path| executable_name = File.basename(path) if executable_name.end_with? ".bat" next end (bin/executable_name).write_env_script libexec/"bin/#{executable_name}", Language::Java.overridable_java_home_env end etc.install "#{libexec}/config" => "hazelcast" rm_rf libexec/"config" libexec.install_symlink "#{etc}/hazelcast" => "config" prefix.install_metafiles inreplace libexec/"lib/hazelcast-download.properties", "hazelcastDownloadId=distribution", "hazelcastDownloadId=brew" end def caveats <<~EOS Configuration files have been placed in #{etc}/hazelcast. EOS end def post_install exec "echo Hazelcast has been installed." end end
83.164384
180
0.766431
ed90d5cc6b595c5736109bf98989b61d324ec3d8
3,651
# frozen_string_literal: true module Stealth module Nlp module Luis class Result < Stealth::Nlp::Result ENTITY_MAP = { 'money' => :currency, 'number' => :number, 'email' => :email, 'percentage' => :percentage, 'Calendar.Duration' => :duration, 'geographyV2' => :geo, 'age' => :age, 'phonenumber' => :phone, 'ordinalV2' => :ordinal, 'url' => :url, 'dimension' => :dimension, 'temperature' => :temp, 'keyPhrase' => :key_phrase, 'name' => :name, 'datetimeV2' => :datetime } def initialize(result:) @result = result if result.status.success? Stealth::Logger.l( topic: :nlp, message: 'NLP lookup successful' ) parsed_result else Stealth::Logger.l( topic: :nlp, message: "NLP lookup FAILED: (#{result.status.code}) #{result.body.to_s}" ) end end # Sample JSON result: # { # "query": "I make between $5400 and $9600 per month", # "prediction": { # "topIntent": "None", # "intents": { # "None": { # "score": 0.5345857 # } # }, # "entities": { # "money": [ # { # "number": 5400, # "units": "Dollar" # }, # { # "number": 9600, # "units": "Dollar" # } # ], # "number": [ # 5400, # 9600 # ] # }, # "sentiment": { # "label": "positive", # "score": 0.7805586 # } # } # } def parsed_result @parsed_result ||= MultiJson.load(result.body.to_s) end def intent top_intent&.to_sym end def intent_score parsed_result&.dig('prediction', 'intents', top_intent, 'score') end def raw_entities parsed_result&.dig('prediction', 'entities') end def entities return {} if raw_entities.blank? _entities = {} raw_entities.each do |type, values| if ENTITY_MAP[type] _entities[ENTITY_MAP[type]] = values else # A custom entity _entities[type.to_sym] = values end end _entities end def sentiment_score parsed_result&.dig('prediction', 'sentiment', 'score') end def sentiment parsed_result&.dig('prediction', 'sentiment', 'label')&.to_sym end private def top_intent @top_intent ||= begin matched_intent = parsed_result&.dig('prediction', 'topIntent') _intent_score = parsed_result&.dig('prediction', 'intents', matched_intent, 'score') if Stealth.config.luis.intent_threshold.is_a?(Numeric) if _intent_score > Stealth.config.luis.intent_threshold matched_intent else Stealth::Logger.l( topic: :nlp, message: "Ignoring intent match. Does not meet threshold (#{Stealth.config.luis.intent_threshold})" ) 'None' # can't be nil or this doesn't get memoized end else matched_intent end end end end end end end
27.659091
117
0.453027
6a1a75218ac3023cad0e22cdbf4dbe5771686382
11,475
require 'test_helper' class WirecardTest < Test::Unit::TestCase include CommStub TEST_AUTHORIZATION_GUWID = 'C822580121385121429927' TEST_PURCHASE_GUWID = 'C865402121385575982910' TEST_CAPTURE_GUWID = 'C833707121385268439116' def setup @gateway = WirecardGateway.new(:login => '', :password => '', :signature => '') @credit_card = credit_card('4200000000000000') @declined_card = credit_card('4000300011112220') @unsupported_card = credit_card('4200000000000000', :brand => :maestro) @amount = 111 @options = { :order_id => '1', :billing_address => address, :description => 'Wirecard Purchase', :email => '[email protected]' } @address_without_state = { :name => 'Jim Smith', :address1 => '1234 My Street', :company => 'Widgets Inc', :city => 'Ottawa', :zip => 'K12 P2A', :country => 'CA', :state => nil, } end def test_successful_authorization @gateway.expects(:ssl_post).returns(successful_authorization_response) assert response = @gateway.authorize(@amount, @credit_card, @options) assert_instance_of Response, response assert_success response assert response.test? assert_equal TEST_AUTHORIZATION_GUWID, response.authorization end def test_successful_purchase @gateway.expects(:ssl_post).returns(successful_purchase_response) assert response = @gateway.purchase(@amount, @credit_card, @options) assert_instance_of Response, response assert_success response assert response.test? assert_equal TEST_PURCHASE_GUWID, response.authorization end def test_wrong_credit_card_authorization @gateway.expects(:ssl_post).returns(wrong_creditcard_authorization_response) assert response = @gateway.authorize(@amount, @declined_card, @options) assert_instance_of Response, response assert_failure response assert response.test? assert_equal TEST_AUTHORIZATION_GUWID, response.authorization assert response.message[/credit card number not allowed in demo mode/i] end def test_successful_authorization_and_capture @gateway.expects(:ssl_post).returns(successful_authorization_response) assert response = @gateway.authorize(@amount, @credit_card, @options) assert_success response assert_equal TEST_AUTHORIZATION_GUWID, response.authorization @gateway.expects(:ssl_post).returns(successful_capture_response) assert response = @gateway.capture(@amount, response.authorization, @options) assert_success response assert response.test? assert response.message[/this is a demo/i] end def test_successful_authorization_and_partial_capture @gateway.expects(:ssl_post).returns(successful_authorization_response) assert response = @gateway.authorize(@amount, @credit_card, @options) assert_success response assert_equal TEST_AUTHORIZATION_GUWID, response.authorization @gateway.expects(:ssl_post).returns(successful_capture_response) assert response = @gateway.capture(@amount - 10, response.authorization, @options) assert_success response assert response.test? assert response.message[/this is a demo/i] end def test_unauthorized_capture @gateway.expects(:ssl_post).returns(unauthorized_capture_response) assert response = @gateway.capture(@amount, "1234567890123456789012", @options) assert_failure response assert_equal TEST_CAPTURE_GUWID, response.authorization assert response.message["Could not find referenced transaction for GuWID 1234567890123456789012."] end def test_no_error_if_no_state_is_provided_in_address options = @options.merge(:billing_address => @address_without_state) @gateway.expects(:ssl_post).returns(unauthorized_capture_response) assert_nothing_raised do @gateway.authorize(@amount, @credit_card, options) end end def test_no_error_if_no_address_provided @options.delete(:billing_address) @gateway.expects(:ssl_post).returns(unauthorized_capture_response) assert_nothing_raised do @gateway.authorize(@amount, @credit_card, @options) end end def test_description_trucated_to_32_chars_in_authorize options = {:description => "32chars-------------------------EXTRA"} stub_comms do @gateway.authorize(@amount, @credit_card, options) end.check_request do |endpoint, data, headers| assert_match(/<FunctionID>32chars-------------------------<\/FunctionID>/, data) end.respond_with(successful_authorization_response) end def test_description_trucated_to_32_chars_in_purchase options = {:description => "32chars-------------------------EXTRA"} stub_comms do @gateway.purchase(@amount, @credit_card, options) end.check_request do |endpoint, data, headers| assert_match(/<FunctionID>32chars-------------------------<\/FunctionID>/, data) end.respond_with(successful_purchase_response) end private # Authorization success def successful_authorization_response <<-XML <?xml version="1.0" encoding="UTF-8"?> <WIRECARD_BXML xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xsi:noNamespaceSchemaLocation="wirecard.xsd"> <W_RESPONSE> <W_JOB> <JobID>test dummy data</JobID> <FNC_CC_PREAUTHORIZATION> <FunctionID>Wirecard remote test purchase</FunctionID> <CC_TRANSACTION> <TransactionID>1</TransactionID> <PROCESSING_STATUS> <GuWID>C822580121385121429927</GuWID> <AuthorizationCode>709678</AuthorizationCode> <Info>THIS IS A DEMO TRANSACTION USING CREDIT CARD NUMBER 420000****0000. NO REAL MONEY WILL BE TRANSFERED.</Info> <StatusType>INFO</StatusType> <FunctionResult>ACK</FunctionResult> <TimeStamp>2008-06-19 06:53:33</TimeStamp> </PROCESSING_STATUS> </CC_TRANSACTION> </FNC_CC_PREAUTHORIZATION> </W_JOB> </W_RESPONSE> </WIRECARD_BXML> XML end # Authorization failure # TODO: replace with real xml string here (current way seems to complicated) def wrong_creditcard_authorization_response error = <<-XML <ERROR> <Type>DATA_ERROR</Type> <Number>24997</Number> <Message>Credit card number not allowed in demo mode.</Message> <Advice>Only demo card number '4200000000000000' is allowed for VISA in demo mode.</Advice> </ERROR> XML result_node = '</FunctionResult>' auth = 'AuthorizationCode' successful_authorization_response.gsub('ACK', 'NOK') \ .gsub(result_node, result_node + error) \ .gsub(/<#{auth}>\w+<\/#{auth}>/, "<#{auth}><\/#{auth}>") \ .gsub(/<Info>.+<\/Info>/, '') end # Capture success def successful_capture_response <<-XML <?xml version="1.0" encoding="UTF-8"?> <WIRECARD_BXML xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xsi:noNamespaceSchemaLocation="wirecard.xsd"> <W_RESPONSE> <W_JOB> <JobID>test dummy data</JobID> <FNC_CC_CAPTURE> <FunctionID>Wirecard remote test purchase</FunctionID> <CC_TRANSACTION> <TransactionID>1</TransactionID> <PROCESSING_STATUS> <GuWID>C833707121385268439116</GuWID> <AuthorizationCode>915025</AuthorizationCode> <Info>THIS IS A DEMO TRANSACTION USING CREDIT CARD NUMBER 420000****0000. NO REAL MONEY WILL BE TRANSFERED.</Info> <StatusType>INFO</StatusType> <FunctionResult>ACK</FunctionResult> <TimeStamp>2008-06-19 07:18:04</TimeStamp> </PROCESSING_STATUS> </CC_TRANSACTION> </FNC_CC_CAPTURE> </W_JOB> </W_RESPONSE> </WIRECARD_BXML> XML end # Capture failure def unauthorized_capture_response <<-XML <?xml version="1.0" encoding="UTF-8"?> <WIRECARD_BXML xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xsi:noNamespaceSchemaLocation="wirecard.xsd"> <W_RESPONSE> <W_JOB> <JobID>test dummy data</JobID> <FNC_CC_CAPTURE> <FunctionID>Test dummy FunctionID</FunctionID> <CC_TRANSACTION> <TransactionID>a2783d471ccc98825b8c498f1a62ce8f</TransactionID> <PROCESSING_STATUS> <GuWID>C833707121385268439116</GuWID> <AuthorizationCode></AuthorizationCode> <StatusType>INFO</StatusType> <FunctionResult>NOK</FunctionResult> <ERROR> <Type>DATA_ERROR</Type> <Number>20080</Number> <Message>Could not find referenced transaction for GuWID 1234567890123456789012.</Message> </ERROR> <TimeStamp>2008-06-19 08:09:20</TimeStamp> </PROCESSING_STATUS> </CC_TRANSACTION> </FNC_CC_CAPTURE> </W_JOB> </W_RESPONSE> </WIRECARD_BXML> XML end # Purchase success def successful_purchase_response <<-XML <?xml version="1.0" encoding="UTF-8"?> <WIRECARD_BXML xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xsi:noNamespaceSchemaLocation="wirecard.xsd"> <W_RESPONSE> <W_JOB> <JobID>test dummy data</JobID> <FNC_CC_PURCHASE> <FunctionID>Wirecard remote test purchase</FunctionID> <CC_TRANSACTION> <TransactionID>1</TransactionID> <PROCESSING_STATUS> <GuWID>C865402121385575982910</GuWID> <AuthorizationCode>531750</AuthorizationCode> <Info>THIS IS A DEMO TRANSACTION USING CREDIT CARD NUMBER 420000****0000. NO REAL MONEY WILL BE TRANSFERED.</Info> <StatusType>INFO</StatusType> <FunctionResult>ACK</FunctionResult> <TimeStamp>2008-06-19 08:09:19</TimeStamp> </PROCESSING_STATUS> </CC_TRANSACTION> </FNC_CC_PURCHASE> </W_JOB> </W_RESPONSE> </WIRECARD_BXML> XML end # Purchase failure def wrong_creditcard_purchase_response <<-XML <?xml version="1.0" encoding="UTF-8"?> <WIRECARD_BXML xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance" xsi:noNamespaceSchemaLocation="wirecard.xsd"> <W_RESPONSE> <W_JOB> <JobID>test dummy data</JobID> <FNC_CC_PURCHASE> <FunctionID>Wirecard remote test purchase</FunctionID> <CC_TRANSACTION> <TransactionID>1</TransactionID> <PROCESSING_STATUS> <GuWID>C824697121385153203112</GuWID> <AuthorizationCode></AuthorizationCode> <StatusType>INFO</StatusType> <FunctionResult>NOK</FunctionResult> <ERROR> <Type>DATA_ERROR</Type> <Number>24997</Number> <Message>Credit card number not allowed in demo mode.</Message> <Advice>Only demo card number '4200000000000000' is allowed for VISA in demo mode.</Advice> </ERROR> <TimeStamp>2008-06-19 06:58:51</TimeStamp> </PROCESSING_STATUS> </CC_TRANSACTION> </FNC_CC_PURCHASE> </W_JOB> </W_RESPONSE> </WIRECARD_BXML> XML end end
37.37785
130
0.652985
bb7c07b2c5242034131e7dace65a5142bdf44b07
1,026
require 'spec_helper' require_relative '../../../../lib/genome/core/helpers/property' RSpec.describe Genome::Core::Helpers::Property do subject(:test_klass) { Class.new { include Genome::Core::Helpers::Property } } let(:property_name) { :test_property } let(:property_parameters) { { param1: 'value_1', param2: 'value_2' } } context '::property_configs' do it 'sets a property' do test_klass.property property_name expect(test_klass.property_configs.key?(property_name)).to be true end it 'sets a property with attributes' do test_klass.property property_name, property_parameters expect(test_klass.property_configs[property_name].to_h).to eq(Genome::Core::Helpers::PropertyConfig.new(property_parameters).to_h) end it 'raises Genome::Error::DuplicateProperty for duplicate property name' do test_klass.property property_name expect { test_klass.property property_name }.to raise_error(Genome::Error::DuplicateProperty) end end end
30.176471
136
0.723197
0310cbb309b9942fc61d0da8d7b65aa1f9006aed
250
module BaconExpect; module Matcher class BeTrue def matches?(value) value == true end def fail!(subject, negated) raise FailedExpectation.new(FailMessageRenderer.message_for_be_true(negated, subject)) end end end; end
22.727273
92
0.712
acd1e8deb97af742a47f00793937a05c1cdf1f6a
741
module RedisRecord module Helpers def redis @redis ||= self.class.redis end def id @fields[:id] ||= SecureRandom.hex(10) end def persisted? find_by(:id, id) end def to_param persisted? ? id : nil end def new_record? to_param ? false : true end def attributes @fields.dup end def namespace self.class.namespace end private def find_by(atr, value) self.class.find_by(atr, value) end def key self.class.key(id) end def normalize_key(key) key.to_sym end def normalize_value(value) value.to_s end def get_type(name) self.class.types[name.to_sym] end end end
13.722222
43
0.576248
112e8e698c82cc0e212f0926f7d9b0ffec8716fe
1,543
# # Copyright:: 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-cli/helpers" RSpec.shared_context "fixture cookbooks checksums" do def id_to_dotted(sha1_id) major = sha1_id[0...14] minor = sha1_id[14...28] patch = sha1_id[28..40] decimal_integers = [major, minor, patch].map { |hex| hex.to_i(16) } decimal_integers.join(".") end let(:cookbook_foo_cksum) { "f24326bbf81d67fcab6a5615c75092d1c6da81cc" } let(:cookbook_foo_cksum_dotted) { id_to_dotted(cookbook_foo_cksum) } let(:cookbook_bar_cksum) { "4c538def500b75e744a3af05df66afd04dc3b3c5" } let(:cookbook_bar_cksum_dotted) { id_to_dotted(cookbook_bar_cksum) } let(:cookbook_baz_cksum) { "5c9063efbc5b5d8acc37024d7383f7dd010ae728" } let(:cookbook_baz_cksum_dotted) { id_to_dotted(cookbook_baz_cksum) } let(:cookbook_dep_of_bar_cksum) { "a4a6a5e4c6d95a580d291f6415d55b010669feac" } let(:cookbook_dep_of_bar_cksum_dotted) { id_to_dotted(cookbook_dep_of_bar_cksum) } end
32.829787
84
0.760855
7960db1bfee3826f0114b89e5257595963948aa6
613
# frozen_string_literal: true module AllinsonFlex class DynamicSchema < ApplicationRecord belongs_to :context belongs_to :profile before_destroy :check_for_works serialize :schema, JSON validates :allinson_flex_class, :schema, presence: true delegate :profile_version, to: :profile private def check_for_works return if allinson_flex_class.constantize.where(dynamic_schema_tesim: id.to_s).blank? errors.add( :base, "There are works using #{name}. This dynamic_schema cannot be deleted." ) throw :abort end end end
25.541667
93
0.69168
625b85db2dbe46087fc63217abd81898d4afb23d
182
class UserNoms < ActiveRecord::Migration def change create_table :user_noms do |t| t.integer :giver_id t.integer :consumer_id t.timestamps end end end
16.545455
40
0.67033
01d931bf081d527a6e7354c7920e62dad218384f
139
class AddArchivedAtToUseAgreement < ActiveRecord::Migration def change add_column :use_agreements, :archived_at, :datetime end end
23.166667
59
0.798561
ff923fbf529ae7e43535130aa676905e43a56d86
195
module CodeRay module Scanners load :html # XML Scanner # # $Id$ # # Currently this is the same scanner as Scanners::HTML. class XML < HTML register_for :xml end end end
10.263158
57
0.646154
ff5406f50423b39ae0a4e570af8eceb374df254e
457
default['duosecurity']['install_type'] = 'source' default['duosecurity']['package_action'] = 'upgrade' default['duosecurity']['source_sha256'] = 'e2df2be50539c54c87cdc4964fdfee0fbd79a3f15fdfd807e94941291b5d6197' default['duosecurity']['source_version'] = '1.10.1' default['duosecurity']['use_pam'] = 'no' default['duosecurity']['protect_sudo'] = 'no' default['duosecurity']['use_duo_repo'] = 'no' default['duosecurity']['apt']['keyserver'] = 'pgp.mit.edu'
45.7
108
0.73523
082cdbaa30d8a1c124efc180447bbcd4474d0017
181
class CreateAPIKeys < ActiveRecord::Migration def change create_table :api_keys do |t| t.string :name t.string :access_token t.timestamps end end end
16.454545
45
0.668508
084b59099529e131bf7965c8efa850234e5d07d6
1,656
# Copyright (c) 2008-2013 Michael Dvorkin and contributors. # # Fat Free CRM is freely distributable under the terms of MIT license. # See MIT-LICENSE file or http://www.opensource.org/licenses/mit-license.php #------------------------------------------------------------------------------ require File.expand_path(File.dirname(__FILE__) + '/../../spec_helper') describe "/home/options" do before do login_and_assign end it "should render [options] template into :options div and show it" do params[:cancel] = nil assign(:asset, "all") assign(:user, "all_users") assign(:action, "all_actions") assign(:duration, "two_days") assign(:all_users, [FactoryGirl.build_stubbed(:user)]) render expect(rendered).to include("$('#options').html") expect(rendered).to include("$(\\'#asset\\').html(\\'campaign\\')") expect(rendered).to include("crm.flip_form('options')") expect(rendered).to include("crm.set_title('title', 'Recent Activity Options')") end it "should load :options partial with JavaScript code for menus" do params[:cancel] = nil assign(:asset, "all") assign(:action, "all_actions") assign(:user, "all_users") assign(:duration, "two_days") assign(:all_users, [FactoryGirl.build_stubbed(:user)]) render expect(view).to render_template(partial: "_options") end it "should hide options form on Cancel" do params[:cancel] = "true" render expect(rendered).not_to include("$('#options').html") expect(rendered).to include("crm.flip_form('options')") expect(rendered).to include("crm.set_title('title', 'Recent Activity')") end end
31.846154
84
0.649155
335c15df8fb232b1c23834453be4f06576826abb
209
class Label # Accessible properties attr_accessor :name, :link_url # Initialize properties def initialize(entry) @name = entry.fields[:name] @link_url = entry.fields[:link_url] end end
14.928571
39
0.69378
01a7c958be1ec6c9ae849805859b310f7801988b
74
# frozen_string_literal: true module UseCaseFlow VERSION = '1.0.0' end
12.333333
29
0.743243
031be181ca3dd3a5253fa5836ac8c0648e589056
1,731
Rails.application.routes.draw do resources :users root 'pages#home' get 'subscribe' => 'users#new', as: 'subscribe' get 'pages/api/:zip' => 'pages#api' # The priority is based upon order of creation: first created -> highest priority. # See how all your routes lay out with "rake routes". # You can have the root of your site routed with "root" # root 'welcome#index' # Example of regular route: # get 'products/:id' => 'catalog#view' # Example of named route that can be invoked with purchase_url(id: product.id) # get 'products/:id/purchase' => 'catalog#purchase', as: :purchase # Example resource route (maps HTTP verbs to controller actions automatically): # resources :products # Example resource route with options: # resources :products do # member do # get 'short' # post 'toggle' # end # # collection do # get 'sold' # end # end # Example resource route with sub-resources: # resources :products do # resources :comments, :sales # resource :seller # end # Example resource route with more complex sub-resources: # resources :products do # resources :comments # resources :sales do # get 'recent', on: :collection # end # end # Example resource route with concerns: # concern :toggleable do # post 'toggle' # end # resources :posts, concerns: :toggleable # resources :photos, concerns: :toggleable # Example resource route within a namespace: # namespace :admin do # # Directs /admin/products/* to Admin::ProductsController # # (app/controllers/admin/products_controller.rb) # resources :products # end end
27.046875
84
0.644714
285dee4ad5adba92658a1ba1fa54b7bbb039e176
1,560
require_relative 'event_relay' module Metro class EventStateManager def initialize @current_state = [] end attr_accessor :window attr_reader :current_state # # Clear all the event relays of the current game state # def clear current_state.clear end # # Fire events for held buttons within the current game state # def fire_events_for_held_buttons current_state.each {|cs| cs.fire_events_for_held_buttons } end # # Fire events for mouse events within the current game state # def fire_events_for_mouse_movement current_state.each {|cs| cs.fire_events_for_mouse_movement } end # # Fire events for button up for the current game state # def fire_button_up(id) current_state.each {|cs| cs.fire_button_up(id) } end # # Fire events for button down within the current game state # def fire_button_down(id) current_state.each {|cs| cs.fire_button_down(id) } end # # Fire notification events within the current game state # def fire_events_for_notification(event,sender) current_state.each {|cs| cs.fire_events_for_notification(event,sender) } end # # An an event relay to the current game state # def add_events_for_target(target,events) relay = EventRelay.new(target,window) events.each do |target_event| relay.send target_event.event, *target_event.buttons, &target_event.block end current_state.push relay end end end
22.285714
81
0.678205
91b142d5da2aa7ab65031f78bbfa4d4581989a79
2,712
require 'spec_helper' describe Chicago::ETL::LoadDatasetBuilder do let(:db) { double(:database).as_null_object } before :each do db.stub(:[]).with(:original_users). and_return(TEST_DB[:original_users]) db.stub(:[]).with(:original_preferences). and_return(TEST_DB[:original_preferences]) db[:original_users].stub(:columns). and_return([:id, :name, :email]) db[:original_preferences].stub(:columns). and_return([:id, :spam]) end it "selects from the specified table" do subject.table(:original_users) subject.build(db, [:name]).opts[:from].should == [:original_users] end it "selects the columns from the table" do subject.configure { table(:original_users) } subject.build(db, [:id, :name]).opts[:select].should == [:id.qualify(:original_users), :name.qualify(:original_users)] end it "can handle column renaming" do subject.configure do table :original_users provide :original_id, :id end subject.build(db, [:original_id, :name]).opts[:select]. should == [:id.qualify(:original_users).as(:original_id), :name.qualify(:original_users)] end it "can provide constructed columns" do subject.configure do table :original_users provide :original_id, :foo.qualify(:bar) end subject.build(db, [:original_id, :name]).opts[:select]. should == [:foo.qualify(:bar).as(:original_id), :name.qualify(:original_users)] end it "left outer joins a denormalized table" do subject.configure do table :original_users denormalize :original_preferences, :id => :id end subject.build(db, [:id, :name]).sql.should =~ /LEFT OUTER JOIN `original_preferences` ON \(`original_preferences`.`id` = `original_users`.`id`\)/ end it "takes columns from the appropriate tables where possible" do subject.configure do table :original_users denormalize :original_preferences, :id => :id end subject.build(db, [:id, :name, :spam]).opts[:select]. should == [:id.qualify(:original_users), :name.qualify(:original_users), :spam.qualify(:original_preferences)] end it "takes renames columns from denormalized tables" do subject.configure do table :original_users denormalize :original_preferences, :id => :id provide :email_allowed, :spam end subject.build(db, [:id, :name, :email_allowed]).opts[:select]. should include(:spam.qualify(:original_preferences).as(:email_allowed)) end it "automatically renames ids of denormalized tables" do subject.configure do table :original_users denormalize :original_preferences, :id => :id end end end
31.172414
149
0.673304
d5c267585b68120211669e4c95db2137b211b5d6
179
class RemoveUniqueNameIndexFromProjectStatus < ActiveRecord::Migration def change remove_index :project_statuses, :name if index_exists?(:project_statuses, :name) end end
29.833333
84
0.810056
01165072bd50e7124d6efa3c5166f4e8897cea4b
1,914
control 'VCST-67-000030' do title 'The Security Token Service must set the secure flag for cookies.' desc "The secure flag is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure flag is to prevent cookies from being observed by unauthorized parties due to the transmission of the cookie in clear text. By setting the secure flag, the browser will prevent the transmission of a cookie over an unencrypted channel. The Security Token Service is configured to only be accessible over a TLS tunnel, but this cookie flag is still a recommended best practice." desc 'rationale', '' desc 'check', " Connect to the PSC, whether external or embedded. At the command prompt, execute the following command: # xmllint --format /usr/lib/vmware-sso/vmware-sts/conf/web.xml | sed '2 s/xmlns=\".*\"//g' | xmllint --xpath '/web-app/session-config/cookie-config/secure' - Expected result: <secure>true</secure> If the output of the command does not match the expected result, this is a finding. " desc 'fix', " Connect to the PSC, whether external or embedded. Navigate to and open /usr/lib/vmware-sso/vmware-sts/conf/web.xml. Navigate to the /<web-apps>/<session-config>/<cookie-config> node and configure it as follows: <cookie-config> <http-only>true</http-only> <secure>true</secure> </cookie-config> " impact 0.5 tag severity: 'medium' tag gtitle: 'SRG-APP-000439-WSR-000155' tag gid: 'V-239681' tag rid: 'SV-239681r816768_rule' tag stig_id: 'VCST-67-000030' tag fix_id: 'F-42873r816767_fix' tag cci: ['CCI-002418'] tag nist: ['SC-8'] describe xml("#{input('webXmlPath')}") do its('/web-app/session-config/cookie-config/secure') { should cmp 'true' } end end
34.8
80
0.685475
28130f03655a053aa883c65e6f28dcee7f1d55ef
2,506
require "spec_helper" describe Volunteer do describe '#name' do it 'returns the name of the volunteer' do test_volunteer = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil}) expect(test_volunteer.name).to eq 'Jane' end end describe '#project_id' do it 'returns the project_id of the volunteer' do test_volunteer = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil}) expect(test_volunteer.project_id).to eq 1 end end describe '#==' do it 'checks for equality based on the name of a volunteer' do volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil}) volunteer2 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil}) expect(volunteer1 == volunteer2).to eq true end end context '.all' do it 'is empty to start' do expect(Volunteer.all).to eq [] end it 'returns all volunteers' do volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil}) volunteer1.save volunteer2 = Volunteer.new({:name => 'Joe', :project_id => 1, :id => nil}) volunteer2.save expect(Volunteer.all).to eq [volunteer1, volunteer2] end end describe '#save' do it 'adds a volunteer to the database' do volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil}) volunteer1.save expect(Volunteer.all).to eq [volunteer1] end end describe '.find' do it 'returns a volunteer by id' do volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil}) volunteer1.save volunteer2 = Volunteer.new({:name => 'Joe', :project_id => 1, :id => nil}) volunteer2.save expect(Volunteer.find(volunteer1.id)).to eq volunteer1 end end describe '#delete' do it 'deletes a volunteer from database' do volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil}) volunteer1.save volunteer2 = Volunteer.new({:name => 'Joe', :project_id => 1, :id => nil}) volunteer2.save volunteer2.delete expect(Volunteer.all).to eq [volunteer1] end end describe '.clear' do it 'clears out volunteer database' do volunteer1 = Volunteer.new({:name => 'Jane', :project_id => 1, :id => nil}) volunteer1.save volunteer2 = Volunteer.new({:name => 'Joe', :project_id => 1, :id => nil}) volunteer2.save Volunteer.clear expect(Volunteer.all).to eq [] end end end
30.560976
85
0.613727
79aed0847e9a091a9e3ece469083a71e0520a9ff
978
cask 'bettertouchtool' do if MacOS.version <= :mavericks version '2.05' sha256 '41013cfeffee286a038363651db3dd315ff3a1e0cf07774d9ce852111be50a5a' # bettertouchtool.net/releases was verified as official when first introduced to the cask url "https://bettertouchtool.net/releases/btt#{version}_final_10_9.zip" else version '2.756' sha256 '23848a8fb3fd9a697a5fcba47d2bc8214cba5a14f0f054d1b1ff7869a740d4bc' # bettertouchtool.net/releases was verified as official when first introduced to the cask url "https://bettertouchtool.net/releases/btt#{version}.zip" appcast 'https://bettertouchtool.net/releases/' end name 'BetterTouchTool' homepage 'https://folivora.ai/' auto_updates true app 'BetterTouchTool.app' uninstall login_item: 'BetterTouchTool' zap trash: [ '~/Library/Preferences/com.hegenberg.BetterTouchTool.plist', '~/Library/Application Support/BetterTouchTool', ] end
31.548387
93
0.735174
bb2ae20c3d34cb99f23b070dae2373301e61ccb3
488
cask "cmdtap" do version "1.9.4" sha256 "7e31179f044f3a834ea51daf250ad5085d6c8ea4bbabb8c1b193cff103d3f5ea" url "https://www.yingdev.com/Content/Projects/CmdTap/Release/#{version}/CmdTap.zip" name "CmdTap" desc "Adds other functions to Task Switcher" homepage "https://www.yingdev.com/projects/cmdtap" livecheck do url "https://www.yingdev.com/projects/cmdtap" strategy :page_match regex(%r{href=.*?/(\d+(?:\.\d+)+)/CmdTap\.zip}i) end app "CmdTap.app" end
27.111111
85
0.711066
abb5b719e4d47d10840d29a832c64557ccce81ac
825
class ContentController < Api::BaseController before_action :validate_params! def show filter = api_request.to_filter content = Finders::Content.call(filter: filter) @content_items = content[:results] @page = content[:page] @total_pages = content[:total_pages] @total_results = content[:total_results] end private def api_request @api_request ||= Api::ContentRequest.new(permitted_params) end def permitted_params params.permit(:from, :to, :organisation_id, :document_type, :format, :page, :page_size, :date_range, :search_term, :sort) end def validate_params! unless api_request.valid? error_response( "validation-error", title: "One or more parameters is invalid", invalid_params: api_request.errors.to_hash, ) end end end
24.264706
125
0.698182
26477a19fd914c4f83aa6e58ce9c529ad45d9722
11,694
# Copyright (C) 2014-2019 MongoDB, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. module Mongo # Represents a single server on the server side that can be standalone, part of # a replica set, or a mongos. # # @since 2.0.0 class Server extend Forwardable include Monitoring::Publishable include Event::Publisher # The default time in seconds to timeout a connection attempt. # # @since 2.4.3 CONNECT_TIMEOUT = 10.freeze # Instantiate a new server object. Will start the background refresh and # subscribe to the appropriate events. # # @api private # # @example Initialize the server. # Mongo::Server.new('127.0.0.1:27017', cluster, monitoring, listeners) # # @note Server must never be directly instantiated outside of a Cluster. # # @param [ Address ] address The host:port address to connect to. # @param [ Cluster ] cluster The cluster the server belongs to. # @param [ Monitoring ] monitoring The monitoring. # @param [ Event::Listeners ] event_listeners The event listeners. # @param [ Hash ] options The server options. # # @option options [ Boolean ] :monitor For internal driver use only: # whether to monitor the server after instantiating it. # @option options [ true, false ] :monitoring_io For internal driver # use only. Set to false to prevent SDAM-related I/O from being # done by this server. Note: setting this option to false will make # the server non-functional. It is intended for use in tests which # manually invoke SDAM state transitions. # # @since 2.0.0 def initialize(address, cluster, monitoring, event_listeners, options = {}) @address = address @cluster = cluster @monitoring = monitoring options = options.dup monitor = options.delete(:monitor) @options = options.freeze @event_listeners = event_listeners @monitor = Monitor.new(address, event_listeners, monitoring, options.merge(app_metadata: Monitor::AppMetadata.new(cluster.options))) unless monitor == false start_monitoring end @connected = true end # @return [ String ] The configured address for the server. attr_reader :address # @return [ Cluster ] cluster The server cluster. attr_reader :cluster # @return [ Monitor ] monitor The server monitor. attr_reader :monitor # @return [ Hash ] The options hash. attr_reader :options # @return [ Monitoring ] monitoring The monitoring. attr_reader :monitoring # Get the description from the monitor and scan on monitor. def_delegators :monitor, :description, :scan!, :heartbeat_frequency, :last_scan, :compressor alias :heartbeat_frequency_seconds :heartbeat_frequency # Delegate convenience methods to the monitor description. def_delegators :description, :arbiter?, :features, :ghost?, :max_wire_version, :max_write_batch_size, :max_bson_object_size, :max_message_size, :tags, :average_round_trip_time, :mongos?, :other?, :primary?, :replica_set_name, :secondary?, :standalone?, :unknown?, :last_write_date, :logical_session_timeout # Get the app metadata from the cluster. def_delegators :cluster, :app_metadata, :cluster_time, :update_cluster_time def_delegators :features, :check_driver_support! # Is this server equal to another? # # @example Is the server equal to the other? # server == other # # @param [ Object ] other The object to compare to. # # @return [ true, false ] If the servers are equal. # # @since 2.0.0 def ==(other) return false unless other.is_a?(Server) address == other.address end # Get a new context for this server in which to send messages. # # @example Get the server context. # server.context # # @return [ Mongo::Server::Context ] context The server context. # # @since 2.0.0 # # @deprecated Will be removed in version 3.0 def context Context.new(self) end # Determine if a connection to the server is able to be established and # messages can be sent to it. # # @example Is the server connectable? # server.connectable? # # @return [ true, false ] If the server is connectable. # # @since 2.1.0 # # @deprecated No longer necessary with Server Selection specification. def connectable?; end # Disconnect the server from the connection. # # @example Disconnect the server. # server.disconnect! # # @param [ Boolean ] wait Whether to wait for background threads to # finish running. # # @return [ true ] Always true with no exception. # # @since 2.0.0 def disconnect!(wait=false) pool.disconnect! monitor.stop!(wait) @connected = false true end # Whether the server is connected. # # @return [ true|false ] Whether the server is connected. # # @api private # @since 2.7.0 def connected? @connected end # When the server is flagged for garbage collection, stop the monitor # thread. # # @example Finalize the object. # Server.finalize(monitor) # # @param [ Server::Monitor ] monitor The server monitor. # # @since 2.2.0 def self.finalize(monitor) proc { monitor.stop! } end # Start monitoring the server. # # Used internally by the driver to add a server to a cluster # while delaying monitoring until the server is in the cluster. # # @api private def start_monitoring publish_sdam_event( Monitoring::SERVER_OPENING, Monitoring::Event::ServerOpening.new(address, cluster.topology) ) if options[:monitoring_io] != false monitor.run! ObjectSpace.define_finalizer(self, self.class.finalize(monitor)) end end # Get a pretty printed server inspection. # # @example Get the server inspection. # server.inspect # # @return [ String ] The nice inspection string. # # @since 2.0.0 def inspect "#<Mongo::Server:0x#{object_id} address=#{address.host}:#{address.port}>" end # @note This method is experimental and subject to change. # # @api experimental # @since 2.7.0 def summary status = case when primary? 'PRIMARY' when secondary? 'SECONDARY' when standalone? 'STANDALONE' when arbiter? 'ARBITER' when ghost? 'GHOST' when other? 'OTHER' end if replica_set_name status += " replica_set=#{replica_set_name}" end address_bit = if address "#{address.host}:#{address.port}" else 'nil' end "#<Server address=#{address_bit} #{status}>" end # Get the connection pool for this server. # # @example Get the connection pool for the server. # server.pool # # @return [ Mongo::Server::ConnectionPool ] The connection pool. # # @since 2.0.0 def pool @pool ||= cluster.pool(self) end # Determine if the provided tags are a subset of the server's tags. # # @example Are the provided tags a subset of the server's tags. # server.matches_tag_set?({ 'rack' => 'a', 'dc' => 'nyc' }) # # @param [ Hash ] tag_set The tag set to compare to the server's tags. # # @return [ true, false ] If the provided tags are a subset of the server's tags. # # @since 2.0.0 def matches_tag_set?(tag_set) tag_set.keys.all? do |k| tags[k] && tags[k] == tag_set[k] end end # Restart the server monitor. # # @example Restart the server monitor. # server.reconnect! # # @return [ true ] Always true. # # @since 2.1.0 def reconnect! monitor.restart! @connected = true end # Execute a block of code with a connection, that is checked out of the # server's pool and then checked back in. # # @example Send a message with the connection. # server.with_connection do |connection| # connection.dispatch([ command ]) # end # # @return [ Object ] The result of the block execution. # # @since 2.3.0 def with_connection(&block) pool.with_connection(&block) end # Handle handshake failure. # # @since 2.7.0 # @api private def handle_handshake_failure! yield rescue Mongo::Error::SocketError, Mongo::Error::SocketTimeoutError unknown! raise end # Handle authentication failure. # # @example Handle possible authentication failure. # server.handle_auth_failure! do # Auth.get(user).login(self) # end # # @raise [ Auth::Unauthorized ] If the authentication failed. # # @return [ Object ] The result of the block execution. # # @since 2.3.0 def handle_auth_failure! yield rescue Mongo::Error::SocketTimeoutError # possibly cluster is slow, do not give up on it raise rescue Mongo::Error::SocketError # non-timeout network error unknown! pool.disconnect! raise rescue Auth::Unauthorized # auth error, keep server description and topology as they are pool.disconnect! raise end # Will writes sent to this server be retried. # # @example Will writes be retried. # server.retry_writes? # # @return [ true, false ] If writes will be retried. # # @note Retryable writes are only available on server versions 3.6+ and with # sharded clusters or replica sets. # # @since 2.5.0 def retry_writes? !!(features.sessions_enabled? && logical_session_timeout && !standalone?) end # Marks server unknown and publishes the associated SDAM event # (server description changed). # # @since 2.4.0, SDAM events are sent as of version 2.7.0 def unknown! # Just dispatch the description changed event here, SDAM flow # will update description on the server without in-place mutations # and invoke SDAM transitions as needed. publish(Event::DESCRIPTION_CHANGED, description, Description.new(address)) end # @api private def update_description(description) monitor.instance_variable_set('@description', description) end end end require 'mongo/server/app_metadata' require 'mongo/server/connectable' require 'mongo/server/connection' require 'mongo/server/connection_pool' require 'mongo/server/context' require 'mongo/server/description' require 'mongo/server/monitor' require 'mongo/server/round_trip_time_averager'
28.945545
85
0.624594
f76b29226351a3fdb3e7d229ac98daf91429e39e
271
module Playable # Override if the current instance maps to multiple playable actions def playable_actions [playable_action] end # Override if the current instance maps to a single playable action def playable_action raise NotImplementedError end end
22.583333
70
0.778598
d5498f5c9c1181cf6ed8490d283dfea330776b3e
663
# Be sure to restart your server when you modify this file. # Your secret key is used for verifying the integrity of signed cookies. # If you change this key, all old signed cookies will become invalid! # Make sure the secret is at least 30 characters and all random, # no regular words or you'll be exposed to dictionary attacks. # You can use `rake secret` to generate a secure secret key. # Make sure your secret_key_base is kept private # if you're sharing your code publicly. PdrServer::Application.config.secret_key_base = 'a9c074f6ba99338c7c50a0664958a5f5fffeaf0370583aacd489da8a9f6eff3ac61ddd7bf098d070ecc832efbff18e3571536f3c3ee4c6938d14cf4308f78c8d'
51
178
0.815988
ac9f340520d8c09e5f7f60c5fe362d651d86eac3
127
object @domain attributes :id, :name, :type child :records => :records do attributes :id, :name, :type, :content, :prio end
18.142857
47
0.685039