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
33176dd5eff11fcf05d4ac60260d4dcfc77159b9
4,760
require "pathname" require "vagrant/action/builder" module VagrantPlugins module ManagedServers module Action # Include the built-in modules so we can use them as top-level things. include Vagrant::Action::Builtin # This action is called to establish linkage between vagrant and the managed server def self.action_up Vagrant::Action::Builder.new.tap do |b| if Vagrant::VERSION < '1.5.0' b.use HandleBoxUrl else b.use HandleBox end b.use ConfigValidate b.use WarnNetworks b.use Call, IsLinked do |env, b2| if env[:result] b2.use MessageAlreadyLinked next end b2.use LinkServer end =begin b.use HandleBoxUrl b.use ConfigValidate b.use Call, IsReachable do |env, b2| if env[:result] b2.use !MessageNotReachable next end b2.use Provision b2.use SyncFolders b2.use WarnNetworks b2.use LinkServer end =end end end # This action is called to "unlink" vagrant from the managed server def self.action_destroy Vagrant::Action::Builder.new.tap do |b| b.use ConfigValidate b.use Call, IsLinked do |env, b2| if !env[:result] b2.use MessageNotLinked next end b2.use UnlinkServer end end end # This action is called when `vagrant provision` is called. def self.action_provision Vagrant::Action::Builder.new.tap do |b| b.use ConfigValidate b.use WarnNetworks b.use Call, IsLinked do |env, b2| if !env[:result] b2.use MessageNotLinked next end b2.use Call, IsReachable do |env, b3| if !env[:result] b3.use MessageNotReachable next end b3.use Provision b3.use SyncFolders end end end end # This action is called to read the state of the machine. The # resulting state is expected to be put into the `:machine_state_id` # key. def self.action_read_state Vagrant::Action::Builder.new.tap do |b| b.use ConfigValidate b.use ReadState end end # This action is called to SSH into the machine. def self.action_ssh Vagrant::Action::Builder.new.tap do |b| b.use ConfigValidate b.use WarnNetworks b.use Call, IsLinked do |env, b2| if !env[:result] b2.use MessageNotLinked next end b2.use Call, IsReachable do |env, b3| if !env[:result] b3.use MessageNotReachable next end b3.use SSHExec end end end end def self.action_ssh_run Vagrant::Action::Builder.new.tap do |b| b.use ConfigValidate b.use WarnNetworks b.use Call, IsLinked do |env, b2| if !env[:result] b2.use MessageNotLinked next end b2.use Call, IsReachable do |env, b3| if !env[:result] b3.use MessageNotReachable next end b3.use SSHRun end end end end def self.action_reload Vagrant::Action::Builder.new.tap do |b| b.use Call, IsLinked do |env, b2| if !env[:result] b2.use MessageNotLinked next end b2.use RebootServer end end end # The autoload farm action_root = Pathname.new(File.expand_path("../action", __FILE__)) autoload :IsLinked, action_root.join("is_linked") autoload :IsReachable, action_root.join("is_reachable") autoload :MessageNotReachable, action_root.join("message_not_reachable") autoload :MessageNotLinked, action_root.join("message_not_linked") autoload :MessageAlreadyLinked, action_root.join("message_already_linked") autoload :ReadState, action_root.join("read_state") autoload :SyncFolders, action_root.join("sync_folders") autoload :WarnNetworks, action_root.join("warn_networks") autoload :LinkServer, action_root.join("link_server") autoload :UnlinkServer, action_root.join("unlink_server") autoload :RebootServer, action_root.join("reboot_server") end end end
28
89
0.55042
614085ceea94bdce7c8b4f5939a77125b5d1b56e
669
## TODO # Attributes # attendance # Leaders class SportsApi::Model::Event SCORE_STATES = [ PREGAME = 'pregame', INPROGRESS = 'in-progress', FINAL = 'final' ] attr_accessor :date, :league, :gameid, :line, :competitors, :status, :score, :headline, :channel, :location, :over_under, :neutral, :notes, :series_notes def score @score ||= competitors.map { |c| c.score }.join(' - ') end def gameid=(id) @gameid = id.to_i end end
18.583333
58
0.437967
ffd4492d0a3146a840070e7040a4834614c68afa
173
# frozen_string_literal: true class AddResourceIdToAnnouncement < ActiveRecord::Migration[5.0] def change add_column :announcements, :resource_id, :integer end end
21.625
64
0.786127
384380e4bf0a2e2d1dee2bc0da85c2004cd085ca
527
require 'zenprofile' ## # A ProfiledProcessor that uses Ryan Davis' ZenProfiler. # # The ZenProfiler profiler requires Ruby 1.8.3 or better and RubyInline. # ZenProfiler can be found at http://rubyforge.org/frs/?group_id=712 class ActionProfiler::ZenProfilerProcessor < ActionProfiler::ProfiledProcessor def start_profile # :nodoc: ZenProfiler.start_profile end def stop_profile # :nodoc: ZenProfiler.stop_profile end def print_profile(io = STDERR) # :nodoc: ZenProfiler.print_profile io end end
21.08
78
0.757116
61d485d03f59287ea945fbe729f6f7ab312aa241
128
CelluloidBenchmark::Session.define do benchmark :home_page, 1 get "https://github.com/scottwillson/celluloid-benchmark" end
25.6
59
0.796875
03f6cd1a96f94f199f077dcc6dab9f7f96b2fcd8
39
require 'honeybadger' raise 'badgers!'
13
21
0.769231
e2e5c061b70def035d80392badacae3d3f3429bc
7,512
module Capybara module Node module Finders ## # # Find an {Capybara::Node::Element} based on the given arguments. +find+ will raise an error if the element # is not found. # # If the driver is capable of executing JavaScript, +find+ will wait for a set amount of time # and continuously retry finding the element until either the element is found or the time # expires. The length of time +find+ will wait is controlled through {Capybara.default_max_wait_time} # and defaults to 2 seconds. # # +find+ takes the same options as +all+. # # page.find('#foo').find('.bar') # page.find(:xpath, '//div[contains(., "bar")]') # page.find('li', :text => 'Quox').click_link('Delete') # # @param (see Capybara::Node::Finders#all) # @option options [Boolean] match The matching strategy to use. # @option options [false, Numeric] wait How long to wait for the element to appear. # # @return [Capybara::Node::Element] The found element # @raise [Capybara::ElementNotFound] If the element can't be found before time expires # def find(*args) query = Capybara::Query.new(*args) synchronize(query.wait) do if query.match == :smart or query.match == :prefer_exact result = query.resolve_for(self, true) result = query.resolve_for(self, false) if result.size == 0 && !query.exact? else result = query.resolve_for(self) end if query.match == :one or query.match == :smart and result.size > 1 raise Capybara::Ambiguous.new("Ambiguous match, found #{result.size} elements matching #{query.description}") end if result.size == 0 raise Capybara::ElementNotFound.new("Unable to find #{query.description}") end result.first end.tap(&:allow_reload!) end ## # # Find a form field on the page. The field can be found by its name, id or label text. # # @param [String] locator Which field to find # @return [Capybara::Node::Element] The found element # def find_field(locator, options={}) find(:field, locator, options) end alias_method :field_labeled, :find_field ## # # Find a link on the page. The link can be found by its id or text. # # @param [String] locator Which link to find # @return [Capybara::Node::Element] The found element # def find_link(locator, options={}) find(:link, locator, options) end ## # # Find a button on the page. The button can be found by its id, name or value. # # @param [String] locator Which button to find # @return [Capybara::Node::Element] The found element # def find_button(locator, options={}) find(:button, locator, options) end ## # # Find a element on the page, given its id. # # @param [String] id Which element to find # @return [Capybara::Node::Element] The found element # def find_by_id(id, options={}) find(:id, id, options) end ## # # Find all elements on the page matching the given selector # and options. # # Both XPath and CSS expressions are supported, but Capybara # does not try to automatically distinguish between them. The # following statements are equivalent: # # page.all(:css, 'a#person_123') # page.all(:xpath, '//a[@id="person_123"]') # # # If the type of selector is left out, Capybara uses # {Capybara.default_selector}. It's set to :css by default. # # page.all("a#person_123") # # Capybara.default_selector = :xpath # page.all('//a[@id="person_123"]') # # The set of found elements can further be restricted by specifying # options. It's possible to select elements by their text or visibility: # # page.all('a', :text => 'Home') # page.all('#menu li', :visible => true) # # By default if no elements are found, an empty array is returned; # however, expectations can be set on the number of elements to be # found using: # # page.assert_selector('p#foo', :count => 4) # page.assert_selector('p#foo', :maximum => 10) # page.assert_selector('p#foo', :minimum => 1) # page.assert_selector('p#foo', :between => 1..10) # # See {Capybara::Helpers#matches_count?} for additional information about # count matching. # # @overload all([kind], locator, options) # @param [:css, :xpath] kind The type of selector # @param [String] locator The selector # @option options [String, Regexp] text Only find elements which contain this text or match this regexp # @option options [Boolean, Symbol] visible Only find elements with the specified visibility: # * true - only finds visible elements. # * false - finds invisible _and_ visible elements. # * :all - same as false; finds visible and invisible elements. # * :hidden - only finds invisible elements. # * :visible - same as true; only finds visible elements. # @option options [Integer] count Exact number of matches that are expected to be found # @option options [Integer] maximum Maximum number of matches that are expected to be found # @option options [Integer] minimum Minimum number of matches that are expected to be found # @option options [Range] between Number of matches found must be within the given range # @option options [Boolean] exact Control whether `is` expressions in the given XPath match exactly or partially # @return [Capybara::Result] A collection of found elements # def all(*args) query = Capybara::Query.new(*args) synchronize(query.wait) do result = query.resolve_for(self) raise Capybara::ExpectationNotMet, result.failure_message unless result.matches_count? result end end alias_method :find_all, :all ## # # Find the first element on the page matching the given selector # and options, or nil if no element matches. # # @overload first([kind], locator, options) # @param [:css, :xpath] kind The type of selector # @param [String] locator The selector # @param [Hash] options Additional options; see {#all} # @return [Capybara::Node::Element] The found element or nil # def first(*args) if Capybara.wait_on_first_by_default options = if args.last.is_a?(Hash) then args.pop.dup else {} end args.push({minimum: 1}.merge(options)) end all(*args).first rescue Capybara::ExpectationNotMet nil end end end end
41.502762
131
0.567226
3909d725f7e6c7e27effcbddb2ec4b414bd1af6b
2,446
require "jekyll" require "uri" module Jekyll module GitHubMetadata class SiteGitHubMunger extend Forwardable def_delegators :"Jekyll::GitHubMetadata", :site private def_delegator :"Jekyll::GitHubMetadata", :repository def initialize(site) Jekyll::GitHubMetadata.site = site end def munge! Jekyll::GitHubMetadata.log :debug, "Initializing..." # This is the good stuff. site.config["github"] = github_namespace add_title_and_description_fallbacks! add_url_and_baseurl_fallbacks! if should_add_url_fallbacks? end private def github_namespace case site.config["github"] when nil drop when Hash Jekyll::Utils.deep_merge_hashes(drop, site.config["github"]) else site.config["github"] end end def drop @drop ||= MetadataDrop.new(GitHubMetadata.site) end # Set `site.url` and `site.baseurl` if unset. def add_url_and_baseurl_fallbacks! site.config["url"] ||= Value.new("url", proc { |_c, r| r.url_without_path }) return unless should_set_baseurl? site.config["baseurl"] = Value.new("baseurl", proc { |_c, r| r.baseurl }) end def add_title_and_description_fallbacks! if should_warn_about_site_name? msg = "site.name is set in _config.yml, but many plugins and themes expect " msg << "site.title to be used instead. To avoid potential inconsistency, " msg << "Jekyll GitHub Metadata will not set site.title to the repository's name." Jekyll::GitHubMetadata.log :warn, msg else site.config["title"] ||= Value.new("title", proc { |_c, r| r.name }) end site.config["description"] ||= Value.new("description", proc { |_c, r| r.tagline }) end # Set the baseurl only if it is `nil` or `/` # Baseurls should never be "/". See http://bit.ly/2s1Srid def should_set_baseurl? site.config["baseurl"].nil? || site.config["baseurl"] == "/" end def should_add_url_fallbacks? Jekyll.env == "production" || Pages.page_build? end def should_warn_about_site_name? site.config["name"] && !site.config["title"] end end end end Jekyll::Hooks.register :site, :after_init do |site| Jekyll::GitHubMetadata::SiteGitHubMunger.new(site).munge! end
29.829268
91
0.624693
266ca47f5ce735bd6af7425f6534391111087a47
3,443
# frozen_string_literal: true require "action_policy/testing" module ActionPolicy # Provides assertions for policies usage module TestHelper class WithScopeTarget attr_reader :scopes def initialize(scopes) @scopes = scopes end def with_target if scopes.size > 1 raise "Too many matching scopings (#{scopes.size}), " \ "you can run `.with_target` only when there is the only one match" end yield scopes.first.target end end # Asserts that the given policy was used to authorize the given target. # # def test_authorize # assert_authorized_to(:show?, user, with: UserPolicy) do # get :show, id: user.id # end # end # # You can omit the policy (then it would be inferred from the target): # # assert_authorized_to(:show?, user) do # get :show, id: user.id # end # def assert_authorized_to(rule, target, with: nil) raise ArgumentError, "Block is required" unless block_given? policy = with || ::ActionPolicy.lookup(target) begin ActionPolicy::Testing::AuthorizeTracker.tracking { yield } rescue ActionPolicy::Unauthorized # we don't want to care about authorization result end actual_calls = ActionPolicy::Testing::AuthorizeTracker.calls assert( actual_calls.any? { |call| call.matches?(policy, rule, target) }, "Expected #{target.inspect} to be authorized with #{policy}##{rule}, " \ "but no such authorization has been made.\n" \ "Registered authorizations: " \ "#{actual_calls.empty? ? "none" : actual_calls.map(&:inspect).join(",")}" ) end # Asserts that the given policy was used for scoping. # # def test_authorize # assert_have_authorized_scope(type: :active_record_relation, with: UserPolicy) do # get :index # end # end # # You can also specify `as` option. # # NOTE: `type` and `with` must be specified. # # You can run additional assertions for the matching target (the object passed # to the `authorized_scope` method) by calling `with_target`: # # def test_authorize # assert_have_authorized_scope(type: :active_record_relation, with: UserPolicy) do # get :index # end.with_target do |target| # assert_equal User.all, target # end # end # def assert_have_authorized_scope(type:, with:, as: :default, scope_options: nil) raise ArgumentError, "Block is required" unless block_given? policy = with ActionPolicy::Testing::AuthorizeTracker.tracking { yield } actual_scopes = ActionPolicy::Testing::AuthorizeTracker.scopings scope_options_message = if scope_options "with scope options #{scope_options}" else "without scope options" end assert( actual_scopes.any? { |scope| scope.matches?(policy, type, as, scope_options) }, "Expected a scoping named :#{as} for :#{type} type " \ "#{scope_options_message} " \ "from #{policy} to have been applied, " \ "but no such scoping has been made.\n" \ "Registered scopings: " \ "#{actual_scopes.empty? ? "none" : actual_scopes.map(&:inspect).join(",")}" ) WithScopeTarget.new(actual_scopes) end end end
30.741071
90
0.623003
f8972dab66749d41d83c686454269e2a93676715
2,166
require 'yaml' require 'pathname' require File.expand_path '../paths', __FILE__ module Libv8 class Location def install! File.open(Pathname(__FILE__).dirname.join('.location.yml'), "w") do |f| f.write self.to_yaml end return 0 end def self.load! File.open(Pathname(__FILE__).dirname.join('.location.yml')) do |f| YAML.load f end end class Vendor < Location def install! require File.expand_path '../builder', __FILE__ builder = Libv8::Builder.new exit_status = builder.build_libv8! super if exit_status == 0 verify_installation! return exit_status end def configure(context = MkmfContext.new) context.incflags.insert 0, Libv8::Paths.include_paths.map{|p| "-I#{p}"}.join(" ") + " " context.ldflags.insert 0, Libv8::Paths.object_paths.join(" ") + " " end def verify_installation! Libv8::Paths.object_paths.each do |p| fail ArchiveNotFound, p unless File.exist? p end end class ArchiveNotFound < StandardError def initialize(filename) super "libv8 did not install properly, expected binary v8 archive '#{filename}'to exist, but it was not found" end end end class System < Location def configure(context = MkmfContext.new) context.send(:dir_config, 'v8') context.send(:find_header, 'v8.h') or fail NotFoundError context.send(:have_library, 'v8') or fail NotFoundError end class NotFoundError < StandardError def initialize(*args) super(<<-EOS) You have chosen to use the version of V8 found on your system and *not* the one that is bundle with the libv8 rubygem. However, it could not be located. please make sure you have a version of v8 that is compatible with #{Libv8::VERSION} installed. You may need to special --with-v8-dir options if it is in a non-standard location thanks, The Mgmt EOS end end end class MkmfContext def incflags $INCFLAGS end def ldflags $LDFLAGS end end end end
26.096386
120
0.633887
089ed22b0cb0e30a70c32218cffcb25632871037
996
require "geoip_redis/store" require "geoip_redis/csv_reader" require "geoip_redis/blocks_parser" require "geoip_redis/locations_parser" module GeoipRedis class CountryLoader def initialize(redis) @store = Store.new(redis) @csv_reader = CSVReader.new @blocks_parser = BlocksParser.new @locations_parser = LocationsParser.new end def load_blocks(path_to_blocks) read_by_batch(path_to_blocks) do |rows| ip_ranges = rows.map { |row| @blocks_parser.ip_range(row) } @store.put_ip_ranges(ip_ranges) end end def load_locations(path_to_locations) read_by_batch(path_to_locations) do |rows| locations = rows.map { |row| @locations_parser.country(row) } @store.put_locations(locations) end end private def read_by_batch(path_to_file, &block) File.open(path_to_file) do |file| @csv_reader.read_by_batch(file) { |rows| block.call(rows) } end end end end
26.210526
69
0.682731
b93a34cb54eb52f248e74bdf60d7661a171d2af4
7,934
class Ffmpeg < Formula desc "Play, record, convert, and stream audio and video" homepage "https://ffmpeg.org/" url "https://ffmpeg.org/releases/ffmpeg-2.8.tar.bz2" sha256 "9565236404d3515aab754283c687c0a001019003148bf7f708e643608c0690b8" head "https://github.com/FFmpeg/FFmpeg.git" bottle do sha256 "845448ddef4bf390d85674e9a5350d67a267d09aa543f30647158f61a6b858c7" => :tiger_altivec sha256 "4676c5d72f1b3dccab80df9837d88386927c61e8b666b27434b0c8b95765d150" => :leopard_g3 sha256 "ecbc453f7e47abd14d926f15f0125e90d05e6f718eac0151b3e4908af3072a8f" => :leopard_altivec end option "without-x264", "Disable H.264 encoder" option "without-lame", "Disable MP3 encoder" option "without-libvo-aacenc", "Disable VisualOn AAC encoder" option "without-xvid", "Disable Xvid MPEG-4 video encoder" option "without-qtkit", "Disable deprecated QuickTime framework" unless MacOS.version < :snow_leopard option "with-rtmpdump", "Enable RTMP protocol" option "with-libass", "Enable ASS/SSA subtitle format" option "with-opencore-amr", "Enable Opencore AMR NR/WB audio format" option "with-openjpeg", "Enable JPEG 2000 image format" option "with-openssl", "Enable SSL support" option "with-libssh", "Enable SFTP protocol via libssh" option "with-schroedinger", "Enable Dirac video format" option "with-ffplay", "Enable FFplay media player" option "with-tools", "Enable additional FFmpeg tools" option "with-fdk-aac", "Enable the Fraunhofer FDK AAC library" option "with-libvidstab", "Enable vid.stab support for video stabilization" option "with-x265", "Enable x265 encoder" option "with-libsoxr", "Enable the soxr resample library" option "with-webp", "Enable using libwebp to encode WEBP images" option "with-zeromq", "Enable using libzeromq to receive commands sent through a libzeromq client" depends_on "pkg-config" => :build # Tiger's make is too old depends_on "make" => :build if MacOS.version < :leopard # Tiger's ld doesn't like -install_name depends_on :ld64 # manpages won't be built without texi2html depends_on "texi2html" => :build depends_on "yasm" => :build depends_on "x264" => :recommended depends_on "lame" => :recommended depends_on "libvo-aacenc" => :recommended depends_on "xvid" => :recommended depends_on "faac" => :optional depends_on "fontconfig" => :optional depends_on "freetype" => :optional depends_on "theora" => :optional depends_on "libvorbis" => :optional depends_on "libvpx" => :optional depends_on "rtmpdump" => :optional depends_on "opencore-amr" => :optional depends_on "libass" => :optional depends_on "openjpeg" => :optional depends_on "sdl" if build.with? "ffplay" depends_on "speex" => :optional depends_on "schroedinger" => :optional depends_on "fdk-aac" => :optional depends_on "opus" => :optional depends_on "frei0r" => :optional depends_on "libcaca" => :optional depends_on "libbluray" => :optional depends_on "libsoxr" => :optional depends_on "libquvi" => :optional depends_on "libvidstab" => :optional depends_on "x265" => :optional depends_on "openssl" => :optional depends_on "libssh" => :optional depends_on "webp" => :optional depends_on "zeromq" => :optional depends_on "libbs2b" => :optional def install args = ["--prefix=#{prefix}", "--enable-shared", "--enable-pthreads", "--enable-gpl", "--enable-version3", "--enable-hardcoded-tables", "--enable-avresample", "--cc=#{ENV.cc}", "--host-cflags=#{ENV.cflags}", "--host-ldflags=#{ENV.ldflags}" ] args << "--enable-opencl" if MacOS.version > :lion args << "--enable-libx264" if build.with? "x264" args << "--enable-libmp3lame" if build.with? "lame" args << "--enable-libvo-aacenc" if build.with? "libvo-aacenc" args << "--enable-libxvid" if build.with? "xvid" args << "--enable-libfontconfig" if build.with? "fontconfig" args << "--enable-libfreetype" if build.with? "freetype" args << "--enable-libtheora" if build.with? "theora" args << "--enable-libvorbis" if build.with? "libvorbis" args << "--enable-libvpx" if build.with? "libvpx" args << "--enable-librtmp" if build.with? "rtmpdump" args << "--enable-libopencore-amrnb" << "--enable-libopencore-amrwb" if build.with? "opencore-amr" args << "--enable-libfaac" if build.with? "faac" args << "--enable-libass" if build.with? "libass" args << "--enable-ffplay" if build.with? "ffplay" args << "--enable-libssh" if build.with? "libssh" args << "--enable-libspeex" if build.with? "speex" args << "--enable-libschroedinger" if build.with? "schroedinger" args << "--enable-libfdk-aac" if build.with? "fdk-aac" args << "--enable-openssl" if build.with? "openssl" args << "--enable-libopus" if build.with? "opus" args << "--enable-frei0r" if build.with? "frei0r" args << "--enable-libcaca" if build.with? "libcaca" args << "--enable-libsoxr" if build.with? "libsoxr" args << "--enable-libquvi" if build.with? "libquvi" args << "--enable-libvidstab" if build.with? "libvidstab" args << "--enable-libx265" if build.with? "x265" args << "--enable-libwebp" if build.with? "webp" args << "--enable-libzmq" if build.with? "zeromq" args << "--disable-indev=qtkit" if build.without?("qtkit") || MacOS.version < :snow_leopard args << "--enable-libbs2b" if build.with? "libbs2b" if build.with? "openjpeg" args << "--enable-libopenjpeg" args << "--disable-decoder=jpeg2000" args << "--extra-cflags=" + `pkg-config --cflags libopenjpeg`.chomp end args << "--disable-asm" if MacOS.version < :leopard args << "--disable-altivec" if !Hardware::CPU.altivec? || (build.bottle? && ARGV.bottle_arch == :g3) # These librares are GPL-incompatible, and require ffmpeg be built with # the "--enable-nonfree" flag, which produces unredistributable libraries if %w[faac fdk-aac openssl].any? { |f| build.with? f } args << "--enable-nonfree" end # A bug in a dispatch header on 10.10, included via CoreFoundation, # prevents GCC from building VDA support. GCC has no problems on # 10.9 and earlier. # See: https://github.com/Homebrew/homebrew/issues/33741 if MacOS.version < :yosemite || ENV.compiler == :clang args << "--enable-vda" else args << "--disable-vda" end # For 32-bit compilation under gcc 4.2, see: # https://trac.macports.org/ticket/20938#comment:22 ENV.append_to_cflags "-mdynamic-no-pic" if Hardware.is_32_bit? && Hardware::CPU.intel? && ENV.compiler == :clang system "./configure", *args if MacOS.prefer_64_bit? inreplace "config.mak" do |s| shflags = s.get_make_var "SHFLAGS" if shflags.gsub!(" -Wl,-read_only_relocs,suppress", "") s.change_make_var! "SHFLAGS", shflags end end end system make_path, "install" if build.with? "tools" system make_path, "alltools" bin.install Dir["tools/*"].select { |f| File.executable? f } end end def caveats if build.without? "faac" then <<-EOS.undent FFmpeg has been built without libfaac for licensing reasons; libvo-aacenc is used by default. To install with libfaac, you can: brew reinstall ffmpeg --with-faac You can also use the experimental FFmpeg encoder, libfdk-aac, or libvo_aacenc to encode AAC audio: ffmpeg -i input.wav -c:a aac -strict experimental output.m4a Or: brew reinstall ffmpeg --with-fdk-aac ffmpeg -i input.wav -c:a libfdk_aac output.m4a EOS end end test do # Create an example mp4 file system "#{bin}/ffmpeg", "-y", "-filter_complex", "testsrc=rate=1:duration=1", "#{testpath}/video.mp4" assert (testpath/"video.mp4").exist? end end
40.070707
116
0.665994
ac1d68216a65058b4fede73bb2a9f5cdcaf45284
4,067
require "set" require "formula" require "formula_versions" class Descriptions CACHE_FILE = HOMEBREW_CACHE + "desc_cache.json" def self.cache @cache || load_cache end # If the cache file exists, load it into, and return, a hash; otherwise, # return nil. def self.load_cache @cache = JSON.parse(CACHE_FILE.read) if CACHE_FILE.exist? end # Write the cache to disk after ensuring the existence of the containing # directory. def self.save_cache HOMEBREW_CACHE.mkpath CACHE_FILE.atomic_write JSON.dump(@cache) end # Create a hash mapping all formulae to their descriptions; # save it for future use. def self.generate_cache @cache = {} Formula.each do |f| @cache[f.full_name] = f.desc end save_cache end # Return true if the cache exists, and none of the Taps # repos were updated more recently than it was. def self.cache_fresh? return false unless CACHE_FILE.exist? cache_mtime = File.mtime(CACHE_FILE) Tap.each do |tap| next unless tap.git? repo_mtime = File.mtime(tap.path/".git/refs/heads/master") return false if repo_mtime > cache_mtime end true end # Create the cache if it doesn't already exist. def self.ensure_cache generate_cache unless cache_fresh? && cache end # Take a {Report}, as generated by cmd/update.rb. # Unless the cache file exists, do nothing. # If it does exist, but the Report is empty, just touch the cache file. # Otherwise, use the report to update the cache. def self.update_cache(report) return unless CACHE_FILE.exist? if report.empty? FileUtils.touch CACHE_FILE else renamings = report.select_formula(:R) alterations = report.select_formula(:A) + report.select_formula(:M) + renamings.map(&:last) cache_formulae(alterations, save: false) uncache_formulae(report.select_formula(:D) + renamings.map(&:first)) end end # Given an array of formula names, add them and their descriptions to the # cache. Save the updated cache to disk, unless explicitly told not to. def self.cache_formulae(formula_names, options = { save: true }) return unless cache formula_names.each do |name| begin desc = Formulary.factory(name).desc rescue FormulaUnavailableError, *FormulaVersions::IGNORED_EXCEPTIONS end @cache[name] = desc end save_cache if options[:save] end # Given an array of formula names, remove them and their descriptions from # the cache. Save the updated cache to disk, unless explicitly told not to. def self.uncache_formulae(formula_names, options = { save: true }) return unless cache formula_names.each { |name| @cache.delete(name) } save_cache if options[:save] end # Given a regex, find all formulae whose specified fields contain a match. def self.search(regex, field = :either) ensure_cache results = case field when :name @cache.select { |name, _| name =~ regex } when :desc @cache.select { |_, desc| desc =~ regex } when :either @cache.select { |name, desc| (name =~ regex) || (desc =~ regex) } end new(results) end # Create an actual instance. def initialize(descriptions) @descriptions = descriptions end # Take search results -- a hash mapping formula names to descriptions -- and # print them. def print blank = Formatter.warning("[no description]") @descriptions.keys.sort.each do |full_name| short_name = short_names[full_name] printed_name = (short_name_counts[short_name] == 1) ? short_name : full_name description = @descriptions[full_name] || blank puts "#{Tty.bold}#{printed_name}:#{Tty.reset} #{description}" end end private def short_names @short_names ||= Hash[@descriptions.keys.map { |k| [k, k.split("/").last] }] end def short_name_counts @short_name_counts ||= short_names.values.each_with_object(Hash.new(0)) { |name, counts| counts[name] += 1 } end end
28.843972
91
0.678387
912e0d838dd04637ffe3ba11f578ea36908e4205
87
# gems require UPPER case ENV variables so translate Idv::UpcaseVendorEnvVars.new.call
29
52
0.827586
91bf3fada7b0c96a80e17c14a2086c30afa657a5
73
Dummy::Application.routes.draw do get ':action', :to => 'sessions' end
18.25
34
0.684932
e8cb5f1688b0f9821a5f892158b190889dcd136e
8,633
require 'jwt' RSpec.describe OAuth2::Strategy::Assertion do subject { client.assertion } let(:client) do cli = OAuth2::Client.new('abc', 'def', :site => 'http://api.example.com', :auth_scheme => auth_scheme) cli.connection.build do |b| b.adapter :test do |stub| stub.post('/oauth/token') do |token_request| @request_body = token_request.body case @response_format when 'formencoded' [200, {'Content-Type' => 'application/x-www-form-urlencoded'}, 'expires_in=600&access_token=salmon&refresh_token=trout'] when 'json' [200, {'Content-Type' => 'application/json'}, '{"expires_in":600,"access_token":"salmon","refresh_token":"trout"}'] else raise 'Please define @response_format to choose a response content type!' end end end end cli end let(:auth_scheme) { :request_body } describe '#authorize_url' do it 'raises NotImplementedError' do expect { subject.authorize_url }.to raise_error(NotImplementedError) end end describe '#get_token' do let(:algorithm) { 'HS256' } let(:key) { 'arowana' } let(:timestamp) { Time.now.to_i } let(:claims) do { :iss => 'carp@example.com', :scope => 'https://oauth.example.com/auth/flounder', :aud => 'https://sturgeon.example.com/oauth2/token', :exp => timestamp + 3600, :iat => timestamp, :sub => '12345', :custom_claim => 'ling cod', } end before do @response_format = 'json' end describe 'assembling a JWT assertion' do let(:jwt) do payload, header = JWT.decode(@request_body[:assertion], key, true, :algorithm => algorithm) {:payload => payload, :header => header} end let(:payload) { jwt[:payload] } let(:header) { jwt[:header] } context 'when encoding as HS256' do let(:algorithm) { 'HS256' } let(:key) { 'super_secret!' } before do subject.get_token(claims, :algorithm => algorithm, :key => key) raise 'No request made!' if @request_body.nil? end it 'indicates HS256 in the header' do expect(header).not_to be_nil expect(header['alg']).to eq('HS256') end it 'encodes the JWT as HS256' do expect(payload).not_to be_nil expect(payload.keys).to match_array(%w[iss scope aud exp iat sub custom_claim]) payload.each do |key, claim| expect(claims[key.to_sym]).to eq(claim) end end end context 'when encoding as RS256' do let(:algorithm) { 'RS256' } let(:key) { OpenSSL::PKey::RSA.new(1024) } before do subject.get_token(claims, :algorithm => algorithm, :key => key) raise 'No request made!' if @request_body.nil? end it 'indicates RS256 in the header' do expect(header).not_to be_nil expect(header['alg']).to eq('RS256') end it 'encodes the JWT as RS256' do expect(payload).not_to be_nil expect(payload.keys).to match_array(%w[iss scope aud exp iat sub custom_claim]) payload.each do |key, claim| expect(claims[key.to_sym]).to eq(claim) end end end context 'with bad encoding params' do let(:encoding_opts) { {:algorithm => algorithm, :key => key} } describe 'non-supported algorithms' do let(:algorithm) { 'the blockchain' } let(:key) { 'machine learning' } it 'raises NotImplementedError' do # this behavior is handled by the JWT gem, but this should make sure it is consistent expect { subject.get_token(claims, encoding_opts) }.to raise_error(NotImplementedError) end end describe 'missing encoding_opts[:algorithm]' do before do encoding_opts.delete(:algorithm) end it 'raises ArgumentError' do expect { subject.get_token(claims, encoding_opts) }.to raise_error(ArgumentError, /algorithm/) end end describe 'missing encoding_opts[:key]' do before do encoding_opts.delete(:key) end it 'raises ArgumentError' do expect { subject.get_token(claims, encoding_opts) }.to raise_error(ArgumentError, /key/) end end end end describe 'POST request parameters' do context 'when using :auth_scheme => :request_body' do let(:auth_scheme) { :request_body } it 'includes assertion and grant_type, along with the client parameters' do subject.get_token(claims, :algorithm => algorithm, :key => key) expect(@request_body).not_to be_nil expect(@request_body.keys).to match_array([:assertion, :grant_type, 'client_id', 'client_secret']) expect(@request_body[:grant_type]).to eq('urn:ietf:params:oauth:grant-type:jwt-bearer') expect(@request_body[:assertion]).to be_a(String) expect(@request_body['client_id']).to eq('abc') expect(@request_body['client_secret']).to eq('def') end it 'includes other params via request_options' do subject.get_token(claims, {:algorithm => algorithm, :key => key}, :scope => 'dover sole') expect(@request_body).not_to be_nil expect(@request_body.keys).to match_array([:assertion, :grant_type, :scope, 'client_id', 'client_secret']) expect(@request_body[:grant_type]).to eq('urn:ietf:params:oauth:grant-type:jwt-bearer') expect(@request_body[:assertion]).to be_a(String) expect(@request_body[:scope]).to eq('dover sole') expect(@request_body['client_id']).to eq('abc') expect(@request_body['client_secret']).to eq('def') end end context 'when using :auth_scheme => :basic_auth' do let(:auth_scheme) { :basic_auth } it 'includes assertion and grant_type by default' do subject.get_token(claims, :algorithm => algorithm, :key => key) expect(@request_body).not_to be_nil expect(@request_body.keys).to match_array([:assertion, :grant_type]) expect(@request_body[:grant_type]).to eq('urn:ietf:params:oauth:grant-type:jwt-bearer') expect(@request_body[:assertion]).to be_a(String) end it 'includes other params via request_options' do subject.get_token(claims, {:algorithm => algorithm, :key => key}, :scope => 'dover sole') expect(@request_body).not_to be_nil expect(@request_body.keys).to match_array([:assertion, :grant_type, :scope]) expect(@request_body[:grant_type]).to eq('urn:ietf:params:oauth:grant-type:jwt-bearer') expect(@request_body[:assertion]).to be_a(String) expect(@request_body[:scope]).to eq('dover sole') end end end describe 'returning the response' do let(:access_token) { subject.get_token(claims, {:algorithm => algorithm, :key => key}, {}, response_opts) } let(:response_opts) { {} } %w[json formencoded].each do |mode| context "when the content type is #{mode}" do before do @response_format = mode end it 'returns an AccessToken' do expect(access_token).to be_an(AccessToken) end it 'returns AccessToken with same Client' do expect(access_token.client).to eq(client) end it 'returns AccessToken with #token' do expect(access_token.token).to eq('salmon') end it 'returns AccessToken with #expires_in' do expect(access_token.expires_in).to eq(600) end it 'returns AccessToken with #expires_at' do expect(access_token.expires_at).not_to be_nil end it 'sets AccessToken#refresh_token to nil' do expect(access_token.refresh_token).to eq(nil) end context 'with custom response_opts' do let(:response_opts) { {:custom_token_option => 'mackerel'} } it 'passes them into the token params' do expect(access_token.params).to eq(response_opts) end end context 'when no custom opts are passed in' do let(:response_opts) { {} } it 'does not set any params by default' do expect(access_token.params).to eq({}) end end end end end end end
34.951417
132
0.598633
d5c52c464763bfaade7d812728d93d621a06d744
2,242
# This test verifies that a previouslt cached fact is being resolved correctly after it is not cached anymore test_name "ttls configured cached fact is resolved after ttls is removed" do tag 'risk:high' require 'facter/acceptance/user_fact_utils' extend Facter::Acceptance::UserFactUtils # This fact must be resolvable on ALL platforms # Do NOT use the 'kernel' fact as it is used to configure the tests cached_fact_name = 'uptime' cached_fact_value = "CACHED_FACT_VALUE" cached_fact_content = <<EOM { "#{cached_fact_name}": "#{cached_fact_value}" } EOM config = <<EOM facts : { ttls : [ { "#{cached_fact_name}" : 30 days } ] } EOM config_no_cache = <<EOM facts : { ttls : [ ] } EOM agents.each do |agent| step "Agent #{agent}: create config file" do config_dir = get_default_fact_dir(agent['platform'], on(agent, facter('kernelmajversion')).stdout.chomp.to_f) config_file = File.join(config_dir, "facter.conf") cached_facts_dir = get_cached_facts_dir(agent['platform'], on(agent, facter('kernelmajversion')).stdout.chomp.to_f) cached_fact_file = File.join(cached_facts_dir, cached_fact_name) # Setup facter conf agent.mkdir_p(config_dir) create_remote_file(agent, config_file, config) teardown do agent.rm_rf(config_dir) agent.rm_rf(cached_facts_dir) end step "Agent #{agent}: create config file with no cached facts" do # Set up a known cached fact agent.rm_rf(cached_facts_dir) on(agent, facter("")) create_remote_file(agent, cached_fact_file, cached_fact_content) end step "Agent #{agent}: resolves fact after ttls was removed" do # Create config file with no caching no_cache_config_file = File.join(config_dir, "no-cache.conf") create_remote_file(agent, no_cache_config_file, config_no_cache) on(agent, facter("--config \"#{no_cache_config_file}\"")) do |facter_output| assert_match(/#{cached_fact_name}/, facter_output.stdout, "Expected to see the fact in output") assert_no_match(/#{cached_fact_value}/, facter_output.stdout, "Expected to not see the cached fact value") end end end end end
32.492754
121
0.693131
398fe80ccf84d1f971acaa66af94346b36dc676e
571
module Kontena::Cli::Vault class WriteCommand < Clamp::Command include Kontena::Cli::Common include Kontena::Cli::GridOptions parameter 'NAME', 'Secret name' parameter '[VALUE]', 'Secret value' def execute require_api_url token = require_token secret = value if secret.to_s == '' secret = STDIN.read end abort('No value provided') if secret.to_s == '' data = { name: name, value: secret } client(token).post("grids/#{current_grid}/secrets", data) end end end
22.84
63
0.595447
6207fb476cfbc9ed32de88036143395216889329
126
module Nlocal module Directory class Document < Attachment include Nlocal::Directory::StiChild end end end
14
41
0.706349
4abeb407879d4a3c38f55defd2c8db13c96b2fdd
814
# # Cookbook Name:: oneview_test # Recipe:: power_device_set_uid_state_off # # (c) Copyright 2017 Hewlett Packard Enterprise Development LP # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. # oneview_power_device 'PowerDeviceUidStateOff' do client node['oneview_test']['client'] uid_state 'off' action :set_uid_state end
37
84
0.777641
18a866283f7b08cc27f1220ad5eb28fab749a13b
218
# -*- encoding : utf-8 -*- class Cuenta::Faccion::CategoriasController < Admin::CategoriasController public def categorias_skip_path '../../../' end def cats_path 'cuenta/faccion/categorias' end end
18.166667
73
0.678899
b936a7f38f6a87510fd47a0857e36a42bec00b0c
713
# frozen_string_literal: true require 'spec_helper' RSpec.describe 'User views services', :js do include_context 'project service activation' it 'shows the list of available services' do visit_project_integrations expect(page).to have_content('Integrations') expect(page).to have_content('Campfire') expect(page).to have_content('Jira') expect(page).to have_content('Assembla') expect(page).to have_content('Pushover') expect(page).to have_content('Atlassian Bamboo') expect(page).to have_content('JetBrains TeamCity') expect(page).to have_content('Asana') expect(page).to have_content('Irker (IRC gateway)') expect(page).to have_content('Packagist') end end
31
55
0.734923
01fe723edda4d7af5a909df776a1078b3c96dc58
401
module ActsAsCommentableWithReplies module Extenders module Commenter def commenter? false end def acts_as_commenter(*args) require 'acts_as_commentable_with_replies/commenter' include ActsAsCommentableWithReplies::Commenter class_eval do def self.commenter? true end end end end end end
16.708333
60
0.623441
8749e72f6bc12968503fbbfc8791c421c64b8a01
1,338
module Withdraws module Withdrawable extend ActiveSupport::Concern included do before_filter :fetch end def create @withdraw = model_kls.new(withdraw_params) if two_factor_auth_verified? if @withdraw.save @withdraw.submit! render nothing: true else render text: @withdraw.errors.full_messages.join(', '), status: 403 end else render text: I18n.t('private.withdraws.create.two_factors_error'), status: 403 end end def destroy Withdraw.transaction do @withdraw = current_user.withdraws.find(params[:id]).lock! @withdraw.cancel @withdraw.save! end render nothing: true end private def fetch @account = current_user.get_account(channel.currency) @model = model_kls @fund_sources = current_user.fund_sources.with_currency(channel.currency) @assets = model_kls.without_aasm_state(:submitting).where(member: current_user).order(:id).reverse_order.limit(10) end def withdraw_params params[:withdraw][:fee] = channel.fee params[:withdraw][:currency] = channel.currency params[:withdraw][:member_id] = current_user.id params.require(:withdraw).permit(:fund_source, :member_id, :currency, :sum) end end end
26.235294
120
0.657698
39bd77e8c53200128538e5c0d0b196fd97489e85
38
module Prct07 VERSION = "0.1.0" end
9.5
19
0.657895
1d78778c75784da092cd18d8194893ed2207f080
34,200
# frozen_string_literal: true require 'spec_helper' RSpec.describe ProjectsHelper do include ProjectForksHelper include AfterNextHelpers let_it_be_with_reload(:project) { create(:project) } let_it_be_with_refind(:project_with_repo) { create(:project, :repository) } let_it_be(:user) { create(:user) } before do helper.instance_variable_set(:@project, project) end describe '#project_incident_management_setting' do context 'when incident_management_setting exists' do let(:project_incident_management_setting) do create(:project_incident_management_setting, project: project) end it 'return project_incident_management_setting' do expect(helper.project_incident_management_setting).to( eq(project_incident_management_setting) ) end end context 'when incident_management_setting does not exist' do it 'builds incident_management_setting' do setting = helper.project_incident_management_setting expect(setting).not_to be_persisted expect(setting.create_issue).to be_falsey expect(setting.send_email).to be_falsey expect(setting.issue_template_key).to be_nil end end end describe '#error_tracking_setting_project_json' do context 'error tracking setting does not exist' do it 'returns nil' do expect(helper.error_tracking_setting_project_json).to be_nil end end context 'error tracking setting exists' do let_it_be(:error_tracking_setting) { create(:project_error_tracking_setting, project: project) } context 'api_url present' do let(:json) do { name: error_tracking_setting.project_name, organization_name: error_tracking_setting.organization_name, organization_slug: error_tracking_setting.organization_slug, slug: error_tracking_setting.project_slug }.to_json end it 'returns error tracking json' do expect(helper.error_tracking_setting_project_json).to eq(json) end end context 'api_url not present' do it 'returns nil' do project.error_tracking_setting.api_url = nil project.error_tracking_setting.enabled = false expect(helper.error_tracking_setting_project_json).to be_nil end end end end describe "#project_status_css_class" do it "returns appropriate class" do expect(project_status_css_class("started")).to eq("table-active") expect(project_status_css_class("failed")).to eq("table-danger") expect(project_status_css_class("finished")).to eq("table-success") end end describe "can_change_visibility_level?" do let_it_be(:user) { create(:project_member, :reporter, user: create(:user), project: project).user } let(:forked_project) { fork_project(project, user) } it "returns false if there are no appropriate permissions" do allow(helper).to receive(:can?) { false } expect(helper.can_change_visibility_level?(project, user)).to be_falsey end it "returns true if there are permissions" do allow(helper).to receive(:can?) { true } expect(helper.can_change_visibility_level?(project, user)).to be_truthy end end describe '#can_disable_emails?' do let_it_be(:user) { create(:project_member, :maintainer, user: create(:user), project: project).user } it 'returns true for the project owner' do allow(helper).to receive(:can?).with(project.owner, :set_emails_disabled, project) { true } expect(helper.can_disable_emails?(project, project.owner)).to be_truthy end it 'returns false for anyone else' do allow(helper).to receive(:can?).with(user, :set_emails_disabled, project) { false } expect(helper.can_disable_emails?(project, user)).to be_falsey end it 'returns false if group emails disabled' do project = create(:project, group: create(:group)) allow(project.group).to receive(:emails_disabled?).and_return(true) expect(helper.can_disable_emails?(project, project.owner)).to be_falsey end end describe "readme_cache_key" do let(:project) { project_with_repo } it "returns a valid cach key" do expect(helper.send(:readme_cache_key)).to eq("#{project.full_path}-#{project.commit.id}-readme") end it "returns a valid cache key if HEAD does not exist" do allow(project).to receive(:commit) { nil } expect(helper.send(:readme_cache_key)).to eq("#{project.full_path}-nil-readme") end end describe "#project_list_cache_key", :clean_gitlab_redis_cache do let(:project) { project_with_repo } before do allow(helper).to receive(:current_user).and_return(user) allow(helper).to receive(:can?).with(user, :read_cross_project) { true } allow(user).to receive(:max_member_access_for_project).and_return(40) allow(Gitlab::I18n).to receive(:locale).and_return('es') end it "includes the route" do expect(helper.project_list_cache_key(project)).to include(project.route.cache_key) end it "includes the project" do expect(helper.project_list_cache_key(project)).to include(project.cache_key) end it "includes the last activity date" do expect(helper.project_list_cache_key(project)).to include(project.last_activity_date) end it "includes the controller name" do expect(helper.controller).to receive(:controller_name).and_return("testcontroller") expect(helper.project_list_cache_key(project)).to include("testcontroller") end it "includes the controller action" do expect(helper.controller).to receive(:action_name).and_return("testaction") expect(helper.project_list_cache_key(project)).to include("testaction") end it "includes the application settings" do settings = Gitlab::CurrentSettings.current_application_settings expect(helper.project_list_cache_key(project)).to include(settings.cache_key) end it "includes a version" do expect(helper.project_list_cache_key(project).last).to start_with('v') end it 'includes whether or not the user can read cross project' do expect(helper.project_list_cache_key(project)).to include('cross-project:true') end it "includes the pipeline status when there is a status" do create(:ci_pipeline, :success, project: project, sha: project.commit.sha) expect(helper.project_list_cache_key(project)).to include("pipeline-status/#{project.commit.sha}-success") end it "includes the user locale" do expect(helper.project_list_cache_key(project)).to include('es') end it "includes the user max member access" do expect(helper.project_list_cache_key(project)).to include('access:40') end end describe '#load_pipeline_status' do it 'loads the pipeline status in batch' do helper.load_pipeline_status([project]) # Skip lazy loading of the `pipeline_status` attribute pipeline_status = project.instance_variable_get('@pipeline_status') expect(pipeline_status).to be_a(Gitlab::Cache::Ci::ProjectPipelineStatus) end end describe '#show_no_ssh_key_message?' do before do allow(helper).to receive(:current_user).and_return(user) end context 'user has no keys' do it 'returns true' do expect(helper.show_no_ssh_key_message?).to be_truthy end end context 'user has an ssh key' do it 'returns false' do create(:personal_key, user: user) expect(helper.show_no_ssh_key_message?).to be_falsey end end end describe '#show_no_password_message?' do before do allow(helper).to receive(:current_user).and_return(user) end context 'user has password set' do it 'returns false' do expect(helper.show_no_password_message?).to be_falsey end end context 'user has hidden the message' do it 'returns false' do allow(helper).to receive(:cookies).and_return(hide_no_password_message: true) expect(helper.show_no_password_message?).to be_falsey end end context 'user requires a password for Git' do it 'returns true' do allow(user).to receive(:require_password_creation_for_git?).and_return(true) expect(helper.show_no_password_message?).to be_truthy end end context 'user requires a personal access token for Git' do it 'returns true' do allow(user).to receive(:require_password_creation_for_git?).and_return(false) allow(user).to receive(:require_personal_access_token_creation_for_git_auth?).and_return(true) expect(helper.show_no_password_message?).to be_truthy end end end describe '#no_password_message' do let(:user) { create(:user, password_automatically_set: true) } before do allow(helper).to receive(:current_user).and_return(user) end context 'password authentication is enabled for Git' do it 'returns message prompting user to set password or set up a PAT' do stub_application_setting(password_authentication_enabled_for_git?: true) expect(helper.no_password_message).to eq('Your account is authenticated with SSO or SAML. To <a href="/help/gitlab-basics/start-using-git#pull-and-push" target="_blank" rel="noopener noreferrer">push and pull</a> over HTTP with Git using this account, you must <a href="/-/profile/password/edit">set a password</a> or <a href="/-/profile/personal_access_tokens">set up a Personal Access Token</a> to use instead of a password. For more information, see <a href="/help/gitlab-basics/start-using-git#clone-with-https" target="_blank" rel="noopener noreferrer">Clone with HTTPS</a>.') end end context 'password authentication is disabled for Git' do it 'returns message prompting user to set up a PAT' do stub_application_setting(password_authentication_enabled_for_git?: false) expect(helper.no_password_message).to eq('Your account is authenticated with SSO or SAML. To <a href="/help/gitlab-basics/start-using-git#pull-and-push" target="_blank" rel="noopener noreferrer">push and pull</a> over HTTP with Git using this account, you must <a href="/-/profile/personal_access_tokens">set up a Personal Access Token</a> to use instead of a password. For more information, see <a href="/help/gitlab-basics/start-using-git#clone-with-https" target="_blank" rel="noopener noreferrer">Clone with HTTPS</a>.') end end end describe '#link_to_project' do let(:group) { create(:group, name: 'group name with space') } let(:project) { create(:project, group: group, name: 'project name with space') } subject { link_to_project(project) } it 'returns an HTML link to the project' do expect(subject).to match(%r{/#{group.full_path}/#{project.path}}) expect(subject).to include('group name with space /') expect(subject).to include('project name with space') end end describe '#link_to_member_avatar' do let(:user) { build_stubbed(:user) } let(:expected) { double } before do expect(helper).to receive(:avatar_icon_for_user).with(user, 16).and_return(expected) end it 'returns image tag for member avatar' do expect(helper).to receive(:image_tag).with(expected, { width: 16, class: %w[avatar avatar-inline s16], alt: "" }) helper.link_to_member_avatar(user) end it 'returns image tag with avatar class' do expect(helper).to receive(:image_tag).with(expected, { width: 16, class: %w[avatar avatar-inline s16 any-avatar-class], alt: "" }) helper.link_to_member_avatar(user, avatar_class: "any-avatar-class") end end describe '#link_to_member' do let(:group) { build_stubbed(:group) } let(:project) { build_stubbed(:project, group: group) } let(:user) { build_stubbed(:user, name: '<h1>Administrator</h1>') } describe 'using the default options' do it 'returns an HTML link to the user' do link = helper.link_to_member(project, user) expect(link).to match(%r{/#{user.username}}) end it 'HTML escapes the name of the user' do link = helper.link_to_member(project, user) expect(link).to include(ERB::Util.html_escape(user.name)) expect(link).not_to include(user.name) end end context 'when user is nil' do it 'returns "(deleted)"' do link = helper.link_to_member(project, nil) expect(link).to eq("(deleted)") end end end describe 'default_clone_protocol' do context 'when user is not logged in and gitlab protocol is HTTP' do it 'returns HTTP' do allow(helper).to receive(:current_user).and_return(nil) expect(helper.send(:default_clone_protocol)).to eq('http') end end context 'when user is not logged in and gitlab protocol is HTTPS' do it 'returns HTTPS' do stub_config_setting(protocol: 'https') allow(helper).to receive(:current_user).and_return(nil) expect(helper.send(:default_clone_protocol)).to eq('https') end end end describe '#last_push_event' do let(:user) { double(:user, fork_of: nil) } let(:project) { double(:project, id: 1) } before do allow(helper).to receive(:current_user).and_return(user) end context 'when there is no current_user' do let(:user) { nil } it 'returns nil' do expect(helper.last_push_event).to eq(nil) end end it 'returns recent push on the current project' do event = double(:event) expect(user).to receive(:recent_push).with(project).and_return(event) expect(helper.last_push_event).to eq(event) end end describe '#show_projects' do let(:projects) do Project.all end before do stub_feature_flags(project_list_filter_bar: false) end it 'returns true when there are projects' do expect(helper.show_projects?(projects, {})).to eq(true) end it 'returns true when there are no projects but a name is given' do expect(helper.show_projects?(Project.none, name: 'foo')).to eq(true) end it 'returns true when there are no projects but personal is present' do expect(helper.show_projects?(Project.none, personal: 'true')).to eq(true) end it 'returns false when there are no projects and there is no name' do expect(helper.show_projects?(Project.none, {})).to eq(false) end end describe '#push_to_create_project_command' do let(:user) { build_stubbed(:user, username: 'john') } it 'returns the command to push to create project over HTTP' do allow(Gitlab::CurrentSettings.current_application_settings).to receive(:enabled_git_access_protocol) { 'http' } expect(helper.push_to_create_project_command(user)).to eq('git push --set-upstream http://test.host/john/$(git rev-parse --show-toplevel | xargs basename).git $(git rev-parse --abbrev-ref HEAD)') end it 'returns the command to push to create project over SSH' do allow(Gitlab::CurrentSettings.current_application_settings).to receive(:enabled_git_access_protocol) { 'ssh' } expect(helper.push_to_create_project_command(user)).to eq("git push --set-upstream #{Gitlab.config.gitlab.user}@localhost:john/$(git rev-parse --show-toplevel | xargs basename).git $(git rev-parse --abbrev-ref HEAD)") end end describe '#any_projects?' do it 'returns true when projects will be returned' do expect(helper.any_projects?(Project.all)).to eq(true) end it 'returns false when no projects will be returned' do expect(helper.any_projects?(Project.none)).to eq(false) end it 'returns true when using a non-empty Array' do expect(helper.any_projects?([project])).to eq(true) end it 'returns false when using an empty Array' do expect(helper.any_projects?([])).to eq(false) end it 'only executes a single query when a LIMIT is applied' do relation = Project.limit(1) recorder = ActiveRecord::QueryRecorder.new do 2.times do helper.any_projects?(relation) end end expect(recorder.count).to eq(1) end end describe '#git_user_name' do let(:user) { build_stubbed(:user, name: 'John "A" Doe53') } before do allow(helper).to receive(:current_user).and_return(user) end it 'parses quotes in name' do expect(helper.send(:git_user_name)).to eq('John \"A\" Doe53') end end describe '#git_user_email' do context 'not logged-in' do before do allow(helper).to receive(:current_user).and_return(nil) end it 'returns your@email.com' do expect(helper.send(:git_user_email)).to eq('your@email.com') end end context 'user logged in' do before do allow(helper).to receive(:current_user).and_return(user) end context 'user has no configured commit email' do it 'returns the primary email' do expect(helper.send(:git_user_email)).to eq(user.email) end end context 'user has a configured commit email' do before do confirmed_email = create(:email, :confirmed, user: user) user.update!(commit_email: confirmed_email.email) end it 'returns the commit email' do expect(helper.send(:git_user_email)).to eq(user.commit_email) end end end end describe 'show_xcode_link' do let(:mac_ua) { 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36' } let(:ios_ua) { 'Mozilla/5.0 (iPad; CPU OS 5_1_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9B206 Safari/7534.48.3' } context 'when the repository is xcode compatible' do before do allow(project.repository).to receive(:xcode_project?).and_return(true) end it 'returns false if the visitor is not using macos' do allow(helper).to receive(:browser).and_return(Browser.new(ios_ua)) expect(helper.show_xcode_link?(project)).to eq(false) end it 'returns true if the visitor is using macos' do allow(helper).to receive(:browser).and_return(Browser.new(mac_ua)) expect(helper.show_xcode_link?(project)).to eq(true) end end context 'when the repository is not xcode compatible' do before do allow(project.repository).to receive(:xcode_project?).and_return(false) end it 'returns false if the visitor is not using macos' do allow(helper).to receive(:browser).and_return(Browser.new(ios_ua)) expect(helper.show_xcode_link?(project)).to eq(false) end it 'returns false if the visitor is using macos' do allow(helper).to receive(:browser).and_return(Browser.new(mac_ua)) expect(helper.show_xcode_link?(project)).to eq(false) end end end describe '#explore_projects_tab?' do subject { helper.explore_projects_tab? } it 'returns true when on the "All" tab under "Explore projects"' do allow(@request).to receive(:path) { explore_projects_path } expect(subject).to be_truthy end it 'returns true when on the "Trending" tab under "Explore projects"' do allow(@request).to receive(:path) { trending_explore_projects_path } expect(subject).to be_truthy end it 'returns true when on the "Starred" tab under "Explore projects"' do allow(@request).to receive(:path) { starred_explore_projects_path } expect(subject).to be_truthy end it 'returns false when on the "Your projects" tab' do allow(@request).to receive(:path) { dashboard_projects_path } expect(subject).to be_falsey end end describe '#show_merge_request_count' do context 'enabled flag' do it 'returns true if compact mode is disabled' do expect(helper.show_merge_request_count?).to be_truthy end it 'returns false if compact mode is enabled' do expect(helper.show_merge_request_count?(compact_mode: true)).to be_falsey end end context 'disabled flag' do it 'returns false if disabled flag is true' do expect(helper.show_merge_request_count?(disabled: true)).to be_falsey end it 'returns true if disabled flag is false' do expect(helper.show_merge_request_count?).to be_truthy end end end describe '#show_issue_count?' do context 'enabled flag' do it 'returns true if compact mode is disabled' do expect(helper.show_issue_count?).to be_truthy end it 'returns false if compact mode is enabled' do expect(helper.show_issue_count?(compact_mode: true)).to be_falsey end end context 'disabled flag' do it 'returns false if disabled flag is true' do expect(helper.show_issue_count?(disabled: true)).to be_falsey end it 'returns true if disabled flag is false' do expect(helper.show_issue_count?).to be_truthy end end end describe '#show_auto_devops_implicitly_enabled_banner?' do using RSpec::Parameterized::TableSyntax let_it_be_with_reload(:project_with_auto_devops) { create(:project, :repository, :auto_devops) } let(:feature_visibilities) do { enabled: ProjectFeature::ENABLED, disabled: ProjectFeature::DISABLED } end where(:global_setting, :project_setting, :builds_visibility, :gitlab_ci_yml, :user_access, :result) do # With ADO implicitly enabled scenarios true | nil | :disabled | true | :developer | false true | nil | :disabled | true | :maintainer | false true | nil | :disabled | true | :owner | false true | nil | :disabled | false | :developer | false true | nil | :disabled | false | :maintainer | false true | nil | :disabled | false | :owner | false true | nil | :enabled | true | :developer | false true | nil | :enabled | true | :maintainer | false true | nil | :enabled | true | :owner | false true | nil | :enabled | false | :developer | false true | nil | :enabled | false | :maintainer | true true | nil | :enabled | false | :owner | true # With ADO enabled scenarios true | true | :disabled | true | :developer | false true | true | :disabled | true | :maintainer | false true | true | :disabled | true | :owner | false true | true | :disabled | false | :developer | false true | true | :disabled | false | :maintainer | false true | true | :disabled | false | :owner | false true | true | :enabled | true | :developer | false true | true | :enabled | true | :maintainer | false true | true | :enabled | true | :owner | false true | true | :enabled | false | :developer | false true | true | :enabled | false | :maintainer | false true | true | :enabled | false | :owner | false # With ADO disabled scenarios true | false | :disabled | true | :developer | false true | false | :disabled | true | :maintainer | false true | false | :disabled | true | :owner | false true | false | :disabled | false | :developer | false true | false | :disabled | false | :maintainer | false true | false | :disabled | false | :owner | false true | false | :enabled | true | :developer | false true | false | :enabled | true | :maintainer | false true | false | :enabled | true | :owner | false true | false | :enabled | false | :developer | false true | false | :enabled | false | :maintainer | false true | false | :enabled | false | :owner | false end def grant_user_access(project, user, access) case access when :developer, :maintainer project.add_user(user, access) when :owner project.namespace.update!(owner: user) end end with_them do let(:project) do if project_setting.nil? project_with_repo else project_with_auto_devops end end before do stub_application_setting(auto_devops_enabled: global_setting) allow_any_instance_of(Repository).to receive(:gitlab_ci_yml).and_return(gitlab_ci_yml) grant_user_access(project, user, user_access) project.project_feature.update_attribute(:builds_access_level, feature_visibilities[builds_visibility]) project.auto_devops.update_attribute(:enabled, project_setting) unless project_setting.nil? end subject { helper.show_auto_devops_implicitly_enabled_banner?(project, user) } it { is_expected.to eq(result) } end end describe '#can_admin_project_member?' do context 'when user is project owner' do before do allow(helper).to receive(:current_user) { project.owner } end it 'returns true for owner of project' do expect(helper.can_admin_project_member?(project)).to eq true end end context 'when user is not a project owner' do using RSpec::Parameterized::TableSyntax where(:user_project_role, :can_admin) do :maintainer | true :developer | false :reporter | false :guest | false end with_them do before do project.add_role(user, user_project_role) allow(helper).to receive(:current_user) { user } end it 'resolves if the user can import members' do expect(helper.can_admin_project_member?(project)).to eq can_admin end end end end describe '#metrics_external_dashboard_url' do context 'metrics_setting exists' do it 'returns external_dashboard_url' do metrics_setting = create(:project_metrics_setting, project: project) expect(helper.metrics_external_dashboard_url).to eq(metrics_setting.external_dashboard_url) end end context 'metrics_setting does not exist' do it 'returns nil' do expect(helper.metrics_external_dashboard_url).to eq(nil) end end end describe '#grafana_integration_url' do subject { helper.grafana_integration_url } it { is_expected.to eq(nil) } context 'grafana integration exists' do let!(:grafana_integration) { create(:grafana_integration, project: project) } it { is_expected.to eq(grafana_integration.grafana_url) } end end describe '#grafana_integration_token' do subject { helper.grafana_integration_masked_token } it { is_expected.to eq(nil) } context 'grafana integration exists' do let!(:grafana_integration) { create(:grafana_integration, project: project) } it { is_expected.to eq(grafana_integration.masked_token) } end end describe '#grafana_integration_enabled?' do subject { helper.grafana_integration_enabled? } it { is_expected.to eq(nil) } context 'grafana integration exists' do let!(:grafana_integration) { create(:grafana_integration, project: project) } it { is_expected.to eq(grafana_integration.enabled) } end end describe '#project_license_name(project)', :request_store do let_it_be(:repository) { project.repository } subject { project_license_name(project) } def license_name project_license_name(project) end context 'gitaly is working appropriately' do let(:license) { Licensee::License.new('mit') } before do expect(repository).to receive(:license).and_return(license) end it 'returns the license name' do expect(subject).to eq(license.name) end it 'memoizes the value' do expect do 2.times { expect(license_name).to eq(license.name) } end.to change { Gitlab::GitalyClient.get_request_count }.by_at_most(1) end end context 'gitaly is unreachable' do shared_examples 'returns nil and tracks exception' do it { is_expected.to be_nil } it 'tracks the exception' do expect(Gitlab::ErrorTracking).to receive(:track_exception).with( an_instance_of(exception) ) subject end it 'memoizes the nil value' do expect do 2.times { expect(license_name).to be_nil } end.to change { Gitlab::GitalyClient.get_request_count }.by_at_most(1) end end before do expect(repository).to receive(:license).and_raise(exception) end context "Gitlab::Git::CommandError" do let(:exception) { Gitlab::Git::CommandError } it_behaves_like 'returns nil and tracks exception' end context "GRPC::Unavailable" do let(:exception) { GRPC::Unavailable } it_behaves_like 'returns nil and tracks exception' end context "GRPC::DeadlineExceeded" do let(:exception) { GRPC::DeadlineExceeded } it_behaves_like 'returns nil and tracks exception' end end end describe '#show_terraform_banner?' do let_it_be(:ruby) { create(:programming_language, name: 'Ruby') } let_it_be(:hcl) { create(:programming_language, name: 'HCL') } subject { helper.show_terraform_banner?(project) } before do create(:repository_language, project: project, programming_language: language, share: 1) end context 'the project does not contain terraform files' do let(:language) { ruby } it { is_expected.to be_falsey } end context 'the project contains terraform files' do let(:language) { hcl } it { is_expected.to be_truthy } context 'the project already has a terraform state' do before do create(:terraform_state, project: project) end it { is_expected.to be_falsey } end context 'the :show_terraform_banner feature flag is disabled' do before do stub_feature_flags(show_terraform_banner: false) end it { is_expected.to be_falsey } end end end describe '#project_title' do subject { helper.project_title(project) } it 'enqueues the elements in the breadcrumb schema list' do expect(helper).to receive(:push_to_schema_breadcrumb).with(project.namespace.name, user_path(project.owner)) expect(helper).to receive(:push_to_schema_breadcrumb).with(project.name, project_path(project)) subject end end describe '#project_permissions_panel_data' do subject { helper.project_permissions_panel_data(project) } before do allow(helper).to receive(:can?) { true } allow(helper).to receive(:current_user).and_return(user) end it 'includes project_permissions_settings' do settings = subject.dig(:currentSettings) expect(settings).to include( packagesEnabled: !!project.packages_enabled, visibilityLevel: project.visibility_level, requestAccessEnabled: !!project.request_access_enabled, issuesAccessLevel: project.project_feature.issues_access_level, repositoryAccessLevel: project.project_feature.repository_access_level, forkingAccessLevel: project.project_feature.forking_access_level, mergeRequestsAccessLevel: project.project_feature.merge_requests_access_level, buildsAccessLevel: project.project_feature.builds_access_level, wikiAccessLevel: project.project_feature.wiki_access_level, snippetsAccessLevel: project.project_feature.snippets_access_level, pagesAccessLevel: project.project_feature.pages_access_level, analyticsAccessLevel: project.project_feature.analytics_access_level, containerRegistryEnabled: !!project.container_registry_enabled, lfsEnabled: !!project.lfs_enabled, emailsDisabled: project.emails_disabled?, metricsDashboardAccessLevel: project.project_feature.metrics_dashboard_access_level, operationsAccessLevel: project.project_feature.operations_access_level, showDefaultAwardEmojis: project.show_default_award_emojis?, securityAndComplianceAccessLevel: project.security_and_compliance_access_level, containerRegistryAccessLevel: project.project_feature.container_registry_access_level ) end end describe '#project_classes' do subject { helper.project_classes(project) } it { is_expected.to be_a(String) } context 'PUC highlighting enabled' do before do project.warn_about_potentially_unwanted_characters = true end it { is_expected.to include('project-highlight-puc') } end context 'PUC highlighting disabled' do before do project.warn_about_potentially_unwanted_characters = false end it { is_expected.not_to include('project-highlight-puc') } end end describe "#delete_confirm_phrase" do subject { helper.delete_confirm_phrase(project) } it 'includes the project path with namespace' do expect(subject).to eq(project.path_with_namespace) end end describe '#fork_button_disabled_tooltip' do using RSpec::Parameterized::TableSyntax subject { helper.fork_button_disabled_tooltip(project) } where(:has_user, :can_fork_project, :can_create_fork, :expected) do false | false | false | nil true | true | true | nil true | false | true | 'You don\'t have permission to fork this project' true | true | false | 'You have reached your project limit' end with_them do before do current_user = user if has_user allow(helper).to receive(:current_user).and_return(current_user) allow(user).to receive(:can?).with(:fork_project, project).and_return(can_fork_project) allow(user).to receive(:can?).with(:create_fork).and_return(can_create_fork) end it 'returns tooltip text when user lacks privilege' do expect(subject).to eq(expected) end end end end
33.203883
589
0.681813
91aa64e46f8947f73fb5780121106850b29a9427
2,669
# mundi_api # # This file was automatically generated by APIMATIC v2.0 # ( https://apimatic.io ). module MundiApi # UpdateSellerRequest Model. class UpdateSellerRequest < BaseModel # Seller name # @return [String] attr_accessor :name # Seller code # @return [String] attr_accessor :code # Seller description # @return [String] attr_accessor :description # Seller document CPF or CNPJ # @return [String] attr_accessor :document # Seller document CPF or CNPJ # @return [String] attr_accessor :status # Seller document CPF or CNPJ # @return [String] attr_accessor :type # Seller document CPF or CNPJ # @return [CreateAddressRequest] attr_accessor :address # Seller document CPF or CNPJ # @return [Array<String, String>] attr_accessor :metadata # A mapping from model property names to API property names. def self.names @_hash = {} if @_hash.nil? @_hash['name'] = 'name' @_hash['code'] = 'code' @_hash['description'] = 'description' @_hash['document'] = 'document' @_hash['status'] = 'status' @_hash['type'] = 'type' @_hash['address'] = 'address' @_hash['metadata'] = 'metadata' @_hash end def initialize(name = nil, code = nil, description = nil, document = nil, status = nil, type = nil, address = nil, metadata = nil) @name = name @code = code @description = description @document = document @status = status @type = type @address = address @metadata = metadata end # Creates an instance of the object from a hash. def self.from_hash(hash) return nil unless hash # Extract variables from the hash. name = hash['name'] code = hash['code'] description = hash['description'] document = hash['document'] status = hash['status'] type = hash['type'] address = CreateAddressRequest.from_hash(hash['address']) if hash['address'] metadata = hash['metadata'] # Create object from extracted values. UpdateSellerRequest.new(name, code, description, document, status, type, address, metadata) end end end
26.69
67
0.520045
ff6799f3544c07ecd1fcb7d079ab7ecc7a4d732b
6,265
# encoding: utf-8 require File.expand_path('../../../spec_helper.rb', __FILE__) describe 'Backup::Syncer::Cloud::CloudFiles' do let(:syncer) do Backup::Syncer::Cloud::CloudFiles.new do |cf| cf.api_key = 'my_api_key' cf.username = 'my_username' cf.container = 'my_container' cf.auth_url = 'my_auth_url' cf.servicenet = true end end it 'should be a subclass of Syncer::Cloud::Base' do Backup::Syncer::Cloud::CloudFiles. superclass.should == Backup::Syncer::Cloud::Base end describe '#initialize' do after { Backup::Syncer::Cloud::CloudFiles.clear_defaults! } it 'should load pre-configured defaults through Syncer::Cloud::Base' do Backup::Syncer::Cloud::CloudFiles.any_instance.expects(:load_defaults!) syncer end it 'should strip any leading slash in path' do syncer = Backup::Syncer::Cloud::CloudFiles.new do |cloud| cloud.path = '/cleaned/path' end syncer.path.should == 'cleaned/path' end context 'when no pre-configured defaults have been set' do it 'should use the values given' do syncer.api_key.should == 'my_api_key' syncer.username.should == 'my_username' syncer.container.should == 'my_container' syncer.auth_url.should == 'my_auth_url' syncer.servicenet.should == true end it 'should use default values if none are given' do syncer = Backup::Syncer::Cloud::CloudFiles.new # from Syncer::Base syncer.path.should == 'backups' syncer.mirror.should == false syncer.directories.should == [] # from Syncer::Cloud::Base syncer.concurrency_type.should == false syncer.concurrency_level.should == 2 syncer.api_key.should == nil syncer.username.should == nil syncer.container.should == nil syncer.auth_url.should == nil syncer.servicenet.should == nil end end # context 'when no pre-configured defaults have been set' context 'when pre-configured defaults have been set' do before do Backup::Syncer::Cloud::CloudFiles.defaults do |cloud| cloud.api_key = 'default_api_key' cloud.username = 'default_username' cloud.container = 'default_container' cloud.auth_url = 'default_auth_url' cloud.servicenet = 'default_servicenet' end end it 'should use pre-configured defaults' do syncer = Backup::Syncer::Cloud::CloudFiles.new # from Syncer::Base syncer.path.should == 'backups' syncer.mirror.should == false syncer.directories.should == [] # from Syncer::Cloud::Base syncer.concurrency_type.should == false syncer.concurrency_level.should == 2 syncer.api_key.should == 'default_api_key' syncer.username.should == 'default_username' syncer.container.should == 'default_container' syncer.auth_url.should == 'default_auth_url' syncer.servicenet.should == 'default_servicenet' end it 'should override pre-configured defaults' do syncer = Backup::Syncer::Cloud::CloudFiles.new do |cloud| cloud.path = 'new_path' cloud.mirror = 'new_mirror' cloud.concurrency_type = 'new_concurrency_type' cloud.concurrency_level = 'new_concurrency_level' cloud.api_key = 'new_api_key' cloud.username = 'new_username' cloud.container = 'new_container' cloud.auth_url = 'new_auth_url' cloud.servicenet = 'new_servicenet' end syncer.path.should == 'new_path' syncer.mirror.should == 'new_mirror' syncer.directories.should == [] syncer.concurrency_type.should == 'new_concurrency_type' syncer.concurrency_level.should == 'new_concurrency_level' syncer.api_key.should == 'new_api_key' syncer.username.should == 'new_username' syncer.container.should == 'new_container' syncer.auth_url.should == 'new_auth_url' syncer.servicenet.should == 'new_servicenet' end end # context 'when pre-configured defaults have been set' end # describe '#initialize' describe '#connection' do let(:connection) { mock } before do Fog::Storage.expects(:new).once.with( :provider => 'Rackspace', :rackspace_username => 'my_username', :rackspace_api_key => 'my_api_key', :rackspace_auth_url => 'my_auth_url', :rackspace_servicenet => true ).returns(connection) end it 'should establish and re-use the connection' do syncer.send(:connection).should == connection syncer.instance_variable_get(:@connection).should == connection syncer.send(:connection).should == connection end end describe '#repository_object' do let(:connection) { mock } let(:directories) { mock } let(:container) { mock } before do syncer.stubs(:connection).returns(connection) connection.stubs(:directories).returns(directories) end context 'when the @container does not exist' do before do directories.expects(:get).once.with('my_container').returns(nil) directories.expects(:create).once.with( :key => 'my_container' ).returns(container) end it 'should create and re-use the container' do syncer.send(:repository_object).should == container syncer.instance_variable_get(:@repository_object).should == container syncer.send(:repository_object).should == container end end context 'when the @container does exist' do before do directories.expects(:get).once.with('my_container').returns(container) directories.expects(:create).never end it 'should retrieve and re-use the container' do syncer.send(:repository_object).should == container syncer.instance_variable_get(:@repository_object).should == container syncer.send(:repository_object).should == container end end end end
34.423077
78
0.631125
267909435efee0c5572d5ca6926bc2125bef3699
6,733
describe Fastlane::Actions::StampChangelogAction do describe 'Stamp CHANGELOG.md with placeholder line action' do let (:changelog_mock_path) { './../spec/fixtures/CHANGELOG_MOCK_PLACEHOLDER_SUPPORT.md' } let (:changelog_mock_path_hook) { './spec/fixtures/CHANGELOG_MOCK_PLACEHOLDER_SUPPORT.md' } # Path to mock CHANGELOG.md with format for placeholders support in [Unreleased] section (https://github.com/dblock/danger-changelog) let (:updated_section_identifier) { '12.34.56' } let (:placeholder_line) { '* Your contribution here.' } before(:each) do @original_content = File.read(changelog_mock_path_hook) end after(:each) do File.open(changelog_mock_path_hook, 'w') { |f| f.write(@original_content) } end it 'rejects to stamp empty [Unreleased] section' do expect(FastlaneCore::UI).to receive(:important).with("WARNING: No changes in [Unreleased] section to stamp!") # Stamp [Unreleased] with given section identifier Fastlane::FastFile.new.parse("lane :test do stamp_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '#{updated_section_identifier}') end").runner.execute(:test) # Try to stamp [Unreleased] section again, while [Unreleased] section is actually empty Fastlane::FastFile.new.parse("lane :test do stamp_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '#{updated_section_identifier}') end").runner.execute(:test) end context "stamps [Unreleased] section with given identifier" do it 'creates a new section identifier with provided identifier' do # Read what's in [Unreleased] read_result = Fastlane::FastFile.new.parse("lane :test do read_changelog(changelog_path: '#{changelog_mock_path}') end").runner.execute(:test) # Stamp [Unreleased] with given section identifier Fastlane::FastFile.new.parse("lane :test do stamp_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '#{updated_section_identifier}') end").runner.execute(:test) # Read updated section post_stamp_read_result = Fastlane::FastFile.new.parse("lane :test do read_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '[#{updated_section_identifier}]') end").runner.execute(:test) expect(read_result).to eq(post_stamp_read_result) end it 'creates an empty [Unreleased] section' do # Stamp [Unreleased] with given section identifier Fastlane::FastFile.new.parse("lane :test do stamp_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '#{updated_section_identifier}') end").runner.execute(:test) # Read what's in [Unreleased] read_result = Fastlane::FastFile.new.parse("lane :test do read_changelog(changelog_path: '#{changelog_mock_path}') end").runner.execute(:test) expect(read_result).to eq("") end it 'excludes placeholder line' do # Stamp [Unreleased] with given section identifier and excludes placeholder line Fastlane::FastFile.new.parse("lane :test do stamp_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '#{updated_section_identifier}', placeholder_line: '#{placeholder_line}') end").runner.execute(:test) # Read updated section post_stamp_read_result = Fastlane::FastFile.new.parse("lane :test do read_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '[#{updated_section_identifier}]') end").runner.execute(:test) expect(post_stamp_read_result).to eq("Added\n* New awesome feature.\n* New amazing feature") end it 'adds placeholder line to [Unreleased] section after stamping' do # Stamp [Unreleased] with given section identifier and provided placeholder line Fastlane::FastFile.new.parse("lane :test do stamp_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '#{updated_section_identifier}', placeholder_line: '#{placeholder_line}') end").runner.execute(:test) # Read updated section read_result = Fastlane::FastFile.new.parse("lane :test do read_changelog(changelog_path: '#{changelog_mock_path}') end").runner.execute(:test) expect(read_result).to eq("* Your contribution here.") end # Combination of the 2 above tests it '1. excludes placeholder line in stamped section and 2. adds placeholder line into [Unreleased] section' do # Stamp [Unreleased] with given section identifier and excludes placeholder line Fastlane::FastFile.new.parse("lane :test do stamp_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '#{updated_section_identifier}', placeholder_line: '#{placeholder_line}') end").runner.execute(:test) # Read updated section stamped_section_read_result = Fastlane::FastFile.new.parse("lane :test do read_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '[#{updated_section_identifier}]') end").runner.execute(:test) unreleased_section_read_result = Fastlane::FastFile.new.parse("lane :test do read_changelog(changelog_path: '#{changelog_mock_path}') end").runner.execute(:test) expect(stamped_section_read_result).to eq("Added\n* New awesome feature.\n* New amazing feature") expect(stamped_section_read_result =~ /^#{placeholder_line}/).to be_falsey expect(unreleased_section_read_result).to eq("* Your contribution here.") end end it 'creates tags comparion GitHub link without prefix' do # Stamp [Unreleased] with given section identifier Fastlane::FastFile.new.parse("lane :test do stamp_changelog(changelog_path: '#{changelog_mock_path}', section_identifier: '3.11.1', git_tag: '3.11.1') end").runner.execute(:test) modified_file = File.read(changelog_mock_path_hook) expect(modified_file.lines.last).to eq("[3.11.1]: https://github.com/olivierlacan/keep-a-changelog/compare/3.11.0...3.11.1\n") end end end
48.092857
229
0.650527
4a8d3dc11c8a6c86a6f5bc8e3f1166211cbbd70e
688
require 'oj' unless defined?(::Oj) require 'multi_json/adapter' module MultiJson module Adapters # Use the Oj library to dump/load. class Oj < Adapter defaults :load, :mode => :strict defaults :dump, :mode => :compat, :time_format => :ruby ParseError = if defined?(::Oj::ParseError) ::Oj::ParseError else SyntaxError end def load(string, options={}) options[:symbol_keys] = true if options.delete(:symbolize_keys) ::Oj.load(string, options) end def dump(object, options={}) options.merge!(:indent => 2) if options[:pretty] ::Oj.dump(object, options) end end end end
23.724138
71
0.601744
21617d2e6092af17e5e66434d338cea95d224418
3,793
providers = Puppet::Util::Reference.newreference :providers, :title => "Provider Suitability Report", :depth => 1, :dynamic => true, :doc => "Which providers are valid for this machine" do types = [] Puppet::Type.loadall Puppet::Type.eachtype do |klass| next unless klass.providers.length > 0 types << klass end types.sort! { |a,b| a.name.to_s <=> b.name.to_s } command_line = Puppet::Util::CommandLine.new types.reject! { |type| ! command_line.args.include?(type.name.to_s) } unless command_line.args.empty? ret = "Details about this host:\n\n" # Throw some facts in there, so we know where the report is from. ["Ruby Version", "Puppet Version", "Operating System", "Operating System Release"].each do |label| name = label.gsub(/\s+/, '') value = Facter.value(name) ret << option(label, value) end ret << "\n" count = 1 # Produce output for each type. types.each do |type| features = type.features ret << "\n" # add a trailing newline # Now build up a table of provider suitability. headers = %w{Provider Suitable?} + features.collect { |f| f.to_s }.sort table_data = {} functional = false notes = [] default = type.defaultprovider ? type.defaultprovider.name : 'none' type.providers.sort { |a,b| a.to_s <=> b.to_s }.each do |pname| data = [] table_data[pname] = data provider = type.provider(pname) # Add the suitability note if missing = provider.suitable?(false) and missing.empty? data << "*X*" suit = true functional = true else data << "[#{count}]_" # A pointer to the appropriate footnote suit = false end # Add a footnote with the details about why this provider is unsuitable, if that's the case unless suit details = ".. [#{count}]\n" missing.each do |test, values| case test when :exists details << " - Missing files #{values.join(", ")}\n" when :variable values.each do |name, facts| if Puppet.settings.valid?(name) details << " - Setting #{name} (currently #{Puppet.settings.value(name).inspect}) not in list #{facts.join(", ")}\n" else details << " - Fact #{name} (currently #{Facter.value(name).inspect}) not in list #{facts.join(", ")}\n" end end when :true details << " - Got #{values} true tests that should have been false\n" when :false details << " - Got #{values} false tests that should have been true\n" when :feature details << " - Missing features #{values.collect { |f| f.to_s }.join(",")}\n" end end notes << details count += 1 end # Add a note for every feature features.each do |feature| if provider.features.include?(feature) data << "*X*" else data << "" end end end ret << markdown_header(type.name.to_s + "_", 2) ret << "[#{type.name}](https://docs.puppetlabs.com/puppet/latest/reference/type.html##{type.name})\n\n" ret << option("Default provider", default) ret << doctable(headers, table_data) notes.each do |note| ret << note + "\n" end ret << "\n" end ret << "\n" ret end providers.header = " Puppet resource types are usually backed by multiple implementations called `providers`, which handle variance between platforms and tools. Different providers are suitable or unsuitable on different platforms based on things like the presence of a given tool. Here are all of the provider-backed types and their different providers. Any unmentioned types do not use providers yet. "
31.87395
188
0.601898
bff02796bff7810ca78f5310e54dfff2fca008ee
26,026
require File.join(File.dirname(__FILE__), 'base') require File.join(File.dirname(__FILE__), 'redis') require File.join(File.dirname(__FILE__), 'socket') require File.join(File.dirname(__FILE__), 'sandbox') module Sensu class Server include Utilities attr_reader :is_master def self.run(options={}) server = self.new(options) EM::run do server.start server.trap_signals end end def initialize(options={}) base = Base.new(options) @logger = base.logger @settings = base.settings @extensions = base.extensions base.setup_process @timers = Array.new @master_timers = Array.new @handlers_in_progress_count = 0 @is_master = false end def setup_redis @logger.debug('connecting to redis', { :settings => @settings[:redis] }) @redis = Redis.connect(@settings[:redis]) @redis.on_error do |error| @logger.fatal('redis connection error', { :error => error.to_s }) stop end @redis.before_reconnect do unless testing? @logger.warn('reconnecting to redis') pause end end @redis.after_reconnect do @logger.info('reconnected to redis') resume end end def setup_rabbitmq @logger.debug('connecting to rabbitmq', { :settings => @settings[:rabbitmq] }) @rabbitmq = RabbitMQ.connect(@settings[:rabbitmq]) @rabbitmq.on_error do |error| @logger.fatal('rabbitmq connection error', { :error => error.to_s }) stop end @rabbitmq.before_reconnect do unless testing? @logger.warn('reconnecting to rabbitmq') pause end end @rabbitmq.after_reconnect do @logger.info('reconnected to rabbitmq') @amq.prefetch(1) resume end @amq = @rabbitmq.channel @amq.prefetch(1) end def setup_keepalives @logger.debug('subscribing to keepalives') @keepalive_queue = @amq.queue!('keepalives') @keepalive_queue.bind(@amq.direct('keepalives')) @keepalive_queue.subscribe(:ack => true) do |header, payload| client = Oj.load(payload) @logger.debug('received keepalive', { :client => client }) @redis.set('client:' + client[:name], Oj.dump(client)) do @redis.sadd('clients', client[:name]) do header.ack end end end end def action_subdued?(check, handler=nil) subdue = false subdue_at = handler ? 'handler' : 'publisher' conditions = Array.new if check[:subdue] conditions << check[:subdue] end if handler && handler[:subdue] conditions << handler[:subdue] end conditions.each do |condition| if condition.has_key?(:begin) && condition.has_key?(:end) begin_time = Time.parse(condition[:begin]) end_time = Time.parse(condition[:end]) if end_time < begin_time if Time.now < end_time begin_time = Time.parse('12:00:00 AM') else end_time = Time.parse('11:59:59 PM') end end if Time.now >= begin_time && Time.now <= end_time subdue = true end end if condition.has_key?(:days) days = condition[:days].map(&:downcase) if days.include?(Time.now.strftime('%A').downcase) subdue = true end end if subdue && condition.has_key?(:exceptions) subdue = condition[:exceptions].none? do |exception| Time.now >= Time.parse(exception[:begin]) && Time.now <= Time.parse(exception[:end]) end end if subdue if subdue_at == (condition[:at] || 'handler') break else subdue = false end end end subdue end def filter_attributes_match?(hash_one, hash_two) hash_one.keys.all? do |key| case when hash_one[key] == hash_two[key] true when hash_one[key].is_a?(Hash) && hash_two[key].is_a?(Hash) filter_attributes_match?(hash_one[key], hash_two[key]) when hash_one[key].is_a?(String) && hash_one[key].start_with?('eval:') begin expression = hash_one[key].gsub(/^eval:(\s+)?/, '') !!Sandbox.eval(expression, hash_two[key]) rescue false end else false end end end def event_filtered?(filter_name, event) if @settings.filter_exists?(filter_name) filter = @settings[:filters][filter_name] matched = filter_attributes_match?(filter[:attributes], event) filter[:negate] ? matched : !matched else @logger.error('unknown filter', { :filter_name => filter_name }) false end end def derive_handlers(handler_list) handler_list.inject(Array.new) do |handlers, handler_name| if @settings.handler_exists?(handler_name) handler = @settings[:handlers][handler_name].merge(:name => handler_name) if handler[:type] == 'set' handlers = handlers + derive_handlers(handler[:handlers]) else handlers << handler end elsif @extensions.handler_exists?(handler_name) handlers << @extensions[:handlers][handler_name] else @logger.error('unknown handler', { :handler_name => handler_name }) end handlers.uniq end end def event_handlers(event) handler_list = Array((event[:check][:handlers] || event[:check][:handler]) || 'default') handlers = derive_handlers(handler_list) event_severity = SEVERITIES[event[:check][:status]] || 'unknown' handlers.select do |handler| if event[:action] == :flapping && !handler[:handle_flapping] @logger.info('handler does not handle flapping events', { :event => event, :handler => handler }) next end if action_subdued?(event[:check], handler) @logger.info('action is subdued', { :event => event, :handler => handler }) next end if handler.has_key?(:severities) && !handler[:severities].include?(event_severity) unless event[:action] == :resolve @logger.debug('handler does not handle event severity', { :event => event, :handler => handler }) next end end if handler.has_key?(:filters) || handler.has_key?(:filter) filter_list = Array(handler[:filters] || handler[:filter]) filtered = filter_list.any? do |filter_name| event_filtered?(filter_name, event) end if filtered @logger.info('event filtered for handler', { :event => event, :handler => handler }) next end end true end end def execute_command(command, data=nil, on_error=nil, &block) on_error ||= Proc.new do |error| @logger.error('failed to execute command', { :command => command, :data => data, :error => error.to_s }) end execute = Proc.new do begin output, status = IO.popen(command, 'r+') do |child| unless data.nil? child.write(data.to_s) end child.close_write end [true, output, status] rescue => error on_error.call(error) [false, nil, nil] end end complete = Proc.new do |success, output, status| if success block.call(output, status) end end EM::defer(execute, complete) end def mutate_event_data(mutator_name, event, &block) case when mutator_name.nil? block.call(Oj.dump(event)) when @settings.mutator_exists?(mutator_name) mutator = @settings[:mutators][mutator_name] on_error = Proc.new do |error| @logger.error('mutator error', { :event => event, :mutator => mutator, :error => error.to_s }) end execute_command(mutator[:command], Oj.dump(event), on_error) do |output, status| if status == 0 block.call(output) else on_error.call('non-zero exit status (' + status.to_s + '): ' + output) end end when @extensions.mutator_exists?(mutator_name) extension = @extensions[:mutators][mutator_name] extension.run(event, @settings.to_hash) do |output, status| if status == 0 block.call(output) else @logger.error('mutator error', { :event => event, :extension => extension, :error => 'non-zero exit status (' + status.to_s + '): ' + output }) end end else @logger.error('unknown mutator', { :mutator_name => mutator_name }) end end def handle_event(event) handlers = event_handlers(event) handlers.each do |handler| log_level = event[:check][:type] == 'metric' ? :debug : :info @logger.send(log_level, 'handling event', { :event => event, :handler => handler }) @handlers_in_progress_count += 1 on_error = Proc.new do |error| @logger.error('handler error', { :event => event, :handler => handler, :error => error.to_s }) @handlers_in_progress_count -= 1 end mutate_event_data(handler[:mutator], event) do |event_data| case handler[:type] when 'pipe' execute_command(handler[:command], event_data, on_error) do |output, status| output.split(/\n+/).each do |line| @logger.info(line) end @handlers_in_progress_count -= 1 end when 'tcp' begin EM::connect(handler[:socket][:host], handler[:socket][:port], SocketHandler) do |socket| socket.on_success = Proc.new do @handlers_in_progress_count -= 1 end socket.on_error = on_error timeout = handler[:socket][:timeout] || 10 socket.pending_connect_timeout = timeout socket.comm_inactivity_timeout = timeout socket.send_data(event_data.to_s) socket.close_connection_after_writing end rescue => error on_error.call(error) end when 'udp' begin EM::open_datagram_socket('127.0.0.1', 0, nil) do |socket| socket.send_datagram(event_data.to_s, handler[:socket][:host], handler[:socket][:port]) socket.close_connection_after_writing @handlers_in_progress_count -= 1 end rescue => error on_error.call(error) end when 'amqp' exchange_name = handler[:exchange][:name] exchange_type = handler[:exchange].has_key?(:type) ? handler[:exchange][:type].to_sym : :direct exchange_options = handler[:exchange].reject do |key, value| [:name, :type].include?(key) end unless event_data.empty? @amq.method(exchange_type).call(exchange_name, exchange_options).publish(event_data) end @handlers_in_progress_count -= 1 when 'extension' handler.run(event_data, @settings.to_hash) do |output, status| output.split(/\n+/).each do |line| @logger.info(line) end @handlers_in_progress_count -= 1 end end end end end def aggregate_result(result) @logger.debug('adding result to aggregate', { :result => result }) check = result[:check] result_set = check[:name] + ':' + check[:issued].to_s @redis.hset('aggregation:' + result_set, result[:client], Oj.dump( :output => check[:output], :status => check[:status] )) do SEVERITIES.each do |severity| @redis.hsetnx('aggregate:' + result_set, severity, 0) end severity = (SEVERITIES[check[:status]] || 'unknown') @redis.hincrby('aggregate:' + result_set, severity, 1) do @redis.hincrby('aggregate:' + result_set, 'total', 1) do @redis.sadd('aggregates:' + check[:name], check[:issued]) do @redis.sadd('aggregates', check[:name]) end end end end end def process_result(result) @logger.debug('processing result', { :result => result }) @redis.get('client:' + result[:client]) do |client_json| unless client_json.nil? client = Oj.load(client_json) check = case when @settings.check_exists?(result[:check][:name]) @settings[:checks][result[:check][:name]].merge(result[:check]) else result[:check] end if check[:aggregate] aggregate_result(result) end @redis.sadd('history:' + client[:name], check[:name]) history_key = 'history:' + client[:name] + ':' + check[:name] @redis.rpush(history_key, check[:status]) do execution_key = 'execution:' + client[:name] + ':' + check[:name] @redis.set(execution_key, check[:executed]) @redis.lrange(history_key, -21, -1) do |history| check[:history] = history total_state_change = 0 unless history.size < 21 state_changes = 0 change_weight = 0.8 previous_status = history.first history.each do |status| unless status == previous_status state_changes += change_weight end change_weight += 0.02 previous_status = status end total_state_change = (state_changes.fdiv(20) * 100).to_i @redis.ltrim(history_key, -21, -1) end @redis.hget('events:' + client[:name], check[:name]) do |event_json| previous_occurrence = event_json ? Oj.load(event_json) : false is_flapping = false if check.has_key?(:low_flap_threshold) && check.has_key?(:high_flap_threshold) was_flapping = previous_occurrence ? previous_occurrence[:flapping] : false is_flapping = case when total_state_change >= check[:high_flap_threshold] true when was_flapping && total_state_change <= check[:low_flap_threshold] false else was_flapping end end event = { :client => client, :check => check, :occurrences => 1 } if check[:status] != 0 || is_flapping if previous_occurrence && check[:status] == previous_occurrence[:status] event[:occurrences] = previous_occurrence[:occurrences] + 1 end @redis.hset('events:' + client[:name], check[:name], Oj.dump( :output => check[:output], :status => check[:status], :issued => check[:issued], :handlers => Array((check[:handlers] || check[:handler]) || 'default'), :flapping => is_flapping, :occurrences => event[:occurrences] )) do unless check[:handle] == false event[:action] = is_flapping ? :flapping : :create handle_event(event) end end elsif previous_occurrence unless check[:auto_resolve] == false && !check[:force_resolve] @redis.hdel('events:' + client[:name], check[:name]) do unless check[:handle] == false event[:occurrences] = previous_occurrence[:occurrences] event[:action] = :resolve handle_event(event) end end end elsif check[:type] == 'metric' handle_event(event) end end end end end end end def setup_results @logger.debug('subscribing to results') @result_queue = @amq.queue!('results') @result_queue.bind(@amq.direct('results')) @result_queue.subscribe(:ack => true) do |header, payload| result = Oj.load(payload) @logger.debug('received result', { :result => result }) process_result(result) EM::next_tick do header.ack end end end def publish_check_request(check) payload = { :name => check[:name], :issued => Time.now.to_i } if check.has_key?(:command) payload[:command] = check[:command] end @logger.info('publishing check request', { :payload => payload, :subscribers => check[:subscribers] }) check[:subscribers].each do |exchange_name| @amq.fanout(exchange_name).publish(Oj.dump(payload)) end end def schedule_checks(checks) check_count = 0 stagger = testing? ? 0 : 2 checks.each do |check| check_count += 1 scheduling_delay = stagger * check_count % 30 @master_timers << EM::Timer.new(scheduling_delay) do interval = testing? ? 0.5 : check[:interval] @master_timers << EM::PeriodicTimer.new(interval) do unless action_subdued?(check) publish_check_request(check) else @logger.info('check request was subdued', { :check => check }) end end end end end def setup_publisher @logger.debug('scheduling check requests') standard_checks = @settings.checks.reject do |check| check[:standalone] || check[:publish] == false end extension_checks = @extensions.checks.reject do |check| check[:standalone] || check[:publish] == false || !check[:interval].is_a?(Integer) end schedule_checks(standard_checks + extension_checks) end def publish_result(client, check) payload = { :client => client[:name], :check => check } @logger.info('publishing check result', { :payload => payload }) @amq.direct('results').publish(Oj.dump(payload)) end def determine_stale_clients @logger.info('determining stale clients') @redis.smembers('clients') do |clients| clients.each do |client_name| @redis.get('client:' + client_name) do |client_json| client = Oj.load(client_json) check = { :name => 'keepalive', :issued => Time.now.to_i, :executed => Time.now.to_i } time_since_last_keepalive = Time.now.to_i - client[:timestamp] case when time_since_last_keepalive >= 180 check[:output] = 'No keep-alive sent from client in over 180 seconds' check[:status] = 2 when time_since_last_keepalive >= 120 check[:output] = 'No keep-alive sent from client in over 120 seconds' check[:status] = 1 else check[:output] = 'Keep-alive sent from client less than 120 seconds ago' check[:status] = 0 end publish_result(client, check) end end end end def setup_client_monitor @logger.debug('monitoring clients') @master_timers << EM::PeriodicTimer.new(30) do determine_stale_clients end end def prune_aggregations @logger.info('pruning aggregations') @redis.smembers('aggregates') do |checks| checks.each do |check_name| @redis.smembers('aggregates:' + check_name) do |aggregates| if aggregates.size > 20 aggregates.sort! aggregates.take(aggregates.size - 20).each do |check_issued| @redis.srem('aggregates:' + check_name, check_issued) do result_set = check_name + ':' + check_issued.to_s @redis.del('aggregate:' + result_set) do @redis.del('aggregation:' + result_set) do @logger.debug('pruned aggregation', { :check => { :name => check_name, :issued => check_issued } }) end end end end end end end end end def setup_aggregation_pruner @logger.debug('pruning aggregations') @master_timers << EM::PeriodicTimer.new(20) do prune_aggregations end end def master_duties setup_publisher setup_client_monitor setup_aggregation_pruner end def request_master_election @redis.setnx('lock:master', Time.now.to_i) do |created| if created @is_master = true @logger.info('i am the master') master_duties else @redis.get('lock:master') do |timestamp| if Time.now.to_i - timestamp.to_i >= 60 @redis.getset('lock:master', Time.now.to_i) do |previous| if previous == timestamp @is_master = true @logger.info('i am now the master') master_duties end end end end end end end def setup_master_monitor request_master_election @timers << EM::PeriodicTimer.new(20) do if @is_master @redis.set('lock:master', Time.now.to_i) do @logger.debug('updated master lock timestamp') end else request_master_election end end end def resign_as_master(&block) block ||= Proc.new {} if @is_master @logger.warn('resigning as master') @master_timers.each do |timer| timer.cancel end @master_timers.clear if @redis.connected? @redis.del('lock:master') do @logger.info('removed master lock') @is_master = false end end timestamp = Time.now.to_i retry_until_true do if !@is_master block.call true elsif Time.now.to_i - timestamp >= 3 @logger.warn('failed to remove master lock') @is_master = false block.call true end end else @logger.debug('not currently master') block.call end end def unsubscribe @logger.warn('unsubscribing from keepalive and result queues') if @rabbitmq.connected? @keepalive_queue.unsubscribe @result_queue.unsubscribe @amq.recover else @keepalive_queue.before_recovery do @keepalive_queue.unsubscribe end @result_queue.before_recovery do @result_queue.unsubscribe end end end def complete_handlers_in_progress(&block) @logger.info('completing handlers in progress', { :handlers_in_progress_count => @handlers_in_progress_count }) retry_until_true do if @handlers_in_progress_count == 0 block.call true end end end def bootstrap setup_keepalives setup_results setup_master_monitor @state = :running end def start setup_redis setup_rabbitmq bootstrap end def pause(&block) unless @state == :pausing || @state == :paused @state = :pausing @timers.each do |timer| timer.cancel end @timers.clear unsubscribe resign_as_master do @state = :paused if block block.call end end end end def resume retry_until_true(1) do if @state == :paused if @redis.connected? && @rabbitmq.connected? bootstrap true end end end end def stop @logger.warn('stopping') @state = :stopping pause do complete_handlers_in_progress do @extensions.stop_all do @redis.close @rabbitmq.close @logger.warn('stopping reactor') EM::stop_event_loop end end end end def trap_signals @signals = Array.new STOP_SIGNALS.each do |signal| Signal.trap(signal) do @signals << signal end end EM::PeriodicTimer.new(1) do signal = @signals.shift if STOP_SIGNALS.include?(signal) @logger.warn('received signal', { :signal => signal }) stop end end end end end
31.432367
107
0.531853
1c02b736f21622b06c4a87045f62ee15f6c9e4da
5,282
=begin #Hydrogen Integration API #The Hydrogen Integration API OpenAPI spec version: 1.3.1 Contact: info@hydrogenplatform.com Generated by: https://github.com/swagger-api/swagger-codegen.git Swagger Codegen version: 2.4.21 =end require 'date' module IntegrationApi class UpdateBaasClientCO attr_accessor :nucleus_document_ids # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { :'nucleus_document_ids' => :'nucleus_document_ids' } end # Attribute type mapping. def self.swagger_types { :'nucleus_document_ids' => :'Array<String>' } end # Initializes the object # @param [Hash] attributes Model attributes in the form of hash def initialize(attributes = {}) return unless attributes.is_a?(Hash) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } if attributes.has_key?(:'nucleus_document_ids') if (value = attributes[:'nucleus_document_ids']).is_a?(Array) self.nucleus_document_ids = value end end end # Show invalid properties with the reasons. Usually used together with valid? # @return Array for valid properties with the reasons def list_invalid_properties invalid_properties = Array.new invalid_properties end # Check to see if the all the properties in the model are valid # @return true if the model is valid def valid? true end # Checks equality by comparing each attribute. # @param [Object] Object to be compared def ==(o) return true if self.equal?(o) self.class == o.class && nucleus_document_ids == o.nucleus_document_ids end # @see the `==` method # @param [Object] Object to be compared def eql?(o) self == o end # Calculates hash code according to all attributes. # @return [Fixnum] Hash code def hash [nucleus_document_ids].hash end # Builds the object from hash # @param [Hash] attributes Model attributes in the form of hash # @return [Object] Returns the model itself def build_from_hash(attributes) self.class.swagger_types.each_pair do |key, type| if type =~ /\AArray<(.*)>/i # check to ensure the input is an array given that the attribute # is documented as an array but the input is not if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map { |v| _deserialize($1, v) }) end elsif !attributes[self.class.attribute_map[key]].nil? self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) end # or else data not found in attributes(hash), not an issue as the data can be optional end self end # Deserializes the data based on type # @param string type Data type # @param string value Value to be deserialized # @return [Object] Deserialized data def _deserialize(type, value) case type.to_sym when :DateTime value when :Date value when :String value.to_s when :Integer value.to_i when :Float value.to_f when :BOOLEAN if value.to_s =~ /\A(true|t|yes|y|1)\z/i true else false end when :Object # generic object (usually a Hash), return directly value when /\AArray<(?<inner_type>.+)>\z/ inner_type = Regexp.last_match[:inner_type] value.map { |v| _deserialize(inner_type, v) } when /\AHash<(?<k_type>.+?), (?<v_type>.+)>\z/ k_type = Regexp.last_match[:k_type] v_type = Regexp.last_match[:v_type] {}.tap do |hash| value.each do |k, v| hash[_deserialize(k_type, k)] = _deserialize(v_type, v) end end else # model temp_model = IntegrationApi.const_get(type).new temp_model.build_from_hash(value) end end # Returns the string representation of the object # @return [String] String presentation of the object def to_s to_hash.to_s end # to_body is an alias to to_hash (backward compatibility) # @return [Hash] Returns the object in the form of hash def to_body to_hash end # Returns the object in the form of hash # @return [Hash] Returns the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |attr, param| value = self.send(attr) hash[param] = _to_hash(value) end hash end # Outputs non-array value in the form of hash # For object, use to_hash. Otherwise, just return the value # @param [Object] value Any valid value # @return [Hash] Returns the value in the form of hash def _to_hash(value) if value.is_a?(Array) value.compact.map { |v| _to_hash(v) } elsif value.is_a?(Hash) {}.tap do |hash| value.each { |k, v| hash[k] = _to_hash(v) } end elsif value.respond_to? :to_hash value.to_hash else value end end end end
28.706522
107
0.62571
6a54054badc8b05a3059edc49d09880f9c21111a
10,874
# frozen_string_literal: true class ProjectPresenter < Gitlab::View::Presenter::Delegated include ActionView::Helpers::NumberHelper include ActionView::Helpers::UrlHelper include GitlabRoutingHelper include StorageHelper include TreeHelper include ChecksCollaboration include Gitlab::Utils::StrongMemoize presents :project AnchorData = Struct.new(:enabled, :label, :link, :class_modifier) MAX_TAGS_TO_SHOW = 3 def statistics_anchors(show_auto_devops_callout:) [ readme_anchor_data, changelog_anchor_data, contribution_guide_anchor_data, files_anchor_data, commits_anchor_data, branches_anchor_data, tags_anchor_data, gitlab_ci_anchor_data, autodevops_anchor_data(show_auto_devops_callout: show_auto_devops_callout), kubernetes_cluster_anchor_data ].compact.select { |item| item.enabled } end def statistics_buttons(show_auto_devops_callout:) [ readme_anchor_data, changelog_anchor_data, contribution_guide_anchor_data, autodevops_anchor_data(show_auto_devops_callout: show_auto_devops_callout), kubernetes_cluster_anchor_data, gitlab_ci_anchor_data, koding_anchor_data ].compact.reject { |item| item.enabled } end def empty_repo_statistics_anchors [ files_anchor_data, commits_anchor_data, branches_anchor_data, tags_anchor_data, autodevops_anchor_data, kubernetes_cluster_anchor_data ].compact.select { |item| item.enabled } end def empty_repo_statistics_buttons [ new_file_anchor_data, readme_anchor_data, autodevops_anchor_data, kubernetes_cluster_anchor_data ].compact.reject { |item| item.enabled } end def default_view return anonymous_project_view unless current_user user_view = current_user.project_view if can?(current_user, :download_code, project) user_view elsif user_view == "activity" "activity" elsif can?(current_user, :read_wiki, project) "wiki" elsif feature_available?(:issues, current_user) "projects/issues/issues" else "customize_workflow" end end def readme_path filename_path(:readme) end def changelog_path filename_path(:changelog) end def license_path filename_path(:license_blob) end def ci_configuration_path filename_path(:gitlab_ci_yml) end def contribution_guide_path if project && contribution_guide = repository.contribution_guide project_blob_path( project, tree_join(project.default_branch, contribution_guide.name) ) end end def add_license_path add_special_file_path(file_name: 'LICENSE') end def add_changelog_path add_special_file_path(file_name: 'CHANGELOG') end def add_contribution_guide_path add_special_file_path(file_name: 'CONTRIBUTING.md', commit_message: 'Add contribution guide') end def add_ci_yml_path add_special_file_path(file_name: '.gitlab-ci.yml') end def add_readme_path add_special_file_path(file_name: 'README.md') end def add_koding_stack_path project_new_blob_path( project, default_branch || 'master', file_name: '.koding.yml', commit_message: "Add Koding stack script", content: <<-CONTENT.strip_heredoc provider: aws: access_key: '${var.aws_access_key}' secret_key: '${var.aws_secret_key}' resource: aws_instance: #{project.path}-vm: instance_type: t2.nano user_data: |- # Created by GitLab UI for :> echo _KD_NOTIFY_@Installing Base packages...@ apt-get update -y apt-get install git -y echo _KD_NOTIFY_@Cloning #{project.name}...@ export KODING_USER=${var.koding_user_username} export REPO_URL=#{root_url}${var.koding_queryString_repo}.git export BRANCH=${var.koding_queryString_branch} sudo -i -u $KODING_USER git clone $REPO_URL -b $BRANCH echo _KD_NOTIFY_@#{project.name} cloned.@ CONTENT ) end def license_short_name license = repository.license license&.nickname || license&.name || 'LICENSE' end def can_current_user_push_code? strong_memoize(:can_current_user_push_code) do if empty_repo? can?(current_user, :push_code, project) else can_current_user_push_to_branch?(default_branch) end end end def can_current_user_push_to_branch?(branch) user_access(project).can_push_to_branch?(branch) end def can_current_user_push_to_default_branch? can_current_user_push_to_branch?(default_branch) end def files_anchor_data AnchorData.new(true, _('Files (%{human_size})') % { human_size: storage_counter(statistics.total_repository_size) }, empty_repo? ? nil : project_tree_path(project)) end def commits_anchor_data AnchorData.new(true, n_('Commit (%{commit_count})', 'Commits (%{commit_count})', statistics.commit_count) % { commit_count: number_with_delimiter(statistics.commit_count) }, empty_repo? ? nil : project_commits_path(project, repository.root_ref)) end def branches_anchor_data AnchorData.new(true, n_('Branch (%{branch_count})', 'Branches (%{branch_count})', repository.branch_count) % { branch_count: number_with_delimiter(repository.branch_count) }, empty_repo? ? nil : project_branches_path(project)) end def tags_anchor_data AnchorData.new(true, n_('Tag (%{tag_count})', 'Tags (%{tag_count})', repository.tag_count) % { tag_count: number_with_delimiter(repository.tag_count) }, empty_repo? ? nil : project_tags_path(project)) end def new_file_anchor_data if current_user && can_current_user_push_to_default_branch? AnchorData.new(false, _('New file'), project_new_blob_path(project, default_branch || 'master'), 'new') end end def readme_anchor_data if current_user && can_current_user_push_to_default_branch? && repository.readme.nil? AnchorData.new(false, _('Add Readme'), add_readme_path) elsif repository.readme AnchorData.new(true, _('Readme'), default_view != 'readme' ? readme_path : '#readme') end end def changelog_anchor_data if current_user && can_current_user_push_to_default_branch? && repository.changelog.blank? AnchorData.new(false, _('Add Changelog'), add_changelog_path) elsif repository.changelog.present? AnchorData.new(true, _('Changelog'), changelog_path) end end def license_anchor_data if repository.license_blob.present? AnchorData.new(true, license_short_name, license_path) else if current_user && can_current_user_push_to_default_branch? AnchorData.new(false, _('Add license'), add_license_path) else AnchorData.new(false, _('No license. All rights reserved'), nil) end end end def contribution_guide_anchor_data if current_user && can_current_user_push_to_default_branch? && repository.contribution_guide.blank? AnchorData.new(false, _('Add Contribution guide'), add_contribution_guide_path) elsif repository.contribution_guide.present? AnchorData.new(true, _('Contribution guide'), contribution_guide_path) end end def autodevops_anchor_data(show_auto_devops_callout: false) if current_user && can?(current_user, :admin_pipeline, project) && repository.gitlab_ci_yml.blank? && !show_auto_devops_callout AnchorData.new(auto_devops_enabled?, auto_devops_enabled? ? _('Auto DevOps enabled') : _('Enable Auto DevOps'), project_settings_ci_cd_path(project, anchor: 'autodevops-settings')) elsif auto_devops_enabled? AnchorData.new(true, _('Auto DevOps enabled'), nil) end end def kubernetes_cluster_anchor_data if current_user && can?(current_user, :create_cluster, project) cluster_link = clusters.count == 1 ? project_cluster_path(project, clusters.first) : project_clusters_path(project) if clusters.empty? cluster_link = new_project_cluster_path(project) end AnchorData.new(!clusters.empty?, clusters.empty? ? _('Add Kubernetes cluster') : _('Kubernetes configured'), cluster_link) end end def gitlab_ci_anchor_data if current_user && can_current_user_push_code? && repository.gitlab_ci_yml.blank? && !auto_devops_enabled? AnchorData.new(false, _('Set up CI/CD'), add_ci_yml_path) elsif repository.gitlab_ci_yml.present? AnchorData.new(true, _('CI/CD configuration'), ci_configuration_path) end end def koding_anchor_data if current_user && can_current_user_push_code? && koding_enabled? && repository.koding_yml.blank? AnchorData.new(false, _('Set up Koding'), add_koding_stack_path) end end def tags_to_show project.tag_list.take(MAX_TAGS_TO_SHOW) end def count_of_extra_tags_not_shown if project.tag_list.count > MAX_TAGS_TO_SHOW project.tag_list.count - MAX_TAGS_TO_SHOW else 0 end end def has_extra_tags? count_of_extra_tags_not_shown > 0 end private def filename_path(filename) if blob = repository.public_send(filename) # rubocop:disable GitlabSecurity/PublicSend project_blob_path( project, tree_join(default_branch, blob.name) ) end end def anonymous_project_view if !project.empty_repo? && can?(current_user, :download_code, project) 'files' else 'activity' end end def add_special_file_path(file_name:, commit_message: nil, branch_name: nil) commit_message ||= s_("CommitMessage|Add %{file_name}") % { file_name: file_name } project_new_blob_path( project, project.default_branch || 'master', file_name: file_name, commit_message: commit_message, branch_name: branch_name ) end def koding_enabled? Gitlab::CurrentSettings.koding_enabled? end end
29.309973
172
0.656428
1d4732387cf7bec6694067ff4846d9f9848cc511
1,515
module ApplicationHelper def current_func_selector(current_func, target_func) if [*target_func].include? current_func 'class="nowMenu"'.html_safe else '' end end # meta-tag を出力する def output_meta_tags if display_meta_tags.blank? assign_meta_tags end display_meta_tags end # meta-tag を紐付ける def assign_meta_tags(options = {}) if display_meta_tags.blank? defaults = t('meta_tags.defaults') a = breadcrumbs.map(&:name).delete_if{|x| %w/バリュートレンド HOME/.include? x}.reverse title = a.join(' | ') a << defaults[:site] full_title = a.join(' | ') configs = { separator: '|', reverse: true, site: defaults[:site], title: title, description: defaults[:description], keywords: defaults[:keywords], canonical: request.original_url, og: { type: 'article', title: full_title, description: defaults[:description], url: request.original_url, image: defaults[:image], site_name: defaults[:site], } } options = configs.merge options end set_meta_tags options end # image_tag をオーバーライド def image_tag(source, options={}) # altが指定されておらず、class が 'icon-xxx' であれば alt=nil とする。 # h1 タグ内の img.alt が Google 検索結果のタイトルに表示されてしまうため。 unless options.has_key? :alt options[:alt] = nil if options[:class]&.index 'icon-' end super source, options end end
24.836066
85
0.607921
33f82cefc0ec6fb2e0b10d700420b75127005255
5,339
# This file is auto-generated from the current state of the database. Instead # of editing this file, please use the migrations feature of Active Record to # incrementally modify your database, and then regenerate this schema definition. # # This file is the source Rails uses to define your schema when running `bin/rails # db:schema:load`. When creating a new database, `bin/rails db:schema:load` tends to # be faster and is potentially less error prone than running all of your # migrations from scratch. Old migrations may fail to apply correctly if those # migrations use external dependencies or application code. # # It's strongly recommended that you check this file into your version control system. ActiveRecord::Schema.define(version: 2021_11_17_023739) do create_table "article_tags", force: :cascade do |t| t.integer "article_id", null: false t.integer "tag_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["article_id", "tag_id"], name: "index_article_tags_on_article_id_and_tag_id", unique: true t.index ["article_id"], name: "index_article_tags_on_article_id" t.index ["tag_id"], name: "index_article_tags_on_tag_id" end create_table "articles", force: :cascade do |t| t.string "title", null: false t.text "body", null: false t.integer "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" t.index "\"user_id\", \"puzzle_id\"", name: "index_articles_on_user_id_and_puzzle_id" t.index ["user_id"], name: "index_articles_on_user_id" end create_table "categories", force: :cascade do |t| t.string "name" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "comments", force: :cascade do |t| t.string "body" t.string "commentable_type", null: false t.integer "commentable_id", null: false t.integer "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["commentable_type", "commentable_id"], name: "index_comments_on_commentable" t.index ["user_id"], name: "index_comments_on_user_id" end create_table "puzzle_categories", force: :cascade do |t| t.integer "puzzle_id" t.integer "category_id" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.integer "complexity", default: 0, null: false t.index ["category_id"], name: "index_puzzle_categories_on_category_id" t.index ["complexity"], name: "index_puzzle_categories_on_complexity" t.index ["puzzle_id"], name: "index_puzzle_categories_on_puzzle_id" end create_table "puzzles", force: :cascade do |t| t.string "title", null: false t.text "body", null: false t.string "solution", null: false t.integer "user_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "image_file_name" t.string "image_content_type" t.integer "image_file_size" t.datetime "image_updated_at" t.index "\"user_id\", \"puzzle_id\"", name: "index_puzzles_on_user_id_and_puzzle_id" t.index ["user_id"], name: "index_puzzles_on_user_id" end create_table "solutions", force: :cascade do |t| t.string "body" t.boolean "solved", default: false t.integer "user_id", null: false t.integer "puzzle_id", null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.index ["puzzle_id"], name: "index_solutions_on_puzzle_id" t.index ["user_id", "puzzle_id", "solved"], name: "index_solutions_on_user_id_and_puzzle_id_and_solved", unique: true t.index ["user_id", "puzzle_id"], name: "index_solutions_on_user_id_and_puzzle_id", unique: true t.index ["user_id"], name: "index_solutions_on_user_id" end create_table "tags", force: :cascade do |t| t.string "title" t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false end create_table "users", force: :cascade do |t| t.string "email", null: false t.string "name" t.string "password_digest" t.string "remember_token_digest" t.integer "role", default: 0, null: false t.datetime "created_at", precision: 6, null: false t.datetime "updated_at", precision: 6, null: false t.string "avatar_file_name" t.string "avatar_content_type" t.integer "avatar_file_size" t.datetime "avatar_updated_at" t.index ["email"], name: "index_users_on_email", unique: true t.index ["role"], name: "index_users_on_role" end add_foreign_key "article_tags", "articles" add_foreign_key "article_tags", "tags" add_foreign_key "articles", "users" add_foreign_key "comments", "users" add_foreign_key "puzzle_categories", "categories" add_foreign_key "puzzle_categories", "puzzles" add_foreign_key "puzzles", "users" add_foreign_key "solutions", "puzzles" add_foreign_key "solutions", "users" end
42.03937
121
0.716239
7a5bf4f69a0cb92afd8eb3418ae86013284e3218
2,439
# frozen_string_literal: true require_relative 'test_helper' class TestPlLocale < Test::Unit::TestCase def setup @phone_prefixes = %w[12 13 14 15 16 17 18 22 23 24 25 29 32 33 34 41 42 43 44 46 48 52 54 55 56 58 59 61 62 63 65 67 68 71 74 75 76 77 81 82 83 84 85 86 87 89 91 94 95].sort @cell_prefixes = %w[50 51 53 57 60 66 69 72 73 78 79 88].sort @previous_locale = Faker::Config.locale Faker::Config.locale = :pl end def teardown Faker::Config.locale = @previous_locale end def test_pl_names names = Faker::Base.fetch_all('name.first_name') + Faker::Base.fetch_all('name.last_name') names.each { |name| assert_match(/([\wĄąĆćĘꣳÓ󌜯żŹź]+\.? ?){2,3}/, name) } end def test_pl_phone_number prefixes = (0..999).map { Faker::PhoneNumber.phone_number[0, 2] }.uniq.sort assert_equal @phone_prefixes, prefixes end def test_pl_cell_phone prefixes = (0..999).map { Faker::PhoneNumber.cell_phone[0, 2] }.uniq.sort assert_equal @cell_prefixes, prefixes end def test_pl_address_methods assert Faker::Address.country.is_a? String assert Faker::Address.state.is_a? String assert Faker::Address.state_abbr.is_a? String assert Faker::Address.city_name.is_a? String assert Faker::Address.country_code.is_a? String assert Faker::Address.building_number.is_a? String assert Faker::Address.street_prefix.is_a? String assert Faker::Address.secondary_address.is_a? String assert Faker::Address.postcode.is_a? String assert Faker::Address.city.is_a? String assert Faker::Address.street_name.is_a? String assert Faker::Address.street_address.is_a? String assert Faker::Address.default_country.is_a? String assert_equal('Polska', Faker::Address.default_country) end def test_pl_coin_methods assert Faker::Coin.flip.is_a? String end def test_pl_company_methods assert Faker::Company.suffix.is_a? String assert Faker::Company.buzzwords.is_a? Array assert Faker::Company.bs.is_a? String assert Faker::Company.name.is_a? String end def test_pl_internet_methods assert Faker::Internet.free_email.is_a? String assert Faker::Internet.domain_suffix.is_a? String end def test_pl_name_methods assert Faker::Name.first_name.is_a? String assert Faker::Name.last_name.is_a? String assert Faker::Name.prefix.is_a? String assert Faker::Name.name_with_middle.is_a? String end end
33.875
177
0.731037
f72cb54e822ed644067c5384c3cca0c28c90726c
9,111
class Hash # ISO does not define Hash#each_pair, so each_pair is defined in gem. alias each_pair each ## # call-seq: # Hash[ key, value, ... ] -> new_hash # Hash[ [ [key, value], ... ] ] -> new_hash # Hash[ object ] -> new_hash # # Creates a new hash populated with the given objects. # # Similar to the literal `{ _key_ => _value_, ... }`. In the first # form, keys and values occur in pairs, so there must be an even number of # arguments. # # The second and third form take a single argument which is either an array # of key-value pairs or an object convertible to a hash. # # Hash["a", 100, "b", 200] #=> {"a"=>100, "b"=>200} # Hash[ [ ["a", 100], ["b", 200] ] ] #=> {"a"=>100, "b"=>200} # Hash["a" => 100, "b" => 200] #=> {"a"=>100, "b"=>200} # def self.[](*object) length = object.length if length == 1 o = object[0] if o.respond_to?(:to_hash) h = Hash.new object[0].to_hash.each { |k, v| h[k] = v } return h elsif o.respond_to?(:to_a) h = Hash.new o.to_a.each do |i| raise ArgumentError, "wrong element type #{i.class} (expected array)" unless i.respond_to?(:to_a) k, v = nil case i.size when 2 k = i[0] v = i[1] when 1 k = i[0] else raise ArgumentError, "invalid number of elements (#{i.size} for 1..2)" end h[k] = v end return h end end unless length % 2 == 0 raise ArgumentError, 'odd number of arguments for Hash' end h = Hash.new 0.step(length - 2, 2) do |i| h[object[i]] = object[i + 1] end h end ## # call-seq: # hsh.merge!(other_hash) -> hsh # hsh.merge!(other_hash){|key, oldval, newval| block} -> hsh # # Adds the contents of _other_hash_ to _hsh_. If no block is specified, # entries with duplicate keys are overwritten with the values from # _other_hash_, otherwise the value of each duplicate key is determined by # calling the block with the key, its value in _hsh_ and its value in # _other_hash_. # # h1 = { "a" => 100, "b" => 200 } # h2 = { "b" => 254, "c" => 300 } # h1.merge!(h2) #=> {"a"=>100, "b"=>254, "c"=>300} # # h1 = { "a" => 100, "b" => 200 } # h2 = { "b" => 254, "c" => 300 } # h1.merge!(h2) { |key, v1, v2| v1 } # #=> {"a"=>100, "b"=>200, "c"=>300} # def merge!(other, &block) raise TypeError, "can't convert argument into Hash" unless other.respond_to?(:to_hash) if block other.each_key{|k| self[k] = (self.has_key?(k))? block.call(k, self[k], other[k]): other[k] } else other.each_key{|k| self[k] = other[k]} end self end alias update merge! ## # call-seq: # hsh.fetch(key [, default] ) -> obj # hsh.fetch(key) {| key | block } -> obj # # Returns a value from the hash for the given key. If the key can't be # found, there are several options: With no other arguments, it will # raise an <code>KeyError</code> exception; if <i>default</i> is # given, then that will be returned; if the optional code block is # specified, then that will be run and its result returned. # # h = { "a" => 100, "b" => 200 } # h.fetch("a") #=> 100 # h.fetch("z", "go fish") #=> "go fish" # h.fetch("z") { |el| "go fish, #{el}"} #=> "go fish, z" # # The following example shows that an exception is raised if the key # is not found and a default value is not supplied. # # h = { "a" => 100, "b" => 200 } # h.fetch("z") # # <em>produces:</em> # # prog.rb:2:in 'fetch': key not found (KeyError) # from prog.rb:2 # def fetch(key, none=NONE, &block) unless self.key?(key) if block block.call(key) elsif none != NONE none else raise KeyError, "Key not found: #{key}" end else self[key] end end ## # call-seq: # hsh.delete_if {| key, value | block } -> hsh # hsh.delete_if -> an_enumerator # # Deletes every key-value pair from <i>hsh</i> for which <i>block</i> # evaluates to <code>true</code>. # # If no block is given, an enumerator is returned instead. # # h = { "a" => 100, "b" => 200, "c" => 300 } # h.delete_if {|key, value| key >= "b" } #=> {"a"=>100} # def delete_if(&block) return to_enum :delete_if unless block_given? self.each do |k, v| self.delete(k) if block.call(k, v) end self end ## # call-seq: # hash.flatten -> an_array # hash.flatten(level) -> an_array # # Returns a new array that is a one-dimensional flattening of this # hash. That is, for every key or value that is an array, extract # its elements into the new array. Unlike Array#flatten, this # method does not flatten recursively by default. The optional # <i>level</i> argument determines the level of recursion to flatten. # # a = {1=> "one", 2 => [2,"two"], 3 => "three"} # a.flatten # => [1, "one", 2, [2, "two"], 3, "three"] # a.flatten(2) # => [1, "one", 2, 2, "two", 3, "three"] # def flatten(level=1) self.to_a.flatten(level) end ## # call-seq: # hsh.invert -> new_hash # # Returns a new hash created by using <i>hsh</i>'s values as keys, and # the keys as values. # # h = { "n" => 100, "m" => 100, "y" => 300, "d" => 200, "a" => 0 } # h.invert #=> {0=>"a", 100=>"m", 200=>"d", 300=>"y"} # def invert h = Hash.new self.each {|k, v| h[v] = k } h end ## # call-seq: # hsh.keep_if {| key, value | block } -> hsh # hsh.keep_if -> an_enumerator # # Deletes every key-value pair from <i>hsh</i> for which <i>block</i> # evaluates to false. # # If no block is given, an enumerator is returned instead. # def keep_if(&block) return to_enum :keep_if unless block_given? keys = [] self.each do |k, v| unless block.call([k, v]) self.delete(k) end end self end ## # call-seq: # hsh.key(value) -> key # # Returns the key of an occurrence of a given value. If the value is # not found, returns <code>nil</code>. # # h = { "a" => 100, "b" => 200, "c" => 300, "d" => 300 } # h.key(200) #=> "b" # h.key(300) #=> "c" # h.key(999) #=> nil # def key(val) self.each do |k, v| return k if v == val end nil end ## # call-seq: # hsh.to_h -> hsh or new_hash # # Returns +self+. If called on a subclass of Hash, converts # the receiver to a Hash object. # def to_h self end ## # call-seq: # hash < other -> true or false # # Returns <code>true</code> if <i>hash</i> is subset of # <i>other</i>. # # h1 = {a:1, b:2} # h2 = {a:1, b:2, c:3} # h1 < h2 #=> true # h2 < h1 #=> false # h1 < h1 #=> false # def <(hash) begin hash = hash.to_hash rescue NoMethodError raise TypeError, "can't convert #{hash.class} to Hash" end size < hash.size and all? {|key, val| hash.key?(key) and hash[key] == val } end ## # call-seq: # hash <= other -> true or false # # Returns <code>true</code> if <i>hash</i> is subset of # <i>other</i> or equals to <i>other</i>. # # h1 = {a:1, b:2} # h2 = {a:1, b:2, c:3} # h1 <= h2 #=> true # h2 <= h1 #=> false # h1 <= h1 #=> true # def <=(hash) begin hash = hash.to_hash rescue NoMethodError raise TypeError, "can't convert #{hash.class} to Hash" end size <= hash.size and all? {|key, val| hash.key?(key) and hash[key] == val } end ## # call-seq: # hash > other -> true or false # # Returns <code>true</code> if <i>other</i> is subset of # <i>hash</i>. # # h1 = {a:1, b:2} # h2 = {a:1, b:2, c:3} # h1 > h2 #=> false # h2 > h1 #=> true # h1 > h1 #=> false # def >(hash) begin hash = hash.to_hash rescue NoMethodError raise TypeError, "can't convert #{hash.class} to Hash" end size > hash.size and hash.all? {|key, val| key?(key) and self[key] == val } end ## # call-seq: # hash >= other -> true or false # # Returns <code>true</code> if <i>other</i> is subset of # <i>hash</i> or equals to <i>hash</i>. # # h1 = {a:1, b:2} # h2 = {a:1, b:2, c:3} # h1 >= h2 #=> false # h2 >= h1 #=> true # h1 >= h1 #=> true # def >=(hash) begin hash = hash.to_hash rescue NoMethodError raise TypeError, "can't convert #{hash.class} to Hash" end size >= hash.size and hash.all? {|key, val| key?(key) and self[key] == val } end end
26.031429
107
0.509275
5d893cb4cab66d04d4ebaaaaaa6c7cf6bdafb86f
14,880
#-- # =============================================================================== # Copyright (c) 2005,2006,2007,2008 Christopher Kleckner # All rights reserved # # This file is part of the Rio library for ruby. # # Rio is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # Rio is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Rio; if not, write to the Free Software # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA # =============================================================================== #++ # # To create the documentation for Rio run the command # ruby build_doc.rb # from the distribution directory. # # Suggested Reading # * RIO::Doc::SYNOPSIS # * RIO::Doc::INTRO # * RIO::Doc::HOWTO # * RIO::Doc::EXAMPLES # * RIO::Rio # module RIO module IF module GrandeEntry # Grande Directory Selection Method # # Sets the rio to return directories. _args_ can be used to select which directories are returned. # ario.dirs(*args) do |f| # f.directory? #=> true # end # # No aguments selects all directories. # if _args_ are: # Regexp:: selects matching directories # glob:: selects matching directories # Proc:: called for each directory. the directory is processed unless the proc returns false # Symbol:: sent to each directory. Each directory is processed unless the symbol returns false # Fixnum:: matched against the "depth" of the directory # # If a block is given, behaves like <tt>ario.dirs(*args).each(&block)</tt> # # See also #files, #entries, #skipdirs # # rio('adir').dirs { |frio| ... } # process all directories in 'adir' # rio('adir').all.dirs { |frio| ... } # same thing recursively # rio('adir').dirs(/^\./) { |frio| ...} # process dot directories # rio('adir').dirs[/^\./] # return an array of dot directories # rio('adir').dirs[:symlink?] # an array of symlinks to directories # # Given the directory structure 'adir/a/b/c/d' # # rio('adir').all.dirs[2] #=> 'adir/a/b' # rio('adir').all.dirs[0..2] #=> 'adir/a','adir/a/b' # rio('adir').all.skipdirs[0..2] #=> 'adir/a/b/c','adir/a/b/c/d' # def dirs(*args,&block) target.dirs(*args,&block); self end # Grande Directory Exclude Method # # If no args are provided selects anything but directories. # ario.skipdirs do |el| # el.directory? #=> false # end # If args are provided, sets the rio to select directories as with #dirs, but the arguments are # used to determine which directories will *not* be processed # # If a block is given behaves like # ario.skipdirs(*args).each(&block) # # See #dirs # # rio('adir').skipdirs { |ent| ... } # iterate through everything except directories # rio('adir').skipdirs(/^\./) { |drio| ... } # iterate through directories, skipping dot directories # # def skipdirs(*args,&block) target.skipdirs(*args,&block); self end # Grande Directory Entry Selection Method # # No aguments selects all entries. # # if +args+ are: # Regexp:: selects matching entries # glob:: selects matching entries # Proc:: called for each entry. the entry is processed unless the proc returns false # Symbol:: sent to each entry. Each entry is processed unless the symbol returns false # # If a block is given, behaves like <tt>ario.etries(*args).each(&block)</tt> # # See also #files, #dirs, #skipentries # # rio('adir').entries { |frio| ... } # process all entries in 'adir' # rio('adir').all.entries { |frio| ... } # same thing recursively # rio('adir').entries(/^\./) { |frio| ...} # process entries starting with a dot # rio('adir').entries[/^\./] # return an array of all entries starting with a dot # rio('adir').entries[:symlink?] # an array of symlinks in 'adir' # def entries(*args,&block) target.entries(*args,&block); self end # Grande Directory Entry Rejection Method # # No aguments rejects all entries. # # Behaves like #entries, except that matching entries are excluded. # # See also #entries, IF::Grande#skip # def skipentries(*args,&block) target.skipentries(*args,&block); self end # Grande File Selection Method # # Configures the rio to process files. +args+ can be used to select which files are returned. # ario.files(*args) do |f| # f.file? #=> true # end # No aguments selects all files. # # +args+ may be zero or more of the following: # # Regexp:: selects matching files # String:: treated as a glob, and selects matching files # Proc:: called for each file. the file is processed unless the proc returns false # Symbol:: sent to each file. Each file is processed unless the symbol returns false # # +files+ returns the Rio which called it. This might seem counter-intuitive at first. # One might reasonably assume that # rio('adir').files('*.rb') # would return files. It does not. It configures the rio to return files and returns # the Rio. This enables chaining for further configuration so constructs like # rio('adir').all.files('*.rb').norecurse('.svn') # are possible. # # If a block is given, behaves like # ario.files(*args).each # # # See also #dirs, #entries, #skipfiles # # rio('adir').files { |frio| ... } # process all files in 'adir' # rio('adir').all.files { |frio| ... } # same thing recursively # rio('adir').files('*.rb') { |frio| ...} # process .rb files # rio('adir').files['*.rb'] # return an array of .rb files # rio('adir').files[/\.rb$/] # same thing using a regular expression # rio('adir').files[:symlink?] # an array of symlinks to files # rio('adir').files >> rio('other_dir') # copy files to 'other_dir' # rio('adir').files('*.rb') >> rio('other_dir') # only copy .rb files # # For Rios that refer to files, <tt>files(*args)</tt> causes the file to be processed only if # it meets the criteria specified by the args. # # rio('afile.z').files['*.z'] #=> [rio('afile.z')] # rio('afile.q').files['*.z'] #=> [] # # === Example Problem # # Fill the array +ruby_progs+ with all ruby programs in a directory and its subdirectories, # skipping those in _subversion_ (.svn) directories. # # ruby_progs = [] # # For the purposes of this problem, a Ruby program is defined as a file ending with .rb or a file # that is executable and whose shebang line contains 'ruby': # # is_ruby_exe = proc{ |f| f.executable? and f.gets =~ /^#!.+ruby/ } # # ==== Solution 1. Use the subscript operator. # # ruby_progs = rio('adir').norecurse('.svn').files['*.rb',is_ruby_exe] # # Explanation: # # 1. Create the Rio # # Create a Rio for a directory # rio('adir') # # 2. Configure the Rio # # Specify recursion and that '.svn' directories should not be included. # rio('adir').norecurse('.svn') # Select files # rio('adir').norecurse('.svn').files # Limit to files ending with '.rb' # rio('adir').norecurse('.svn').files('*.rb') # Also allow files for whom +is_ruby_exe+ returns true # rio('adir').norecurse('.svn').files('*.rb',is_ruby_exe) # # 3. Do the I/O # # Return an array rather than iterating thru them # ruby_progs = rio('adir').norecurse('.svn').files['*.rb',is_ruby_exe] # # ==== Solution 2. Use the copy-to operator # # rio('adir').files('*.rb',is_ruby_exe).norecurse('.svn') > ruby_progs # # Explanation: # # 1. Create the Rio # # Create a Rio for a directory # rio('adir') # # 2. Configure the Rio # # Select only files # rio('adir').files # Limit to files ending with '.rb' # rio('adir').files('*.rb') # Also allow files for whom +is_ruby_exe+ returns true # rio('adir').files('*.rb',is_ruby_exe) # Specify recursion and that '.svn' directories should not be included. # rio('adir').files('*.rb',is_ruby_exe).norecurse('.svn') # # 3. Do the I/O # # Copy the Rio to ruby_progs # rio('adir').files('*.rb',is_ruby_exe).norecurse('.svn') > ruby_progs # # ==== Example Discussion # # Note that the only difference between Step 2 of Solution 1 and that of Solution 2 is # the order of the configuration methods. Step 2 of Solution 1 would have worked equally # well: # # rio('adir').norecurse('.svn').files('*.rb',is_ruby_exe) > ruby_progs # # Furthermore if our problem were changed slightly and instead of having our results # ending up in an array, we wished to iterate through them, we could use: # # rio('adir').norecurse('.svn').files('*.rb',is_ruby_exe) { |ruby_prog_rio| ... } # # Note the similarities. In fact, solution 1 could have been written: # # rio('adir').norecurse('.svn').files('*.rb',is_ruby_exe).to_a # or # rio('adir').norecurse('.svn').files('*.rb',is_ruby_exe)[] # # Passing the arguments for +files+ to the subscript operator is syntactic sugar. # The subscript operator does not really take any arguments of its own. It always # passes them to the most recently called of the grande selection methods (or the # default selection method, if none have been called). So, # # rio('adir').files['*.rb'] # is a shortcut for # rio('adir').files('*.rb').to_a # # and # # rio('adir')['*.rb'] # is a shortcut for # rio('adir').entries('*.rb').to_a # # and # # rio('afile').lines[0..10] # is a shortcut for # rio('afile').lines(0..10).to_a # # And so on. # # # def files(*args,&block) target.files(*args,&block); self end # Grande File Exclude Method # # If no args are provided selects anything but files. # ario.skipfiles do |el| # el.file? #=> false # end # If args are provided, sets the rio to select files as with #files, but the arguments are # used to determine which files will *not* be processed # # If a block is given behaves like <tt>ario.skipfiles(*args).each(&block)</tt> # # See #files, IF::Grande#skip # # rio('adir').skipfiles { |ent| ... } # iterate through everything except files # rio('adir').skipfiles('*~') { |frio| ... } # iterate through files, skipping those ending with a tilde # # def skipfiles(*args,&block) target.skipfiles(*args,&block); self end # Returns +true+ if the rio is in +all+ (recursive) mode. See #all # # adir = rio('adir').all.dirs # adir.all? # true # adir.each do |subdir| # subdir.all? # true # end # # rio('adir').all? # false # def all?() target.all?() end # Grande Directory Recursion Method # # Sets the Rio to all mode (recursive) # # When called with a block, behaves as if all.each(&block) had been called # # +all+ causes subsequent calls to +files+ or +dirs+ to be applied recursively # to subdirectories # # rio('adir').all.files('*.[ch]').each { |file| ... } # process all c language source files in adir # # and all subdirectories of adir # rio('adir').all.files(/\.[ch]$/) { |file| ... } # same as above # rio('adir').files("*.[ch]").all { |file| ... } # once again # rio('adir').all.files["*.[ch]"] # same, but return an array instead of iterating # def all(arg=true,&block) target.all(arg,&block); self end # Grande Directory Recursion Selection Method # # Sets the Rio to recurse into directories like #all. If no args are provided behaves like #all. # If args are provided, they are processed like #dirs to select which subdirectories should # be recursed into. #recurse always implies #all. # # +args+ may be one or more of: # Regexp:: recurse into matching subdirectories # glob:: recurse into matching subdirectories # Proc:: called for each directory. The directory is recursed into unless the proc returns false # Symbol:: sent to each directory. Each directory is recursed into unless the symbol returns false # Fixnum:: recurse into directories only at the given depth # Range:: recurse into directories at a range of depths # # If a block is given, behaves like <tt>ario.recurse(*args).each(&block)</tt> # # See also #norecurse, #all, #dirs # # rio('adir').recurse('test*') { |drio| ... } # process all entries and all entries in subdirectories # # starting with 'test' -- recursively # def recurse(*args,&block) target.recurse(*args,&block); self end # Grande Directory Recursion Exclude Method # # Sets the Rio to recurse into directories like #all. If no args are provided, no # directories will be recursed into. If args are provided, behaves like #recurse, except # that matching directories will *not* be recursed into # # rio('adir').norecurse('.svn') { |drio| ... } # recurse, skipping subversion directories # # rio('adir').norecurse(3) {|drio| ... } # only recurse 2 levels deep into a directory structure # def norecurse(*args,&block) target.norecurse(*args,&block); self end end end end module RIO class Rio include RIO::IF::GrandeEntry end end
39.157895
111
0.578024
ff723bd3422b4b77302d3a657635f4b0f55af3ef
56
FROM golang:1.17-alpine RUN apk --no-cache add make git
18.666667
31
0.75
916e9046ee93bc2ee3d55cdfa5b4b0fbd13a8ee0
566
require "mustache" Mustache.template_path = __dir__ require "active_support" require "active_support/core_ext" require "salesforce_test_data_factory/version" require "salesforce_test_data_factory/generator" require "salesforce_test_data_factory/salesforce/client" require "salesforce_test_data_factory/salesforce/sobject" require "salesforce_test_data_factory/apex/class_type" require "salesforce_test_data_factory/apex/class" require "salesforce_test_data_factory/apex/class_xml" require "salesforce_test_data_factory/helper" module SalesforceTestDataFactory end
33.294118
57
0.879859
abe4e3bbe5e9e0b4715b38f24331a38cc9eda77f
3,360
include Niche::Aws::Ec2 # Support whyrun def whyrun_supported? true end action :associate do ip = new_resource.ip || node['aws']['elastic_ip'][new_resource.name]['ip'] addr = address(ip) if addr.nil? raise "Elastic IP #{ip} does not exist" elsif addr[:instance_id] == instance_id Chef::Log.debug("Elastic IP #{ip} is already attached to the instance") else converge_by("attach Elastic IP #{ip} to the instance") do Chef::Log.info("Attaching Elastic IP #{ip} to the instance") attach(ip, new_resource.timeout) node.set['aws']['elastic_ip'][new_resource.name]['ip'] = ip node.save unless Chef::Config[:solo] end end end action :disassociate do ip = new_resource.ip || node['aws']['elastic_ip'][new_resource.name]['ip'] addr = address(ip) if addr.nil? Chef::Log.debug("Elastic IP #{ip} does not exist, so there is nothing to detach") elsif addr[:instance_id] != instance_id Chef::Log.debug("Elastic IP #{ip} is already detached from the instance") else converge_by("detach Elastic IP #{ip} from the instance") do Chef::Log.info("Detaching Elastic IP #{ip} from the instance") detach(ip, new_resource.timeout) end end end action :allocate do current_elastic_ip = node['aws']['elastic_ip'][new_resource.name]['ip'] if current_elastic_ip Chef::Log.info("An Elastic IP was already allocated for #{new_resource.name} #{current_elastic_ip} from the instance") else converge_by("allocate new Elastic IP for #{new_resource.name}") do addr = ec2.allocate_address Chef::Log.info("Allocated Elastic IP #{addr[:public_ip]} from the instance") node.set['aws']['elastic_ip'][new_resource.name]['ip'] = addr[:public_ip] node.save unless Chef::Config[:solo] end end end private def address(ip) ec2.describe_addresses.find { |a| a[:public_ip] == ip } end def attach(ip, timeout) addr = address(ip) if addr[:domain] == 'vpc' ec2.associate_address(instance_id, {:allocation_id => addr[:allocation_id]}) else ec2.associate_address(instance_id, {:public_ip => addr[:public_ip]}) end # block until attached begin Timeout::timeout(timeout) do while true addr = address(ip) if addr.nil? raise "Elastic IP has been deleted while waiting for attachment" elsif addr[:instance_id] == instance_id Chef::Log.debug("Elastic IP is attached to this instance") break else Chef::Log.debug("Elastic IP is currently attached to #{addr[:instance_id]}") end sleep 3 end end rescue Timeout::Error raise "Timed out waiting for attachment after #{timeout} seconds" end end def detach(ip, timeout) ec2.disassociate_address({:public_ip => ip}) # block until detached begin Timeout::timeout(timeout) do while true addr = address(ip) if addr.nil? Chef::Log.debug("Elastic IP has been deleted while waiting for detachment") elsif addr[:instance_id] != instance_id Chef::Log.debug("Elastic IP is detached from this instance") break else Chef::Log.debug("Elastic IP is still attached") end sleep 3 end end rescue Timeout::Error raise "Timed out waiting for detachment after #{timeout} seconds" end end
29.473684
122
0.66131
ac8d191491ec81fd362af9d10acf41699f6241a0
1,293
=begin #Ory APIs #Documentation for all public and administrative Ory APIs. Administrative APIs can only be accessed with a valid Personal Access Token. Public APIs are mostly used in browsers. The version of the OpenAPI document: v0.0.1-alpha.71 Contact: support@ory.sh Generated by: https://openapi-generator.tech OpenAPI Generator version: 5.4.0 =end require 'spec_helper' require 'json' require 'date' # Unit tests for OryClient::UiNodeAttributes # Automatically generated by openapi-generator (https://openapi-generator.tech) # Please update as you see appropriate describe OryClient::UiNodeAttributes do describe '.openapi_one_of' do it 'lists the items referenced in the oneOf array' do expect(described_class.openapi_one_of).to_not be_empty end end describe '.openapi_discriminator_name' do it 'returns the value of the "discriminator" property' do expect(described_class.openapi_discriminator_name).to_not be_empty end end describe '.openapi_discriminator_mapping' do it 'returns the key/values of the "mapping" property' do expect(described_class.openapi_discriminator_mapping.values.sort).to eq(described_class.openapi_one_of.sort) end end describe '.build' do it 'returns the correct model' do end end end
29.386364
177
0.769528
26890969a85e7ac2603de6ad402cd8fa88c32a0f
2,732
require '<%= gem_name %>/version' AUTHOR = '<%= author %>' # can also be an array of Authors EMAIL = "<%= email %>" DESCRIPTION = "description of gem" GEM_NAME = '<%= gem_name %>' # what ppl will type to install your gem RUBYFORGE_PROJECT = '<%= gem_name %>' # The unix name for your project HOMEPATH = "http://#{RUBYFORGE_PROJECT}.rubyforge.org" DOWNLOAD_PATH = "http://rubyforge.org/projects/#{RUBYFORGE_PROJECT}" EXTRA_DEPENDENCIES = [ # ['activesupport', '>= 1.3.1'] ] # An array of rubygem dependencies [name, version] @config_file = "~/.rubyforge/user-config.yml" @config = nil RUBYFORGE_USERNAME = "unknown" def rubyforge_username unless @config begin @config = YAML.load(File.read(File.expand_path(@config_file))) rescue puts <<-EOS ERROR: No rubyforge config file found: #{@config_file} Run 'rubyforge setup' to prepare your env for access to Rubyforge - See http://newgem.rubyforge.org/rubyforge.html for more details EOS exit end end RUBYFORGE_USERNAME.replace @config["username"] end REV = nil # UNCOMMENT IF REQUIRED: # REV = YAML.load(`svn info`)['Revision'] VERS = <%= module_name %>::VERSION::STRING + (REV ? ".#{REV}" : "") RDOC_OPTS = ['--quiet', '--title', '<%= gem_name %> documentation', "--opname", "index.html", "--line-numbers", "--main", "README", "--inline-source"] class Hoe def extra_deps @extra_deps.reject! { |x| Array(x).first == 'hoe' } @extra_deps end end # Generate all the Rake tasks # Run 'rake -T' to see list of generated tasks (from gem root directory) $hoe = Hoe.new(GEM_NAME, VERS) do |p| p.developer(AUTHOR, EMAIL) p.description = DESCRIPTION p.summary = DESCRIPTION p.url = HOMEPATH p.rubyforge_name = RUBYFORGE_PROJECT if RUBYFORGE_PROJECT p.test_globs = ["test/**/test_*.rb"] p.clean_globs |= ['**/.*.sw?', '*.gem', '.config', '**/.DS_Store'] #An array of file patterns to delete on clean. # == Optional p.changes = p.paragraphs_of("History.txt", 0..1).join("\n\n") #p.extra_deps = EXTRA_DEPENDENCIES <% if is_jruby -%> # JRuby gem created, e.g. <%= gem_name %>-X.Y.Z-jruby.gem p.spec_extras = { :platform => 'jruby' } # A hash of extra values to set in the gemspec. <% else -%> #p.spec_extras = {} # A hash of extra values to set in the gemspec. <% end -%> end CHANGES = $hoe.paragraphs_of('History.txt', 0..1).join("\\n\\n") PATH = (RUBYFORGE_PROJECT == GEM_NAME) ? RUBYFORGE_PROJECT : "#{RUBYFORGE_PROJECT}/#{GEM_NAME}" $hoe.remote_rdoc_dir = File.join(PATH.gsub(/^#{RUBYFORGE_PROJECT}\/?/,''), 'rdoc') $hoe.rsync_args = '-av --delete --ignore-errors' $hoe.spec.post_install_message = File.open(File.dirname(__FILE__) + "/../PostInstall.txt").read rescue ""
35.025641
116
0.659956
8764f94d7263ea846a3cb3cb9a37c33cd2ec7351
317
all rule 'MD002', :level => 1 rule 'MD007', :indent => 4 rule 'MD013', :line_length => 160, :code_blocks => false, :tables => false rule 'MD026', :punctuation => ".,;:!" exclude_rule 'MD013' exclude_rule 'MD014' exclude_rule 'MD030' exclude_rule 'MD032' exclude_rule 'MD033' exclude_rule 'MD041' exclude_rule 'MD046'
24.384615
74
0.70347
b97b8174dfdcacec98769638eacb76a0893daa46
2,712
# frozen_string_literal: true RSpec.describe Sports::Butler::SoccerApi::ApiFootballCom::HeadToHead do let(:sport) { :soccer } let(:api_name) { :api_football_com } let(:endpoint) { :head_to_head } let(:response_type) { Hash } before do ConfigHelpers.set_api_football_com stubs_head_to_head_api_football_com end describe 'when #by_teams' do it_behaves_like 'when #by_teams', 1, 2, :response_head_to_head_one_api_football_com, :response end end def stubs_head_to_head_api_football_com stub_request(:get, "#{Sports::Butler::Configuration.api_base_url[sport][api_name]}/fixtures/headtohead?h2h=1-2") .to_return(status: 200, body: get_mocked_response('head_to_head.json', sport, api_name)) end def response_head_to_head_one_api_football_com [ { "fixture": { "id": 135797, "referee": "Antonio Mateu, Spain", "timezone": "UTC", "date": "2018-06-21T12:00:00+00:00", "timestamp": 1529582400, "periods": { "first": 1529582400, "second": 1529586000 }.with_indifferent_access, "venue": { "id": "", "name": "Samara Arena", "city": "Samara" }.with_indifferent_access, "status": { "long": "Match Finished", "short": "FT", "elapsed": 90 }.with_indifferent_access }.with_indifferent_access, "league": { "id": 1, "name": "World Cup", "country": "World", "logo": "https://media.api-sports.io/football/leagues/1.png", "flag": "", "season": 2018, "round": "Group Stage - 2" }.with_indifferent_access, "teams": { "home": { "id": 21, "name": "Denmark", "logo": "https://media.api-sports.io/football/teams/21.png", "winner": "" }.with_indifferent_access, "away": { "id": 20, "name": "Australia", "logo": "https://media.api-sports.io/football/teams/20.png", "winner": "" }.with_indifferent_access }.with_indifferent_access, "goals": { "home": 1, "away": 1 }.with_indifferent_access, "score": { "halftime": { "home": 1, "away": 1 }.with_indifferent_access, "fulltime": { "home": 1, "away": 1 }.with_indifferent_access, "extratime": { "home": "", "away": "" }.with_indifferent_access, "penalty": { "home": "", "away": "" }.with_indifferent_access }.with_indifferent_access }.with_indifferent_access ] end
27.673469
114
0.547935
1ce1029b4e6b5678360a8a813305ca6e142acc6d
11,318
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. require 'date' require_relative 'create_job_details' # rubocop:disable Lint/UnneededCopDisableDirective, Metrics/LineLength module OCI # The details specific to the SQL job request. class DatabaseManagement::Models::CreateSqlJobDetails < DatabaseManagement::Models::CreateJobDetails # The SQL text to be executed as part of the job. # @return [String] attr_accessor :sql_text # @return [String] attr_accessor :sql_type # **[Required]** The SQL operation type. # @return [String] attr_accessor :operation_type # The database user name used to execute the SQL job. If the job is being executed on a # Managed Database Group, then the user name should exist on all the databases in the # group with the same password. # # @return [String] attr_accessor :user_name # The password for the database user name used to execute the SQL job. # @return [String] attr_accessor :password # The role of the database user. Indicates whether the database user is a normal user or sysdba. # @return [String] attr_accessor :role # Attribute mapping from ruby-style variable name to JSON key. def self.attribute_map { # rubocop:disable Style/SymbolLiteral 'name': :'name', 'description': :'description', 'compartment_id': :'compartmentId', 'managed_database_group_id': :'managedDatabaseGroupId', 'managed_database_id': :'managedDatabaseId', 'database_sub_type': :'databaseSubType', 'schedule_type': :'scheduleType', 'job_type': :'jobType', 'timeout': :'timeout', 'result_location': :'resultLocation', 'sql_text': :'sqlText', 'sql_type': :'sqlType', 'operation_type': :'operationType', 'user_name': :'userName', 'password': :'password', 'role': :'role' # rubocop:enable Style/SymbolLiteral } end # Attribute type mapping. def self.swagger_types { # rubocop:disable Style/SymbolLiteral 'name': :'String', 'description': :'String', 'compartment_id': :'String', 'managed_database_group_id': :'String', 'managed_database_id': :'String', 'database_sub_type': :'String', 'schedule_type': :'String', 'job_type': :'String', 'timeout': :'String', 'result_location': :'OCI::DatabaseManagement::Models::JobExecutionResultLocation', 'sql_text': :'String', 'sql_type': :'String', 'operation_type': :'String', 'user_name': :'String', 'password': :'String', 'role': :'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] :name The value to assign to the {OCI::DatabaseManagement::Models::CreateJobDetails#name #name} proprety # @option attributes [String] :description The value to assign to the {OCI::DatabaseManagement::Models::CreateJobDetails#description #description} proprety # @option attributes [String] :compartment_id The value to assign to the {OCI::DatabaseManagement::Models::CreateJobDetails#compartment_id #compartment_id} proprety # @option attributes [String] :managed_database_group_id The value to assign to the {OCI::DatabaseManagement::Models::CreateJobDetails#managed_database_group_id #managed_database_group_id} proprety # @option attributes [String] :managed_database_id The value to assign to the {OCI::DatabaseManagement::Models::CreateJobDetails#managed_database_id #managed_database_id} proprety # @option attributes [String] :database_sub_type The value to assign to the {OCI::DatabaseManagement::Models::CreateJobDetails#database_sub_type #database_sub_type} proprety # @option attributes [String] :schedule_type The value to assign to the {OCI::DatabaseManagement::Models::CreateJobDetails#schedule_type #schedule_type} proprety # @option attributes [String] :timeout The value to assign to the {OCI::DatabaseManagement::Models::CreateJobDetails#timeout #timeout} proprety # @option attributes [OCI::DatabaseManagement::Models::JobExecutionResultLocation] :result_location The value to assign to the {OCI::DatabaseManagement::Models::CreateJobDetails#result_location #result_location} proprety # @option attributes [String] :sql_text The value to assign to the {#sql_text} property # @option attributes [String] :sql_type The value to assign to the {#sql_type} property # @option attributes [String] :operation_type The value to assign to the {#operation_type} property # @option attributes [String] :user_name The value to assign to the {#user_name} property # @option attributes [String] :password The value to assign to the {#password} property # @option attributes [String] :role The value to assign to the {#role} property def initialize(attributes = {}) return unless attributes.is_a?(Hash) attributes['jobType'] = 'SQL' super(attributes) # convert string to symbol for hash key attributes = attributes.each_with_object({}) { |(k, v), h| h[k.to_sym] = v } self.sql_text = attributes[:'sqlText'] if attributes[:'sqlText'] raise 'You cannot provide both :sqlText and :sql_text' if attributes.key?(:'sqlText') && attributes.key?(:'sql_text') self.sql_text = attributes[:'sql_text'] if attributes[:'sql_text'] self.sql_type = attributes[:'sqlType'] if attributes[:'sqlType'] raise 'You cannot provide both :sqlType and :sql_type' if attributes.key?(:'sqlType') && attributes.key?(:'sql_type') self.sql_type = attributes[:'sql_type'] if attributes[:'sql_type'] self.operation_type = attributes[:'operationType'] if attributes[:'operationType'] raise 'You cannot provide both :operationType and :operation_type' if attributes.key?(:'operationType') && attributes.key?(:'operation_type') self.operation_type = attributes[:'operation_type'] if attributes[:'operation_type'] self.user_name = attributes[:'userName'] if attributes[:'userName'] raise 'You cannot provide both :userName and :user_name' if attributes.key?(:'userName') && attributes.key?(:'user_name') self.user_name = attributes[:'user_name'] if attributes[:'user_name'] self.password = attributes[:'password'] if attributes[:'password'] self.role = attributes[:'role'] if attributes[:'role'] 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 && name == other.name && description == other.description && compartment_id == other.compartment_id && managed_database_group_id == other.managed_database_group_id && managed_database_id == other.managed_database_id && database_sub_type == other.database_sub_type && schedule_type == other.schedule_type && job_type == other.job_type && timeout == other.timeout && result_location == other.result_location && sql_text == other.sql_text && sql_type == other.sql_type && operation_type == other.operation_type && user_name == other.user_name && password == other.password && role == other.role 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 [name, description, compartment_id, managed_database_group_id, managed_database_id, database_sub_type, schedule_type, job_type, timeout, result_location, sql_text, sql_type, operation_type, user_name, password, role].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
43.034221
245
0.684838
4aabd1ca79921d1dc40a4fa7477ca92ae1be65ea
2,998
# frozen_string_literal: true module MergeRequests # Performs the merge between source SHA and the target branch or the specified first parent ref. Instead # of writing the result to the MR target branch, it targets the `target_ref`. # # Ideally this should leave the `target_ref` state with the same state the # target branch would have if we used the regular `MergeService`, but without # every side-effect that comes with it (MR updates, mails, source branch # deletion, etc). This service should be kept idempotent (i.e. can # be executed regardless of the `target_ref` current state). # class MergeToRefService < MergeRequests::MergeBaseService extend ::Gitlab::Utils::Override def execute(merge_request, cache_merge_to_ref_calls = false) @merge_request = merge_request error_check! commit_id = commit(cache_merge_to_ref_calls) raise_error('Conflicts detected during merge') unless commit_id commit = project.commit(commit_id) target_id, source_id = commit.parent_ids success(commit_id: commit.id, target_id: target_id, source_id: source_id) rescue MergeError, ArgumentError => error error(error.message) end private override :source def source merge_request.diff_head_sha end override :error_check! def error_check! check_source end ## # The parameter `target_ref` is where the merge result will be written. # Default is the merge ref i.e. `refs/merge-requests/:iid/merge`. def target_ref params[:target_ref] || merge_request.merge_ref_path end ## # The parameter `first_parent_ref` is the main line of the merge commit. # Default is the target branch ref of the merge request. def first_parent_ref params[:first_parent_ref] || merge_request.target_branch_ref end ## # The parameter `allow_conflicts` is a flag whether merge conflicts should be merged into diff # Default is false def allow_conflicts params[:allow_conflicts] || false end def commit(cache_merge_to_ref_calls = false) if cache_merge_to_ref_calls && Feature.enabled?(:cache_merge_to_ref_calls, project, default_enabled: false) Rails.cache.fetch(cache_key, expires_in: 1.day) do extracted_merge_to_ref end else extracted_merge_to_ref end end def extracted_merge_to_ref repository.merge_to_ref(current_user, source_sha: source, branch: merge_request.target_branch, target_ref: target_ref, message: commit_message, first_parent_ref: first_parent_ref, allow_conflicts: allow_conflicts) rescue Gitlab::Git::PreReceiveError, Gitlab::Git::CommandError => error raise MergeError, error.message end def cache_key [:merge_to_ref_service, project.full_path, merge_request.target_branch_sha, merge_request.source_branch_sha] end end end
31.229167
114
0.70547
6134109cf332fcb2ab15dd69cec7afcc44687cba
1,203
# # Cookbook Name:: oracle # Recipe:: ora_os_setup # # 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. # Configure Oracle user, install the RDBMS's dependencies, configure # kernel parameters. # Set up and configure the oracle user. include_recipe 'oracle::oracle_user_config' ## Install dependencies and configure kernel parameters. # Node attribute changes for 12c, if default[:oracle][:rdbms][:dbbin_version] is set to 12c if node[:oracle][:rdbms][:dbbin_version] == "12c" node.set[:oracle][:rdbms][:deps] = node[:oracle][:rdbms][:deps_12c] include_recipe 'oracle::deps_install' else include_recipe 'oracle::deps_install' end # Setting up kernel parameters include_recipe 'oracle::kernel_params'
35.382353
91
0.760599
1a13c25aec541ff2056136e4d86d436163871d7b
1,123
# # Cookbook Name:: god # Definition:: god_monitor # # Copyright 2009, Opscode, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # define :god_monitor, :config => "mongrel.god.erb", :max_memory => 100, :cpu => 50 do include_recipe "god" template "/etc/god/conf.d/#{params[:name]}.god" do source params[:config] owner "root" group "root" mode 0644 variables( :name => params[:name], :max_memory => params[:max_memory], :cpu => params[:cpu], :sv_bin => node[:runit][:sv_bin], :params => params ) notifies :restart, resources(:service => "god") end end
28.794872
84
0.676759
6ada47c91f428c271d34daf2fb0d577f16837571
329
# frozen_string_literal: true # Migration adding github email attribute to user model so that github oauth is possible and separate # from a database perspective than auth through a user given email. class AddGithubEmailToUsers < ActiveRecord::Migration[6.0] def change add_column :users, :github_email, :string end end
32.9
101
0.790274
39d9b8cbf53436c14545eabf0188b6b51ff830a1
2,160
class OrdersController < ApplicationController include CurrentCart before_action :set_cart, only: [:new, :create] before_action :set_order, only: [:show, :edit, :update, :destroy] # GET /orders # GET /orders.json def index @orders = Order.all end # GET /orders/1 # GET /orders/1.json def show end # GET /orders/new def new if @cart.line_items.empty? redirect_to store_url, notice: "Your cart is empty" return end @order = Order.new end # GET /orders/1/edit def edit end # POST /orders # POST /orders.json def create @order = Order.new(order_params) @order.add_line_items_from_cart(@cart) respond_to do |format| if @order.save Cart.destroy(session[:cart_id]) session[:cart_id] = nil format.html { redirect_to store_url, notice: 'Thank you for your order.' } format.json { render action: 'show', status: :created, location: @order } else format.html { render action: 'new' } format.json { render json: @order.errors, status: :unprocessable_entity } end end end # PATCH/PUT /orders/1 # PATCH/PUT /orders/1.json def update respond_to do |format| if @order.update(order_params) format.html { redirect_to @order, notice: 'Order was successfully updated.' } format.json { head :no_content } else format.html { render action: 'edit' } format.json { render json: @order.errors, status: :unprocessable_entity } end end end # DELETE /orders/1 # DELETE /orders/1.json def destroy @order.destroy respond_to do |format| format.html { redirect_to orders_url } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_order @order = Order.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def order_params params.require(:order).permit(:name, :address, :email, :pay_type) end end
24.545455
88
0.625
1cd313ec819690703e101ccee2bb42bd08dacad9
754
require 'active_support' require 'test/unit' class FlashCacheOnPrivateMemoizationTest < Test::Unit::TestCase extend ActiveSupport::Memoizable def test_public assert_method_unmemoizable :pub end def test_protected assert_method_unmemoizable :prot end def test_private assert_method_unmemoizable :priv end def pub; rand end memoize :pub protected def prot; rand end memoize :prot private def priv; rand end memoize :priv def assert_method_unmemoizable(meth, message=nil) full_message = build_message(message, "<?> not unmemoizable.\n", meth) assert_block(full_message) do a = send meth b = send meth unmemoize_all c = send meth a == b && a != c end end end
17.136364
74
0.698939
ac4bbaab928f93800a63f92c6e061299139633cf
859
# coding: utf-8 lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'digimon/version' Gem::Specification.new do |spec| spec.name = "digimon" spec.version = Digimon::VERSION spec.authors = ["Xiaoting"] spec.email = ["yext4011@gmail.com"] spec.summary = %q{a gem for circuit breaker.} spec.description = %q{a gem for circuit breaker.} spec.homepage = "" spec.license = "MIT" spec.files = `git ls-files -z`.split("\x0") spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) } spec.test_files = spec.files.grep(%r{^(test|spec|features)/}) spec.require_paths = ["lib"] spec.add_development_dependency "bundler", "~> 1.6" spec.add_development_dependency "rake" spec.add_dependency 'activesupport' end
34.36
74
0.643772
1accf3c8f55008bd8393403731a7b20295e5f8a8
2,154
class MatchesController < ApplicationController layout "modal", only: [ :edit_match_stats ] include Select, StatusEnum before_action :authorize_administrator, only: [:pend, :activate, :finish, :update, :postpone, :edit_match_stats, :update_match_stats] def update @match = Match.find(params[:id]) datetime_str = update_params[:datetime] begin if !datetime_str.empty? @match.datetime = DateTime.parse(datetime_str) else @match.datetime = @match.postpone end if @match.save flash[:success] = "Match datetime updated." else flash[:danger] = "The match datetime could not be updated." end rescue ArgumentError flash[:danger] = "The datetime '#{datetime_str}' is invalid." end redirect_to @match.match_day end def edit_match_stats @match = Match.find(params[:id]) end def update_match_stats match_stats_file = params[:match_stats_file] update_previous_points_and_goals = params[:update_previous_points_and_goals] == "true" finish = params[:finish] == "true" begin match = Match.find(params[:id]) session[:upload_result] = UploadMatchStatsJson.new(match, update_previous_points_and_goals, finish).upload(match_stats_file.read) if !session[:upload_result][:validation_errors].any? && !session[:upload_result][:data_errors].any? && !session[:upload_result][:missing_players].any? flash[:success] = [ "Match data updated." ].concat(session[:upload_result][:data_updates]) end redirect_to match ensure # Not strictly necessary, just so we don't get loads and loads of files # before they're garbage collected. match_stats_file.tempfile.unlink end end def postpone match = Match.find(params[:id]) if !match.postponed? match.postpone match.save flash[:success] = "Match postponed." else flash[:danger] = "The match was already postponed." end redirect_to match.match_day end private def update_params params.require(:match).permit(:datetime) end end
29.506849
156
0.669452
4a45b0a0c00771b062cc998ac972469eb39955da
314
class CreateContacts < ActiveRecord::Migration[5.1] def change create_table :contacts do |t| t.string :name t.string :email t.string :mobile t.string :project t.string :role t.text :address t.references :user, foreign_key: true t.timestamps end end end
19.625
51
0.627389
b97154132e1619abb6e00835bbd95a54ceed2293
1,372
require 'rails_helper' describe 'Layouts (Design)' do fixtures :users before(:each) do @admin = users(:captain_janeway) log_in_as @admin.login click_link 'Design' end context 'without any layouts' do it 'says it has no layouts' do expect(page).to have_content 'No Layouts' end it 'lets you add a layout' do click_link 'New Layout' fill_in 'Name', with: 'Petunias' fill_in 'Body', with: 'Wisteria' click_button 'Create Layout' expect(page).to have_content 'Petunias' end end context 'with a layout' do before(:each) do Layout.create!(name: 'Petunias', content: 'Wisteria') visit '/admin/layouts' end it 'lets you edit the layout' do click_link 'Petunias' expect(page).to have_content 'Edit Layout' expect(page).to have_field 'Name', with: 'Petunias' expect(page).to have_field 'Body', with: 'Wisteria' expect(page).to have_button 'Save Changes' expect(page).to have_content 'Last Updated by Kathryn Janeway' end it 'lets you remove the layout' do click_link 'Remove' expect(page).to have_content 'Are you sure you want to permanently remove the following layout?' click_button 'Delete Layout' expect(page).to have_content 'No Layouts' expect(page).to have_link 'New Layout' end end end
27.44
102
0.662536
2196c3e0ebda7eacd281a6b8e273962997586f87
2,792
require 'tempfile' module Puppet::Parser::Functions newfunction(:validate_augeas, :doc => <<-'ENDHEREDOC') do |args| Perform validation of a string using an Augeas lens The first argument of this function should be a string to test, and the second argument should be the name of the Augeas lens to use. If Augeas fails to parse the string with the lens, the compilation will abort with a parse error. A third argument can be specified, listing paths which should not be found in the file. The `$file` variable points to the location of the temporary file being tested in the Augeas tree. For example, if you want to make sure your passwd content never contains a user `foo`, you could write: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/foo']) Or if you wanted to ensure that no users used the '/bin/barsh' shell, you could use: validate_augeas($passwdcontent, 'Passwd.lns', ['$file/*[shell="/bin/barsh"]'] If a fourth argument is specified, this will be the error message raised and seen by the user. A helpful error message can be returned like this: validate_augeas($sudoerscontent, 'Sudoers.lns', [], 'Failed to validate sudoers content with Augeas') ENDHEREDOC unless Puppet.features.augeas? raise Puppet::ParseError, ("validate_augeas(): this function requires the augeas feature. See http://docs.puppetlabs.com/guides/augeas.html#pre-requisites for how to activate it.") end if (args.length < 2) or (args.length > 4) then raise Puppet::ParseError, ("validate_augeas(): wrong number of arguments (#{args.length}; must be 2, 3, or 4)") end msg = args[3] || "validate_augeas(): Failed to validate content against #{args[1].inspect}" require 'augeas' aug = Augeas::open(nil, nil, Augeas::NO_MODL_AUTOLOAD) begin content = args[0] # Test content in a temporary file tmpfile = Tempfile.new("validate_augeas") begin tmpfile.write(content) ensure tmpfile.close end # Check for syntax lens = args[1] aug.transform( :lens => lens, :name => 'Validate_augeas', :incl => tmpfile.path ) aug.load! unless aug.match("/augeas/files#{tmpfile.path}//error").empty? error = aug.get("/augeas/files#{tmpfile.path}//error/message") msg += " with error: #{error}" raise Puppet::ParseError, (msg) end # Launch unit tests tests = args[2] || [] aug.defvar('file', "/files#{tmpfile.path}") tests.each do |t| msg += " testing path #{t}" raise Puppet::ParseError, (msg) unless aug.match(t).empty? end ensure aug.close tmpfile.unlink end end end
33.238095
186
0.65043
03368beb9c7172201d8222436541151e73d44456
1,011
# # Copyright (C) 2010-2016 dtk contributors # # This file is part of the dtk project. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # module DTK class NodeImage < Model def self.find_iaas_match(target, logical_image_name) legacy_bridge_to_node_template(target, logical_image_name) end private def self.legacy_bridge_to_node_template(target, logical_image_name) image_id, os_type = Node::Template.find_image_id_and_os_type(logical_image_name, target) image_id end end end
32.612903
94
0.761622
7a02b2a08ef47300703f319f87adf417595e4c71
719
require 'spec_helper' require 'docker/compose' describe 'Example3' do compose = Docker::Compose.new set :docker_container, 'sinatra' before(:all) do compose.up(detached: true) c = Docker::Container.get('consul') sleep 3 # wait for consul to start c.exec(['consul', 'kv', 'put', 'sinatra/message', 'hello from consul']) end after(:all) do compose.kill compose.rm(force: true) end describe 'Consul Connection' do it 'should respond with consul kv "hello from consul"' do wait_for( website_content('http://localhost:4567/message') ).to match(/hello from consul/) end end end def website_content(url) command("curl #{url}").stdout end
21.147059
61
0.653686
f8502a48bd99b197ee506e86738b7e9e6b78d645
5,994
describe MiqAeMethod do let(:user) { FactoryBot.create(:user_with_group) } it "should return editable as false if the parent namespace/class is not editable" do n1 = FactoryBot.create(:miq_ae_system_domain, :tenant => user.current_tenant) c1 = FactoryBot.create(:miq_ae_class, :namespace_id => n1.id, :name => "foo") f1 = FactoryBot.create(:miq_ae_method, :class_id => c1.id, :name => "foo_method", :scope => "instance", :language => "ruby", :location => "inline") expect(f1.editable?(user)).to be_falsey end it "should return editable as true if the parent namespace/class is editable" do n1 = FactoryBot.create(:miq_ae_domain, :tenant => user.current_tenant) c1 = FactoryBot.create(:miq_ae_class, :namespace_id => n1.id, :name => "foo") f1 = FactoryBot.create(:miq_ae_method, :class_id => c1.id, :name => "foo_method", :scope => "instance", :language => "ruby", :location => "inline") expect(f1.editable?(user)).to be_truthy end it "should lookup method" do n1 = FactoryBot.create(:miq_ae_system_domain, :tenant => user.current_tenant) c1 = FactoryBot.create(:miq_ae_class, :namespace_id => n1.id, :name => "foo") f1 = FactoryBot.create(:miq_ae_method, :class_id => c1.id, :name => "foo_method", :scope => "instance", :language => "ruby", :location => "inline") expect(f1.editable?(user)).to be_falsey expect(MiqAeMethod.lookup_by_class_id_and_name(c1.id, "foo_method")).to eq(f1) end context "#copy" do let(:d2) { FactoryBot.create(:miq_ae_domain, :name => "domain2", :priority => 2) } let(:ns1) { FactoryBot.create(:miq_ae_namespace, :name => "ns1", :parent_id => @d1.id) } let(:m1) { FactoryBot.create(:miq_ae_method, :class_id => @cls1.id, :name => "foo_method1", :scope => "instance", :language => "ruby", :location => "inline") } let(:m2) { FactoryBot.create(:miq_ae_method, :class_id => @cls1.id, :name => "foo_method2", :scope => "instance", :language => "ruby", :location => "inline") } before do @d1 = FactoryBot.create(:miq_ae_namespace, :name => "domain1", :parent_id => nil, :priority => 1) @cls1 = FactoryBot.create(:miq_ae_class, :name => "cls1", :namespace_id => ns1.id) @ns2 = FactoryBot.create(:miq_ae_namespace, :name => "ns2", :parent_id => d2.id) end it "copies instances under specified namespace" do options = { :domain => d2.name, :namespace => nil, :overwrite_location => false, :ids => [m1.id, m2.id] } res = MiqAeMethod.copy(options) expect(res.count).to eq(2) end it "copy instances under same namespace raise error when class exists" do options = { :domain => @d1.name, :namespace => ns1.fqname, :overwrite_location => false, :ids => [m1.id, m2.id] } expect { MiqAeMethod.copy(options) }.to raise_error(RuntimeError) end it "replaces instances under same namespace when class exists" do options = { :domain => d2.name, :namespace => @ns2.name, :overwrite_location => true, :ids => [m1.id, m2.id] } res = MiqAeMethod.copy(options) expect(res.count).to eq(2) end end describe "#to_export_xml" do let(:miq_ae_method) do described_class.new( :class_id => 321, :created_on => Time.now, :data => "the data", :id => 123, :inputs => inputs, :updated_by => "me", :updated_on => Time.now ) end let(:inputs) { [miq_ae_field] } let(:miq_ae_field) { MiqAeField.new } before do allow(miq_ae_field).to receive(:to_export_xml) do |options| options[:builder].inputs end end it "produces the expected xml" do expected_xml = <<-XML <MiqAeMethod name="" language="" scope="" location=""><![CDATA[the data]]><inputs/></MiqAeMethod> XML expect(miq_ae_method.to_export_xml).to eq(expected_xml.chomp) end end it "#domain" do d1 = FactoryBot.create(:miq_ae_system_domain, :name => 'dom1', :priority => 10) n1 = FactoryBot.create(:miq_ae_namespace, :name => 'ns1', :parent_id => d1.id) c1 = FactoryBot.create(:miq_ae_class, :namespace_id => n1.id, :name => "foo") m1 = FactoryBot.create(:miq_ae_method, :class_id => c1.id, :name => "foo_method", :scope => "instance", :language => "ruby", :location => "inline") expect(m1.domain.name).to eql('dom1') end it "#to_export_yaml" do d1 = FactoryBot.create(:miq_ae_system_domain, :name => 'dom1', :priority => 10) n1 = FactoryBot.create(:miq_ae_namespace, :name => 'ns1', :parent_id => d1.id) c1 = FactoryBot.create(:miq_ae_class, :namespace_id => n1.id, :name => "foo") m1 = FactoryBot.create(:miq_ae_method, :class_id => c1.id, :name => "foo_method", :scope => "instance", :language => "ruby", :location => "inline") result = m1.to_export_yaml expect(result['name']).to eql('foo_method') expect(result['location']).to eql('inline') keys = result.keys expect(keys.exclude?('options')).to be_truthy expect(keys.exclude?('embedded_methods')).to be_truthy end end
39.96
163
0.541041
38a96b84c8687cc0b2e7d5205e812b889bd10c03
2,704
require 'test_helper' class ResetsControllerTest < CleanControllerTest setup do @user = User.make!(password: 'Password1') end test "Can't do anything if logged in" do log_in(@user) assert_404([ [:get, :new, nil], [:get, :show, {params: {id: 'foo'}}], [:post, :create, {params: {reset: {email: 'foo'}}}], [:patch, :update, {params: {id: 'foo', password: '12345678'}}] ]) end test "new loads and renders" do get :new assert_response :success assert_template :new end test "can create a new reset with a valid email" do post :create, params: { reset: { email: @user.email }}, format: 'js' assert_response :success assert @response.body.include? "check your email" end test "can't create a new reset with an invalid email" do post :create, params: { reset: { email: 'foo' }}, format: 'js' assert_response :unprocessable_entity assert @response.body.include? 'too short' end test "valid emails pretend to work if the address isn't found" do post :create, params: { reset: { email: 'foo@bar.com' }}, format: 'js' assert_response :success assert @response.body.include? "check your email" end test "can view a reset if it's still valid" do reset = Reset.create email: @user.email get :show, params: { id: reset.token } assert_response :success assert assigns(:reset) assert_template :show end test "can't view a reset if it doesn't exist" do assert_404 [[:get, :show, {params: {id: 'fdsfds'}}]] end test "can't view a reset if it's expired" do reset = Reset.create email: @user.email Timecop.freeze(Time.now + 1.month) do assert_404 [[:get, :show, {params: {id: reset.token}}]] end end test "can set a new password for a valid reset" do reset = Reset.create email: @user.email patch :update, params: {id: reset.token, password: '12345678'}, format: 'js' assert_response 302 assert @response.body.include? sign_in_path end test "can't set a new password for an invalid reset" do assert_404 [[:patch, :update, {params: {id: 'foo', password: '12345678', format: 'js'}}]] end test "can't set a new password for an expired reset" do reset = Reset.create email: @user.email Timecop.freeze(Time.now + 1.month) do assert_404 [[:patch, :update, {params: {id: reset.token, password: '12345678', format: 'js'}}]] end end test "can't reset password with invalid password" do reset = Reset.create email: @user.email patch :update, params: { id: reset.token, password: ''}, format: 'js' assert_response :unprocessable_entity assert @response.body.include? 'too short' end end
31.44186
101
0.653476
33b739c8aee96dd26ec0c41ad9717f83617ca9ff
81
class Redis class Retryable class RetryError < RuntimeError; end end end
13.5
40
0.740741
ac2c9d3f9d3eef834fd364c5275d70b2dd992cab
425
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ApiManagement::Mgmt::V2016_07_07 module Models # # Defines values for NameAvailabilityReason # module NameAvailabilityReason Valid = "Valid" Invalid = "Invalid" AlreadyExists = "AlreadyExists" end end end
23.611111
70
0.708235
21a85e313342382e10c002921de415e48b668248
5,845
# 0: Original class MountainBike TIRE_WIDTH_FACTOR = 0.6 FRONT_SUSPENSION_FACTOR = 0.5 REAR_SUSPENSION_FACTOR = 0.4 def initialize(params) params.each { |key, value| instance_variable_set "@#{key}", value } @base_price ||= 300 @front_suspension_price ||= 200 @rear_suspension_price ||= 100 @commission ||= 0.05 @rear_fork_travel ||= 1.1 @front_fork_travel ||= 0.8 end def off_road_ability result = @tire_width * TIRE_WIDTH_FACTOR if @type_code == :front_suspension || @type_code == :full_suspension result += @front_fork_travel * FRONT_SUSPENSION_FACTOR end if @type_code == :full_suspension result += @rear_fork_travel * REAR_SUSPENSION_FACTOR end result end def price case @type_code when :rigid (1 + @commission) * @base_price when :front_suspension (1 + @commission) * @base_price + @front_suspension_price when :full_suspension (1 + @commission) * @base_price + @front_suspension_price + @rear_suspension_price end end end # # First: Create a Class for Each Type, Change the Class that uses the type code into a module # # module MountainBike # TIRE_WIDTH_FACTOR = 0.6 # FRONT_SUSPENSION_FACTOR = 0.5 # REAR_SUSPENSION_FACTOR = 0.4 # # def initialize(params) # params.each { |key, value| instance_variable_set "@#{key}", value } # @base_price ||= 300 # @front_suspension_price ||= 200 # @rear_suspension_price ||= 100 # @commission ||= 0.05 # @rear_fork_travel ||= 1.1 # @front_fork_travel ||= 0.8 # end # # def off_road_ability # result = @tire_width * TIRE_WIDTH_FACTOR # if @type_code == :front_suspension || @type_code == :full_suspension # result += @front_fork_travel * FRONT_SUSPENSION_FACTOR # end # if @type_code == :full_suspension # result += @rear_fork_travel * REAR_SUSPENSION_FACTOR # end # result # end # # def price # case @type_code # when :rigid # (1 + @commission) * @base_price # when :front_suspension # (1 + @commission) * @base_price + @front_suspension_price # when :full_suspension # (1 + @commission) * @base_price + @front_suspension_price + @rear_suspension_price # end # end # end # class RigidMountainBike # include MountainBike # end # # class FrontSuspensionMountainBike # include MountainBike # end # # class FullSuspensionMountainBike # include MountainBike # end # # Second override the polymorphic methods in the new classes # # module MountainBike # TIRE_WIDTH_FACTOR = 0.6 # FRONT_SUSPENSION_FACTOR = 0.5 # REAR_SUSPENSION_FACTOR = 0.4 # # def initialize(params) # params.each { |key, value| instance_variable_set "@#{key}", value } # @base_price ||= 300 # @front_suspension_price ||= 200 # @rear_suspension_price ||= 100 # @commission ||= 0.05 # @rear_fork_travel ||= 1.1 # @front_fork_travel ||= 0.8 # end # # def off_road_ability # result = @tire_width * TIRE_WIDTH_FACTOR # if @type_code == :front_suspension || @type_code == :full_suspension # result += @front_fork_travel * FRONT_SUSPENSION_FACTOR # end # if @type_code == :full_suspension # result += @rear_fork_travel * REAR_SUSPENSION_FACTOR # end # result # end # # def price # case @type_code # when :rigid # (1 + @commission) * @base_price # when :front_suspension # (1 + @commission) * @base_price + @front_suspension_price # when :full_suspension # (1 + @commission) * @base_price + @front_suspension_price + @rear_suspension_price # end # end # end # # class RigidMountainBike # include MountainBike # # def off_road_ability # @tire_width * TIRE_WIDTH_FACTOR # end # # def price # (1 + @commission) * @base_price # end # end # # class FrontSuspensionMountainBike # include MountainBike # # def off_road_ability # @tire_width * TIRE_WIDTH_FACTOR + @front_fork_travel * FRONT_SUSPENSION_FACTOR # end # # def price # (1 + @commission) * @base_price + @front_suspension_price # end # end # # class FullSuspensionMountainBike # include MountainBike # # def off_road_ability # @tire_width * TIRE_WIDTH_FACTOR + # @front_fork_travel * FRONT_SUSPENSION_FACTOR + # @rear_fork_travel * REAR_SUSPENSION_FACTOR # end # # def price # (1 + @commission) * @base_price + @front_suspension_price + @rear_suspension_price # end # end # # Third remove unneeded methods from the module, or delete the module of totally unneeded # # module MountainBike # TIRE_WIDTH_FACTOR = 0.6 # FRONT_SUSPENSION_FACTOR = 0.5 # REAR_SUSPENSION_FACTOR = 0.4 # # def initialize(params) # params.each { |key, value| instance_variable_set "@#{key}", value } # @base_price ||= 300 # @front_suspension_price ||= 200 # @rear_suspension_price ||= 100 # @commission ||= 0.05 # @rear_fork_travel ||= 1.1 # @front_fork_travel ||= 0.8 # end # end # # class RigidMountainBike # include MountainBike # # def off_road_ability # @tire_width * TIRE_WIDTH_FACTOR # end # # def price # (1 + @commission) * @base_price # end # end # # class FrontSuspensionMountainBike # include MountainBike # # def off_road_ability # @tire_width * TIRE_WIDTH_FACTOR + @front_fork_travel * FRONT_SUSPENSION_FACTOR # end # # def price # (1 + @commission) * @base_price + @front_suspension_price # end # end # # class FullSuspensionMountainBike # include MountainBike # # def off_road_ability # @tire_width * TIRE_WIDTH_FACTOR + # @front_fork_travel * FRONT_SUSPENSION_FACTOR + # @rear_fork_travel * REAR_SUSPENSION_FACTOR # end # # def price # (1 + @commission) * @base_price + @front_suspension_price + @rear_suspension_price # end # end
25.524017
95
0.667066
1a9e9ea358fdc1bf38585105c8ecce83cbc5b4d2
1,035
require 'spec_helper' class UsageJsSpec < Bootstrap::Sass::Rails::Spec describe 'application.js' do let(:app_js) { dummy_asset('application.js') } it 'will render main bootstrap.js file and all included modules' do app_js.must_include 'affix.js' app_js.must_include 'alert.js' app_js.must_include 'button.js' app_js.must_include 'carousel.js' app_js.must_include 'collapse.js' app_js.must_include 'dropdown.js' app_js.must_include 'modal.js' app_js.must_include 'popover.js' app_js.must_include 'scrollspy.js' app_js.must_include 'tab.js' app_js.must_include 'tooltip.js' app_js.must_include 'transition.js' end it 'must include basic js afterward' do app_js.must_include '$(document).ready(function(){...});' end end describe 'individual.js' do let(:individual_js) { dummy_asset('individual.js') } it 'will render bootstrap variables and mixins' do individual_js.must_include 'modal.js' end end end
25.243902
71
0.685024
e9ade35d60ef6ba787a542a6f2b99850ebf98bf1
926
require 'rails_helper' describe 'list src images using the JSON API', type: :request do it 'lists src images' do src_image = FactoryGirl.create(:src_image, work_in_progress: false) src_image.set_derived_image_fields src_image.save! src_image.reload get( '/api/v3/src_images', '', 'HTTP_ACCEPT' => 'application/json') expect(JSON.parse(response.body)).to eq( [ { 'id_hash' => src_image.id_hash, 'width' => 399, 'height' => 399, 'size' => 9141, 'content_type' => 'image/jpeg', 'created_at' => src_image.created_at.strftime('%Y-%m-%dT%H:%M:%S.%LZ'), 'updated_at' => src_image.updated_at.strftime('%Y-%m-%dT%H:%M:%S.%LZ'), 'name' => 'src image name', 'image_url' => "http://www.example.com/src_images/#{src_image.id_hash}.jpg" } ] ) end end
26.457143
71
0.557235
18f07751914d9327114c9436cdbbf7687511ccfb
1,260
module BibleReferenceParser # This module encapsulates shared behavior for classes that keep track of parsing errors. # For example, a BookReference may encounter a parsing error due to a book that doesn't # exist. A ChapterReference may have a parsing error because the chapter number isn't valid # for the book it is referencing. module TracksErrors def initialize(*args, &block) super # A collection of error messages. @errors = [] end # Add an error message. def add_error(message) @errors << message end # Erase all error messages. def clear_errors @errors = [] end # Get the list of error messages. This will include any errors in child references # if include_child_errors is true (by default it's true). def errors(include_child_errors = true) if(include_child_errors && respond_to?("children") && children) return @errors + children.errors(true) end @errors end # Whether any errors occured when parsing. def has_errors? !errors.empty? end # Convienence method for the reverse of "has_errors?" def no_errors? errors.empty? end end end
27.391304
94
0.645238
ab11e3b4276050959e06b31a3b5aa17b452a0e75
1,029
SwellMedia::Engine.routes.draw do root to: 'static#home' # set media to HP if null id #resources :admin, only: :index resources :articles, path: SwellMedia.article_path resources :article_admin, path: 'blog_admin' do get :preview, on: :member delete :empty_trash, on: :collection end resources :asset_manager, only: [ :new, :create, :destroy ] do post :callback_create, on: :collection get :callback_create, on: :collection end resources :asset_admin do delete :empty_trash, on: :collection end resources :browse resources :category_admin resources :contacts do get :thanks, on: :collection end resources :contact_admin resources :optins, only: [:create] do get :thank_you, on: :member, path: 'thank-you' end resources :page_admin do put :clone, on: :member get :preview, on: :member delete :empty_trash, on: :collection end resources :user_admin # quick catch-all route for static pages # set root route to field any media get '/:id', to: 'root#show', as: 'root_show' end
21
63
0.718173
e88a88d821be12963680d2748b44078c7d06a470
254
# frozen_string_literal: true class DropParticipationRecord < ActiveRecord::Migration[6.1] def change drop_table :participation_records, id: :uuid do |t| t.timestamps t.string :state, null: false, default: "assigned" end end end
23.090909
60
0.712598
9199555b55341f43520d27494923eda8de5f2588
22
module BandHelper end
7.333333
17
0.863636
e9f534d9e2f956449bfb2cd6916bfa7e13034a05
3,601
module ActionView::Helpers::TagHelper def william_paginate(total_count = (@count || 0), per_page = @per_page, page = (@page || 1), method = :get) page = 1 if page < 1 max = (total_count / (per_page*1.0)).ceil rescue 1 page = max if page > max adjacents = 2 prev_page = page - 1 next_page = page + 1 last_page = (total_count / per_page.to_f).ceil lpm1 = last_page - 1 returning '' do |pgn| if last_page > 1 pgn << %{<div class="pagination">} pgn << (page > 1 ? link_to("&laquo; Previous", params.merge(:page => prev_page), {:method => method}) : content_tag(:span, "&laquo; Previous", :class => 'disabled')) # not enough pages to bother breaking if last_page < 7 + (adjacents * 2) 1.upto(last_page) { |ctr| pgn << (ctr == page ? content_tag(:span, ctr, :class => 'current') : link_to(ctr, params.merge(:page => ctr), {:method => method})) } # enough pages to hide some elsif last_page > 5 + (adjacents * 2) # close to beginning, only hide later pages if page < 1 + (adjacents * 2) 1.upto(3 + (adjacents * 2)) { |ctr| pgn << (ctr == page ? content_tag(:span, ctr, :class => 'current') : link_to(ctr, {:page => ctr}, {:method => method})) } pgn << "..." + link_to(lpm1, params.merge(:page => lpm1), {:method => method}) + link_to(last_page, params.merge(:page => last_page), {:method => method}) # in middle, hide some from both sides elsif last_page - (adjacents * 2) > page && page > (adjacents * 2) pgn << link_to('1', params.merge(:page => 1), {:method => method}) + link_to('2', params.merge(:page => 2), {:method => method}) + "..." (page - adjacents).upto(page + adjacents) { |ctr| pgn << (ctr == page ? content_tag(:span, ctr, :class => 'current') : link_to(ctr, params.merge(:page => ctr), {:method => method})) } pgn << "..." + link_to(lpm1, params.merge(:page => lpm1), {:method => method}) + link_to(last_page, params.merge(:page => last_page), {:method => method}) # close to end, only hide early pages else pgn << link_to('1', params.merge(:page => 1), {:method => method}) + link_to('2', params.merge(:page => 2), {:method => method}) + "..." (last_page - (2 + (adjacents * 2))).upto(last_page) { |ctr| pgn << (ctr == page ? content_tag(:span, ctr, :class => 'current') : link_to(ctr, params.merge(:page => ctr), {:method => method})) } end end pgn << (page < last_page ? link_to("Next &raquo;", params.merge(:page => next_page), {:method => method}) : content_tag(:span, "Next &raquo;", :class => 'disabled')) if method==:post pgn << "<select style=\"width: 50px;\" id=\"leftside_select_for_pager\" class=\"no_border\" onchange=\"var f = document.createElement('form'); f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.value;f.submit();return false;\">" 1.upto(last_page){|i| pgn << "<option #{'selected="selected" ' if page == i}value=\"#{url_for(params.merge(:page => i))}\">#{i}</option>"} pgn << "</select>" else pgn << "<select style=\"width: 50px;\" id=\"leftside_select_for_pager\" class=\"no_border\" onchange=\"window.location=this.value;\">" 1.upto(last_page){|i| pgn << "<option #{'selected="selected" ' if page == i}value=\"#{url_for(params.merge(:page => i))}\">#{i}</option>"} pgn << "</select>" end pgn << '</div>' end end end end
62.086207
280
0.563455
280da1bf3594ce8198b518eb48ca796fe1b14639
723
# TODO - relies on rake to load files for us class AutoSeed4 < SeedSuper # TODO - this chunk should be configured in a file somewhere ... yaml? # TODO - faker gem should go in here # TODO - wrap in it's own method - in prep for going to file or faker gem # Preping the attributes def self.make_fields(model) # Preping the attributes insert_string = "1234" # default string in attributes reject_attribs = ["id", "created_at", "updated_at"] # Attributes to filter attribs = model.column_names - reject_attribs # drop extra db columns attribs = attribs.map {|x| [x, insert_string]}.to_h # setup hash of columns return attribs end end
32.863636
80
0.652835
d509283273ac097acac02520ab9074998ee8f116
5,546
# frozen_string_literal: true module RuboCop module Cop module Lint # # This cop emulates the following Ruby warnings in Ruby 2.6. # # % cat example.rb # ERB.new('hi', nil, '-', '@output_buffer') # % ruby -rerb example.rb # example.rb:1: warning: Passing safe_level with the 2nd argument of # ERB.new is deprecated. Do not use it, and specify other arguments as # keyword arguments. # example.rb:1: warning: Passing trim_mode with the 3rd argument of # ERB.new is deprecated. Use keyword argument like # ERB.new(str, trim_mode:...) instead. # example.rb:1: warning: Passing eoutvar with the 4th argument of ERB.new # is deprecated. Use keyword argument like ERB.new(str, eoutvar: ...) # instead. # # Now non-keyword arguments other than first one are softly deprecated # and will be removed when Ruby 2.5 becomes EOL. # `ERB.new` with non-keyword arguments is deprecated since ERB 2.2.0. # Use `:trim_mode` and `:eoutvar` keyword arguments to `ERB.new`. # This cop identifies places where `ERB.new(str, trim_mode, eoutvar)` can # be replaced by `ERB.new(str, :trim_mode: trim_mode, eoutvar: eoutvar)`. # # @example # # Target codes supports Ruby 2.6 and higher only # # bad # ERB.new(str, nil, '-', '@output_buffer') # # # good # ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') # # # Target codes supports Ruby 2.5 and lower only # # good # ERB.new(str, nil, '-', '@output_buffer') # # # Target codes supports Ruby 2.6, 2.5 and lower # # bad # ERB.new(str, nil, '-', '@output_buffer') # # # good # # Ruby standard library style # # https://github.com/ruby/ruby/commit/3406c5d # if ERB.instance_method(:initialize).parameters.assoc(:key) # Ruby 2.6+ # ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') # else # ERB.new(str, nil, '-', '@output_buffer') # end # # # good # # Use `RUBY_VERSION` style # if RUBY_VERSION >= '2.6' # ERB.new(str, trim_mode: '-', eoutvar: '@output_buffer') # else # ERB.new(str, nil, '-', '@output_buffer') # end # class ErbNewArguments < Base include RangeHelp extend TargetRubyVersion extend AutoCorrector minimum_target_ruby_version 2.6 MESSAGES = [ 'Passing safe_level with the 2nd argument of `ERB.new` is ' \ 'deprecated. Do not use it, and specify other arguments as ' \ 'keyword arguments.', 'Passing trim_mode with the 3rd argument of `ERB.new` is ' \ 'deprecated. Use keyword argument like ' \ '`ERB.new(str, trim_mode: %<arg_value>s)` instead.', 'Passing eoutvar with the 4th argument of `ERB.new` is ' \ 'deprecated. Use keyword argument like ' \ '`ERB.new(str, eoutvar: %<arg_value>s)` instead.' ].freeze RESTRICT_ON_SEND = %i[new].freeze # @!method erb_new_with_non_keyword_arguments(node) def_node_matcher :erb_new_with_non_keyword_arguments, <<~PATTERN (send (const {nil? cbase} :ERB) :new $...) PATTERN def on_send(node) erb_new_with_non_keyword_arguments(node) do |arguments| return if arguments.empty? || correct_arguments?(arguments) arguments[1..3].each_with_index do |argument, i| next if !argument || argument.hash_type? message = format(MESSAGES[i], arg_value: argument.source) add_offense( argument.source_range, message: message ) do |corrector| autocorrect(corrector, node) end end end end private def autocorrect(corrector, node) str_arg = node.arguments[0].source kwargs = build_kwargs(node) overridden_kwargs = override_by_legacy_args(kwargs, node) good_arguments = [str_arg, overridden_kwargs].flatten.compact.join(', ') corrector.replace(arguments_range(node), good_arguments) end def correct_arguments?(arguments) arguments.size == 1 || arguments.size == 2 && arguments[1].hash_type? end def build_kwargs(node) return [nil, nil] unless node.arguments.last.hash_type? trim_mode_arg, eoutvar_arg = nil node.arguments.last.pairs.each do |pair| case pair.key.source when 'trim_mode' trim_mode_arg = "trim_mode: #{pair.value.source}" when 'eoutvar' eoutvar_arg = "eoutvar: #{pair.value.source}" end end [trim_mode_arg, eoutvar_arg] end def override_by_legacy_args(kwargs, node) arguments = node.arguments overridden_kwargs = kwargs.dup overridden_kwargs[0] = "trim_mode: #{arguments[2].source}" if arguments[2] if arguments[3] && !arguments[3].hash_type? overridden_kwargs[1] = "eoutvar: #{arguments[3].source}" end overridden_kwargs end def arguments_range(node) arguments = node.arguments range_between(arguments.first.source_range.begin_pos, arguments.last.source_range.end_pos) end end end end end
34.02454
100
0.583664
ff195392ca03f82f2f4e31a4e879cf1353bcc454
148
class AddEditorFeedbackToUsers < ActiveRecord::Migration def change add_column :users, :editor_feedback, :boolean, :default => false end end
24.666667
67
0.77027
e277d8751a5ff3b05a9bbd898df4f3a04db704f0
1,129
# frozen_string_literal: true module TestHelpers class FakePushPackageRepository def initialize @cache = {} end def create_push_package( script_project:, script_content:, compiled_type:, metadata:, library: ) id = id(script_project.script_name, compiled_type) @cache[id] = Script::Layers::Domain::PushPackage.new( id: id, uuid: script_project.uuid, extension_point_type: script_project.extension_point_type, script_content: script_content, compiled_type: compiled_type, metadata: metadata, script_config: script_project.script_config, library: library ) end def get_push_package(script_project:, compiled_type:, metadata:, library:) _ = metadata _ = library id = id(script_project.script_name, compiled_type) if @cache.key?(id) @cache[id] else raise Script::Layers::Domain::Errors::PushPackageNotFoundError end end private def id(script_name, compiled_type) "#{script_name}.#{compiled_type}" end end end
24.021277
78
0.64659
03fe924de63c8d8c7a39a2f5a2eb170bffe7c8c6
2,689
require 'rollbar' begin require 'rack/mock' rescue LoadError end require 'logger' namespace :rollbar do desc 'Verify your gem installation by sending a test exception to Rollbar' task :test => [:environment] do if defined?(Rails) Rails.logger = if defined?(ActiveSupport::TaggedLogging) ActiveSupport::TaggedLogging.new(Logger.new(STDOUT)) else Logger.new(STDOUT) end Rails.logger.level = Logger::DEBUG Rollbar.preconfigure do |config| config.logger = Rails.logger end end class RollbarTestingException < RuntimeError; end unless Rollbar.configuration.access_token puts 'Rollbar needs an access token configured. Check the README for instructions.' exit end puts 'Testing manual report...' Rollbar.error('Test error from rollbar:test') # Module to inject into the Rails controllers or # rack apps module RollbarTest def test_rollbar puts 'Raising RollbarTestingException to simulate app failure.' raise RollbarTestingException.new, 'Testing rollbar with "rake rollbar:test". If you can see this, it works.' end end if defined?(Rack::MockRequest) if defined?(Rails) puts 'Setting up the controller.' class RollbarTestController < ActionController::Base include RollbarTest def verify test_rollbar end def logger nil end end Rails.application.routes_reloader.execute_if_updated Rails.application.routes.draw do get 'verify' => 'rollbar_test#verify', :as => 'verify' end # from http://stackoverflow.com/questions/5270835/authlogic-activation-problems if defined? Authlogic Authlogic::Session::Base.controller = Authlogic::ControllerAdapters::RailsAdapter.new(self) end protocol = (defined? Rails.application.config.force_ssl && Rails.application.config.force_ssl) ? 'https' : 'http' app = Rails.application else protocol = 'http' app = Class.new do include RollbarTest def self.call(_env) new.test_rollbar end end end puts 'Processing...' env = Rack::MockRequest.env_for("#{protocol}://www.example.com/verify") status, = app.call(env) unless status.to_i == 500 puts 'Test failed! You may have a configuration issue, or you could be using a gem that\'s blocking the test. Contact support@rollbar.com if you need help troubleshooting.' end end end end
28.606383
180
0.633321
ff5b9e53d28804a9bcbed66bda7d814fde96ebbb
2,789
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::ImportExport::Mgmt::V2016_11_01 module Models # # A property containing information about the blobs to be exported for an # export job. This property is required for export jobs, but must not be # specified for import jobs. # class Export include MsRestAzure # @return [Array<String>] A collection of blob-path strings. attr_accessor :blob_path # @return [Array<String>] A collection of blob-prefix strings. attr_accessor :blob_path_prefix # @return [String] The relative URI to the block blob that contains the # list of blob paths or blob path prefixes as defined above, beginning # with the container name. If the blob is in root container, the URI must # begin with $root. attr_accessor :blob_listblob_path # # Mapper for Export class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'Export', type: { name: 'Composite', class_name: 'Export', model_properties: { blob_path: { client_side_validation: true, required: false, serialized_name: 'blobList.blobPath', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, blob_path_prefix: { client_side_validation: true, required: false, serialized_name: 'blobList.blobPathPrefix', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'StringElementType', type: { name: 'String' } } } }, blob_listblob_path: { client_side_validation: true, required: false, serialized_name: 'blobListblobPath', type: { name: 'String' } } } } } end end end end
30.988889
79
0.499821
ff40ea3c140efcbb7bad1d5c0a32af5992cb5cbc
3,961
# encoding: utf-8 #-- # Copyright 2013-2015 DataStax, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #++ module Cassandra module Auth # An auth provider is a factory for {Cassandra::Auth::Authenticator authenticator} instances (or objects matching that interface). Its # {#create_authenticator} will be called once for each connection that # requires authentication. # # If the authentication requires keeping state, keep that in the # authenticator instances, not in the auth provider. # # @note Creating an authenticator must absolutely not block, or the whole # connection process will block. # # @abstract Auth providers given to {Cassandra.cluster} don't need to be # subclasses of this class, but need to implement the same methods. This # class exists only for documentation purposes. # # @see Cassandra::Auth::Providers class Provider # @!method create_authenticator(authentication_class, protocol_version) # # Create a new authenticator object. This method will be called once per # connection that requires authentication. The auth provider can create # different authenticators for different authentication classes, or return # nil if it does not support the authentication class. # # @note This method must absolutely not block. # # @param authentication_class [String] the authentication class used by # the server. # @return [Cassandra::Auth::Authenticator, nil] an object with an # interface matching {Cassandra::Auth::Authenticator} or `nil` if the # authentication class is not supported. end # An authenticator handles the authentication challenge/response cycles of # a single connection. It can be stateful, but it must not for any reason # block. If any of the method calls block, the whole connection process # will be blocked. # # @abstract Authenticators created by auth providers don't need to be # subclasses of this class, but need to implement the same methods. This # class exists only for documentation purposes. # # @see https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v2.spec#L257-L273 Cassandra native protocol v2 SASL authentication # @see Cassandra::Auth::Provider#create_authenticator class Authenticator # @!method initial_response # # This method must return the initial authentication token to be sent to # the server. # # @note This method must absolutely not block. # # @return [String] the initial authentication token # @!method challenge_response(token) # # If the authentication requires multiple challenge/response cycles this # method will be called when a challenge is returned by the server. A # response token must be created and will be sent back to the server. # # @note This method must absolutely not block. # # @param token [String] a challenge token sent by the server # @return [String] the authentication token to send back to the server # @!method authentication_successful(token) # # Called when the authentication is successful. # # @note This method must absolutely not block. # # @param token [String] a token sent by the server # @return [void] end end end require 'cassandra/auth/providers'
40.418367
144
0.703105
4af27add36c07e36144bec40b047e001040a65fe
369
class CreateShortenedUrls < ActiveRecord::Migration[5.1] def change create_table :shortened_urls do |t| t.string :long_url, null: false t.string :short_url, null: false t.integer :submitter_id, null: false t.timestamps end add_index :shortened_urls, :short_url, unique: true add_index :shortened_urls, :submitter_id end end
26.357143
56
0.704607
ff84eb9375478c313d2b6a7882a8c367aba7c7cf
593
Pod::Spec.new do |s| s.name = "PokerNowKit" s.version = "0.0.10" s.summary = "Shared framework of PokerNow.club log parsing code" s.homepage = "https://github.com/pj4533/PokerNowKit" s.license = { :type => "MIT", :file => "LICENSE" } s.author = { "PJ Gray" => "pj4533@gmail.com" } s.source = { :git => "git@github.com:pj4533/PokerNowKit.git", :tag => s.version } s.swift_version = "5.0" s.osx.deployment_target = "10.10" s.dependency 'CryptoSwift' s.source_files = "PokerNowKit/**/*.{h,swift}" s.requires_arc = true end
31.210526
89
0.591906
380f48fab793dde3886a4468c89d16b2593611b7
848
ENV['RAILS_ENV'] ||= 'test' require File.expand_path('../../config/environment', __FILE__) require 'rails/test_help' class ActiveSupport::TestCase # Setup all fixtures in test/fixtures/*.yml for all tests in alphabetical order. fixtures :all # Add more helper methods to be used by all tests here... # Returns true if a test user is logged in. def is_logged_in? !session[:user_id].nil? end # Log in as a particular user. def log_in_as(user) session[:user_id] = user.id end end class ActionDispatch::IntegrationTest # Log in as a particular user. def log_in_as(user, password: 'password', remember_me: '1') post login_path, params: { session: { email: user.email, password: password, remember_me: remember_me } } end end
27.354839
82
0.639151
e8a943789a11f5e615de28f3573bdff467758b23
1,054
require_relative "shared_examples_for_index" require_relative "shared_examples_for_tags" RSpec.describe("v3.0 - ContainerGroup") do include ::Spec::Support::TenantIdentity let(:headers) { {"CONTENT_TYPE" => "application/json", "x-rh-identity" => identity} } let(:container_node) { ContainerNode.create!(:tenant => tenant, :source => source, :source_ref => SecureRandom.uuid) } let(:container_project) { ContainerProject.create!(:tenant => tenant, :source => source, :source_ref => SecureRandom.uuid) } let(:source) { Source.create!(:tenant => tenant) } let(:attributes) do { "container_node_id" => container_node.id.to_s, "container_project_id" => container_project.id.to_s, "source_id" => source.id.to_s, "tenant_id" => tenant.id.to_s, "source_ref" => SecureRandom.uuid } end include_examples( "v3x0_test_index_and_subcollections", "container_groups", ["containers"], ) include_examples("v3x0_test_tags_subcollection", "container_groups") end
35.133333
126
0.680266
394568a3e30f37940a0c87d504033e9131877a22
1,101
cask 'unity-ios-support-for-editor@2018.1.9f1' do version '2018.1.9f1,24bbd83e8b9e' sha256 :no_check url "https://download.unity3d.com/download_unity/24bbd83e8b9e/MacEditorTargetInstaller/UnitySetup-iOS-Support-for-Editor-2018.1.9f1.pkg" name 'iOS Build Support' homepage 'https://unity3d.com/unity/' pkg 'UnitySetup-iOS-Support-for-Editor-2018.1.9f1.pkg' depends_on cask: 'unity@2018.1.9f1' preflight do if File.exist? "/Applications/Unity" FileUtils.move "/Applications/Unity", "/Applications/Unity.temp" end if File.exist? "/Applications/Unity-2018.1.9f1" FileUtils.move "/Applications/Unity-2018.1.9f1", '/Applications/Unity' end end postflight do if File.exist? '/Applications/Unity' FileUtils.move '/Applications/Unity', "/Applications/Unity-2018.1.9f1" end if File.exist? '/Applications/Unity.temp' FileUtils.move '/Applications/Unity.temp', '/Applications/Unity' end end uninstall quit: 'com.unity3d.UnityEditor5.x', delete: '/Applications/Unity-2018.1.9f1/PlaybackEngines/iOSSupport' end
30.583333
138
0.71208
6187d6aa1c5dd378e2cc4b0d1a957079eaa41db0
2,658
class PostsController < ApplicationController before_action :set_post, only: [:show, :edit, :update, :destroy] # GET /posts # GET /posts.json def index case params[:sort] when 'newest' @posts = Post.paginate(page: params[:page], per_page: 15).order(created_at: :desc) else @posts = Post.paginate(page: params[:page], per_page: 15).order(score: :desc) end if current_user @votes = current_user.votes @posts.map do |post| post.update_score post.save @votes.each do |vote| post.current_user_voted = true if vote.post_id == post.id end end end end def preview temporary_attributes = Post.scrape_site(params[:link]) if temporary_attributes @post = Post.new(temporary_attributes) render :'_form.html.erb', layout: false if request.xhr? else flash[:warning] = "Please enter a valid URL" redirect '/' end end # GET /posts/1 # GET /posts/1.json def show end # GET /posts/new def new @post = Post.new end # GET /posts/1/edit def edit end # POST /posts # POST /posts.json def create @post = Post.new(post_params) @post.user_id = current_user.id respond_to do |format| if @post.save format.html { redirect_to '/?sort=newest'} # , notice: 'Post was successfully created.' format.json { render :show, status: :created, location: @post } else format.html { render :new } format.json { render json: @post.errors, status: :unprocessable_entity } end end end # PATCH/PUT /posts/1 # PATCH/PUT /posts/1.json def update respond_to do |format| if @post.update(post_params) format.html { redirect_to @post, notice: 'Post was successfully updated.' } format.json { render :show, status: :ok, location: @post } else format.html { render :edit } format.json { render json: @post.errors, status: :unprocessable_entity } end end end # DELETE /posts/1 # DELETE /posts/1.json def destroy @post.destroy respond_to do |format| format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_post @post = Post.find(params[:id]) end # Never trust parameters from the scary internet, only allow the white list through. def post_params params.require(:post).permit(:title, :vanity_link, :link, :user_id, :upvotes, :score, :summary, :photo_url) end end
25.557692
113
0.634688
6281dfe96d686fc5383aa0a972b50bc7c5eb7d6b
710
cask 'squirrel' do version '0.9.26.2' sha256 '7ba8f934f8d4fe1d42c944ea0771f1a54ed558dd65ea558c4ba4d203505bc130' # dl.bintray.com/lotem/rime was verified as official when first introduced to the cask url "https://dl.bintray.com/lotem/rime/Squirrel-#{version}.zip" name 'Squirrel' homepage 'http://rime.im/download/' depends_on macos: '>= :lion' pkg 'Squirrel.pkg' uninstall pkgutil: 'com.googlecode.rimeime.Squirrel.pkg', delete: '/Library/Input Methods/Squirrel.app' zap delete: [ '~/Library/Caches/com.googlecode.rimeime.inputmethod.Squirrel', '~/Library/Preferences/com.googlecode.rimeime.inputmethod.Squirrel.plist', ] end
32.272727
90
0.694366
f8c9fb14f0d83f8d501560fcbfb222767f05bca4
3,478
# frozen_string_literal: true module EE module Registrations module WelcomeController extend ActiveSupport::Concern extend ::Gitlab::Utils::Override include ::Gitlab::Utils::StrongMemoize TRIAL_ONBOARDING_BOARD_NAME = 'GitLab onboarding' prepended do include OneTrustCSP before_action :authorized_for_trial_onboarding!, only: [ :trial_getting_started, :trial_onboarding_board ] before_action only: :show do publish_combined_registration_experiment end before_action only: [:trial_getting_started] do push_frontend_feature_flag(:gitlab_gtm_datalayer, type: :ops) end end def trial_getting_started render locals: { learn_gitlab_project: learn_gitlab_project } end def trial_onboarding_board board = learn_gitlab_project.boards.find_by_name(TRIAL_ONBOARDING_BOARD_NAME) path = board ? project_board_path(learn_gitlab_project, board) : project_boards_path(learn_gitlab_project) redirect_to path end def continuous_onboarding_getting_started project = ::Project.find(params[:project_id]) return access_denied! unless can?(current_user, :owner_access, project) cookies[:confetti_post_signup] = true render locals: { project: project } end private override :update_params def update_params clean_params = super.merge(params.require(:user).permit(:email_opted_in, :registration_objective)) return clean_params unless ::Gitlab.com? clean_params[:email_opted_in] = '1' if clean_params[:setup_for_company] == 'true' if clean_params[:email_opted_in] == '1' clean_params[:email_opted_in_ip] = request.remote_ip clean_params[:email_opted_in_source_id] = User::EMAIL_OPT_IN_SOURCE_ID_GITLAB_COM clean_params[:email_opted_in_at] = Time.zone.now end clean_params end override :show_signup_onboarding? def show_signup_onboarding? !helpers.in_subscription_flow? && !helpers.user_has_memberships? && !helpers.in_oauth_flow? && !helpers.in_trial_flow? && helpers.signup_onboarding_enabled? end def authorized_for_trial_onboarding! access_denied! unless can?(current_user, :owner_access, learn_gitlab_project) end def learn_gitlab_project strong_memoize(:learn_gitlab_project) do ::Project.find(params[:learn_gitlab_project_id]) end end def publish_combined_registration_experiment combined_registration_experiment.publish if show_signup_onboarding? end def combined_registration_experiment experiment(:combined_registration, user: current_user) end override :update_success_path def update_success_path if params[:joining_project] == 'true' bypass_registration_event(:joining_project) path_for_signed_in_user(current_user) else bypass_registration_event(:creating_project) experiment(:combined_registration, user: current_user).redirect_path end end def bypass_registration_event(event_name) experiment(:bypass_registration, user: current_user).track(event_name, user: current_user) end end end end
31.053571
114
0.678551
87b606313977fc88925a6763a9448f6aacaf06f3
1,250
require 'sinatra' require_relative 'lib/dumb' Dumbstore::App.register_all! # routes get('/') { erb :index } get('/apps') { @apps = Dumbstore::Text.apps.merge(Dumbstore::Voice.apps).values.uniq; erb :apps } get('/about') { erb :about } get('/documentation') { erb :documentation } # These cause method not found errors. See #48 #Dumbstore.twilio_account_sid = ENV['DUMBSTORE_ACCOUNT_SID'] #Dumbstore.twilio_auth_token = ENV['DUMBSTORE_AUTH_TOKEN'] #Dumbstore.twilio_app_name = "Dumbstore - Sandbox" post '/voice' do @params = params if params['Digits'] begin Dumbstore::Voice.get(params['Digits']).voice(params) || Twilio::TwiML::Response.new.text rescue # TODO differentiate errors erb :voice_error end else erb :voice_welcome end end post '/text' do @params = params if params['Body'].empty? erb :text_welcome else param_ary = params['Body'].split @app_id = param_ary.shift.downcase params['Body'] = param_ary.join ' ' begin Dumbstore::Text.get(@app_id).text(params) || Twilio::TwiML::Response.new.text rescue Dumbstore::AppNotFoundError => e # TODO differentiate errors erb :text_app_not_found rescue erb :text_app_crashed end end end
25
97
0.684
26546ff44bb62f26e928007b7ccece46210f32ac
181
module Gluttonberg module Settings class Main < Gluttonberg::Application include Gluttonberg::AdminController def index render end end end end
16.454545
42
0.668508
ffd5e08b75b608db14bff031dde21c666dab5f98
3,680
require_relative 'utilities' require 'yaml' def provision_postgres(root_loc, new_containers) puts colorize_lightblue('Searching for postgres initialisation SQL in the apps') # Load configuration.yml into a Hash config = YAML.load_file("#{root_loc}/dev-env-config/configuration.yml") return unless config['applications'] # Did the container previously exist, if not then we MUST provision regardless of .commodities value new_db_container = false if new_containers.include?('postgres') new_db_container = true puts colorize_yellow('The Postgres container has been newly created - '\ 'provision status in .commodities will be ignored') end started = false config['applications'].each do |appname, _appconfig| # To help enforce the accuracy of the app's dependency file, only search for init sql # if the app specifically specifies postgres in it's commodity list next unless File.exist?("#{root_loc}/apps/#{appname}/configuration.yml") next unless commodity_required?(root_loc, appname, 'postgres') # Load any SQL contained in the apps into the docker commands list if File.exist?("#{root_loc}/apps/#{appname}/fragments/postgres-init-fragment.sql") started = start_postgres_maybe(root_loc, appname, started, new_db_container) else puts colorize_yellow("#{appname} says it uses Postgres but doesn't contain an init SQL file. " \ 'Oh well, onwards we go!') end end end def start_postgres_maybe(root_loc, appname, started, new_db_container) puts colorize_pink("Found some in #{appname}") if commodity_provisioned?(root_loc, appname, 'postgres') && !new_db_container puts colorize_yellow("Postgres has previously been provisioned for #{appname}, skipping") else started = start_postgres(root_loc, appname, started) end started end def start_postgres(root_loc, appname, started) unless started run_command_noshell(['docker-compose', 'up', '-d', 'postgres']) # Better not run anything until postgres is ready to accept connections... puts colorize_lightblue('Waiting for Postgres to finish initialising') command_output = [] command_outcode = 1 until command_outcode.zero? && command_output.any? && command_output[0].start_with?('"healthy"') command_output.clear command_outcode = run_command('docker inspect --format="{{json .State.Health.Status}}" postgres', command_output) puts colorize_yellow('Postgres is unavailable - sleeping') sleep(3) end # Sleep 3 more seconds to allow the root user to be set up if needed sleep(3) puts colorize_green('Postgres is ready') started = true end # Copy the app's init sql into postgres then execute it with psql. # We don't just use docker cp with a plain file path as the source, to deal with WSL, # where LinuxRuby passes a path to WindowsDocker that it can't parse. # Therefore we create and pipe a tar file into docker cp instead, handy as tar runs in the # shell and understands Ruby's paths in both WSL and Git Bash! run_command('tar -c ' \ " -C #{root_loc}/apps/#{appname}/fragments" + # This is the context, so tar will not contain file path ' postgres-init-fragment.sql' + # The file to add to the tar ' | docker cp - postgres:/') # Pipe it into docker cp, which will extract it for us run_command_noshell(['docker', 'exec', 'postgres', 'psql', '-q', '-f', 'postgres-init-fragment.sql']) # Update the .commodities.yml to indicate that postgres has now been provisioned set_commodity_provision_status(root_loc, appname, 'postgres', true) started end
44.878049
119
0.714674
ab0ded4356d4009455321afee631f9acbda8594a
1,989
# frozen_string_literal: true # Copyright (c) 2017-2019 Yegor Bugayenko # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. require 'yaml' require 'aws-sdk-dynamodb' # # Dynamo client # class Dynamo def initialize(config = {}) @config = config end def aws Aws::DynamoDB::Client.new( if ENV['RACK_ENV'] == 'test' cfg = File.join(Dir.pwd, 'dynamodb-local/target/dynamo.yml') raise 'Test config is absent' unless File.exist?(cfg) yaml = YAML.safe_load(File.open(cfg)) { region: 'us-east-1', endpoint: "http://localhost:#{yaml['port']}", access_key_id: yaml['key'], secret_access_key: yaml['secret'], http_open_timeout: 5, http_read_timeout: 5 } else { region: @config['dynamodb']['region'], access_key_id: @config['dynamodb']['key'], secret_access_key: @config['dynamodb']['secret'] } end ) end end
34.293103
80
0.683761
01689045dfb06b17da78580adc7d207de97ee16f
116
require "gemita/version" require "gemita/menu" require "gemita/lista" module Gemita # Your code goes here... end
14.5
26
0.741379
79716df6b6033d1f3f7d688faab33a26700df48f
12,775
# frozen_string_literal: true require 'spec_helper' RSpec.describe Gitlab::Ci::Config::Entry::Root do let(:root) { described_class.new(hash) } describe '.nodes' do it 'returns a hash' do expect(described_class.nodes).to be_a(Hash) end context 'when filtering all the entry/node names' do it 'contains the expected node names' do # No inheritable fields should be added to the `Root` # # Inheritable configuration can only be added to `default:` # # The purpose of `Root` is have only globally defined configuration. expect(described_class.nodes.keys) .to match_array(%i[before_script image services after_script variables cache stages types include default workflow]) end end end context 'when configuration is valid' do context 'when top-level entries are defined' do let(:hash) do { before_script: %w(ls pwd), image: 'ruby:2.7', default: {}, services: ['postgres:9.1', 'mysql:5.5'], variables: { VAR: 'root' }, after_script: ['make clean'], stages: %w(build pages release), cache: { key: 'k', untracked: true, paths: ['public/'] }, rspec: { script: %w[rspec ls] }, spinach: { before_script: [], variables: {}, script: 'spinach' }, release: { stage: 'release', before_script: [], after_script: [], variables: { 'VAR' => 'job' }, script: ["make changelog | tee release_changelog.txt"], release: { tag_name: 'v0.06', name: "Release $CI_TAG_NAME", description: "./release_changelog.txt" } } } end describe '#compose!' do before do root.compose! end it 'creates nodes hash' do expect(root.descendants).to be_an Array end it 'creates node object for each entry' do expect(root.descendants.count).to eq 11 end it 'creates node object using valid class' do expect(root.descendants.first) .to be_an_instance_of Gitlab::Ci::Config::Entry::Default expect(root.descendants.second) .to be_an_instance_of Gitlab::Config::Entry::Unspecified end it 'sets correct description for nodes' do expect(root.descendants.first.description) .to eq 'Default configuration for all jobs.' expect(root.descendants.second.description) .to eq 'List of external YAML files to include.' end describe '#leaf?' do it 'is not leaf' do expect(root).not_to be_leaf end end end context 'when composed' do before do root.compose! end describe '#errors' do it 'has no errors' do expect(root.errors).to be_empty end end describe '#stages_value' do context 'when stages key defined' do it 'returns array of stages' do expect(root.stages_value).to eq %w[build pages release] end end context 'when deprecated types key defined' do let(:hash) do { types: %w(test deploy), rspec: { script: 'rspec' } } end it 'returns array of types as stages' do expect(root.stages_value).to eq %w[test deploy] end end end describe '#jobs_value' do it 'returns jobs configuration' do expect(root.jobs_value.keys).to eq([:rspec, :spinach, :release]) expect(root.jobs_value[:rspec]).to eq( { name: :rspec, script: %w[rspec ls], before_script: %w(ls pwd), image: { name: 'ruby:2.7' }, services: [{ name: 'postgres:9.1' }, { name: 'mysql:5.5' }], stage: 'test', cache: { key: 'k', untracked: true, paths: ['public/'], policy: 'pull-push', when: 'on_success' }, variables: { 'VAR' => 'root' }, ignore: false, after_script: ['make clean'], only: { refs: %w[branches tags] }, scheduling_type: :stage } ) expect(root.jobs_value[:spinach]).to eq( { name: :spinach, before_script: [], script: %w[spinach], image: { name: 'ruby:2.7' }, services: [{ name: 'postgres:9.1' }, { name: 'mysql:5.5' }], stage: 'test', cache: { key: 'k', untracked: true, paths: ['public/'], policy: 'pull-push', when: 'on_success' }, variables: { 'VAR' => 'root' }, ignore: false, after_script: ['make clean'], only: { refs: %w[branches tags] }, scheduling_type: :stage } ) expect(root.jobs_value[:release]).to eq( { name: :release, stage: 'release', before_script: [], script: ["make changelog | tee release_changelog.txt"], release: { name: "Release $CI_TAG_NAME", tag_name: 'v0.06', description: "./release_changelog.txt" }, image: { name: "ruby:2.7" }, services: [{ name: "postgres:9.1" }, { name: "mysql:5.5" }], cache: { key: "k", untracked: true, paths: ["public/"], policy: "pull-push", when: 'on_success' }, only: { refs: %w(branches tags) }, variables: { 'VAR' => 'job' }, after_script: [], ignore: false, scheduling_type: :stage } ) end end end end context 'when a mix of top-level and default entries is used' do let(:hash) do { before_script: %w(ls pwd), after_script: ['make clean'], default: { image: 'ruby:2.7', services: ['postgres:9.1', 'mysql:5.5'] }, variables: { VAR: 'root' }, stages: %w(build pages), cache: { key: 'k', untracked: true, paths: ['public/'] }, rspec: { script: %w[rspec ls] }, spinach: { before_script: [], variables: { VAR: 'job' }, script: 'spinach' } } end context 'when composed' do before do root.compose! end describe '#errors' do it 'has no errors' do expect(root.errors).to be_empty end end describe '#jobs_value' do it 'returns jobs configuration' do expect(root.jobs_value).to eq( rspec: { name: :rspec, script: %w[rspec ls], before_script: %w(ls pwd), image: { name: 'ruby:2.7' }, services: [{ name: 'postgres:9.1' }, { name: 'mysql:5.5' }], stage: 'test', cache: { key: 'k', untracked: true, paths: ['public/'], policy: 'pull-push', when: 'on_success' }, variables: { 'VAR' => 'root' }, ignore: false, after_script: ['make clean'], only: { refs: %w[branches tags] }, scheduling_type: :stage }, spinach: { name: :spinach, before_script: [], script: %w[spinach], image: { name: 'ruby:2.7' }, services: [{ name: 'postgres:9.1' }, { name: 'mysql:5.5' }], stage: 'test', cache: { key: 'k', untracked: true, paths: ['public/'], policy: 'pull-push', when: 'on_success' }, variables: { 'VAR' => 'job' }, ignore: false, after_script: ['make clean'], only: { refs: %w[branches tags] }, scheduling_type: :stage } ) end end end end context 'when most of entires not defined' do before do root.compose! end let(:hash) do { cache: { key: 'a' }, rspec: { script: %w[ls] } } end describe '#nodes' do it 'instantizes all nodes' do expect(root.descendants.count).to eq 11 end it 'contains unspecified nodes' do expect(root.descendants.first) .not_to be_specified end end describe '#variables_value' do it 'returns root value for variables' do expect(root.variables_value).to eq({}) end end describe '#stages_value' do it 'returns an array of root stages' do expect(root.stages_value).to eq %w[.pre build test deploy .post] end end describe '#cache_value' do it 'returns correct cache definition' do expect(root.cache_value).to eq(key: 'a', policy: 'pull-push', when: 'on_success') end end end context 'when variables resembles script-type job' do before do root.compose! end let(:hash) do { variables: { script: "ENV_VALUE" }, rspec: { script: "echo Hello World" } } end describe '#variables_value' do it 'returns root value for variables' do expect(root.variables_value).to eq("script" => "ENV_VALUE") end end describe '#jobs_value' do it 'returns one job' do expect(root.jobs_value.keys).to contain_exactly(:rspec) end end end ## # When nodes are specified but not defined, we assume that # configuration is valid, and we assume that entry is simply undefined, # despite the fact, that key is present. See issue #18775 for more # details. # context 'when entries are specified but not defined' do before do root.compose! end let(:hash) do { variables: nil, rspec: { script: 'rspec' } } end describe '#variables_value' do it 'undefined entry returns a root value' do expect(root.variables_value).to eq({}) end end end end context 'when configuration is not valid' do before do root.compose! end context 'when before script is not an array' do let(:hash) do { before_script: 'ls' } end describe '#valid?' do it 'is not valid' do expect(root).not_to be_valid end end describe '#errors' do it 'reports errors from child nodes' do expect(root.errors) .to include 'before_script config should be an array containing strings and arrays of strings' end end end context 'when job does not have commands' do let(:hash) do { before_script: ['echo 123'], rspec: { stage: 'test' } } end describe '#errors' do it 'reports errors about missing script or trigger' do expect(root.errors) .to include 'jobs rspec config should implement a script: or a trigger: keyword' end end end end context 'when value is not a hash' do let(:hash) { [] } describe '#valid?' do it 'is not valid' do expect(root).not_to be_valid end end describe '#errors' do it 'returns error about invalid type' do expect(root.errors.first).to match /should be a hash/ end end end describe '#specified?' do it 'is concrete entry that is defined' do expect(root.specified?).to be true end end describe '#[]' do before do root.compose! end let(:hash) do { cache: { key: 'a' }, rspec: { script: 'ls' } } end context 'when entry exists' do it 'returns correct entry' do expect(root[:cache]) .to be_an_instance_of Gitlab::Ci::Config::Entry::Cache expect(root[:jobs][:rspec][:script].value).to eq ['ls'] end end context 'when entry does not exist' do it 'always return unspecified node' do expect(root[:some][:unknown][:node]) .not_to be_specified end end end end
31.778607
126
0.501996
91f0a9217b6a8972b7ea7ef81a418b10e19c0d70
294
name 'cdo-users' maintainer 'Code.org' maintainer_email 'will@code.org' license 'All rights reserved' description 'Creates users for the accounts defined in Chef' long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) version '0.1.18'
36.75
72
0.673469
9102ab91def3c4e721716a537227639aecb4cc05
2,179
cask "cocktail" do if MacOS.version <= :yosemite version "8.9.2" sha256 "acc7d191313fa0eb4109ae56f62f73e7ed6685f7d7d438d5138b85d68e40edd8" url "https://www.maintain.se/downloads/sparkle/yosemite/Cocktail_#{version}.zip" appcast "https://www.maintain.se/downloads/sparkle/yosemite/yosemite.xml" elsif MacOS.version <= :el_capitan version "9.7" sha256 "ca6b4a264ca60a08ff45761f82b0b6161cbe3412bd6cbeedd5dbecebc8d26712" url "https://www.maintain.se/downloads/sparkle/elcapitan/Cocktail_#{version}.zip" appcast "https://www.maintain.se/downloads/sparkle/elcapitan/elcapitan.xml" elsif MacOS.version <= :sierra version "10.9.1" sha256 "c41bdcff4e0a1bdf3b0b1dfa11e12de71acf64010c7dccfd337ec2f42ca7bd4f" url "https://www.maintain.se/downloads/sparkle/sierra/Cocktail_#{version}.zip" appcast "https://www.maintain.se/downloads/sparkle/sierra/sierra.xml" elsif MacOS.version <= :high_sierra version "11.7" sha256 "e1d8b4529963e94b8a5d710ee3dd75f15423701aead815da271d624b2c653278" url "https://www.maintain.se/downloads/sparkle/highsierra/Cocktail_#{version}.zip" appcast "https://www.maintain.se/downloads/sparkle/highsierra/highsierra.xml" elsif MacOS.version <= :mojave version "12.5" sha256 "bdbda2d7c86e598dd9504ba3158dcab71d0b9e2b935b2917c45bb1696fc105cd" url "https://www.maintain.se/downloads/sparkle/mojave/Cocktail_#{version}.zip" appcast "https://www.maintain.se/downloads/sparkle/mojave/mojave.xml" elsif MacOS.version <= :catalina version "13.2.6" sha256 "9b59655ef2511218e16736679b0eadde43f9b1a90e7162ffef2e284ca71d149b" url "https://www.maintain.se/downloads/sparkle/catalina/Cocktail_#{version}.zip" appcast "https://www.maintain.se/downloads/sparkle/catalina/catalina.xml" else version "14.2.3" sha256 "adba54cc975eca846453f5f6a0a8e64bedda177041bfd7e140dda4276fb78fb6" url "https://www.maintain.se/downloads/Cocktail#{version.major}BSE.dmg" appcast "https://www.maintain.se/cocktail/" end name "Cocktail" desc "Cleans, repairs and optimizes computer systems" homepage "https://www.maintain.se/cocktail/" app "Cocktail.app" end
41.903846
86
0.765489
39b286c320762d8812380db373ae1c925697a7d3
783
module Api class RequestParser def self.parse_user(data) user_name = Hash(data).fetch_path("requester", "user_name") return if user_name.blank? user = User.lookup_by_identity(user_name) raise BadRequestError, "Unknown requester user_name #{user_name} specified" unless user user end def self.parse_options(data) raise BadRequestError, "Request is missing options" if data["options"].blank? data["options"].deep_symbolize_keys end def self.parse_auto_approve(data) case data["auto_approve"] when TrueClass, "true" then true when FalseClass, "false", nil then false else raise BadRequestError, "Invalid requester auto_approve value #{data["auto_approve"]} specified" end end end end
31.32
106
0.698595
7a82ddd091754714e83c51de7468162ba9e4310d
510
# frozen_string_literal: true module InternshipOfferInfos class WeeklyFramed < InternshipOfferInfo validates :weeks, presence: true has_many :internship_offer_info_weeks, dependent: :destroy, foreign_key: :internship_offer_info_id, inverse_of: :internship_offer_info has_many :weeks, through: :internship_offer_info_weeks def weekly? true end def free_date? false end end end
24.285714
82
0.62549
18b314c642d34183b8ce731d19e47c7d94aa225d
3,024
# $Id: udp.rb 14 2008-03-02 05:42:30Z warchild $ # # Copyright (c) 2008, Jon Hart # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # * Neither the name of the <organization> nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY Jon Hart ``AS IS'' AND ANY # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL Jon Hart BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # User Datagram Protocol: UDP # # RFC768 (http://www.faqs.org/rfcs/rfc768.html) module Racket class UDP < RacketPart # Source Port unsigned :src_port, 16 # Destination Port unsigned :dst_port, 16 # Datagram Length unsigned :len, 16 # Checksum unsigned :csum, 16 # Payload rest :payload # Check the checksum for this UDP datagram def checksum?(src_ip, dst_ip) self.csum == 0 || (self.csum == compute_checksum(src_ip, dst_ip)) end # Compute and set the checksum for this UDP datagram def checksum!(src_ip, dst_ip) # set the checksum to 0 for usage in the pseudo header... self.csum = 0 self.csum = compute_checksum(src_ip, dst_ip) end # Fix this packet up for proper sending. Sets the length # and checksum properly. def fix!(src_ip, dst_ip) self.len = self.class.bit_length/8 + self.payload.length self.checksum!(src_ip, dst_ip) end def initialize(*args) super @autofix = false end private # Compute the checksum for this UDP datagram def compute_checksum(src_ip, dst_ip) # pseudo header used for checksum calculation as per RFC 768 pseudo = [L3::Misc.ipv42long(src_ip), L3::Misc.ipv42long(dst_ip), 17, self.payload.length + self.class.bit_length/8 ] header = [self.src_port, self.dst_port, self.payload.length + self.class.bit_length/8, 0, self.payload] L3::Misc.checksum((pseudo << header).flatten.pack("NNnnnnnna*")) end end end # vim: set ts=2 et sw=2:
37.8
121
0.728836
e2177c63da18d8f1e4f298870ae808f85a54baaf
2,112
module Poniard # Mixing this module into a Rails controller provides the poniard DSL to that # controller. To enable poniard on all controllers, mix this in to # `ApplicationController`. module Controller # @private def self.included(klass) klass.extend(ClassMethods) end # Call the given method via the poniard injector. A `ControllerSource` is # provided as default, along with any sources passed to `provided_by`. def inject(method) injector = Injector.new [ ControllerSource.new(self) ] + self.class.sources.map(&:new) injector.eager_dispatch self.class.provided_by.new.method(method) end # Class methods that are automatically added when `Controller` is included. module ClassMethods # For every non-inherited public instance method on the given class, # generates a method of the same name that calls it via the injector. # # If a `layout` method is present on the class, it is given special # treatment and set up so that it will be called using the Rails `layout` # DSL method. def provided_by(klass = nil, opts = {}) if klass methods = klass.public_instance_methods(false) layout_method = methods.delete(:layout) methods.each do |m| class_eval <<-RUBY def #{m} inject :#{m} end RUBY end if layout_method layout :layout_for_controller class_eval <<-RUBY def layout_for_controller inject :layout end RUBY end @provided_by = klass @sources = opts.fetch(:sources, []).reverse else @provided_by end end # An array of sources to be used for all injected methods on the host # class. This is typically specified using the `sources` option to # `provided_by`, however you can override it for more complicated dynamic # behaviour. def sources @sources end end end end
30.608696
79
0.615057
4a5a769a42e4b29ce7ebff1cda797c01f6d329d1
945
module CurrencyRate class ExmoAdapter < Adapter # No need to use it for fetching, just additional information about supported currencies SUPPORTED_CURRENCIES = %w( ADA BCH BTC BTCZ BTG DASH DOGE DXT EOS ETC ETH EUR GAS GNT GUSD HB HBZ INK KICK LSK LTC MNX NEO OMG PLN QTUM RUB SMART STQ TRX TRY UAH USD USDT WAVES XEM XLM XMR XRP ZEC ZRX ) ANCHOR_CURRENCY = "BTC" FETCH_URL = "https://api.exmo.com/v1/ticker/" def normalize(data) return nil unless super data.reduce({ "anchor" => ANCHOR_CURRENCY }) do |result, (key, value)| if key.split("_")[0] == ANCHOR_CURRENCY result[key.sub("#{self.class::ANCHOR_CURRENCY}_", "")] = BigDecimal.new(value["avg"].to_s) elsif key.split("_")[1] == ANCHOR_CURRENCY result[key.sub("_#{self.class::ANCHOR_CURRENCY}", "")] = 1 / BigDecimal.new(value["avg"].to_s) end result end end end end
33.75
104
0.639153