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
6aeba6be0c119682d570a260aec9aaba8bcee8e4
686
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # http://www.morningstarsecurity.com/research/whatweb ## Plugin.define "Intrinsyc-deviceWEB" do author "Brendan Coles <[email protected]>" # 2013-07-28 version "0.1" description "Intrinsyc deviceWEB - a web server specialized for embedded devices" website "http://www.intrinsyc.com/" # ShodanHQ results # 2013-07-28 # 82 for Intrinsyc deviceWEB # Matches # matches [ # Version Detection # HTTP Server Header { :search=>"headers[server]", :version=>/^Intrinsyc deviceWEB v([\d\.]+)$/ }, ] end
25.407407
81
0.739067
6a481560bb3f5b51cd940b8bd9884423314c5abf
421
# frozen_string_literal: true # os detection module OS def self.windows? (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil end def self.mac? (/darwin/ =~ RUBY_PLATFORM) != nil end def self.unix? !OS.windows? end def self.linux? OS.unix? && !OS.mac? end end def get_nodejs_platform if OS.windows? 'win32' elsif OS.mac? 'darwin' else 'linux' end end
13.580645
67
0.624703
e9d47764a916ea6a4ea6d88135d92485dd757a03
1,714
# Generated by jeweler # DO NOT EDIT THIS FILE DIRECTLY # Instead, edit Jeweler::Tasks in Rakefile, and run 'rake gemspec' # -*- encoding: utf-8 -*- Gem::Specification.new do |s| s.name = %q{statsd-ruby} s.version = "0.3.0.github.1" s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version= s.authors = ["Rein Henrichs"] s.date = %q{2011-06-24} s.description = %q{A Statsd client in Ruby} s.email = %q{[email protected]} s.extra_rdoc_files = [ "LICENSE.txt", "README.rdoc" ] s.files = [ ".document", "LICENSE.txt", "README.rdoc", "Rakefile", "VERSION", "lib/statsd.rb", "spec/helper.rb", "spec/statsd_spec.rb", "statsd-ruby.gemspec" ] s.homepage = %q{http://github.com/reinh/statsd} s.licenses = ["MIT"] s.require_paths = ["lib"] s.rubygems_version = %q{1.3.9.1} s.summary = %q{A Statsd client in Ruby} if s.respond_to? :specification_version then s.specification_version = 3 if Gem::Version.new(Gem::VERSION) >= Gem::Version.new('1.2.0') then s.add_development_dependency(%q<minitest>, [">= 0"]) s.add_development_dependency(%q<yard>, ["~> 0.6.0"]) s.add_development_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_development_dependency(%q<rcov>, [">= 0"]) else s.add_dependency(%q<minitest>, [">= 0"]) s.add_dependency(%q<yard>, ["~> 0.6.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end else s.add_dependency(%q<minitest>, [">= 0"]) s.add_dependency(%q<yard>, ["~> 0.6.0"]) s.add_dependency(%q<jeweler>, ["~> 1.5.2"]) s.add_dependency(%q<rcov>, [">= 0"]) end end
29.551724
105
0.607351
18270f19d0b429ef539fedeb28c8e10662b01622
2,138
# frozen_string_literal: true require_relative '../../../step/buy_sell_par_shares' require_relative 'par_and_buy_actions' module Engine module Game module G1893 module Step class BuySellParSharesFollowingSr < Engine::Step::BuySellParShares def can_buy?(_entity, bundle) super && @game.buyable?(bundle.corporation) end def can_sell?(_entity, bundle) return !bought? if bundle.corporation == @game.adsk super && @game.buyable?(bundle.corporation) end def can_gain?(_entity, bundle, exchange: false) return false if exchange super && @game.buyable?(bundle.corporation) end def can_exchange?(_entity) false end include ParAndBuy def process_sell_shares(action) if action.bundle.corporation == @game.adsk sell_adsk(action.bundle) else # In case president's share is reserved, do not change presidency allow_president_change = action.bundle.corporation.presidents_share.buyable sell_shares(action.entity, action.bundle, swap: action.swap, allow_president_change: allow_president_change) end @round.last_to_act = action.entity @current_actions << action end private def sell_adsk(bundle) entity = bundle.owner price = bundle.price @log << "#{entity.name} sell #{bundle.percent}% " \ "of #{bundle.corporation.name} and receives #{@game.format_currency(price)}" @game.share_pool.transfer_shares(bundle, @game.share_pool, spender: @bank, receiver: entity, price: price, allow_president_change: false) end end end end end end
32.393939
103
0.527128
f852e425891ed8e350cb702e4b5d99093b926a5b
1,895
class SnippetsController < ApplicationController before_filter :authenticate_user! before_filter :project before_filter :snippet, only: [:show, :edit, :destroy, :update, :raw] layout "project" # Authorize before_filter :add_project_abilities # Allow read any snippet before_filter :authorize_read_snippet! # Allow write(create) snippet before_filter :authorize_write_snippet!, only: [:new, :create] # Allow modify snippet before_filter :authorize_modify_snippet!, only: [:edit, :update] # Allow destroy snippet before_filter :authorize_admin_snippet!, only: [:destroy] respond_to :html def index @snippets = @project.snippets end def new @snippet = @project.snippets.new end def create @snippet = @project.snippets.new(params[:snippet]) @snippet.author = current_user @snippet.save if @snippet.valid? redirect_to [@project, @snippet] else respond_with(@snippet) end end def edit end def update @snippet.update_attributes(params[:snippet]) if @snippet.valid? redirect_to [@project, @snippet] else respond_with(@snippet) end end def show @note = @project.notes.new(noteable: @snippet) render_full_content end def destroy return access_denied! unless can?(current_user, :admin_snippet, @snippet) @snippet.destroy redirect_to project_snippets_path(@project) end def raw send_data( @snippet.content, type: "text/plain", disposition: 'inline', filename: @snippet.file_name ) end protected def snippet @snippet ||= @project.snippets.find(params[:id]) end def authorize_modify_snippet! return render_404 unless can?(current_user, :modify_snippet, @snippet) end def authorize_admin_snippet! return render_404 unless can?(current_user, :admin_snippet, @snippet) end end
20.376344
77
0.698681
185e426012b403b172fd6141a331b1106091d978
5,381
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. require 'date' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # Specifies the compartment to move the dedicated virtual machine host to. class Core::Models::ChangeDedicatedVmHostCompartmentDetails # **[Required]** The [OCID](https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the compartment # to move the dedicated virtual machine host to. # # @return [String] attr_accessor :compartment_id # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'compartment_id': :'compartmentId' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'compartment_id': :'String' # rubocop:enable Style/SymbolLiteral } end # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:disable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # Initializes the object # @param [Hash] attributes Model attributes in the form of hash # @option attributes [String] :compartment_id The value to assign to the {#compartment_id} property def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } self.compartment_id = attributes[:'compartmentId'] if attributes[:'compartmentId'] raise 'You cannot provide both :compartmentId and :compartment_id' if attributes.key?(:'compartmentId') && attributes.key?(:'compartment_id') self.compartment_id = attributes[:'compartment_id'] if attributes[:'compartment_id'] end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity # rubocop:enable Metrics/MethodLength, Layout/EmptyLines, Style/SymbolLiteral # rubocop:disable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # Checks equality by comparing each attribute. # @param [Object] other the other object to be compared def ==(other) return true if equal?(other) self.class == other.class && compartment_id == other.compartment_id end # rubocop:enable Metrics/CyclomaticComplexity, Metrics/AbcSize, Metrics/PerceivedComplexity, Layout/EmptyLines # @see the `==` method # @param [Object] other the other object to be compared def eql?(other) self == other end # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [compartment_id].hash end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # rubocop:disable Metrics/AbcSize, Layout/EmptyLines # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| if type =~ /^Array<(.*)>/i # check to ensure the input is an array given that the the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) public_method("#{key}=").call( attributes[self.class.attribute_map[key]] .map { |v| OCI::Internal::Util.convert_to_type(Regexp.last_match(1), v) } ) end elsif !attributes[self.class.attribute_map[key]].nil? public_method("#{key}=").call( OCI::Internal::Util.convert_to_type(type, attributes[self.class.attribute_map[key]]) ) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # rubocop:enable Metrics/AbcSize, Layout/EmptyLines # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = public_method(attr).call next if value.nil? && !instance_variable_defined?("@#{attr}") hash[param] = _to_hash(value) end hash end private # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end # rubocop:enable Lint/UnneededCopDisableDirective, Metrics/LineLength
34.49359
147
0.674596
2888cedcc2b4bb4df0b33dc61986f9c2ba999f31
523
class AuthenticationToken < ApplicationRecord DEFAULT_TTL = 2.weeks belongs_to :user validates :id, presence: true, length: {is: 8} validates :secret_digest, presence: true, length: {is: 64} before_create :set_expiration def expired? expires_at <= Time.zone.now end def revoked? revoked_at? end def revoke! update!(revoked_at: Time.zone.now) unless revoked? end private def set_expiration self.expires_at = created_at + DEFAULT_TTL unless self.expires_at.present? end end
18.678571
78
0.718929
61d66d774749016d806d099fcb4192376a1d3174
5,421
class Passenger < Formula desc "Server for Ruby, Python, and Node.js apps via Apache/NGINX" homepage "https://www.phusionpassenger.com/" url "https://github.com/phusion/passenger/releases/download/release-6.0.6/passenger-6.0.6.tar.gz" sha256 "fbf89ebfacc079bdf6466567eabc9eb741a5abd8f230133311f7a40fff763842" license "MIT" head "https://github.com/phusion/passenger.git", :branch => "stable-6.0" bottle do cellar :any sha256 "48e7ef980025088764027462024f76e53adbe65776a886d983fcd154bf2a820e" => :catalina sha256 "426d4d09cbcd5f4e557a0f251ba175717a80920e9947bf1785f24920125793bc" => :mojave sha256 "67b86b595e1a4a96b8209bbb9d5ce5cfb24dea86be98a970a7a1c4df193223af" => :high_sierra end # to build nginx module depends_on "nginx" => [:build, :test] depends_on "[email protected]" depends_on "pcre" def install if MacOS.version >= :mojave && MacOS::CLT.installed? ENV["SDKROOT"] = MacOS::CLT.sdk_path(MacOS.version) else ENV.delete("SDKROOT") end inreplace "src/ruby_supportlib/phusion_passenger/platform_info/openssl.rb" do |s| s.gsub! "-I/usr/local/opt/openssl/include", "-I#{Formula["[email protected]"].opt_include}" s.gsub! "-L/usr/local/opt/openssl/lib", "-L#{Formula["[email protected]"].opt_lib}" end system "rake", "apache2" system "rake", "nginx" nginx_addon_dir = `./bin/passenger-config about nginx-addon-dir`.strip mkdir "nginx" do system "tar", "-xf", "#{Formula["nginx"].opt_pkgshare}/src/src.tar.xz", "--strip-components", "1" args = (Formula["nginx"].opt_pkgshare/"src/configure_args.txt").read.split("\n") args << "--add-dynamic-module=#{nginx_addon_dir}" system "./configure", *args system "make" (libexec/"modules").install "objs/ngx_http_passenger_module.so" end (libexec/"download_cache").mkpath # Fixes https://github.com/phusion/passenger/issues/1288 rm_rf "buildout/libev" rm_rf "buildout/libuv" rm_rf "buildout/cache" necessary_files = %w[configure Rakefile README.md CONTRIBUTORS CONTRIBUTING.md LICENSE CHANGELOG package.json passenger.gemspec build bin doc images dev src resources buildout] cp_r necessary_files, libexec, :preserve => true # Allow Homebrew to create symlinks for the Phusion Passenger commands. bin.install_symlink Dir["#{libexec}/bin/*"] # Ensure that the Phusion Passenger commands can always find their library # files. locations_ini = `./bin/passenger-config --make-locations-ini --for-native-packaging-method=homebrew` locations_ini.gsub!(/=#{Regexp.escape Dir.pwd}/, "=#{libexec}") (libexec/"src/ruby_supportlib/phusion_passenger/locations.ini").write(locations_ini) ruby_libdir = `./bin/passenger-config about ruby-libdir`.strip ruby_libdir.gsub!(/^#{Regexp.escape Dir.pwd}/, libexec) system "./dev/install_scripts_bootstrap_code.rb", "--ruby", ruby_libdir, *Dir[libexec/"bin/*"] system "./bin/passenger-config", "compile-nginx-engine" cp Dir["buildout/support-binaries/nginx*"], libexec/"buildout/support-binaries", :preserve => true nginx_addon_dir.gsub!(/^#{Regexp.escape Dir.pwd}/, libexec) system "./dev/install_scripts_bootstrap_code.rb", "--nginx-module-config", libexec/"bin", "#{nginx_addon_dir}/config" man1.install Dir["man/*.1"] man8.install Dir["man/*.8"] end def caveats <<~EOS To activate Phusion Passenger for Nginx, run: brew install nginx And add the following to #{etc}/nginx/nginx.conf at the top scope (outside http{}): load_module #{opt_libexec}/modules/ngx_http_passenger_module.so; And add the following to #{etc}/nginx/nginx.conf in the http scope: passenger_root #{opt_libexec}/src/ruby_supportlib/phusion_passenger/locations.ini; passenger_ruby /usr/bin/ruby; To activate Phusion Passenger for Apache, create /etc/apache2/other/passenger.conf: LoadModule passenger_module #{opt_libexec}/buildout/apache2/mod_passenger.so PassengerRoot #{opt_libexec}/src/ruby_supportlib/phusion_passenger/locations.ini PassengerDefaultRuby /usr/bin/ruby EOS end test do ruby_libdir = `#{HOMEBREW_PREFIX}/bin/passenger-config --ruby-libdir`.strip assert_equal "#{libexec}/src/ruby_supportlib", ruby_libdir (testpath/"nginx.conf").write <<~EOS load_module #{opt_libexec}/modules/ngx_http_passenger_module.so; worker_processes 4; error_log #{testpath}/error.log; pid #{testpath}/nginx.pid; events { worker_connections 1024; } http { passenger_root #{opt_libexec}/src/ruby_supportlib/phusion_passenger/locations.ini; passenger_ruby /usr/bin/ruby; client_body_temp_path #{testpath}/client_body_temp; fastcgi_temp_path #{testpath}/fastcgi_temp; proxy_temp_path #{testpath}/proxy_temp; scgi_temp_path #{testpath}/scgi_temp; uwsgi_temp_path #{testpath}/uwsgi_temp; passenger_temp_path #{testpath}/passenger_temp; server { passenger_enabled on; listen 8080; root #{testpath}; access_log #{testpath}/access.log; error_log #{testpath}/error.log; } } EOS system "#{Formula["nginx"].opt_bin}/nginx", "-t", "-c", testpath/"nginx.conf" end end
38.721429
104
0.685482
0809bcecbdf41e4b7cf9957bd8151cd27d9213dd
239
require 'rails' require 'bootstrap/glyphicons/version' module Bootstrap module Glyphicons if ::Rails.version < '3.1' require 'bootstrap/glyphicons/railtie' else require 'bootstrap/glyphicons/engine' end end end
19.916667
44
0.711297
18f168fb41cb5c0cf9ab31c04c961793cd0465d1
1,225
require "benchmark" require "sshkit/formatters/pretty" # Capistrano v3 uses Rake's DSL instead of its own module Rake class Task alias old_invoke invoke def invoke(*args) result = nil reporter = Capistrano::Datadog.reporter task_name = name reporter.current_task = task_name timing = Benchmark.measure(task_name) do result = old_invoke(*args) end reporter.record_task(task_name, timing.real, roles, Capistrano::Configuration.env.fetch(:stage), Capistrano::Configuration.env.fetch(:application)) result end end end module Capistrano module Datadog class CaptureIO def initialize(wrapped) @wrapped = wrapped end def write(*args) @wrapped.write(*args) args.each { |arg| Capistrano::Datadog.reporter.record_log(arg) } end alias :<< :write def close @wrapped.close end end end end module SSHKit module Formatter class Pretty def initialize(oio) super(Capistrano::Datadog::CaptureIO.new(oio)) end end end end at_exit do api_key = Capistrano::Configuration.env.fetch :datadog_api_key Capistrano::Datadog.submit api_key end
21.12069
103
0.663673
4a4a6e75cb32c426194c5e4cc55af50f78767c45
744
# gem install benchmark_suite require 'benchmark/ips' require 'hamster/list' Benchmark.ips do |b| sml_list = Hamster.list(1) # med_list = Hamster.iterate(1, &:next).take(100) # lrg_list = Hamster.iterate(1, &:next).take(10000) med_list = Hamster.list 100.times {|i| med_list = med_list.cons(i)} lrg_list = Hamster.list 10000.times {|i| lrg_list = lrg_list.cons(i)} b.report "at small" do |n| a = 0 x = 0 while a < n x = sml_list.at(0) a += 1 end end b.report "at medium" do |n| a = 0 x = 0 while a < n x = med_list.at(99) a += 1 end end b.report "at large" do |n| a = 0 x = 0 while a < n x = lrg_list.at(9999) a += 1 end end end
17.714286
53
0.563172
1a67aaf429087774204506f32a5bcecdde46687f
398
# frozen_string_literal: true class DropRepositoriesFromJobs < ActiveRecord::Migration[4.2] def up remove_foreign_key :jobs, column: :repository_id remove_column :jobs, :repository_id, :integer end def down add_column :jobs, :repository_id, :integer add_foreign_key :jobs, :repositories, column: :repository_id, name: :jobs_repository_id_fkey, on_delete: :cascade end end
28.428571
117
0.761307
2632601f11ef7705ab86399432ab83eb04cb2a00
701
module Time_to # Based on @jorgeepunan's 18.js def self.september x = Date.new(2019, 9, 18) y = Time.now.to_date d = (x - y).to_i if d == 0 return ':chile: ¡Hoy es 18! ¡A emborracharte!' else return ":chile: Quedan #{d} días pa'l 18 de septiembre." end end # Based on @hectorpalmatellez's gardel.js def self.gardel require 'week_of_month' date = Date.parse(Date.today.to_s) last = Date.parse(date.end_of_month.downto(date).find(&:working_day?).to_s) d = last.mjd - date.mjd - 2 p = if date.mjd > 1 'n' else '' end d == 0 ? '¡Hoy pagan!' : "Falta#{p} #{d} días para que paguen." end end
20.617647
79
0.569187
38bcef232e10fec759600adfb2fc28225d069bd0
1,535
# frozen_string_literal: true require_relative 'helper' require 'query' describe Query do it 'returns given amount' do query = Query.new(amount: '100') query.amount.must_equal 100.0 end it 'defaults amount to nothing' do query = Query.new query.amount.must_be_nil end it 'returns given base' do query = Query.new(base: 'USD') query.base.must_equal 'USD' end it 'upcases given base' do query = Query.new(base: 'usd') query.base.must_equal 'USD' end it 'defaults base to nothing' do query = Query.new query.base.must_be_nil end it 'aliases base with from' do query = Query.new(from: 'USD') query.base.must_equal 'USD' end it 'returns given symbols' do query = Query.new(symbols: 'USD,GBP') query.symbols.must_equal %w[USD GBP] end it 'upcases given symbols' do query = Query.new(symbols: 'usd,gbp') query.symbols.must_equal %w[USD GBP] end it 'aliases symbols with to' do query = Query.new(to: 'USD') query.symbols.must_equal ['USD'] end it 'defaults symbols to nothing' do query = Query.new query.symbols.must_be_nil end it 'returns given date' do date = '2014-01-01' query = Query.new(date: date) query.date.must_equal Date.parse(date) end it 'returns given date interval' do start_date = '2014-01-01' end_date = '2014-12-31' query = Query.new(start_date: start_date, end_date: end_date) query.date.must_equal((Date.parse(start_date)..Date.parse(end_date))) end end
21.928571
73
0.670358
ed3feba2c3a9c3ad2f31f82540f592fd103b0443
1,095
class User < ActiveRecord::Base has_many :viewed_homes has_many :homes, through: :viewed_homes # Include default devise modules. Others available are: # :confirmable, :lockable, :timeoutable devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:facebook, :twitter] validates_presence_of :email validates_presence_of :password, on: :create validates_uniqueness_of :email def self.from_omniauth(auth) where(provider: auth.provider, uid: auth.uid).first_or_create do |user| if auth.info.email user.email = auth.info.email else user.email = "random#{rand(9999)}@random.com" end user.password = Devise.friendly_token[0,20] user.name = auth.info.name end end def self.new_with_session(params, session) super.tap do |user| if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["raw_info"] user.email = data["email"] if user.email.blank? end end end end
32.205882
103
0.691324
18a06e7a70da9d6611518c162fec2d705e68aa65
79
# frozen_string_literal: true module Apiomatic VERSION = '0.0.1'.freeze end
13.166667
29
0.746835
bf0dc7ca8e6efd7a94fe4c4bb1eac0b297550211
20,557
module LVGL [ :ANIM, :BTN_STYLE, :BORDER, :CONT_STYLE, :CURSOR, :EVENT, :FIT, :KB_MODE, :KB_STYLE, :LABEL_ALIGN, :LABEL_LONG, :LABEL_STYLE, :LAYOUT, :PAGE_STYLE, :PROTECT, :SHADOW, :SW_STYLE, :TASK_PRIO, :TA_STYLE, ].each do |enum_name| const_set(enum_name, LVGL::FFI.const_get("LV_#{enum_name}".to_sym)) LVGL.const_get(enum_name).module_exec do def self.from_value(needle) self.constants.find do |name| needle == self.const_get(name) end end end end def self.ffi_call!(klass, meth, *args, _initiator_class: nil) _initiator_class ||= klass unless klass.const_defined?(:LV_TYPE) raise "Tried to ffi_call!(..., #{meth}) with a #{_initiator_class.name}, which does not define LV_TYPE" end ffi_name = "lv_#{klass.const_get(:LV_TYPE)}_#{meth}".to_sym if LVGL::FFI.respond_to?(ffi_name) args = args.map do |arg| case arg when nil 0 when false 0 when true 1 else if arg.respond_to? :lv_obj_pointer arg.lv_obj_pointer else arg end end end return LVGL::FFI.send(ffi_name, *args) else if klass.superclass return ffi_call!(klass.superclass, meth, *args, _initiator_class: _initiator_class) else raise "Could not find #{meth} in the class hierarchy." end end end def self.layer_top() LVObject.from_pointer(LVGL::FFI.lv_layer_top()) end def self.layer_sys() LVObject.from_pointer(LVGL::FFI.lv_layer_sys()) end class LVDisplay # This is not actually an object type in LVGL proper. # Get default display def self.get_default() LVGL::FFI.lv_disp_get_default() end # Gets the current active screen. def self.get_scr_act() LVObject.from_pointer( LVGL::FFI.lv_disp_get_scr_act(get_default()) ) end end class LVObject LV_TYPE = :obj # Hack... # I need to figure out how to use Fiddle's #to_value to rehydrate an mruby # Object into its proper form. REGISTRY = { # @self_pointer int value => instance } def initialize(parent = nil, pointer: nil) @__event_handler_proc = nil unless pointer parent_ptr = if parent parent.lv_obj_pointer else nil end @self_pointer = LVGL.ffi_call!(self.class, :create, parent_ptr, nil) else @self_pointer = pointer end register_userdata unless parent or pointer LVGL::FFI.lv_disp_load_scr(@self_pointer) end end def lv_obj_pointer() @self_pointer end def self.from_pointer(pointer) if REGISTRY[pointer.to_i] REGISTRY[pointer.to_i] else self.new(pointer: pointer) end end def get_style() style = LVGL.ffi_call!(self.class, :get_style, @self_pointer) LVGL::LVStyle.from_pointer(style) end def set_style(style) # Prevents the object from being collected @style = style LVGL.ffi_call!(self.class, :set_style, @self_pointer, style.lv_style_pointer) end def glue_obj(value) value = if value 1 else 0 end LVGL::FFI.lv_page_glue_obj(@self_pointer, value) end def method_missing(meth, *args) LVGL.ffi_call!(self.class, meth, @self_pointer, *args) end def event_handler=(cb_proc) # Hook the handler on-the-fly, assuming it wasn't set if we didn't have # a handler proc. unless @__event_handler_proc LVGL.ffi_call!(self.class, :set_event_cb, @self_pointer, LVGL::FFI["handle_lv_event"]) end @__event_handler_proc = cb_proc end def event_handler() @__event_handler_proc end def register_userdata() userdata = Fiddle::Pointer[self] REGISTRY[@self_pointer.to_i] = self LVGL.ffi_call!(self.class, :set_user_data, @self_pointer, userdata) end def get_parent() ptr = LVGL.ffi_call!(self.class, :get_parent, @self_pointer) LVObject.from_pointer(ptr) end def get_children() children = [] last_child = nil loop do ptr = LVGL.ffi_call!(self.class, :get_child_back, @self_pointer, last_child) break if ptr.null? last_child = LVObject.from_pointer(ptr) children << last_child end children end end class LVContainer < LVObject LV_TYPE = :cont def set_layout(*args) LVGL::FFI.lv_cont_set_layout(@self_pointer, *args) end def get_style(type) # type is unused, see lvgl/src/lv_objx/lv_cont.h super() end def set_style(type, style) # type is unused, see lvgl/src/lv_objx/lv_cont.h super(style) end end class LVLabel < LVObject LV_TYPE = :label def get_style(type) # type is unused, see lvgl/src/lv_objx/lv_label.h super() end def set_style(type, style) # type is unused, see lvgl/src/lv_objx/lv_label.h super(style) end def set_text(text) text ||= "" # The "\0" thing is a bit scary; it seems that *something* related # to C string and "\0" in either mruby or LVGL, likely mruby, may # cause issues when using something like `split` to split a bigger # string. # # My assumption is that the ruby string is not \0 completed, and # given as-is to the C world via ffi. LVGL.ffi_call!(self.class, :set_text, @self_pointer, text + "\0") end end class LVImage < LVObject LV_TYPE = :img end class LVPage < LVContainer LV_TYPE = :page def set_style(type, style) # Prevents the object from being collected @style = style LVGL.ffi_call!(self.class, :set_style, @self_pointer, type, style.lv_style_pointer) end def get_style(style_type) style = LVGL.ffi_call!(self.class, :get_style, @self_pointer, style_type) LVGL::LVStyle.from_pointer(style) end def focus(obj, anim) ptr = if obj.respond_to?(:lv_obj_pointer) obj.lv_obj_pointer else obj end LVGL.ffi_call!(self.class, :focus, @self_pointer, ptr, anim) end end class LVButton < LVContainer LV_TYPE = :btn def get_style(style_type) style = LVGL.ffi_call!(self.class, :get_style, @self_pointer, style_type) LVGL::LVStyle.from_pointer(style) end def set_style(style_type, style) # Prevents the object from being collected @_style ||= {} @_style[style_type] = style LVGL.ffi_call!(self.class, :set_style, @self_pointer, style_type, style.lv_style_pointer) end end class LVSwitch < LVObject LV_TYPE = :sw def on(anim = false) LVGL.ffi_call!(self.class, :on, @self_pointer, anim) end def off(anim = false) LVGL.ffi_call!(self.class, :off, @self_pointer, anim) end def toggle(anim = false) LVGL.ffi_call!(self.class, :toggle, @self_pointer, anim) end def get_state() LVGL.ffi_call!(self.class, :get_state, @self_pointer) != 0 end def get_style(style_type) style = LVGL.ffi_call!(self.class, :get_style, @self_pointer, style_type) LVGL::LVStyle.from_pointer(style) end def set_style(style_type, style) # Prevents the object from being collected @_style ||= {} @_style[style_type] = style LVGL.ffi_call!(self.class, :set_style, @self_pointer, style_type, style.lv_style_pointer) end end class LVTextArea < LVObject LV_TYPE = :ta def add_text(text) # The "\0" thing is a bit scary; it seems that *something* related # to C string and "\0" in either mruby or LVGL, likely mruby, may # cause issues when using something like `split` to split a bigger # string. # # My assumption is that the ruby string is not \0 completed, and # given as-is to the C world via ffi. LVGL.ffi_call!(self.class, :add_text, @self_pointer, text + "\0") end def set_text(text) # The "\0" thing is a bit scary; it seems that *something* related # to C string and "\0" in either mruby or LVGL, likely mruby, may # cause issues when using something like `split` to split a bigger # string. # # My assumption is that the ruby string is not \0 completed, and # given as-is to the C world via ffi. LVGL.ffi_call!(self.class, :set_text, @self_pointer, text + "\0") end def set_placeholder_text(text) # The "\0" thing is a bit scary; it seems that *something* related # to C string and "\0" in either mruby or LVGL, likely mruby, may # cause issues when using something like `split` to split a bigger # string. # # My assumption is that the ruby string is not \0 completed, and # given as-is to the C world via ffi. LVGL.ffi_call!(self.class, :set_placeholder_text, @self_pointer, text + "\0") end def set_accepted_chars(text) # The "\0" thing is a bit scary; it seems that *something* related # to C string and "\0" in either mruby or LVGL, likely mruby, may # cause issues when using something like `split` to split a bigger # string. # # My assumption is that the ruby string is not \0 completed, and # given as-is to the C world via ffi. LVGL.ffi_call!(self.class, :set_accepted_chars, @self_pointer, text + "\0") end def get_style(style_type) style = LVGL.ffi_call!(self.class, :get_style, @self_pointer, style_type) LVGL::LVStyle.from_pointer(style) end def set_style(style_type, style) # Prevents the object from being collected @_style ||= {} @_style[style_type] = style LVGL.ffi_call!(self.class, :set_style, @self_pointer, style_type, style.lv_style_pointer) end end class LVKeyboard < LVObject LV_TYPE = :kb def get_style(style_type) style = LVGL.ffi_call!(self.class, :get_style, @self_pointer, style_type) LVGL::LVStyle.from_pointer(style) end def set_style(style_type, style) # Prevents the object from being collected @_style ||= {} @_style[style_type] = style LVGL.ffi_call!(self.class, :set_style, @self_pointer, style_type, style.lv_style_pointer) end end # Wraps an +lv_style_t+ in a class with some light duty housekeeping. class LVStyle # Given a +Fiddle::Pointer+ pointing to an +lv_style_t+, instantiates # an LVStyle class, wrapping the struct. def self.from_pointer(pointer) instance = LVGL::LVStyle.new() instance.instance_exec do @self_pointer = pointer end instance end # Allocates a new +lv_style_t+, and copies the styles using the LVGL # +lv_style_copy+. def initialize_copy(orig) @self_pointer = LVGL::FFI.lvgui_allocate_lv_style() LVGL::FFI.lv_style_copy(@self_pointer, orig.lv_style_pointer) end def lv_style_pointer() @self_pointer end # Proxy all methods to the struct accessors we are wrapping. # It's dumb, but it works so well! def method_missing(meth, *args) meth = if meth.to_s.match(/=$/) "lvgui_set_lv_style__#{meth.to_s[0..-2]}".to_sym else "lvgui_get_lv_style__#{meth}".to_sym end LVGL::FFI.send(meth, @self_pointer, *args) end private def initialize() end public # Initializes global styles [ "scr", "transp", "transp_tight", "transp_fit", "plain", "plain_color", "pretty", "pretty_color", "btn_rel", "btn_pr", "btn_tgl_rel", "btn_tgl_pr", "btn_ina", ].each do |name| global_name = "lv_style_#{name}".downcase const_name = "style_#{name}".upcase.to_sym wrapped = self.from_pointer( LVGL::FFI.handler.sym(global_name) ) const_set(const_name, wrapped) end end class LVGroup LV_TYPE = :group REGISTRY = { # @self_pointer int value => instance } def initialize(pointer: nil) @focus_handler_proc_stack = [nil] @focus_groups_stack = [[]] @last_focused_in_stack = [] unless pointer raise "(FIXME) Creating a focus group is not implemented" #@self_pointer = LVGL.ffi_call!(self.class, :create) else @self_pointer = pointer end register_userdata end # Given a +Fiddle::Pointer+ pointing to an +lv_group_t+, instantiates # an LVGroup class, wrapping the struct. def self.from_pointer(pointer) if REGISTRY[pointer.to_i] REGISTRY[pointer.to_i] else self.new(pointer: pointer) end end def initialize_copy(orig) raise "Not implemented" end def lv_group_pointer() @self_pointer end def method_missing(meth, *args) LVGL.ffi_call!(self.class, meth, @self_pointer, *args) end def add_obj(obj) @focus_groups_stack.last << obj _add_obj(obj) end def focus_obj(obj) # Automatic bindings fail since there is no "self" argument here. ptr = if obj.respond_to?(:lv_obj_pointer) obj.lv_obj_pointer else obj end LVGL.ffi_call!(self.class, :focus_obj, ptr) end def get_focused() LVObject.from_pointer( LVGL.ffi_call!(self.class, :get_focused, @self_pointer) ) end def remove_all_objs() # Evict the current array from the stack @focus_groups_stack.pop() # Don't forget to add a new one! @focus_groups_stack.push([]) LVGL.ffi_call!(self.class, :remove_all_objs, @self_pointer) end def focus_handler=(cb_proc) # Replace the last item from the stack @focus_handler_proc_stack.pop() @focus_handler_proc_stack << cb_proc _set_focus_handler(cb_proc) end def register_userdata() LVGL.ffi_call!(self.class, :remove_all_objs, @self_pointer) userdata = Fiddle::Pointer[self] REGISTRY[@self_pointer.to_i] = self LVGL.ffi_call!(self.class, :set_user_data, @self_pointer, userdata) end # Keep the previous focus group aside in memory, and empty the focus group. # Use +#pop+ to put back the last focus group def push() @last_focused_in_stack << get_focused() @focus_groups_stack << [] @focus_handler_proc_stack << nil _set_focus_handler(@focus_handler_proc_stack.last) LVGL.ffi_call!(self.class, :remove_all_objs, @self_pointer) end # Empties the current focus group, and puts back the previous one from the # stack. def pop() LVGL.ffi_call!(self.class, :remove_all_objs, @self_pointer) @focus_groups_stack.pop() @focus_groups_stack.last.each do |obj| _add_obj(obj) end focus_obj(@last_focused_in_stack.pop()) @focus_handler_proc_stack.pop() _set_focus_handler(@focus_handler_proc_stack.last) end private def _add_obj(obj) ptr = if obj.respond_to?(:lv_obj_pointer) obj.lv_obj_pointer else obj end LVGL.ffi_call!(self.class, :add_obj, @self_pointer, ptr) end def _set_focus_handler(cb_proc) # Hook the handler on-the-fly. LVGL.ffi_call!(self.class, :set_focus_cb, @self_pointer, LVGL::FFI["handle_lv_focus"]) end end # Wraps an +lv_anim_t+ in a class with some light duty housekeeping. class LVAnim LV_TYPE = :anim # Given a +Fiddle::Pointer+ pointing to an +lv_anim_t+, instantiates # an LVAnim class, wrapping the struct. def self.from_pointer(pointer) instance = LVGL::LVAnim.new() instance.instance_exec do @self_pointer = pointer end instance end def initialize() @self_pointer = LVGL::FFI.lvgui_allocate_lv_anim() self.init end def lv_anim_pointer() @self_pointer end def set_exec_cb(obj, cb_name) fn = LVGL::FFI[cb_name.to_s] raise "No function for #{cb_name} on LVGL::FFI" unless fn LVGL.ffi_call!(self.class, "set_exec_cb", @self_pointer, obj.lv_obj_pointer, fn) end def method_missing(meth, *args) LVGL.ffi_call!(self.class, meth, @self_pointer, *args) end module Path # Initializes global animation paths [ "linear", "step", "ease_in", "ease_out", "ease_in_out", "overshoot", "bounce", ].each do |name| const_set( name.upcase.to_sym, LVGL::FFI.handler.sym("lv_anim_path_#{name}".downcase) ) end end end module Symbols AUDIO = "\xef\x80\x81" # 61441, 0xF001 VIDEO = "\xef\x80\x88" # 61448, 0xF008 LIST = "\xef\x80\x8b" # 61451, 0xF00B OK = "\xef\x80\x8c" # 61452, 0xF00C CLOSE = "\xef\x80\x8d" # 61453, 0xF00D POWER = "\xef\x80\x91" # 61457, 0xF011 SETTINGS = "\xef\x80\x93" # 61459, 0xF013 HOME = "\xef\x80\x95" # 61461, 0xF015 DOWNLOAD = "\xef\x80\x99" # 61465, 0xF019 DRIVE = "\xef\x80\x9c" # 61468, 0xF01C REFRESH = "\xef\x80\xa1" # 61473, 0xF021 MUTE = "\xef\x80\xa6" # 61478, 0xF026 VOLUME_MID = "\xef\x80\xa7" # 61479, 0xF027 VOLUME_MAX = "\xef\x80\xa8" # 61480, 0xF028 IMAGE = "\xef\x80\xbe" # 61502, 0xF03E EDIT = "\xef\x8C\x84" # 62212, 0xF304 PREV = "\xef\x81\x88" # 61512, 0xF048 PLAY = "\xef\x81\x8b" # 61515, 0xF04B PAUSE = "\xef\x81\x8c" # 61516, 0xF04C STOP = "\xef\x81\x8d" # 61517, 0xF04D NEXT = "\xef\x81\x91" # 61521, 0xF051 EJECT = "\xef\x81\x92" # 61522, 0xF052 LEFT = "\xef\x81\x93" # 61523, 0xF053 RIGHT = "\xef\x81\x94" # 61524, 0xF054 PLUS = "\xef\x81\xa7" # 61543, 0xF067 MINUS = "\xef\x81\xa8" # 61544, 0xF068 EYE_OPEN = "\xef\x81\xae" # 61550, 0xF06E EYE_CLOSE = "\xef\x81\xb0" # 61552, 0xF070 WARNING = "\xef\x81\xb1" # 61553, 0xF071 SHUFFLE = "\xef\x81\xb4" # 61556, 0xF074 UP = "\xef\x81\xb7" # 61559, 0xF077 DOWN = "\xef\x81\xb8" # 61560, 0xF078 LOOP = "\xef\x81\xb9" # 61561, 0xF079 DIRECTORY = "\xef\x81\xbb" # 61563, 0xF07B UPLOAD = "\xef\x82\x93" # 61587, 0xF093 CALL = "\xef\x82\x95" # 61589, 0xF095 CUT = "\xef\x83\x84" # 61636, 0xF0C4 COPY = "\xef\x83\x85" # 61637, 0xF0C5 SAVE = "\xef\x83\x87" # 61639, 0xF0C7 CHARGE = "\xef\x83\xa7" # 61671, 0xF0E7 PASTE = "\xef\x83\xAA" # 61674, 0xF0EA BELL = "\xef\x83\xb3" # 61683, 0xF0F3 KEYBOARD = "\xef\x84\x9c" # 61724, 0xF11C GPS = "\xef\x84\xa4" # 61732, 0xF124 FILE = "\xef\x85\x9b" # 61787, 0xF158 WIFI = "\xef\x87\xab" # 61931, 0xF1EB BATTERY_FULL = "\xef\x89\x80" # 62016, 0xF240 BATTERY_3 = "\xef\x89\x81" # 62017, 0xF241 BATTERY_2 = "\xef\x89\x82" # 62018, 0xF242 BATTERY_1 = "\xef\x89\x83" # 62019, 0xF243 BATTERY_EMPTY = "\xef\x89\x84" # 62020, 0xF244 USB = "\xef\x8a\x87" # 62087, 0xF287 BLUETOOTH = "\xef\x8a\x93" # 62099, 0xF293 TRASH = "\xef\x8B\xAD" # 62189, 0xF2ED BACKSPACE = "\xef\x95\x9A" # 62810, 0xF55A SD_CARD = "\xef\x9F\x82" # 63426, 0xF7C2 NEW_LINE = "\xef\xA2\xA2" # 63650, 0xF8A2 end # OPA_50 -> OPA::50 is illegal # enum { # LV_OPA_TRANSP = 0, # LV_OPA_0 = 0, # LV_OPA_10 = 25, # LV_OPA_20 = 51, # LV_OPA_30 = 76, # LV_OPA_40 = 102, # LV_OPA_50 = 127, # LV_OPA_60 = 153, # LV_OPA_70 = 178, # LV_OPA_80 = 204, # LV_OPA_90 = 229, # LV_OPA_100 = 255, # LV_OPA_COVER = 255, # }; module OPA TRANSP = 0 COVER = 255 HALF = 127 # 50 # 0-100 def self.scale(num) (255*num/100.0).round end end module LVColor def self.mix(col1, col2, mix) LVGL::FFI.lv_color_mix(col1, col2, mix) end end end
27.930707
109
0.602277
e8ff484146fa1d51aa4674140d9e48706be7e7d8
1,779
cask '[email protected]' do version '5.6.0f3,497a0f351392' sha256 '77f16eaaec847b5afc7795924b2561a8ce16aca132ebe973790b584f7d0aa96e' url "http://download.unity3d.com/download_unity/#{version.after_comma}/MacEditorTargetInstaller/UnitySetup-WebGL-Support-for-Editor-#{version.before_comma}.pkg" name 'Unity WebGL Build Support' homepage 'https://unity3d.com/unity/' depends_on cask: '[email protected]' pkg "UnitySetup-WebGL-Support-for-Editor-#{version.before_comma}.pkg" preflight do if File.exist? '/Applications/Unity' FileUtils.move '/Applications/Unity', '/Applications/Unity.temp' end if File.exist? "/Applications/Unity-#{@cask.version.before_comma}" FileUtils.move "/Applications/Unity-#{@cask.version.before_comma}", '/Applications/Unity' end end postflight do if File.exist? '/Applications/Unity' FileUtils.move '/Applications/Unity', "/Applications/Unity-#{@cask.version.before_comma}" end if File.exist? '/Applications/Unity.temp' FileUtils.move '/Applications/Unity.temp', '/Applications/Unity' end end uninstall_preflight do if File.exist? '/Applications/Unity' FileUtils.move '/Applications/Unity', '/Applications/Unity.temp' end if File.exist? "/Applications/Unity-#{@cask.version.before_comma}" FileUtils.move "/Applications/Unity-#{@cask.version.before_comma}", '/Applications/Unity' end end uninstall_postflight do if File.exist? '/Applications/Unity' FileUtils.move '/Applications/Unity', "/Applications/Unity-#{@cask.version.before_comma}" end if File.exist? '/Applications/Unity.temp' FileUtils.move '/Applications/Unity.temp', '/Applications/Unity' end end uninstall pkgutil: '' end
32.345455
162
0.72063
8792ed665934aabb86109b42c4442c88fa6810ac
707
require_relative '../../algorithms/rate_limiter' describe 'RateLimiter' do let(:rate_limitor) { RateLimiter.new } specify '#hit_endpoint does not allow 11 requests within 10 seconds' do request_statuses = [] 11.times do request_statuses << rate_limitor.hit_endpoint end request_statuses[0..9].each do |status| expect(status).to be_truthy end expect(request_statuses.last).to be_falsey end specify '#hit_endpoint allows 11 requests over 11 seconds' do request_statuses = [] 11.times do request_statuses << rate_limitor.hit_endpoint sleep(1) end request_statuses.each do |status| expect(status).to be_truthy end end end
23.566667
73
0.698727
6a188641c58f9252f29899cbb4af92594ed254b6
609
require 'rails_helper' RSpec.describe "home/index.html.haml" do it "displays a new poll form" do assign(:poll, Poll.new(answers: ['',''])) render expect(rendered).to have_selector("form#new_poll") expect(rendered).to have_selector("input[name='poll[question]']") expect(rendered).to have_selector("input[name='poll[answers][]']", count: 2) expect(rendered).to have_selector("input[name='poll[allow_multiple]']") expect(rendered).to have_selector("input[name='poll[allow_duplication]']") expect(rendered).to have_selector("div#last-poll") if cookies[:last_link] end end
38.0625
80
0.706076
877fc810e1a64ca4ffa88303c2c3468b2301415a
9,780
require 'spec_helper' describe "RailsAdmin Basic List" do include Warden::Test::Helpers before(:each) do RailsAdmin::AbstractModel.new("Division").destroy_all! RailsAdmin::AbstractModel.new("Draft").destroy_all! RailsAdmin::AbstractModel.new("Fan").destroy_all! RailsAdmin::AbstractModel.new("League").destroy_all! RailsAdmin::AbstractModel.new("Player").destroy_all! RailsAdmin::AbstractModel.new("Team").destroy_all! RailsAdmin::AbstractModel.new("User").destroy_all! user = RailsAdmin::AbstractModel.new("User").create( :email => "[email protected]", :password => "test1234" ) login_as user end after(:each) do Warden.test_reset! end describe "GET /admin" do before(:each) do get rails_admin_dashboard_path end it "should respond sucessfully" do response.code.should == "200" end end describe "GET /admin/player as list" do before(:each) do get rails_admin_list_path(:model_name => "player") end it "should respond sucessfully" do response.should be_successful end it "should show \"Select model to edit\"" do response.body.should contain("Select player to edit") end it "should show filters" do response.body.should contain(/CREATED AT\n\s*UPDATED AT\n\s*/) end it "should show column headers" do response.body.should contain(/EDIT\n\s*DELETE\n\s*/) end end describe "GET /admin/player with sort" do before(:each) do RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 32, :name => "Sandy Koufax", :position => "Starting patcher") RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 42, :name => "Jackie Robinson", :position => "Second baseman") get rails_admin_list_path(:model_name => "player", :sort => "name", :set => 1) end it "should respond sucessfully" do response.should be_successful end it "should be sorted correctly" do response.body.should contain(/Sandy Koufax/) response.body.should contain(/Jackie Robinson/) end end describe "GET /admin/player with reverse sort" do before(:each) do RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 32, :name => "Sandy Koufax", :position => "Starting patcher") RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 42, :name => "Jackie Robinson", :position => "Second baseman") get rails_admin_list_path(:model_name => "player", :sort => "name", :sort_reverse => "true", :set => 1) end it "should respond sucessfully" do response.should be_successful end it "should be sorted correctly" do response.body.should contain(/Sandy Koufax/) response.body.should contain(/Jackie Robinson/) end end describe "GET /admin/player with query" do before(:each) do RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 32, :name => "Sandy Koufax", :position => "Starting patcher") RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 42, :name => "Jackie Robinson", :position => "Second baseman") get rails_admin_list_path(:model_name => "player", :query => "Jackie Robinson", :set => 1) end it "should respond sucessfully" do @response.should be_successful end it "should show a correct result" do @response.body.should contain("Jackie Robinson") end it "should not contain an incorrect result" do @response.body.should_not contain("Sandy Koufax") end end describe "GET /admin/player with query and boolean filter" do before(:each) do RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 32, :name => "Sandy Koufax", :position => "Starting patcher", :retired => true, :injured => true) RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 42, :name => "Jackie Robinson", :position => "Second baseman", :retired => true, :injured => false) RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 18, :name => "Moises Alou", :position => "Left fielder", :retired => false, :injured => true) RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 5, :name => "David Wright", :position => "Third baseman", :retired => false, :injured => false) get rails_admin_list_path(:model_name => "player", :query => "Sandy Koufax", :filter => {:injured => "true"}, :set => 1) end it "should respond sucessfully" do response.should be_successful end it "should show a correct result" do response.body.should contain("Sandy Koufax") end it "should not contain an incorrect result" do response.body.should_not contain("Jackie Robinson") response.body.should_not contain("Moises Alou") response.body.should_not contain("David Wright") end end describe "GET /admin/player with boolean filter" do before(:each) do RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 18, :name => "Moises Alou", :position => "Left fielder", :injured => true) RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 5, :name => "David Wright", :position => "Third baseman", :injured => false) get rails_admin_list_path(:model_name => "player", :filter => {:injured => "true"}, :set => 1) end it "should respond sucessfully" do response.should be_successful end it "should show a correct result" do response.body.should contain("Moises Alou") end it "should not contain an incorrect result" do response.body.should_not contain("David Wright") end end describe "GET /admin/player with boolean filters" do before(:each) do RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 32, :name => "Sandy Koufax", :position => "Starting patcher", :retired => true, :injured => true) RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 42, :name => "Jackie Robinson", :position => "Second baseman", :retired => true, :injured => false) RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 18, :name => "Moises Alou", :position => "Left fielder", :retired => false, :injured => true) RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => 5, :name => "David Wright", :position => "Third baseman", :retired => false, :injured => false) get rails_admin_list_path(:model_name => "player", :filter => {:retired => "true", :injured => "true"}, :set => 1) end it "should respond sucessfully" do @response.should be_successful end it "should show a correct result" do end it "should not contain an incorrect result" do @response.body.should_not contain("Jackie Robinson") @response.body.should_not contain("Moises Alou") @response.body.should_not contain("David Wright") end end describe "GET /admin/player with 2 objects" do before(:each) do (1..2).each do |number| RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => number, :name => "Player #{number}") end get rails_admin_list_path(:model_name => "player") end it "should respond sucessfully" do response.should be_successful end it "should show \"2 results\"" do response.body.should contain("2 players") end end describe "GET /admin/player with 20 objects" do before(:each) do (1..20).each do |number| RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => number, :name => "Player #{number}") end get rails_admin_list_path(:model_name => "player") end it "should respond sucessfully" do @response.should be_successful end it "should show \"20 results\"" do @response.body.should contain("20 players") end end describe "GET /admin/player with 20 pages, page 8" do before(:each) do per_page = 20 page_numers = 20 (1..per_page * page_numers).each do |number| RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => number, :name => "Player #{number}") end get rails_admin_list_path(:model_name => "player", :page => 8) end it "should respond sucessfully" do response.should be_successful end it "should paginate correctly" do response.body.should contain(/1 2 [^0-9]*5 6 7 8 9 10 11[^0-9]*19 20/) end end describe "list with 20 pages, page 17" do before(:each) do per_page = 20 max_pages = 20 (1..per_page * max_pages).each do |number| RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => number, :name => "Player #{number}") end get rails_admin_list_path(:model_name => "player", :page => 18) end it "should respond sucessfully" do response.should be_successful end it "should paginate correctly" do @response.body.should contain(/1 2[^0-9]*12 13 14 15 16 17 18 19 20/) end end describe "GET /admin/player show all" do before(:each) do (1..2).each do |number| RailsAdmin::AbstractModel.new("Player").create(:team_id => rand(99999), :number => number, :name => "Player #{number}") end get rails_admin_list_path(:model_name => "player", :all => true) end it "should respond sucessfully" do @response.should be_successful end end end
35.955882
188
0.653579
f7149c5de5902318e9040193b918644686dfef2a
1,686
# frozen_string_literal: true module DiscourseReactions::TopicViewSerializerExtension def posts if SiteSetting.discourse_reactions_enabled posts = object.posts.includes(:post_actions, reactions: { reaction_users: :user }) post_ids = posts.map(&:id).uniq posts_reaction_users_count = TopicViewSerializer.posts_reaction_users_count(post_ids) posts.each do |post| post.reaction_users_count = posts_reaction_users_count[post.id].to_i end object.instance_variable_set(:@posts, posts) end super end def self.prepended(base) def base.posts_reaction_users_count(post_ids) posts_reaction_users_count_query = DB.query(<<~SQL, post_ids: Array.wrap(post_ids), like_id: PostActionType.types[:like]) SELECT union_subquery.post_id, COUNT(DISTINCT(union_subquery.user_id)) FROM ( SELECT user_id, post_id FROM post_actions WHERE post_id IN (:post_ids) AND post_action_type_id = :like_id AND deleted_at IS NULL UNION ALL SELECT discourse_reactions_reaction_users.user_id, posts.id from posts LEFT JOIN discourse_reactions_reactions ON discourse_reactions_reactions.post_id = posts.id LEFT JOIN discourse_reactions_reaction_users ON discourse_reactions_reaction_users.reaction_id = discourse_reactions_reactions.id WHERE posts.id IN (:post_ids) ) AS union_subquery WHERE union_subquery.post_ID IS NOT NULL GROUP BY union_subquery.post_id SQL posts_reaction_users_count_query.each_with_object({}) do |row, hash| hash[row.post_id] = row.count end end end end
40.142857
143
0.718861
e996b9931169d006799bc2bb3fd154cbdbddaf96
453
class Hbc::Container::Naked < Hbc::Container::Base # Either inherit from this class and override with self.me?(criteria), # or use this class directly as "container :type => :naked", # in which case self.me? is not called. def self.me?(*) false end def extract @command.run!("/usr/bin/ditto", args: ["--", @path, @cask.staged_path.join(target_file)]) end def target_file URI.decode(File.basename(@cask.url.path)) end end
26.647059
93
0.671082
e93caeee4534e6c13ed26d809dcdeee253d310da
2,514
# rubocop:disable Metrics/BlockLength Rails.application.routes.draw do get "/autoyast", to: "dashboard#autoyast" devise_for :users, controllers: { registrations: "auth/registrations", sessions: "auth/sessions" } resource :dashboard, only: [:index] resource :updates, only: [:create] get "/assign_nodes", to: "dashboard#unassigned_nodes" post "/assign_nodes", to: "dashboard#assign_nodes" authenticated :user do root "dashboard#index", as: :authenticated_root end devise_scope :user do root to: "auth/sessions#new" end get "/autoyast", to: "dashboard#autoyast" get "/kubectl-config", to: redirect("/kubeconfig") # deprecated get "/kubeconfig", to: "oidc#index" get "/_health", to: "health#index" post "/update", to: "salt#update" get "/oidc", to: "oidc#index" get "/oidc/done", to: "oidc#done" post "/oidc/kubeconfig", to: "oidc#kubeconfig" namespace :orchestrations do resource :bootstrap, only: :create, controller: :bootstrap resource :upgrade, only: :create, controller: :upgrade resource :migration, only: :create, controller: :migration namespace :migration do post :check, action: :check_mirror post :reboot, action: :reboot_nodes get :status end end namespace :setup do get "/", action: :welcome match "/", action: :configure, via: [:put, :patch] get "worker-bootstrap" post :build_cloud_cluster get :discovery post :discovery, action: :set_roles get :bootstrap post :bootstrap, action: :do_bootstrap end resources :minions, only: :destroy do delete :force, action: :force_destroy, on: :member post "accept-minion", to: "salt#accept_minion" post "remove-minion", to: "salt#remove_minion" post "reject-minion", to: "salt#reject_minion" end namespace :internal_api, path: "internal-api" do namespace :v1 do resource :pillar, only: :show end end namespace :settings do get "/", action: :index resources :registries post :apply resources :registry_mirrors, path: :mirrors resources :kubelet_compute_resources_reservations, only: [:index, :create] resources :auditing, only: [:index, :create] resources :system_certificates resources :ldap_test resources :dex_connector_ldaps, path: :ldap_connectors resources :dex_connector_oidcs, path: :oidc_connectors resources :external_cert, only: [:index, :create] end end # rubocop:enable Metrics/BlockLength
30.658537
78
0.682578
28a39e98179fdb2ad1a429f8825b5d8ef8072198
1,490
require 'rails/generators' module Inky module Generators class InstallGenerator < ::Rails::Generators::Base desc 'Install Foundation for Emails' source_root File.join(File.dirname(__FILE__), 'templates') argument :layout_name, type: :string, default: 'mailer', banner: 'layout_name' class_option :haml, desc: "Generate layout in Haml", type: :boolean class_option :slim, desc: "Generate layout in Slim", type: :boolean def preserve_original_mailer_layout return unless layout_name == 'mailer' && extension == 'erb' original_mailer = File.join(layouts_base_dir, "mailer.html.erb") rename_filename = File.join(layouts_base_dir, "old_mailer_#{Time.now.to_i}.html.erb") File.rename(original_mailer, rename_filename) if File.exist? original_mailer end def create_mailer_stylesheet template 'foundation_emails.scss', File.join(stylesheets_base_dir, 'foundation_emails.scss') end def create_mailer_layout template "mailer_layout.html.#{extension}", File.join(layouts_base_dir, "#{layout_name.underscore}.html.#{extension}") end private def stylesheets_base_dir File.join('app', 'assets', 'stylesheets') end def layouts_base_dir File.join('app', 'views', 'layouts') end def extension %w(haml slim).each do |ext| return ext if options.send(ext) end 'erb' end end end end
31.041667
126
0.667785
e27ebe50ccd893e232fe93117631dd217517e083
828
module Uniquify def self.included(base) base.extend ClassMethods end def ensure_unique(name) begin self[name] = yield end while self.class.exists?(name => self[name]) end module ClassMethods def uniquify(*args, &block) options = { :length => 8, :chars => ('a'..'z').to_a + ('A'..'Z').to_a + ('0'..'9').to_a } options.merge!(args.pop) if args.last.kind_of? Hash args.each do |name| before_create do |record| if block record.ensure_unique(name, &block) else record.ensure_unique(name) do Array.new(options[:length]) { options[:chars].to_a[rand(options[:chars].to_a.size)] }.join end end end end end end end class ActiveRecord::Base include Uniquify end
23
104
0.571256
f725a16bdc0431f6d8c15d53718723cfc280a128
2,621
module Packet module NbioHelper def packet_classify(original_string) word_parts = original_string.split('_') return word_parts.map { |x| x.capitalize}.join end def gen_worker_key(worker_name,worker_key = nil) return worker_name if worker_key.nil? return "#{worker_name}_#{worker_key}".to_sym end def read_data(t_sock) sock_data = [] begin while(t_data = t_sock.read_nonblock((16*1024)-1)) sock_data << t_data end rescue Errno::EAGAIN return sock_data.join rescue Errno::EWOULDBLOCK return sock_data.join rescue raise DisconnectError.new(t_sock,sock_data.join) end end # method writes data to socket in a non blocking manner, but doesn't care if there is a error writing data def write_once(p_data,p_sock) t_data = p_data.to_s written_length = 0 data_length = t_data.length begin written_length = p_sock.write_nonblock(t_data) return "" if written_length == data_length return t_data[written_length..-1] rescue Errno::EAGAIN return t_data[written_length..-1] rescue Errno::EPIPE raise DisconnectError.new(p_sock) rescue Errno::ECONNRESET raise DisconnectError.new(p_sock) rescue raise DisconnectError.new(p_sock) end end # write the data in socket buffer and schedule the thing def write_and_schedule sock outbound_data.each_with_index do |t_data,index| leftover = write_once(t_data,sock) if leftover.empty? outbound_data[index] = nil else outbound_data[index] = leftover reactor.schedule_write(sock,self) break end end outbound_data.compact! reactor.cancel_write(sock) if outbound_data.empty? end # returns Marshal dump of the specified object def object_dump p_data object_dump = Marshal.dump(p_data) dump_length = object_dump.length.to_s length_str = dump_length.rjust(9,'0') final_data = length_str + object_dump end # method dumps the object in a protocol format which can be easily picked by a recursive descent parser def dump_object(p_data,p_sock) object_dump = Marshal.dump(p_data) dump_length = object_dump.length.to_s length_str = dump_length.rjust(9,'0') final_data = length_str + object_dump outbound_data << final_data begin write_and_schedule(p_sock) rescue DisconnectError => sock close_connection(sock) end end end end
30.126437
110
0.66158
2683d702b1ca1918d7aef6717f8be69ab2fd883d
305
require "domain/shared/callable" require "domain/customers/services/create_customer" module Carpanta module Commands class CreateCustomer extend Domain::Shared::Callable def call(params = {}) Domain::Customers::Services::CreateCustomer.call(params) end end end end
20.333333
64
0.711475
bb901bd598934058cf80441d7236b3a2d993e9f7
1,466
require 'workers/event_catcher' describe BlacklistedEvent do let(:total_blacklist_entry_count) { ExtManagementSystem.descendants.collect(&:default_blacklisted_event_names).flatten.count } before do MiqRegion.seed end context '.seed' do it 'loads event filters' do described_class.seed expect(described_class.count).to eq(total_blacklist_entry_count) end it 're-seeds deleted event filters' do described_class.seed described_class.where(:event_name => 'AlarmCreatedEvent').destroy_all expect(described_class.count).to eq(total_blacklist_entry_count - 1) described_class.seed expect(described_class.count).to eq(total_blacklist_entry_count) end it 'does not re-seed existing event filters' do User.current_user = FactoryBot.create(:user) filter = FactoryBot.create(:blacklisted_event, :event_name => 'AlarmActionTriggeredEvent', :provider_model => 'ManageIQ::Providers::Vmware::InfraManager' ) filter_attrs = filter.attributes described_class.seed expect(filter.attributes).to eq(filter_attrs) end end it '#enabled=' do User.current_user = FactoryBot.create(:user) f = FactoryBot.create(:blacklisted_event, :event_name => 'event_1') expect(f.enabled).to be_truthy f.enabled = false expect(f.enabled).to be_falsey end end
31.869565
128
0.680764
08eb649f20e38a2f2f64a576e8dd252fb8abd843
87
CouponsCode::Engine.routes.draw do resources :coupons root to: "coupons#index" end
17.4
34
0.758621
21eb09e5cefb87762662eda59dabfbe1eae13dcf
12,526
=begin #Datadog API V1 Collection #Collection of all Datadog Public endpoints. The version of the OpenAPI document: 1.0 Contact: [email protected] Generated by: https://openapi-generator.tech Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License. This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2020-Present Datadog, Inc. =end require 'date' require 'time' module DatadogAPIClient::V1 # A service level objective object includes a service level indicator, thresholds for one or more timeframes, and metadata (`name`, `description`, `tags`, etc.). class SLOResponseData # whether the object has unparsed attributes attr_accessor :_unparsed # A list of SLO monitors IDs that reference this SLO. This field is returned only when `with_configured_alert_ids` parameter is true in query. attr_accessor :configured_alert_ids # Creation timestamp (UNIX time in seconds) Always included in service level objective responses. attr_accessor :created_at attr_accessor :creator # A user-defined description of the service level objective. Always included in service level objective responses (but may be `null`). Optional in create/update requests. attr_accessor :description # A list of (up to 20) monitor groups that narrow the scope of a monitor service level objective. Included in service level objective responses if it is not empty. Optional in create/update requests for monitor service level objectives, but may only be used when then length of the `monitor_ids` field is one. attr_accessor :groups # A unique identifier for the service level objective object. Always included in service level objective responses. attr_accessor :id # Modification timestamp (UNIX time in seconds) Always included in service level objective responses. attr_accessor :modified_at # A list of monitor ids that defines the scope of a monitor service level objective. **Required if type is `monitor`**. attr_accessor :monitor_ids # The union of monitor tags for all monitors referenced by the `monitor_ids` field. Always included in service level objective responses for monitor service level objectives (but may be empty). Ignored in create/update requests. Does not affect which monitors are included in the service level objective (that is determined entirely by the `monitor_ids` field). attr_accessor :monitor_tags # The name of the service level objective object. attr_accessor :name attr_accessor :query # A list of tags associated with this service level objective. Always included in service level objective responses (but may be empty). Optional in create/update requests. attr_accessor :tags # The thresholds (timeframes and associated targets) for this service level objective object. attr_accessor :thresholds attr_accessor :type # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'configured_alert_ids' => :'configured_alert_ids', :'created_at' => :'created_at', :'creator' => :'creator', :'description' => :'description', :'groups' => :'groups', :'id' => :'id', :'modified_at' => :'modified_at', :'monitor_ids' => :'monitor_ids', :'monitor_tags' => :'monitor_tags', :'name' => :'name', :'query' => :'query', :'tags' => :'tags', :'thresholds' => :'thresholds', :'type' => :'type' } end # Returns all the JSON keys this model knows about def self.acceptable_attributes attribute_map.values end # Attribute type mapping. def self.openapi_types { :'configured_alert_ids' => :'Array<Integer>', :'created_at' => :'Integer', :'creator' => :'Creator', :'description' => :'String', :'groups' => :'Array<String>', :'id' => :'String', :'modified_at' => :'Integer', :'monitor_ids' => :'Array<Integer>', :'monitor_tags' => :'Array<String>', :'name' => :'String', :'query' => :'ServiceLevelObjectiveQuery', :'tags' => :'Array<String>', :'thresholds' => :'Array<SLOThreshold>', :'type' => :'SLOType' } end # List of attributes with nullable: true def self.openapi_nullable Set.new([ :'description', ]) end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) if (!attributes.is_a?(Hash)) fail ArgumentError, "The input argument (attributes) must be a hash in `DatadogAPIClient::V1::SLOResponseData` initialize method" end # check to see if the attribute exists and convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| if (!self.class.attribute_map.key?(k.to_sym)) fail ArgumentError, "`#{k}` is not a valid attribute in `DatadogAPIClient::V1::SLOResponseData`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect end h[k.to_sym] = v } if attributes.key?(:'configured_alert_ids') if (value = attributes[:'configured_alert_ids']).is_a?(Array) self.configured_alert_ids = value end end if attributes.key?(:'created_at') self.created_at = attributes[:'created_at'] end if attributes.key?(:'creator') self.creator = attributes[:'creator'] end if attributes.key?(:'description') self.description = attributes[:'description'] end if attributes.key?(:'groups') if (value = attributes[:'groups']).is_a?(Array) self.groups = value end end if attributes.key?(:'id') self.id = attributes[:'id'] end if attributes.key?(:'modified_at') self.modified_at = attributes[:'modified_at'] end if attributes.key?(:'monitor_ids') if (value = attributes[:'monitor_ids']).is_a?(Array) self.monitor_ids = value end end if attributes.key?(:'monitor_tags') if (value = attributes[:'monitor_tags']).is_a?(Array) self.monitor_tags = value end end if attributes.key?(:'name') self.name = attributes[:'name'] end if attributes.key?(:'query') self.query = attributes[:'query'] end if attributes.key?(:'tags') if (value = attributes[:'tags']).is_a?(Array) self.tags = value end end if attributes.key?(:'thresholds') if (value = attributes[:'thresholds']).is_a?(Array) self.thresholds = value end end if attributes.key?(:'type') self.type = attributes[:'type'] 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 && configured_alert_ids == o.configured_alert_ids && created_at == o.created_at && creator == o.creator && description == o.description && groups == o.groups && id == o.id && modified_at == o.modified_at && monitor_ids == o.monitor_ids && monitor_tags == o.monitor_tags && name == o.name && query == o.query && tags == o.tags && thresholds == o.thresholds && type == o.type end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Integer] Hash code def hash [configured_alert_ids, created_at, creator, description, groups, id, modified_at, monitor_ids, monitor_tags, name, query, tags, thresholds, type].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def self.build_from_hash(attributes) new.build_from_hash(attributes) end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.openapi_types.each_pair do |key, type| if attributes[self.class.attribute_map[key]].nil? && self.class.openapi_nullable.include?(key) self.send("#{key}=", nil) elsif type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :Time Time.parse(value) when :Date Date.parse(value) when :String value.to_s when :Integer value.to_i when :Float value.to_f when :Boolean if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when :Array # generic array, return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model # models (e.g. Pet) or oneOf klass = DatadogAPIClient::V1.const_get(type) res = klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) if res.instance_of? DatadogAPIClient::V1::UnparsedObject self._unparsed = true end res end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) if value.nil? is_nullable = self.class.openapi_nullable.include?(attr) next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) end hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
33.491979
365
0.630289
d5b0c0dff5f88ead17561af3c04b97cd43ce64b3
6,625
# This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'faker' Faker::UniqueGenerator.clear Category.create!(heading: 'For the table', body: 'Some shared plates to start', display: true) Category.create!(heading: 'First Course', body: 'A first course for each diner', display: true) Category.create!(heading: 'Second Course', body: 'A second course for each diner', display: true) Category.create!(heading: 'Third Course', body: 'An entree course', display: true) Category.create!(heading: 'Dessert', body: 'Something sweet to finish', display: true) 5.times do |i| product = Product.create( name: Faker::Food.unique.dish, description: Faker::Food.description, price: Faker::Commerce.price(range: 0.50..50.00), dairy_free: Faker::Boolean.boolean(true_ratio: 0.3), gluten_free: Faker::Boolean.boolean(true_ratio: 0.4), kosher: Faker::Boolean.boolean(true_ratio: 0.2), peanut_free: Faker::Boolean.boolean(true_ratio: 0.8), treenut_free: Faker::Boolean.boolean(true_ratio: 0.7), vegetarian: Faker::Boolean.boolean(true_ratio: 0.25), available: true, catering: Faker::Boolean.boolean(true_ratio: 0.5), featured: true, category: Category.find(1) ) if product.vegetarian == true && product.dairy_free == true product.vegan = Faker::Boolean.boolean(true_ratio: 0.9) else product.vegan = false end filename = product.name.gsub(/ /, '_').to_s product.image.attach(io: URI.open(Faker::LoremFlickr.image(size: "640x480", search_terms: ['food'])), filename: '#{filename}.jpg') product.save end 5.times do |i| product = Product.create( name: Faker::Food.unique.dish, description: Faker::Food.description, price: Faker::Commerce.price(range: 0.50..50.00), dairy_free: Faker::Boolean.boolean(true_ratio: 0.3), gluten_free: Faker::Boolean.boolean(true_ratio: 0.4), kosher: Faker::Boolean.boolean(true_ratio: 0.2), peanut_free: Faker::Boolean.boolean(true_ratio: 0.8), treenut_free: Faker::Boolean.boolean(true_ratio: 0.7), vegetarian: Faker::Boolean.boolean(true_ratio: 0.25), available: true, catering: Faker::Boolean.boolean(true_ratio: 0.5), featured: true, category: Category.find(2) ) if product.vegetarian == true && product.dairy_free == true product.vegan = Faker::Boolean.boolean(true_ratio: 0.9) else product.vegan = false end filename = product.name.gsub(/ /, '_').to_s product.image.attach(io: URI.open(Faker::LoremFlickr.image(size: "640x480", search_terms: ['food'])), filename: '#{filename}.jpg') product.save end 5.times do |i| product = Product.create( name: Faker::Food.unique.dish, description: Faker::Food.description, price: Faker::Commerce.price(range: 0.50..50.00), dairy_free: Faker::Boolean.boolean(true_ratio: 0.3), gluten_free: Faker::Boolean.boolean(true_ratio: 0.4), kosher: Faker::Boolean.boolean(true_ratio: 0.2), peanut_free: Faker::Boolean.boolean(true_ratio: 0.8), treenut_free: Faker::Boolean.boolean(true_ratio: 0.7), vegetarian: Faker::Boolean.boolean(true_ratio: 0.25), available: true, catering: Faker::Boolean.boolean(true_ratio: 0.5), featured: true, category: Category.find(3) ) if product.vegetarian == true && product.dairy_free == true product.vegan = Faker::Boolean.boolean(true_ratio: 0.9) else product.vegan = false end filename = product.name.gsub(/ /, '_').to_s product.image.attach(io: URI.open(Faker::LoremFlickr.image(size: "640x480", search_terms: ['food'])), filename: '#{filename}.jpg') product.save end 5.times do |i| product = Product.create( name: Faker::Food.unique.dish, description: Faker::Food.description, price: Faker::Commerce.price(range: 0.50..50.00), dairy_free: Faker::Boolean.boolean(true_ratio: 0.3), gluten_free: Faker::Boolean.boolean(true_ratio: 0.4), kosher: Faker::Boolean.boolean(true_ratio: 0.2), peanut_free: Faker::Boolean.boolean(true_ratio: 0.8), treenut_free: Faker::Boolean.boolean(true_ratio: 0.7), vegetarian: Faker::Boolean.boolean(true_ratio: 0.25), available: true, catering: Faker::Boolean.boolean(true_ratio: 0.5), featured: true, category: Category.find(4) ) if product.vegetarian == true && product.dairy_free == true product.vegan = Faker::Boolean.boolean(true_ratio: 0.9) else product.vegan = false end filename = product.name.gsub(/ /, '_').to_s product.image.attach(io: URI.open(Faker::LoremFlickr.image(size: "640x480", search_terms: ['food'])), filename: '#{filename}.jpg') product.save end 5.times do |i| product = Product.create( name: Faker::Dessert.unique.variety, description: Faker::Food.description, price: Faker::Commerce.price(range: 0.50..50.00), dairy_free: Faker::Boolean.boolean(true_ratio: 0.3), gluten_free: Faker::Boolean.boolean(true_ratio: 0.4), kosher: Faker::Boolean.boolean(true_ratio: 0.2), peanut_free: Faker::Boolean.boolean(true_ratio: 0.8), treenut_free: Faker::Boolean.boolean(true_ratio: 0.7), vegetarian: Faker::Boolean.boolean(true_ratio: 0.25), available: true, catering: Faker::Boolean.boolean(true_ratio: 0.5), featured: true, category: Category.find(5) ) if product.vegetarian == true && product.dairy_free == true product.vegan = Faker::Boolean.boolean(true_ratio: 0.9) else product.vegan = false end filename = product.name.gsub(/ /, '_').to_s product.image.attach(io: URI.open(Faker::LoremFlickr.image(size: "640x480", search_terms: ['food'])), filename: '#{filename}.jpg') product.save end User.create!(email: '[email protected]', password: 'password', password_confirmation: 'password', username: 'admin', admin: true)
41.149068
111
0.638491
ff9005c0d780fae19b8c28ade85aa11f7a20c149
2,339
require File.expand_path(File.dirname(__FILE__) + "/test_helper") class OutputCommandTest < Test::Unit::TestCase context "A plain command" do setup do @output = Whenever.cron \ <<-file every 2.hours do command "blahblah" end file end should "output the command" do assert_match /^.+ .+ .+ .+ blahblah$/, @output end end context "A command when the cron_log is set" do setup do @output = Whenever.cron \ <<-file set :cron_log, 'logfile.log' every 2.hours do command "blahblah" end file end should "output the command with the log syntax appended" do assert_match /^.+ .+ .+ .+ blahblah >> logfile.log 2>&1$/, @output end end context "A command when the cron_log is set and the comand overrides it" do setup do @output = Whenever.cron \ <<-file set :cron_log, 'logfile.log' every 2.hours do command "blahblah", :cron_log => 'otherlog.log' end file end should "output the command with the log syntax appended" do assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output assert_match /^.+ .+ .+ .+ blahblah >> otherlog.log 2>&1$/, @output end end context "A command when the cron_log is set and the comand rejects it" do setup do @output = Whenever.cron \ <<-file set :cron_log, 'logfile.log' every 2.hours do command "blahblah", :cron_log => false end file end should "output the command without the log syntax appended" do assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output assert_match /^.+ .+ .+ .+ blahblah$/, @output end end context "A command when the cron_log is set and is overridden by the :set option" do setup do @output = Whenever.cron :set => 'cron_log=otherlog.log', :string => \ <<-file set :cron_log, 'logfile.log' every 2.hours do command "blahblah" end file end should "output the otherlog.log as the log file" do assert_no_match /.+ .+ .+ .+ blahblah >> logfile.log 2>&1/, @output assert_match /^.+ .+ .+ .+ blahblah >> otherlog.log 2>&1/, @output end end end
26.885057
86
0.575887
bb2b728cc49131b9d9bc56d26667faf7625569f1
1,732
class Covid19CDC::Scraper @@all = [] @@search_array = [] def self.all @@all end def self.search_array @@search_array end #total_cases: total_cases, total_deaths: total_deaths, new_cases: new_cases, new_deaths:new_deaths def self.mass_create_from_api(newsarr, second_array) second_array.each do |newshash| new(newshash[:total_cases], newshash[:total_deaths], newshash[:new_cases], newshash[:new_deaths] ) end newsarr.each do |newshash| new(newshash[:state], newshash[:url], newshash[:cases_reported], newshash[:tranmission] ) end binding.pry end attr_accessor :state, :url, :cases_reported, :tranmission, :total_cases, :total_deaths, :new_cases, :new_deaths def initialize(state, url, cases_reported, tranmission) @state = state @url = url @cases_reported = cases_reported @tranmission = tranmission @total_cases = total_cases @total_deaths = total_deaths @new_cases = new_cases @new_deaths = new_deaths save test end def test binding.pry end def to_s self.name end def name @title.capitalize end def save @@all << self end def save_to_search @@search_array << self end def self.destroy_all @@search_array = [] end def more? !!@description end def full_details <<-DESC TITLE: #{title} DESCRIPTION: #{description} CONTENT: #{content} URL TO ARTICLE : #{url} DESC end end
19.908046
115
0.567552
1a5afd856df62f5d991a5d8aac135dbdfbe842f1
922
module ErrorMethods extend ActiveSupport::Concern included do # Return a 404 for any routing issues rescue_from ActionController::RoutingError, with: :not_found end # Utility function to return a 403 header def forbidden render_error( :forbidden ) end # Utility function to return a 404 header. def not_found render_error( :not_found ) end # Utility function to return a 401 header def unauthorized render_error( :unauthorized ) end protected # Returns an appropriate response for an HTTP status code. This should be used with any of the utility functions # above. def render_error( status_code ) respond_to do |format| format.html { render( action: status_code, status: status_code )} format.all { head( status_code )} end @error_sent = true true # return something so we can chain things end end
17.730769
116
0.687636
1da651531636b1178d644d4e2ced393429e07178
655
# This is the Ruby 1.9-specific kernel file. # Thread features are always available in 1.9. require 'thread.jar' # These are loads so they don't pollute LOADED_FEATURES load 'jruby/kernel19/thread.rb' load 'jruby/kernel19/kernel.rb' load 'jruby/kernel19/proc.rb' load 'jruby/kernel19/process.rb' load 'jruby/kernel19/jruby/process_util.rb' load 'jruby/kernel19/jruby/type.rb' load 'jruby/kernel19/enumerator.rb' load 'jruby/kernel19/enumerable.rb' load 'jruby/kernel19/io.rb' load 'jruby/kernel19/time.rb' load 'jruby/kernel19/gc.rb' load 'jruby/kernel19/encoding/converter.rb' load 'jruby/kernel19/rubygems.rb' unless JRuby::CONFIG.rubygems_disabled?
31.190476
73
0.783206
1a65bab1d7b22d4e568367c85b5528723bdd0c66
5,999
$LOAD_PATH << Rails.root.join("tools").to_s require "fix_auth/auth_model" require "fix_auth/auth_config_model" require "fix_auth/models" RSpec.describe FixAuth::AuthModel do let(:v0_key) { ManageIQ::Password::Key.new("AES-128-CBC", Base64.encode64("9999999999999999"), Base64.encode64("5555555555555555")) } let(:v1_key) { ManageIQ::Password.generate_symmetric } let(:pass) { "password" } let(:enc_v1) { ManageIQ::Password.new.encrypt(pass, "v1", v1_key) } let(:enc_v2) { ManageIQ::Password.new.encrypt(pass) } let(:bad_v2) { "v2:{5555555555555555555555==}" } before do ManageIQ::Password.add_legacy_key(v1_key, :v1) end after do ManageIQ::Password.clear_keys end context "#authentications" do subject { FixAuth::FixAuthentication } let(:contenders) { subject.contenders.select(:name).collect(&:name) } let(:v1_v2) { subject.create(:name => "v2_v1", :password => enc_v2, :auth_key => enc_v1) } let(:v2_v1) { subject.create(:name => "v1_v2", :password => enc_v1, :auth_key => enc_v2) } let(:v1) { subject.create(:name => "v1", :password => enc_v1) } let(:v2) { subject.create(:name => "v2", :password => enc_v2) } let(:badv2) { subject.create(:name => "badv2", :password => bad_v2) } let(:nls) { subject.create(:name => "nls") } let(:not_c) { subject.create(:name => "notc", :password => "nope") } it "should read column_names" do expect(subject.column_names).to include("id", "resource_id", "created_on") end it "should determine available_columns" do expect(subject.available_columns).to eq(%w(password auth_key)) end it "should limit available_columns when not all columns are available" do allow(subject).to receive_messages(:column_names => %w(password id)) expect(subject.available_columns).to eq(%w(password)) end it "should build selection criteria (non selects)" do expect(subject.selection_criteria).to match(/password.*OR.*auth_key/) end it "should not find empty records" do nls.save! expect(contenders).not_to include(nls.name) end it "should find records with encrypted passwords" do [v2, nls].each(&:save!) expect(contenders).to include(v2.name) expect(contenders).not_to include(nls.name) end it "should find viable records among mixed mode records" do [v1_v2, v2_v1].each(&:save!) expect(contenders).to include(v1_v2.name) expect(contenders).to include(v2_v1.name) end context "#recrypt" do it "should not upgrade blank column" do subject.fix_passwords(nls) expect(nls).not_to be_password_changed end it "should upgrade v1 columns" do subject.fix_passwords(v1) expect(v1).to be_password_changed expect(v1.password).to be_encrypted_version(2) end it "should skip over non-encrypted columns" do subject.fix_passwords(not_c) expect(not_c).not_to be_password_changed end it "should raise exception for bad encryption" do expect { subject.fix_passwords(badv2) }.to raise_error(ManageIQ::Password::PasswordError) end it "should replace for bad encryption" do subject.fix_passwords(badv2, :invalid => "other") expect(badv2.password).to be_encrypted("other") end end context "#hardcode" do it "should upgrade v2 columns" do subject.fix_passwords(v2, :hardcode => "newpass") expect(v2.password).to be_encrypted("newpass") expect(v2.password).to be_encrypted_version(2) expect(v2.auth_key).to be_blank end end end context "#miq_database" do subject { FixAuth::FixMiqDatabase } let(:v1) { subject.create(:session_secret_token => enc_v1) } let(:v2) { subject.create(:session_secret_token => enc_v2) } let(:bad) { subject.create(:session_secret_token => bad_v2) } it "uses random numbers for hardcode" do subject.fix_passwords(v1, :hardcode => "newpass") expect(v1.session_secret_token).to be_encrypted_version(2) expect(v1.session_secret_token).to be_encrypted expect(ManageIQ::Password.decrypt(v1.session_secret_token)).to_not eq "newpass" expect(v1.session_secret_token).not_to eq(enc_v2) end it "uses random numbers for invalid" do subject.fix_passwords(bad, :invalid => "newpass") expect(bad.session_secret_token).to be_encrypted_version(2) expect(bad.session_secret_token).to be_encrypted expect(ManageIQ::Password.decrypt(bad.session_secret_token)).to_not eq "newpass" expect(bad.session_secret_token).not_to eq(enc_v2) end it "upgrades" do expect(subject.fix_passwords(v1).session_secret_token).to eq(enc_v2) expect(subject.fix_passwords(v2).session_secret_token).to eq(enc_v2) end end context "#miq_ae_values" do subject { FixAuth::FixMiqAeValue } let(:pass_field) { FixAuth::FixMiqAeField.new(:name => "pass", :datatype => "password") } let(:v2) { subject.create(:field => pass_field, :value => enc_v2) } it "should update with complex contenders" do v2 # make sure record exists subject.run(:silent => true) expect(v2.reload.value).to be_encrypted_version(2) end end context "#settings_change" do subject { FixAuth::FixSettingsChange } let(:v1) { subject.create(:key => "/v1/password", :value => enc_v1) } let(:v2) { subject.create(:key => "/v2/password", :value => enc_v2) } let(:bad) { subject.create(:key => "/bad/password", :value => bad_v2) } it "with hardcode" do subject.fix_passwords(v1, :hardcode => pass) expect(v1.value).to eq(enc_v2) end it "with invalid" do subject.fix_passwords(bad, :invalid => pass) expect(bad.value).to eq(enc_v2) end it "upgrades" do expect(subject.fix_passwords(v1).value).to eq(enc_v2) expect(subject.fix_passwords(v2).value).to eq(enc_v2) end end end
35.708333
136
0.670278
4a39e304f643fa0a963efeb1a972fb0c9a3038dc
497
module SpreeSalesPricing class Engine < Rails::Engine require 'spree/core' isolate_namespace Spree engine_name 'spree_sales_pricing' # use rspec for tests config.generators do |g| g.test_framework :rspec end def self.activate Dir.glob(File.join(File.dirname(__FILE__), '../../app/**/*_decorator*.rb')) do |c| Rails.configuration.cache_classes ? require(c) : load(c) end end config.to_prepare(&method(:activate).to_proc) end end
23.666667
88
0.665996
b9abf12ee35f442bda4eebaf6f3255e03802a2ac
14,300
require 'spec_helper' describe 'cis_hardening::logaudit::accounting' do on_supported_os.each do |os, os_facts| context "on #{os}" do let(:facts) { os_facts } # Check for default class it { is_expected.to contain_class('cis_hardening::logaudit::accounting') } # Ensure Auditing is enabled - Section 4.1.1 # Ensure that auditd is installed - Section 4.1.1.1 it { is_expected.to contain_package('auditd').with( 'ensure' => 'present', ) } it { is_expected.to contain_package('audit-libs').with( 'ensure' => 'present', ) } # Ensure that Exec to notify from auditd rules changes - Section 4.1.1.2 it { is_expected.to contain_service('auditd').with( 'ensure' => 'running', 'enable' => true, 'hasstatus' => true, 'hasrestart' => true, ).that_requires('File[/etc/audit/audit.rules') } it { is_expected.to contain_exec('restart_auditd').with( 'path' => '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin', 'command' => '/bin/systemctl restart auditd', ).that_requires('Package[audit]') } # Ensure that Ensure audit log storage size is configured - Section 4.1.1.1 it { is_expected.to contain_file_line('set_auditd_logfile_size').with( 'ensure' => 'present', 'path' => '/etc/audit/auditd.conf', 'line' => 'max_log_file = 1024', 'match' => '^max_log_file\ \=', ).that_notifies('Exec[restart_auditd]') } # Ensure that system is disabled when audit logs are full - Section 4.1.1.2 it { is_expected.to contain_file_line('full_logfile_notify_action').with( 'ensure' => 'present', 'path' => '/etc/audit/auditd.conf', 'line' => 'space_left_action = email', 'match' => '^space_left_action\ \=', ).that_notifies('Exec[restart_auditd]') } it { is_expected.to contain_file_line('set_action_mail_account').with( 'ensure' => 'present', 'path' => '/etc/audit/auditd.conf', 'line' => 'action_mail_acct = root', 'match' => '^action_mail_acct\ \=', ).that_notifies('Exec[restart_auditd]') } it { is_expected.to contain_file_line('set_admin_space_left_action').with( 'ensure' => 'present', 'path' => '/etc/audit/auditd.conf', 'line' => 'admin_space_left_action = SYSLOG', 'match' => '^admin_space_left_action\ \=', ).that_notifies('Exec[restart_auditd]') } # Ensure that Ensure audit logs are not automatically deleted - Section 4.1.1.3 it { is_expected.to contain_file_line('set_max_logfile_action').with( 'ensure' => 'present', 'path' => '/etc/audit/auditd.conf', 'line' => 'max_log_file_action = keep_logs', 'match' => '^max_log_file_action\ \=', ) } # Ensure that Ensure auditd service is enabled - Section 4.1.2 it { is_expected.to contain_service('auditd').with( 'ensure' => 'running', 'enable' => true, 'hasstatus' => true, 'hasrestart' => true, ) } # Ensure that Ensure defaults directory is present for grub settings - Section 4.1.3 prerequisites it { is_expected.to contain_file('/etc/default').with( 'ensure' => 'directory', 'owner' => 'root', 'group' => 'root', 'mode' => '0755', ) } it { is_expected.to contain_file('/etc/default/grub').with( 'ensure' => 'file', 'owner' => 'root', 'group' => 'root', 'mode' => '0644', ).that_requires('File[/etc/default]') } # Ensure that Ensure events that modify date and time information are collected - Section 4.1.4 it { is_expected.to contain_file_line('time_change_64bit_item1').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time-change', ) } it { is_expected.to contain_file_line('time_change_64bit_item2').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S clock_settime -k time-change', ) } it { is_expected.to contain_file_line('time_change_64bit_item3').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/localtime -p wa -k time-change', ) } # Ensure that Ensure events that modify user/group information are collected - Section 4.1.5 it { is_expected.to contain_file_line('ownerchange_group').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/group -p wa -k identity', ) } it { is_expected.to contain_file_line('ownerchange_passwd').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/passwd -p wa -k identity', ) } it { is_expected.to contain_file_line('ownerchange_gshadow').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/gshadow -p wa -k identity', ) } it { is_expected.to contain_file_line('ownerchange_shadow').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/shadow -p wa -k identity', ) } it { is_expected.to contain_file_line('ownerchange_opasswd').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/security/opasswd -p wa -k identity', ) } # Ensure that Ensure events that modify the system's network environment are collected - Section 4.1.6 it { is_expected.to contain_file_line('network_namechanges').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S sethostname -S setdomainname -k system-locale', ) } it { is_expected.to contain_file_line('network_issue').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/issue -p wa -k system-locale', ) } it { is_expected.to contain_file_line('network_issuedotnet').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/issue.net -p wa -k system-locale', ) } it { is_expected.to contain_file_line('network_network').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/sysconfig/network -p wa -k system-locale', ) } it { is_expected.to contain_file_line('network_networkscripts').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/sysconfig/network-scripts/ -p wa -k system-locale', ) } # Ensure that Ensure events that modify the system's Mandatory Access Controls are collected - Section 4.1.7 it { is_expected.to contain_file_line('macpolicy_selinux').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/selinux/ -p wa -k MAC-policy', ) } it { is_expected.to contain_file_line('macpolicy_selinuxshare').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /usr/share/selinux/ -p wa -k MAC-policy', ) } # Ensure that Ensure login and logout events are collected - Section 4.1.8 it { is_expected.to contain_file_line('lastlogin').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /var/log/lastlog -p wa -k logins', ) } it { is_expected.to contain_file_line('faillock').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /var/run/faillock/ -p wa -k logins', ) } # Ensure that Ensure session initiation information is collected - Section 4.1.9 it { is_expected.to contain_file_line('utmp_entry').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /var/run/utmp -p wa -k session', ) } it { is_expected.to contain_file_line('wtmp_entry').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /var/run/wtmp -p wa -k logins', ) } it { is_expected.to contain_file_line('btmp_entry').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /var/run/btmp -p wa -k logins', ) } # Ensure that Ensure discretionary access control permission modification events are collected - Section 4.1.10 it { is_expected.to contain_file_line('chmod_cmds').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S chmod -S fchmod -S fchmodat -F auid>=1000 -F auid!=4294967295 -k perm_mod', ) } it { is_expected.to contain_file_line('chown_cmds').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S chown -S fchown -S fchownat -S lchown -F auid>=1000 -F auid!=4294967295 -k perm_mod', ) } it { is_expected.to contain_file_line('xattr_cmds').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S setxattr -S lsetxattr -S fsetxattr -S removexattr -S lremovexattr -S fremovexattr -F auid>=1000 -F auid!=4294967295 -k perm_mod', ) } # Ensure that Ensure unsuccessful unauthorized file access attempts are collected - Section 4.1.11 it { is_expected.to contain_file_line('file_truncate').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S creat -S open -S openat -S truncate -S ftruncate -F exit=-EACCES -F auid>=1000 -F auid!=4294967295 -k access', ) } # Ensure that Ensure use of privileged commands is collected - Section 4.1.12 **unused** # Ensure that Ensure succesful filesystem mounts are collected - Section 4.1.13 it { is_expected.to contain_file_line('mount_cmds').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S mount -F auid>=1000 -F auid!=4294967295 -k mounts', ) } # Ensure that Ensure file deletion events by users are captured - Section 4.1.14 it { is_expected.to contain_file_line('file_deletions').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete', ) } # Ensure that Ensure changes to system administration scope (sudoers) is collected - Section 4.1.15 it { is_expected.to contain_file_line('sudoers_file').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/sudoers -p wa -k scope', ) } it { is_expected.to contain_file_line('sudoers_dir').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /etc/sudoers.d/ -p wa -k scope', ) } # Ensure that Ensure system administrator actions (sudolog) are collected - Section 4.1.16 it { is_expected.to contain_file_line('sudolog').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /var/log/sudo.log -p wa -k actions', ) } # Ensure that Ensure Kernel module loading and unloading are collected - Section 4.1.17 it { is_expected.to contain_file_line('check_insmod').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /sbin/insmod -p x -k modules', ) } it { is_expected.to contain_file_line('check_rmmod').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /sbin/rmmod -p x -k modules', ) } it { is_expected.to contain_file_line('check_modprobe').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-w /sbin/modprobe -p x -k modules', ) } it { is_expected.to contain_file_line('check_modulestate').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-a always,exit -F arch=b64 -S init_module -S delete_module -k modules', ) } it { is_expected.to contain_file_line('make_auditd_immutable').with( 'ensure' => 'present', 'path' => '/etc/audit/audit.rules', 'line' => '-e 2', 'match' => '^-e\ ', 'append_on_no_match' => true, ) } # Ensure manifest compiles with all dependencies it { is_expected.to compile.with_all_deps } end end end
33.806147
182
0.533706
33b79b41233353e480f210d43cfd7cdaf76773ce
73,429
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::DataFactory::Mgmt::V2018_06_01 # # The Azure Data Factory V2 management API provides a RESTful set of web # services that interact with Azure Data Factory V2 services. # class Triggers include MsRestAzure # # Creates and initializes a new instance of the Triggers class. # @param client service class for accessing basic functionality. # def initialize(client) @client = client end # @return [DataFactoryManagementClient] reference to the DataFactoryManagementClient attr_reader :client # # Lists triggers. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Array<TriggerResource>] operation results. # def list_by_factory(resource_group_name, factory_name, custom_headers:nil) first_page = list_by_factory_as_lazy(resource_group_name, factory_name, custom_headers:custom_headers) first_page.get_all_items end # # Lists triggers. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @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 list_by_factory_with_http_info(resource_group_name, factory_name, custom_headers:nil) list_by_factory_async(resource_group_name, factory_name, custom_headers:custom_headers).value! end # # Lists triggers. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @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 list_by_factory_async(resource_group_name, factory_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.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.DataFactory/factories/{factoryName}/triggers' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_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::DataFactory::Mgmt::V2018_06_01::Models::TriggerListResponse.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 # # Query triggers. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param filter_parameters [TriggerFilterParameters] Parameters to filter the # triggers. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerQueryResponse] operation results. # def query_by_factory(resource_group_name, factory_name, filter_parameters, custom_headers:nil) response = query_by_factory_async(resource_group_name, factory_name, filter_parameters, custom_headers:custom_headers).value! response.body unless response.nil? end # # Query triggers. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param filter_parameters [TriggerFilterParameters] Parameters to filter the # triggers. # @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 query_by_factory_with_http_info(resource_group_name, factory_name, filter_parameters, custom_headers:nil) query_by_factory_async(resource_group_name, factory_name, filter_parameters, custom_headers:custom_headers).value! end # # Query triggers. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param filter_parameters [TriggerFilterParameters] Parameters to filter the # triggers. # @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 query_by_factory_async(resource_group_name, factory_name, filter_parameters, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'filter_parameters is nil' if filter_parameters.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::DataFactory::Mgmt::V2018_06_01::Models::TriggerFilterParameters.mapper() request_content = @client.serialize(request_mapper, filter_parameters) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/querytriggers' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_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(:post, 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::DataFactory::Mgmt::V2018_06_01::Models::TriggerQueryResponse.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 # # Creates or updates a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param trigger [TriggerResource] Trigger resource definition. # @param if_match [String] ETag of the trigger entity. Should only be # specified for update, for which it should match existing entity or can be * # for unconditional update. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerResource] operation results. # def create_or_update(resource_group_name, factory_name, trigger_name, trigger, if_match:nil, custom_headers:nil) response = create_or_update_async(resource_group_name, factory_name, trigger_name, trigger, if_match:if_match, custom_headers:custom_headers).value! response.body unless response.nil? end # # Creates or updates a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param trigger [TriggerResource] Trigger resource definition. # @param if_match [String] ETag of the trigger entity. Should only be # specified for update, for which it should match existing entity or can be * # for unconditional update. # @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_or_update_with_http_info(resource_group_name, factory_name, trigger_name, trigger, if_match:nil, custom_headers:nil) create_or_update_async(resource_group_name, factory_name, trigger_name, trigger, if_match:if_match, custom_headers:custom_headers).value! end # # Creates or updates a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param trigger [TriggerResource] Trigger resource definition. # @param if_match [String] ETag of the trigger entity. Should only be # specified for update, for which it should match existing entity or can be * # for unconditional update. # @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_or_update_async(resource_group_name, factory_name, trigger_name, trigger, if_match:nil, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, 'trigger_name is nil' if trigger_name.nil? fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MaxLength': '260'" if !trigger_name.nil? && trigger_name.length > 260 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MinLength': '1'" if !trigger_name.nil? && trigger_name.length < 1 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'" if !trigger_name.nil? && trigger_name.match(Regexp.new('^^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.nil? fail ArgumentError, 'trigger is nil' if trigger.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['If-Match'] = if_match unless if_match.nil? request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? # Serialize Request request_mapper = Azure::DataFactory::Mgmt::V2018_06_01::Models::TriggerResource.mapper() request_content = @client.serialize(request_mapper, trigger) request_content = request_content != nil ? JSON.generate(request_content, quirks_mode: true) : nil path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/triggers/{triggerName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_name,'triggerName' => trigger_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::DataFactory::Mgmt::V2018_06_01::Models::TriggerResource.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 # # Gets a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param if_none_match [String] ETag of the trigger entity. Should only be # specified for get. If the ETag matches the existing entity tag, or if * was # provided, then no content will be returned. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerResource] operation results. # def get(resource_group_name, factory_name, trigger_name, if_none_match:nil, custom_headers:nil) response = get_async(resource_group_name, factory_name, trigger_name, if_none_match:if_none_match, custom_headers:custom_headers).value! response.body unless response.nil? end # # Gets a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param if_none_match [String] ETag of the trigger entity. Should only be # specified for get. If the ETag matches the existing entity tag, or if * was # provided, then no content will be returned. # @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, factory_name, trigger_name, if_none_match:nil, custom_headers:nil) get_async(resource_group_name, factory_name, trigger_name, if_none_match:if_none_match, custom_headers:custom_headers).value! end # # Gets a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param if_none_match [String] ETag of the trigger entity. Should only be # specified for get. If the ETag matches the existing entity tag, or if * was # provided, then no content will be returned. # @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, factory_name, trigger_name, if_none_match:nil, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, 'trigger_name is nil' if trigger_name.nil? fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MaxLength': '260'" if !trigger_name.nil? && trigger_name.length > 260 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MinLength': '1'" if !trigger_name.nil? && trigger_name.length < 1 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'" if !trigger_name.nil? && trigger_name.match(Regexp.new('^^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.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['If-None-Match'] = if_none_match unless if_none_match.nil? request_headers['accept-language'] = @client.accept_language unless @client.accept_language.nil? path_template = 'subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/triggers/{triggerName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_name,'triggerName' => trigger_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 || status_code == 304 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::DataFactory::Mgmt::V2018_06_01::Models::TriggerResource.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 # # Deletes a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def delete(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = delete_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! nil end # # Deletes a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 delete_with_http_info(resource_group_name, factory_name, trigger_name, custom_headers:nil) delete_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! end # # Deletes a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 delete_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, 'trigger_name is nil' if trigger_name.nil? fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MaxLength': '260'" if !trigger_name.nil? && trigger_name.length > 260 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MinLength': '1'" if !trigger_name.nil? && trigger_name.length < 1 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'" if !trigger_name.nil? && trigger_name.match(Regexp.new('^^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.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.DataFactory/factories/{factoryName}/triggers/{triggerName}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_name,'triggerName' => trigger_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:delete, 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 || status_code == 204 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? result end promise.execute end # # Subscribe event trigger to events. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerSubscriptionOperationStatus] operation results. # def subscribe_to_events(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = subscribe_to_events_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def subscribe_to_events_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) # Send request promise = begin_subscribe_to_events_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| result_mapper = Azure::DataFactory::Mgmt::V2018_06_01::Models::TriggerSubscriptionOperationStatus.mapper() parsed_response = @client.deserialize(result_mapper, parsed_response) end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Get a trigger's event subscription status. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerSubscriptionOperationStatus] operation results. # def get_event_subscription_status(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = get_event_subscription_status_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # Get a trigger's event subscription status. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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_event_subscription_status_with_http_info(resource_group_name, factory_name, trigger_name, custom_headers:nil) get_event_subscription_status_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! end # # Get a trigger's event subscription status. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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_event_subscription_status_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, 'trigger_name is nil' if trigger_name.nil? fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MaxLength': '260'" if !trigger_name.nil? && trigger_name.length > 260 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MinLength': '1'" if !trigger_name.nil? && trigger_name.length < 1 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'" if !trigger_name.nil? && trigger_name.match(Regexp.new('^^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.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.DataFactory/factories/{factoryName}/triggers/{triggerName}/getEventSubscriptionStatus' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_name,'triggerName' => trigger_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, 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::DataFactory::Mgmt::V2018_06_01::Models::TriggerSubscriptionOperationStatus.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 # # Unsubscribe event trigger from events. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerSubscriptionOperationStatus] operation results. # def unsubscribe_from_events(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = unsubscribe_from_events_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def unsubscribe_from_events_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) # Send request promise = begin_unsubscribe_from_events_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| result_mapper = Azure::DataFactory::Mgmt::V2018_06_01::Models::TriggerSubscriptionOperationStatus.mapper() parsed_response = @client.deserialize(result_mapper, parsed_response) end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Starts a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def start(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = start_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def start_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) # Send request promise = begin_start_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Stops a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # def stop(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = stop_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! nil end # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [Concurrent::Promise] promise which provides async access to http # response. # def stop_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) # Send request promise = begin_stop_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers) promise = promise.then do |response| # Defining deserialization method. deserialize_method = lambda do |parsed_response| end # Waiting for response. @client.get_long_running_operation_result(response, deserialize_method) end promise end # # Subscribe event trigger to events. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerSubscriptionOperationStatus] operation results. # def begin_subscribe_to_events(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = begin_subscribe_to_events_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # Subscribe event trigger to events. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 begin_subscribe_to_events_with_http_info(resource_group_name, factory_name, trigger_name, custom_headers:nil) begin_subscribe_to_events_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! end # # Subscribe event trigger to events. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 begin_subscribe_to_events_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, 'trigger_name is nil' if trigger_name.nil? fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MaxLength': '260'" if !trigger_name.nil? && trigger_name.length > 260 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MinLength': '1'" if !trigger_name.nil? && trigger_name.length < 1 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'" if !trigger_name.nil? && trigger_name.match(Regexp.new('^^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.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.DataFactory/factories/{factoryName}/triggers/{triggerName}/subscribeToEvents' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_name,'triggerName' => trigger_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, 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 || status_code == 202 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::DataFactory::Mgmt::V2018_06_01::Models::TriggerSubscriptionOperationStatus.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 # # Unsubscribe event trigger from events. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerSubscriptionOperationStatus] operation results. # def begin_unsubscribe_from_events(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = begin_unsubscribe_from_events_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! response.body unless response.nil? end # # Unsubscribe event trigger from events. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 begin_unsubscribe_from_events_with_http_info(resource_group_name, factory_name, trigger_name, custom_headers:nil) begin_unsubscribe_from_events_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! end # # Unsubscribe event trigger from events. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 begin_unsubscribe_from_events_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, 'trigger_name is nil' if trigger_name.nil? fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MaxLength': '260'" if !trigger_name.nil? && trigger_name.length > 260 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MinLength': '1'" if !trigger_name.nil? && trigger_name.length < 1 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'" if !trigger_name.nil? && trigger_name.match(Regexp.new('^^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.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.DataFactory/factories/{factoryName}/triggers/{triggerName}/unsubscribeFromEvents' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_name,'triggerName' => trigger_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, 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 || status_code == 202 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::DataFactory::Mgmt::V2018_06_01::Models::TriggerSubscriptionOperationStatus.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 # # Starts a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_start(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = begin_start_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! nil end # # Starts a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 begin_start_with_http_info(resource_group_name, factory_name, trigger_name, custom_headers:nil) begin_start_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! end # # Starts a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 begin_start_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, 'trigger_name is nil' if trigger_name.nil? fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MaxLength': '260'" if !trigger_name.nil? && trigger_name.length > 260 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MinLength': '1'" if !trigger_name.nil? && trigger_name.length < 1 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'" if !trigger_name.nil? && trigger_name.match(Regexp.new('^^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.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.DataFactory/factories/{factoryName}/triggers/{triggerName}/start' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_name,'triggerName' => trigger_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, 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? result end promise.execute end # # Stops a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # def begin_stop(resource_group_name, factory_name, trigger_name, custom_headers:nil) response = begin_stop_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! nil end # # Stops a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 begin_stop_with_http_info(resource_group_name, factory_name, trigger_name, custom_headers:nil) begin_stop_async(resource_group_name, factory_name, trigger_name, custom_headers:custom_headers).value! end # # Stops a trigger. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param trigger_name [String] The trigger name. # @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 begin_stop_async(resource_group_name, factory_name, trigger_name, custom_headers:nil) fail ArgumentError, '@client.subscription_id is nil' if @client.subscription_id.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, 'factory_name is nil' if factory_name.nil? fail ArgumentError, "'factory_name' should satisfy the constraint - 'MaxLength': '63'" if !factory_name.nil? && factory_name.length > 63 fail ArgumentError, "'factory_name' should satisfy the constraint - 'MinLength': '3'" if !factory_name.nil? && factory_name.length < 3 fail ArgumentError, "'factory_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$'" if !factory_name.nil? && factory_name.match(Regexp.new('^^[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*$$')).nil? fail ArgumentError, 'trigger_name is nil' if trigger_name.nil? fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MaxLength': '260'" if !trigger_name.nil? && trigger_name.length > 260 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'MinLength': '1'" if !trigger_name.nil? && trigger_name.length < 1 fail ArgumentError, "'trigger_name' should satisfy the constraint - 'Pattern': '^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$'" if !trigger_name.nil? && trigger_name.match(Regexp.new('^^[A-Za-z0-9_][^<>*#.%&:\\+?/]*$$')).nil? fail ArgumentError, '@client.api_version is nil' if @client.api_version.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.DataFactory/factories/{factoryName}/triggers/{triggerName}/stop' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], path_params: {'subscriptionId' => @client.subscription_id,'resourceGroupName' => resource_group_name,'factoryName' => factory_name,'triggerName' => trigger_name}, query_params: {'api-version' => @client.api_version}, headers: request_headers.merge(custom_headers || {}), base_url: request_url } promise = @client.make_request_async(:post, 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? result end promise.execute end # # Lists triggers. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerListResponse] operation results. # def list_by_factory_next(next_page_link, custom_headers:nil) response = list_by_factory_next_async(next_page_link, custom_headers:custom_headers).value! response.body unless response.nil? end # # Lists triggers. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @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 list_by_factory_next_with_http_info(next_page_link, custom_headers:nil) list_by_factory_next_async(next_page_link, custom_headers:custom_headers).value! end # # Lists triggers. # # @param next_page_link [String] The NextLink from the previous successful call # to List operation. # @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 list_by_factory_next_async(next_page_link, custom_headers:nil) fail ArgumentError, 'next_page_link is nil' if next_page_link.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 = '{nextLink}' request_url = @base_url || @client.base_url options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], skip_encoding_path_params: {'nextLink' => next_page_link}, 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::DataFactory::Mgmt::V2018_06_01::Models::TriggerListResponse.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 # # Lists triggers. # # @param resource_group_name [String] The resource group name. # @param factory_name [String] The factory name. # @param custom_headers [Hash{String => String}] A hash of custom headers that # will be added to the HTTP request. # # @return [TriggerListResponse] which provide lazy access to pages of the # response. # def list_by_factory_as_lazy(resource_group_name, factory_name, custom_headers:nil) response = list_by_factory_async(resource_group_name, factory_name, custom_headers:custom_headers).value! unless response.nil? page = response.body page.next_method = Proc.new do |next_page_link| list_by_factory_next_async(next_page_link, custom_headers:custom_headers) end page end end end end
53.441776
219
0.701943
e2a3846531e1113889acad8485da48d5606ed117
3,394
class Libressl < Formula desc "Version of the SSL/TLS protocol forked from OpenSSL" homepage "https://www.libressl.org/" # Please ensure when updating version the release is from stable branch. url "https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-3.2.3.tar.gz" mirror "https://mirrorservice.org/pub/OpenBSD/LibreSSL/libressl-3.2.3.tar.gz" sha256 "412dc2baa739228c7779e93eb07cd645d5c964d2f2d837a9fd56db7498463d73" license "OpenSSL" livecheck do url :homepage regex(/latest stable release is (\d+(?:\.\d+)+)/i) end bottle do sha256 "c5060969c420fd7d097a372aeb1c083cb65f26ce4a3a7d760a3e770f56faef0c" => :big_sur sha256 "f4d6d7f7decf667206d58554e63810eec52a20e869d4a74c6c1756ceef77ac8d" => :arm64_big_sur sha256 "4a11c712731e131c223b4b73f25507b1c1c826821257b538b1b5f5f05c0f0736" => :catalina sha256 "a84aa0482ece558c5afe0f2bae8ea6175f61e912778a5e9effa1c959b68a56b6" => :mojave sha256 "66bd209a42da9acedf76e642d2e58015f12808122a15c887b9920978e4e25537" => :x86_64_linux end head do url "https://github.com/libressl-portable/portable.git" depends_on "autoconf" => :build depends_on "automake" => :build depends_on "libtool" => :build end keg_only :provided_by_macos def install args = %W[ --disable-dependency-tracking --disable-silent-rules --prefix=#{prefix} --with-openssldir=#{etc}/libressl --sysconfdir=#{etc}/libressl ] system "./autogen.sh" if build.head? system "./configure", *args system "make" system "make", "check" system "make", "install" end def post_install return unless OS.mac? keychains = %w[ /System/Library/Keychains/SystemRootCertificates.keychain ] certs_list = `security find-certificate -a -p #{keychains.join(" ")}` certs = certs_list.scan( /-----BEGIN CERTIFICATE-----.*?-----END CERTIFICATE-----/m, ) valid_certs = certs.select do |cert| IO.popen("#{bin}/openssl x509 -inform pem -checkend 0 -noout", "w") do |openssl_io| openssl_io.write(cert) openssl_io.close_write end $CHILD_STATUS.success? end # LibreSSL install a default pem - We prefer to use macOS for consistency. rm_f %W[#{etc}/libressl/cert.pem #{etc}/libressl/cert.pem.default] (etc/"libressl/cert.pem").atomic_write(valid_certs.join("\n")) end def caveats <<~EOS A CA file has been bootstrapped using certificates from the SystemRoots keychain. To add additional certificates (e.g. the certificates added in the System keychain), place .pem files in #{etc}/libressl/certs and run #{opt_bin}/openssl certhash #{etc}/libressl/certs EOS end test do # Make sure the necessary .cnf file exists, otherwise LibreSSL gets moody. assert_predicate HOMEBREW_PREFIX/"etc/libressl/openssl.cnf", :exist?, "LibreSSL requires the .cnf file for some functionality" # Check LibreSSL itself functions as expected. (testpath/"testfile.txt").write("This is a test file") expected_checksum = "e2d0fe1585a63ec6009c8016ff8dda8b17719a637405a4e23c0ff81339148249" system "#{bin}/openssl", "dgst", "-sha256", "-out", "checksum.txt", "testfile.txt" open("checksum.txt") do |f| checksum = f.read(100).split("=").last.strip assert_equal checksum, expected_checksum end end end
33.27451
95
0.696818
edd31ec06e6d81b4469cd3b1a7f3df6fb2762887
384
require 'fix/protocol/messages/md_entry' module Fix module Protocol module Messages # # A market data entry type component, see http://www.onixs.biz/fix-dictionary/4.4/tagNum_269.html # class MdEntryType < MessagePart field :md_entry_type, tag: 269, required: true, mapping: FP::Messages::MdEntry::MD_ENTRY_TYPES end end end end
20.210526
103
0.677083
08bf9a3a06c00fc7204ed55e13357a98ce1ce8b0
1,371
# Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ApiManagement::Mgmt::V2017_03_01 module Models # # Defines values for TemplateName # module TemplateName ApplicationApprovedNotificationMessage = "applicationApprovedNotificationMessage" AccountClosedDeveloper = "accountClosedDeveloper" QuotaLimitApproachingDeveloperNotificationMessage = "quotaLimitApproachingDeveloperNotificationMessage" NewDeveloperNotificationMessage = "newDeveloperNotificationMessage" EmailChangeIdentityDefault = "emailChangeIdentityDefault" InviteUserNotificationMessage = "inviteUserNotificationMessage" NewCommentNotificationMessage = "newCommentNotificationMessage" ConfirmSignUpIdentityDefault = "confirmSignUpIdentityDefault" NewIssueNotificationMessage = "newIssueNotificationMessage" PurchaseDeveloperNotificationMessage = "purchaseDeveloperNotificationMessage" PasswordResetIdentityDefault = "passwordResetIdentityDefault" PasswordResetByAdminNotificationMessage = "passwordResetByAdminNotificationMessage" RejectDeveloperNotificationMessage = "rejectDeveloperNotificationMessage" RequestDeveloperNotificationMessage = "requestDeveloperNotificationMessage" end end end
48.964286
109
0.817651
5d66f755c232a7775c33ff48dfa8c366eed8dad4
1,887
class XboxLiveApi class Achievement # @return [String] the name of the achievement attr_reader :name # @return [Fixnum] a unique identifier attr_reader :id # @return [Boolean] true if the achievement has been unlocked by the player attr_reader :is_unlocked # @return [String] the url for icon on xbox.com attr_reader :icon_url # @return [Boolean] true if the achievement is secret attr_reader :is_secret # @return [String] the description to be used when the achievement is unlocked attr_reader :unlocked_description # @return [String] the description to be used when the achievement is locked attr_reader :locked_description # @return [Fixnum] the gamescore value awarded for unlocking this achievement attr_reader :value # @return [String] the date the achievement was unlocked. The formatting is dependent # on the actual xbox live api. Xbox 360 achievements have the form "2015-07-25T13:55:01.5300000Z". # Xbox one achievements have the form "2015-07-25T13:16:50.2887979Z". attr_reader :time_unlocked def initialize(name: nil, id: nil, is_unlocked: nil, icon_url: nil, is_secret: nil, unlocked_description: nil, locked_description: nil, value: nil, time_unlocked: nil) @name = name @id = id @is_unlocked = is_unlocked @icon_url = icon_url @is_secret = is_secret @unlocked_description = unlocked_description @locked_description = locked_description @value = value @time_unlocked = time_unlocked end def ==(o) o.instance_of?(self.class) && o.state == state end def hash state.hash end protected def state [@name, @id, @is_unlocked, @icon_url, @is_secret, @unlocked_description, @locked_description, @value, @time_unlocked] end end end
34.944444
106
0.682035
1ad4585d2537fd48a967db818bceef8c8f9d126e
67,667
# frozen_string_literal: true describe Grape::Validations do subject { Class.new(Grape::API) } def app subject end def declared_params subject.namespace_stackable(:declared_params).flatten end describe 'params' do context 'optional' do before do subject.params do optional :a_number, regexp: /^[0-9]+$/ optional :attachment, type: File end subject.get '/optional' do 'optional works!' end end it 'validates when params is present' do get '/optional', a_number: 'string' expect(last_response.status).to eq(400) expect(last_response.body).to eq('a_number is invalid') get '/optional', a_number: 45 expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional works!') end it "doesn't validate when param not present" do get '/optional', a_number: nil, attachment: nil expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional works!') end it 'adds to declared parameters' do subject.params do optional :some_param end expect(declared_params).to eq([:some_param]) end end context 'optional using Grape::Entity documentation' do def define_optional_using documentation = { field_a: { type: String }, field_b: { type: String } } subject.params do optional :all, using: documentation end end before do define_optional_using subject.get '/optional' do 'optional with using works' end end it 'adds entity documentation to declared params' do define_optional_using expect(declared_params).to eq(%i[field_a field_b]) end it 'works when field_a and field_b are not present' do get '/optional' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional with using works') end it 'works when field_a is present' do get '/optional', field_a: 'woof' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional with using works') end it 'works when field_b is present' do get '/optional', field_b: 'woof' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional with using works') end end context 'required' do before do subject.params do requires :key, type: String end subject.get('/required') { 'required works' } subject.put('/required') { { key: params[:key] }.to_json } end it 'errors when param not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('key is missing') end it "doesn't throw a missing param when param is present" do get '/required', key: 'cool' expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end it 'adds to declared parameters' do subject.params do requires :some_param end expect(declared_params).to eq([:some_param]) end it 'works when required field is present but nil' do put '/required', { key: nil }.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(200) expect(JSON.parse(last_response.body)).to eq('key' => nil) end end context 'requires with nested params' do before do subject.params do requires :first_level, type: Hash do optional :second_level, type: Array do requires :value, type: Integer optional :name, type: String optional :third_level, type: Array do requires :value, type: Integer optional :name, type: String optional :fourth_level, type: Array do requires :value, type: Integer optional :name, type: String end end end end end subject.put('/required') { 'required works' } end let(:request_params) do { first_level: { second_level: [ { value: 1, name: 'Lisa' }, { value: 2, name: 'James', third_level: [ { value: 'three', name: 'Sophie' }, { value: 4, name: 'Jenny', fourth_level: [ { name: 'Samuel' }, { value: 6, name: 'Jane' } ] } ] } ] } } end it 'validates correctly in deep nested params' do put '/required', request_params.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(400) expect(last_response.body).to eq( 'first_level[second_level][1][third_level][0][value] is invalid, ' \ 'first_level[second_level][1][third_level][1][fourth_level][0][value] is missing' ) end end context 'requires :all using Grape::Entity documentation' do def define_requires_all documentation = { required_field: { type: String }, optional_field: { type: String } } subject.params do requires :all, except: :optional_field, using: documentation end end before do define_requires_all subject.get '/required' do 'required works' end end it 'adds entity documentation to declared params' do define_requires_all expect(declared_params).to eq(%i[required_field optional_field]) end it 'errors when required_field is not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('required_field is missing') end it 'works when required_field is present' do get '/required', required_field: 'woof' expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end end context 'requires :none using Grape::Entity documentation' do def define_requires_none documentation = { required_field: { type: String }, optional_field: { type: String } } subject.params do requires :none, except: :required_field, using: documentation end end before do define_requires_none subject.get '/required' do 'required works' end end it 'adds entity documentation to declared params' do define_requires_none expect(declared_params).to eq(%i[required_field optional_field]) end it 'errors when required_field is not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('required_field is missing') end it 'works when required_field is present' do get '/required', required_field: 'woof' expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end end context 'requires :all or :none but except a non-existent field using Grape::Entity documentation' do context 'requires :all' do def define_requires_all documentation = { required_field: { type: String }, optional_field: { type: String } } subject.params do requires :all, except: :non_existent_field, using: documentation end end it 'adds only the entity documentation to declared params, nothing more' do define_requires_all expect(declared_params).to eq(%i[required_field optional_field]) end end context 'requires :none' do def define_requires_none documentation = { required_field: { type: String }, optional_field: { type: String } } subject.params do requires :none, except: :non_existent_field, using: documentation end end it 'adds only the entity documentation to declared params, nothing more' do expect { define_requires_none }.to raise_error(ArgumentError) end end end context 'required with an Array block' do before do subject.params do requires :items, type: Array do requires :key end end subject.get('/required') { 'required works' } subject.put('/required') { { items: params[:items] }.to_json } end it 'errors when param not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is missing') end it 'errors when param is not an Array' do get '/required', items: 'hello' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') get '/required', items: { key: 'foo' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') end it "doesn't throw a missing param when param is present" do get '/required', items: [{ key: 'hello' }, { key: 'world' }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end it "doesn't throw a missing param when param is present but empty" do put '/required', { items: [] }.to_json, 'CONTENT_TYPE' => 'application/json' expect(last_response.status).to eq(200) expect(JSON.parse(last_response.body)).to eq('items' => []) end it 'adds to declared parameters' do subject.params do requires :items, type: Array do requires :key end end expect(declared_params).to eq([items: [:key]]) end end # Ensure there is no leakage between declared Array types and # subsequent Hash types context 'required with an Array and a Hash block' do before do subject.params do requires :cats, type: Array[String], default: [] requires :items, type: Hash do requires :key end end subject.get '/required' do 'required works' end end it 'does not output index [0] for Hash types' do get '/required', cats: ['Garfield'], items: { foo: 'bar' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[key] is missing') end end context 'required with a Hash block' do before do subject.params do requires :items, type: Hash do requires :key end end subject.get '/required' do 'required works' end end it 'errors when param not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is missing, items[key] is missing') end it 'errors when nested param not present' do get '/required', items: { foo: 'bar' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[key] is missing') end it 'errors when param is not a Hash' do get '/required', items: 'hello' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid, items[key] is missing') get '/required', items: [{ key: 'foo' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') end it "doesn't throw a missing param when param is present" do get '/required', items: { key: 'hello' } expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end it 'adds to declared parameters' do subject.params do requires :items, type: Array do requires :key end end expect(declared_params).to eq([items: [:key]]) end end context 'hash with a required param with validation' do before do subject.params do requires :items, type: Hash do requires :key, type: String, values: %w[a b] end end subject.get '/required' do 'required works' end end it 'errors when param is not a Hash' do get '/required', items: 'not a hash' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid, items[key] is missing, items[key] is invalid') get '/required', items: [{ key: 'hash in array' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid, items[key] does not have a valid value') end it 'works when all params match' do get '/required', items: { key: 'a' } expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end end context 'group' do before do subject.params do group :items, type: Array do requires :key end end subject.get '/required' do 'required works' end end it 'errors when param not present' do get '/required' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is missing') end it "doesn't throw a missing param when param is present" do get '/required', items: [key: 'hello'] expect(last_response.status).to eq(200) expect(last_response.body).to eq('required works') end it 'adds to declared parameters' do subject.params do group :items, type: Array do requires :key end end expect(declared_params).to eq([items: [:key]]) end end context 'group params with nested params which has a type' do let(:invalid_items) { { items: '' } } before do subject.params do optional :items, type: Array do optional :key1, type: String optional :key2, type: String end end subject.post '/group_with_nested' do 'group with nested works' end end it 'errors when group param is invalid' do post '/group_with_nested', items: invalid_items expect(last_response.status).to eq(400) end end context 'custom validator for a Hash' do let(:date_range_validator) do Class.new(Grape::Validations::Validators::Base) do def validate_param!(attr_name, params) return if params[attr_name][:from] <= params[attr_name][:to] raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: "'from' must be lower or equal to 'to'") end end end before do described_class.register_validator('date_range', date_range_validator) end after do described_class.deregister_validator('date_range') end before do subject.params do optional :date_range, date_range: true, type: Hash do requires :from, type: Integer requires :to, type: Integer end end subject.get('/optional') do 'optional works' end subject.params do requires :date_range, date_range: true, type: Hash do requires :from, type: Integer requires :to, type: Integer end end subject.get('/required') do 'required works' end end context 'which is optional' do it "doesn't throw an error if the validation passes" do get '/optional', date_range: { from: 1, to: 2 } expect(last_response.status).to eq(200) end it 'errors if the validation fails' do get '/optional', date_range: { from: 2, to: 1 } expect(last_response.status).to eq(400) end end context 'which is required' do it "doesn't throw an error if the validation passes" do get '/required', date_range: { from: 1, to: 2 } expect(last_response.status).to eq(200) end it 'errors if the validation fails' do get '/required', date_range: { from: 2, to: 1 } expect(last_response.status).to eq(400) end end end context 'validation within arrays' do before do subject.params do group :children, type: Array do requires :name group :parents, type: Array do requires :name, allow_blank: false end end end subject.get '/within_array' do 'within array works' end end it 'can handle new scopes within child elements' do get '/within_array', children: [ { name: 'John', parents: [{ name: 'Jane' }, { name: 'Bob' }] }, { name: 'Joe', parents: [{ name: 'Josie' }] } ] expect(last_response.status).to eq(200) expect(last_response.body).to eq('within array works') end it 'errors when a parameter is not present' do get '/within_array', children: [ { name: 'Jim', parents: [{ name: 'Joy' }] }, { name: 'Job', parents: [{}] } ] # NOTE: with body parameters in json or XML or similar this # should actually fail with: children[parents][name] is missing. expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[1][parents] is missing, children[0][parents][1][name] is missing, children[0][parents][1][name] is empty') end it 'errors when a parameter is not present in array within array' do get '/within_array', children: [ { name: 'Jim', parents: [{ name: 'Joy' }] }, { name: 'Job', parents: [{ name: 'Bill' }, { name: '' }] } ] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[1][parents][1][name] is empty') end it 'handle errors for all array elements' do get '/within_array', children: [ { name: 'Jim', parents: [] }, { name: 'Job', parents: [] } ] expect(last_response.status).to eq(400) expect(last_response.body).to eq( 'children[0][parents][0][name] is missing, ' \ 'children[1][parents][0][name] is missing' ) end it 'safely handles empty arrays and blank parameters' do # NOTE: with body parameters in json or XML or similar this # should actually return 200, since an empty array is valid. get '/within_array', children: [] expect(last_response.status).to eq(400) expect(last_response.body).to eq( 'children[0][name] is missing, ' \ 'children[0][parents] is missing, ' \ 'children[0][parents] is invalid, ' \ 'children[0][parents][0][name] is missing, ' \ 'children[0][parents][0][name] is empty' ) get '/within_array', children: [name: 'Jay'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[0][parents] is missing, children[0][parents][0][name] is missing, children[0][parents][0][name] is empty') end it 'errors when param is not an Array' do get '/within_array', children: 'hello' expect(last_response.status).to eq(400) expect(last_response.body).to eq('children is invalid') get '/within_array', children: { name: 'foo' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('children is invalid') get '/within_array', children: [name: 'Jay', parents: { name: 'Fred' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[0][parents] is invalid') end end context 'with block param' do before do subject.params do requires :planets, type: Array do requires :name end end subject.get '/req' do 'within array works' end subject.put '/req' do '' end subject.params do group :stars, type: Array do requires :name end end subject.get '/grp' do 'within array works' end subject.put '/grp' do '' end subject.params do requires :name optional :moons, type: Array do requires :name end end subject.get '/opt' do 'within array works' end subject.put '/opt' do '' end end it 'requires defaults to Array type' do get '/req', planets: 'Jupiter, Saturn' expect(last_response.status).to eq(400) expect(last_response.body).to eq('planets is invalid') get '/req', planets: { name: 'Jupiter' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('planets is invalid') get '/req', planets: [{ name: 'Venus' }, { name: 'Mars' }] expect(last_response.status).to eq(200) put_with_json '/req', planets: [] expect(last_response.status).to eq(200) end it 'optional defaults to Array type' do get '/opt', name: 'Jupiter', moons: 'Europa, Ganymede' expect(last_response.status).to eq(400) expect(last_response.body).to eq('moons is invalid') get '/opt', name: 'Jupiter', moons: { name: 'Ganymede' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('moons is invalid') get '/opt', name: 'Jupiter', moons: [{ name: 'Io' }, { name: 'Callisto' }] expect(last_response.status).to eq(200) put_with_json '/opt', name: 'Venus' expect(last_response.status).to eq(200) put_with_json '/opt', name: 'Mercury', moons: [] expect(last_response.status).to eq(200) end it 'group defaults to Array type' do get '/grp', stars: 'Sun' expect(last_response.status).to eq(400) expect(last_response.body).to eq('stars is invalid') get '/grp', stars: { name: 'Sun' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('stars is invalid') get '/grp', stars: [{ name: 'Sun' }] expect(last_response.status).to eq(200) put_with_json '/grp', stars: [] expect(last_response.status).to eq(200) end end context 'validation within arrays with JSON' do before do subject.params do group :children, type: Array do requires :name group :parents, type: Array do requires :name end end end subject.put '/within_array' do 'within array works' end end it 'can handle new scopes within child elements' do put_with_json '/within_array', children: [ { name: 'John', parents: [{ name: 'Jane' }, { name: 'Bob' }] }, { name: 'Joe', parents: [{ name: 'Josie' }] } ] expect(last_response.status).to eq(200) expect(last_response.body).to eq('within array works') end it 'errors when a parameter is not present' do put_with_json '/within_array', children: [ { name: 'Jim', parents: [{}] }, { name: 'Job', parents: [{ name: 'Joy' }] } ] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[0][parents][0][name] is missing') end it 'safely handles empty arrays and blank parameters' do put_with_json '/within_array', children: [] expect(last_response.status).to eq(200) put_with_json '/within_array', children: [name: 'Jay'] expect(last_response.status).to eq(400) expect(last_response.body).to eq('children[0][parents] is missing, children[0][parents][0][name] is missing') end end context 'optional with an Array block' do before do subject.params do optional :items, type: Array do requires :key end end subject.get '/optional_group' do 'optional group works' end end it "doesn't throw a missing param when the group isn't present" do get '/optional_group' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional group works') end it "doesn't throw a missing param when both group and param are given" do get '/optional_group', items: [{ key: 'foo' }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional group works') end it 'errors when group is present, but required param is not' do get '/optional_group', items: [{ not_key: 'foo' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][key] is missing') end it "errors when param is present but isn't an Array" do get '/optional_group', items: 'hello' expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') get '/optional_group', items: { key: 'foo' } expect(last_response.status).to eq(400) expect(last_response.body).to eq('items is invalid') end it 'adds to declared parameters' do subject.params do optional :items, type: Array do requires :key end end expect(declared_params).to eq([items: [:key]]) end end context 'nested optional Array blocks' do before do subject.params do optional :items, type: Array do requires :key optional(:optional_subitems, type: Array) { requires :value } requires(:required_subitems, type: Array) { requires :value } end end subject.get('/nested_optional_group') { 'nested optional group works' } end it 'does no internal validations if the outer group is blank' do get '/nested_optional_group' expect(last_response.status).to eq(200) expect(last_response.body).to eq('nested optional group works') end it 'does internal validations if the outer group is present' do get '/nested_optional_group', items: [{ key: 'foo' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][required_subitems] is missing, items[0][required_subitems][0][value] is missing') get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }] }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('nested optional group works') end it 'handles deep nesting' do get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }], optional_subitems: [{ not_value: 'baz' }] }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][optional_subitems][0][value] is missing') get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }], optional_subitems: [{ value: 'baz' }] }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('nested optional group works') end it 'handles validation within arrays' do get '/nested_optional_group', items: [{ key: 'foo' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][required_subitems] is missing, items[0][required_subitems][0][value] is missing') get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }] }] expect(last_response.status).to eq(200) expect(last_response.body).to eq('nested optional group works') get '/nested_optional_group', items: [{ key: 'foo', required_subitems: [{ value: 'bar' }], optional_subitems: [{ not_value: 'baz' }] }] expect(last_response.status).to eq(400) expect(last_response.body).to eq('items[0][optional_subitems][0][value] is missing') end it 'adds to declared parameters' do subject.params do optional :items, type: Array do requires :key optional(:optional_subitems, type: Array) { requires :value } requires(:required_subitems, type: Array) { requires :value } end end expect(declared_params).to eq([items: [:key, { optional_subitems: [:value] }, { required_subitems: [:value] }]]) end context <<~DESC do Issue occurs whenever: * param structure with at least three levels * 1st level item is a required Array that has >1 entry with an optional item present and >1 entry with an optional item missing#{' '} * 2nd level is an optional Array or Hash#{' '} * 3rd level is a required item (can be any type) * additional levels do not effect the issue from occuring DESC it 'example based off actual real world use case' do subject.params do requires :orders, type: Array do requires :id, type: Integer optional :drugs, type: Array do requires :batches, type: Array do requires :batch_no, type: String end end end end subject.get '/validate_required_arrays_under_optional_arrays' do 'validate_required_arrays_under_optional_arrays works!' end data = { orders: [ { id: 77, drugs: [{ batches: [{ batch_no: 'A1234567' }] }] }, { id: 70 } ] } get '/validate_required_arrays_under_optional_arrays', data expect(last_response.body).to eq('validate_required_arrays_under_optional_arrays works!') expect(last_response.status).to eq(200) end it 'simplest example using Array -> Array -> Hash -> String' do subject.params do requires :orders, type: Array do requires :id, type: Integer optional :drugs, type: Array do requires :batch_no, type: String end end end subject.get '/validate_required_arrays_under_optional_arrays' do 'validate_required_arrays_under_optional_arrays works!' end data = { orders: [ { id: 77, drugs: [{ batch_no: 'A1234567' }] }, { id: 70 } ] } get '/validate_required_arrays_under_optional_arrays', data expect(last_response.body).to eq('validate_required_arrays_under_optional_arrays works!') expect(last_response.status).to eq(200) end it 'simplest example using Array -> Hash -> String' do subject.params do requires :orders, type: Array do requires :id, type: Integer optional :drugs, type: Hash do requires :batch_no, type: String end end end subject.get '/validate_required_arrays_under_optional_arrays' do 'validate_required_arrays_under_optional_arrays works!' end data = { orders: [ { id: 77, drugs: { batch_no: 'A1234567' } }, { id: 70 } ] } get '/validate_required_arrays_under_optional_arrays', data expect(last_response.body).to eq('validate_required_arrays_under_optional_arrays works!') expect(last_response.status).to eq(200) end it 'correctly indexes invalida data' do subject.params do requires :orders, type: Array do requires :id, type: Integer optional :drugs, type: Array do requires :batch_no, type: String requires :quantity, type: Integer end end end subject.get '/correctly_indexes' do 'correctly_indexes works!' end data = { orders: [ { id: 70 }, { id: 77, drugs: [{ batch_no: 'A1234567', quantity: 12 }, { batch_no: 'B222222' }] } ] } get '/correctly_indexes', data expect(last_response.body).to eq('orders[1][drugs][1][quantity] is missing') expect(last_response.status).to eq(400) end context 'multiple levels of optional and requires settings' do before do subject.params do requires :top, type: Array do requires :top_id, type: Integer, allow_blank: false optional :middle_1, type: Array do requires :middle_1_id, type: Integer, allow_blank: false optional :middle_2, type: Array do requires :middle_2_id, type: String, allow_blank: false optional :bottom, type: Array do requires :bottom_id, type: Integer, allow_blank: false end end end end end subject.get '/multi_level' do 'multi_level works!' end end it 'with valid data' do data = { top: [ { top_id: 1, middle_1: [ { middle_1_id: 11 }, { middle_1_id: 12, middle_2: [ { middle_2_id: 121 }, { middle_2_id: 122, bottom: [{ bottom_id: 1221 }] } ] } ] }, { top_id: 2, middle_1: [ { middle_1_id: 21 }, { middle_1_id: 22, middle_2: [ { middle_2_id: 221 } ] } ] }, { top_id: 3, middle_1: [ { middle_1_id: 31 }, { middle_1_id: 32 } ] }, { top_id: 4 } ] } get '/multi_level', data expect(last_response.body).to eq('multi_level works!') expect(last_response.status).to eq(200) end it 'with invalid data' do data = { top: [ { top_id: 1, middle_1: [ { middle_1_id: 11 }, { middle_1_id: 12, middle_2: [ { middle_2_id: 121 }, { middle_2_id: 122, bottom: [{ bottom_id: nil }] } ] } ] }, { top_id: 2, middle_1: [ { middle_1_id: 21 }, { middle_1_id: 22, middle_2: [{ middle_2_id: nil }] } ] }, { top_id: 3, middle_1: [ { middle_1_id: nil }, { middle_1_id: 32 } ] }, { top_id: nil, missing_top_id: 4 } ] } # debugger get '/multi_level', data expect(last_response.body.split(', ')).to match_array([ 'top[3][top_id] is empty', 'top[2][middle_1][0][middle_1_id] is empty', 'top[1][middle_1][1][middle_2][0][middle_2_id] is empty', 'top[0][middle_1][1][middle_2][1][bottom][0][bottom_id] is empty' ]) expect(last_response.status).to eq(400) end end end it 'exactly_one_of' do subject.params do requires :orders, type: Array do requires :id, type: Integer optional :drugs, type: Hash do optional :batch_no, type: String optional :batch_id, type: String exactly_one_of :batch_no, :batch_id end end end subject.get '/exactly_one_of' do 'exactly_one_of works!' end data = { orders: [ { id: 77, drugs: { batch_no: 'A1234567' } }, { id: 70 } ] } get '/exactly_one_of', data expect(last_response.body).to eq('exactly_one_of works!') expect(last_response.status).to eq(200) end it 'at_least_one_of' do subject.params do requires :orders, type: Array do requires :id, type: Integer optional :drugs, type: Hash do optional :batch_no, type: String optional :batch_id, type: String at_least_one_of :batch_no, :batch_id end end end subject.get '/at_least_one_of' do 'at_least_one_of works!' end data = { orders: [ { id: 77, drugs: { batch_no: 'A1234567' } }, { id: 70 } ] } get '/at_least_one_of', data expect(last_response.body).to eq('at_least_one_of works!') expect(last_response.status).to eq(200) end it 'all_or_none_of' do subject.params do requires :orders, type: Array do requires :id, type: Integer optional :drugs, type: Hash do optional :batch_no, type: String optional :batch_id, type: String all_or_none_of :batch_no, :batch_id end end end subject.get '/all_or_none_of' do 'all_or_none_of works!' end data = { orders: [ { id: 77, drugs: { batch_no: 'A1234567', batch_id: '12' } }, { id: 70 } ] } get '/all_or_none_of', data expect(last_response.body).to eq('all_or_none_of works!') expect(last_response.status).to eq(200) end end context 'multiple validation errors' do before do subject.params do requires :yolo requires :swag end subject.get '/two_required' do 'two required works' end end it 'throws the validation errors' do get '/two_required' expect(last_response.status).to eq(400) expect(last_response.body).to match(/yolo is missing/) expect(last_response.body).to match(/swag is missing/) end end context 'custom validation' do let(:custom_validator) do Class.new(Grape::Validations::Validators::Base) do def validate_param!(attr_name, params) return if params[attr_name] == 'im custom' raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: 'is not custom!') end end end before do described_class.register_validator('customvalidator', custom_validator) end after do described_class.deregister_validator('customvalidator') end context 'when using optional with a custom validator' do before do subject.params do optional :custom, customvalidator: true end subject.get '/optional_custom' do 'optional with custom works!' end end it 'validates when param is present' do get '/optional_custom', custom: 'im custom' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional with custom works!') get '/optional_custom', custom: 'im wrong' expect(last_response.status).to eq(400) expect(last_response.body).to eq('custom is not custom!') end it "skips validation when parameter isn't present" do get '/optional_custom' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional with custom works!') end it 'validates with custom validator when param present and incorrect type' do subject.params do optional :custom, type: String, customvalidator: true end get '/optional_custom', custom: 123 expect(last_response.status).to eq(400) expect(last_response.body).to eq('custom is not custom!') end end context 'when using requires with a custom validator' do before do subject.params do requires :custom, customvalidator: true end subject.get '/required_custom' do 'required with custom works!' end end it 'validates when param is present' do get '/required_custom', custom: 'im wrong, validate me' expect(last_response.status).to eq(400) expect(last_response.body).to eq('custom is not custom!') get '/required_custom', custom: 'im custom' expect(last_response.status).to eq(200) expect(last_response.body).to eq('required with custom works!') end it 'validates when param is not present' do get '/required_custom' expect(last_response.status).to eq(400) expect(last_response.body).to eq('custom is missing, custom is not custom!') end context 'nested namespaces' do before do subject.params do requires :custom, customvalidator: true end subject.namespace 'nested' do get 'one' do 'validation failed' end namespace 'nested' do get 'two' do 'validation failed' end end end subject.namespace 'peer' do get 'one' do 'no validation required' end namespace 'nested' do get 'two' do 'no validation required' end end end subject.namespace 'unrelated' do params do requires :name end get 'one' do 'validation required' end namespace 'double' do get 'two' do 'no validation required' end end end end specify 'the parent namespace uses the validator' do get '/nested/one', custom: 'im wrong, validate me' expect(last_response.status).to eq(400) expect(last_response.body).to eq('custom is not custom!') end specify 'the nested namespace inherits the custom validator' do get '/nested/nested/two', custom: 'im wrong, validate me' expect(last_response.status).to eq(400) expect(last_response.body).to eq('custom is not custom!') end specify 'peer namespaces does not have the validator' do get '/peer/one', custom: 'im not validated' expect(last_response.status).to eq(200) expect(last_response.body).to eq('no validation required') end specify 'namespaces nested in peers should also not have the validator' do get '/peer/nested/two', custom: 'im not validated' expect(last_response.status).to eq(200) expect(last_response.body).to eq('no validation required') end specify 'when nested, specifying a route should clear out the validations for deeper nested params' do get '/unrelated/one' expect(last_response.status).to eq(400) get '/unrelated/double/two' expect(last_response.status).to eq(200) end end end context 'when using options on param' do let(:custom_validator_with_options) do Class.new(Grape::Validations::Validators::Base) do def validate_param!(attr_name, params) return if params[attr_name] == @option[:text] raise Grape::Exceptions::Validation.new(params: [@scope.full_name(attr_name)], message: message) end end end before do described_class.register_validator('customvalidator_with_options', custom_validator_with_options) end after do described_class.deregister_validator('customvalidator_with_options') end before do subject.params do optional :custom, customvalidator_with_options: { text: 'im custom with options', message: 'is not custom with options!' } end subject.get '/optional_custom' do 'optional with custom works!' end end it 'validates param with custom validator with options' do get '/optional_custom', custom: 'im custom with options' expect(last_response.status).to eq(200) expect(last_response.body).to eq('optional with custom works!') get '/optional_custom', custom: 'im wrong' expect(last_response.status).to eq(400) expect(last_response.body).to eq('custom is not custom with options!') end end end context 'named' do context 'can be defined' do it 'in helpers' do subject.helpers do params :pagination do end end end it 'in helper module which kind of Grape::DSL::Helpers::BaseHelper' do shared_params = Module.new do extend Grape::DSL::Helpers::BaseHelper params :pagination do end end subject.helpers shared_params end end context 'can be included in usual params' do before do shared_params = Module.new do extend Grape::DSL::Helpers::BaseHelper params :period do optional :start_date optional :end_date end end subject.helpers shared_params subject.helpers do params :pagination do optional :page, type: Integer optional :per_page, type: Integer end end end it 'by #use' do subject.params do use :pagination end expect(declared_params).to eq %i[page per_page] end it 'by #use with multiple params' do subject.params do use :pagination, :period end expect(declared_params).to eq %i[page per_page start_date end_date] end end context 'with block' do before do subject.helpers do params :order do |options| optional :order, type: Symbol, values: %i[asc desc], default: options[:default_order] optional :order_by, type: Symbol, values: options[:order_by], default: options[:default_order_by] end end subject.format :json subject.params do use :order, default_order: :asc, order_by: %i[name created_at], default_order_by: :created_at end subject.get '/order' do { order: params[:order], order_by: params[:order_by] } end end it 'returns defaults' do get '/order' expect(last_response.status).to eq(200) expect(last_response.body).to eq({ order: :asc, order_by: :created_at }.to_json) end it 'overrides default value for order' do get '/order?order=desc' expect(last_response.status).to eq(200) expect(last_response.body).to eq({ order: :desc, order_by: :created_at }.to_json) end it 'overrides default value for order_by' do get '/order?order_by=name' expect(last_response.status).to eq(200) expect(last_response.body).to eq({ order: :asc, order_by: :name }.to_json) end it 'fails with invalid value' do get '/order?order=invalid' expect(last_response.status).to eq(400) expect(last_response.body).to eq('{"error":"order does not have a valid value"}') end end end context 'with block and keyword argument' do before do subject.helpers do params :shared_params do |type:| optional :param, default: type end end subject.format :json subject.params do use :shared_params, type: 'value' end subject.get '/shared_params' do { param: params[:param] } end end it 'works' do get '/shared_params' expect(last_response.status).to eq(200) expect(last_response.body).to eq({ param: 'value' }.to_json) end end context 'all or none' do context 'optional params' do before do subject.resource :custom_message do params do optional :beer optional :wine optional :juice all_or_none_of :beer, :wine, :juice, message: 'all params are required or none is required' end get '/all_or_none' do 'all_or_none works!' end end end context 'with a custom validation message' do it 'errors when any one is present' do get '/custom_message/all_or_none', beer: 'string' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine, juice all params are required or none is required' end it 'works when all params are present' do get '/custom_message/all_or_none', beer: 'string', wine: 'anotherstring', juice: 'anotheranotherstring' expect(last_response.status).to eq(200) expect(last_response.body).to eq 'all_or_none works!' end it 'works when none are present' do get '/custom_message/all_or_none' expect(last_response.status).to eq(200) expect(last_response.body).to eq 'all_or_none works!' end end end end context 'mutually exclusive' do context 'optional params' do context 'with custom validation message' do it 'errors when two or more are present' do subject.resources :custom_message do params do optional :beer optional :wine optional :juice mutually_exclusive :beer, :wine, :juice, message: 'are mutually exclusive cannot pass both params' end get '/mutually_exclusive' do 'mutually_exclusive works!' end end get '/custom_message/mutually_exclusive', beer: 'string', wine: 'anotherstring' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine are mutually exclusive cannot pass both params' end end it 'errors when two or more are present' do subject.params do optional :beer optional :wine optional :juice mutually_exclusive :beer, :wine, :juice end subject.get '/mutually_exclusive' do 'mutually_exclusive works!' end get '/mutually_exclusive', beer: 'string', wine: 'anotherstring' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine are mutually exclusive' end end context 'more than one set of mutually exclusive params' do context 'with a custom validation message' do it 'errors for all sets' do subject.resources :custom_message do params do optional :beer optional :wine mutually_exclusive :beer, :wine, message: 'are mutually exclusive pass only one' optional :nested, type: Hash do optional :scotch optional :aquavit mutually_exclusive :scotch, :aquavit, message: 'are mutually exclusive pass only one' end optional :nested2, type: Array do optional :scotch2 optional :aquavit2 mutually_exclusive :scotch2, :aquavit2, message: 'are mutually exclusive pass only one' end end get '/mutually_exclusive' do 'mutually_exclusive works!' end end get '/custom_message/mutually_exclusive', beer: 'true', wine: 'true', nested: { scotch: 'true', aquavit: 'true' }, nested2: [{ scotch2: 'true' }, { scotch2: 'true', aquavit2: 'true' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq( 'beer, wine are mutually exclusive pass only one, nested[scotch], nested[aquavit] are mutually exclusive pass only one, nested2[1][scotch2], nested2[1][aquavit2] are mutually exclusive pass only one' ) end end it 'errors for all sets' do subject.params do optional :beer optional :wine mutually_exclusive :beer, :wine optional :nested, type: Hash do optional :scotch optional :aquavit mutually_exclusive :scotch, :aquavit end optional :nested2, type: Array do optional :scotch2 optional :aquavit2 mutually_exclusive :scotch2, :aquavit2 end end subject.get '/mutually_exclusive' do 'mutually_exclusive works!' end get '/mutually_exclusive', beer: 'true', wine: 'true', nested: { scotch: 'true', aquavit: 'true' }, nested2: [{ scotch2: 'true' }, { scotch2: 'true', aquavit2: 'true' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine are mutually exclusive, nested[scotch], nested[aquavit] are mutually exclusive, nested2[1][scotch2], nested2[1][aquavit2] are mutually exclusive' end end context 'in a group' do it 'works when only one from the set is present' do subject.params do group :drink, type: Hash do optional :wine optional :beer optional :juice mutually_exclusive :beer, :wine, :juice end end subject.get '/mutually_exclusive_group' do 'mutually_exclusive_group works!' end get '/mutually_exclusive_group', drink: { beer: 'true' } expect(last_response.status).to eq(200) end it 'errors when more than one from the set is present' do subject.params do group :drink, type: Hash do optional :wine optional :beer optional :juice mutually_exclusive :beer, :wine, :juice end end subject.get '/mutually_exclusive_group' do 'mutually_exclusive_group works!' end get '/mutually_exclusive_group', drink: { beer: 'true', juice: 'true', wine: 'true' } expect(last_response.status).to eq(400) end end context 'mutually exclusive params inside Hash group' do it 'invalidates if request param is invalid type' do subject.params do optional :wine, type: Hash do optional :grape optional :country mutually_exclusive :grape, :country end end subject.post '/mutually_exclusive' do 'mutually_exclusive works!' end post '/mutually_exclusive', wine: '2015 sauvignon' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'wine is invalid' end end end context 'exactly one of' do context 'params' do before do subject.resources :custom_message do params do optional :beer optional :wine optional :juice exactly_one_of :beer, :wine, :juice, message: 'are missing, exactly one parameter is required' end get '/exactly_one_of' do 'exactly_one_of works!' end end subject.params do optional :beer optional :wine optional :juice exactly_one_of :beer, :wine, :juice end subject.get '/exactly_one_of' do 'exactly_one_of works!' end end context 'with a custom validation message' do it 'errors when none are present' do get '/custom_message/exactly_one_of' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine, juice are missing, exactly one parameter is required' end it 'succeeds when one is present' do get '/custom_message/exactly_one_of', beer: 'string' expect(last_response.status).to eq(200) expect(last_response.body).to eq 'exactly_one_of works!' end it 'errors when two or more are present' do get '/custom_message/exactly_one_of', beer: 'string', wine: 'anotherstring' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine are missing, exactly one parameter is required' end end it 'errors when none are present' do get '/exactly_one_of' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine, juice are missing, exactly one parameter must be provided' end it 'succeeds when one is present' do get '/exactly_one_of', beer: 'string' expect(last_response.status).to eq(200) expect(last_response.body).to eq 'exactly_one_of works!' end it 'errors when two or more are present' do get '/exactly_one_of', beer: 'string', wine: 'anotherstring' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine are mutually exclusive' end end context 'nested params' do before do subject.params do requires :nested, type: Hash do optional :beer_nested optional :wine_nested optional :juice_nested exactly_one_of :beer_nested, :wine_nested, :juice_nested end optional :nested2, type: Array do optional :beer_nested2 optional :wine_nested2 optional :juice_nested2 exactly_one_of :beer_nested2, :wine_nested2, :juice_nested2 end end subject.get '/exactly_one_of_nested' do 'exactly_one_of works!' end end it 'errors when none are present' do get '/exactly_one_of_nested' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'nested is missing, nested[beer_nested], nested[wine_nested], nested[juice_nested] are missing, exactly one parameter must be provided' end it 'succeeds when one is present' do get '/exactly_one_of_nested', nested: { beer_nested: 'string' } expect(last_response.status).to eq(200) expect(last_response.body).to eq 'exactly_one_of works!' end it 'errors when two or more are present' do get '/exactly_one_of_nested', nested: { beer_nested: 'string' }, nested2: [{ beer_nested2: 'string', wine_nested2: 'anotherstring' }] expect(last_response.status).to eq(400) expect(last_response.body).to eq 'nested2[0][beer_nested2], nested2[0][wine_nested2] are mutually exclusive' end end end context 'at least one of' do context 'params' do before do subject.resources :custom_message do params do optional :beer optional :wine optional :juice at_least_one_of :beer, :wine, :juice, message: 'are missing, please specify at least one param' end get '/at_least_one_of' do 'at_least_one_of works!' end end subject.params do optional :beer optional :wine optional :juice at_least_one_of :beer, :wine, :juice end subject.get '/at_least_one_of' do 'at_least_one_of works!' end end context 'with a custom validation message' do it 'errors when none are present' do get '/custom_message/at_least_one_of' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine, juice are missing, please specify at least one param' end it 'does not error when one is present' do get '/custom_message/at_least_one_of', beer: 'string' expect(last_response.status).to eq(200) expect(last_response.body).to eq 'at_least_one_of works!' end it 'does not error when two are present' do get '/custom_message/at_least_one_of', beer: 'string', wine: 'string' expect(last_response.status).to eq(200) expect(last_response.body).to eq 'at_least_one_of works!' end end it 'errors when none are present' do get '/at_least_one_of' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'beer, wine, juice are missing, at least one parameter must be provided' end it 'does not error when one is present' do get '/at_least_one_of', beer: 'string' expect(last_response.status).to eq(200) expect(last_response.body).to eq 'at_least_one_of works!' end it 'does not error when two are present' do get '/at_least_one_of', beer: 'string', wine: 'string' expect(last_response.status).to eq(200) expect(last_response.body).to eq 'at_least_one_of works!' end end context 'nested params' do before do subject.params do requires :nested, type: Hash do optional :beer optional :wine optional :juice at_least_one_of :beer, :wine, :juice end optional :nested2, type: Array do optional :beer optional :wine optional :juice at_least_one_of :beer, :wine, :juice end end subject.get '/at_least_one_of_nested' do 'at_least_one_of works!' end end it 'errors when none are present' do get '/at_least_one_of_nested' expect(last_response.status).to eq(400) expect(last_response.body).to eq 'nested is missing, nested[beer], nested[wine], nested[juice] are missing, at least one parameter must be provided' end it 'does not error when one is present' do get '/at_least_one_of_nested', nested: { beer: 'string' }, nested2: [{ beer: 'string' }] expect(last_response.status).to eq(200) expect(last_response.body).to eq 'at_least_one_of works!' end it 'does not error when two are present' do get '/at_least_one_of_nested', nested: { beer: 'string', wine: 'string' }, nested2: [{ beer: 'string', wine: 'string' }] expect(last_response.status).to eq(200) expect(last_response.body).to eq 'at_least_one_of works!' end end end context 'in a group' do it 'works when only one from the set is present' do subject.params do group :drink, type: Hash do optional :wine optional :beer optional :juice exactly_one_of :beer, :wine, :juice end end subject.get '/exactly_one_of_group' do 'exactly_one_of_group works!' end get '/exactly_one_of_group', drink: { beer: 'true' } expect(last_response.status).to eq(200) end it 'errors when no parameter from the set is present' do subject.params do group :drink, type: Hash do optional :wine optional :beer optional :juice exactly_one_of :beer, :wine, :juice end end subject.get '/exactly_one_of_group' do 'exactly_one_of_group works!' end get '/exactly_one_of_group', drink: {} expect(last_response.status).to eq(400) end it 'errors when more than one from the set is present' do subject.params do group :drink, type: Hash do optional :wine optional :beer optional :juice exactly_one_of :beer, :wine, :juice end end subject.get '/exactly_one_of_group' do 'exactly_one_of_group works!' end get '/exactly_one_of_group', drink: { beer: 'true', juice: 'true', wine: 'true' } expect(last_response.status).to eq(400) end it 'does not falsely think the param is there if it is provided outside the block' do subject.params do group :drink, type: Hash do optional :wine optional :beer optional :juice exactly_one_of :beer, :wine, :juice end end subject.get '/exactly_one_of_group' do 'exactly_one_of_group works!' end get '/exactly_one_of_group', drink: { foo: 'bar' }, beer: 'true' expect(last_response.status).to eq(400) end end end describe 'require_validator' do subject { described_class.require_validator(short_name) } context 'when found' do let(:short_name) { :presence } it { is_expected.to be(Grape::Validations::Validators::PresenceValidator) } end context 'when not found' do let(:short_name) { :test } it 'raises an error' do expect { subject }.to raise_error(Grape::Exceptions::UnknownValidator) end end end end
33.715496
213
0.565342
1a5b1a057eb8090fb43b8c98796a5d84df60d567
115
# frozen_string_literal: true Rebrandly.configure do |config| config.api_key = Darjeelink.rebrandly_api_key end
19.166667
47
0.817391
d5be4a877b862fe101634e59a30ee6d7eed1280f
1,352
cask "gitkraken" do arch = Hardware::CPU.intel? ? "darwin" : "darwin-arm64" version "8.6.0" if Hardware::CPU.intel? sha256 "ec32e4d887c4af155a2d70087cfc6c1a524b3c1eb8f7a7efc66f46b394318a8e" else sha256 "4297f729aba0101ca8f93f80f910eb4a3433542a4f007736abea3e8139cd8a53" end url "https://release.axocdn.com/#{arch}/GitKraken-v#{version}.zip", verified: "release.axocdn.com/" name "GitKraken" desc "Git client focusing on productivity" homepage "https://www.gitkraken.com/" livecheck do url "https://support.gitkraken.com/release-notes/current/" regex(/Version\s(\d+(?:\.\d+)+)/i) end auto_updates true depends_on macos: ">= :el_capitan" app "GitKraken.app" uninstall quit: "com.axosoft.gitkraken" zap trash: [ "~/.gitkraken", "~/Library/Application Support/com.axosoft.gitkraken.ShipIt", "~/Library/Application Support/GitKraken", "~/Library/Caches/com.axosoft.gitkraken.ShipIt", "~/Library/Caches/com.axosoft.gitkraken", "~/Library/Caches/GitKraken", "~/Library/Cookies/com.axosoft.gitkraken.binarycookies", "~/Library/HTTPStorages/com.axosoft.gitkraken", "~/Library/Preferences/com.axosoft.gitkraken.helper.plist", "~/Library/Preferences/com.axosoft.gitkraken.plist", "~/Library/Saved Application State/com.axosoft.gitkraken.savedState", ] end
30.727273
77
0.714497
1805b6b78b069a9ab01e0f56c7d92f59598d4f12
568
require 'spec_helper' describe Angus::SDoc::HtmlFormatter do subject(:formatter) { Angus::SDoc::HtmlFormatter } describe '.format_service' do let(:service) { FactoryGirl.build(:full_service) } context 'when "en" language' do subject { formatter.format_service(service, 'en') } it { should be_kind_of(String) } it { should_not be_empty } end context 'when "es" language' do subject { formatter.format_service(service, 'es') } it { should be_kind_of(String) } it { should_not be_empty } end end end
21.037037
57
0.658451
21e72f510f45df3cc4c62205ef549f1e7719ae40
1,656
# frozen_string_literal: true require 'gruff' # Helpers for generating graphs module GraphUtil # Applies a basic theme to a given graph # @param g [Gruff::Base] Graph def self.apply_theme(graph) graph.hide_legend = true graph.hide_dots = true graph.marker_font_size = 18 graph.font = 'DejaVu-Sans' graph.theme = { colors: ['#aedaa9', '#12a702'], marker_color: '#dddddd', font_color: 'black', background_colors: 'white' } end # @param power [#value] List of power values # @param hours [Numeric>] Number of hours graph covers # @param hour_parts [Numeric] Number of hour subdivisions e.g. 4 for 15mins # @return [Array<Array>] Tuple of list of labels and values def self.make_power_graph_labels_and_values(power, hours: 24, hour_parts: 4) labels = (0...hours).to_a.each_with_object({}) do |hour, hash| hash[hour * hour_parts] = hour end power_values = power.map do |v| v.value.nil? ? 0 : v.value end # Ensure our array is always at least 24 hours * 4 long power_values.concat( (power_values.size...hours * hour_parts).to_a.map { 0 } ) [labels, power_values] end # @param date [Date] Date graph covers # @param labels [Hash<Numeric, String>] Date graph covers # @param values [Array<Numeric>] Date graph covers # @return [Gruff::Line] Formatted power graph def self.power_graph(date, labels, values) g = Gruff::Line.new g.title = "Power Over Time: #{date}" apply_theme(g) g.labels = labels g.data 'Power', values g.minimum_value = 0 g.maximum_value = 6_500 # should be configurable g end end
30.109091
78
0.664251
f80821ee6583f9731d79ecc3bbef51b6a56605c8
5,552
#! /usr/bin/env ruby # frozen_string_literal: false # check-kube-pods-running # # DESCRIPTION: # => Check if pods are in a running state # # OUTPUT: # plain text # # PLATFORMS: # Linux # # DEPENDENCIES: # gem: sensu-plugin # gem: kube-client # # Usage: ./check-kube-pods-running.rb (options) # --ca-file CA-FILE CA file to verify API server cert # --cert CERT-FILE Client cert to present # --key KEY-FILE Client key for the client cert # --in-cluster Use service account authentication # --password PASSWORD If user is passed, also pass a password # -s, --api-server URL URL to API server # -t, --token TOKEN Bearer token for authorization # --token-file TOKEN-FILE File containing bearer token for authorization # -u, --user USER User with access to API # -v, --api-version VERSION API version # -n NAMESPACES, Exclude the specified list of namespaces # --exclude-namespace # -i NAMESPACES, Include the specified list of namespaces, an # --include-namespace empty list includes all namespaces # --exclude-nodes Exclude the specified nodes (comma separated list) # Exclude wins when a node is in both include and exclude lists # --include-nodes Include the specified nodes (comma separated list), an # empty list includes all nodes # --time TIME Threshold for pods to be in the non ready state # -f, --filter FILTER Selector filter for pods to be checked # -p, --pods PODS List of pods to check # NOTES: # => The filter used for the -f flag is in the form key=value. If multiple # filters need to be specfied, use a comma. ex. foo=bar,red=color # # LICENSE: # Barry Martin <[email protected]> # Released under the same terms as Sensu (the MIT license); see LICENSE # for details. # require 'sensu-plugins-kubernetes/cli' require 'sensu-plugins-kubernetes/exclude' class AllPodsAreRunning < Sensu::Plugins::Kubernetes::CLI @options = Sensu::Plugins::Kubernetes::CLI.options.dup include Sensu::Plugins::Kubernetes::Exclude option :pod_list, description: 'List of pods to check', short: '-p PODS', long: '--pods', default: 'all' option :not_ready_time, description: 'Threshold for pods to be in the non ready state', long: '--time TIME', proc: proc(&:to_i), default: 0 option :pod_filter, description: 'Selector filter for pods to be checked', short: '-f FILTER', long: '--filter' option :exclude_namespace, description: 'Exclude the specified list of namespaces', short: '-n NAMESPACES', long: '--exclude-namespace', proc: proc { |a| a.split(',') }, default: '' option :include_namespace, description: 'Include the specified list of namespaces', short: '-i NAMESPACES', long: '--include-namespace', proc: proc { |a| a.split(',') }, default: '' option :exclude_nodes, description: 'Exclude the specified nodes (comma separated list)', long: '--exclude-nodes NODES', proc: proc { |a| a.split(',') }, default: '' option :include_nodes, description: 'Include the specified nodes (comma separated list)', long: '--include-nodes NODES', proc: proc { |a| a.split(',') }, default: '' def run pods_list = [] failed_pods = [] pods = [] if config[:pod_filter].nil? pods_list = parse_list(config[:pod_list]) pods = client.get_pods else pods = client.get_pods(label_selector: config[:pod_filter].to_s) if pods.empty? unknown 'The filter specified resulted in 0 pods' end pods_list = ['all'] end pods.each do |pod| next if pod.nil? next if should_exclude_namespace(pod.metadata.namespace) next if should_exclude_node(pod.spec.nodeName) next unless pods_list.include?(pod.metadata.name) || pods_list.include?('all') next unless pod.status.phase != 'Succeeded' && !pod.status.conditions.nil? pod_stamp = if pod.status.phase == 'Pending' Time.parse(pod.metadata.creationTimestamp) else Time.parse(pod.status.startTime) end runtime = (Time.now.utc - pod_stamp.utc).to_i next if runtime < config[:not_ready_time] failed_pods << pod.metadata.name unless ready? pod end if failed_pods.empty? ok 'All pods are reporting as ready' else critical "Pods found in a non-ready state: #{failed_pods.join(' ')}" end rescue KubeException => e critical 'API error: ' << e.message end def parse_list(list) return list.split(',') if list&.include?(',') return [list] if list [''] end def should_exclude_namespace(namespace) return !config[:include_namespace].include?(namespace) unless config[:include_namespace].empty? config[:exclude_namespace].include?(namespace) end def ready?(pod) failed = true pod.status.conditions.each do |c| if c.type == 'Ready' failed = false if c.status == 'True' break end end !failed end end
33.445783
100
0.596182
e230ae571d1e61946017c0751041359a52de71f5
4,832
require File.join(File.dirname(__FILE__), %w[.. setup]) module TestLogging module TestAppenders class TestBufferedIO < Test::Unit::TestCase include LoggingTestCase def setup super ::Logging.init @levels = ::Logging::LEVELS @appender = ::Logging::Appenders::StringIo.new( 'test_appender', :auto_flushing => 3, :immediate_at => :error ) @sio = @appender.sio begin readline rescue EOFError end end def test_append event = ::Logging::LogEvent.new('TestLogger', @levels['warn'], [1, 2, 3, 4], false) @appender.append event assert_nil(readline) @appender.append event assert_nil(readline) event.level = @levels['debug'] event.data = 'the big log message' @appender.append event assert_equal " WARN TestLogger : <Array> #{[1, 2, 3, 4]}\n", readline assert_equal " WARN TestLogger : <Array> #{[1, 2, 3, 4]}\n", readline assert_equal "DEBUG TestLogger : the big log message\n", readline assert_nil(readline) @appender.close assert_raise(RuntimeError) {@appender.append event} end def test_append_error # setup an internal logger to capture error messages from the IO # appender log = Logging::Appenders::StringIo.new('__internal_io') Logging::Logger[Logging].add_appenders(log) Logging::Logger[Logging].level = 'all' # close the string IO object so we get an error @sio.close event = ::Logging::LogEvent.new('TestLogger', @levels['warn'], [1, 2, 3, 4], false) @appender.append event assert_nil(log.readline) @appender.append event assert_nil(log.readline) @appender.append event assert_equal "INFO Logging : appender \"test_appender\" has been disabled", log.readline.strip assert_equal "ERROR Logging : <IOError> not opened for writing", log.readline.strip assert_equal false, @appender.closed? assert_equal 5, @appender.level end def test_close assert_equal false, @sio.closed? assert_equal false, @appender.closed? @appender.close assert_equal true, @sio.closed? assert_equal true, @appender.closed? [STDIN, STDERR, STDOUT].each do |io| @appender = ::Logging::Appenders::IO.new 'test', io @appender.close assert_equal false, io.closed? assert_equal true, @appender.closed? end end def test_concat @appender << "this is a test message\n" assert_nil(readline) @appender << "this is another message\n" assert_nil(readline) @appender << "some other line\n" assert_equal "this is a test message\n", readline assert_equal "this is another message\n", readline assert_equal "some other line\n", readline assert_nil(readline) @appender.close assert_raise(RuntimeError) {@appender << 'message'} end def test_concat_error # setup an internal logger to capture error messages from the IO # appender log = Logging::Appenders::StringIo.new('__internal_io') Logging::Logger[Logging].add_appenders(log) Logging::Logger[Logging].level = 'all' # close the string IO object so we get an error @sio.close @appender << 'oopsy' assert_nil(log.readline) @appender << 'whoopsy' assert_nil(log.readline) @appender << 'pooh' assert_equal "INFO Logging : appender \"test_appender\" has been disabled", log.readline.strip assert_equal "ERROR Logging : <IOError> not opened for writing", log.readline.strip # and the appender does not close itself assert_equal false, @appender.closed? assert_equal 5, @appender.level end def test_flush ary = [] @sio.instance_variable_set :@ary, ary def @sio.flush() @ary << :flush end @appender << "this is a test message\n" assert_nil(readline) @appender.flush assert_equal :flush, ary.pop assert_equal "this is a test message\n", readline assert_nil(readline) end def test_immediate_at event = ::Logging::LogEvent.new('TestLogger', @levels['warn'], [1, 2, 3, 4], false) @appender.append event assert_nil(readline) event.level = @levels['error'] event.data = 'an error message' @appender.append event assert_equal " WARN TestLogger : <Array> #{[1, 2, 3, 4]}\n", readline assert_equal "ERROR TestLogger : an error message\n", readline assert_nil(readline) end private def readline @appender.readline end end # class TestBufferedIO end # module TestAppenders end # module TestLogging # EOF
28.591716
101
0.629139
d5939419c690576a41782b043c669b526048fa97
5,854
require 'rails_helper' describe Nu::ScoresController do include_context "signed up developer" include_context "authenticated user" include_context "bearer token authentication" let! (:pasta_corn_cooked) { FactoryGirl.create :pasta_corn_cooked } let! (:eat) { FactoryGirl.create :eat, user: oauth_user } let! (:old_eat) { FactoryGirl.create :old_eat, user: oauth_user } let! (:yesterdays_eat) { FactoryGirl.create :yesterdays_eat, user: oauth_user } let(:team) { FactoryGirl.create :team } it "returns 30 days by default" do get "/v3/nu/scores.json", nil, bearer_auth expect(json_body["scores"].length).to eq(30) end before do FactoryGirl.create :historical_score, history: oauth_user, date: Date.yesterday, biometric: 800 end it "can be decreased to 7 days" do get "/v3/nu/scores.json?days=7", nil, bearer_auth expect(json_body["scores"].length).to eq(7) end it "cannot grow beyond 30 days" do get "/v3/nu/scores.json?days=700", nil, bearer_auth expect(json_body["scores"].length).to eq(30) end %w(biometric_score activity_score nutrition_score nu_score).each do |score| it "contains a valid #{score}" do get "/v3/nu/scores.json?days=7", nil, bearer_auth expect(json_body["scores"].first[score]).to be_present expect(json_body["scores"].first[score]).to have_key("score") end end describe "team history scores" do before do FactoryGirl.create :historical_score, history: oauth_user, date: Date.yesterday, biometric: 80, nutrition: 40, activity: 60 FactoryGirl.create :membership, team: team, user: oauth_user, owner: true team.users << oauth_user end before do FactoryGirl.create :historical_score, history: team, date: Date.yesterday, activity: team.activity_score, nutrition: team.nutrition_score, biometric: team.biometric_score, nu: team.nu_score end it "contains the correct historical scores" do get "/v3/nu/teams/#{team.id}/scores.json?days=7", nil, bearer_auth expect(json_body["scores"].first["biometric_score"]["score"]).to eq(80) expect(json_body["scores"].first["nu_score"]["score"]).to eq(60) end it "connot grow beyond 30 days" do get "/v3/nu/teams/#{team.id}/scores.json?days=70", nil, bearer_auth expect(json_body["scores"].length).to eq(30) end end describe "team history with no scores" do it "should not break stuffs" do get "/v3/nu/teams/#{team.id}/scores.json?days=7", nil, bearer_auth expect(json_body["scores"].first["biometric_score"]["score"]).to eq(nil) end end describe "doesn't show a nutrional breakdown without DCN" do it "returns 30 days by default" do get "/v3/nu/scores.json", nil, bearer_auth expect(json_body["scores"].first["breakdown"]["breakdown"]).to eq(nil) end end describe "shows nutrional 30-day breakdown for users with DCN" do before do oauth_user.profile.update FactoryGirl.attributes_for :profile_giulia yesterdays_eat.components.create!(ingredient_id: pasta_corn_cooked.id, amount: 240) Nu::Score.new(oauth_user.reload).daily_scores(Date.current) end it "returns 30 days by default" do get "/v3/nu/scores.json", nil, bearer_auth expect(json_body["scores"].first["breakdown"]["breakdown"]["score"]).to eq(12) end end describe "biometrics" do before do FactoryGirl.create :historical_score, history: oauth_user, date: Date.yesterday, biometric: 800 end it "returns values stored in the db" do get "/v3/nu/scores.json?days=1", nil, bearer_auth result = json_body["scores"].first["biometric_score"] expect(result["score"]).to eq(800) end end describe "activities" do before do FactoryGirl.create :historical_score, history: oauth_user, date: Date.yesterday, activity: 600 end it "returns values stored in the db" do get "/v3/nu/scores.json?days=1", nil, bearer_auth result = json_body["scores"].first["activity_score"] expect(result["score"]).to eq(600) end end describe "nutrition" do before do FactoryGirl.create :historical_score, history: oauth_user, date: Date.yesterday, nutrition: 770 end it "returns values stored in the db" do get "/v3/nu/scores.json?days=1", nil, bearer_auth result = json_body["scores"].first["nutrition_score"] expect(result["score"]).to eq(770) end end describe "today score without DCN" do it "posts an error without DCN" do get "/v3/nu/scores/today.json", nil, bearer_auth expect(response.status).to eq(400) end end describe "today score with DCN" do before do oauth_user.profile.update FactoryGirl.attributes_for :profile_giulia eat.components.create!(ingredient_id: pasta_corn_cooked.id, amount: 240) Nu::Score.new(oauth_user.reload).daily_scores(Date.current) end it "returns values stored in the db" do get "/v3/nu/scores/today.json", nil, bearer_auth expect(response.status).to eq(200) end it "contains the correct values" do get "/v3/nu/scores/today.json", nil, bearer_auth expect(json_body["breakdown"]["breakdown"]["carbs"]["g"]).to eq("55.464") end end describe "week score with DCN" do before do oauth_user.profile.update FactoryGirl.attributes_for :profile_giulia Nu::Score.new(oauth_user.reload).daily_scores(Date.yesterday) end it "returns values stored in the db" do get "/v3/nu/scores/week.json", nil, bearer_auth expect(response.status).to eq(200) end it "contains the correct values" do get "/v3/nu/scores/week.json", nil, bearer_auth expect(json_body).to have_key("scores") expect(json_body["scores"].first["historical_score"]["nu"]).to eq(12) end end end
34.034884
195
0.689101
bba52ff9fcee2453a5f40a675044068651f199e0
758
class ComfortableMexicanSofa::Tag::Asset include ComfortableMexicanSofa::Tag def self.regex_tag_signature(identifier = nil) identifier ||= IDENTIFIER_REGEX /\{\{\s*cms:asset:(#{identifier}):?(.*?)\s*\}\}/ end def content return unless (layout = Cms::Layout.find_by_identifier(identifier)) type = params[0] format = params[1] case type when 'css' out = "/cms-css/#{page.site.id}/#{identifier}.css" out = "<link href='#{out}' media='screen' rel='stylesheet' type='text/css' />" if format == 'html_tag' out when 'js' out = "/cms-js/#{page.site.id}/#{identifier}.js" out = "<script src='#{out}' type='text/javascript'></script>" if format == 'html_tag' out end end end
29.153846
108
0.609499
28592c7b27e7d192cc84b7389066f5bbb491861d
1,515
# frozen_string_literal: true require 'rails_helper' RSpec.describe AssessmentQuestions::Importer do subject(:importer) { described_class.new } context 'with no existing records' do it 'creates all the input items' do expect { importer.call }.to change(AssessmentQuestion, :count).by(17) end it 'creates `Violent`' do importer.call expect(AssessmentQuestion.find_by(key: 'violent', category: 'risk', title: 'Violent')).to be_present end it 'creates `Pregnant`.' do importer.call expect(AssessmentQuestion.find_by(key: 'pregnant', category: 'health', title: 'Pregnant')).to be_present end it 'creates `Interpreter`' do importer.call expect( AssessmentQuestion.find_by(key: 'interpreter', category: 'court', title: 'Sign or other language interpreter'), ).to be_present end end context 'with one existing record' do before do AssessmentQuestion.create!(key: 'pregnant', category: 'health', title: 'Pregnant') end it 'creates only the missing item' do expect { importer.call }.to change(AssessmentQuestion, :count).by(16) end end context 'with one existing record with the wrong title' do let!(:other_court) do AssessmentQuestion.create!(key: 'other_court', category: 'court', title: 'Any other info') end it 'updates the title of the existing record' do importer.call expect(other_court.reload.title).to eq 'Any other information' end end end
29.134615
119
0.684488
ff637b55cef6b019e3835c4a037babaaf1c94ce6
692
class YoutubeVideoRenderer < ResourceRenderer::AttributeRenderer::Base def display(attribute_name, label, options = {}, &block) options.reverse_merge!(width: 640, height: 480, aspect_ratio: '16by9') aspect_ratio = options.delete(:aspect_ratio) # width = options.delete(:width) # height = options.delete(:height) iframe_attributes = { class: 'embed-responsive-item', # width: width, # height: height, src: "https://www.youtube.com/embed/#{model.identifier}", frameborder: '0' } h.content_tag(:div, class: "embed-responsive embed-responsive-#{aspect_ratio}") do h.content_tag(:iframe, nil, iframe_attributes) end end end
34.6
86
0.677746
7a0c09c1693dca210f04821a7b769081797a32de
884
# lib/breadcrumbs/builders/structured_data_breadcrumbs_builder.rb class Breadcrumbs::Builders::StructuredDataBreadcrumbsBuilder < BreadcrumbsOnRails::Breadcrumbs::Builder def render @elements.collect do |element| render_element(element) end.join(@options[:separator] || " &raquo; ") end def render_element(element) if element.path == nil content = compute_name(element) else content = @context.link_to_unless_current(compute_name(element), compute_path(element), element.options.merge({ itemscope: "", itemtype: "http://schema.org/Thing", itemprop: "item" })) end if @options[:tag] @context.content_tag( @options[:tag], content, {itemprop:"itemListElement", itemscope: "", itemtype:"http://schema.org/ListItem"} ) else ERB::Util.h(content) end end end
28.516129
117
0.661765
2616ca3388c3f6be18a2bbd7bfd9cd281e23b535
207
class CurrentUserController < ApplicationController # before_action :authenticate_user! def index # byebug render json: UserSerializer.new(current_user).serializable_hash, status: :ok end end
25.875
80
0.777778
61a4fbc268905b88fba6348ab635251728b78e55
507
cask 'bloodhound' do version '1.5.2' sha256 'a2090197c5cf82c6799cf7f8f7f1d0d42436882c67814b70d458c4ae8e9c7e32' url "https://github.com/BloodHoundAD/BloodHound/releases/download/#{version}/BloodHound-darwin-x64.zip" appcast 'https://github.com/BloodHoundAD/BloodHound/releases.atom', checkpoint: '3043e8d3935e99c729b993b632ba3927ac31f357e03bc4e73b0675ceae45fa1b' name 'bloodhound' homepage 'https://github.com/BloodHoundAD/BloodHound' app 'BloodHound-darwin-x64/BloodHound.app' end
39
105
0.798817
1c131ae8fdf62edb2925b22852057aade4611d33
4,622
# The controller for serving cms content... class ComatoseController < ActionController::Base unloadable before_filter :handle_authorization, :set_content_type after_filter :cache_cms_page helper :application # Render a specific page def show page_name, page_ext = get_page_path page = ComatosePage.find_by_path( page_name ) status = nil if page.nil? page = ComatosePage.find_by_path( '404' ) status = 404 end # if it's still nil, well, send a 404 status if page.nil? render :nothing=>true, :status=>status #raise ActiveRecord::RecordNotFound.new("Comatose page not found ") else # Make the page access 'safe' @page = Comatose::PageWrapper.new(page) # For accurate uri creation, tell the page class which is the active mount point... ComatosePage.active_mount_info = get_active_mount_point(params[:index]) render :text=>page.to_html({'params'=>params.stringify_keys}), :layout=>get_page_layout, :status=>status end end protected def handle_authorization if Comatose.config.authorization.is_a? Proc instance_eval &Comatose.config.authorization elsif Comatose.config.authorization.is_a? Symbol send(Comatose.config.authorization) elsif defined? authorize authorize else true end end def allow_page_cache? # You should have access to the @page being rendered true end # For use in the #show method... determines the current mount point def get_active_mount_point( index ) Comatose.mount_points.each do |path_info| if path_info[:index] == index return path_info end end {:root=>"", :index=>index} end # For use in the #show method... determines the current page path def get_page_path if params[:page].is_a? String page_name = params[:page].to_s #in rails 2.0, params[:page] comes back as just an Array, so to_s doesn't do join('/') elsif params[:page].is_a? Array page_name = params[:page].join("/") #in rails 1.x, params[:page] comes back as ActionController::Routing::PathSegment::Result #elsif params[:page].is_a? ActionController::Routing::PathSegment::Result # page_name = params[:page].to_s else logger.debug "get_page_path - params[:page] is an unrecognized type, may cause problems: #{params[:page].class}" page_name = params[:page].to_s end page_ext = page_name.split('.')[1] unless page_name.empty? # TODO: Automatic support for page RSS feeds... ???? if page_name.nil? or page_name.empty? page_name = params[:index] params[:cache_path] = "#{request.request_uri}/index" elsif !params[:index].empty? page_name = "#{params[:index]}/#{page_name}" end return page_name, page_ext end # Returns a path to plugin layout, if it's unspecified, otherwise # a path to an application layout... def get_page_layout params[:layout] end # An after_filter implementing page caching if it's enabled, globally, # and is allowed by #allow_page_cache? def cache_cms_page unless Comatose.config.disable_caching or response.headers['Status'] == '404 Not Found' return unless params[:use_cache].to_s == 'true' and allow_page_cache? path = params[:cache_path] || request.fullpath begin # TODO: Don't cache pages rendering '404' content... self.class.cache_page( response.body, path ) rescue logger.error "Comatose CMS Page Cache Exception: #{$!}" end end end # An after_filter that sets the HTTP header for Content-Type to # what's defined in Comatose.config.content_type. Defaults to utf-8. def set_content_type response.headers["Content-Type"] = "text/html; charset=#{Comatose.config.content_type}" unless Comatose.config.content_type.nil? or response.headers['Status'] == '404 Not Found' end COMATOSE_VIEW_PATH = File.join(Rails.root.to_s, 'vendor', 'plugins', 'comatose', 'views') ActionController::Base.append_view_path(COMATOSE_VIEW_PATH) unless ActionController::Base.view_paths.include?(COMATOSE_VIEW_PATH) # Include any, well, includes... Comatose.config.includes.each do |mod| mod_klass = if mod.is_a? String mod.constantize elsif mod.is_a? Symbol mod.to_s.classify.constantize else mod end include mod_klass end # Include any helpers... Comatose.config.helpers.each do |mod| mod_klass = if mod.is_a? String mod.constantize elsif mod.is_a? Symbol mod.to_s.classify.constantize else mod end helper mod_klass end end
32.780142
181
0.690177
0810c35078afab00a18b6ea366a667f603aa4b9c
787
# Cookbook Name:: vagrant # Recipe:: fedora # Author:: Joshua Timberman <[email protected]> # Copyright:: Copyright (c) 2014, Joshua Timberman # 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. include_recipe 'vagrant::rhel'
37.47619
75
0.738247
266310c1e38a5441b11d450f00429aea92926a8a
1,210
module Query # Observations of a given name. class ObservationOfName < Query::ObservationBase include Query::Initializers::OfName def parameter_declarations super.merge(of_name_parameter_declarations) end def initialize_flavor give_parameter_defaults names = target_names choose_a_title(names) add_name_conditions(names) super end def add_join_to_observations(table) add_join(table) end def coerce_into_image_query do_coerce(:Image) end def coerce_into_location_query do_coerce(:Location) end # TODO: need 'synonyms' flavor # params[:synonyms] == :all / :no / :exclusive # params[:misspellings] == :either / :no / :only # def coerce_into_name_query # # This should result in a query with exactly one result, so the # # resulting index should immediately display the actual location # # instead of an index. Thus title and saving the old sort order are # # unimportant. # Query.lookup(:Name, :in_set, ids: params[:name]) # end def do_coerce(new_model) Query.lookup(new_model, :with_observations_of_name, params_plus_old_by) end end end
26.304348
77
0.684298
d5969f29455071d4feb420e8c2c1dccb7b3a0e30
2,303
## # This module requires Metasploit: http://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## require 'msf/core' class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::Tcp include Msf::Exploit::Remote::HttpClient def initialize(info = {}) super(update_info(info, 'Name' => 'Generic Web Application Unix Command Execution', 'Description' => %q{ This module can be used to exploit any generic command execution vulnerability for CGI applications on Unix-like platforms. To use this module, specify the CMDURI path, replacing the command itself with XXcmdXX. This module is currently limited to forms vulnerable through GET requests with query parameters. }, 'Author' => [ 'hdm' ], 'License' => MSF_LICENSE, 'References' => [ ], 'Privileged' => false, 'Payload' => { 'DisableNops' => true, 'Space' => 1024, 'Compat' => { 'PayloadType' => 'cmd cmd_bash', 'RequiredCmd' => 'generic perl telnet netcat netcat-e bash-tcp', } }, 'Platform' => 'unix', 'Arch' => ARCH_CMD, 'Targets' => [[ 'Automatic', { }]], 'DisclosureDate' => 'Nov 14 1993', # CGI historical date :) 'DefaultTarget' => 0)) register_options( [ OptString.new('CMDURI', [true, "The full URI path with the XXcmdXX parameter", "/cgi-bin/generic?cmd=XXcmdXX"]), ], self.class) end def exploit uri = datastore['CMDURI'].to_s uri,query = uri.split('?', 2) if query query = query.split('&').map{|var| k,v = var.split('=', 2) Rex::Text.uri_encode(k) + "=" + Rex::Text.uri_encode(v.gsub("XXcmdXX", payload.encoded)) }.join('&') uri = uri + '?' + query end print_status("Sending HTTP request for #{uri}") res = send_request_cgi( { 'global' => true, 'uri' => uri }, 30) if res print_status("The server responded with HTTP CODE #{res.code}") else print_status("The server did not respond to our request") end handler end end
29.909091
120
0.568389
b943235b76acbf9e68b201a9b9608d7b4cc786da
987
# frozen_string_literal: true require_relative '../../../bolt/error' require_relative '../../../bolt/config/transport/base' module Bolt class Config module Transport class Orch < Base OPTIONS = %w[ cacert host job-poll-interval job-poll-timeout read-timeout service-url task-environment token-file ].freeze DEFAULTS = { "task-environment" => "production" }.freeze private def validate super if @config['cacert'] @config['cacert'] = File.expand_path(@config['cacert'], @project) Bolt::Util.validate_file('cacert', @config['cacert']) end if @config['token-file'] @config['token-file'] = File.expand_path(@config['token-file'], @project) Bolt::Util.validate_file('token-file', @config['token-file']) end end end end end end
23.5
85
0.539007
bf6b367492600c112982a2d8ca61880c1c7d8ec1
261
module Figma class Rectangle attr_reader :x, :y, :width, :height def initialize(raw) @x = raw['x'] @y = raw['y'] @width = raw['width'] @height = raw['height'] end end end
18.642857
43
0.429119
38152801136856348b85f604f2b7e74982769aee
1,893
class EmsStorageController < ApplicationController include Mixins::GenericListMixin include Mixins::GenericShowMixin include Mixins::EmsCommon include Mixins::GenericSessionMixin include Mixins::BreadcrumbsMixin include Mixins::DashboardViewMixin include Mixins::GenericFeatureActionMixin before_action :check_privileges before_action :get_session_data after_action :cleanup_action after_action :set_session_data def self.model ManageIQ::Providers::StorageManager end def self.table_name @table_name ||= "ems_storage" end TYPE_CHECK_SHOW_IDENTIFIERS = %w[ems_storage_show].freeze def check_generic_rbac ident = "#{controller_name}_#{action_name == 'report_data' ? 'show_list' : action_name}" return true if TYPE_CHECK_SHOW_IDENTIFIERS.include?(ident) super end def type_feature_role_check return true unless TYPE_CHECK_SHOW_IDENTIFIERS.include?("#{controller_name}_#{action_name}") && respond_to?(:feature_role) handle_generic_rbac(role_allows?(:feature => feature_role(@record))) end def init_show(model_class = self.class.model) @ems = @record = identify_record(params[:id], model_class) return true unless type_feature_role_check super end def feature_role(record) if record.supports_object_storage? 'ems_object_storage_show' elsif record.supports_block_storage? 'ems_block_storage_show' end end def breadcrumbs_options { :breadcrumbs => [ {:title => _("Storage")}, ], } end private def record_class params[:pressed].starts_with?('cloud_object_store_object') ? CloudObjectStoreObject : CloudObjectStoreContainer end def textual_group_list [ %i[properties status], %i[relationships topology smart_management] ] end helper_method :textual_group_list menu_section :sto has_custom_buttons end
23.962025
126
0.744849
4a890799f7070681ecdd1908bdec1f1f7c40e3d2
1,769
# Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. require 'google/apis/firebasehosting_v1beta1/service.rb' require 'google/apis/firebasehosting_v1beta1/classes.rb' require 'google/apis/firebasehosting_v1beta1/representations.rb' module Google module Apis # Firebase Hosting API # # The Firebase Hosting REST API enables programmatic and customizable # deployments to your Firebase-hosted sites. Use this REST API to deploy new or # updated hosting configurations and content files. # # @see https://firebase.google.com/docs/hosting/ module FirebasehostingV1beta1 VERSION = 'V1beta1' REVISION = '20200811' # View and manage your data across Google Cloud Platform services AUTH_CLOUD_PLATFORM = 'https://www.googleapis.com/auth/cloud-platform' # View your data across Google Cloud Platform services AUTH_CLOUD_PLATFORM_READ_ONLY = 'https://www.googleapis.com/auth/cloud-platform.read-only' # View and administer all your Firebase data and settings AUTH_FIREBASE = 'https://www.googleapis.com/auth/firebase' # View all your Firebase data and settings AUTH_FIREBASE_READONLY = 'https://www.googleapis.com/auth/firebase.readonly' end end end
38.456522
96
0.747315
622d2293cb6eae4207f26257136ce29cebab6025
1,733
require 'core_ext/hash/compact' class Build module Json all_attrs = [:id, :repository_id, :parent_id, :number, :commit, :branch, :message, :status, :log, :started_at, :finished_at, :committed_at, :committer_name, :committer_email, :author_name, :author_email, :compare_url, :config] JSON_ATTRS = { :default => all_attrs, :job => [:id, :number, :commit, :config, :branch], :'build:queued' => [:id, :number], :'build:removed' => [:id, :number], :'build:started' => all_attrs - [:status, :log, :finished_at], :'build:configured' => all_attrs - [:status, :log, :finished_at], :'build:log' => [:id, :parent_id], :'build:finished' => [:id, :parent_id, :status, :finished_at], :webhook => [:id, :build_log_url, :number, :commit, :branch, :message, :status, :started_at, :finished_at, :committed_at, :committer_name, :committer_email, :author_name, :author_email, :compare_url] } JSON_MERGE = { :webhook => lambda {|build| { :repository => build.repository.as_json(:for => :webhook), # TODO the repository will also be included in the controller, already, see BuildsController# :github_url => build.repository.url, # TODO shouldn't this be part of the repository? :status_message => build.status_message } } } def as_json(options = nil) options ||= {} json = super(:only => JSON_ATTRS[options[:for] || :default]) json.merge!(JSON_MERGE[options[:for]].call(self)) if JSON_MERGE[options[:for]] json.merge!('matrix' => matrix.as_json(:for => options[:for])) if matrix? json.compact end end end
43.325
160
0.601269
e8c4ab158a95e0ee4b1ddf03ebbc66836e05fb4d
1,716
class ArmLinuxGnueabihfBinutils < Formula desc "FSF/GNU binutils for cross-compiling to arm-linux" homepage "https://www.gnu.org/software/binutils/binutils.html" url "https://ftp.gnu.org/gnu/binutils/binutils-2.36.tar.xz" mirror "https://ftpmirror.gnu.org/binutils/binutils-2.36.tar.xz" sha256 "5788292cc5bbcca0848545af05986f6b17058b105be59e99ba7d0f9eb5336fb8" license "GPL-3.0-or-later" livecheck do url :stable end bottle do sha256 "471292a385af21149fe0236e61e7d7e0f7b98f339fe1591e3ba85f97d8008ce4" => :big_sur sha256 "91344b354b969486b4c8f941da0088f99fb5cae9aae060cf873fdd8e654f26c8" => :arm64_big_sur sha256 "bf12f413c20355ed062998979a61234933e1710d509a021e54f71a3b730590a5" => :catalina sha256 "39970ddd1f19a06664d5d1edd3f938776a71dc031e4b7069392940cb77731401" => :mojave end uses_from_macos "texinfo" def install ENV.cxx11 # Avoid build failure: https://sourceware.org/bugzilla/show_bug.cgi?id=23424 ENV.append "CXXFLAGS", "-Wno-c++11-narrowing" system "./configure", "--disable-debug", "--disable-dependency-tracking", "--enable-deterministic-archives", "--prefix=#{prefix}", "--disable-werror", "--target=arm-linux-gnueabihf", "--enable-gold=yes", "--enable-ld=yes", "--enable-interwork", "--with-system-zlib", "--disable-nls" system "make" system "make", "install" end test do assert_match "f()", shell_output("#{bin}/arm-linux-gnueabihf-c++filt _Z1fv") end end
36.510638
95
0.631119
87898dfcd43e5a26f06080b8254d29160a5a70fe
1,390
module SocialStream module Views module Location # Renders the location stack for your view. You can add as many stack levels as you wish. # # Usage: # <%= location(level1,leve2,level3,level4,....) %> # # Output: # base > level1 > level2 > level3 > level 4 # # Default configuration: # base => "You are here" ("location.base" on config/locales) # separator => ">" ("location.separator" on config/locales) # # Styles and HTML wrapping: # partial => location/_location.html.erb # # Example: # Render a location with two leves depth: # # <%= location(link_to(leve1.name, level1.url),link_to(leve2.name, level2.url)) %> # def location(*stack) location_body = render :partial => "location/location_body", :locals=>{:stack => stack} location_div = capture do render :partial => "location/location", :locals=>{:location_body => location_body} end case request.format when Mime::JS response = <<-EOJ $('#map_location').html("#{ escape_javascript(location_div) }"); EOJ response.html_safe else content_for(:location) do location_div end end end end end end
28.367347
95
0.543165
aca8b4303b4fd0fd2d97bc58897389dcbe1779da
483
# Cribbed from http://stackoverflow.com/questions/7749568/how-can-i-do-standard-deviation-in-ruby module MathHelper def sum(values) values.inject(0){|accum, i| accum + i } end def mean(values) sum(values)/values.length.to_f end def sample_variance(values) m = mean(values) sum = values.inject(0){|accum, i| accum +(i-m)**2 } sum/(values.length - 1).to_f end def standard_deviation(values) return Math.sqrt(sample_variance(values)) end end
21.954545
97
0.687371
7a3f4b4226210646cbdd098d5594ff354f42778e
8,039
require 'rubygems' require 'active_support/inflector' require 'json' require 'fileutils' require 'andand' require 'arvados/google_api_client' ActiveSupport::Inflector.inflections do |inflect| inflect.irregular 'specimen', 'specimens' inflect.irregular 'human', 'humans' end module Kernel def suppress_warnings original_verbosity = $VERBOSE $VERBOSE = nil result = yield $VERBOSE = original_verbosity return result end end class Arvados class TransactionFailedError < StandardError end @@config = nil @@debuglevel = 0 class << self attr_accessor :debuglevel end def initialize(opts={}) @application_version ||= 0.0 @application_name ||= File.split($0).last @arvados_api_version = opts[:api_version] || 'v1' @arvados_api_host = opts[:api_host] || config['ARVADOS_API_HOST'] or raise "#{$0}: no :api_host or ENV[ARVADOS_API_HOST] provided." @arvados_api_token = opts[:api_token] || config['ARVADOS_API_TOKEN'] or raise "#{$0}: no :api_token or ENV[ARVADOS_API_TOKEN] provided." if (opts[:suppress_ssl_warnings] or %w(1 true yes).index(config['ARVADOS_API_HOST_INSECURE']. andand.downcase)) suppress_warnings do OpenSSL::SSL.const_set 'VERIFY_PEER', OpenSSL::SSL::VERIFY_NONE end end # Define a class and an Arvados instance method for each Arvados # resource. After this, self.job will return Arvados::Job; # self.job.new() and self.job.find() will do what you want. _arvados = self namespace_class = Arvados.const_set "A#{self.object_id}", Class.new self.arvados_api.schemas.each do |classname, schema| next if classname.match /List$/ klass = Class.new(Arvados::Model) do def self.arvados @arvados end def self.api_models_sym @api_models_sym end def self.api_model_sym @api_model_sym end end # Define the resource methods (create, get, update, delete, ...) self. arvados_api. send(classname.underscore.split('/').last.pluralize.to_sym). discovered_methods. each do |method| class << klass; self; end.class_eval do define_method method.name do |*params| self.api_exec method, *params end end end # Give the new class access to the API klass.instance_eval do @arvados = _arvados # TODO: Pull these from the discovery document instead. @api_models_sym = classname.underscore.split('/').last.pluralize.to_sym @api_model_sym = classname.underscore.split('/').last.to_sym end # Create the new class in namespace_class so it doesn't # interfere with classes created by other Arvados objects. The # result looks like Arvados::A26949680::Job. namespace_class.const_set classname, klass self.class.class_eval do define_method classname.underscore do klass end end end end def client @client ||= Google::APIClient. new(:host => @arvados_api_host, :application_name => @application_name, :application_version => @application_version.to_s) end def arvados_api @arvados_api ||= self.client.discovered_api('arvados', @arvados_api_version) end def self.debuglog(message, verbosity=1) $stderr.puts "#{File.split($0).last} #{$$}: #{message}" if @@debuglevel >= verbosity end def debuglog *args self.class.debuglog *args end def config(config_file_path="~/.config/arvados/settings.conf") return @@config if @@config # Initialize config settings with environment variables. config = {} config['ARVADOS_API_HOST'] = ENV['ARVADOS_API_HOST'] config['ARVADOS_API_TOKEN'] = ENV['ARVADOS_API_TOKEN'] config['ARVADOS_API_HOST_INSECURE'] = ENV['ARVADOS_API_HOST_INSECURE'] if config['ARVADOS_API_HOST'] and config['ARVADOS_API_TOKEN'] # Environment variables take precedence over the config file, so # there is no point reading the config file. If the environment # specifies a _HOST without asking for _INSECURE, we certainly # shouldn't give the config file a chance to create a # system-wide _INSECURE state for this user. # # Note: If we start using additional configuration settings from # this file in the future, we might have to read the file anyway # instead of returning here. return (@@config = config) end begin expanded_path = File.expand_path config_file_path if File.exist? expanded_path # Load settings from the config file. lineno = 0 File.open(expanded_path).each do |line| lineno = lineno + 1 # skip comments and blank lines next if line.match('^\s*#') or not line.match('\S') var, val = line.chomp.split('=', 2) var.strip! val.strip! # allow environment settings to override config files. if !var.empty? and val config[var] ||= val else debuglog "#{expanded_path}: #{lineno}: could not parse `#{line}'", 0 end end end rescue StandardError => e debuglog "Ignoring error reading #{config_file_path}: #{e}", 0 end @@config = config end class Model def self.arvados_api arvados.arvados_api end def self.client arvados.client end def self.debuglog(*args) arvados.class.debuglog *args end def debuglog(*args) self.class.arvados.class.debuglog *args end def self.api_exec(method, parameters={}) api_method = arvados_api.send(api_models_sym).send(method.name.to_sym) parameters.each do |k,v| parameters[k] = v.to_json if v.is_a? Array or v.is_a? Hash end # Look for objects expected by request.properties.(key).$ref and # move them from parameters (query string) to request body. body = nil method.discovery_document['request']. andand['properties']. andand.each do |k,v| if v.is_a? Hash and v['$ref'] body ||= {} body[k] = parameters.delete k.to_sym end end result = client. execute(:api_method => api_method, :authenticated => false, :parameters => parameters, :body_object => body, :headers => { :authorization => 'OAuth2 '+arvados.config['ARVADOS_API_TOKEN'] }) resp = JSON.parse result.body, :symbolize_names => true if resp[:errors] raise Arvados::TransactionFailedError.new(resp[:errors]) elsif resp[:uuid] and resp[:etag] self.new(resp) elsif resp[:items].is_a? Array resp.merge(:items => resp[:items].collect do |i| self.new(i) end) else resp end end def []=(x,y) @attributes_to_update[x] = y @attributes[x] = y end def [](x) if @attributes[x].is_a? Hash or @attributes[x].is_a? Array # We won't be notified via []= if these change, so we'll just # assume they are going to get changed, and submit them if # save() is called. @attributes_to_update[x] = @attributes[x] end @attributes[x] end def save @attributes_to_update.keys.each do |k| @attributes_to_update[k] = @attributes[k] end j = self.class.api_exec :update, { :uuid => @attributes[:uuid], self.class.api_model_sym => @attributes_to_update.to_json } unless j.respond_to? :[] and j[:uuid] debuglog "Failed to save #{self.to_s}: #{j[:errors] rescue nil}", 0 nil else @attributes_to_update = {} @attributes = j end end protected def initialize(j) @attributes_to_update = {} @attributes = j end end end
30.221805
88
0.619231
f7a2640884b546da0e57c4a815515a3c02a447cc
10,140
require 'rails_helper' RSpec.feature 'viewing metrics', type: :feature do before do department1 = FactoryGirl.create(:department, name: "Department for Business, Energy & Industrial Strategy") department2 = FactoryGirl.create(:department, name: "Department for Communities and Local Government") department3 = FactoryGirl.create(:department, name: "Department for Education") department4 = FactoryGirl.create(:department, name: "Department for Environment, Food & Rural Affairs") department5 = FactoryGirl.create(:department, name: "Department for Transport") department6 = FactoryGirl.create(:department, name: "Department for Work and Pensions") department7 = FactoryGirl.create(:department, name: "Ministry of Justice") delivery_organisation1 = FactoryGirl.create(:delivery_organisation, department: department1, name: "Department for Business, Energy & Industrial Strategy") delivery_organisation2 = FactoryGirl.create(:delivery_organisation, department: department2, name: "Department for Communities and Local Government") delivery_organisation3 = FactoryGirl.create(:delivery_organisation, department: department3, name: "Department for Education") delivery_organisation4 = FactoryGirl.create(:delivery_organisation, department: department4, name: "Department for Environment, Food & Rural Affairs") delivery_organisation5 = FactoryGirl.create(:delivery_organisation, department: department5, name: "Department for Transport") delivery_organisation6 = FactoryGirl.create(:delivery_organisation, department: department6, name: "Department for Work and Pensions") delivery_organisation7 = FactoryGirl.create(:delivery_organisation, department: department7, name: "Ministry of Justice") service1 = FactoryGirl.create(:service, delivery_organisation: delivery_organisation1, name: "File your Accounts") service2 = FactoryGirl.create(:service, delivery_organisation: delivery_organisation2, name: "Planning application appeals") service3 = FactoryGirl.create(:service, delivery_organisation: delivery_organisation3, name: "Get Into Teaching") service4 = FactoryGirl.create(:service, delivery_organisation: delivery_organisation4, name: "Get a wildlife licence") service5 = FactoryGirl.create(:service, delivery_organisation: delivery_organisation5, name: "Pay the Dartford Crossing charge (Dartcharge)") service6 = FactoryGirl.create(:service, delivery_organisation: delivery_organisation6, name: "Check your State Pension") service7 = FactoryGirl.create(:service, delivery_organisation: delivery_organisation7, name: "Appeal to the tax tribunal") time_period = TimePeriod.default FactoryGirl.create(:monthly_service_metrics, :published, service: service1, month: time_period.start_month, online_transactions: 4436000, calls_received: 171) FactoryGirl.create(:monthly_service_metrics, :published, service: service1, month: time_period.end_month, online_transactions: 917) FactoryGirl.create(:monthly_service_metrics, :published, service: service2, month: time_period.start_month, online_transactions: 11000) FactoryGirl.create(:monthly_service_metrics, :published, service: service2, month: time_period.end_month, online_transactions: 560) FactoryGirl.create(:monthly_service_metrics, :published, service: service3, month: time_period.start_month, online_transactions: 91000) FactoryGirl.create(:monthly_service_metrics, :published, service: service3, month: time_period.end_month, online_transactions: 223) FactoryGirl.create(:monthly_service_metrics, :published, service: service4, month: time_period.start_month, online_transactions: 12537000, calls_received: 213775) FactoryGirl.create(:monthly_service_metrics, :published, service: service4, month: time_period.end_month, online_transactions: 482) FactoryGirl.create(:monthly_service_metrics, :published, service: service5, month: time_period.start_month, online_transactions: 5747000, calls_received: 313749) FactoryGirl.create(:monthly_service_metrics, :published, service: service5, month: time_period.end_month, online_transactions: 785) FactoryGirl.create(:monthly_service_metrics, :published, service: service6, month: time_period.start_month, online_transactions: 3709000, calls_received: 467495) FactoryGirl.create(:monthly_service_metrics, :published, service: service6, month: time_period.end_month, online_transactions: 191) FactoryGirl.create(:monthly_service_metrics, :published, service: service7, month: time_period.start_month, online_transactions: 58000) FactoryGirl.create(:monthly_service_metrics, :published, service: service7, month: time_period.end_month, online_transactions: 140) end context 'sorting metrics' do with_conditional_javascript do it 'allows sorting of metric groups' do visit view_data_government_metrics_path(group_by: Metrics::GroupBy::Department) expect(page).to have_text('Service data for UK government') expect(metric_groups(:name)).to eq([ ["Total for UK government"], ["Department for Business, Energy & Industrial Strategy"], ["Department for Communities and Local Government"], ["Department for Education"], ["Department for Environment, Food & Rural Affairs"], ["Department for Transport"], ["Department for Work and Pensions"], ["Ministry of Justice"] ]) select 'transactions received', from: 'Sort by' click_on 'Apply' unless javascript_enabled all('a', text: /\AOpen\z/).each(&:click) if javascript_enabled expect(metric_groups(:name, :transactions_received_total)).to eq([ ["Total for UK government", "26592298"], ["Department for Environment, Food & Rural Affairs", "12537482"], ["Department for Transport", "5747785"], ["Department for Business, Energy & Industrial Strategy", "4436917"], ["Department for Work and Pensions", "3709191"], ["Department for Education", "91223"], ["Ministry of Justice", "58140"], ["Department for Communities and Local Government", "11560"], ]) if javascript_enabled find('label', text: 'Low to High').click else choose 'Low to High' end click_on 'Apply' unless javascript_enabled all('a', text: /\AOpen\z/).each(&:click) if javascript_enabled expect(metric_groups(:name, :transactions_received_total)).to eq([ ["Department for Communities and Local Government", "11560"], ["Ministry of Justice", "58140"], ["Department for Education", "91223"], ["Department for Work and Pensions", "3709191"], ["Department for Business, Energy & Industrial Strategy", "4436917"], ["Department for Transport", "5747785"], ["Department for Environment, Food & Rural Affairs", "12537482"], ["Total for UK government", "26592298"], ]) end end it 'collapses metric groups, when sorting by attributes (other than name)', js: true do visit view_data_government_metrics_path(group_by: Metrics::GroupBy::Department, order_by: "name") expect(page).to have_selector('.m-metric-group', count: 8) expect(page).to have_selector('.m-metric-group[data-behaviour~="m-metric-group__collapsible"]', count: 0) expect(page).to have_selector('.completeness', count: 8) select 'transactions received', from: 'Sort by' expect(page).to have_selector('.m-metric-group[data-behaviour~="m-metric-group__collapsible"]', count: 8) end it 'correctly shows transactions with outcome', js: true do visit view_data_government_metrics_path(group_by: Metrics::GroupBy::Department, order_by: "transactions_with_outcome") expect(page).to have_selector('.m-metric-group', count: 8) expect(page).to have_selector('.m-metric-group[data-behaviour~="m-metric-group__collapsible"]', count: 0) expect(page).to have_selector('.completeness', count: 8) end it 'gov totals show how many services' do visit view_data_government_metrics_path(group_by: Metrics::GroupBy::Department, order_by: "name") expect(page).to have_content('based on 7 services', count: 1) end it 'collapsed totals show how many services' do visit view_data_government_metrics_path(group_by: Metrics::GroupBy::Department, order_by: "transactions-received") expect(page).to have_content('based on 7 services', count: 1) end end context 'sometimes we have unspecified calls received' do it 'sometimes has unspecified values, sometimes not' do visit view_data_government_metrics_path(group_by: Metrics::GroupBy::Department) expect(metric_groups(:name, :calls_received_unspecified)).to eq([ ['Total for UK government', '995190'], ['Department for Business, Energy & Industrial Strategy', '171'], ["Department for Communities and Local Government", nil], ['Department for Education', nil], ['Department for Environment, Food & Rural Affairs', '213775'], ['Department for Transport', '313749'], ['Department for Work and Pensions', '467495'], ['Ministry of Justice', nil], ]) end end private def metric_groups(*attrs) attributes = ->(metric_group) { attrs.map { |attribute| metric_group.send(attribute) } } all('.m-metric-group') .map { |element| MetricGroup.new(element) } .collect(&attributes) end class MetricGroup def initialize(element) @element = element end attr_reader :element def name element.find('h2').text end def transactions_received_total begin element.find('.m-metric__transactions-received .m-metric-headline data', visible: false)[:value] rescue nil end end def calls_received_unspecified begin element.find('li[data-metric-item-identifier="calls-received"] .metric-value data')[:value] rescue nil end end end end
53.93617
166
0.722091
f87060fec087a126515416165d85ec02e37c0ef3
6,012
# # Copyright 2012-2016 Chef Software, 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. # name "openssl" license "OpenSSL" license_file "LICENSE" skip_transitive_dependency_licensing true dependency "zlib" dependency "cacerts" dependency "makedepend" unless aix? || windows? default_version "1.1.1k" # OpenSSL source ships with broken symlinks which windows doesn't allow. # Skip error checking. source url: "https://www.openssl.org/source/openssl-#{version}.tar.gz", extract: :lax_tar version("1.1.1k") { source sha256: "892a0875b9872acd04a9fde79b1f943075d5ea162415de3047c327df33fbaee5" } version("1.0.2t") { source sha256: "14cb464efe7ac6b54799b34456bd69558a749a4931ecfd9cf9f71d7881cac7bc" } version("1.0.2o") { source sha256: "ec3f5c9714ba0fd45cb4e087301eb1336c317e0d20b575a125050470e8089e4d" } version("1.0.2k") { source sha256: "6b3977c61f2aedf0f96367dcfb5c6e578cf37e7b8d913b4ecb6643c3cb88d8c0" } version("1.0.2j") { source sha256: "e7aff292be21c259c6af26469c7a9b3ba26e9abaaffd325e3dccc9785256c431" } version("1.0.2i") { source sha256: "9287487d11c9545b6efb287cdb70535d4e9b284dd10d51441d9b9963d000de6f" } version("1.0.2h") { source sha256: "1d4007e53aad94a5b2002fe045ee7bb0b3d98f1a47f8b2bc851dcd1c74332919" } version("1.0.2g") { source md5: "f3c710c045cdee5fd114feb69feba7aa" } version("1.0.1u") { source sha256: "4312b4ca1215b6f2c97007503d80db80d5157f76f8f7d3febbe6b4c56ff26739" } version("1.0.1t") { source md5: "9837746fcf8a6727d46d22ca35953da1" } version("1.0.1s") { source md5: "562986f6937aabc7c11a6d376d8a0d26" } version("1.0.1r") { source md5: "1abd905e079542ccae948af37e393d28" } relative_path "openssl-#{version}" build do if aix? env = aix_env else env = with_standard_compiler_flags(with_embedded_path) end if aix? env["M4"] = "/opt/freeware/bin/m4" elsif freebsd? # Should this just be in standard_compiler_flags? env["LDFLAGS"] += " -Wl,-rpath,#{install_dir}/embedded/lib" elsif windows? # XXX: OpenSSL explicitly sets -march=i486 and expects that to be honored. # It has OPENSSL_IA32_SSE2 controlling whether it emits optimized SSE2 code # and the 32-bit calling convention involving XMM registers is... vague. # Do not enable SSE2 generally because the hand optimized assembly will # overwrite registers that mingw expects to get preserved. env["CFLAGS"] = "-I#{install_dir}/embedded/include" env["CPPFLAGS"] = env["CFLAGS"] env["CXXFLAGS"] = env["CFLAGS"] end configure_args = [ "--prefix=#{install_dir}/embedded", "--with-zlib-lib=#{install_dir}/embedded/lib", "--with-zlib-include=#{install_dir}/embedded/include", "no-idea", "no-mdc2", "no-rc5", "shared", "no-ssl3", ] if windows? configure_args << "zlib-dynamic" else configure_args << "zlib" end configure_cmd = if aix? # "perl ./Configure aix64-cc" # Use GCC "perl ./Configure aix64-gcc" elsif mac_os_x? "./Configure darwin64-x86_64-cc" elsif smartos? "/bin/bash ./Configure solaris64-x86_64-gcc -static-libgcc" elsif omnios? "/bin/bash ./Configure solaris-x86-gcc" elsif solaris_10? # This should not require a /bin/sh, but without it we get # Errno::ENOEXEC: Exec format error platform = sparc? ? "solaris-sparcv9-gcc" : "solaris-x86-gcc" "/bin/sh ./Configure #{platform} -static-libgcc" elsif solaris_11? platform = sparc? ? "solaris64-sparcv9-gcc" : "solaris64-x86_64-gcc" "/bin/bash ./Configure #{platform} -static-libgcc" elsif windows? platform = windows_arch_i386? ? "mingw" : "mingw64" "perl.exe ./Configure #{platform}" else prefix = if linux? && ppc64? "./Configure linux-ppc64" elsif linux? && s390x? # With gcc > 4.3 on s390x there is an error building # with inline asm enabled "./Configure linux64-s390x -DOPENSSL_NO_INLINE_ASM" else "./config" end "#{prefix} disable-gost" end if windows? # Patch Makefile.org to update the compiler flags/options table for mingw. patch source: "openssl-1.0.1q-fix-compiler-flags-table-for-msys.patch", env: env end # Out of abundance of caution, we put the feature flags first and then # the crazy platform specific compiler flags at the end. configure_args << env["CFLAGS"] << env["LDFLAGS"] configure_command = configure_args.unshift(configure_cmd).join(" ") command configure_command, env: env, in_msys_bash: true if aix? # This enables omnibus to use 'makedepend' # from fileset 'X11.adt.imake' (AIX install media) env["PATH"] = "/usr/lpp/X11/bin:#{ENV["PATH"]}" end make "depend", env: env # make -j N on openssl is not reliable make env: env if aix? # We have to sudo this because you can't actually run slibclean without being root. # Something in openssl changed in the build process so now it loads the libcrypto # and libssl libraries into AIX's shared library space during the first part of the # compile. This means we need to clear the space since it's not being used and we # can't install the library that is already in use. Ideally we would patch openssl # to make this not be an issue. # Bug Ref: http://rt.openssl.org/Ticket/Display.html?id=2986&user=guest&pass=guest command "sudo /usr/sbin/slibclean", env: env end # This is equivalent to 'install' except it excludes the docs make "install_sw install_ssldirs", env: env end
37.811321
103
0.707585
e2e82d8fa7dac28655789c4804de59ebbbba7740
83
class IssueComment < ActiveRecord::Base belongs_to :issue belongs_to :user end
16.6
39
0.783133
189ca5fe3aed89a71094f4590562ce9ef0baedb8
620
require 'benchmark' iterations = 100_000 Benchmark.bm do |bm| bm.report('define_method') do class NullOrder ['usd', 'euro', 'yen'].each do |method| define_method "price_#{method}".to_sym do 0.0 end end end iterations.times do o = NullOrder.new o.price_euro o.price_usd end end bm.report('method_missing') do class NullOrder2 def method_missing(m, *args, &block) m.to_s =~ /price_/ ? 0.0 : super end end iterations.times do o2 = NullOrder2.new o2.price_euro o2.price_usd end end end
16.315789
48
0.583871
284504d7a1b3d03fe22855ba39412917309ac769
3,164
class RubyMotionQuery::Device class << self def fake_height(value) @_three_point_five_inch = nil @_four_inch = nil @_four_point_seven_inch = nil @_five_point_five_inch = nil s = size_a @_size_a[1] = value end def reset_fake_caches @_three_point_five_inch = nil @_four_inch = nil @_four_point_seven_inch = nil @_five_point_five_inch = nil @_size_a = nil end end end describe 'image' do before do @rmq = RubyMotionQuery::RMQ end it 'should return image from RMQ or an instance of rmq' do @rmq.image.should == RubyMotionQuery::ImageUtils rmq = RubyMotionQuery::RMQ.new rmq.image.should == RubyMotionQuery::ImageUtils end it "should convert a view to a UIImage" do view = UIView.alloc.initWithFrame([[0, 0], [10, 10]]) image = @rmq.image.from_view(view) image.class.should == UIImage CGSizeEqualToSize(image.size, [10, 10]).should == true image.scale.should == UIScreen.mainScreen.scale end describe "resource_for_device" do it "should get the correct image size for a three point five inch device" do @rmq.device.fake_height(480) image = @rmq.image.resource_for_device('Default') @rmq.device.reset_fake_caches image.is_a?(UIImage).should.be.true image.size.height.should == 480 end it "should get the -568h image on a four inch" do @rmq.device.fake_height(568) image = @rmq.image.resource_for_device('Default') @rmq.device.reset_fake_caches image.is_a?(UIImage).should.be.true image.size.height.should == 568 end it "should get the -667h image on a four point seven inch" do @rmq.device.fake_height(667) image = @rmq.image.resource_for_device('Default') @rmq.device.reset_fake_caches image.is_a?(UIImage).should.be.true image.size.height.should == 667 end it "should get the -736h image on a five point five inch" do @rmq.device.fake_height(736) image = @rmq.image.resource_for_device('Default') @rmq.device.reset_fake_caches image.is_a?(UIImage).should.be.true image.size.height.should == 736 end end describe "resource_resizable" do it "should return an image with the proper cap insets" do opts = { top: 1, left: 1, bottom: 1, right: 1 } image = @rmq.image.resource_resizable('logo', opts) image.is_a?(UIImage).should.be.true image.capInsets.should == UIEdgeInsetsMake(1.0, 1.0, 1.0, 1.0) end it "should accept the shortcut labels for position as well" do opts = { t: 1, l: 1, b: 1, r: 1 } image = @rmq.image.resource_resizable('logo', opts) image.is_a?(UIImage).should.be.true image.capInsets.should == UIEdgeInsetsMake(1.0, 1.0, 1.0, 1.0) end end describe "resource" do it "should return the image when cached" do image = @rmq.image.resource('logo') image.is_a?(UIImage).should.be.true end it "should return the image when cached is false" do image = @rmq.image.resource('logo', {cache: false}) image.is_a?(UIImage).should.be.true end end end
29.296296
80
0.659924
1adbaea70283745e54af840932b3796950ebfbd3
3,335
require 'helper' class TestFakerNamePL < Test::Unit::TestCase include DeterministicHelper assert_methods_are_deterministic( FFaker::NamePL, :name, :name_with_prefix, :last_name, :first_name, :female_name_with_prefix, :male_name_with_prefix, :female_full_name, :male_full_name, :female_first_name, :female_last_name, :male_first_name, :male_last_name, :prefix, :female_prefix, :male_prefix, :academic_degree_prefix ) def setup @tester = FFaker::NamePL end def test_name assert_match(/(\w+\.? ?){2}/, @tester.name) end def name_with_prefix prefix, first_name, last_name = @tester.name_with_prefix.split assert_include(@tester::PREFIXES, prefix) refute_empty(first_name) refute_empty(last_name) end def test_female_name_with_prefix prefix, first_name, last_name = @tester.female_name_with_prefix.split assert_include(@tester::FEMALE_PREFIXES, prefix) assert_include(@tester::FEMALE_FIRST_NAMES, first_name) assert_include(@tester::FEMALE_LAST_NAMES, last_name) end def test_male_name_with_prefix prefix, first_name, last_name = @tester.male_name_with_prefix.split assert_include(@tester::MALE_PREFIXES, prefix) assert_include(@tester::MALE_FIRST_NAMES, first_name) assert_include(@tester::MALE_LAST_NAMES, last_name) end def test_female_full_name first_name, last_name = @tester.female_full_name.split assert_include(@tester::FEMALE_FIRST_NAMES, first_name) assert_include(@tester::FEMALE_LAST_NAMES, last_name) end def test_male_full_name first_name, last_name = @tester.male_full_name.split assert_include(@tester::MALE_FIRST_NAMES, first_name) assert_include(@tester::MALE_LAST_NAMES, last_name) end def test_first_name first_names = @tester::FEMALE_FIRST_NAMES + @tester::MALE_FIRST_NAMES assert_include(first_names, @tester.first_name) end def test_first_name_with_argument assert_include(@tester::FEMALE_FIRST_NAMES, @tester.first_name(:female)) end def test_female_first_name assert_include(@tester::FEMALE_FIRST_NAMES, @tester.female_first_name) end def test_male_first_name assert_include(@tester::MALE_FIRST_NAMES, @tester.male_first_name) end def test_last_name last_names = @tester::FEMALE_LAST_NAMES + @tester::MALE_LAST_NAMES assert_include(last_names, @tester.last_name) end def test_last_name_with_argument assert_include(@tester::MALE_LAST_NAMES, @tester.last_name(:male)) end def test_female_last_name assert_include(@tester::FEMALE_LAST_NAMES, @tester.female_last_name) end def test_male_last_name assert_include(@tester::MALE_LAST_NAMES, @tester.male_last_name) end def test_prefix assert_include(@tester::PREFIXES, @tester.prefix) end def test_female_prefix assert_include(@tester::FEMALE_PREFIXES, @tester.female_prefix) end def test_male_prefix assert_include(@tester::MALE_PREFIXES, @tester.male_prefix) end def test_academic_degree_prefix assert_include(@tester::ACADEMIC_DEGREE_PREFIXES, @tester.academic_degree_prefix) end def test_name_for_gender_raises_argument_error error = assert_raises(ArgumentError) { @tester.send(:name_for_gender, :name, :vodka) } assert_match("Gender must be one of: #{@tester::GENDERS}", error.message) end end
30.318182
90
0.771214
d52d1d05771a7e9a246618d58fdb4d5e997cdedf
4,349
require File.expand_path('../../../spec_helper', __FILE__) describe "Integer#divmod" do context "fixnum" do it "returns an Array containing quotient and modulus obtained from dividing self by the given argument" do 13.divmod(4).should == [3, 1] 4.divmod(13).should == [0, 4] 13.divmod(4.0).should == [3, 1] 4.divmod(13.0).should == [0, 4] 1.divmod(2.0).should == [0, 1.0] 200.divmod(bignum_value).should == [0, 200] end it "raises a ZeroDivisionError when the given argument is 0" do lambda { 13.divmod(0) }.should raise_error(ZeroDivisionError) lambda { 0.divmod(0) }.should raise_error(ZeroDivisionError) lambda { -10.divmod(0) }.should raise_error(ZeroDivisionError) end it "raises a ZeroDivisionError when the given argument is 0 and a Float" do lambda { 0.divmod(0.0) }.should raise_error(ZeroDivisionError) lambda { 10.divmod(0.0) }.should raise_error(ZeroDivisionError) lambda { -10.divmod(0.0) }.should raise_error(ZeroDivisionError) end it "raises a TypeError when given a non-Integer" do lambda { (obj = mock('10')).should_receive(:to_int).any_number_of_times.and_return(10) 13.divmod(obj) }.should raise_error(TypeError) lambda { 13.divmod("10") }.should raise_error(TypeError) lambda { 13.divmod(:symbol) }.should raise_error(TypeError) end end context "bignum" do before :each do @bignum = bignum_value(55) end # Based on MRI's test/test_integer.rb (test_divmod), # MRI maintains the following property: # if q, r = a.divmod(b) ==> # assert(0 < b ? (0 <= r && r < b) : (b < r && r <= 0)) # So, r is always between 0 and b. it "returns an Array containing quotient and modulus obtained from dividing self by the given argument" do @bignum.divmod(4).should == [2305843009213693965, 3] @bignum.divmod(13).should == [709490156681136604, 11] @bignum.divmod(4.5).should == [2049638230412172288, 3.5] not_supported_on :opal do @bignum.divmod(4.0).should == [2305843009213693952, 0.0] @bignum.divmod(13.0).should == [709490156681136640, 8.0] @bignum.divmod(2.0).should == [4611686018427387904, 0.0] end @bignum.divmod(bignum_value).should == [1, 55] (-(10**50)).divmod(-(10**40 + 1)).should == [9999999999, -9999999999999999999999999999990000000001] (10**50).divmod(10**40 + 1).should == [9999999999, 9999999999999999999999999999990000000001] (-10**50).divmod(10**40 + 1).should == [-10000000000, 10000000000] (10**50).divmod(-(10**40 + 1)).should == [-10000000000, -10000000000] end describe "with q = floor(x/y), a = q*b + r," do it "returns [q,r] when a < 0, b > 0 and |a| < b" do a = -@bignum + 1 b = @bignum a.divmod(b).should == [-1, 1] end it "returns [q,r] when a > 0, b < 0 and a > |b|" do b = -@bignum + 1 a = @bignum a.divmod(b).should == [-2, -@bignum + 2] end it "returns [q,r] when a > 0, b < 0 and a < |b|" do a = @bignum - 1 b = -@bignum a.divmod(b).should == [-1, -1] end it "returns [q,r] when a < 0, b < 0 and |a| < |b|" do a = -@bignum + 1 b = -@bignum a.divmod(b).should == [0, -@bignum + 1] end end it "raises a ZeroDivisionError when the given argument is 0" do lambda { @bignum.divmod(0) }.should raise_error(ZeroDivisionError) lambda { (-@bignum).divmod(0) }.should raise_error(ZeroDivisionError) end # Behaviour established as correct in r23953 it "raises a FloatDomainError if other is NaN" do lambda { @bignum.divmod(nan_value) }.should raise_error(FloatDomainError) end it "raises a ZeroDivisionError when the given argument is 0 and a Float" do lambda { @bignum.divmod(0.0) }.should raise_error(ZeroDivisionError) lambda { (-@bignum).divmod(0.0) }.should raise_error(ZeroDivisionError) end it "raises a TypeError when the given argument is not an Integer" do lambda { @bignum.divmod(mock('10')) }.should raise_error(TypeError) lambda { @bignum.divmod("10") }.should raise_error(TypeError) lambda { @bignum.divmod(:symbol) }.should raise_error(TypeError) end end end
36.855932
110
0.618763
79373ce48972e2ef02accfc6fe4e90f746a458f9
6,725
require 'test_helper' class DocumentsControllerTest < ActionController::TestCase def test_routing assert_recognizes( { controller: 'documents', id:'1', action: 'send_pdf', slug:'a_simple_image_named' }, { path: '/documents/1/a_simple_image_named.pdf', method: :get } ) assert_recognizes( { controller: 'documents', id:'1', action: 'send_full_text', slug:'a_simple_image_named' }, { path: '/documents/1/a_simple_image_named.txt', method: :get } ) assert_recognizes( { controller: 'documents', id:'1', page_name: 'a_simple_image_named', action: 'send_page_text' }, { path: '/documents/1/pages/a_simple_image_named.txt', method: :get } ) assert_recognizes( { controller: 'documents', id:'1', page_name: 'a_simple_image_named', action: 'set_page_text' }, { path: '/documents/1/pages/a_simple_image_named.txt', method: :post } ) assert_recognizes( { controller: 'documents', id:'1', page_name: 'a_simple_image_named', action: 'send_page_image' }, { path: '/documents/1/pages/a_simple_image_named.gif', method: :get } ) end def test_it_can_log_in_a_reviewer reviewer = accounts(:freelancer_bob) reviewer.ensure_security_key! get :show, :id=>doc.id, :format=>:html, :key=>reviewer.security_key.key assert_response :success assert_equal reviewer.id, session['account_id'] end def test_it_renders_a_public_document get :show, :id=>doc.id, :format=>:html assert_response :success refute assigns[:edits_enabled] login_account! get :show, :id=>doc.id, :format=>:html assert assigns[:edits_enabled] end def test_it_renders_a_private_document_to_owner get :show, :id=>secret_doc.id, :format=>:html assert_response :forbidden login_account! get :show, :id=>secret_doc.id, :format=>:html assert assigns[:edits_enabled] assert_response :success end def test_update login_account! put :update, :id=>doc.id, :title=>'A new Title' assert_response :success assert_equal 'A new Title', doc.reload.title Document.populate_annotation_counts(louis, [doc]) assert_equal ActiveSupport::JSON.decode( doc.to_json ), json_body end def test_destroy login_account! assert_difference( 'Document.count', -1 ){ delete :destroy, :id=>doc.id } assert_response :success assert_empty Document.where( id: doc.id ) end def test_redact_pages login_account! post :redact_pages, :id=>doc.id, :redactions=>'[{"location":"286,614,353,437","page":1}]', :color=>'black' assert_response :success assert_job_action 'redact_pages' end def test_remove_pages login_account! post :remove_pages, :id=>doc.id, :pages=>[1,2] assert_response :success assert_job_action 'document_remove_pages' end def test_reorder_pages login_account! post :reorder_pages, :id=>doc.id, :page_order=> (0...doc.page_count).to_a.shuffle assert_response :success assert_job_action 'document_reorder_pages' end def test_upload_insert_document login_account! post :upload_insert_document, :id=>doc.id assert_response 409 post :upload_insert_document, :id=>doc.id, :file=>'none', :replace_pages_start=>1, :document_number=>1, :document_count=>1 assert_response :success assert_job_action 'document_remove_pages' end def test_save_page_text login_account! post :save_page_text, :id=>doc.id, :modified_pages=>'{"1":"new page text"}' assert_response :success assert_equal 'new page text', doc.reload.pages.where(:page_number=>1).first.text assert_job_action 'reindex_document' end def test_entities login_account! get :entities, :ids=>[doc.id] assert_equal entities(:person).as_json, json_body['entities'].first end def test_entity login_account! get :entity, :entity_id=>entities(:person).id assert_response :success assert_equal entities(:person).as_json( :include_excerpts => true ).with_indifferent_access, json_body['entities'].first end def test_dates login_account! ed = entity_dates(:jan1) get :dates, :id=>ed.id json = ed.as_json(:include_excerpts=>true) assert_response :success assert_equal json.with_indifferent_access, json_body['date'] end def test_retrieving_occurrence login_account! get :occurrence, :id=>entities(:person).id, :occurrence=>'8:16' assert_response :success ex = json_body['excerpts'] assert_equal 1, ex.length assert_equal "Call me <span class=\"occurrence\">Ishmael.</span>", ex.first['excerpt'] assert_equal 1, ex.first['page_number'] end def test_mentions login_account! get :mentions, :id=>doc.id, :q=>'Ishmael' assert_response :success assert_equal "Call me <b>Ishmael</b>.", json_body['mentions'].first['text'] end def test_status login_account! get :status, :ids=>[doc.id] assert_response :success Document.populate_annotation_counts(louis,[doc]) assert_equal doc.access, json_body['documents'].first['access'] end def test_per_page_note_counts login_account! get :per_page_note_counts, :id=>doc.id assert_response :success assert_equal( { "2"=>2, "1"=>1 }, json_body ) end def test_queue_length login_account! get :queue_length assert_equal 0, json_body['queue_length'] doc.update_attributes :access=>Document::PENDING get :queue_length assert_equal 1, json_body['queue_length'] end def test_reprocess_text login_account! get :reprocess_text, :id=>doc.id assert_response :success assert_job_action 'large_document_import' end def test_send_pdf get :send_pdf, :id=>doc.id assert_redirected_to doc.pdf_url(direct: true) end def test_send_page_image get :send_page_image, :id=>doc.id, :page_name=>'one-p1-800' assert_match doc.page_image_path(1, 800), response.headers['Location'] end def test_send_full_text get :send_full_text, :id=>doc.id assert_match doc.full_text_path, response.headers['Location'] end def test_send_page_text # n.b. the document's title might have /-p\d/ naturally occuring # We should get the page that corresponds to the last occurance get :send_page_text, :id=>doc.id, :page_name=>'one-p88-p1-800' assert_response :success assert_equal pages(:first).text, response.body end def test_set_page_text login_account! post :set_page_text, :id=>doc.id, :page_name=>'one-p1-800', :text=>'This is my page!' assert_equal "This is my page!", pages(:first).text end def test_preview login_account! get :preview, :id=>doc.id assert_response :success assert_template "preview" end end
30.990783
126
0.705576
ac9326ced197b865925039447de6eb9d04a54664
256
class NdlStatCheckout < ActiveRecord::Base belongs_to :ndl_statistic validates_presence_of :checkout_type_id, :carrier_type_id, :users_count, :items_count validates_numericality_of :checkout_type_id, :carrier_type_id, :users_count, :items_count end
36.571429
91
0.835938
7a26b55ac625b9ac50d3a521587fa41d62d291c2
770
# frozen_string_literal: true require 'rubygems/command' require 'rubygems/query_utils' require 'rubygems/deprecate' class Gem::Commands::QueryCommand < Gem::Command extend Gem::Deprecate rubygems_deprecate_command include Gem::QueryUtils def initialize(name = 'query', summary = 'Query gem information in local or remote repositories') super name, summary, :name => //, :domain => :local, :details => false, :versions => true, :installed => nil, :version => Gem::Requirement.default add_option('-n', '--name-matches REGEXP', 'Name of gem(s) to query on matches the', 'provided REGEXP') do |value, options| options[:name] = /#{value}/i end add_query_options end end
26.551724
83
0.645455
5d4b8682b19ae921aa46bd1057f5145fb73b89cb
416
# frozen_string_literal: true require 'spec_helper' RSpec.describe NilSolrEndpoint do let(:instance) { described_class.new } describe "#ping" do subject { instance.ping } it { is_expected.to be false } end describe "#persisted?" do it { is_expected.not_to be_persisted } end describe "#url" do subject { instance.url } it { is_expected.to eq 'Solr not initialized' } end end
17.333333
51
0.685096
210568f7631ae0ef3379a56c075fcb8bd22f98c0
1,234
# encoding: utf-8 require 'spec_helper' describe RuboCop::Cop::Style::ParameterLists, :config do subject(:cop) { described_class.new(config) } let(:cop_config) do { 'Max' => 4, 'CountKeywordArgs' => true } end it 'registers an offense for a method def with 5 parameters' do inspect_source(cop, ['def meth(a, b, c, d, e)', 'end']) expect(cop.offenses.size).to eq(1) expect(cop.config_to_allow_offenses).to eq('Max' => 5) end it 'accepts a method def with 4 parameters' do inspect_source(cop, ['def meth(a, b, c, d)', 'end']) expect(cop.offenses).to be_empty end context 'When CountKeywordArgs is true' do it 'counts keyword arguments as well', ruby: 2.0 do inspect_source(cop, ['def meth(a, b, c, d: 1, e: 2)', 'end']) expect(cop.offenses.size).to eq(1) end end context 'When CountKeywordArgs is false' do before { cop_config['CountKeywordArgs'] = false } it 'it does not count keyword arguments', ruby: 2.0 do inspect_source(cop, ['def meth(a, b, c, d: 1, e: 2)', 'end']) expect(cop.offenses).to be_empty end end end
27.422222
65
0.585089
114ad50dd37dce70d85633adf2d92f50c978a4c9
1,092
require_relative 'safe/format' class String alias :old_method_missing :method_missing alias :old_respond_to? :respond_to? def method_missing(method, *args) name = method.to_s colors = 'black|red|green|yellow|blue|purple|cyan|white|none' if (name =~ /format(_bold)?(_underline)?(?:_fg_(#{colors}))?(?:_bg_(#{colors}))?/).nil? old_method_missing(method, *args) else EverydayCliUtils::Format::format(self, EverydayCliUtils::Format::build_string(!$1.nil?, !$2.nil?, $3.nil? ? nil : $3.to_sym, $4.nil? ? nil : $4.to_sym)) end end def respond_to?(method, include_all = false) name = method.to_s colors = 'black|red|green|yellow|blue|purple|cyan|white|none' (!(name =~ /format(_bold)?(_underline)?(?:_fg_(#{colors}))?(?:_bg_(#{colors}))?/).nil?) || old_respond_to?(method, include_all) end def format_all EverydayCliUtils::Format::format_all(self) end def remove_format EverydayCliUtils::Format::remove_format(self) end def mycenter(len, char = ' ') EverydayCliUtils::Format::mycenter(self, len, char) end end
32.117647
158
0.673993
f7a3204eba7fcc4c3702e8d6fad1e747d75c2eef
53
json.partial! "companies/company", company: @company
26.5
52
0.773585
1a6d54651c06fa8058b48292b96cbe54acee2b36
955
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `rails # db:schema:load`. When creating a new database, `rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2021_07_02_021645) do create_table "to_dos", force: :cascade do |t| t.string "listItem" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end end
43.409091
86
0.770681
e2c8712bc2966d1486041e025f8eaf2170db0149
221
worker_processes 2 pid "tmp/pids/unicorn.pid" working_directory ENV["UNICORN_PWD"] stderr_path "log/unicorn.stderr.log" stdout_path "log/unicorn.stdout.log" listen File.join(ENV["SHARED_PATH"], "tmp/sockets/unicorn.sock")
36.833333
64
0.800905
bb02325f8429b3adb5cff8381acc0a7460801e1f
992
# 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: 20190414052436) do create_table "users", force: :cascade do |t| t.string "name" t.string "email" t.datetime "created_at", null: false t.datetime "updated_at", null: false t.string "password_digest" end end
41.333333
86
0.765121
1a264f73a975b09dba0e3578eaab10d5c08d35fc
26
# typed: true { foo: 2 }
6.5
13
0.5
4a80e0df3389d16d88e7cafb34f7e58b9bbd5a69
5,516
require 'rails_helper' RSpec.describe Admin::TeamsController, type: :controller do let(:admin) { create(:admin) } describe "GET index" do it "assigns all teams as @teams" do sign_in admin team = create(:team) get :index expect(assigns(:teams)).to eq [team] end end describe "GET show" do it "assigns the requested team as @team" do sign_in admin team = create(:team) get :show, {id: team.to_param} expect(assigns(:team)).to eq team end end describe "GET new" do it "assigns a new team as @team" do sign_in admin get :new expect(assigns(:team)).to be_a_new(Team) end end describe "GET edit" do it "assigns the requested team as @team" do sign_in admin team = create(:team) get :edit, {id: team.to_param} expect(assigns(:team)).to eq team end end describe "POST create" do describe "with valid params" do it "creates a new Team" do sign_in admin pw = 'teampw' expect { post :create, team: attributes_for(:team) }.to change(Team, :count).by(1) end it "assigns a newly created team as @team" do sign_in admin pw = 'teampw' post :create, team: attributes_for(:team) expect(assigns(:team)).to be_a(Team) expect(assigns(:team)).to be_persisted end it "redirects to the created team" do sign_in admin pw = 'teampw' post :create, team: attributes_for(:team) expect(response).to redirect_to admin_team_path(Team.last) end end describe "with invalid params" do it "assigns a newly created but unsaved team as @team" do sign_in admin # Trigger the behavior that occurs when invalid params are submitted allow_any_instance_of(Team).to receive(:save).and_return(false) post :create, team: attributes_for(:team, name: '') expect(assigns(:team)).to be_a_new(Team) end it "re-renders the 'new' template" do sign_in admin # Trigger the behavior that occurs when invalid params are submitted allow_any_instance_of(Team).to receive(:save).and_return(false) post :create, team: attributes_for(:team, name: '') expect(response).to render_template('new') end end end describe "PUT update" do describe "with valid params" do it "updates the requested team" do sign_in admin team = create(:team) # Assuming there are no other teams in the database, this # specifies that the Team created on the previous line # receives the :update_attributes message with whatever params are # submitted in the request. expect_any_instance_of(Team).to receive(:update).with({'name' => 'updated!'}) put :update, {id: team.to_param, team: {'name' => 'updated!'}} end it "assigns the requested team as @team" do sign_in admin team = create(:team) put :update, id: team.to_param, team: make_valid_team_param_hash(team) expect(assigns(:team)).to eq team end it "redirects to the team" do sign_in admin team = create(:team) put :update, id: team.to_param, team: make_valid_team_param_hash(team) expect(response).to redirect_to admin_team_path(team) end end describe "with invalid params" do it "assigns the team as @team" do sign_in admin team = create(:team) # Trigger the behavior that occurs when invalid params are submitted allow_any_instance_of(Team).to receive(:save).and_return(false) put :update, id: team.to_param, team: make_invalid_team_param_hash(team) expect(assigns(:team)).to eq team end it "re-renders the 'edit' template" do sign_in admin team = create(:team) # Trigger the behavior that occurs when invalid params are submitted allow_any_instance_of(Team).to receive(:save).and_return(false) put :update, id: team.to_param, team: make_invalid_team_param_hash(team) expect(response).to render_template('edit') end end end describe "DELETE destroy" do context 'for the team which has no members' do it "destroys the requested team" do sign_in admin team = create(:team) expect { delete :destroy, {id: team.to_param} }.to change(Team, :count).by(-1) end it "redirects to the teams list" do sign_in admin team = create(:team) delete :destroy, {id: team.to_param} expect(response).to redirect_to admin_teams_path end end context 'for the team which has some members' do it 'does not destroy the requested team' do sign_in admin team = create(:team) player = create(:player) player.confirm team.players << player request.env['HTTP_REFERER'] = admin_team_path(team) expect { delete :destroy, id: team.to_param } .not_to change(Team, :count) end it 'redirects to the requested team' do sign_in admin team = create(:team) player = create(:player) player.confirm team.players << player request.env['HTTP_REFERER'] = admin_team_path(team) delete :destroy, id: team.to_param expect(response).to redirect_to(admin_team_path(team)) end end end end
30.815642
85
0.624365
39b8b17a763137750cd82a4b140836cbc6cc4603
160
class AddAdminNameColumnToSpreeStockLocations < ActiveRecord::Migration[4.2] def change add_column :spree_stock_locations, :admin_name, :string end end
26.666667
76
0.80625
abbad6c1924a872bebd4cb5f0eb58771bafa7f4d
55,378
# frozen_string_literal: true # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Auto-generated by gapic-generator-ruby. DO NOT EDIT! module Google module Cloud module Compute module V1 # Messages # @!attribute [rw] code # @return [::String] # [Output Only] The error type identifier for this error. # @!attribute [rw] location # @return [::String] # [Output Only] Indicates the field in the request that caused the error. This property is optional. # @!attribute [rw] message # @return [::String] # [Output Only] An optional, human-readable error message. class Errors include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # [Output Only] If errors are generated during processing of the operation, this field will be populated. # @!attribute [rw] errors # @return [::Array<::Google::Cloud::Compute::V1::Errors>] # [Output Only] The array of errors encountered while processing this operation. class Error include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # @!attribute [rw] key # @return [::String] # [Output Only] A key that provides more detail on the warning being returned. For example, for warnings where there are no results in a list request for a particular zone, this key might be scope and the key value might be the zone name. Other examples might be a key indicating a deprecated resource and a suggested replacement, or a warning about invalid network settings (for example, if an instance attempts to perform IP forwarding but is not enabled for IP forwarding). # @!attribute [rw] value # @return [::String] # [Output Only] A warning data value corresponding to the key. class Data include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # @!attribute [rw] code # @return [::Google::Cloud::Compute::V1::Warnings::Code] # [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response. # @!attribute [rw] data # @return [::Array<::Google::Cloud::Compute::V1::Data>] # [Output Only] Metadata about this warning in key: value format. For example: # "data": [ { "key": "scope", "value": "zones/us-east1-d" } # @!attribute [rw] message # @return [::String] # [Output Only] A human-readable description of the warning code. class Warnings include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response. module Code # A value indicating that the enum field is not set. UNDEFINED_CODE = 0 CLEANUP_FAILED = 150308440 DEPRECATED_RESOURCE_USED = 123400130 DEPRECATED_TYPE_USED = 78090774 DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 101007511 EXPERIMENTAL_TYPE_USED = 183518987 EXTERNAL_API_WARNING = 175546307 FIELD_VALUE_OVERRIDEN = 61233967 INJECTED_KERNELS_DEPRECATED = 148941963 LARGE_DEPLOYMENT_WARNING = 213005222 MISSING_TYPE_DEPENDENCY = 76070007 NEXT_HOP_ADDRESS_NOT_ASSIGNED = 56529543 NEXT_HOP_CANNOT_IP_FORWARD = 114947431 NEXT_HOP_INSTANCE_NOT_FOUND = 195814990 NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 243758146 NEXT_HOP_NOT_RUNNING = 148645809 NOT_CRITICAL_ERROR = 105763924 NO_RESULTS_ON_PAGE = 30036744 PARTIAL_SUCCESS = 39966469 REQUIRED_TOS_AGREEMENT = 3745539 RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 228293185 RESOURCE_NOT_DELETED = 168598460 SCHEMA_VALIDATION_IGNORED = 6810186 SINGLE_INSTANCE_PROPERTY_TEMPLATE = 268305617 UNDECLARED_PROPERTIES = 122077983 UNREACHABLE = 13328052 end end # Represents an Operation resource. # # Google Compute Engine has three Operation resources: # # * [Global](/compute/docs/reference/rest/\\{$api_version}/globalOperations) * [Regional](/compute/docs/reference/rest/\\{$api_version}/regionOperations) * [Zonal](/compute/docs/reference/rest/\\{$api_version}/zoneOperations) # # You can use an operation resource to manage asynchronous API requests. For more information, read Handling API responses. # # Operations can be global, regional or zonal. # - For global operations, use the `globalOperations` resource. # - For regional operations, use the `regionOperations` resource. # - For zonal operations, use the `zonalOperations` resource. # # For more information, read Global, Regional, and Zonal Resources. (== resource_for \\{$api_version}.globalOperations ==) (== resource_for \\{$api_version}.regionOperations ==) (== resource_for \\{$api_version}.zoneOperations ==) # @!attribute [rw] client_operation_id # @return [::String] # [Output Only] The value of `requestId` if you provided it in the request. Not present otherwise. # @!attribute [rw] creation_timestamp # @return [::String] # [Deprecated] This field is deprecated. # @!attribute [rw] description # @return [::String] # [Output Only] A textual description of the operation, which is set when the operation is created. # @!attribute [rw] end_time # @return [::String] # [Output Only] The time that this operation was completed. This value is in RFC3339 text format. # @!attribute [rw] error # @return [::Google::Cloud::Compute::V1::Error] # [Output Only] If errors are generated during processing of the operation, this field will be populated. # @!attribute [rw] http_error_message # @return [::String] # [Output Only] If the operation fails, this field contains the HTTP error message that was returned, such as `NOT FOUND`. # @!attribute [rw] http_error_status_code # @return [::Integer] # [Output Only] If the operation fails, this field contains the HTTP error status code that was returned. For example, a `404` means the resource was not found. # @!attribute [rw] id # @return [::Integer] # [Output Only] The unique identifier for the operation. This identifier is defined by the server. # @!attribute [rw] insert_time # @return [::String] # [Output Only] The time that this operation was requested. This value is in RFC3339 text format. # @!attribute [rw] kind # @return [::String] # [Output Only] Type of the resource. Always `compute#operation` for Operation resources. # @!attribute [rw] name # @return [::String] # [Output Only] Name of the operation. # @!attribute [rw] operation_group_id # @return [::String] # [Output Only] An ID that represents a group of operations, such as when a group of operations results from a `bulkInsert` API request. # @!attribute [rw] operation_type # @return [::String] # [Output Only] The type of operation, such as `insert`, `update`, or `delete`, and so on. # @!attribute [rw] progress # @return [::Integer] # [Output Only] An optional progress indicator that ranges from 0 to 100. There is no requirement that this be linear or support any granularity of operations. This should not be used to guess when the operation will be complete. This number should monotonically increase as the operation progresses. # @!attribute [rw] region # @return [::String] # [Output Only] The URL of the region where the operation resides. Only applicable when performing regional operations. # @!attribute [rw] self_link # @return [::String] # [Output Only] Server-defined URL for the resource. # @!attribute [rw] start_time # @return [::String] # [Output Only] The time that this operation was started by the server. This value is in RFC3339 text format. # @!attribute [rw] status # @return [::Google::Cloud::Compute::V1::Operation::Status] # [Output Only] The status of the operation, which can be one of the following: `PENDING`, `RUNNING`, or `DONE`. # @!attribute [rw] status_message # @return [::String] # [Output Only] An optional textual description of the current status of the operation. # @!attribute [rw] target_id # @return [::Integer] # [Output Only] The unique target ID, which identifies a specific incarnation of the target resource. # @!attribute [rw] target_link # @return [::String] # [Output Only] The URL of the resource that the operation modifies. For operations related to creating a snapshot, this points to the persistent disk that the snapshot was created from. # @!attribute [rw] user # @return [::String] # [Output Only] User who requested the operation, for example: `[email protected]`. # @!attribute [rw] warnings # @return [::Array<::Google::Cloud::Compute::V1::Warnings>] # [Output Only] If warning messages are generated during processing of the operation, this field will be populated. # @!attribute [rw] zone # @return [::String] # [Output Only] The URL of the zone where the operation resides. Only applicable when performing per-zone operations. class Operation include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # [Output Only] The status of the operation, which can be one of the following: `PENDING`, `RUNNING`, or `DONE`. module Status # A value indicating that the enum field is not set. UNDEFINED_STATUS = 0 DONE = 2104194 PENDING = 35394935 RUNNING = 121282975 end end # [Output Only] Informational warning message. # @!attribute [rw] code # @return [::Google::Cloud::Compute::V1::Warning::Code] # [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response. # @!attribute [rw] data # @return [::Array<::Google::Cloud::Compute::V1::Data>] # [Output Only] Metadata about this warning in key: value format. For example: # "data": [ { "key": "scope", "value": "zones/us-east1-d" } # @!attribute [rw] message # @return [::String] # [Output Only] A human-readable description of the warning code. class Warning include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # [Output Only] A warning code, if applicable. For example, Compute Engine returns NO_RESULTS_ON_PAGE if there are no results in the response. module Code # A value indicating that the enum field is not set. UNDEFINED_CODE = 0 CLEANUP_FAILED = 150308440 DEPRECATED_RESOURCE_USED = 123400130 DEPRECATED_TYPE_USED = 78090774 DISK_SIZE_LARGER_THAN_IMAGE_SIZE = 101007511 EXPERIMENTAL_TYPE_USED = 183518987 EXTERNAL_API_WARNING = 175546307 FIELD_VALUE_OVERRIDEN = 61233967 INJECTED_KERNELS_DEPRECATED = 148941963 LARGE_DEPLOYMENT_WARNING = 213005222 MISSING_TYPE_DEPENDENCY = 76070007 NEXT_HOP_ADDRESS_NOT_ASSIGNED = 56529543 NEXT_HOP_CANNOT_IP_FORWARD = 114947431 NEXT_HOP_INSTANCE_NOT_FOUND = 195814990 NEXT_HOP_INSTANCE_NOT_ON_NETWORK = 243758146 NEXT_HOP_NOT_RUNNING = 148645809 NOT_CRITICAL_ERROR = 105763924 NO_RESULTS_ON_PAGE = 30036744 PARTIAL_SUCCESS = 39966469 REQUIRED_TOS_AGREEMENT = 3745539 RESOURCE_IN_USE_BY_OTHER_RESOURCE_WARNING = 228293185 RESOURCE_NOT_DELETED = 168598460 SCHEMA_VALIDATION_IGNORED = 6810186 SINGLE_INSTANCE_PROPERTY_TEMPLATE = 268305617 UNDECLARED_PROPERTIES = 122077983 UNREACHABLE = 13328052 end end # Use global external addresses for GFE-based external HTTP(S) load balancers in Premium Tier. # # Use global internal addresses for reserved peering network range. # # Use regional external addresses for the following resources: # # - External IP addresses for VM instances - Regional external forwarding rules - Cloud NAT external IP addresses - GFE based LBs in Standard Tier - Network LBs in Premium or Standard Tier - Cloud VPN gateways (both Classic and HA) # # Use regional internal IP addresses for subnet IP ranges (primary and secondary). This includes: # # - Internal IP addresses for VM instances - Alias IP ranges of VM instances (/32 only) - Regional internal forwarding rules - Internal TCP/UDP load balancer addresses - Internal HTTP(S) load balancer addresses - Cloud DNS inbound forwarding IP addresses # # For more information, read reserved IP address. # # (== resource_for \\{$api_version}.addresses ==) (== resource_for \\{$api_version}.globalAddresses ==) # @!attribute [rw] address # @return [::String] # The static IP address represented by this resource. # @!attribute [rw] address_type # @return [::Google::Cloud::Compute::V1::Address::AddressType] # The type of address to reserve, either INTERNAL or EXTERNAL. If unspecified, defaults to EXTERNAL. # @!attribute [rw] creation_timestamp # @return [::String] # [Output Only] Creation timestamp in RFC3339 text format. # @!attribute [rw] description # @return [::String] # An optional description of this resource. Provide this field when you create the resource. # @!attribute [rw] id # @return [::String] # [Output Only] The unique identifier for the resource. This identifier is defined by the server. # @!attribute [rw] ip_version # @return [::Google::Cloud::Compute::V1::Address::IpVersion] # The IP version that will be used by this address. Valid options are IPV4 or IPV6. This can only be specified for a global address. # @!attribute [rw] kind # @return [::String] # [Output Only] Type of the resource. Always compute#address for addresses. # @!attribute [rw] name # @return [::String] # Name of the resource. Provided by the client when the resource is created. The name must be 1-63 characters long, and comply with RFC1035. Specifically, the name must be 1-63 characters long and match the regular expression `[a-z]([-a-z0-9]*[a-z0-9])?`. The first character must be a lowercase letter, and all following characters (except for the last character) must be a dash, lowercase letter, or digit. The last character must be a lowercase letter or digit. # @!attribute [rw] network # @return [::String] # The URL of the network in which to reserve the address. This field can only be used with INTERNAL type with the VPC_PEERING purpose. # @!attribute [rw] network_tier # @return [::Google::Cloud::Compute::V1::Address::NetworkTier] # This signifies the networking tier used for configuring this address and can only take the following values: PREMIUM or STANDARD. Global forwarding rules can only be Premium Tier. Regional forwarding rules can be either Premium or Standard Tier. Standard Tier addresses applied to regional forwarding rules can be used with any external load balancer. Regional forwarding rules in Premium Tier can only be used with a network load balancer. # # If this field is not specified, it is assumed to be PREMIUM. # @!attribute [rw] prefix_length # @return [::Integer] # The prefix length if the resource reprensents an IP range. # @!attribute [rw] purpose # @return [::Google::Cloud::Compute::V1::Address::Purpose] # The purpose of this resource, which can be one of the following values: # - `GCE_ENDPOINT` for addresses that are used by VM instances, alias IP ranges, internal load balancers, and similar resources. # - `DNS_RESOLVER` for a DNS resolver address in a subnetwork # - `VPC_PEERING` for addresses that are reserved for VPC peer networks. # - `NAT_AUTO` for addresses that are external IP addresses automatically reserved for Cloud NAT. # - `IPSEC_INTERCONNECT` for addresses created from a private IP range that are reserved for a VLAN attachment in an IPsec encrypted Interconnect configuration. These addresses are regional resources. # @!attribute [rw] region # @return [::String] # [Output Only] The URL of the region where the regional address resides. This field is not applicable to global addresses. You must specify this field as part of the HTTP request URL. # @!attribute [rw] self_link # @return [::String] # [Output Only] Server-defined URL for the resource. # @!attribute [rw] status # @return [::Google::Cloud::Compute::V1::Address::Status] # [Output Only] The status of the address, which can be one of RESERVING, RESERVED, or IN_USE. An address that is RESERVING is currently in the process of being reserved. A RESERVED address is currently reserved and available to use. An IN_USE address is currently being used by another resource and is not available. # @!attribute [rw] subnetwork # @return [::String] # The URL of the subnetwork in which to reserve the address. If an IP address is specified, it must be within the subnetwork's IP range. This field can only be used with INTERNAL type with a GCE_ENDPOINT or DNS_RESOLVER purpose. # @!attribute [rw] users # @return [::Array<::String>] # [Output Only] The URLs of the resources that are using this address. class Address include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # The type of address to reserve, either INTERNAL or EXTERNAL. If unspecified, defaults to EXTERNAL. module AddressType # A value indicating that the enum field is not set. UNDEFINED_ADDRESS_TYPE = 0 EXTERNAL = 35607499 INTERNAL = 10860221 UNSPECIFIED_TYPE = 53933922 end # The IP version that will be used by this address. Valid options are IPV4 or IPV6. This can only be specified for a global address. module IpVersion # A value indicating that the enum field is not set. UNDEFINED_IP_VERSION = 0 IPV4 = 2254341 IPV6 = 2254343 UNSPECIFIED_VERSION = 21850000 end # This signifies the networking tier used for configuring this address and can only take the following values: PREMIUM or STANDARD. Global forwarding rules can only be Premium Tier. Regional forwarding rules can be either Premium or Standard Tier. Standard Tier addresses applied to regional forwarding rules can be used with any external load balancer. Regional forwarding rules in Premium Tier can only be used with a network load balancer. # # If this field is not specified, it is assumed to be PREMIUM. module NetworkTier # A value indicating that the enum field is not set. UNDEFINED_NETWORK_TIER = 0 PREMIUM = 131095095 STANDARD = 216207037 end # The purpose of this resource, which can be one of the following values: # - `GCE_ENDPOINT` for addresses that are used by VM instances, alias IP ranges, internal load balancers, and similar resources. # - `DNS_RESOLVER` for a DNS resolver address in a subnetwork # - `VPC_PEERING` for addresses that are reserved for VPC peer networks. # - `NAT_AUTO` for addresses that are external IP addresses automatically reserved for Cloud NAT. # - `IPSEC_INTERCONNECT` for addresses created from a private IP range that are reserved for a VLAN attachment in an IPsec encrypted Interconnect configuration. These addresses are regional resources. module Purpose # A value indicating that the enum field is not set. UNDEFINED_PURPOSE = 0 DNS_RESOLVER = 207679100 GCE_ENDPOINT = 230515243 NAT_AUTO = 163666477 SHARED_LOADBALANCER_VIP = 26012116 VPC_PEERING = 132364714 end # [Output Only] The status of the address, which can be one of RESERVING, RESERVED, or IN_USE. An address that is RESERVING is currently in the process of being reserved. A RESERVED address is currently reserved and available to use. An IN_USE address is currently being used by another resource and is not available. module Status # A value indicating that the enum field is not set. UNDEFINED_STATUS = 0 IN_USE = 17393485 RESERVED = 163805992 RESERVING = 246151769 end end # @!attribute [rw] addresses # @return [::Array<::Google::Cloud::Compute::V1::Address>] # [Output Only] A list of addresses contained in this scope. # @!attribute [rw] warning # @return [::Google::Cloud::Compute::V1::Warning] # [Output Only] Informational warning which replaces the list of addresses when the list is empty. class AddressesScopedList include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # @!attribute [rw] id # @return [::String] # [Output Only] Unique identifier for the resource; defined by the server. # @!attribute [rw] items # @return [::Google::Protobuf::Map{::String => ::Google::Cloud::Compute::V1::AddressesScopedList}] # A list of AddressesScopedList resources. # @!attribute [rw] kind # @return [::String] # [Output Only] Type of resource. Always compute#addressAggregatedList for aggregated lists of addresses. # @!attribute [rw] next_page_token # @return [::String] # [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results. # @!attribute [rw] self_link # @return [::String] # [Output Only] Server-defined URL for this resource. # @!attribute [rw] unreachables # @return [::Array<::String>] # [Output Only] Unreachable resources. # @!attribute [rw] warning # @return [::Google::Cloud::Compute::V1::Warning] # [Output Only] Informational warning message. class AddressAggregatedList include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # @!attribute [rw] key # @return [::String] # @!attribute [rw] value # @return [::Google::Cloud::Compute::V1::AddressesScopedList] class ItemsEntry include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end end # Contains a list of addresses. # @!attribute [rw] id # @return [::String] # [Output Only] Unique identifier for the resource; defined by the server. # @!attribute [rw] items # @return [::Array<::Google::Cloud::Compute::V1::Address>] # A list of Address resources. # @!attribute [rw] kind # @return [::String] # [Output Only] Type of resource. Always compute#addressList for lists of addresses. # @!attribute [rw] next_page_token # @return [::String] # [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results. # @!attribute [rw] self_link # @return [::String] # [Output Only] Server-defined URL for this resource. # @!attribute [rw] warning # @return [::Google::Cloud::Compute::V1::Warning] # [Output Only] Informational warning message. class AddressList include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for Addresses.AggregatedList. See the method description for details. # @!attribute [rw] filter # @return [::String] # A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. # # For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. # # You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. # # To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` # @!attribute [rw] include_all_scopes # @return [::Boolean] # Indicates whether every visible scope for each scope type (zone, region, global) should be included in the response. For new resource types added after this field, the flag has no effect as new resource types will always include every visible scope for each scope type in response. For resource types which predate this field, if this flag is omitted or false, only scopes of the scope types where the resource type is expected to be found will be included. # @!attribute [rw] max_results # @return [::Integer] # The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) # @!attribute [rw] order_by # @return [::String] # Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. # # You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. # # Currently, only sorting by `name` or `creationTimestamp desc` is supported. # @!attribute [rw] page_token # @return [::String] # Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] return_partial_success # @return [::Boolean] # Opt-in for partial success behavior which provides partial results in case of failure. The default value is false and the logic is the same as today. class AggregatedListAddressesRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for Addresses.Delete. See the method description for details. # @!attribute [rw] address # @return [::String] # Name of the address resource to delete. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # Name of the region for this request. # @!attribute [rw] request_id # @return [::String] # An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. # # For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. # # The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). class DeleteAddressRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for Addresses.Get. See the method description for details. # @!attribute [rw] address # @return [::String] # Name of the address resource to return. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # Name of the region for this request. class GetAddressRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for Addresses.Insert. See the method description for details. # @!attribute [rw] address_resource # @return [::Google::Cloud::Compute::V1::Address] # The body resource for this request # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # Name of the region for this request. # @!attribute [rw] request_id # @return [::String] # An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. # # For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. # # The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). class InsertAddressRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for Addresses.List. See the method description for details. # @!attribute [rw] filter # @return [::String] # A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. # # For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. # # You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. # # To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` # @!attribute [rw] max_results # @return [::Integer] # The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) # @!attribute [rw] order_by # @return [::String] # Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. # # You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. # # Currently, only sorting by `name` or `creationTimestamp desc` is supported. # @!attribute [rw] page_token # @return [::String] # Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # Name of the region for this request. # @!attribute [rw] return_partial_success # @return [::Boolean] # Opt-in for partial success behavior which provides partial results in case of failure. The default value is false and the logic is the same as today. class ListAddressesRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # Contains a list of Operation resources. # @!attribute [rw] id # @return [::String] # [Output Only] The unique identifier for the resource. This identifier is defined by the server. # @!attribute [rw] items # @return [::Array<::Google::Cloud::Compute::V1::Operation>] # [Output Only] A list of Operation resources. # @!attribute [rw] kind # @return [::String] # [Output Only] Type of resource. Always `compute#operations` for Operations resource. # @!attribute [rw] next_page_token # @return [::String] # [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than `maxResults`, use the `nextPageToken` as a value for the query parameter `pageToken` in the next list request. Subsequent list requests will have their own `nextPageToken` to continue paging through the results. # @!attribute [rw] self_link # @return [::String] # [Output Only] Server-defined URL for this resource. # @!attribute [rw] warning # @return [::Google::Cloud::Compute::V1::Warning] # [Output Only] Informational warning message. class OperationList include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for RegionOperations.Delete. See the method description for details. # @!attribute [rw] operation # @return [::String] # Name of the Operations resource to delete. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # Name of the region for this request. class DeleteRegionOperationRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A response message for RegionOperations.Delete. See the method description for details. class DeleteRegionOperationResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for RegionOperations.Get. See the method description for details. # @!attribute [rw] operation # @return [::String] # Name of the Operations resource to return. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # Name of the region for this request. class GetRegionOperationRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for RegionOperations.List. See the method description for details. # @!attribute [rw] filter # @return [::String] # A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. # # For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. # # You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. # # To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` # @!attribute [rw] max_results # @return [::Integer] # The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) # @!attribute [rw] order_by # @return [::String] # Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. # # You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. # # Currently, only sorting by `name` or `creationTimestamp desc` is supported. # @!attribute [rw] page_token # @return [::String] # Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # Name of the region for this request. # @!attribute [rw] return_partial_success # @return [::Boolean] # Opt-in for partial success behavior which provides partial results in case of failure. The default value is false and the logic is the same as today. class ListRegionOperationsRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for RegionOperations.Wait. See the method description for details. # @!attribute [rw] operation # @return [::String] # Name of the Operations resource to return. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # Name of the region for this request. class WaitRegionOperationRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for RegionInstanceGroupManagers.Resize. See the method description for details. # @!attribute [rw] instance_group_manager # @return [::String] # Name of the managed instance group. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # Name of the region scoping this request. # @!attribute [rw] request_id # @return [::String] # An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. # # For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. # # The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). # @!attribute [rw] size # @return [::Integer] # Number of instances that should exist in this instance group manager. class ResizeRegionInstanceGroupManagerRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # @!attribute [rw] dest_range # @return [::String] # The destination range of the route. # @!attribute [rw] imported # @return [::Boolean] # True if the peering route has been imported from a peer. The actual import happens if the field networkPeering.importCustomRoutes is true for this network, and networkPeering.exportCustomRoutes is true for the peer network, and the import does not result in a route conflict. # @!attribute [rw] next_hop_region # @return [::String] # The region of peering route next hop, only applies to dynamic routes. # @!attribute [rw] priority # @return [::Integer] # The priority of the peering route. # @!attribute [rw] type # @return [::Google::Cloud::Compute::V1::ExchangedPeeringRoute::Type] # The type of the peering route. class ExchangedPeeringRoute include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # The type of the peering route. module Type # A value indicating that the enum field is not set. UNDEFINED_TYPE = 0 DYNAMIC_PEERING_ROUTE = 201359402 STATIC_PEERING_ROUTE = 204972089 SUBNET_PEERING_ROUTE = 197347048 end end # @!attribute [rw] id # @return [::String] # [Output Only] Unique identifier for the resource; defined by the server. # @!attribute [rw] items # @return [::Array<::Google::Cloud::Compute::V1::ExchangedPeeringRoute>] # A list of ExchangedPeeringRoute resources. # @!attribute [rw] kind # @return [::String] # [Output Only] Type of resource. Always compute#exchangedPeeringRoutesList for exchanged peering routes lists. # @!attribute [rw] next_page_token # @return [::String] # [Output Only] This token allows you to get the next page of results for list requests. If the number of results is larger than maxResults, use the nextPageToken as a value for the query parameter pageToken in the next list request. Subsequent list requests will have their own nextPageToken to continue paging through the results. # @!attribute [rw] self_link # @return [::String] # [Output Only] Server-defined URL for this resource. # @!attribute [rw] warning # @return [::Google::Cloud::Compute::V1::Warning] # [Output Only] Informational warning message. class ExchangedPeeringRoutesList include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for Networks.ListPeeringRoutes. See the method description for details. # @!attribute [rw] direction # @return [::Google::Cloud::Compute::V1::ListPeeringRoutesNetworksRequest::Direction] # The direction of the exchanged routes. # @!attribute [rw] filter # @return [::String] # A filter expression that filters resources listed in the response. The expression must specify the field name, a comparison operator, and the value that you want to use for filtering. The value must be a string, a number, or a boolean. The comparison operator must be either `=`, `!=`, `>`, or `<`. # # For example, if you are filtering Compute Engine instances, you can exclude instances named `example-instance` by specifying `name != example-instance`. # # You can also filter nested fields. For example, you could specify `scheduling.automaticRestart = false` to include instances only if they are not scheduled for automatic restarts. You can use filtering on nested fields to filter based on resource labels. # # To filter on multiple expressions, provide each separate expression within parentheses. For example: ``` (scheduling.automaticRestart = true) (cpuPlatform = "Intel Skylake") ``` By default, each expression is an `AND` expression. However, you can include `AND` and `OR` expressions explicitly. For example: ``` (cpuPlatform = "Intel Skylake") OR (cpuPlatform = "Intel Broadwell") AND (scheduling.automaticRestart = true) ``` # @!attribute [rw] max_results # @return [::Integer] # The maximum number of results per page that should be returned. If the number of available results is larger than `maxResults`, Compute Engine returns a `nextPageToken` that can be used to get the next page of results in subsequent list requests. Acceptable values are `0` to `500`, inclusive. (Default: `500`) # @!attribute [rw] network # @return [::String] # Name of the network for this request. # @!attribute [rw] order_by # @return [::String] # Sorts list results by a certain order. By default, results are returned in alphanumerical order based on the resource name. # # You can also sort results in descending order based on the creation timestamp using `orderBy="creationTimestamp desc"`. This sorts results based on the `creationTimestamp` field in reverse chronological order (newest result first). Use this to sort resources like operations so that the newest operation is returned first. # # Currently, only sorting by `name` or `creationTimestamp desc` is supported. # @!attribute [rw] page_token # @return [::String] # Specifies a page token to use. Set `pageToken` to the `nextPageToken` returned by a previous list request to get the next page of results. # @!attribute [rw] peering_name # @return [::String] # The response will show routes exchanged over the given peering connection. # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] region # @return [::String] # The region of the request. The response will include all subnet routes, static routes and dynamic routes in the region. # @!attribute [rw] return_partial_success # @return [::Boolean] # Opt-in for partial success behavior which provides partial results in case of failure. The default value is false and the logic is the same as today. class ListPeeringRoutesNetworksRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods # The direction of the exchanged routes. module Direction # A value indicating that the enum field is not set. UNDEFINED_DIRECTION = 0 INCOMING = 70117414 OUTGOING = 39002988 end end # @!attribute [rw] name # @return [::String] # Name of the peering, which should conform to RFC1035. class NetworksRemovePeeringRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for Networks.RemovePeering. See the method description for details. # @!attribute [rw] network # @return [::String] # Name of the network resource to remove peering from. # @!attribute [rw] networks_remove_peering_request_resource # @return [::Google::Cloud::Compute::V1::NetworksRemovePeeringRequest] # The body resource for this request # @!attribute [rw] project # @return [::String] # Project ID for this request. # @!attribute [rw] request_id # @return [::String] # An optional request ID to identify requests. Specify a unique request ID so that if you must retry your request, the server will know to ignore the request if it has already been completed. # # For example, consider a situation where you make an initial request and the request times out. If you make the request again with the same request ID, the server can check if original operation with the same request ID was received, and if so, will ignore the second request. This prevents clients from accidentally creating duplicate commitments. # # The request ID must be a valid UUID with the exception that zero UUID is not supported (00000000-0000-0000-0000-000000000000). class RemovePeeringNetworkRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for GlobalOperations.Delete. See the method description for details. # @!attribute [rw] operation # @return [::String] # Name of the Operations resource to delete. # @!attribute [rw] project # @return [::String] # Project ID for this request. class DeleteGlobalOperationRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A response message for GlobalOperations.Delete. See the method description for details. class DeleteGlobalOperationResponse include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end # A request message for GlobalOperations.Get. See the method description for details. # @!attribute [rw] operation # @return [::String] # Name of the Operations resource to return. # @!attribute [rw] project # @return [::String] # Project ID for this request. class GetGlobalOperationRequest include ::Google::Protobuf::MessageExts extend ::Google::Protobuf::MessageExts::ClassMethods end end end end end
57.327122
488
0.650999
e8b27eb8583c951d33099dc095a51708201e78e0
779
ActiveAdmin.register ExpertDetail do actions :all, except: [:new, :destroy] permit_params :category_ids form do |f| inputs 'Details' do input :category_ids, label: 'Category', as: :select, collection: Category.where(profession_id: f.object.profession_id).all.map{|c| [c.name, c.id]} end actions end index do column :name do |e| e.user.name end column :email do |e| e.user.email end column :profession do |e| e.profession.name end column :categories do |e| Category.where(id: e.category_ids).map(&:name).join(', ') end column :created_at column :updated_at actions end controller do def scoped_collection super.includes(:user, :profession) end end end
20.5
101
0.63543
18115c956ea778d059cda0cb568eceafb9ae7fc9
932
=begin This class represnets Turn Model. =end class Turn include CustoraQueue include Common attr_accessor :game =begin This function is used to initialize turn. =end def initialize(game) @game = game next_turn end =begin This function is used to switch to next turm. =end def next_turn game_id = game.instance_variable_get("@id") json_info = RestClient.get("#{HOST}/games/#{game_id}/next_turn").body object_generator(json_info, self) end =begin This method is used assign jobs to machines. =end def assign_jobs(machine) jobs = instance_variable_get("@jobs") job_ids = jobs.map{|job| job["id"]} machine_id = machine.instance_variable_get("@id") game_id = instance_variable_get("@game").instance_variable_get("@id") RestClient.post( "#{HOST}/games/#{game_id}/machines/#{machine_id}/job_assignments", job_ids: JSON.dump(job_ids) ).body end end
21.674419
73
0.699571
1a5af10e072f0d98f43d3a3a38173d62597c3554
144
class AddSubmissionIdToTestResults < ActiveRecord::Migration[4.2] def change add_column :test_results, :submission_id, :integer end end
24
65
0.784722
1d09c720bf7a47df86675f9c3b2dc695ec186bdf
3,451
# frozen_string_literal: true require 'fast_spec_helper' require 'rubocop' require 'rubocop/rspec/support' require_relative '../../../../rubocop/cop/gitlab/module_with_instance_variables' RSpec.describe RuboCop::Cop::Gitlab::ModuleWithInstanceVariables do include CopHelper subject(:cop) { described_class.new } shared_examples('registering offense') do |options| let(:offending_lines) { options[:offending_lines] } it 'registers an offense when instance variable is used in a module' do inspect_source(source) aggregate_failures do expect(cop.offenses.size).to eq(offending_lines.size) expect(cop.offenses.map(&:line)).to eq(offending_lines) end end end shared_examples('not registering offense') do it 'does not register offenses' do inspect_source(source) expect(cop.offenses).to be_empty end end context 'when source is a regular module' do it_behaves_like 'registering offense', offending_lines: [3] do let(:source) do <<~RUBY module M def f @f = true end end RUBY end end end context 'when source is a nested module' do it_behaves_like 'registering offense', offending_lines: [4] do let(:source) do <<~RUBY module N module M def f @f = true end end end RUBY end end end context 'when source is a nested module with multiple offenses' do it_behaves_like 'registering offense', offending_lines: [4, 12] do let(:source) do <<~RUBY module N module M def f @f = true end def g true end def h @h = true end end end RUBY end end end context 'when source is using simple or ivar assignment' do it_behaves_like 'not registering offense' do let(:source) do <<~RUBY module M def f @f ||= true end end RUBY end end end context 'when source is using simple ivar' do it_behaves_like 'not registering offense' do let(:source) do <<~RUBY module M def f? @f end end RUBY end end end context 'when source is defining initialize' do it_behaves_like 'not registering offense' do let(:source) do <<~RUBY module M def initialize @a = 1 @b = 2 end end RUBY end end end context 'when source is using simple or ivar assignment with other ivar' do it_behaves_like 'registering offense', offending_lines: [3] do let(:source) do <<~RUBY module M def f @f ||= g(@g) end end RUBY end end end context 'when source is using or ivar assignment with something else' do it_behaves_like 'registering offense', offending_lines: [3, 4] do let(:source) do <<~RUBY module M def f @f ||= true @f.to_s end end RUBY end end end end
21.56875
80
0.53202
bb87f69469aaa76bf9d7c71e9d0850d89dbbbc06
21
class Invitation end
7
16
0.857143
bbf7232c5839b8587a9ca897c595b4ddcfa6b313
1,257
# frozen_string_literal: true require "rails_helper" RSpec.describe Types::Resource do describe "fields" do subject { described_class } it { is_expected.to have_field(:id).of_type(String) } it { is_expected.to have_field(:url).of_type(String) } it { is_expected.to have_field(:label).of_type(String) } it { is_expected.to have_field(:viewingHint).of_type(String) } it { is_expected.to have_field(:members) } it { is_expected.to have_field(:orangelightId).of_type(String) } it { is_expected.to have_field(:sourceMetadataIdentifier) } it { is_expected.to have_field(:thumbnail).of_type("Types::Thumbnail") } end describe ".resolve_type" do it "returns a ScannedResourceType for a ScannedResource" do expect(described_class.resolve_type(ScannedResource.new, {})).to eq Types::ScannedResourceType end it "returns a FileSetType for a FileSet" do expect(described_class.resolve_type(FileSet.new, {})).to eq Types::FileSetType end end describe ".helper" do it "defines an overridden image_path to just return the given parameter back" do type = Types::ScannedResourceType.new(ScannedResource.new, {}) expect(type.helper.image_path("test")).to eq "test" end end end
38.090909
100
0.722355
5da35a972eab4d407362744c30f974ea269f52fa
386
module ApplicationMeritsTask class StatementOfCase < ApplicationRecord belongs_to :legal_aid_application belongs_to :provider_uploader, class_name: 'Provider', optional: true def original_attachments legal_aid_application.attachments.statement_of_case end def pdf_attachments legal_aid_application.attachments.statement_of_case_pdf end end end
25.733333
73
0.795337
0823bf11a39b0d2bb6966a2bf94637a217601d16
559
module SupportInterface class ActiveProviderUsersExport def data_for_export(*) active_provider_users = ProviderUser.includes(:providers).where.not(last_signed_in_at: nil) active_provider_users.find_each(batch_size: 100).map do |provider_user| { provider_full_name: provider_user.full_name, provider_email_address: provider_user.email_address, providers: provider_user.providers.map(&:name).join(', '), last_signed_in_at: provider_user.last_signed_in_at, } end end end end
32.882353
97
0.711986